-
-
Notifications
You must be signed in to change notification settings - Fork 400
/
tag.js
410 lines (340 loc) · 11.5 KB
/
tag.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
/*
* Tag instance
*/
const fs = require('fs-extra');
const path = require('path');
const Model = require('./model.js');
const Tags = require('./tags.js');
const slug = require('./helpers/slug');
const ImageHelper = require('./helpers/image.helper.js');
const Themes = require('./themes.js');
const Utils = require('./helpers/utils.js');
class Tag extends Model {
constructor(appInstance, tagData, storeMode = true) {
super(appInstance, tagData);
this.id = parseInt(tagData.id, 10);
this.tagsData = new Tags(appInstance, tagData);
this.storeMode = storeMode;
if (tagData.additionalData) {
this.additionalData = tagData.additionalData;
}
if(tagData.name || tagData.name === '') {
this.name = (tagData.name).toString();
this.slug = tagData.slug;
this.description = tagData.description;
this.additionalData = tagData.additionalData;
this.prepareTagName();
}
}
/*
* Save tag
*/
save() {
if(this.name === '') {
return {
status: false,
message: 'tag-empty-name'
};
}
if(this.slug === '' || this.createSlug(this.slug) === '') {
this.slug = this.createSlug(this.name);
}
if(!this.isTagNameUnique()) {
return {
status: false,
message: 'tag-duplicate-name'
};
}
if(this.isTagRestrictedSlug()) {
return {
status: false,
message: 'tag-restricted-slug'
};
}
if(!this.isTagSlugUnique()) {
return {
status: false,
message: 'tag-duplicate-slug'
};
}
if(this.id !== 0) {
return this.updateTag();
}
this.checkAndCleanImages();
return this.addTag();
}
/*
* Add new tag
*/
addTag() {
let sqlQuery = this.db.prepare(`INSERT INTO tags VALUES(null, @name, @slug, @desc, @data)`);
sqlQuery.run({
name: this.name,
slug: this.createSlug(this.slug),
desc: this.description,
data: JSON.stringify(this.additionalData)
});
// Get the newly added item ID if necessary
if (this.id === 0) {
this.id = this.db.prepare('SELECT last_insert_rowid() AS id').get().id;
// Move images from the temp directory
let tempDirectoryExists = true;
let tempImagesDir = path.join(this.siteDir, 'input', 'media', 'tags', 'temp');
try {
fs.statSync(tempImagesDir).isDirectory();
} catch (err) {
tempDirectoryExists = false;
}
if (tempDirectoryExists) {
let finalImagesDir = path.join(this.siteDir, 'input', 'media', 'tags', (this.id).toString());
fs.copySync(tempImagesDir, finalImagesDir);
fs.removeSync(tempImagesDir);
}
}
return {
status: true,
message: 'tag-added',
tagID: this.id,
tags: this.tagsData.load()
};
}
/*
* Update existing tag
*/
updateTag() {
let sqlQuery = this.db.prepare(`UPDATE tags
SET
name = @name,
slug = @slug,
description = @desc,
additional_data = @data
WHERE
id = @id`);
sqlQuery.run({
name: this.name,
slug: this.createSlug(this.slug),
desc: this.description,
data: JSON.stringify(this.additionalData),
id: this.id
});
return {
status: true,
message: 'tag-updated',
tags: this.tagsData.load()
};
}
/*
* Prepare tag name to save
*/
prepareTagName() {
if(typeof this.name == 'undefined') {
this.name = '';
}
// Remove leading and ending spaces (trim it)
// it will also exclude case when tag name contains only
// whitespaces
this.name = this.name.replace(/^\s+/, '').replace(/\s+$/, '');
}
/*
* Check if the tag name is unique
*/
isTagNameUnique() {
let query = this.db.prepare('SELECT * FROM tags WHERE name LIKE @name AND id != @id');
let queryParams = {
name: this.escape(this.name),
id: this.id
};
for (const tag of query.iterate(queryParams)) {
if (tag.name === this.name) {
return false;
}
}
return true;
}
isTagSlugUnique() {
let query = this.db.prepare('SELECT slug FROM tags WHERE id != @id');
let queryParams = {
id: this.id
};
for (const tag of query.iterate(queryParams)) {
if (this.slug === tag.slug) {
return false;
}
}
return true;
}
/*
* Check if the tag slug is not restricted
*/
isTagRestrictedSlug() {
let slug = this.createSlug(this.slug);
if(this.application.sites[this.site].advanced.urls.tagsPrefix !== '') {
return false;
}
let restrictedSlugs = [
'assets',
this.application.sites[this.site].advanced.urls.authorsPrefix,
'media',
this.application.sites[this.site].advanced.urls.pageName
];
return restrictedSlugs.indexOf(slug) > -1;
}
/*
* Delete tag
*/
delete() {
let tagsSqlQuery = this.db.prepare(`DELETE FROM tags WHERE id = @id`);
let postTagsSqlQuery = this.db.prepare(`DELETE FROM posts_tags WHERE tag_id = @id`);
tagsSqlQuery.run({
id: this.id
});
postTagsSqlQuery.run({
id: this.id
});
ImageHelper.deleteImagesDirectory(this.siteDir, 'tags', this.id);
return {
status: true,
message: 'tag-deleted'
};
}
/*
* Create slug for given string
*/
createSlug(string) {
return slug(string);
}
/*
* Remove unused images
*/
checkAndCleanImages (cancelEvent = false) {
let tagDir = this.id;
if(this.id === 0) {
tagDir = 'temp';
}
let imagesDir = path.join(this.siteDir, 'input', 'media', 'tags', (tagDir).toString());
let tagDirectoryExists = true;
try {
fs.statSync(imagesDir).isDirectory();
} catch (err) {
tagDirectoryExists = false;
}
if(!tagDirectoryExists) {
return;
}
let images = fs.readdirSync(imagesDir);
this.cleanImages(images, imagesDir, cancelEvent);
}
/*
* Removes images from a given image dir
*/
cleanImages(images, imagesDir, cancelEvent) {
let tagDir = this.id;
let featuredImage = path.parse(this.additionalData.featuredImage).base;
// If post is cancelled - get the previous featured image
if (cancelEvent && this.id !== 0) {
let featuredImageSqlQuery = `SELECT additional_data FROM tags WHERE id = @id`;
let featuredImageResult = this.db.prepare(featuredImageSqlQuery).all({
id: this.id
});
if (featuredImageResult) {
try {
featuredImageResult = JSON.parse(featuredImageResult[0].additional_data).featuredImage;
} catch (e) {
console.log('(!) An issue occurred during parsing tag additional data', this.id);
}
}
}
if (this.id === 0) {
tagDir = 'temp';
}
// Iterate through images
for (let i in images) {
let imagePath = images[i];
let fullPath = path.join(imagesDir, imagePath);
// Skip dirs and symlinks
if (imagePath === '.' || imagePath === '..' || imagePath === 'responsive') {
continue;
}
if ((cancelEvent && tagDir === 'temp') || featuredImage !== imagePath) {
try {
fs.unlinkSync(fullPath);
} catch(e) {
console.error(e);
}
this.removeResponsiveImages(fullPath);
}
}
}
/*
* Remove unused responsive images
*/
removeResponsiveImages(originalPath) {
let themesHelper = new Themes(this.application, { site: this.site });
let currentTheme = themesHelper.currentTheme();
// If there is no selected theme
if (currentTheme === 'not selected') {
return;
}
// Load theme config
let themeConfig = Utils.loadThemeConfig(path.join(this.siteDir, 'input'), currentTheme);
// check if responsive images config exists
if(Utils.responsiveImagesConfigExists(themeConfig)) {
let dimensions = Utils.responsiveImagesDimensions(themeConfig, 'contentImages');
let featuredDimensions = Utils.responsiveImagesDimensions(themeConfig, 'tagImages');
if (featuredDimensions !== false) {
featuredDimensions.forEach(item => {
if (dimensions.indexOf(item) === -1) {
dimensions.push(item);
}
});
}
let responsiveImagesDir = path.parse(originalPath).dir;
responsiveImagesDir = path.join(responsiveImagesDir, 'responsive');
if (typeof dimensions === "boolean") {
return;
}
let forceWebp = !!this.application.sites[this.site]?.advanced?.forceWebp;
// Remove responsive images of each size
for(let dimensionName of dimensions) {
let filename = path.parse(originalPath).name;
let extension = path.parse(originalPath).ext;
if (forceWebp && ['.png', '.jpg', '.jpeg'].indexOf(extension.toLowerCase()) > -1) {
extension = '.webp';
}
let responsiveImagePath = path.join(responsiveImagesDir, filename + '-' + dimensionName + extension);
if(Utils.fileExists(responsiveImagePath)){
fs.unlinkSync(responsiveImagePath);
}
}
}
}
/*
* Change tag visibility status
*/
changeStatus(status, inverse = false) {
let selectQuery = this.db.prepare(`SELECT additional_data FROM tags WHERE id = @id`).all({ id: this.id });
let additionalData = selectQuery[0].additional_data;
try {
additionalData = JSON.parse(additionalData);
if (inverse) {
additionalData.isHidden = false;
} else {
additionalData.isHidden = true;
}
} catch (e) {
return false;
}
let updateQuery = this.db.prepare(`UPDATE
tags
SET
additional_data = @updatedData
WHERE
id = @id`);
updateQuery.run({
updatedData: JSON.stringify(additionalData),
id: this.id
});
return true;
}
}
module.exports = Tag;