forked from bpatrik/pigallery2-sample-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
362 lines (362 loc) · 15.1 KB
/
server.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
"use strict";
/* eslint-disable @typescript-eslint/no-inferrable-types */
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanUp = exports.init = exports.DigikamGasketConfig = exports.Image = exports.Album = void 0;
const tslib_1 = require("tslib");
const Config_1 = require("./node_modules/pigallery2-extension-kit/lib/common/config/private/Config");
const PrivateConfig_1 = require("./node_modules/pigallery2-extension-kit/lib/common/config/private/PrivateConfig");
// Importing packages that are available in the main app (listed in the packages.json in pigallery2)
const typeorm_1 = require("typeorm");
const SubConfigClass_1 = require("typeconfig/src/decorators/class/SubConfigClass");
const ConfigPropoerty_1 = require("typeconfig/src/decorators/property/ConfigPropoerty");
const path = require("path");
const util = require("util");
const forcedDebug = process.env.NODE_ENV === 'debug';
const extensionLog = (() => {
let realLog = null;
return {
setup: (extension) => {
if (realLog == null) {
realLog = extension.Logger;
}
},
silly: (func) => {
if (!forcedDebug && Config_1.Config.Server.Log.level < PrivateConfig_1.LogLevel.silly) {
return;
}
realLog.silly(func());
},
debug: (func) => {
if (!forcedDebug && Config_1.Config.Server.Log.level < PrivateConfig_1.LogLevel.debug) {
return;
}
realLog.debug(func());
},
verbose: (func) => {
if (!forcedDebug && Config_1.Config.Server.Log.level < PrivateConfig_1.LogLevel.verbose) {
return;
}
realLog.verbose(func());
},
info: (func) => {
if (!forcedDebug && Config_1.Config.Server.Log.level < PrivateConfig_1.LogLevel.info) {
return;
}
realLog.info(func());
},
warn: (func) => {
if (!forcedDebug && Config_1.Config.Server.Log.level < PrivateConfig_1.LogLevel.warn) {
return;
}
realLog.warn(func());
},
error: (func) => {
if (!forcedDebug && Config_1.Config.Server.Log.level < PrivateConfig_1.LogLevel.error) {
return;
}
realLog.error(func());
}
};
})();
// https://github.com/typeorm/typeorm/blob/master/docs/entities.md#what-is-entity
let Album = class Album {
};
tslib_1.__decorate([
(0, typeorm_1.PrimaryGeneratedColumn)(),
tslib_1.__metadata("design:type", Number)
], Album.prototype, "id", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", Number)
], Album.prototype, "albumRoot", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", String)
], Album.prototype, "relativePath", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", Date)
], Album.prototype, "date", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", String)
], Album.prototype, "caption", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", String)
], Album.prototype, "collection", void 0);
tslib_1.__decorate([
(0, typeorm_1.ManyToOne)(type => Image),
(0, typeorm_1.JoinColumn)({ name: 'icon' }),
tslib_1.__metadata("design:type", Object)
], Album.prototype, "icon", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", Date)
], Album.prototype, "modificationDate", void 0);
tslib_1.__decorate([
(0, typeorm_1.OneToMany)(() => Image, (image) => image.album),
tslib_1.__metadata("design:type", Array)
], Album.prototype, "images", void 0);
Album = tslib_1.__decorate([
(0, typeorm_1.Entity)('Albums')
], Album);
exports.Album = Album;
let Image = class Image {
};
tslib_1.__decorate([
(0, typeorm_1.PrimaryGeneratedColumn)(),
tslib_1.__metadata("design:type", Number)
], Image.prototype, "id", void 0);
tslib_1.__decorate([
(0, typeorm_1.ManyToOne)(() => Album, (album) => album.images),
(0, typeorm_1.JoinColumn)({ name: 'album' }),
tslib_1.__metadata("design:type", Album)
], Image.prototype, "album", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", String)
], Image.prototype, "name", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", Number)
], Image.prototype, "status", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", Number)
], Image.prototype, "category", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", Date)
], Image.prototype, "modificationDate", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", Number)
], Image.prototype, "fileSize", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", String)
], Image.prototype, "uniqueHash", void 0);
tslib_1.__decorate([
(0, typeorm_1.Column)(),
tslib_1.__metadata("design:type", Number)
], Image.prototype, "manualOrder", void 0);
Image = tslib_1.__decorate([
(0, typeorm_1.Entity)('Images')
], Image);
exports.Image = Image;
// Using https://github.com/bpatrik/typeconfig for configuration
let DigikamGasketConfig = class DigikamGasketConfig {
constructor() {
this.digikamShowCollection = 'Public';
this.digikamDbType = 'MySQL';
this.digikamSqliteDb = '/app/data/digikam/digikam.db';
this.digikamMysqlHost = 'localhost';
this.digikamMysqlPort = 3306;
this.digikamMysqlDb = 'digikam';
this.digikamMysqlUser = 'digikam';
this.digikamMysqlPassword = 'password';
}
};
tslib_1.__decorate([
(0, ConfigPropoerty_1.ConfigProperty)({ description: 'DigiKam Directory Category' }),
tslib_1.__metadata("design:type", String)
], DigikamGasketConfig.prototype, "digikamShowCollection", void 0);
tslib_1.__decorate([
(0, ConfigPropoerty_1.ConfigProperty)({ description: 'DigiKam Database Type (MySQL or SQLite)' }),
tslib_1.__metadata("design:type", String)
], DigikamGasketConfig.prototype, "digikamDbType", void 0);
tslib_1.__decorate([
(0, ConfigPropoerty_1.ConfigProperty)({ description: 'DigiKam SQLite DB filename' }),
tslib_1.__metadata("design:type", String)
], DigikamGasketConfig.prototype, "digikamSqliteDb", void 0);
tslib_1.__decorate([
(0, ConfigPropoerty_1.ConfigProperty)({ description: 'DigiKam MySQL DB hostname' }),
tslib_1.__metadata("design:type", String)
], DigikamGasketConfig.prototype, "digikamMysqlHost", void 0);
tslib_1.__decorate([
(0, ConfigPropoerty_1.ConfigProperty)({ description: 'DigiKam MySQL DB port' }),
tslib_1.__metadata("design:type", Number)
], DigikamGasketConfig.prototype, "digikamMysqlPort", void 0);
tslib_1.__decorate([
(0, ConfigPropoerty_1.ConfigProperty)({ description: 'DigiKam MySQL DB name' }),
tslib_1.__metadata("design:type", String)
], DigikamGasketConfig.prototype, "digikamMysqlDb", void 0);
tslib_1.__decorate([
(0, ConfigPropoerty_1.ConfigProperty)({ description: 'DigiKam MySQL DB username' }),
tslib_1.__metadata("design:type", String)
], DigikamGasketConfig.prototype, "digikamMysqlUser", void 0);
tslib_1.__decorate([
(0, ConfigPropoerty_1.ConfigProperty)({ description: 'DigiKam MySQL DB password' }),
tslib_1.__metadata("design:type", String)
], DigikamGasketConfig.prototype, "digikamMysqlPassword", void 0);
DigikamGasketConfig = tslib_1.__decorate([
(0, SubConfigClass_1.SubConfigClass)({ softReadonly: true })
], DigikamGasketConfig);
exports.DigikamGasketConfig = DigikamGasketConfig;
/**
* Set up DigiKam DB connection
*/
const digikamDB = (() => {
let instance = null;
const createInstance = async (extension) => {
const commonOpts = {
entities: [Album, Image],
logging: (forcedDebug || Config_1.Config.Server.Log.level >= PrivateConfig_1.LogLevel.debug)
};
const dbOpts = (() => {
switch (extension.config.getConfig().digikamDbType) {
case 'MySQL': return {
type: 'mysql',
host: extension.config.getConfig().digikamMysqlHost,
port: extension.config.getConfig().digikamMysqlPort,
database: extension.config.getConfig().digikamMysqlDb,
username: extension.config.getConfig().digikamMysqlUser,
password: extension.config.getConfig().digikamMysqlPassword
};
case 'SQLite': return {
type: 'better-sqlite3',
database: extension.config.getConfig().digikamSqliteDb
};
// FIXME: error out otherwise
}
})();
const fullOpts = { ...commonOpts, ...dbOpts };
const DigikamDataSource = new typeorm_1.DataSource(fullOpts);
try {
await DigikamDataSource.initialize();
extensionLog.verbose(() => 'DigiKam Connector has successfully connected to the DigiKam DB');
}
catch (err) {
extensionLog.error(() => `DigiKam Connector encountered an error when connecting to the DigiKam DB: ${err}`);
}
return DigikamDataSource;
};
return {
getDataSource: async (extension) => {
if (instance == null) {
instance = await createInstance(extension);
}
return instance;
},
cleanUp: async () => {
if (instance != null) {
await instance.destroy();
instance = null;
}
}
};
})();
const init = async (extension) => {
extensionLog.setup(extension);
extensionLog.info(() => `My extension is setting up. name: ${extension.extensionName}, id: ${extension.extensionId}`);
/**
* (Optional) Setting the configuration template
*/
extension.config.setTemplate(DigikamGasketConfig);
/**
* Only index directories tagged with the right collection
*/
const baseQuery = async () => {
const ds = await digikamDB.getDataSource(extension);
const query = ds.getRepository(Album)
.createQueryBuilder('album')
.where('album.collection = :collection', { collection: extension.config.getConfig().digikamShowCollection });
return query;
};
const indexDir = async (dir) => {
extensionLog.silly(() => `indexDir:${dir}`);
// https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#adding-where-expression
const q = await baseQuery();
const count = await q
.andWhere(new typeorm_1.Brackets((qb) => {
qb.where('album.relativePath = :dir', { dir })
.orWhere('album.relativePath LIKE :path', { path: `${dir}/%` });
}))
.getCount();
extensionLog.silly(() => `public album count:${count}`);
return count > 0;
};
const showDirPics = async (dir) => {
extensionLog.silly(() => `showDirPics:${dir}`);
// https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#adding-where-expression
const q = await baseQuery();
const count = await q
.andWhere('album.relativePath = :dir', { dir })
.getCount();
extensionLog.silly(() => `public album count:${count}`);
return count > 0;
};
// https://advancedweb.hu/how-to-use-async-functions-with-array-filter-in-javascript/
const asyncFilter = async (arr, predicate) => {
const results = await Promise.all(arr.map(predicate));
return arr.filter((_v, index) => results[index]);
};
extension.events.gallery.DiskManager
.scanDirectory.after(async (data) => {
extensionLog.debug(() => `scanDirectory.after: output = ${util.inspect(data.output)}`);
// FIXME: this would be better accomplished by having an extension hook into DiskManager.excludeDir, but this works.
// https://www.aleksandrhovhannisyan.com/blog/async-functions-that-return-booleans/
const dirs = await asyncFilter(data.output.directories, async (dir) => { const val = await indexDir(path.join(path.sep, dir.path, dir.name)); return val; });
data.output.directories = dirs;
// Also, don't show any photos in this directory if it's not the right collection
const showPics = await showDirPics(path.join(path.sep, data.output.path, data.output.name));
if (!showPics) {
extensionLog.silly(() => 'Do not show pics in this directory!');
data.output.media = [];
}
extensionLog.debug(() => `scanDirectory.after: altered output = ${util.inspect(data.output)}`);
return data.output;
});
/**
* Select covers specified in DigiKam (if present)
* */
extension.events.gallery.CoverManager
.getCoverForDirectory.before(async (input, event) => {
extensionLog.debug(() => `getCoverForDirectory.before: input = ${util.inspect(input)}`);
const inputQuery = input[0];
const albumPath = (inputQuery.path === './')
? path.join(path.sep, inputQuery.name)
: path.join(path.sep, inputQuery.path, inputQuery.name);
const ds = await digikamDB.getDataSource(extension);
const albumInfo = await ds.getRepository(Album)
.createQueryBuilder('album')
.leftJoinAndSelect('album.icon', 'icon')
.leftJoinAndSelect('icon.album', 'iconalbum')
.where('album.relativepath = :path', { path: albumPath })
.limit(1)
.getOne();
extensionLog.debug(() => `getCoverForDirectory.before: albumInfo = ${util.inspect(albumInfo)}`);
if (albumInfo.icon == null) {
return input;
}
const conn = await extension.db.getSQLConnection();
const mediaEntity = extension.db._getAllTables().find((entity) => entity.name === 'MediaEntity');
const coverMedia = await conn
.getRepository(mediaEntity)
.createQueryBuilder('media')
.innerJoin('media.directory', 'directory')
.select(['media.name', 'media.id', 'directory.name', 'directory.path'])
.where('media.name = :mediaName', { mediaName: albumInfo.icon.name })
.andWhere('directory.name = :dirName', { dirName: path.basename(albumInfo.icon.album.relativePath) })
.andWhere('directory.path = :dirPath', { dirPath: path.join(path.relative('/', path.dirname(albumInfo.icon.album.relativePath)), path.sep) })
.limit(1)
.getOne();
extensionLog.debug(() => `getCoverForDirectory.before: coverMedia = ${util.inspect(coverMedia)}`);
if (coverMedia != null) {
event.stopPropagation = true;
return coverMedia;
}
return input;
});
};
exports.init = init;
const cleanUp = async (extension) => {
extension.Logger.debug('Cleaning up');
await digikamDB.cleanUp();
/*
* No need to clean up changed through extension.db, extension.RESTApi or extension.events
* */
};
exports.cleanUp = cleanUp;
//# sourceMappingURL=server.js.map