Completed
Push — master ( b123fa...21b1ea )
by Angus
02:44
created

Tracker_Admin_Model   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 268
Duplicated Lines 5.97 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 2.03%

Importance

Changes 0
Metric Value
dl 16
loc 268
ccs 3
cts 148
cp 0.0203
rs 8.8
c 0
b 0
f 0
wmc 36
lcom 1
cbo 5

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B updateLatestChapters() 0 83 6
D updateCustom() 11 46 10
B refollowCustom() 0 33 5
C updateTitles() 5 51 8
B getNextUpdateTime() 0 33 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php declare(strict_types=1); defined('BASEPATH') OR exit('No direct script access allowed');
2
3
class Tracker_Admin_Model extends Tracker_Base_Model {
4 119
	public function __construct() {
5 119
		parent::__construct();
6 119
	}
7
8
	/**
9
	 * Checks for any series that haven't updated in 16 hours and updates them.
10
	 * This is ran every 4 hours via a cron job.
11
	 */
12
	public function updateLatestChapters() {
13
		// @formatter:off
14
		$query = $this->db
15
			->select('
16
				tracker_titles.id as title_id,
17
				tracker_titles.title,
18
				tracker_titles.title_url,
19
				tracker_titles.status,
20
				tracker_sites.site,
21
				tracker_sites.site_class,
22
				tracker_sites.status,
23
				tracker_titles.latest_chapter,
24
				tracker_titles.last_updated,
25
				from_unixtime(MAX(auth_users.last_login)) AS timestamp
26
			')
27
			->from('tracker_titles')
28
			->join('tracker_sites', 'tracker_sites.id = tracker_titles.site_id', 'left')
29
			->join('tracker_chapters', 'tracker_titles.id = tracker_chapters.title_id', 'left')
30
			->join('auth_users', 'tracker_chapters.user_id = auth_users.id', 'left')
31
			->where('tracker_sites.status', 'enabled')
32
			->group_start()
33
				//Check if title is marked as on-going...
34
				->where('tracker_titles.status', 0)
35
				//AND matches one of where queries below
36
				->group_start()
37
					//Then check if it's NULL (only occurs for new series)
38
					->where('latest_chapter', NULL)
39
					//OR if it hasn't updated within the past 12 hours AND isn't a custom update site
40
					->or_group_start()
41
						->where('tracker_sites.use_custom', 'N')
42
						->where('last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)')
43
					->group_end()
44
					//OR it is a custom update site and hasn't updated within the past 72 hours (3 days)
45
					->or_where('last_checked < DATE_SUB(NOW(), INTERVAL 72 HOUR)')
46
				->group_end()
47
			->group_end()
48
			->or_group_start()
49
				//Check if title is marked as complete...
50
				->where('tracker_titles.status', 1)
51
				//Then check if it hasn't updated within the past week
52
				->where('last_checked < DATE_SUB(NOW(), INTERVAL 1 WEEK)')
53
			->group_end()
54
			//Status 2 (One-shot) & 255 (Ignore) are both not updated intentionally.
55
			->group_by('tracker_titles.id, tracker_chapters.active')
56
			//Check if the series is actually being tracked by someone
57
			->having('timestamp IS NOT NULL')
58
			//AND if it's currently marked as active by the user
59
			->having('tracker_chapters.active', 'Y')
60
			//AND if they have been active in the last 120 hours (5 days)
61
			->having('timestamp > DATE_SUB(NOW(), INTERVAL 120 HOUR)')
62
			->order_by('tracker_titles.title', 'ASC')
63
			->get();
64
		// @formatter:on
65
66
		if($query->num_rows() > 0) {
67
			foreach ($query->result() as $row) {
68
				print "> {$row->title} <{$row->site_class}> | <{$row->title_id}>"; //Print this prior to doing anything so we can more easily find out if something went wrong
69
				$titleData = $this->sites->{$row->site_class}->getTitleData($row->title_url);
70
				if(is_array($titleData) && !is_null($titleData['latest_chapter'])) {
71
					//FIXME: "At the moment" we don't seem to be doing anything with TitleData['last_updated'].
72
					//       Should we even use this? Y/N
73
					if($this->Tracker->title->updateByID((int) $row->title_id, $titleData['latest_chapter'])) {
74
						//Make sure last_checked is always updated on successful run.
75
						//CHECK: Is there a reason we aren't just doing this in updateByID?
76
						$this->db->set('last_checked', 'CURRENT_TIMESTAMP', FALSE)
77
						         ->where('id', $row->title_id)
78
						         ->update('tracker_titles');
79
80
						print " - ({$titleData['latest_chapter']})\n";
81
					} else {
82
						log_message('error', "{$row->title} failed to update successfully");
83
84
						print " - Something went wrong?\n";
85
					}
86
				} else {
87
					log_message('error', "{$row->title} failed to update successfully");
88
					$this->Tracker->title->updateFailedChecksByID((int) $row->title_id);
89
90
					print " - FAILED TO PARSE\n";
91
				}
92
			}
93
		}
94
	}
95
96
	/**
97
	 * Checks for any sites which support custom updating (usually via following lists) and updates them.
98
	 * This is run hourly.
99
	 */
100
	public function updateCustom() {
101
		$query = $this->db->select('*')
102
		                  ->from('tracker_sites')
103
		                  ->where('status', 'enabled')
104
		                  ->where('tracker_sites.use_custom', 'Y')
105
		                  ->get();
106
107
		$sites = $query->result_array();
108
		foreach ($sites as $site) {
109
			$siteClass = $this->sites->{$site['site_class']};
110
			if($titleDataList = $siteClass->doCustomUpdate()) {
111
				foreach ($titleDataList as $titleURL => $titleData) {
112
					print "> {$titleData['title']} <{$site['site_class']}>"; //Print this prior to doing anything so we can more easily find out if something went wrong
113
					if(is_array($titleData) && !is_null($titleData['latest_chapter'])) {
114
						if($dbTitleData = $this->Tracker->title->getID($titleURL, (int) $site['id'], FALSE, TRUE)) {
115
							if($this->sites->{$site['site_class']}->doCustomCheck($dbTitleData['latest_chapter'], $titleData['latest_chapter'])) {
116
								$titleID = $dbTitleData['id'];
117 View Code Duplication
								if($this->Tracker->title->updateByID((int) $titleID, $titleData['latest_chapter'])) {
118
									//Make sure last_checked is always updated on successful run.
119
									//CHECK: Is there a reason we aren't just doing this in updateByID?
120
									$this->db->set('last_checked', 'CURRENT_TIMESTAMP', FALSE)
121
									         ->where('id', $titleID)
122
									         ->update('tracker_titles');
123
124
									print " - ({$titleData['latest_chapter']})\n";
125
								} else {
126
									print " - Title doesn't exist? ($titleID)\n";
127
								}
128
							} else {
129
								print " - Failed Check (DB: '{$dbTitleData['latest_chapter']}' || UPDATE: '{$titleData['latest_chapter']}')\n";
130
							}
131
						} else {
132
							//We only need to log if following page is missing title, not latest releases
133
							if($siteClass->customType === 1) {
134
								log_message('error', "CUSTOM: {$titleData['title']} - {$site['site_class']} || Title does not exist in DB??");
135
								print " - Title doesn't currently exist in DB? Maybe different language or title stub change? ($titleURL)\n";
136
							}
137
						}
138
					} else {
139
						log_message('error', "CUSTOM: {$titleData['title']} - {$site['site_class']} failed to custom update successfully");
140
						print " - FAILED TO PARSE\n";
141
					}
142
				}
143
			}
144
		}
145
	}
146
147
	public function refollowCustom() {
148
		$query = $this->db->select('tracker_titles.id, tracker_titles.title_url, tracker_sites.site_class')
149
		                  ->from('tracker_titles')
150
		                  ->join('tracker_sites', 'tracker_sites.id = tracker_titles.site_id', 'left')
151
		                  ->where('tracker_titles.followed','N')
152
		                  ->where('tracker_titles !=', '255')
153
		                  ->where('tracker_sites.status', 'enabled')
154
		                  ->where('tracker_sites.use_custom', 'Y')
155
		                  ->get();
156
157
		if($query->num_rows() > 0) {
158
			foreach($query->result() as $row) {
159
				$titleData = $this->Tracker->sites->{$row->site_class}->getTitleData($row->title_url, TRUE);
160
161
				if($titleData) {
162
					$titleData = array_intersect_key($titleData, array_flip(['followed']));
163
164
					if(!empty($titleData)) {
165
						$this->db->set($titleData)
166
						         ->where('id', $row->id)
167
						         ->update('tracker_titles');
168
169
						print "> {$row->site_class}:{$row->id}:{$row->title_url} FOLLOWED\n";
170
					} else {
171
						print "> {$row->site_class}:{$row->id}:{$row->title_url} FAILED (NO FOLLOWED)\n";
172
					}
173
				} else {
174
					log_message('error', "getTitleData failed for: {$row->site_class} | {$row->title_url}");
175
					print "> {$row->site_class}:{$row->id}:{$row->title_url} FAILED (NO TITLEDATA)\n";
176
				}
177
			}
178
		}
179
	}
180
181
	/**
182
	 * Checks every series to see if title has changed, and update if so.
183
	 * This is ran once a month via a cron job
184
	 */
185
	public function updateTitles() {
186
		// @formatter:off
187
		$query = $this->db
188
			->select('
189
				tracker_titles.id,
190
				tracker_titles.title,
191
				tracker_titles.title_url,
192
				tracker_titles.status,
193
				tracker_sites.site,
194
				tracker_sites.site_class,
195
				tracker_sites.status,
196
				tracker_titles.latest_chapter,
197
				tracker_titles.last_updated
198
			')
199
			->from('tracker_titles')
200
			->join('tracker_sites', 'tracker_sites.id = tracker_titles.site_id', 'left')
201
			->where('tracker_sites.status', 'enabled')
202
203
			->group_by('tracker_titles.id')
204
			->order_by('tracker_titles.title', 'ASC')
205
			->get();
206
		// @formatter:on
207
208
		if($query->num_rows() > 0) {
209
			foreach ($query->result() as $row) {
210
				print "> {$row->title} <{$row->site_class}>"; //Print this prior to doing anything so we can more easily find out if something went wrong
211
				$titleData = $this->sites->{$row->site_class}->getTitleData($row->title_url);
212
				if($titleData['title'] && is_array($titleData) && !is_null($titleData['latest_chapter'])) {
213
					if($titleData['title'] !== $row->title) {
214
						$this->db->set('title', $titleData['title'])
215
						         ->where('id', $row->id)
216
						         ->update('tracker_titles');
217
						//TODO: Add to history somehow?
218
						print " - NEW TITLE ({$titleData['title']})\n";
219
					} else {
220
						print " - TITLE NOT CHANGED\n";
221
					}
222
223
					//We might as well try to update as well.
224 View Code Duplication
					if($this->Tracker->title->updateByID((int) $row->id, $titleData['latest_chapter'])) {
225
						$this->db->set('last_checked', 'CURRENT_TIMESTAMP', FALSE)
226
						         ->where('id', $row->id)
227
						         ->update('tracker_titles');
228
					}
229
				} else {
230
					log_message('error', "{$row->title} failed to update title successfully");
231
					print " - FAILED TO PARSE\n";
232
				}
233
			}
234
		}
235
	}
236
237
	public function getNextUpdateTime(string $format = "%H:%I:%S") : string {
238
		$temp_now = new DateTime();
239
		$temp_now->setTimezone(new DateTimeZone('America/New_York'));
240
		$temp_now_formatted = $temp_now->format('Y-m-d H:i:s');
241
242
		//NOTE: PHP Bug: DateTime:diff doesn't play nice with setTimezone, so we need to create another DT object
243
		$now         = new DateTime($temp_now_formatted);
244
		$future_date = new DateTime($temp_now_formatted);
245
		$now_hour    = (int) $now->format('H');
246
		if($now_hour < 4) {
247
			//Time until 4am
248
			$future_date->setTime(4, 00);
249
		} elseif($now_hour < 8) {
250
			//Time until 8am
251
			$future_date->setTime(8, 00);
252
		} elseif($now_hour < 12) {
253
			//Time until 12pm
254
			$future_date->setTime(12, 00);
255
		} elseif($now_hour < 16) {
256
			//Time until 4pm
257
			$future_date->setTime(16, 00);
258
		} elseif($now_hour < 20) {
259
			//Time until 8pm
260
			$future_date->setTime(20, 00);
261
		} else {
262
			//Time until 12am
263
			$future_date->setTime(00, 00);
264
			$future_date->add(new DateInterval('P1D'));
265
		}
266
267
		$interval = $future_date->diff($now);
268
		return $interval->format($format);
269
	}
270
}
271