forked from devbab/plex-ttp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plex.js
executable file
·520 lines (420 loc) · 15.1 KB
/
plex.js
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
let PLEXLIB = null;
//"C:/Users/chamaide/AppData/Local/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db";
const Database = require("better-sqlite3");
const fs = require("fs");
const path = require("path");
let TheTTPTags = null; // list des tags TTP existants
let ThePlaceTags = null; // list des tags Places existants
let db = null;
let triggerBeforeDelete = null;
let triggerAfterInsert = null;
function init() {
//console.log("plex.init");
// if not specified above, database should be there...
if (!PLEXLIB)
PLEXLIB = path.join("/srv/dev-disk-by-label-HDD/plex/", "Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db");
if (!fs.existsSync(PLEXLIB)) {
console.log(`${PLEXLIB} does not EXIST`);
process.exit(1);
}
console.log(`${PLEXLIB} is the folder`);
// open the database
db = new Database(PLEXLIB, {
// verbose: console.log,
fileMustExist: true
});
}
/**
* close connection to db
*/
function end() {
db.close();
//console.log("plex.end");
}
function storeTriggers() {
/*
SELECT sql FROM sqlite_master WHERE type='trigger' and name='fts4_tag_titles_before_delete_icu';
SELECT sql FROM sqlite_master WHERE type='trigger' and name='fts4_tag_titles_after_insert_icu';
*/
let sql = "SELECT sql FROM sqlite_master WHERE type='trigger' and name='fts4_tag_titles_before_delete_icu'";
let stmt = db.prepare(sql);
triggerBeforeDelete = stmt.get();
sql = "SELECT sql FROM sqlite_master WHERE type='trigger' and name='fts4_tag_titles_after_insert_icu'";
stmt = db.prepare(sql);
triggerAfterInsert = stmt.get();
console.log("Before Delete: ", triggerBeforeDelete.sql);
console.log("After Insert: ", triggerAfterInsert.sql);
}
function deleteTriggers() {
/*
drop trigger fts4_tag_titles_before_delete_icu;
drop trigger fts4_tag_titles_after_insert_icu;
*/
let sql = "DROP TRIGGER fts4_tag_titles_before_delete_icu";
let stmt = db.prepare(sql);
stmt.run();
sql = "DROP TRIGGER fts4_tag_titles_after_insert_icu";
stmt = db.prepare(sql);
stmt.run();
console.log("deleted triggers");
}
function createTriggers() {
/*
CREATE TRIGGER fts4_tag_titles_before_delete_icu BEFORE DELETE ON tags BEGIN DELETE FROM fts4_tag_titles_icu WHERE docid=old.rowid; END
CREATE TRIGGER fts4_tag_titles_after_insert_icu AFTER INSERT ON tags BEGIN INSERT INTO fts4_tag_titles_icu(docid, tag) VALUES(new.rowid, new.tag); END
*/
//console.log("Create: Before Delete: ", triggerBeforeDelete.sql);
//console.log("Create: After Insert: ", triggerAfterInsert.sql);
let sql = triggerBeforeDelete.sql; //"CREATE TRIGGER fts4_tag_titles_before_delete_icu BEFORE DELETE ON tags BEGIN DELETE FROM fts4_tag_titles_icu WHERE docid=old.rowid; END";
let stmt = db.prepare(sql);
stmt.run();
sql = triggerAfterInsert.sql; //"CREATE TRIGGER fts4_tag_titles_after_insert_icu AFTER INSERT ON tags BEGIN INSERT INTO fts4_tag_titles_icu(docid, tag) VALUES(new.rowid, new.tag); END";
stmt = db.prepare(sql);
stmt.run();
console.log("created triggers");
}
// add a column to table media_items, to store datetime of TTP update
// catch error if column alreadu exists
function addColumnTTPUpdate() {
let sql = "ALTER TABLE media_items ADD COLUMN \"TTP_updated_at\" datetime";
try {
let stmt = db.prepare(sql);
stmt.run();
} catch (err) {} // if already exist, no pb
}
// add a column to table media_items, to store datetime of Place update
// catch error if column alreadu exists
function addColumnPlaceUpdate() {
let sql = "ALTER TABLE media_items ADD COLUMN \"Place_updated_at\" datetime";
try {
let stmt = db.prepare(sql);
stmt.run();
} catch (err) {} // if already exist, no pb
}
/**
* look for photo library. used to find items in this library
* returns id(s) of photo library as comma separated string
*/
function getPhotoLibraryId() {
let sql = "SELECT id as id,name as name, scanner as scanner FROM library_sections WHERE scanner = ?";
let para = "Plex Photo Scanner";
let stmt = db.prepare(sql);
let rec = stmt.all(para);
if (rec.length == 0) // no photo library
return [];
return rec.map(elt => elt.id).join(",");
}
/**
* returns list of tags for a media_item_id
* @param {*} file
* @returns [{tid,tag}] taggings_id, tag
*/
function getTTPTags(mid) {
let sql = `SELECT A.id as tid,B.tag as tag FROM taggings as A, tags as B
WHERE A.tag_id = ?
AND A.tag_id = B.id
AND B.tag_type = 0
AND json_extract(B.extra_data, '$.ttp') = 'TTP'`;
let stmt = db.prepare(sql);
let recs = stmt.all(mid);
//console.log("taggins ", recs);
return recs;
}
/**
* returns list of tags for a media_item_id
* @param {} mid mid is metadata_item_id of taggings
* @returns [{tid,tag}] taggings_id, tag
*/
function getPlaceTags(mid) {
let sql = `SELECT A.id as tid,B.tag as tag,B.tag_value as tag_value FROM taggings as A, tags as B
WHERE A.metadata_item_id = ?
AND A.tag_id = B.id
AND B.tag_type = 400`;
let stmt = db.prepare(sql);
let recs = stmt.all(mid);
//console.log("taggins ", recs);
return recs;
}
/**
* remove all TTP tags for a specific mid
* mid is the metadata_item_id of an image
* @param {*} mid
*/
function deleteTTPTags(mid) {
console.log("id: ", mid);
let sql = `DELETE FROM taggings WHERE tag_id = ? `;
let stmt = db.prepare(sql);
stmt.run(mid);
sql = "DELETE FROM tags WHERE id = ? ";
stmt = db.prepare(sql);
stmt.run(mid);
}
/**
* remove all Places tags for a specific mid
* mid is the metadata_item_id of an image
* remove the tagging link as other images may reference same tag
* @param {*} mid
*/
function deletePlaceTags(mid) {
let tags = getPlaceTags(mid);
if (tags.length == 0) // no tags
return;
let ids = tags.map(tag => tag.tid).join(",");
//console.log("ids ", ids);
let sql = `DELETE FROM taggings WHERE id IN (${ids})`;
let stmt = db.prepare(sql);
stmt.run();
}
// delete all tags related to a place
// tag with tag_type = 400
// and taggings related to them
function deleteAllPlaceTags() {
let sql = `DELETE FROM taggings WHERE tag_id in
(select id from tags WHERE tag_type = 400) `;
let stmt = db.prepare(sql);
stmt.run();
sql = "DELETE FROM tags WHERE tag_type = 400 ";
stmt = db.prepare(sql);
stmt.run();
}
/**
* remove all TTP Tags not referenced with taggings table
*/
function cleanLoneTTPTags() {
// search tags not referenced
let sql = `DELETE FROM tags
WHERE tag_type = 0
AND json_extract(extra_data, '$.ttp') = 'TTP'
AND id NOT IN (select tag_id from taggings WHERE "index" = 0)`;
let stmt = db.prepare(sql);
stmt.run();
}
/**
* remove all Place Tags not referenced with taggings table
*/
function cleanLonePlaceTags() {
// search tags not referenced
let sql = `DELETE FROM tags
WHERE tag_type = 400
AND id NOT IN (select tag_id from taggings WHERE "index" IN (0,1,2,3,4) )`;
let stmt = db.prepare(sql);
stmt.run();
}
/**
* returns list of TTP tags already created
* so as not to check each and every time
* @return array of {id,tag} where id is from table tags
*/
function scanTTPTags() {
if (TheTTPTags)
return;
// search if tag exists in tags table
let sql = `SELECT id,tag FROM tags
WHERE tag_type = 0
AND json_extract(extra_data, '$.ttp') = 'TTP'`;
let stmt = db.prepare(sql);
TheTTPTags = stmt.all();
}
/**
* returns list of TTP tags already created
* so as not to check each and every time
* tag_valye : 10:country 20:region 30:city 40: 50: road
* @return array of {id,tag,tag_value} where id is from table tags
*/
function scanPlacesTags() {
if (ThePlaceTags)
return;
// search if tag exists in tags table
let sql = `SELECT id,tag,tag_value FROM tags
WHERE tag_type = 400`;
let stmt = db.prepare(sql);
ThePlaceTags = stmt.all();
return ThePlaceTags;
}
/**
* add tags to an image referenced by mid
* assuming the tag is not already associated
* uses global variable TheTTPTags to check if tag exists, and modifies it when a tag is created
* mid is metadata_item_id of image
* @param {*} mid
* @param {*} tags
*/
function addTTPTags(mid, tags) {
console.log("add tags for meta_item_id ", mid, tags);
for (let i = 0; i < tags.length; i++) {
let tag = tags[i];
let tid = null;
console.log (`Finding`);
let found = TheTTPTags.find(elt => elt.tag == tag);
if (found) {
console.log (`${tag} already exists`,found);
tid = found.id;
} else {
console.log (`Not exists`);
// if not exists
const sql = "INSERT INTO tags (tag, tag_type,extra_data) VALUES (?, 0,'{\"ttp\":\"TTP\",\"url\":\"\"}')";
console.log (`Preparing`);
const stmt = db.prepare(sql);
console.log (`Running`);
const info = stmt.run(tag);
console.log (`info`);
tid = info.lastInsertRowid;
TheTTPTags.push({
id: tid,
tag: tag
}); // add a new entry in TheTTPTags
console.log("created ",tag, " as ",tid)
}
console.log("tag created ", tid);
let sql = "INSERT INTO taggings (metadata_item_id, tag_id, \"index\") VALUES (?, ?, '0')";
let stmt = db.prepare(sql);
stmt.run(mid, tid);
//const rid = info.lastInsertRowid;
console.log("tagging created ", tid);
}
// update field TTP_updated_at
const nowIso = new Date().toISOString();
const sql = `UPDATE media_items SET TTP_updated_at = '${nowIso}' WHERE metadata_item_id = ${mid}`;
const stmt = db.prepare(sql);
stmt.run();
}
/**
* add tags to an image referenced by mid
* assuming the tag is not already associated
* uses global variable ThePlaceTags to check if tag exists, and modifies it when a tag is created
* mid is metadata_item_id of image
* 10:country 20:region 30:city 40: 50: road
* @param {*} mid
* @param {object} {city,county,district,country}
*/
function addPlaceTags(mid, addr) {
//console.log("addPlaceTags for meta_item_id ", mid, places);
let places = { ...addr };
const fields = [
{
name: "district", // arrondissement, quartier
taggings: 1,
tags: 40
},{
name: "city",
taggings: 3,
tags: 30
},
{
name: "county", //department
taggings: 2,
tags: 20
},
{
name: "country",
taggings: 0,
tags: 10
}
];
if (places.county == places.city)
places.county = "";
// add city name to district to make it simpler to read
if (places.district && places.city)
places.district +=", "+ places.city;
// if (places.country == "France")
// console.log("place ", places);
for (let i = 0; i < fields.length; i++) {
let field = fields[i];
let name = places[field.name];
if (!name || name == "")
continue;
let tid = null;
let found = ThePlaceTags.find(elt => {
return (elt.tag == name && elt.tag_value == field.tags);
});
if (found) {
tid = found.id;
} else {
// if not exists
// eslint-disable-next-line no-console
console.log("====> Adding new place ", name, field.tags);
const sql = "INSERT INTO tags (tag, tag_type,tag_value, extra_data) VALUES (?, 400,?,'{\"ttp\":\"PLACE\"}')";
const stmt = db.prepare(sql);
const info = stmt.run(name, field.tags);
tid = info.lastInsertRowid;
ThePlaceTags.push({
id: tid,
tag: name,
tag_value: field.tags
});
}
//console.log("tag created ", rid);
let sql = "INSERT INTO taggings (metadata_item_id, tag_id, \"index\") VALUES (?, ?, ?)";
//console.log("taggings sql ",sql)
let stmt = db.prepare(sql);
stmt.run(mid, tid, field.taggings);
//const rid = info.lastInsertRowid;
//console.log("tagging created ", rid);
}
// update field Place_updated_at
const nowIso = new Date().toISOString();
const sql = `UPDATE media_items SET Place_updated_at = '${nowIso}' WHERE metadata_item_id = ${mid}`;
const stmt = db.prepare(sql);
stmt.run();
}
// met le timestamp de l'image à la date de l'instant
function updatePlaceImageTimestamp(mid) {
// update field Place_updated_at
const nowIso = new Date().toISOString();
const sql = `UPDATE media_items SET Place_updated_at = '${nowIso}' WHERE metadata_item_id = ${mid}`;
const stmt = db.prepare(sql);
stmt.run();
}
// scan all media form library Photo
/**
*
* @param {*} max max files to return
* returns {file,mid,uat} filename, media_item_id, updated_time as date
*/
function scanPhotos(max = 0) {
let ids = getPhotoLibraryId();
if (!ids)
return [];
let sql = `SELECT B.metadata_item_id as mid,A.file as file,
B.TTP_updated_at as FaceUpdateTime, B.Place_updated_at as PlaceUpdateTime
FROM media_parts as A, media_items as B
WHERE A.media_item_id = B.id AND B.library_section_id in (${ids})
AND B.container = 'jpeg' `;
if (max != 0) sql += ` LIMIT ${max}`;
let stmt = db.prepare(sql);
let req = stmt.all();
return req;
}
// list tags matching a regex
function listTag(tag) {
scanTTPTags();
if (tag == "")
return TheTTPTags;
//console.log("TTP tags ", TheTTPTags);
const regex = new RegExp(tag);
const res = TheTTPTags.filter(elt => elt.tag.match(regex));
//console.log(res);
return res;
}
module.exports = {
init: init,
end: end,
listTag: listTag,
scanPhotos: scanPhotos,
deleteTriggers: deleteTriggers,
createTriggers: createTriggers,
storeTriggers: storeTriggers,
addColumnTTPUpdate: addColumnTTPUpdate,
cleanLoneTTPTags: cleanLoneTTPTags,
addTTPTags: addTTPTags,
deleteTTPTags: deleteTTPTags,
scanTTPTags: scanTTPTags,
addColumnPlaceUpdate: addColumnPlaceUpdate,
scanPlacesTags: scanPlacesTags,
cleanLonePlaceTags: cleanLonePlaceTags,
getPlaceTags: getPlaceTags,
deletePlaceTags: deletePlaceTags,
deleteAllPlaceTags: deleteAllPlaceTags,
addPlaceTags: addPlaceTags,
updatePlaceImageTimestamp: updatePlaceImageTimestamp
};