Completed
Push — master ( f17fab...21371d )
by Angus
06:56
created

Tracker_Admin_Model   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 356
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 1.55%

Importance

Changes 0
Metric Value
dl 0
loc 356
ccs 3
cts 194
cp 0.0155
rs 8.96
c 0
b 0
f 0
wmc 43
lcom 1
cbo 6

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B updateLatestChapters() 0 85 6
A updateAllTitlesBySite() 0 50 4
B handleUpdate() 0 59 9
B updateCustom() 0 49 10
A refollowCustom() 0 33 5
A incrementRequests() 0 21 2
B getNextUpdateTime() 0 33 6

How to fix   Complexity   

Complex Class

Complex classes like Tracker_Admin_Model often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Tracker_Admin_Model, and based on these observations, apply Extract Interface, too.

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 96
	public function __construct() {
5 96
		parent::__construct();
6 96
	}
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
		// region $query = Get all titles ready to update;
14
		// @formatter:off
15
		$query = $this->db
16
			->select('
17
				tracker_titles.id as title_id,
18
				tracker_titles.title,
19
				tracker_titles.title_url,
20
				tracker_titles.status,
21
				tracker_sites.site,
22
				tracker_sites.site_class,
23
				tracker_sites.status,
24
				tracker_titles.latest_chapter,
25
				tracker_titles.last_updated,
26
				from_unixtime(MAX(auth_users.last_login)) AS timestamp
27
			')
28
			->from('tracker_titles')
29
			->join('tracker_sites', 'tracker_sites.id = tracker_titles.site_id', 'left')
30
			->join('tracker_chapters', 'tracker_titles.id = tracker_chapters.title_id', 'left')
31
			->join('auth_users', 'tracker_chapters.user_id = auth_users.id', 'left')
32
			->where('tracker_sites.status', 'enabled')
33
			->group_start()
34
				->group_start()
35
					//Check if title is marked as on-going...
36
					->where('tracker_titles.status', 0)
37
					//AND matches one of where queries below
38
					->group_start()
39
						//Then check if it's NULL (only occurs for new series)
40
						//->where('latest_chapter', NULL) //NOTE: This isn't needed anymore??
41
						//OR if it hasn't updated within the past 12 hours AND isn't a custom update site
42
						->group_start()
43
							->where('tracker_sites.use_custom', 'N')
44
							->where('last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)')
45
						->group_end()
46
						//OR it is a custom update site, has more than one follower and hasn't updated within the past 72 hours.
47
						->or_group_start()
48
							->where('tracker_titles.id IN (
49
								SELECT title_id
50
								FROM tracker_chapters
51
								GROUP BY title_id
52
								HAVING COUNT(title_id) > 1
53
							)', NULL, FALSE)
54
							->where('last_checked < DATE_SUB(NOW(), INTERVAL 72 HOUR)')
55
						->group_end()
56
						//OR it is a custom update site and hasn't updated within the past 120 hours (5 days)
57
						->or_where('last_checked < DATE_SUB(NOW(), INTERVAL 120 HOUR)')
58
					->group_end()
59
				->group_end()
60
				->or_group_start()
61
					//Check if title is marked as complete...
62
					->where('tracker_titles.status', 1)
63
					//Then check if it hasn't updated within the past week
64
					->where('last_checked < DATE_SUB(NOW(), INTERVAL 1 WEEK)')
65
				->group_end()
66
			->group_end()
67
			//Status 2 (One-shot) & 255 (Ignore) are both not updated intentionally.
68
			->group_by('tracker_titles.id, tracker_chapters.active')
69
			//Check if the series is actually being tracked by someone
70
			->having('timestamp IS NOT NULL')
71
			//AND if it's currently marked as active by the user
72
			->having('tracker_chapters.active', 'Y')
73
			//AND if they have been active in the last 120 hours (5 days)
74
			->having('timestamp > DATE_SUB(NOW(), INTERVAL 120 HOUR)')
75
			->order_by('tracker_titles.title', 'ASC');
76
		// endregion
77
		$query = $query->get();
78
79
		if($query->num_rows() > 0) {
80
			$hardRateLimit  = 500; //This is to avoid any possible IP bans by cache breaking again.
81
			$siteRateLimits = [];
82
			foreach ($query->result() as $row) {
83
				if(!array_key_exists($row->site_class,$siteRateLimits)) {
84
					$siteRateLimits[$row->site_class] = 0;
85
				}
86
				if($siteRateLimits[$row->site_class] > 25) {
87
					// We're doing lots of requests to a single site, so add delays.
88
					sleep(1);
89
				}
90
				$siteRateLimits[$row->site_class]++;
91
				if($siteRateLimits[$row->site_class] > $hardRateLimit) continue;
92
93
				$this->handleUpdate($row);
94
			}
95
		}
96
	}
97
98
	/**
99
	 * Intended to be only used as a quick way to update all series on a site after a bug.
100
	 *
101
	 * @param string      $site
102
	 * @param null|string $last_checked
103
	 */
104
	public function updateAllTitlesBySite(string $site, ?string $last_checked = NULL) {
105
		// region $query = Get all titles by $site;
106
		// @formatter:off
107
		$query = $this->db
108
			->select('
109
				tracker_titles.id as title_id,
110
				tracker_titles.title,
111
				tracker_titles.title_url,
112
				tracker_titles.status,
113
				tracker_sites.site,
114
				tracker_sites.site_class,
115
				tracker_sites.status,
116
				tracker_titles.latest_chapter,
117
				tracker_titles.last_updated,
118
				from_unixtime(MAX(auth_users.last_login)) AS timestamp
119
			')
120
			->from('tracker_titles')
121
			->join('tracker_sites', 'tracker_sites.id = tracker_titles.site_id', 'left')
122
			->join('tracker_chapters', 'tracker_titles.id = tracker_chapters.title_id', 'left')
123
			->join('auth_users', 'tracker_chapters.user_id = auth_users.id', 'left')
124
			->where('tracker_sites.status', 'enabled')
125
			->where('tracker_sites.site_class', $site)
126
			->group_start()
127
				//Check if title is marked as on-going...
128
				->where('tracker_titles.status', 0)
129
				//Check if title is marked as complete...
130
				->or_where('tracker_titles.status', 1)
131
			->group_end()
132
			//Status 2 (One-shot) & 255 (Ignore) are both not updated intentionally.
133
			->group_by('tracker_titles.id, tracker_chapters.active')
134
			//Check if the series is actually being tracked by someone
135
			->having('timestamp IS NOT NULL')
136
			//AND if it's currently marked as active by the user
137
			->having('tracker_chapters.active', 'Y')
138
			//AND if they have been active in the last 120 hours (5 days)
139
			->having('timestamp > DATE_SUB(NOW(), INTERVAL 120 HOUR)')
140
			->order_by('tracker_titles.last_checked', 'ASC');
141
		// @formatter:on
142
		if(!is_null($last_checked)) {
143
			$query = $query->where('tracker_titles.last_checked >', $last_checked);
144
		}
145
		// endregion
146
		$query = $query->get();
147
148
		if($query->num_rows() > 0) {
149
			foreach ($query->result() as $row) {
150
				$this->handleUpdate($row);
151
			}
152
		}
153
	}
154
155
	protected function handleUpdate(object $row) : void {
156
		/** @var Base_Site_Model $site */
157
		$site = $this->sites->{$row->site_class};
158
159
		print "> {$row->title} <{$row->site_class} - {$row->title_url}> | <{$row->title_id}>"; //Print this prior to doing anything so we can more easily find out if something went wrong
160
161
		$updateData = $site->handleBatchUpdate($row->title_url);
162
		if(!$updateData['limited']) {
163
			$titleData = $updateData['titleData'];
164
			if(is_array($titleData) && (!is_null($titleData['latest_chapter']) || $site->canHaveNoChapters)) {
165
				if(count($titleData) >= 3) {
166
					// Normal update.
167
168
					//FIXME: "At the moment" we don't seem to be doing anything with TitleData['last_updated'].
169
					//       Should we even use this? Y/N
170
					if($this->Tracker->title->updateByID((int) $row->title_id, $titleData['latest_chapter'])) {
171
						//Make sure last_checked is always updated on successful run.
172
						//CHECK: Is there a reason we aren't just doing this in updateByID?
173
						$this->db->set('last_checked', 'CURRENT_TIMESTAMP', FALSE)
174
						         ->where('id', $row->title_id)
175
						         ->update('tracker_titles');
176
177
						print " - ({$titleData['latest_chapter']})\n";
178
					} else {
179
						log_message('error', "{$row->site_class} | {$row->title} ({$row->title_url}) | Failed to update.");
0 ignored issues
show
Unused Code introduced by
The call to the function log_message() seems unnecessary as the function has no side-effects.
Loading history...
180
181
						print " - Something went wrong?\n";
182
					}
183
				} else {
184
					// No chapters were returned, but site allows this.
185
					if($this->Tracker->title->updateByID((int) $row->title_id, NULL)) {
186
						//Make sure last_checked is always updated on successful run.
187
						//CHECK: Is there a reason we aren't just doing this in updateByID?
188
						$this->db->set('last_checked', 'CURRENT_TIMESTAMP', FALSE)
189
						         ->where('id', $row->title_id)
190
						         ->update('tracker_titles');
191
192
						print " - (No chapters found?)\n";
193
					} else {
194
						log_message('error', "{$row->site_class} | {$row->title} ({$row->title_url}) | Failed to update.");
0 ignored issues
show
Unused Code introduced by
The call to the function log_message() seems unnecessary as the function has no side-effects.
Loading history...
195
196
						print " - Something went wrong?\n";
197
					}
198
				}
199
			}
200
			else {
201
				//TODO: We should have some way to handle this in the site models.
202
				if($row->site_class !== 'MangaKakarot') {
203
					log_message('error', "{$row->site_class} | {$row->title} ({$row->title_url}) | Failed to update.");
0 ignored issues
show
Unused Code introduced by
The call to the function log_message() seems unnecessary as the function has no side-effects.
Loading history...
204
				}
205
				$this->Tracker->title->updateFailedChecksByID((int) $row->title_id);
206
207
				print " - FAILED TO PARSE\n";
208
			}
209
		} else {
210
			// Rate limited, do nothing.
211
			print " - Rate Limited!\n";
212
		}
213
	}
214
215
	/**
216
	 * Checks for any sites which support custom updating (usually via following lists) and updates them.
217
	 * This is run hourly.
218
	 */
219
	public function updateCustom() {
220
		$query = $this->db->select('*')
221
		                  ->from('tracker_sites')
222
		                  ->where('tracker_sites.status', 'enabled')
223
		                  ->where('tracker_sites.use_custom', 'Y')
224
		                  ->get();
225
226
		$sites = $query->result_array();
227
		foreach ($sites as $site) {
228
			$siteClass = $this->sites->{$site['site_class']};
229
			if($titleDataList = $siteClass->doCustomUpdate()) {
230
				foreach ($titleDataList as $titleURL => $titleData) {
231
					$titleURL = (string) $titleURL; //Number only keys get converted to int for some reason, so we need to fix that.
232
					print "> {$titleData['title']} <{$site['site_class']}>"; //Print this prior to doing anything so we can more easily find out if something went wrong
233
					if(is_array($titleData) && !is_null($titleData['latest_chapter'])) {
234
						if($dbTitleData = $this->Tracker->title->getID($titleURL, (int) $site['id'], FALSE, TRUE)) {
235
							if($this->sites->{$site['site_class']}->doCustomCheck($dbTitleData['latest_chapter'], $titleData['latest_chapter'])) {
236
								$titleID = $dbTitleData['id'];
237
								if($this->Tracker->title->updateByID((int) $titleID, $titleData['latest_chapter'])) {
238
									//Make sure last_checked is always updated on successful run.
239
									//CHECK: Is there a reason we aren't just doing this in updateByID?
240
									$this->db->set('last_checked', 'CURRENT_TIMESTAMP', FALSE)
241
									         ->where('id', $titleID)
242
									         ->update('tracker_titles');
243
244
									print " - ({$titleData['latest_chapter']})\n";
245
								} else {
246
									print " - Title doesn't exist? ($titleID)\n";
247
								}
248
							} else {
249
								print " - Failed Check (DB: '{$dbTitleData['latest_chapter']}' || UPDATE: '{$titleData['latest_chapter']}')\n";
250
							}
251
						} else {
252
							if($siteClass->customType === 1) {
253
								//We only need to log if following page is missing title, not latest releases
254
								log_message('error', "CUSTOM: {$titleData['title']} - {$site['site_class']} || Title does not exist in DB??");
0 ignored issues
show
Unused Code introduced by
The call to the function log_message() seems unnecessary as the function has no side-effects.
Loading history...
255
								print " - Title doesn't currently exist in DB? Maybe different language or title stub change? ($titleURL)\n";
256
							} else {
257
								print " - Title isn't currently tracked.\n";
258
							}
259
						}
260
					} else {
261
						log_message('error', "CUSTOM: {$titleData['title']} - {$site['site_class']} failed to custom update successfully");
0 ignored issues
show
Unused Code introduced by
The call to the function log_message() seems unnecessary as the function has no side-effects.
Loading history...
262
						print " - FAILED TO PARSE\n";
263
					}
264
				}
265
			}
266
		}
267
	}
268
269
	public function refollowCustom() {
270
		$query = $this->db->select('tracker_titles.id, tracker_titles.title_url, tracker_sites.site_class')
271
		                  ->from('tracker_titles')
272
		                  ->join('tracker_sites', 'tracker_sites.id = tracker_titles.site_id', 'left')
273
		                  ->where('tracker_titles.followed','N')
274
		                  ->where('tracker_titles !=', '255')
275
		                  ->where('tracker_sites.status', 'enabled')
276
		                  ->where('tracker_sites.use_custom', 'Y')
277
		                  ->get();
278
279
		if($query->num_rows() > 0) {
280
			foreach($query->result() as $row) {
281
				$titleData = $this->Tracker->sites->{$row->site_class}->getTitleData($row->title_url, TRUE);
282
283
				if($titleData) {
284
					$titleData = array_intersect_key($titleData, array_flip(['followed']));
285
286
					if(!empty($titleData)) {
287
						$this->db->set($titleData)
288
						         ->where('id', $row->id)
289
						         ->update('tracker_titles');
290
291
						print "> {$row->site_class}:{$row->id}:{$row->title_url} FOLLOWED\n";
292
					} else {
293
						print "> {$row->site_class}:{$row->id}:{$row->title_url} FAILED (NO FOLLOWED)\n";
294
					}
295
				} else {
296
					log_message('error', "getTitleData failed for: {$row->site_class} | {$row->title_url}");
0 ignored issues
show
Unused Code introduced by
The call to the function log_message() seems unnecessary as the function has no side-effects.
Loading history...
297
					print "> {$row->site_class}:{$row->id}:{$row->title_url} FAILED (NO TITLEDATA)\n";
298
				}
299
			}
300
		}
301
	}
302
303
	public function incrementRequests() : void {
304
		$temp_now = new DateTime();
305
		$temp_now->setTimezone(new DateTimeZone('America/New_York'));
306
		$date = $temp_now->format('Y-m-d');
307
308
		$query = $this->db->select('1')
309
		                  ->from('site_stats')
310
		                  ->where('date', $date)
311
		                  ->get();
312
313
		if($query->num_rows() > 0) {
314
			$this->db->set('total_requests', 'total_requests+1', FALSE)
315
			         ->where('date', $date)
316
			         ->update('site_stats');
317
		} else {
318
			$this->db->insert('site_stats', [
319
				'date'           => $date,
320
				'total_requests' => 1
321
			]);
322
		}
323
	}
324
325
	public function getNextUpdateTime(string $format = "%H:%I:%S") : string {
326
		$temp_now = new DateTime();
327
		$temp_now->setTimezone(new DateTimeZone('America/New_York'));
328
		$temp_now_formatted = $temp_now->format('Y-m-d H:i:s');
329
330
		//NOTE: PHP Bug: DateTime:diff doesn't play nice with setTimezone, so we need to create another DT object
331
		$now         = new DateTime($temp_now_formatted);
332
		$future_date = new DateTime($temp_now_formatted);
333
		$now_hour    = (int) $now->format('H');
334
		if($now_hour < 4) {
335
			//Time until 4am
336
			$future_date->setTime(4, 00);
337
		} elseif($now_hour < 8) {
338
			//Time until 8am
339
			$future_date->setTime(8, 00);
340
		} elseif($now_hour < 12) {
341
			//Time until 12pm
342
			$future_date->setTime(12, 00);
343
		} elseif($now_hour < 16) {
344
			//Time until 4pm
345
			$future_date->setTime(16, 00);
346
		} elseif($now_hour < 20) {
347
			//Time until 8pm
348
			$future_date->setTime(20, 00);
349
		} else {
350
			//Time until 12am
351
			$future_date->setTime(00, 00);
352
			$future_date->add(new DateInterval('P1D'));
353
		}
354
355
		$interval = $future_date->diff($now);
356
		return $interval->format($format);
357
	}
358
}
359