Completed
Push — master ( 9bc104...8c3ec6 )
by Angus
02:49
created

Tracker_Admin_Model   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 352
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 1.56%

Importance

Changes 0
Metric Value
dl 0
loc 352
ccs 3
cts 192
cp 0.0156
rs 9.0399
c 0
b 0
f 0
wmc 42
lcom 1
cbo 6

8 Methods

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