Completed
Push — master ( 40cff3...c302c1 )
by Angus
02:30
created

Tracker_Admin_Model   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 264
Duplicated Lines 6.06 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 2.05%

Importance

Changes 0
Metric Value
dl 16
loc 264
ccs 3
cts 146
cp 0.0205
rs 9
c 0
b 0
f 0
wmc 35
lcom 1
cbo 5

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B updateLatestChapters() 0 83 6
D updateCustom() 11 42 9
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
			if($titleDataList = $this->sites->{$site['site_class']}->doCustomUpdate()) {
110
				foreach ($titleDataList as $titleURL => $titleData) {
111
					print "> {$titleData['title']} <{$site['site_class']}>"; //Print this prior to doing anything so we can more easily find out if something went wrong
112
					if(is_array($titleData) && !is_null($titleData['latest_chapter'])) {
113
						if($dbTitleData = $this->Tracker->title->getID($titleURL, (int) $site['id'], FALSE, TRUE)) {
114
							if($this->sites->{$site['site_class']}->doCustomCheck($dbTitleData['latest_chapter'], $titleData['latest_chapter'])) {
115
								$titleID = $dbTitleData['id'];
116 View Code Duplication
								if($this->Tracker->title->updateByID((int) $titleID, $titleData['latest_chapter'])) {
117
									//Make sure last_checked is always updated on successful run.
118
									//CHECK: Is there a reason we aren't just doing this in updateByID?
119
									$this->db->set('last_checked', 'CURRENT_TIMESTAMP', FALSE)
120
									         ->where('id', $titleID)
121
									         ->update('tracker_titles');
122
123
									print " - ({$titleData['latest_chapter']})\n";
124
								} else {
125
									print " - Title doesn't exist? ($titleID)\n";
126
								}
127
							} else {
128
								print " - Failed Check (DB: '{$dbTitleData['latest_chapter']}' || UPDATE: '{$titleData['latest_chapter']}')\n";
129
							}
130
						} else {
131
							log_message('error', "CUSTOM: {$titleData['title']} - {$site['site_class']} || Title does not exist in DB??");
132
							print " - Title doesn't currently exist in DB? Maybe different language or title stub change? ($titleURL)\n";
133
						}
134
					} else {
135
						log_message('error', "CUSTOM: {$titleData['title']} - {$site['site_class']} failed to custom update successfully");
136
						print " - FAILED TO PARSE\n";
137
					}
138
				}
139
			}
140
		}
141
	}
142
143
	public function refollowCustom() {
144
		$query = $this->db->select('tracker_titles.id, tracker_titles.title_url, tracker_sites.site_class')
145
		                  ->from('tracker_titles')
146
		                  ->join('tracker_sites', 'tracker_sites.id = tracker_titles.site_id', 'left')
147
		                  ->where('tracker_titles.followed','N')
148
		                  ->where('tracker_titles !=', '255')
149
		                  ->where('tracker_sites.status', 'enabled')
150
		                  ->where('tracker_sites.use_custom', 'Y')
151
		                  ->get();
152
153
		if($query->num_rows() > 0) {
154
			foreach($query->result() as $row) {
155
				$titleData = $this->Tracker->sites->{$row->site_class}->getTitleData($row->title_url, TRUE);
156
157
				if($titleData) {
158
					$titleData = array_intersect_key($titleData, array_flip(['followed']));
159
160
					if(!empty($titleData)) {
161
						$this->db->set($titleData)
162
						         ->where('id', $row->id)
163
						         ->update('tracker_titles');
164
165
						print "> {$row->site_class}:{$row->id}:{$row->title_url} FOLLOWED\n";
166
					} else {
167
						print "> {$row->site_class}:{$row->id}:{$row->title_url} FAILED (NO FOLLOWED)\n";
168
					}
169
				} else {
170
					log_message('error', "getTitleData failed for: {$row->site_class} | {$row->title_url}");
171
					print "> {$row->site_class}:{$row->id}:{$row->title_url} FAILED (NO TITLEDATA)\n";
172
				}
173
			}
174
		}
175
	}
176
177
	/**
178
	 * Checks every series to see if title has changed, and update if so.
179
	 * This is ran once a month via a cron job
180
	 */
181
	public function updateTitles() {
182
		// @formatter:off
183
		$query = $this->db
184
			->select('
185
				tracker_titles.id,
186
				tracker_titles.title,
187
				tracker_titles.title_url,
188
				tracker_titles.status,
189
				tracker_sites.site,
190
				tracker_sites.site_class,
191
				tracker_sites.status,
192
				tracker_titles.latest_chapter,
193
				tracker_titles.last_updated
194
			')
195
			->from('tracker_titles')
196
			->join('tracker_sites', 'tracker_sites.id = tracker_titles.site_id', 'left')
197
			->where('tracker_sites.status', 'enabled')
198
199
			->group_by('tracker_titles.id')
200
			->order_by('tracker_titles.title', 'ASC')
201
			->get();
202
		// @formatter:on
203
204
		if($query->num_rows() > 0) {
205
			foreach ($query->result() as $row) {
206
				print "> {$row->title} <{$row->site_class}>"; //Print this prior to doing anything so we can more easily find out if something went wrong
207
				$titleData = $this->sites->{$row->site_class}->getTitleData($row->title_url);
208
				if($titleData['title'] && is_array($titleData) && !is_null($titleData['latest_chapter'])) {
209
					if($titleData['title'] !== $row->title) {
210
						$this->db->set('title', $titleData['title'])
211
						         ->where('id', $row->id)
212
						         ->update('tracker_titles');
213
						//TODO: Add to history somehow?
214
						print " - NEW TITLE ({$titleData['title']})\n";
215
					} else {
216
						print " - TITLE NOT CHANGED\n";
217
					}
218
219
					//We might as well try to update as well.
220 View Code Duplication
					if($this->Tracker->title->updateByID((int) $row->id, $titleData['latest_chapter'])) {
221
						$this->db->set('last_checked', 'CURRENT_TIMESTAMP', FALSE)
222
						         ->where('id', $row->id)
223
						         ->update('tracker_titles');
224
					}
225
				} else {
226
					log_message('error', "{$row->title} failed to update title successfully");
227
					print " - FAILED TO PARSE\n";
228
				}
229
			}
230
		}
231
	}
232
233
	public function getNextUpdateTime(string $format = "%H:%I:%S") : string {
234
		$temp_now = new DateTime();
235
		$temp_now->setTimezone(new DateTimeZone('America/New_York'));
236
		$temp_now_formatted = $temp_now->format('Y-m-d H:i:s');
237
238
		//NOTE: PHP Bug: DateTime:diff doesn't play nice with setTimezone, so we need to create another DT object
239
		$now         = new DateTime($temp_now_formatted);
240
		$future_date = new DateTime($temp_now_formatted);
241
		$now_hour    = (int) $now->format('H');
242
		if($now_hour < 4) {
243
			//Time until 4am
244
			$future_date->setTime(4, 00);
245
		} elseif($now_hour < 8) {
246
			//Time until 8am
247
			$future_date->setTime(8, 00);
248
		} elseif($now_hour < 12) {
249
			//Time until 12pm
250
			$future_date->setTime(12, 00);
251
		} elseif($now_hour < 16) {
252
			//Time until 4pm
253
			$future_date->setTime(16, 00);
254
		} elseif($now_hour < 20) {
255
			//Time until 8pm
256
			$future_date->setTime(20, 00);
257
		} else {
258
			//Time until 12am
259
			$future_date->setTime(00, 00);
260
			$future_date->add(new DateInterval('P1D'));
261
		}
262
263
		$interval = $future_date->diff($now);
264
		return $interval->format($format);
265
	}
266
}
267