@opengis/cms 0.0.26 → 0.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +98 -98
  2. package/dist/index-W-qQIppj-DunG40EG.js +2452 -0
  3. package/dist/index.html +28 -28
  4. package/dist/index.js +12683 -6702
  5. package/dist/index.umd.cjs +87 -41
  6. package/dist/style.css +1 -0
  7. package/package.json +68 -68
  8. package/plugin.js +76 -76
  9. package/server/app.js +35 -35
  10. package/server/config.js +4 -4
  11. package/server/functions/getDraftKey.js +22 -22
  12. package/server/index.js +22 -22
  13. package/server/migrations/fixes.sql +123 -123
  14. package/server/migrations/site.sql +545 -545
  15. package/server/plugins/adminHook.js +78 -78
  16. package/server/plugins/hook.js +59 -59
  17. package/server/plugins/vite.js +84 -84
  18. package/server/routes/category/controllers/cms.category.delete.js +21 -21
  19. package/server/routes/category/controllers/cms.category.get.js +17 -17
  20. package/server/routes/category/controllers/cms.category.list.js +16 -16
  21. package/server/routes/category/controllers/cms.category.post.js +21 -21
  22. package/server/routes/category/controllers/cms.category.put.js +23 -23
  23. package/server/routes/category/index.mjs +22 -22
  24. package/server/routes/cms/controllers/cmsStat.js +55 -55
  25. package/server/routes/cms/controllers/cmsSuggest.js +57 -57
  26. package/server/routes/cms/controllers/deleteContent.js +114 -114
  27. package/server/routes/cms/controllers/deleteMedia.js +75 -75
  28. package/server/routes/cms/controllers/downloadMedia.js +48 -48
  29. package/server/routes/cms/controllers/getContent.js +110 -110
  30. package/server/routes/cms/controllers/getContentBySlug.js +95 -95
  31. package/server/routes/cms/controllers/getPermissions.js +15 -15
  32. package/server/routes/cms/controllers/insertContent.js +218 -218
  33. package/server/routes/cms/controllers/listMedia.js +93 -93
  34. package/server/routes/cms/controllers/metadataMedia.js +38 -38
  35. package/server/routes/cms/controllers/properties.get.js +53 -53
  36. package/server/routes/cms/controllers/properties.post.js +99 -99
  37. package/server/routes/cms/controllers/searchContent.js +205 -205
  38. package/server/routes/cms/controllers/setPermissions.js +49 -49
  39. package/server/routes/cms/controllers/translate.js +89 -89
  40. package/server/routes/cms/controllers/updateContent.js +238 -238
  41. package/server/routes/cms/controllers/uploadMedia.js +78 -78
  42. package/server/routes/cms/index.mjs +114 -114
  43. package/server/routes/cms/utils/additionalData.js +35 -35
  44. package/server/routes/cms/utils/getCollection.js +81 -81
  45. package/server/routes/cms/utils/getSingle.js +187 -187
  46. package/server/routes/cms/utils/insertContentLocalization.js +86 -86
  47. package/server/routes/cms/utils/requestTranslation.js +85 -85
  48. package/server/routes/cms/utils/updateLocalization.js +47 -47
  49. package/server/routes/cmsSpace/controllers/deleteSpace.js +25 -25
  50. package/server/routes/cmsSpace/controllers/getSpaces.js +27 -27
  51. package/server/routes/cmsSpace/controllers/insertSpace.js +21 -21
  52. package/server/routes/cmsSpace/controllers/updateSpace.js +23 -23
  53. package/server/routes/cmsSpace/index.mjs +20 -20
  54. package/server/routes/contentType/controllers/addContentType.js +162 -162
  55. package/server/routes/contentType/controllers/contentTypeList.js +54 -54
  56. package/server/routes/contentType/controllers/delContentType.js +75 -75
  57. package/server/routes/contentType/controllers/editContentType.js +61 -61
  58. package/server/routes/contentType/controllers/getContentType.js +37 -37
  59. package/server/routes/contentType/index.mjs +35 -35
  60. package/server/routes/contentType/utils/updateContents.js +28 -28
  61. package/server/routes/contentType/utils/updateCustomContentTable.js +55 -55
  62. package/server/routes/feedback/controllers/email.list.js +24 -24
  63. package/server/routes/feedback/controllers/feedback.js +48 -48
  64. package/server/routes/feedback/controllers/feedback.list.js +37 -37
  65. package/server/routes/feedback/controllers/news.subscriptions.js +44 -44
  66. package/server/routes/feedback/index.mjs +71 -71
  67. package/server/routes/logs/controllers/export.user.logs.js +77 -77
  68. package/server/routes/logs/controllers/user.logs.js +44 -44
  69. package/server/routes/logs/index.mjs +9 -9
  70. package/server/routes/menu/controllers/addMenu.js +37 -37
  71. package/server/routes/menu/controllers/delMenu.js +31 -31
  72. package/server/routes/menu/controllers/editMenu.js +41 -41
  73. package/server/routes/menu/controllers/getMenu.js +42 -42
  74. package/server/routes/menu/index.mjs +13 -13
  75. package/server/routes/migration/controllers/collectionToCustom.js +137 -137
  76. package/server/routes/migration/index.mjs +8 -8
  77. package/server/routes/root.mjs +8 -8
  78. package/server/routes/tags/controllers/add.tags.js +24 -24
  79. package/server/routes/tags/controllers/del.tags.js +19 -19
  80. package/server/routes/tags/controllers/edit.tags.js +25 -25
  81. package/server/routes/tags/controllers/get.tags.js +15 -15
  82. package/server/routes/tags/index.mjs +14 -14
  83. package/server/templates/cls/cms.category_type.json +9 -9
  84. package/server/templates/cls/cms.content_review_status.json +9 -9
  85. package/server/templates/cls/cms.content_status.json +9 -9
  86. package/server/templates/cls/cms.content_type.json +9 -9
  87. package/server/templates/cls/cms.lang.json +9 -9
  88. package/server/templates/page/login.html +126 -126
  89. package/server/templates/select/core.user_mentioned.sql +1 -1
  90. package/dist/index-W-qQIppj-DRzFSjU1.js +0 -2452
@@ -1,219 +1,219 @@
1
- import { config, checkSQL, getTemplate, pgClients, dataInsert, logger } from '@opengis/fastify-table/utils.js';
2
- import { existsSync, readFileSync } from 'node:fs';
3
-
4
- const inputTypes = existsSync('input-types.json') ? JSON.parse(readFileSync('input-types.json') || '{}') : {};
5
-
6
- import updateLocalization from '../utils/updateLocalization.js';
7
-
8
- const defaultColumns = [
9
- 'content_id',
10
- 'space_id',
11
- 'content_type_id',
12
- 'created_at',
13
- 'updated_at',
14
- 'published_at',
15
- 'revision',
16
- 'locale',
17
- 'status',
18
- 'slug',
19
- 'title',
20
- 'created_by',
21
- 'published_by',
22
- 'updated_by',
23
- 'meta',
24
- ];
25
-
26
- export default async function insertContent(req, reply) {
27
- const {
28
- pg = pgClients.client,
29
- params = {},
30
- user = {},
31
- body = {},
32
- headers = {},
33
- } = req;
34
-
35
- const { type, id = body?.id } = params;
36
-
37
- if (!type) {
38
- return reply.status(400).send('not enough params: type');
39
- }
40
-
41
- const arr = config.pg ? await pg.query(`select array_agg(relname)::text[] from pg_class a
42
- left join pg_namespace b on a.relnamespace=b.oid
43
- where a.relam=2 and b.nspname='data'`).then(el => el.rows?.[0]?.array_agg || []) : [];
44
-
45
- if (!arr.length) {
46
- return reply.status(400).send('empty schema: data');
47
- }
48
-
49
- const table = arr.find(el => el === params.type);
50
-
51
- const { content_id: contentId, type: contentType } = await pg.query(
52
- 'select content_id, (select type from site.content_types where content_type_id=t.content_type_id) from site.contents t where slug=$1',
53
- [['single', 'pages'].includes(type) ? id : type],
54
- ).then(el => el.rows?.[0] || {});
55
-
56
- const ctypeId = contentId && contentId !== 'pages' && contentType === 'single' ? await pg.query(
57
- 'select content_type_id from site.contents where content_id=$1',
58
- [contentId],
59
- ).then(el => el.rows?.[0]?.content_type_id) : null;
60
-
61
- const { ctid, dbtable, columns: contentColumns } = await pg.query(
62
- 'select content_type_id as ctid, table_name as dbtable, columns from site.content_types where $1 in (content_type_id, name)',
63
- [type === 'single' && id ? id : (ctypeId || type)],
64
- ).then(el => el.rows?.[0] || {});
65
-
66
- const loadTable = (ctypeId || type) === 'pages' ? await getTemplate('table', 'single.default.table') : {};
67
-
68
- const columns = (ctypeId || type) === 'pages'
69
- ? (loadTable?.columns || []).concat(contentColumns.filter(col => loadTable?.columns.findIndex(el => el.name === col.name) === -1))
70
- : contentColumns;
71
-
72
- // site.content_data, includes singletone
73
- if (((!table && !dbtable) || type === 'pages')) {
74
- const cid = await pg.query(
75
- 'select content_id from site.contents where content_type_id=$1 limit 1',
76
- [ctid || 'pages'],
77
- ).then(el => el.rows?.[0]?.content_id);
78
-
79
- const ctid1 = body.content_type_id || ctid || 'pages';
80
-
81
- if (!cid) {
82
- return reply.status(404).send('contents not found');
83
- }
84
-
85
- const columnList = columns?.map?.(el => el.name) || [];
86
- const types = columns?.reduce?.((acc, curr) => ({ ...acc, [curr.name]: curr.type || 'text' }), {}) || {};
87
- const keys = Object.keys(body || {}).filter(key => columnList.includes(key) && !defaultColumns.includes(key));
88
-
89
- if (!Object.keys(body || {}).length) {
90
- return reply.status(400).send('invalid payload');
91
- }
92
-
93
- // const xss = checkXSS({ body });
94
- const sql = checkSQL({ body });
95
-
96
- if (/*xss.error ||*/ sql.error && false) {
97
- logger.file(`injection/${/*xss.error ? 'xss' : */'sql'}/cms`, {
98
- table,
99
- ...params,
100
- uid: user?.uid,
101
- ...(/*xss.error ? xss : */sql),
102
- });
103
- return reply
104
- .status(409)
105
- .send(
106
- `Дані містять заборонені ${/*xss.error ? 'xss' : */'sql'} символи. Приберіть їх та спробуйте ще раз`
107
- );
108
- }
109
-
110
- const client = await pg.connect();
111
-
112
- try {
113
- await client.query('begin');
114
- const res = await dataInsert({
115
- pg: client,
116
- table: 'site.contents',
117
- id,
118
- data: { ...body, content_type_id: ctid1 },
119
- uid: user?.uid,
120
- }).then(el => el.rows?.[0] || {});
121
-
122
- if (!res?.content_id) throw new Error('insert contents error');
123
-
124
- await Promise.all(keys.map(async key => dataInsert({
125
- pg: client,
126
- table: 'site.content_data',
127
- data: {
128
- field_key: key,
129
- content_id: res.content_id,
130
- object_id: res.content_id,
131
- field_type: types[key] || 'text',
132
- field_value: inputTypes[types[key] || ''] === 'json' ? undefined : body[key],
133
- field_value_object: inputTypes[types[key] || ''] === 'json' ? body[key] : undefined,
134
- },
135
- uid: user?.uid,
136
- })));
137
-
138
- await updateLocalization(client, res.content_id, body, ctid1, user?.uid);
139
-
140
- if (body?.tag_list?.length) {
141
- await Promise.all(body.tag_list.map(async tag => dataInsert({
142
- pg: client,
143
- table: 'site.tag_data',
144
- data: {
145
- tag_id: tag,
146
- data_id: id,
147
- },
148
- uid: user?.uid,
149
- })));
150
- }
151
-
152
- await client.query('commit');
153
-
154
- return {
155
- id: res.content_id, rows: [res].filter(Boolean)
156
- };
157
- } catch (err) {
158
- await client.query('rollback');
159
- return reply.status(500).send(err.toString());
160
- } finally {
161
- client.release();
162
- }
163
- }
164
-
165
- // custom table
166
- if (!table && !dbtable) {
167
- return reply.status(400).send('invalid params: type');
168
- }
169
-
170
- const client = await pg.connect();
171
-
172
- try {
173
- await client.query('begin');
174
-
175
- // const types = columns?.reduce?.((acc, curr) => ({ ...acc, [curr.name]: inputTypes[curr.type] || 'text' }), {}) || {};
176
- const { rows = [] } = await dataInsert({
177
- pg: client,
178
- id,
179
- table: 'data.' + `"${(table || dbtable)}"`,
180
- data: body,
181
- referer: headers?.referer,
182
- uid: user?.uid,
183
- }).catch(err => {
184
- if (err.message?.includes?.('unique constraint')) {
185
- throw new Error('Порушенні унікальності: ' + err.message?.match?.(/([^']+)/g)?.[1]);
186
- }
187
- throw err;
188
- }) || {};
189
-
190
- const idRes = rows?.[0]?.id;
191
-
192
- if (!idRes) {
193
- throw new Error('content insert error');
194
- }
195
-
196
- await updateLocalization(client, idRes, body, ctid, user?.uid);
197
-
198
- if (body?.tag_list?.length) {
199
- await Promise.all(body.tag_list.map(async tag => dataInsert({
200
- pg: client,
201
- table: 'site.tag_data',
202
- data: {
203
- tag_id: tag,
204
- data_id: id || idRes,
205
- },
206
- uid: user?.uid,
207
- })));
208
- }
209
-
210
- await client.query('commit');
211
-
212
- return reply.status(200).send({ id: idRes, rows });
213
- } catch (err) {
214
- await client.query('rollback');
215
- return reply.status(500).send(err.toString());
216
- } finally {
217
- client.release();
218
- }
1
+ import { config, checkSQL, getTemplate, pgClients, dataInsert, logger } from '@opengis/fastify-table/utils.js';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+
4
+ const inputTypes = existsSync('input-types.json') ? JSON.parse(readFileSync('input-types.json') || '{}') : {};
5
+
6
+ import updateLocalization from '../utils/updateLocalization.js';
7
+
8
+ const defaultColumns = [
9
+ 'content_id',
10
+ 'space_id',
11
+ 'content_type_id',
12
+ 'created_at',
13
+ 'updated_at',
14
+ 'published_at',
15
+ 'revision',
16
+ 'locale',
17
+ 'status',
18
+ 'slug',
19
+ 'title',
20
+ 'created_by',
21
+ 'published_by',
22
+ 'updated_by',
23
+ 'meta',
24
+ ];
25
+
26
+ export default async function insertContent(req, reply) {
27
+ const {
28
+ pg = pgClients.client,
29
+ params = {},
30
+ user = {},
31
+ body = {},
32
+ headers = {},
33
+ } = req;
34
+
35
+ const { type, id = body?.id } = params;
36
+
37
+ if (!type) {
38
+ return reply.status(400).send('not enough params: type');
39
+ }
40
+
41
+ const arr = config.pg ? await pg.query(`select array_agg(relname)::text[] from pg_class a
42
+ left join pg_namespace b on a.relnamespace=b.oid
43
+ where a.relam=2 and b.nspname='data'`).then(el => el.rows?.[0]?.array_agg || []) : [];
44
+
45
+ if (!arr.length) {
46
+ return reply.status(400).send('empty schema: data');
47
+ }
48
+
49
+ const table = arr.find(el => el === params.type);
50
+
51
+ const { content_id: contentId, type: contentType } = await pg.query(
52
+ 'select content_id, (select type from site.content_types where content_type_id=t.content_type_id) from site.contents t where slug=$1',
53
+ [['single', 'pages'].includes(type) ? id : type],
54
+ ).then(el => el.rows?.[0] || {});
55
+
56
+ const ctypeId = contentId && contentId !== 'pages' && contentType === 'single' ? await pg.query(
57
+ 'select content_type_id from site.contents where content_id=$1',
58
+ [contentId],
59
+ ).then(el => el.rows?.[0]?.content_type_id) : null;
60
+
61
+ const { ctid, dbtable, columns: contentColumns } = await pg.query(
62
+ 'select content_type_id as ctid, table_name as dbtable, columns from site.content_types where $1 in (content_type_id, name)',
63
+ [type === 'single' && id ? id : (ctypeId || type)],
64
+ ).then(el => el.rows?.[0] || {});
65
+
66
+ const loadTable = (ctypeId || type) === 'pages' ? await getTemplate('table', 'single.default.table') : {};
67
+
68
+ const columns = (ctypeId || type) === 'pages'
69
+ ? (loadTable?.columns || []).concat(contentColumns.filter(col => loadTable?.columns.findIndex(el => el.name === col.name) === -1))
70
+ : contentColumns;
71
+
72
+ // site.content_data, includes singletone
73
+ if (((!table && !dbtable) || type === 'pages')) {
74
+ const cid = await pg.query(
75
+ 'select content_id from site.contents where content_type_id=$1 limit 1',
76
+ [ctid || 'pages'],
77
+ ).then(el => el.rows?.[0]?.content_id);
78
+
79
+ const ctid1 = body.content_type_id || ctid || 'pages';
80
+
81
+ if (!cid) {
82
+ return reply.status(404).send('contents not found');
83
+ }
84
+
85
+ const columnList = columns?.map?.(el => el.name) || [];
86
+ const types = columns?.reduce?.((acc, curr) => ({ ...acc, [curr.name]: curr.type || 'text' }), {}) || {};
87
+ const keys = Object.keys(body || {}).filter(key => columnList.includes(key) && !defaultColumns.includes(key));
88
+
89
+ if (!Object.keys(body || {}).length) {
90
+ return reply.status(400).send('invalid payload');
91
+ }
92
+
93
+ // const xss = checkXSS({ body });
94
+ const sql = checkSQL({ body });
95
+
96
+ if (/*xss.error ||*/ sql.error && false) {
97
+ logger.file(`injection/${/*xss.error ? 'xss' : */'sql'}/cms`, {
98
+ table,
99
+ ...params,
100
+ uid: user?.uid,
101
+ ...(/*xss.error ? xss : */sql),
102
+ });
103
+ return reply
104
+ .status(409)
105
+ .send(
106
+ `Дані містять заборонені ${/*xss.error ? 'xss' : */'sql'} символи. Приберіть їх та спробуйте ще раз`
107
+ );
108
+ }
109
+
110
+ const client = await pg.connect();
111
+
112
+ try {
113
+ await client.query('begin');
114
+ const res = await dataInsert({
115
+ pg: client,
116
+ table: 'site.contents',
117
+ id,
118
+ data: { ...body, content_type_id: ctid1 },
119
+ uid: user?.uid,
120
+ }).then(el => el.rows?.[0] || {});
121
+
122
+ if (!res?.content_id) throw new Error('insert contents error');
123
+
124
+ await Promise.all(keys.map(async key => dataInsert({
125
+ pg: client,
126
+ table: 'site.content_data',
127
+ data: {
128
+ field_key: key,
129
+ content_id: res.content_id,
130
+ object_id: res.content_id,
131
+ field_type: types[key] || 'text',
132
+ field_value: inputTypes[types[key] || ''] === 'json' ? undefined : body[key],
133
+ field_value_object: inputTypes[types[key] || ''] === 'json' ? body[key] : undefined,
134
+ },
135
+ uid: user?.uid,
136
+ })));
137
+
138
+ await updateLocalization(client, res.content_id, body, ctid1, user?.uid);
139
+
140
+ if (body?.tag_list?.length) {
141
+ await Promise.all(body.tag_list.map(async tag => dataInsert({
142
+ pg: client,
143
+ table: 'site.tag_data',
144
+ data: {
145
+ tag_id: tag,
146
+ data_id: id,
147
+ },
148
+ uid: user?.uid,
149
+ })));
150
+ }
151
+
152
+ await client.query('commit');
153
+
154
+ return {
155
+ id: res.content_id, rows: [res].filter(Boolean)
156
+ };
157
+ } catch (err) {
158
+ await client.query('rollback');
159
+ return reply.status(500).send(err.toString());
160
+ } finally {
161
+ client.release();
162
+ }
163
+ }
164
+
165
+ // custom table
166
+ if (!table && !dbtable) {
167
+ return reply.status(400).send('invalid params: type');
168
+ }
169
+
170
+ const client = await pg.connect();
171
+
172
+ try {
173
+ await client.query('begin');
174
+
175
+ // const types = columns?.reduce?.((acc, curr) => ({ ...acc, [curr.name]: inputTypes[curr.type] || 'text' }), {}) || {};
176
+ const { rows = [] } = await dataInsert({
177
+ pg: client,
178
+ id,
179
+ table: 'data.' + `"${(table || dbtable)}"`,
180
+ data: body,
181
+ referer: headers?.referer,
182
+ uid: user?.uid,
183
+ }).catch(err => {
184
+ if (err.message?.includes?.('unique constraint')) {
185
+ throw new Error('Порушенні унікальності: ' + err.message?.match?.(/([^']+)/g)?.[1]);
186
+ }
187
+ throw err;
188
+ }) || {};
189
+
190
+ const idRes = rows?.[0]?.id;
191
+
192
+ if (!idRes) {
193
+ throw new Error('content insert error');
194
+ }
195
+
196
+ await updateLocalization(client, idRes, body, ctid, user?.uid);
197
+
198
+ if (body?.tag_list?.length) {
199
+ await Promise.all(body.tag_list.map(async tag => dataInsert({
200
+ pg: client,
201
+ table: 'site.tag_data',
202
+ data: {
203
+ tag_id: tag,
204
+ data_id: id || idRes,
205
+ },
206
+ uid: user?.uid,
207
+ })));
208
+ }
209
+
210
+ await client.query('commit');
211
+
212
+ return reply.status(200).send({ id: idRes, rows });
213
+ } catch (err) {
214
+ await client.query('rollback');
215
+ return reply.status(500).send(err.toString());
216
+ } finally {
217
+ client.release();
218
+ }
219
219
  }
@@ -1,94 +1,94 @@
1
- import path from 'node:path';
2
- import { existsSync, mkdirSync } from 'node:fs';
3
- import { readdir, stat } from 'node:fs/promises';
4
-
5
- import { config, getFolder, pgClients, getMimeType } from '@opengis/fastify-table/utils.js';
6
- import { createHash } from 'node:crypto';
7
-
8
- const rootDir = getFolder(config, 'local');
9
- const dir = '/files';
10
-
11
- mkdirSync(path.join(rootDir, dir), { recursive: true });
12
-
13
- export default async function listMedia(req, reply) {
14
- const { pg = pgClients.client, query = {} } = req;
15
- const { subdir: subdir1 = '', search } = query;
16
-
17
- if (!pg.pk?.['site.media']) {
18
- return reply.status(404).send('table not found');
19
- }
20
-
21
- if (typeof subdir1 !== 'string' || subdir1.includes('..')) {
22
- return reply.status(403).send('invalid params: subdir');
23
- }
24
-
25
- const subdir = subdir1.replace(/\/{2,}/g, '/');
26
- const relpath = path.join(dir, subdir1).replace(/\\/g, '/');
27
- const dirpath = path.join(rootDir, relpath).replace(/\\/g, '/');
28
-
29
- if (!existsSync(dirpath)) {
30
- return { data: [], relpath, msg: 'directory not exists' };
31
- }
32
-
33
- const isDirectory = (await stat(dirpath)).isDirectory();
34
-
35
- const allItems = isDirectory ? await readdir(dirpath, { withFileTypes: true, recursive: true }) : [];
36
- const items = isDirectory ? await readdir(dirpath, { withFileTypes: true }) : [];
37
-
38
- const rows = await pg.query(
39
- `select
40
- media_id as id, filename, filetype, filesize, url, description, alt,
41
- mime, preview_url, created_at, updated_at, created_by, updated_by
42
- from site.media
43
- where ${subdir ? 'subdir = $1' : (search ? '1=1' : 'subdir is null')} ${search ? `and filename ilike '%${search.replace(/'/g, "''")}%'` : ''}`,
44
- [subdir].filter(Boolean),
45
- ).then(el => el.rows || []); // ?.filter(row => items.map(el => el.name).includes(row.filename))
46
-
47
- const subdirs = items
48
- .filter(el => el.isDirectory())
49
- .map(el => ({ type: 'dir', name: el.name }))
50
- .filter(el => search ? el.name.includes(search) : true);
51
-
52
- if (subdirs.length) {
53
- await Promise.all(subdirs.map(async (item) => {
54
- const items = isDirectory ? await readdir(path.join(dirpath, item.name)) : [];
55
- Object.assign(item, { count: items.length });
56
- }));
57
- }
58
-
59
- const result = { relpath };
60
-
61
- if (config.debug) {
62
- Object.assign(result, { rootDir });
63
- }
64
-
65
- const files = (search ? allItems.filter(el => el.name.includes(search)) : items)
66
- .filter(el => el.isFile())
67
- .map(el => {
68
- const media = rows.find(row => row.filename === el.name);
69
- const filepath = media ? media.url : ('/files/' + (el.path.split('/files/')[1] ? el.path.split('/files/')[1] + '/' : '') + el.name);
70
- return media ? {
71
- type: 'file',
72
- ...media,
73
- url: `${req.routeOptions.url}/${media.id}/file`,
74
- preview: `${req.routeOptions.url}/${media.id}/preview`,
75
- filepath,
76
- metadata: `${req.routeOptions.url}/${media.id}`,
77
- } : {
78
- id: createHash('md5').update(filepath).digest('hex'),
79
- hash: true,
80
- type: 'file',
81
- filename: el.name,
82
- filepath,
83
- filetype: getMimeType(el.name)?.startsWith('image/') ? "image" : "other",
84
- filesize: 0,
85
- url: filepath,
86
- mime: getMimeType(el.name),
87
- preview: filepath,
88
- }
89
- });
90
-
91
- Object.assign(result, { data: subdirs.concat(files) });
92
- return result;
93
-
1
+ import path from 'node:path';
2
+ import { existsSync, mkdirSync } from 'node:fs';
3
+ import { readdir, stat } from 'node:fs/promises';
4
+
5
+ import { config, getFolder, pgClients, getMimeType } from '@opengis/fastify-table/utils.js';
6
+ import { createHash } from 'node:crypto';
7
+
8
+ const rootDir = getFolder(config, 'local');
9
+ const dir = '/files';
10
+
11
+ mkdirSync(path.join(rootDir, dir), { recursive: true });
12
+
13
+ export default async function listMedia(req, reply) {
14
+ const { pg = pgClients.client, query = {} } = req;
15
+ const { subdir: subdir1 = '', search } = query;
16
+
17
+ if (!pg.pk?.['site.media']) {
18
+ return reply.status(404).send('table not found');
19
+ }
20
+
21
+ if (typeof subdir1 !== 'string' || subdir1.includes('..')) {
22
+ return reply.status(403).send('invalid params: subdir');
23
+ }
24
+
25
+ const subdir = subdir1.replace(/\/{2,}/g, '/');
26
+ const relpath = path.join(dir, subdir1).replace(/\\/g, '/');
27
+ const dirpath = path.join(rootDir, relpath).replace(/\\/g, '/');
28
+
29
+ if (!existsSync(dirpath)) {
30
+ return { data: [], relpath, msg: 'directory not exists' };
31
+ }
32
+
33
+ const isDirectory = (await stat(dirpath)).isDirectory();
34
+
35
+ const allItems = isDirectory ? await readdir(dirpath, { withFileTypes: true, recursive: true }) : [];
36
+ const items = isDirectory ? await readdir(dirpath, { withFileTypes: true }) : [];
37
+
38
+ const rows = await pg.query(
39
+ `select
40
+ media_id as id, filename, filetype, filesize, url, description, alt,
41
+ mime, preview_url, created_at, updated_at, created_by, updated_by
42
+ from site.media
43
+ where ${subdir ? 'subdir = $1' : (search ? '1=1' : 'subdir is null')} ${search ? `and filename ilike '%${search.replace(/'/g, "''")}%'` : ''}`,
44
+ [subdir].filter(Boolean),
45
+ ).then(el => el.rows || []); // ?.filter(row => items.map(el => el.name).includes(row.filename))
46
+
47
+ const subdirs = items
48
+ .filter(el => el.isDirectory())
49
+ .map(el => ({ type: 'dir', name: el.name }))
50
+ .filter(el => search ? el.name.includes(search) : true);
51
+
52
+ if (subdirs.length) {
53
+ await Promise.all(subdirs.map(async (item) => {
54
+ const items = isDirectory ? await readdir(path.join(dirpath, item.name)) : [];
55
+ Object.assign(item, { count: items.length });
56
+ }));
57
+ }
58
+
59
+ const result = { relpath };
60
+
61
+ if (config.debug) {
62
+ Object.assign(result, { rootDir });
63
+ }
64
+
65
+ const files = (search ? allItems.filter(el => el.name.includes(search)) : items)
66
+ .filter(el => el.isFile())
67
+ .map(el => {
68
+ const media = rows.find(row => row.filename === el.name);
69
+ const filepath = media ? media.url : ('/files/' + (el.path.split('/files/')[1] ? el.path.split('/files/')[1] + '/' : '') + el.name);
70
+ return media ? {
71
+ type: 'file',
72
+ ...media,
73
+ url: `${req.routeOptions.url}/${media.id}/file`,
74
+ preview: `${req.routeOptions.url}/${media.id}/preview`,
75
+ filepath,
76
+ metadata: `${req.routeOptions.url}/${media.id}`,
77
+ } : {
78
+ id: createHash('md5').update(filepath).digest('hex'),
79
+ hash: true,
80
+ type: 'file',
81
+ filename: el.name,
82
+ filepath,
83
+ filetype: getMimeType(el.name)?.startsWith('image/') ? "image" : "other",
84
+ filesize: 0,
85
+ url: filepath,
86
+ mime: getMimeType(el.name),
87
+ preview: filepath,
88
+ }
89
+ });
90
+
91
+ Object.assign(result, { data: subdirs.concat(files) });
92
+ return result;
93
+
94
94
  }