/
DbCacheService.php
382 lines (309 loc) · 9.04 KB
/
DbCacheService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<?php
namespace OCA\Cookbook\Service;
use OCA\Cookbook\Db\RecipeDb;
use OCP\Files\File;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\IConfig;
use OCA\Cookbook\Exception\InvalidJSONFileException;
class DbCacheService {
private $userId;
// var $root;
/**
* @var RecipeDb
*/
private $db;
/**
* @var RecipeService
*/
private $recipeService;
/**
* @var IConfig
*/
private $config;
private $jsonFiles;
private $dbReceipeFiles;
private $dbKeywords;
private $dbCategories;
private $newRecipes;
private $obsoleteRecipes;
private $updatedRecipes;
public function __construct(?string $UserId, RecipeDb $db, RecipeService $recipeService, IConfig $config) {
$this->userId = $UserId;
$this->db = $db;
$this->recipeService = $recipeService;
$this->config = $config;
}
public function updateCache() {
$this->jsonFiles = $this->parseJSONFiles();
$this->dbReceipeFiles = $this->fetchDbRecipeInformations();
$this->carryOutUpdate();
}
/**
* @param File $recipeFile
*/
public function addRecipe(File $recipeFile) {
try {
$json = $this->parseJSONFile($recipeFile);
} catch (InvalidJSONFileException $e) {
// XXX Put a log message and infor the user of problem.
return;
}
$id = $json['id'];
$this->jsonFiles = [$id => $json];
$this->dbReceipeFiles = [];
try {
$dbEntry = $this->fetchSingleRecipeDbInformations($id);
$this->dbReceipeFiles[$id] = $dbEntry;
} catch (DoesNotExistException $e) {
// No entry was found, keep the array empty
}
$this->carryOutUpdate();
}
private function carryOutUpdate() {
$this->resetFields();
$this->compareReceipeLists();
$this->applyDbReceipeChanges();
$this->fetchDbAssociatedInformations();
$this->updateCategories();
$this->updateKeywords();
}
private function resetFields() {
$this->newRecipes = [];
$this->obsoleteRecipes = [];
$this->updatedRecipes = [];
}
private function parseJSONFiles() {
$ret = [];
$jsonFiles = $this->recipeService->getRecipeFiles();
foreach ($jsonFiles as $jsonFile) {
try {
$json = $this->parseJSONFile($jsonFile);
} catch (InvalidJSONFileException $e) {
continue;
}
$id = $json['id'];
$ret[$id] = $json;
}
return $ret;
}
/**
* @param File $jsonFile
* @throws InvalidJSONFileException
* @return array
*/
private function parseJSONFile(File $jsonFile) : array {
// XXX Export of file reading into library/service?
$json = json_decode($jsonFile->getContent(), true);
if (!$json || !isset($json['name']) || $json['name'] === 'No name') {
$id = $jsonFile->getParent()->getId();
throw new InvalidJSONFileException("The JSON file in the folder with id $id does not have a valid name.");
}
$id = (int) $jsonFile->getParent()->getId();
$json['id'] = $id;
return $json;
}
private function fetchDbRecipeInformations() {
$dbResult = $this->db->findAllRecipes($this->userId);
$ret = [];
foreach ($dbResult as $row) {
// XXX Create an Entity from DB row better in DB file
$id = $row['recipe_id'];
$obj = [];
$obj['name'] = $row['name'];
$obj['id'] = $id;
$ret[$id] = $obj;
}
return $ret;
}
/**
*
* @param int $id
* @return array
* @throws DoesNotExistException
*/
private function fetchSingleRecipeDbInformations(int $id) {
return $this->db->findRecipeById($id);
}
private function fetchDbAssociatedInformations() {
$recipeIds = array_keys($this->jsonFiles);
$this->dbKeywords = [];
$this->dbCategories = [];
foreach ($recipeIds as $rid) {
// XXX Enhancement by selecting all keywords/categories and associating in RAM into data structure
$this->dbKeywords[$rid] = $this->db->getKeywordsOfRecipe($rid, $this->userId);
$category = $this->db->getCategoryOfRecipe($rid, $this->userId);
$this->dbCategories[$rid] = $category;
}
}
private function compareReceipeLists() {
foreach (array_keys($this->jsonFiles) as $id) {
if (array_key_exists($id, $this->dbReceipeFiles)) {
// The file was at least in the database
if (! $this->isDbEntryUpToDate($id)) {
// An update is needed
$this->updatedRecipes[] = $id;
}
// Remove from array for later removal of old recipes
unset($this->dbReceipeFiles[$id]);
} else {
// The file needs to be inserted in the database
$this->newRecipes[] = $id;
}
}
// Any remining recipe in dbFiles is to be removed
$this->obsoleteRecipes = array_keys($this->dbReceipeFiles);
}
// private function
private function isDbEntryUpToDate($id) {
$dbEntry = $this->dbReceipeFiles[$id];
$fileEntry = $this->jsonFiles[$id];
if ($dbEntry['name'] !== $fileEntry['name']) {
return false;
}
return true;
}
private function applyDbReceipeChanges() {
$this->db->deleteRecipes($this->obsoleteRecipes, $this->userId);
$newRecipes = array_map(
function ($id) {
return $this->jsonFiles[$id];
},
$this->newRecipes
);
$this->db->insertRecipes($newRecipes, $this->userId);
$updatedRecipes = array_map(
function ($id) {
return $this->jsonFiles[$id];
},
$this->updatedRecipes
);
$this->db->updateRecipes($updatedRecipes, $this->userId);
}
private function updateCategories() {
foreach ($this->jsonFiles as $rid => $json) {
if ($this->hasJSONCategory($json)) {
// There is a category in the JSON file present.
$category = trim($this->getJSONCategory($json));
if (isset($this->dbCategories[$rid])) {
// There is a category present. Update needed?
if ($this->dbCategories[$rid] !== trim($category)) {
$this->db->updateCategoryOfRecipe($rid, $category, $this->userId);
}
} else {
$this->db->addCategoryOfRecipe($rid, $category, $this->userId);
}
} else {
// There is no category in the JSON file present.
if (isset($this->dbCategories[$rid])) {
$this->db->removeCategoryOfRecipe($rid, $this->userId);
}
}
}
}
/**
* @param array $json
* @return boolean
*/
private function hasJSONCategory(array $json): bool {
return ! is_null($this->getJSONCategory($json));
}
/**
* Get the category of a recipe.
*
* This will only return the very first category if there are multiple registered.
*
* @param array $json The recipe
* @return string|null The category name of null if no category was found.
*/
private function getJSONCategory(array $json): ?string {
if (!isset($json['recipeCategory'])) {
return null;
}
$category = $json['recipeCategory'];
if (is_array($category)) {
if (count($category) > 0) {
$category = $category[0];
} else {
$category = null;
}
}
if (strlen(trim($category)) == 0) {
return null;
}
return $category;
}
private function updateKeywords() {
$newPairs = [];
$obsoletePairs = [];
foreach ($this->jsonFiles as $rid => $json) {
$textKeywords = $json['keywords'] ?? '';
if (is_array($textKeywords)) {
$keywords = $textKeywords;
} else {
$keywords = explode(',', $textKeywords);
}
$keywords = array_map(function ($v) {
return trim($v);
}, $keywords);
$keywords = array_filter($keywords, function ($v) {
return ! empty($v);
});
$dbKeywords = $this->dbKeywords[$rid];
$onlyInDb = array_filter($dbKeywords, function ($v) use ($keywords) {
return empty(array_keys($keywords, $v));
});
$onlyInJSON = array_filter($keywords, function ($v) use ($dbKeywords) {
return empty(array_keys($dbKeywords, $v));
});
$newPairs = array_merge($newPairs, array_map(function ($keyword) use ($rid) {
return [
'recipeId' => $rid,
'name' => $keyword
];
}, $onlyInJSON));
$obsoletePairs = array_merge($obsoletePairs, array_map(function ($keyword) use ($rid) {
return [
'recipeId' => $rid,
'name' => $keyword
];
}, $onlyInDb));
}
$this->db->addKeywordPairs($newPairs, $this->userId);
$this->db->removeKeywordPairs($obsoletePairs, $this->userId);
}
/**
* Gets the last time the search index was updated
*/
public function getSearchIndexLastUpdateTime() {
return (int) $this->config->getUserValue($this->userId, 'cookbook', 'last_index_update');
}
/**
* @return int
*/
public function getSearchIndexUpdateInterval(): int {
$interval = (int)$this->config->getUserValue($this->userId, 'cookbook', 'update_interval');
if ($interval < 1) {
$interval = 5;
}
return $interval;
}
public function triggerCheck() {
// TODO Locking
// XXX Catch Exceptions
$this->checkSearchIndexUpdate();
}
/**
* Checks if a search index update is needed and performs it
*/
private function checkSearchIndexUpdate() {
$last_index_update = $this->getSearchIndexLastUpdateTime();
$interval = $this->getSearchIndexUpdateInterval();
if ($last_index_update < 1 || time() > $last_index_update + ($interval * 60)) {
$this->updateCache();
// Cache the last index update
$this->config->setUserValue($this->userId, 'cookbook', 'last_index_update', time());
// TODO Make triggers more general, need refactoring of *all* Services
$this->recipeService->updateSearchIndex();
}
}
}