Passed
Push — master ( b5c6ae...9e80f6 )
by Joas
15:35 queued 18s
created
apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php 1 patch
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -42,84 +42,84 @@
 block discarded – undo
42 42
  */
43 43
 class RetryJob extends Job {
44 44
 
45
-	/** @var  bool */
46
-	private $retainJob = true;
45
+    /** @var  bool */
46
+    private $retainJob = true;
47 47
 
48
-	/** @var Notifications */
49
-	private $notifications;
48
+    /** @var Notifications */
49
+    private $notifications;
50 50
 
51
-	/** @var int max number of attempts to send the request */
52
-	private $maxTry = 20;
51
+    /** @var int max number of attempts to send the request */
52
+    private $maxTry = 20;
53 53
 
54
-	/** @var int how much time should be between two tries (10 minutes) */
55
-	private $interval = 600;
54
+    /** @var int how much time should be between two tries (10 minutes) */
55
+    private $interval = 600;
56 56
 
57 57
 
58
-	public function __construct(Notifications $notifications,
59
-								ITimeFactory $time) {
60
-		parent::__construct($time);
61
-		$this->notifications = $notifications;
62
-	}
58
+    public function __construct(Notifications $notifications,
59
+                                ITimeFactory $time) {
60
+        parent::__construct($time);
61
+        $this->notifications = $notifications;
62
+    }
63 63
 
64
-	/**
65
-	 * run the job, then remove it from the jobList
66
-	 *
67
-	 * @param IJobList $jobList
68
-	 * @param ILogger|null $logger
69
-	 */
70
-	public function execute(IJobList $jobList, ILogger $logger = null) {
71
-		if ($this->shouldRun($this->argument)) {
72
-			parent::execute($jobList, $logger);
73
-			$jobList->remove($this, $this->argument);
74
-			if ($this->retainJob) {
75
-				$this->reAddJob($jobList, $this->argument);
76
-			}
77
-		}
78
-	}
64
+    /**
65
+     * run the job, then remove it from the jobList
66
+     *
67
+     * @param IJobList $jobList
68
+     * @param ILogger|null $logger
69
+     */
70
+    public function execute(IJobList $jobList, ILogger $logger = null) {
71
+        if ($this->shouldRun($this->argument)) {
72
+            parent::execute($jobList, $logger);
73
+            $jobList->remove($this, $this->argument);
74
+            if ($this->retainJob) {
75
+                $this->reAddJob($jobList, $this->argument);
76
+            }
77
+        }
78
+    }
79 79
 
80
-	protected function run($argument) {
81
-		$remote = $argument['remote'];
82
-		$remoteId = $argument['remoteId'];
83
-		$token = $argument['token'];
84
-		$action = $argument['action'];
85
-		$data = json_decode($argument['data'], true);
86
-		$try = (int)$argument['try'] + 1;
80
+    protected function run($argument) {
81
+        $remote = $argument['remote'];
82
+        $remoteId = $argument['remoteId'];
83
+        $token = $argument['token'];
84
+        $action = $argument['action'];
85
+        $data = json_decode($argument['data'], true);
86
+        $try = (int)$argument['try'] + 1;
87 87
 
88
-		$result = $this->notifications->sendUpdateToRemote($remote, $remoteId, $token, $action, $data, $try);
88
+        $result = $this->notifications->sendUpdateToRemote($remote, $remoteId, $token, $action, $data, $try);
89 89
 
90
-		if ($result === true || $try > $this->maxTry) {
91
-			$this->retainJob = false;
92
-		}
93
-	}
90
+        if ($result === true || $try > $this->maxTry) {
91
+            $this->retainJob = false;
92
+        }
93
+    }
94 94
 
95
-	/**
96
-	 * re-add background job with new arguments
97
-	 *
98
-	 * @param IJobList $jobList
99
-	 * @param array $argument
100
-	 */
101
-	protected function reAddJob(IJobList $jobList, array $argument) {
102
-		$jobList->add(RetryJob::class,
103
-			[
104
-				'remote' => $argument['remote'],
105
-				'remoteId' => $argument['remoteId'],
106
-				'token' => $argument['token'],
107
-				'data' => $argument['data'],
108
-				'action' => $argument['action'],
109
-				'try' => (int)$argument['try'] + 1,
110
-				'lastRun' => $this->time->getTime()
111
-			]
112
-		);
113
-	}
95
+    /**
96
+     * re-add background job with new arguments
97
+     *
98
+     * @param IJobList $jobList
99
+     * @param array $argument
100
+     */
101
+    protected function reAddJob(IJobList $jobList, array $argument) {
102
+        $jobList->add(RetryJob::class,
103
+            [
104
+                'remote' => $argument['remote'],
105
+                'remoteId' => $argument['remoteId'],
106
+                'token' => $argument['token'],
107
+                'data' => $argument['data'],
108
+                'action' => $argument['action'],
109
+                'try' => (int)$argument['try'] + 1,
110
+                'lastRun' => $this->time->getTime()
111
+            ]
112
+        );
113
+    }
114 114
 
115
-	/**
116
-	 * test if it is time for the next run
117
-	 *
118
-	 * @param array $argument
119
-	 * @return bool
120
-	 */
121
-	protected function shouldRun(array $argument) {
122
-		$lastRun = (int)$argument['lastRun'];
123
-		return (($this->time->getTime() - $lastRun) > $this->interval);
124
-	}
115
+    /**
116
+     * test if it is time for the next run
117
+     *
118
+     * @param array $argument
119
+     * @return bool
120
+     */
121
+    protected function shouldRun(array $argument) {
122
+        $lastRun = (int)$argument['lastRun'];
123
+        return (($this->time->getTime() - $lastRun) > $this->interval);
124
+    }
125 125
 }
Please login to merge, or discard this patch.
apps/dav/lib/BackgroundJob/CleanupInvitationTokenJob.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -32,23 +32,23 @@
 block discarded – undo
32 32
 
33 33
 class CleanupInvitationTokenJob extends TimedJob {
34 34
 
35
-	/** @var IDBConnection  */
36
-	private $db;
37
-
38
-	public function __construct(IDBConnection $db, ITimeFactory $time) {
39
-		parent::__construct($time);
40
-		$this->db = $db;
41
-
42
-		// Run once a day at off-peak time
43
-		$this->setInterval(24 * 60 * 60);
44
-		$this->setTimeSensitivity(self::TIME_INSENSITIVE);
45
-	}
46
-
47
-	public function run($argument) {
48
-		$query = $this->db->getQueryBuilder();
49
-		$query->delete('calendar_invitations')
50
-			->where($query->expr()->lt('expiration',
51
-				$query->createNamedParameter($this->time->getTime())))
52
-			->execute();
53
-	}
35
+    /** @var IDBConnection  */
36
+    private $db;
37
+
38
+    public function __construct(IDBConnection $db, ITimeFactory $time) {
39
+        parent::__construct($time);
40
+        $this->db = $db;
41
+
42
+        // Run once a day at off-peak time
43
+        $this->setInterval(24 * 60 * 60);
44
+        $this->setTimeSensitivity(self::TIME_INSENSITIVE);
45
+    }
46
+
47
+    public function run($argument) {
48
+        $query = $this->db->getQueryBuilder();
49
+        $query->delete('calendar_invitations')
50
+            ->where($query->expr()->lt('expiration',
51
+                $query->createNamedParameter($this->time->getTime())))
52
+            ->execute();
53
+    }
54 54
 }
Please login to merge, or discard this patch.
apps/dav/lib/BackgroundJob/CalendarRetentionJob.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -30,20 +30,20 @@
 block discarded – undo
30 30
 use OCP\BackgroundJob\TimedJob;
31 31
 
32 32
 class CalendarRetentionJob extends TimedJob {
33
-	/** @var RetentionService */
34
-	private $service;
33
+    /** @var RetentionService */
34
+    private $service;
35 35
 
36
-	public function __construct(ITimeFactory $time,
37
-								RetentionService $service) {
38
-		parent::__construct($time);
39
-		$this->service = $service;
36
+    public function __construct(ITimeFactory $time,
37
+                                RetentionService $service) {
38
+        parent::__construct($time);
39
+        $this->service = $service;
40 40
 
41
-		// Run four times a day
42
-		$this->setInterval(6 * 60 * 60);
43
-		$this->setTimeSensitivity(self::TIME_SENSITIVE);
44
-	}
41
+        // Run four times a day
42
+        $this->setInterval(6 * 60 * 60);
43
+        $this->setTimeSensitivity(self::TIME_SENSITIVE);
44
+    }
45 45
 
46
-	protected function run($argument): void {
47
-		$this->service->cleanUp();
48
-	}
46
+    protected function run($argument): void {
47
+        $this->service->cleanUp();
48
+    }
49 49
 }
Please login to merge, or discard this patch.
apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php 1 patch
Indentation   +409 added lines, -409 removed lines patch added patch discarded remove patch
@@ -42,413 +42,413 @@
 block discarded – undo
42 42
 
43 43
 class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob {
44 44
 
45
-	/** @var IResourceManager */
46
-	private $resourceManager;
47
-
48
-	/** @var IRoomManager */
49
-	private $roomManager;
50
-
51
-	/** @var IDBConnection */
52
-	private $dbConnection;
53
-
54
-	/** @var CalDavBackend */
55
-	private $calDavBackend;
56
-
57
-	public function __construct(ITimeFactory $time,
58
-								IResourceManager $resourceManager,
59
-								IRoomManager $roomManager,
60
-								IDBConnection $dbConnection,
61
-								CalDavBackend $calDavBackend) {
62
-		parent::__construct($time);
63
-		$this->resourceManager = $resourceManager;
64
-		$this->roomManager = $roomManager;
65
-		$this->dbConnection = $dbConnection;
66
-		$this->calDavBackend = $calDavBackend;
67
-
68
-		// Run once an hour
69
-		$this->setInterval(60 * 60);
70
-		$this->setTimeSensitivity(self::TIME_SENSITIVE);
71
-	}
72
-
73
-	/**
74
-	 * @param $argument
75
-	 */
76
-	public function run($argument): void {
77
-		$this->runForBackend(
78
-			$this->resourceManager,
79
-			'calendar_resources',
80
-			'calendar_resources_md',
81
-			'resource_id',
82
-			'principals/calendar-resources'
83
-		);
84
-		$this->runForBackend(
85
-			$this->roomManager,
86
-			'calendar_rooms',
87
-			'calendar_rooms_md',
88
-			'room_id',
89
-			'principals/calendar-rooms'
90
-		);
91
-	}
92
-
93
-	/**
94
-	 * Run background-job for one specific backendManager
95
-	 * either ResourceManager or RoomManager
96
-	 *
97
-	 * @param IResourceManager|IRoomManager $backendManager
98
-	 * @param string $dbTable
99
-	 * @param string $dbTableMetadata
100
-	 * @param string $foreignKey
101
-	 * @param string $principalPrefix
102
-	 */
103
-	private function runForBackend($backendManager,
104
-								   string $dbTable,
105
-								   string $dbTableMetadata,
106
-								   string $foreignKey,
107
-								   string $principalPrefix): void {
108
-		$backends = $backendManager->getBackends();
109
-
110
-		foreach ($backends as $backend) {
111
-			$backendId = $backend->getBackendIdentifier();
112
-
113
-			try {
114
-				if ($backend instanceof IResourceBackend) {
115
-					$list = $backend->listAllResources();
116
-				} else {
117
-					$list = $backend->listAllRooms();
118
-				}
119
-			} catch (BackendTemporarilyUnavailableException $ex) {
120
-				continue;
121
-			}
122
-
123
-			$cachedList = $this->getAllCachedByBackend($dbTable, $backendId);
124
-			$newIds = array_diff($list, $cachedList);
125
-			$deletedIds = array_diff($cachedList, $list);
126
-			$editedIds = array_intersect($list, $cachedList);
127
-
128
-			foreach ($newIds as $newId) {
129
-				try {
130
-					if ($backend instanceof IResourceBackend) {
131
-						$resource = $backend->getResource($newId);
132
-					} else {
133
-						$resource = $backend->getRoom($newId);
134
-					}
135
-
136
-					$metadata = [];
137
-					if ($resource instanceof IMetadataProvider) {
138
-						$metadata = $this->getAllMetadataOfBackend($resource);
139
-					}
140
-				} catch (BackendTemporarilyUnavailableException $ex) {
141
-					continue;
142
-				}
143
-
144
-				$id = $this->addToCache($dbTable, $backendId, $resource);
145
-				$this->addMetadataToCache($dbTableMetadata, $foreignKey, $id, $metadata);
146
-				// we don't create the calendar here, it is created lazily
147
-				// when an event is actually scheduled with this resource / room
148
-			}
149
-
150
-			foreach ($deletedIds as $deletedId) {
151
-				$id = $this->getIdForBackendAndResource($dbTable, $backendId, $deletedId);
152
-				$this->deleteFromCache($dbTable, $id);
153
-				$this->deleteMetadataFromCache($dbTableMetadata, $foreignKey, $id);
154
-
155
-				$principalName = implode('-', [$backendId, $deletedId]);
156
-				$this->deleteCalendarDataForResource($principalPrefix, $principalName);
157
-			}
158
-
159
-			foreach ($editedIds as $editedId) {
160
-				$id = $this->getIdForBackendAndResource($dbTable, $backendId, $editedId);
161
-
162
-				try {
163
-					if ($backend instanceof IResourceBackend) {
164
-						$resource = $backend->getResource($editedId);
165
-					} else {
166
-						$resource = $backend->getRoom($editedId);
167
-					}
168
-
169
-					$metadata = [];
170
-					if ($resource instanceof IMetadataProvider) {
171
-						$metadata = $this->getAllMetadataOfBackend($resource);
172
-					}
173
-				} catch (BackendTemporarilyUnavailableException $ex) {
174
-					continue;
175
-				}
176
-
177
-				$this->updateCache($dbTable, $id, $resource);
178
-
179
-				if ($resource instanceof IMetadataProvider) {
180
-					$cachedMetadata = $this->getAllMetadataOfCache($dbTableMetadata, $foreignKey, $id);
181
-					$this->updateMetadataCache($dbTableMetadata, $foreignKey, $id, $metadata, $cachedMetadata);
182
-				}
183
-			}
184
-		}
185
-	}
186
-
187
-	/**
188
-	 * add entry to cache that exists remotely but not yet in cache
189
-	 *
190
-	 * @param string $table
191
-	 * @param string $backendId
192
-	 * @param IResource|IRoom $remote
193
-	 *
194
-	 * @return int Insert id
195
-	 */
196
-	private function addToCache(string $table,
197
-								string $backendId,
198
-								$remote): int {
199
-		$query = $this->dbConnection->getQueryBuilder();
200
-		$query->insert($table)
201
-			->values([
202
-				'backend_id' => $query->createNamedParameter($backendId),
203
-				'resource_id' => $query->createNamedParameter($remote->getId()),
204
-				'email' => $query->createNamedParameter($remote->getEMail()),
205
-				'displayname' => $query->createNamedParameter($remote->getDisplayName()),
206
-				'group_restrictions' => $query->createNamedParameter(
207
-					$this->serializeGroupRestrictions(
208
-						$remote->getGroupRestrictions()
209
-					))
210
-			])
211
-			->executeStatement();
212
-		return $query->getLastInsertId();
213
-	}
214
-
215
-	/**
216
-	 * @param string $table
217
-	 * @param string $foreignKey
218
-	 * @param int $foreignId
219
-	 * @param array $metadata
220
-	 */
221
-	private function addMetadataToCache(string $table,
222
-										string $foreignKey,
223
-										int $foreignId,
224
-										array $metadata): void {
225
-		foreach ($metadata as $key => $value) {
226
-			$query = $this->dbConnection->getQueryBuilder();
227
-			$query->insert($table)
228
-				->values([
229
-					$foreignKey => $query->createNamedParameter($foreignId),
230
-					'key' => $query->createNamedParameter($key),
231
-					'value' => $query->createNamedParameter($value),
232
-				])
233
-				->executeStatement();
234
-		}
235
-	}
236
-
237
-	/**
238
-	 * delete entry from cache that does not exist anymore remotely
239
-	 *
240
-	 * @param string $table
241
-	 * @param int $id
242
-	 */
243
-	private function deleteFromCache(string $table,
244
-									 int $id): void {
245
-		$query = $this->dbConnection->getQueryBuilder();
246
-		$query->delete($table)
247
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)))
248
-			->executeStatement();
249
-	}
250
-
251
-	/**
252
-	 * @param string $table
253
-	 * @param string $foreignKey
254
-	 * @param int $id
255
-	 */
256
-	private function deleteMetadataFromCache(string $table,
257
-											 string $foreignKey,
258
-											 int $id): void {
259
-		$query = $this->dbConnection->getQueryBuilder();
260
-		$query->delete($table)
261
-			->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
262
-			->executeStatement();
263
-	}
264
-
265
-	/**
266
-	 * update an existing entry in cache
267
-	 *
268
-	 * @param string $table
269
-	 * @param int $id
270
-	 * @param IResource|IRoom $remote
271
-	 */
272
-	private function updateCache(string $table,
273
-								 int $id,
274
-								 $remote): void {
275
-		$query = $this->dbConnection->getQueryBuilder();
276
-		$query->update($table)
277
-			->set('email', $query->createNamedParameter($remote->getEMail()))
278
-			->set('displayname', $query->createNamedParameter($remote->getDisplayName()))
279
-			->set('group_restrictions', $query->createNamedParameter(
280
-				$this->serializeGroupRestrictions(
281
-					$remote->getGroupRestrictions()
282
-				)))
283
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)))
284
-			->executeStatement();
285
-	}
286
-
287
-	/**
288
-	 * @param string $dbTable
289
-	 * @param string $foreignKey
290
-	 * @param int $id
291
-	 * @param array $metadata
292
-	 * @param array $cachedMetadata
293
-	 */
294
-	private function updateMetadataCache(string $dbTable,
295
-										 string $foreignKey,
296
-										 int $id,
297
-										 array $metadata,
298
-										 array $cachedMetadata): void {
299
-		$newMetadata = array_diff_key($metadata, $cachedMetadata);
300
-		$deletedMetadata = array_diff_key($cachedMetadata, $metadata);
301
-
302
-		foreach ($newMetadata as $key => $value) {
303
-			$query = $this->dbConnection->getQueryBuilder();
304
-			$query->insert($dbTable)
305
-				->values([
306
-					$foreignKey => $query->createNamedParameter($id),
307
-					'key' => $query->createNamedParameter($key),
308
-					'value' => $query->createNamedParameter($value),
309
-				])
310
-				->executeStatement();
311
-		}
312
-
313
-		foreach ($deletedMetadata as $key => $value) {
314
-			$query = $this->dbConnection->getQueryBuilder();
315
-			$query->delete($dbTable)
316
-				->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
317
-				->andWhere($query->expr()->eq('key', $query->createNamedParameter($key)))
318
-				->executeStatement();
319
-		}
320
-
321
-		$existingKeys = array_keys(array_intersect_key($metadata, $cachedMetadata));
322
-		foreach ($existingKeys as $existingKey) {
323
-			if ($metadata[$existingKey] !== $cachedMetadata[$existingKey]) {
324
-				$query = $this->dbConnection->getQueryBuilder();
325
-				$query->update($dbTable)
326
-					->set('value', $query->createNamedParameter($metadata[$existingKey]))
327
-					->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
328
-					->andWhere($query->expr()->eq('key', $query->createNamedParameter($existingKey)))
329
-					->executeStatement();
330
-			}
331
-		}
332
-	}
333
-
334
-	/**
335
-	 * serialize array of group restrictions to store them in database
336
-	 *
337
-	 * @param array $groups
338
-	 *
339
-	 * @return string
340
-	 */
341
-	private function serializeGroupRestrictions(array $groups): string {
342
-		return \json_encode($groups);
343
-	}
344
-
345
-	/**
346
-	 * Gets all metadata of a backend
347
-	 *
348
-	 * @param IResource|IRoom $resource
349
-	 *
350
-	 * @return array
351
-	 */
352
-	private function getAllMetadataOfBackend($resource): array {
353
-		if (!($resource instanceof IMetadataProvider)) {
354
-			return [];
355
-		}
356
-
357
-		$keys = $resource->getAllAvailableMetadataKeys();
358
-		$metadata = [];
359
-		foreach ($keys as $key) {
360
-			$metadata[$key] = $resource->getMetadataForKey($key);
361
-		}
362
-
363
-		return $metadata;
364
-	}
365
-
366
-	/**
367
-	 * @param string $table
368
-	 * @param string $foreignKey
369
-	 * @param int $id
370
-	 *
371
-	 * @return array
372
-	 */
373
-	private function getAllMetadataOfCache(string $table,
374
-										   string $foreignKey,
375
-										   int $id): array {
376
-		$query = $this->dbConnection->getQueryBuilder();
377
-		$query->select(['key', 'value'])
378
-			->from($table)
379
-			->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)));
380
-		$result = $query->executeQuery();
381
-		$rows = $result->fetchAll();
382
-		$result->closeCursor();
383
-
384
-		$metadata = [];
385
-		foreach ($rows as $row) {
386
-			$metadata[$row['key']] = $row['value'];
387
-		}
388
-
389
-		return $metadata;
390
-	}
391
-
392
-	/**
393
-	 * Gets all cached rooms / resources by backend
394
-	 *
395
-	 * @param $tableName
396
-	 * @param $backendId
397
-	 *
398
-	 * @return array
399
-	 */
400
-	private function getAllCachedByBackend(string $tableName,
401
-										   string $backendId): array {
402
-		$query = $this->dbConnection->getQueryBuilder();
403
-		$query->select('resource_id')
404
-			->from($tableName)
405
-			->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)));
406
-		$result = $query->executeQuery();
407
-		$rows = $result->fetchAll();
408
-		$result->closeCursor();
409
-
410
-		return array_map(function ($row): string {
411
-			return $row['resource_id'];
412
-		}, $rows);
413
-	}
414
-
415
-	/**
416
-	 * @param $principalPrefix
417
-	 * @param $principalUri
418
-	 */
419
-	private function deleteCalendarDataForResource(string $principalPrefix,
420
-												   string $principalUri): void {
421
-		$calendar = $this->calDavBackend->getCalendarByUri(
422
-			implode('/', [$principalPrefix, $principalUri]),
423
-			CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI);
424
-
425
-		if ($calendar !== null) {
426
-			$this->calDavBackend->deleteCalendar(
427
-				$calendar['id'],
428
-				true // Because this wasn't deleted by a user
429
-			);
430
-		}
431
-	}
432
-
433
-	/**
434
-	 * @param $table
435
-	 * @param $backendId
436
-	 * @param $resourceId
437
-	 *
438
-	 * @return int
439
-	 */
440
-	private function getIdForBackendAndResource(string $table,
441
-												string $backendId,
442
-												string $resourceId): int {
443
-		$query = $this->dbConnection->getQueryBuilder();
444
-		$query->select('id')
445
-			->from($table)
446
-			->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
447
-			->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
448
-		$result = $query->executeQuery();
449
-
450
-		$id = (int) $result->fetchOne();
451
-		$result->closeCursor();
452
-		return $id;
453
-	}
45
+    /** @var IResourceManager */
46
+    private $resourceManager;
47
+
48
+    /** @var IRoomManager */
49
+    private $roomManager;
50
+
51
+    /** @var IDBConnection */
52
+    private $dbConnection;
53
+
54
+    /** @var CalDavBackend */
55
+    private $calDavBackend;
56
+
57
+    public function __construct(ITimeFactory $time,
58
+                                IResourceManager $resourceManager,
59
+                                IRoomManager $roomManager,
60
+                                IDBConnection $dbConnection,
61
+                                CalDavBackend $calDavBackend) {
62
+        parent::__construct($time);
63
+        $this->resourceManager = $resourceManager;
64
+        $this->roomManager = $roomManager;
65
+        $this->dbConnection = $dbConnection;
66
+        $this->calDavBackend = $calDavBackend;
67
+
68
+        // Run once an hour
69
+        $this->setInterval(60 * 60);
70
+        $this->setTimeSensitivity(self::TIME_SENSITIVE);
71
+    }
72
+
73
+    /**
74
+     * @param $argument
75
+     */
76
+    public function run($argument): void {
77
+        $this->runForBackend(
78
+            $this->resourceManager,
79
+            'calendar_resources',
80
+            'calendar_resources_md',
81
+            'resource_id',
82
+            'principals/calendar-resources'
83
+        );
84
+        $this->runForBackend(
85
+            $this->roomManager,
86
+            'calendar_rooms',
87
+            'calendar_rooms_md',
88
+            'room_id',
89
+            'principals/calendar-rooms'
90
+        );
91
+    }
92
+
93
+    /**
94
+     * Run background-job for one specific backendManager
95
+     * either ResourceManager or RoomManager
96
+     *
97
+     * @param IResourceManager|IRoomManager $backendManager
98
+     * @param string $dbTable
99
+     * @param string $dbTableMetadata
100
+     * @param string $foreignKey
101
+     * @param string $principalPrefix
102
+     */
103
+    private function runForBackend($backendManager,
104
+                                    string $dbTable,
105
+                                    string $dbTableMetadata,
106
+                                    string $foreignKey,
107
+                                    string $principalPrefix): void {
108
+        $backends = $backendManager->getBackends();
109
+
110
+        foreach ($backends as $backend) {
111
+            $backendId = $backend->getBackendIdentifier();
112
+
113
+            try {
114
+                if ($backend instanceof IResourceBackend) {
115
+                    $list = $backend->listAllResources();
116
+                } else {
117
+                    $list = $backend->listAllRooms();
118
+                }
119
+            } catch (BackendTemporarilyUnavailableException $ex) {
120
+                continue;
121
+            }
122
+
123
+            $cachedList = $this->getAllCachedByBackend($dbTable, $backendId);
124
+            $newIds = array_diff($list, $cachedList);
125
+            $deletedIds = array_diff($cachedList, $list);
126
+            $editedIds = array_intersect($list, $cachedList);
127
+
128
+            foreach ($newIds as $newId) {
129
+                try {
130
+                    if ($backend instanceof IResourceBackend) {
131
+                        $resource = $backend->getResource($newId);
132
+                    } else {
133
+                        $resource = $backend->getRoom($newId);
134
+                    }
135
+
136
+                    $metadata = [];
137
+                    if ($resource instanceof IMetadataProvider) {
138
+                        $metadata = $this->getAllMetadataOfBackend($resource);
139
+                    }
140
+                } catch (BackendTemporarilyUnavailableException $ex) {
141
+                    continue;
142
+                }
143
+
144
+                $id = $this->addToCache($dbTable, $backendId, $resource);
145
+                $this->addMetadataToCache($dbTableMetadata, $foreignKey, $id, $metadata);
146
+                // we don't create the calendar here, it is created lazily
147
+                // when an event is actually scheduled with this resource / room
148
+            }
149
+
150
+            foreach ($deletedIds as $deletedId) {
151
+                $id = $this->getIdForBackendAndResource($dbTable, $backendId, $deletedId);
152
+                $this->deleteFromCache($dbTable, $id);
153
+                $this->deleteMetadataFromCache($dbTableMetadata, $foreignKey, $id);
154
+
155
+                $principalName = implode('-', [$backendId, $deletedId]);
156
+                $this->deleteCalendarDataForResource($principalPrefix, $principalName);
157
+            }
158
+
159
+            foreach ($editedIds as $editedId) {
160
+                $id = $this->getIdForBackendAndResource($dbTable, $backendId, $editedId);
161
+
162
+                try {
163
+                    if ($backend instanceof IResourceBackend) {
164
+                        $resource = $backend->getResource($editedId);
165
+                    } else {
166
+                        $resource = $backend->getRoom($editedId);
167
+                    }
168
+
169
+                    $metadata = [];
170
+                    if ($resource instanceof IMetadataProvider) {
171
+                        $metadata = $this->getAllMetadataOfBackend($resource);
172
+                    }
173
+                } catch (BackendTemporarilyUnavailableException $ex) {
174
+                    continue;
175
+                }
176
+
177
+                $this->updateCache($dbTable, $id, $resource);
178
+
179
+                if ($resource instanceof IMetadataProvider) {
180
+                    $cachedMetadata = $this->getAllMetadataOfCache($dbTableMetadata, $foreignKey, $id);
181
+                    $this->updateMetadataCache($dbTableMetadata, $foreignKey, $id, $metadata, $cachedMetadata);
182
+                }
183
+            }
184
+        }
185
+    }
186
+
187
+    /**
188
+     * add entry to cache that exists remotely but not yet in cache
189
+     *
190
+     * @param string $table
191
+     * @param string $backendId
192
+     * @param IResource|IRoom $remote
193
+     *
194
+     * @return int Insert id
195
+     */
196
+    private function addToCache(string $table,
197
+                                string $backendId,
198
+                                $remote): int {
199
+        $query = $this->dbConnection->getQueryBuilder();
200
+        $query->insert($table)
201
+            ->values([
202
+                'backend_id' => $query->createNamedParameter($backendId),
203
+                'resource_id' => $query->createNamedParameter($remote->getId()),
204
+                'email' => $query->createNamedParameter($remote->getEMail()),
205
+                'displayname' => $query->createNamedParameter($remote->getDisplayName()),
206
+                'group_restrictions' => $query->createNamedParameter(
207
+                    $this->serializeGroupRestrictions(
208
+                        $remote->getGroupRestrictions()
209
+                    ))
210
+            ])
211
+            ->executeStatement();
212
+        return $query->getLastInsertId();
213
+    }
214
+
215
+    /**
216
+     * @param string $table
217
+     * @param string $foreignKey
218
+     * @param int $foreignId
219
+     * @param array $metadata
220
+     */
221
+    private function addMetadataToCache(string $table,
222
+                                        string $foreignKey,
223
+                                        int $foreignId,
224
+                                        array $metadata): void {
225
+        foreach ($metadata as $key => $value) {
226
+            $query = $this->dbConnection->getQueryBuilder();
227
+            $query->insert($table)
228
+                ->values([
229
+                    $foreignKey => $query->createNamedParameter($foreignId),
230
+                    'key' => $query->createNamedParameter($key),
231
+                    'value' => $query->createNamedParameter($value),
232
+                ])
233
+                ->executeStatement();
234
+        }
235
+    }
236
+
237
+    /**
238
+     * delete entry from cache that does not exist anymore remotely
239
+     *
240
+     * @param string $table
241
+     * @param int $id
242
+     */
243
+    private function deleteFromCache(string $table,
244
+                                        int $id): void {
245
+        $query = $this->dbConnection->getQueryBuilder();
246
+        $query->delete($table)
247
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)))
248
+            ->executeStatement();
249
+    }
250
+
251
+    /**
252
+     * @param string $table
253
+     * @param string $foreignKey
254
+     * @param int $id
255
+     */
256
+    private function deleteMetadataFromCache(string $table,
257
+                                                string $foreignKey,
258
+                                                int $id): void {
259
+        $query = $this->dbConnection->getQueryBuilder();
260
+        $query->delete($table)
261
+            ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
262
+            ->executeStatement();
263
+    }
264
+
265
+    /**
266
+     * update an existing entry in cache
267
+     *
268
+     * @param string $table
269
+     * @param int $id
270
+     * @param IResource|IRoom $remote
271
+     */
272
+    private function updateCache(string $table,
273
+                                    int $id,
274
+                                    $remote): void {
275
+        $query = $this->dbConnection->getQueryBuilder();
276
+        $query->update($table)
277
+            ->set('email', $query->createNamedParameter($remote->getEMail()))
278
+            ->set('displayname', $query->createNamedParameter($remote->getDisplayName()))
279
+            ->set('group_restrictions', $query->createNamedParameter(
280
+                $this->serializeGroupRestrictions(
281
+                    $remote->getGroupRestrictions()
282
+                )))
283
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)))
284
+            ->executeStatement();
285
+    }
286
+
287
+    /**
288
+     * @param string $dbTable
289
+     * @param string $foreignKey
290
+     * @param int $id
291
+     * @param array $metadata
292
+     * @param array $cachedMetadata
293
+     */
294
+    private function updateMetadataCache(string $dbTable,
295
+                                            string $foreignKey,
296
+                                            int $id,
297
+                                            array $metadata,
298
+                                            array $cachedMetadata): void {
299
+        $newMetadata = array_diff_key($metadata, $cachedMetadata);
300
+        $deletedMetadata = array_diff_key($cachedMetadata, $metadata);
301
+
302
+        foreach ($newMetadata as $key => $value) {
303
+            $query = $this->dbConnection->getQueryBuilder();
304
+            $query->insert($dbTable)
305
+                ->values([
306
+                    $foreignKey => $query->createNamedParameter($id),
307
+                    'key' => $query->createNamedParameter($key),
308
+                    'value' => $query->createNamedParameter($value),
309
+                ])
310
+                ->executeStatement();
311
+        }
312
+
313
+        foreach ($deletedMetadata as $key => $value) {
314
+            $query = $this->dbConnection->getQueryBuilder();
315
+            $query->delete($dbTable)
316
+                ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
317
+                ->andWhere($query->expr()->eq('key', $query->createNamedParameter($key)))
318
+                ->executeStatement();
319
+        }
320
+
321
+        $existingKeys = array_keys(array_intersect_key($metadata, $cachedMetadata));
322
+        foreach ($existingKeys as $existingKey) {
323
+            if ($metadata[$existingKey] !== $cachedMetadata[$existingKey]) {
324
+                $query = $this->dbConnection->getQueryBuilder();
325
+                $query->update($dbTable)
326
+                    ->set('value', $query->createNamedParameter($metadata[$existingKey]))
327
+                    ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
328
+                    ->andWhere($query->expr()->eq('key', $query->createNamedParameter($existingKey)))
329
+                    ->executeStatement();
330
+            }
331
+        }
332
+    }
333
+
334
+    /**
335
+     * serialize array of group restrictions to store them in database
336
+     *
337
+     * @param array $groups
338
+     *
339
+     * @return string
340
+     */
341
+    private function serializeGroupRestrictions(array $groups): string {
342
+        return \json_encode($groups);
343
+    }
344
+
345
+    /**
346
+     * Gets all metadata of a backend
347
+     *
348
+     * @param IResource|IRoom $resource
349
+     *
350
+     * @return array
351
+     */
352
+    private function getAllMetadataOfBackend($resource): array {
353
+        if (!($resource instanceof IMetadataProvider)) {
354
+            return [];
355
+        }
356
+
357
+        $keys = $resource->getAllAvailableMetadataKeys();
358
+        $metadata = [];
359
+        foreach ($keys as $key) {
360
+            $metadata[$key] = $resource->getMetadataForKey($key);
361
+        }
362
+
363
+        return $metadata;
364
+    }
365
+
366
+    /**
367
+     * @param string $table
368
+     * @param string $foreignKey
369
+     * @param int $id
370
+     *
371
+     * @return array
372
+     */
373
+    private function getAllMetadataOfCache(string $table,
374
+                                            string $foreignKey,
375
+                                            int $id): array {
376
+        $query = $this->dbConnection->getQueryBuilder();
377
+        $query->select(['key', 'value'])
378
+            ->from($table)
379
+            ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)));
380
+        $result = $query->executeQuery();
381
+        $rows = $result->fetchAll();
382
+        $result->closeCursor();
383
+
384
+        $metadata = [];
385
+        foreach ($rows as $row) {
386
+            $metadata[$row['key']] = $row['value'];
387
+        }
388
+
389
+        return $metadata;
390
+    }
391
+
392
+    /**
393
+     * Gets all cached rooms / resources by backend
394
+     *
395
+     * @param $tableName
396
+     * @param $backendId
397
+     *
398
+     * @return array
399
+     */
400
+    private function getAllCachedByBackend(string $tableName,
401
+                                            string $backendId): array {
402
+        $query = $this->dbConnection->getQueryBuilder();
403
+        $query->select('resource_id')
404
+            ->from($tableName)
405
+            ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)));
406
+        $result = $query->executeQuery();
407
+        $rows = $result->fetchAll();
408
+        $result->closeCursor();
409
+
410
+        return array_map(function ($row): string {
411
+            return $row['resource_id'];
412
+        }, $rows);
413
+    }
414
+
415
+    /**
416
+     * @param $principalPrefix
417
+     * @param $principalUri
418
+     */
419
+    private function deleteCalendarDataForResource(string $principalPrefix,
420
+                                                    string $principalUri): void {
421
+        $calendar = $this->calDavBackend->getCalendarByUri(
422
+            implode('/', [$principalPrefix, $principalUri]),
423
+            CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI);
424
+
425
+        if ($calendar !== null) {
426
+            $this->calDavBackend->deleteCalendar(
427
+                $calendar['id'],
428
+                true // Because this wasn't deleted by a user
429
+            );
430
+        }
431
+    }
432
+
433
+    /**
434
+     * @param $table
435
+     * @param $backendId
436
+     * @param $resourceId
437
+     *
438
+     * @return int
439
+     */
440
+    private function getIdForBackendAndResource(string $table,
441
+                                                string $backendId,
442
+                                                string $resourceId): int {
443
+        $query = $this->dbConnection->getQueryBuilder();
444
+        $query->select('id')
445
+            ->from($table)
446
+            ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
447
+            ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
448
+        $result = $query->executeQuery();
449
+
450
+        $id = (int) $result->fetchOne();
451
+        $result->closeCursor();
452
+        return $id;
453
+    }
454 454
 }
Please login to merge, or discard this patch.
apps/dav/lib/BackgroundJob/CleanupDirectLinksJob.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -31,20 +31,20 @@
 block discarded – undo
31 31
 use OCP\BackgroundJob\TimedJob;
32 32
 
33 33
 class CleanupDirectLinksJob extends TimedJob {
34
-	/** @var DirectMapper */
35
-	private $mapper;
34
+    /** @var DirectMapper */
35
+    private $mapper;
36 36
 
37
-	public function __construct(ITimeFactory $timeFactory, DirectMapper $mapper) {
38
-		parent::__construct($timeFactory);
39
-		$this->mapper = $mapper;
37
+    public function __construct(ITimeFactory $timeFactory, DirectMapper $mapper) {
38
+        parent::__construct($timeFactory);
39
+        $this->mapper = $mapper;
40 40
 
41
-		// Run once a day at off-peak time
42
-		$this->setInterval(24 * 60 * 60);
43
-		$this->setTimeSensitivity(self::TIME_INSENSITIVE);
44
-	}
41
+        // Run once a day at off-peak time
42
+        $this->setInterval(24 * 60 * 60);
43
+        $this->setTimeSensitivity(self::TIME_INSENSITIVE);
44
+    }
45 45
 
46
-	protected function run($argument) {
47
-		// Delete all shares expired 24 hours ago
48
-		$this->mapper->deleteExpired($this->time->getTime() - 60 * 60 * 24);
49
-	}
46
+    protected function run($argument) {
47
+        // Delete all shares expired 24 hours ago
48
+        $this->mapper->deleteExpired($this->time->getTime() - 60 * 60 * 24);
49
+    }
50 50
 }
Please login to merge, or discard this patch.
apps/dav/lib/BackgroundJob/EventReminderJob.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -33,39 +33,39 @@
 block discarded – undo
33 33
 
34 34
 class EventReminderJob extends TimedJob {
35 35
 
36
-	/** @var ReminderService */
37
-	private $reminderService;
36
+    /** @var ReminderService */
37
+    private $reminderService;
38 38
 
39
-	/** @var IConfig */
40
-	private $config;
39
+    /** @var IConfig */
40
+    private $config;
41 41
 
42
-	public function __construct(ITimeFactory $time,
43
-								ReminderService $reminderService,
44
-								IConfig $config) {
45
-		parent::__construct($time);
46
-		$this->reminderService = $reminderService;
47
-		$this->config = $config;
42
+    public function __construct(ITimeFactory $time,
43
+                                ReminderService $reminderService,
44
+                                IConfig $config) {
45
+        parent::__construct($time);
46
+        $this->reminderService = $reminderService;
47
+        $this->config = $config;
48 48
 
49
-		// Run every 5 minutes
50
-		$this->setInterval(5 * 60);
51
-		$this->setTimeSensitivity(self::TIME_SENSITIVE);
52
-	}
49
+        // Run every 5 minutes
50
+        $this->setInterval(5 * 60);
51
+        $this->setTimeSensitivity(self::TIME_SENSITIVE);
52
+    }
53 53
 
54
-	/**
55
-	 * @param $arg
56
-	 * @throws \OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException
57
-	 * @throws \OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException
58
-	 * @throws \OC\User\NoUserException
59
-	 */
60
-	public function run($arg):void {
61
-		if ($this->config->getAppValue('dav', 'sendEventReminders', 'yes') !== 'yes') {
62
-			return;
63
-		}
54
+    /**
55
+     * @param $arg
56
+     * @throws \OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException
57
+     * @throws \OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException
58
+     * @throws \OC\User\NoUserException
59
+     */
60
+    public function run($arg):void {
61
+        if ($this->config->getAppValue('dav', 'sendEventReminders', 'yes') !== 'yes') {
62
+            return;
63
+        }
64 64
 
65
-		if ($this->config->getAppValue('dav', 'sendEventRemindersMode', 'backgroundjob') !== 'backgroundjob') {
66
-			return;
67
-		}
65
+        if ($this->config->getAppValue('dav', 'sendEventRemindersMode', 'backgroundjob') !== 'backgroundjob') {
66
+            return;
67
+        }
68 68
 
69
-		$this->reminderService->processReminders();
70
-	}
69
+        $this->reminderService->processReminders();
70
+    }
71 71
 }
Please login to merge, or discard this patch.
apps/dav/lib/BackgroundJob/GenerateBirthdayCalendarBackgroundJob.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -32,44 +32,44 @@
 block discarded – undo
32 32
 
33 33
 class GenerateBirthdayCalendarBackgroundJob extends QueuedJob {
34 34
 
35
-	/** @var BirthdayService */
36
-	private $birthdayService;
35
+    /** @var BirthdayService */
36
+    private $birthdayService;
37 37
 
38
-	/** @var IConfig */
39
-	private $config;
38
+    /** @var IConfig */
39
+    private $config;
40 40
 
41
-	public function __construct(ITimeFactory $time,
42
-								BirthdayService $birthdayService,
43
-								IConfig $config) {
44
-		parent::__construct($time);
41
+    public function __construct(ITimeFactory $time,
42
+                                BirthdayService $birthdayService,
43
+                                IConfig $config) {
44
+        parent::__construct($time);
45 45
 
46
-		$this->birthdayService = $birthdayService;
47
-		$this->config = $config;
48
-	}
46
+        $this->birthdayService = $birthdayService;
47
+        $this->config = $config;
48
+    }
49 49
 
50
-	/**
51
-	 * @param array $arguments
52
-	 */
53
-	public function run($arguments) {
54
-		$userId = $arguments['userId'];
55
-		$purgeBeforeGenerating = $arguments['purgeBeforeGenerating'] ?? false;
50
+    /**
51
+     * @param array $arguments
52
+     */
53
+    public function run($arguments) {
54
+        $userId = $arguments['userId'];
55
+        $purgeBeforeGenerating = $arguments['purgeBeforeGenerating'] ?? false;
56 56
 
57
-		// make sure admin didn't change his mind
58
-		$isGloballyEnabled = $this->config->getAppValue('dav', 'generateBirthdayCalendar', 'yes');
59
-		if ($isGloballyEnabled !== 'yes') {
60
-			return;
61
-		}
57
+        // make sure admin didn't change his mind
58
+        $isGloballyEnabled = $this->config->getAppValue('dav', 'generateBirthdayCalendar', 'yes');
59
+        if ($isGloballyEnabled !== 'yes') {
60
+            return;
61
+        }
62 62
 
63
-		// did the user opt out?
64
-		$isUserEnabled = $this->config->getUserValue($userId, 'dav', 'generateBirthdayCalendar', 'yes');
65
-		if ($isUserEnabled !== 'yes') {
66
-			return;
67
-		}
63
+        // did the user opt out?
64
+        $isUserEnabled = $this->config->getUserValue($userId, 'dav', 'generateBirthdayCalendar', 'yes');
65
+        if ($isUserEnabled !== 'yes') {
66
+            return;
67
+        }
68 68
 
69
-		if ($purgeBeforeGenerating) {
70
-			$this->birthdayService->resetForUser($userId);
71
-		}
69
+        if ($purgeBeforeGenerating) {
70
+            $this->birthdayService->resetForUser($userId);
71
+        }
72 72
 
73
-		$this->birthdayService->syncUser($userId);
74
-	}
73
+        $this->birthdayService->syncUser($userId);
74
+    }
75 75
 }
Please login to merge, or discard this patch.