UpdateCalendarResourcesRoomsBackgroundJob.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. /**
  3. * @copyright 2019, Georg Ehrke <oc.list@georgehrke.com>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Georg Ehrke <oc.list@georgehrke.com>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OCA\DAV\BackgroundJob;
  25. use OC\BackgroundJob\TimedJob;
  26. use OCA\DAV\CalDAV\CalDavBackend;
  27. use OCP\Calendar\BackendTemporarilyUnavailableException;
  28. use OCP\Calendar\IMetadataProvider;
  29. use OCP\Calendar\Resource\IBackend as IResourceBackend;
  30. use OCP\Calendar\Resource\IManager as IResourceManager;
  31. use OCP\Calendar\Resource\IResource;
  32. use OCP\Calendar\Room\IManager as IRoomManager;
  33. use OCP\Calendar\Room\IRoom;
  34. use OCP\IDBConnection;
  35. class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob {
  36. /** @var IResourceManager */
  37. private $resourceManager;
  38. /** @var IRoomManager */
  39. private $roomManager;
  40. /** @var IDBConnection */
  41. private $dbConnection;
  42. /** @var CalDavBackend */
  43. private $calDavBackend;
  44. /**
  45. * UpdateCalendarResourcesRoomsBackgroundJob constructor.
  46. *
  47. * @param IResourceManager $resourceManager
  48. * @param IRoomManager $roomManager
  49. * @param IDBConnection $dbConnection
  50. * @param CalDavBackend $calDavBackend
  51. */
  52. public function __construct(IResourceManager $resourceManager,
  53. IRoomManager $roomManager,
  54. IDBConnection $dbConnection,
  55. CalDavBackend $calDavBackend) {
  56. $this->resourceManager = $resourceManager;
  57. $this->roomManager = $roomManager;
  58. $this->dbConnection = $dbConnection;
  59. $this->calDavBackend = $calDavBackend;
  60. // run once an hour
  61. $this->setInterval(60 * 60);
  62. }
  63. /**
  64. * @param $argument
  65. */
  66. public function run($argument):void {
  67. $this->runForBackend(
  68. $this->resourceManager,
  69. 'calendar_resources',
  70. 'calendar_resources_md',
  71. 'resource_id',
  72. 'principals/calendar-resources'
  73. );
  74. $this->runForBackend(
  75. $this->roomManager,
  76. 'calendar_rooms',
  77. 'calendar_rooms_md',
  78. 'room_id',
  79. 'principals/calendar-rooms'
  80. );
  81. }
  82. /**
  83. * Run background-job for one specific backendManager
  84. * either ResourceManager or RoomManager
  85. *
  86. * @param IResourceManager|IRoomManager $backendManager
  87. * @param string $dbTable
  88. * @param string $dbTableMetadata
  89. * @param string $foreignKey
  90. * @param string $principalPrefix
  91. */
  92. private function runForBackend($backendManager,
  93. string $dbTable,
  94. string $dbTableMetadata,
  95. string $foreignKey,
  96. string $principalPrefix):void {
  97. $backends = $backendManager->getBackends();
  98. foreach ($backends as $backend) {
  99. $backendId = $backend->getBackendIdentifier();
  100. try {
  101. if ($backend instanceof IResourceBackend) {
  102. $list = $backend->listAllResources();
  103. } else {
  104. $list = $backend->listAllRooms();
  105. }
  106. } catch (BackendTemporarilyUnavailableException $ex) {
  107. continue;
  108. }
  109. $cachedList = $this->getAllCachedByBackend($dbTable, $backendId);
  110. $newIds = array_diff($list, $cachedList);
  111. $deletedIds = array_diff($cachedList, $list);
  112. $editedIds = array_intersect($list, $cachedList);
  113. foreach ($newIds as $newId) {
  114. try {
  115. if ($backend instanceof IResourceBackend) {
  116. $resource = $backend->getResource($newId);
  117. } else {
  118. $resource = $backend->getRoom($newId);
  119. }
  120. $metadata = [];
  121. if ($resource instanceof IMetadataProvider) {
  122. $metadata = $this->getAllMetadataOfBackend($resource);
  123. }
  124. } catch (BackendTemporarilyUnavailableException $ex) {
  125. continue;
  126. }
  127. $id = $this->addToCache($dbTable, $backendId, $resource);
  128. $this->addMetadataToCache($dbTableMetadata, $foreignKey, $id, $metadata);
  129. // we don't create the calendar here, it is created lazily
  130. // when an event is actually scheduled with this resource / room
  131. }
  132. foreach ($deletedIds as $deletedId) {
  133. $id = $this->getIdForBackendAndResource($dbTable, $backendId, $deletedId);
  134. $this->deleteFromCache($dbTable, $id);
  135. $this->deleteMetadataFromCache($dbTableMetadata, $foreignKey, $id);
  136. $principalName = implode('-', [$backendId, $deletedId]);
  137. $this->deleteCalendarDataForResource($principalPrefix, $principalName);
  138. }
  139. foreach ($editedIds as $editedId) {
  140. $id = $this->getIdForBackendAndResource($dbTable, $backendId, $editedId);
  141. try {
  142. if ($backend instanceof IResourceBackend) {
  143. $resource = $backend->getResource($editedId);
  144. } else {
  145. $resource = $backend->getRoom($editedId);
  146. }
  147. $metadata = [];
  148. if ($resource instanceof IMetadataProvider) {
  149. $metadata = $this->getAllMetadataOfBackend($resource);
  150. }
  151. } catch (BackendTemporarilyUnavailableException $ex) {
  152. continue;
  153. }
  154. $this->updateCache($dbTable, $id, $resource);
  155. if ($resource instanceof IMetadataProvider) {
  156. $cachedMetadata = $this->getAllMetadataOfCache($dbTableMetadata, $foreignKey, $id);
  157. $this->updateMetadataCache($dbTableMetadata, $foreignKey, $id, $metadata, $cachedMetadata);
  158. }
  159. }
  160. }
  161. }
  162. /**
  163. * add entry to cache that exists remotely but not yet in cache
  164. *
  165. * @param string $table
  166. * @param string $backendId
  167. * @param IResource|IRoom $remote
  168. * @return int Insert id
  169. */
  170. private function addToCache(string $table,
  171. string $backendId,
  172. $remote):int {
  173. $query = $this->dbConnection->getQueryBuilder();
  174. $query->insert($table)
  175. ->values([
  176. 'backend_id' => $query->createNamedParameter($backendId),
  177. 'resource_id' => $query->createNamedParameter($remote->getId()),
  178. 'email' => $query->createNamedParameter($remote->getEMail()),
  179. 'displayname' => $query->createNamedParameter($remote->getDisplayName()),
  180. 'group_restrictions' => $query->createNamedParameter(
  181. $this->serializeGroupRestrictions(
  182. $remote->getGroupRestrictions()
  183. ))
  184. ])
  185. ->execute();
  186. return $query->getLastInsertId();
  187. }
  188. /**
  189. * @param string $table
  190. * @param string $foreignKey
  191. * @param int $foreignId
  192. * @param array $metadata
  193. */
  194. private function addMetadataToCache(string $table,
  195. string $foreignKey,
  196. int $foreignId,
  197. array $metadata):void {
  198. foreach ($metadata as $key => $value) {
  199. $query = $this->dbConnection->getQueryBuilder();
  200. $query->insert($table)
  201. ->values([
  202. $foreignKey => $query->createNamedParameter($foreignId),
  203. 'key' => $query->createNamedParameter($key),
  204. 'value' => $query->createNamedParameter($value),
  205. ])
  206. ->execute();
  207. }
  208. }
  209. /**
  210. * delete entry from cache that does not exist anymore remotely
  211. *
  212. * @param string $table
  213. * @param int $id
  214. */
  215. private function deleteFromCache(string $table,
  216. int $id):void {
  217. $query = $this->dbConnection->getQueryBuilder();
  218. $query->delete($table)
  219. ->where($query->expr()->eq('id', $query->createNamedParameter($id)))
  220. ->execute();
  221. }
  222. /**
  223. * @param string $table
  224. * @param string $foreignKey
  225. * @param int $id
  226. */
  227. private function deleteMetadataFromCache(string $table,
  228. string $foreignKey,
  229. int $id):void {
  230. $query = $this->dbConnection->getQueryBuilder();
  231. $query->delete($table)
  232. ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
  233. ->execute();
  234. }
  235. /**
  236. * update an existing entry in cache
  237. *
  238. * @param string $table
  239. * @param int $id
  240. * @param IResource|IRoom $remote
  241. */
  242. private function updateCache(string $table,
  243. int $id,
  244. $remote):void {
  245. $query = $this->dbConnection->getQueryBuilder();
  246. $query->update($table)
  247. ->set('email', $query->createNamedParameter($remote->getEMail()))
  248. ->set('displayname', $query->createNamedParameter($remote->getDisplayName()))
  249. ->set('group_restrictions', $query->createNamedParameter(
  250. $this->serializeGroupRestrictions(
  251. $remote->getGroupRestrictions()
  252. )))
  253. ->where($query->expr()->eq('id', $query->createNamedParameter($id)))
  254. ->execute();
  255. }
  256. /**
  257. * @param string $dbTable
  258. * @param string $foreignKey
  259. * @param int $id
  260. * @param array $metadata
  261. * @param array $cachedMetadata
  262. */
  263. private function updateMetadataCache(string $dbTable,
  264. string $foreignKey,
  265. int $id,
  266. array $metadata,
  267. array $cachedMetadata):void {
  268. $newMetadata = array_diff_key($metadata, $cachedMetadata);
  269. $deletedMetadata = array_diff_key($cachedMetadata, $metadata);
  270. foreach ($newMetadata as $key => $value) {
  271. $query = $this->dbConnection->getQueryBuilder();
  272. $query->insert($dbTable)
  273. ->values([
  274. $foreignKey => $query->createNamedParameter($id),
  275. 'key' => $query->createNamedParameter($key),
  276. 'value' => $query->createNamedParameter($value),
  277. ])
  278. ->execute();
  279. }
  280. foreach ($deletedMetadata as $key => $value) {
  281. $query = $this->dbConnection->getQueryBuilder();
  282. $query->delete($dbTable)
  283. ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
  284. ->andWhere($query->expr()->eq('key', $query->createNamedParameter($key)))
  285. ->execute();
  286. }
  287. $existingKeys = array_keys(array_intersect_key($metadata, $cachedMetadata));
  288. foreach ($existingKeys as $existingKey) {
  289. if ($metadata[$existingKey] !== $cachedMetadata[$existingKey]) {
  290. $query = $this->dbConnection->getQueryBuilder();
  291. $query->update($dbTable)
  292. ->set('value', $query->createNamedParameter($metadata[$existingKey]))
  293. ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)))
  294. ->andWhere($query->expr()->eq('key', $query->createNamedParameter($existingKey)))
  295. ->execute();
  296. }
  297. }
  298. }
  299. /**
  300. * serialize array of group restrictions to store them in database
  301. *
  302. * @param array $groups
  303. * @return string
  304. */
  305. private function serializeGroupRestrictions(array $groups):string {
  306. return \json_encode($groups);
  307. }
  308. /**
  309. * Gets all metadata of a backend
  310. *
  311. * @param IResource|IRoom $resource
  312. * @return array
  313. */
  314. private function getAllMetadataOfBackend($resource):array {
  315. if (!($resource instanceof IMetadataProvider)) {
  316. return [];
  317. }
  318. $keys = $resource->getAllAvailableMetadataKeys();
  319. $metadata = [];
  320. foreach ($keys as $key) {
  321. $metadata[$key] = $resource->getMetadataForKey($key);
  322. }
  323. return $metadata;
  324. }
  325. /**
  326. * @param string $table
  327. * @param string $foreignKey
  328. * @param int $id
  329. * @return array
  330. */
  331. private function getAllMetadataOfCache(string $table,
  332. string $foreignKey,
  333. int $id):array {
  334. $query = $this->dbConnection->getQueryBuilder();
  335. $query->select(['key', 'value'])
  336. ->from($table)
  337. ->where($query->expr()->eq($foreignKey, $query->createNamedParameter($id)));
  338. $stmt = $query->execute();
  339. $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
  340. $metadata = [];
  341. foreach ($rows as $row) {
  342. $metadata[$row['key']] = $row['value'];
  343. }
  344. return $metadata;
  345. }
  346. /**
  347. * Gets all cached rooms / resources by backend
  348. *
  349. * @param $tableName
  350. * @param $backendId
  351. * @return array
  352. */
  353. private function getAllCachedByBackend(string $tableName,
  354. string $backendId):array {
  355. $query = $this->dbConnection->getQueryBuilder();
  356. $query->select('resource_id')
  357. ->from($tableName)
  358. ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)));
  359. $stmt = $query->execute();
  360. return array_map(function ($row) {
  361. return $row['resource_id'];
  362. }, $stmt->fetchAll(\PDO::FETCH_NAMED));
  363. }
  364. /**
  365. * @param $principalPrefix
  366. * @param $principalUri
  367. */
  368. private function deleteCalendarDataForResource(string $principalPrefix,
  369. string $principalUri):void {
  370. $calendar = $this->calDavBackend->getCalendarByUri(
  371. implode('/', [$principalPrefix, $principalUri]),
  372. CalDavBackend::RESOURCE_BOOKING_CALENDAR_URI);
  373. if ($calendar !== null) {
  374. $this->calDavBackend->deleteCalendar($calendar['id']);
  375. }
  376. }
  377. /**
  378. * @param $table
  379. * @param $backendId
  380. * @param $resourceId
  381. * @return int
  382. */
  383. private function getIdForBackendAndResource(string $table,
  384. string $backendId,
  385. string $resourceId):int {
  386. $query = $this->dbConnection->getQueryBuilder();
  387. $query->select('id')
  388. ->from($table)
  389. ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
  390. ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
  391. $stmt = $query->execute();
  392. return $stmt->fetch(\PDO::FETCH_NAMED)['id'];
  393. }
  394. }