prostgles-server 3.0.69 → 3.0.71

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 (32) hide show
  1. package/dist/PubSubManager/PubSubManager.d.ts +4 -4
  2. package/dist/PubSubManager/PubSubManager.d.ts.map +1 -1
  3. package/dist/PubSubManager/PubSubManager.js +1 -1
  4. package/dist/PubSubManager/PubSubManager.js.map +1 -1
  5. package/dist/PubSubManager/initPubSubManager.d.ts.map +1 -1
  6. package/dist/PubSubManager/initPubSubManager.js +52 -36
  7. package/dist/PubSubManager/initPubSubManager.js.map +1 -1
  8. package/lib/AuthHandler.js +213 -209
  9. package/lib/DBEventsManager.js +34 -31
  10. package/lib/DboBuilder/QueryBuilder/QueryBuilder.js +163 -155
  11. package/lib/DboBuilder/TableHandler.js +21 -20
  12. package/lib/DboBuilder/ViewHandler.js +23 -8
  13. package/lib/DboBuilder/runSQL.js +5 -5
  14. package/lib/DboBuilder.js +85 -65
  15. package/lib/FileManager.js +369 -364
  16. package/lib/PostgresNotifListenManager.js +26 -20
  17. package/lib/Prostgles.js +194 -177
  18. package/lib/PubSubManager/PubSubManager.d.ts +4 -4
  19. package/lib/PubSubManager/PubSubManager.d.ts.map +1 -1
  20. package/lib/PubSubManager/PubSubManager.js +250 -240
  21. package/lib/PubSubManager/PubSubManager.ts +2 -2
  22. package/lib/PubSubManager/initPubSubManager.d.ts.map +1 -1
  23. package/lib/PubSubManager/initPubSubManager.js +52 -36
  24. package/lib/PubSubManager/initPubSubManager.ts +53 -37
  25. package/lib/PublishParser.js +7 -2
  26. package/lib/SchemaWatch.js +2 -1
  27. package/lib/TableConfig.js +94 -91
  28. package/package.json +1 -1
  29. package/tests/client/PID.txt +1 -1
  30. package/tests/client/tsconfig.json +2 -2
  31. package/tests/server/package-lock.json +1 -1
  32. package/tests/server/tsconfig.json +2 -2
@@ -25,7 +25,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
25
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
- var _a;
29
28
  Object.defineProperty(exports, "__esModule", { value: true });
30
29
  exports.bytesToSize = exports.getFileType = exports.getFileTypeFromFilename = exports.removeExpressRoute = exports.asSQLIdentifier = void 0;
31
30
  const aws_sdk_1 = require("aws-sdk");
@@ -44,343 +43,40 @@ const runSQL_1 = require("./DboBuilder/runSQL");
44
43
  const path = __importStar(require("path"));
45
44
  const ViewHandler_1 = require("./DboBuilder/ViewHandler");
46
45
  class FileManager {
47
- constructor(config, imageOptions) {
48
- this.getFileUrl = (name) => this.fileRoute ? `${this.fileRoute}/${name}` : "";
49
- this.checkFreeSpace = async (folderPath, fileSize = 0) => {
50
- if (!this.s3Client && "localFolderPath" in this.config) {
51
- const { minFreeBytes = 1.048e6 } = this.config;
52
- const required = Math.max(fileSize, minFreeBytes);
53
- if (required) {
54
- const diskSpace = await (0, check_disk_space_1.default)(folderPath);
55
- if (diskSpace.free < required) {
56
- const err = `There is not enough space on the server to save files.\nTotal: ${bytesToSize(diskSpace.size)} \nRemaning: ${bytesToSize(diskSpace.free)} \nRequired: ${bytesToSize(required)}`;
57
- throw new Error(err);
58
- }
59
- }
60
- }
61
- };
62
- this.uploadStream = (name, mime, onProgress, onError, onEnd, expectedSizeBytes) => {
63
- const passThrough = new stream.PassThrough();
64
- if (!this.s3Client && "localFolderPath" in this.config) {
65
- // throw new Error("S3 config missing. Can only upload streams to S3");
66
- try {
67
- this.checkFreeSpace(this.config.localFolderPath, expectedSizeBytes).catch(err => {
68
- onError?.(err);
69
- passThrough.end();
70
- });
71
- const url = this.getFileUrl(name);
72
- fs.mkdirSync(this.config.localFolderPath, { recursive: true });
73
- const filePath = path.resolve(`${this.config.localFolderPath}/${name}`);
74
- const writeStream = fs.createWriteStream(filePath);
75
- let errored = false;
76
- let loaded = 0;
77
- writeStream.on('error', err => {
78
- errored = true;
79
- onError?.(err);
80
- });
81
- let lastProgress = Date.now();
82
- const throttle = 1000;
83
- if (onProgress) {
84
- passThrough.on('data', function (chunk) {
85
- loaded += chunk.length;
86
- const now = Date.now();
87
- if (now - lastProgress > throttle) {
88
- lastProgress = now;
89
- onProgress?.({ loaded, total: 0 });
90
- }
91
- });
92
- }
93
- if (onEnd)
94
- writeStream.on('finish', () => {
95
- if (errored)
96
- return;
97
- let content_length = 0;
98
- try {
99
- content_length = fs.statSync(filePath).size;
100
- onEnd?.({
101
- url,
102
- filePath,
103
- etag: `none`,
104
- content_length
105
- });
106
- }
107
- catch (err) {
108
- onError?.(err);
109
- }
110
- });
111
- passThrough.pipe(writeStream);
112
- }
113
- catch (err) {
114
- onError?.(err);
115
- }
116
- }
117
- else {
118
- this.upload(passThrough, name, mime, onProgress).then(onEnd)
119
- .catch(onError);
120
- }
121
- return passThrough;
122
- };
123
- this.uploadAsMedia = async (params) => {
124
- const { item, imageOptions } = params;
125
- const { name, data, content_type, extension } = item;
126
- if (!data)
127
- throw "No file provided";
128
- if (!name || typeof name !== "string")
129
- throw "Expecting a string name";
130
- // const type = await this.getMIME(data, name, allowedExtensions, dissallowedExtensions);
131
- let _data = data;
132
- /** Resize/compress/remove exif from photos */
133
- if (content_type.startsWith("image") && extension.toLowerCase() !== "gif") {
134
- const compression = imageOptions?.compression;
135
- if (compression) {
136
- console.log("Resizing image");
137
- let opts;
138
- if ("contain" in compression) {
139
- opts = {
140
- fit: sharp.fit.contain,
141
- ...compression.contain
142
- };
143
- }
144
- else if ("inside" in compression) {
145
- opts = {
146
- fit: sharp.fit.inside,
147
- ...compression.inside
148
- };
149
- }
150
- _data = await sharp(data)
151
- .resize(opts)
152
- .withMetadata(Boolean(imageOptions?.keepMetadata))
153
- // .jpeg({ quality: 80 })
154
- .toBuffer();
155
- }
156
- else if (!imageOptions?.keepMetadata) {
157
- /**
158
- * Remove exif
159
- */
160
- // const metadata = await simg.metadata();
161
- // const simg = await sharp(data);
162
- _data = await sharp(data).clone().withMetadata({
163
- exif: {}
164
- })
165
- .toBuffer();
166
- }
167
- }
168
- const res = await this.upload(_data, name, content_type);
169
- return res;
170
- };
171
- this.parseSQLIdentifier = async (name) => (0, exports.asSQLIdentifier)(name, this.prostgles.db); // this.prostgles.dbo.sql<"value">("select format('%I', $1)", [name], { returnType: "value" } )
172
- this.getColInfo = (args) => {
173
- const { colName, tableName } = args;
174
- const tableConfig = this.prostgles?.opts.fileTable?.referencedTables?.[tableName];
175
- const isReferencingFileTable = this.dbo[tableName]?.columns?.some(c => c.name === colName && c.references && c.references?.some(({ ftable }) => ftable === this.tableName));
176
- if (isReferencingFileTable) {
177
- if (tableConfig && typeof tableConfig !== "string") {
178
- return tableConfig.referenceColumns[colName];
179
- }
180
- return { acceptedContent: "*" };
181
- }
182
- return undefined;
183
- };
184
- this.init = async (prg) => {
185
- this.prostgles = prg;
186
- // const { dbo, db, opts } = prg;
187
- const { fileTable } = prg.opts;
188
- if (!fileTable)
189
- throw "fileTable missing";
190
- const { tableName = "media", referencedTables = {} } = fileTable;
191
- this.tableName = tableName;
192
- const maxBfSizeMB = (prg.opts.io?.engine?.opts?.maxHttpBufferSize || 1e6) / 1e6;
193
- console.log(`Prostgles: Initiated file manager. Max allowed file size: ${maxBfSizeMB}MB (maxHttpBufferSize = 1e6). To increase this set maxHttpBufferSize in socket.io server init options`);
194
- // throw `this.db.tx(d => do everything in a transaction pls!!!!`;
195
- const canCreate = await (0, runSQL_1.canCreateTables)(this.db);
196
- const runQuery = (q) => {
197
- if (!canCreate)
198
- throw "File table creation failed. Your postgres user does not have CREATE table privileges";
199
- return this.db.any(q);
200
- };
201
- /**
202
- * 1. Create media table
203
- */
204
- if (!this.dbo[tableName]) {
205
- console.log(`Creating fileTable ${(0, prostgles_types_1.asName)(tableName)} ...`);
206
- await runQuery(`CREATE EXTENSION IF NOT EXISTS pgcrypto `);
207
- await runQuery(`CREATE TABLE IF NOT EXISTS ${(0, prostgles_types_1.asName)(tableName)} (
208
- url TEXT NOT NULL,
209
- original_name TEXT NOT NULL,
210
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
211
- name TEXT NOT NULL,
212
- extension TEXT NOT NULL,
213
- content_type TEXT NOT NULL,
214
- content_length BIGINT NOT NULL DEFAULT 0,
215
- added TIMESTAMP NOT NULL DEFAULT NOW(),
216
- description TEXT,
217
- s3_url TEXT,
218
- signed_url TEXT,
219
- signed_url_expires BIGINT,
220
- etag TEXT,
221
- deleted BIGINT,
222
- deleted_from_storage BIGINT,
223
- UNIQUE(id),
224
- UNIQUE(name)
225
- )`);
226
- console.log(`Created fileTable ${(0, prostgles_types_1.asName)(tableName)}`);
227
- await prg.refreshDBO();
228
- }
229
- /**
230
- * 2. Create media lookup tables
231
- */
232
- await Promise.all((0, prostgles_types_1.getKeys)(referencedTables).map(async (refTable) => {
233
- if (!this.dbo[refTable])
234
- throw `Referenced table (${refTable}) from fileTable.referencedTables prostgles init config does not exist`;
235
- const cols = await this.dbo[refTable].getColumns();
236
- const tableConfig = referencedTables[refTable];
237
- if (typeof tableConfig !== "string") {
238
- for await (const colName of (0, prostgles_types_1.getKeys)(tableConfig.referenceColumns)) {
239
- const existingCol = cols.find(c => c.name === colName);
240
- if (existingCol) {
241
- if (existingCol.references?.some(({ ftable }) => ftable === tableName)) {
242
- // All ok
243
- }
244
- else {
245
- if (existingCol.udt_name === "uuid") {
246
- try {
247
- const query = `ALTER TABLE ${(0, prostgles_types_1.asName)(refTable)} ADD FOREIGN KEY (${(0, prostgles_types_1.asName)(colName)}) REFERENCES ${(0, prostgles_types_1.asName)(tableName)} (id);`;
248
- console.log(`Referenced file column ${refTable} (${colName}) exists but is not referencing file table. Trying to add REFERENCE constraing...\n${query}`);
249
- await runQuery(query);
250
- console.log("SUCCESS: " + query);
251
- }
252
- catch (e) {
253
- console.error(`Could not add constraing. Err: ${e instanceof Error ? e.message : JSON.stringify(e)}`);
254
- }
255
- }
256
- else {
257
- console.error(`Referenced file column ${refTable} (${colName}) exists but is not of required type (UUID). Choose a different column name or ALTER the existing column to match the type and the data found in file table ${tableName}(id)`);
258
- }
259
- }
260
- }
261
- else {
262
- try {
263
- const query = `ALTER TABLE ${(0, prostgles_types_1.asName)(refTable)} ADD COLUMN ${(0, prostgles_types_1.asName)(colName)} UUID REFERENCES ${(0, prostgles_types_1.asName)(tableName)} (id);`;
264
- console.log(`Creating referenced file column ${refTable} (${colName})...\n${query}`);
265
- await runQuery(query);
266
- console.log("SUCCESS: " + query);
267
- }
268
- catch (e) {
269
- console.error(`FAILED. Err: ${e instanceof Error ? e.message : JSON.stringify(e)}`);
270
- }
271
- }
272
- }
273
- }
274
- else {
275
- const lookupTableName = await this.parseSQLIdentifier(`prostgles_lookup_${tableName}_${refTable}`);
276
- const pKeyFields = cols.filter(f => f.is_pkey);
277
- if (pKeyFields.length !== 1) {
278
- console.error(`Could not make link table for ${refTable}. ${pKeyFields} must have exactly one primary key column. Current pkeys: ${pKeyFields.map(f => f.name)}`);
279
- }
280
- const pkField = pKeyFields[0];
281
- const refType = referencedTables[refTable];
282
- if (!this.dbo[lookupTableName]) {
283
- // if(!(await dbo[lookupTableName].count())) await db.any(`DROP TABLE IF EXISTS ${lookupTableName};`);
284
- const action = ` (${tableName} <-> ${refTable}) join table ${lookupTableName}`; // PRIMARY KEY
285
- const query = `
286
- CREATE TABLE ${lookupTableName} (
287
- foreign_id ${pkField.udt_name} ${refType === "one" ? " PRIMARY KEY " : ""} REFERENCES ${(0, prostgles_types_1.asName)(refTable)}(${(0, prostgles_types_1.asName)(pkField.name)}),
288
- media_id UUID NOT NULL REFERENCES ${(0, prostgles_types_1.asName)(tableName)}(id)
289
- )
290
- `;
291
- console.log(`Creating ${action} ...`, lookupTableName);
292
- await runQuery(query);
293
- console.log(`Created ${action}`);
294
- }
295
- else {
296
- const cols = await this.dbo[lookupTableName].getColumns();
297
- const badCols = cols.filter(c => !c.references);
298
- await Promise.all(badCols.map(async (badCol) => {
299
- console.error(`Prostgles: media ${lookupTableName} joining table has lost a reference constraint for column ${badCol.name}.` +
300
- ` This may have been caused by a DROP TABLE ... CASCADE.`);
301
- let q = ` ALTER TABLE ${(0, prostgles_types_1.asName)(lookupTableName)} ADD FOREIGN KEY (${badCol.name}) `;
302
- console.log("Trying to add the missing constraint back");
303
- if (badCol.name === "foreign_id") {
304
- q += `REFERENCES ${(0, prostgles_types_1.asName)(refTable)}(${(0, prostgles_types_1.asName)(pkField.name)}) `;
305
- }
306
- else if (badCol.name === "media_id") {
307
- q += `REFERENCES ${(0, prostgles_types_1.asName)(tableName)}(id) `;
308
- }
309
- if (q) {
310
- try {
311
- await runQuery(q);
312
- console.log("Added missing constraint back");
313
- }
314
- catch (e) {
315
- console.error("Failed to add missing constraint", e);
316
- }
317
- }
318
- }));
319
- }
320
- }
321
- await prg.refreshDBO();
322
- return true;
323
- }));
324
- /**
325
- * 4. Serve media through express
326
- */
327
- const { fileServeRoute = `/${tableName}`, expressApp: app } = fileTable;
328
- if (fileServeRoute.endsWith("/")) {
329
- throw `fileServeRoute must not end with a '/'`;
330
- }
331
- this.fileRoute = fileServeRoute;
332
- if (app) {
333
- app.get(this.fileRouteExpress, async (req, res) => {
334
- if (!this.dbo[tableName]) {
335
- res.status(500).json({ err: `Internal error: media table (${tableName}) not valid` });
336
- return false;
337
- }
338
- const mediaTable = this.dbo[tableName];
339
- try {
340
- const { name } = req.params;
341
- if (typeof name !== "string" || !name)
342
- throw "Invalid media name";
343
- const media = await mediaTable.findOne({ name }, { select: { id: 1, name: 1, signed_url: 1, signed_url_expires: 1, content_type: 1 } }, { httpReq: req });
344
- if (!media) {
345
- /**
346
- * Redirect to login !??
347
- */
348
- // const mediaExists = await mediaTable.count({ name });
349
- // if(mediaExists && this.prostgles.authHandler){
350
- // } else {
351
- // throw "Invalid media";
352
- // }
353
- throw "Invalid media";
354
- }
355
- if (this.s3Client) {
356
- let url = media.signed_url;
357
- const expires = +(media.signed_url_expires || 0);
358
- const EXPIRES = Date.now() + HOUR;
359
- if (!url || expires < EXPIRES) {
360
- url = await this.getFileS3URL(media.name, 60 * 60);
361
- await mediaTable.update({ name }, { signed_url: url, signed_url_expires: EXPIRES });
362
- }
363
- res.redirect(url);
364
- }
365
- else {
366
- const pth = `${this.config.localFolderPath}/${media.name}`;
367
- if (!fs.existsSync(pth)) {
368
- throw new Error("File not found");
369
- }
370
- res.contentType(media.content_type);
371
- res.sendFile(pth);
372
- }
373
- }
374
- catch (e) {
375
- console.log(e);
376
- res.status(404).json({ err: "Invalid/missing media" });
377
- }
378
- });
379
- }
380
- };
381
- this.destroy = () => {
382
- (0, exports.removeExpressRoute)(this.prostgles?.opts.fileTable?.expressApp, [this.fileRouteExpress]);
46
+ static testCredentials = async (accessKeyId, secretAccessKey) => {
47
+ const sts = new aws_sdk_2.default.STS();
48
+ aws_sdk_2.default.config.credentials = {
49
+ accessKeyId,
50
+ secretAccessKey
383
51
  };
52
+ const ident = await sts.getCallerIdentity({}).promise();
53
+ return ident;
54
+ };
55
+ s3Client;
56
+ config;
57
+ imageOptions;
58
+ prostgles;
59
+ get dbo() {
60
+ if (!this.prostgles?.dbo) {
61
+ // this.prostgles?.refreshDBO();
62
+ throw "this.prostgles.dbo missing";
63
+ }
64
+ return this.prostgles.dbo;
65
+ }
66
+ ;
67
+ get db() {
68
+ if (!this.prostgles?.db)
69
+ throw "this.prostgles.db missing";
70
+ return this.prostgles.db;
71
+ }
72
+ ;
73
+ tableName;
74
+ fileRoute;
75
+ get fileRouteExpress() {
76
+ return this.fileRoute + "/:name";
77
+ }
78
+ checkInterval;
79
+ constructor(config, imageOptions) {
384
80
  this.config = config;
385
81
  this.imageOptions = imageOptions;
386
82
  if ("region" in config) {
@@ -407,23 +103,6 @@ class FileManager {
407
103
  }, Math.max(10000, (fullConfig.delayedDelete.checkIntervalHours || 0) * HOUR));
408
104
  }
409
105
  }
410
- get dbo() {
411
- if (!this.prostgles?.dbo) {
412
- // this.prostgles?.refreshDBO();
413
- throw "this.prostgles.dbo missing";
414
- }
415
- return this.prostgles.dbo;
416
- }
417
- ;
418
- get db() {
419
- if (!this.prostgles?.db)
420
- throw "this.prostgles.db missing";
421
- return this.prostgles.db;
422
- }
423
- ;
424
- get fileRouteExpress() {
425
- return this.fileRoute + "/:name";
426
- }
427
106
  async getFileStream(name) {
428
107
  if ("bucket" in this.config && this.s3Client) {
429
108
  return this.s3Client.getObject({ Key: name, Bucket: this.config.bucket }).createReadStream();
@@ -505,6 +184,81 @@ class FileManager {
505
184
  throw `File MIME type not found for the provided extension: ${result?.ext}`;
506
185
  return result;
507
186
  }
187
+ getFileUrl = (name) => this.fileRoute ? `${this.fileRoute}/${name}` : "";
188
+ checkFreeSpace = async (folderPath, fileSize = 0) => {
189
+ if (!this.s3Client && "localFolderPath" in this.config) {
190
+ const { minFreeBytes = 1.048e6 } = this.config;
191
+ const required = Math.max(fileSize, minFreeBytes);
192
+ if (required) {
193
+ const diskSpace = await (0, check_disk_space_1.default)(folderPath);
194
+ if (diskSpace.free < required) {
195
+ const err = `There is not enough space on the server to save files.\nTotal: ${bytesToSize(diskSpace.size)} \nRemaning: ${bytesToSize(diskSpace.free)} \nRequired: ${bytesToSize(required)}`;
196
+ throw new Error(err);
197
+ }
198
+ }
199
+ }
200
+ };
201
+ uploadStream = (name, mime, onProgress, onError, onEnd, expectedSizeBytes) => {
202
+ const passThrough = new stream.PassThrough();
203
+ if (!this.s3Client && "localFolderPath" in this.config) {
204
+ // throw new Error("S3 config missing. Can only upload streams to S3");
205
+ try {
206
+ this.checkFreeSpace(this.config.localFolderPath, expectedSizeBytes).catch(err => {
207
+ onError?.(err);
208
+ passThrough.end();
209
+ });
210
+ const url = this.getFileUrl(name);
211
+ fs.mkdirSync(this.config.localFolderPath, { recursive: true });
212
+ const filePath = path.resolve(`${this.config.localFolderPath}/${name}`);
213
+ const writeStream = fs.createWriteStream(filePath);
214
+ let errored = false;
215
+ let loaded = 0;
216
+ writeStream.on('error', err => {
217
+ errored = true;
218
+ onError?.(err);
219
+ });
220
+ let lastProgress = Date.now();
221
+ const throttle = 1000;
222
+ if (onProgress) {
223
+ passThrough.on('data', function (chunk) {
224
+ loaded += chunk.length;
225
+ const now = Date.now();
226
+ if (now - lastProgress > throttle) {
227
+ lastProgress = now;
228
+ onProgress?.({ loaded, total: 0 });
229
+ }
230
+ });
231
+ }
232
+ if (onEnd)
233
+ writeStream.on('finish', () => {
234
+ if (errored)
235
+ return;
236
+ let content_length = 0;
237
+ try {
238
+ content_length = fs.statSync(filePath).size;
239
+ onEnd?.({
240
+ url,
241
+ filePath,
242
+ etag: `none`,
243
+ content_length
244
+ });
245
+ }
246
+ catch (err) {
247
+ onError?.(err);
248
+ }
249
+ });
250
+ passThrough.pipe(writeStream);
251
+ }
252
+ catch (err) {
253
+ onError?.(err);
254
+ }
255
+ }
256
+ else {
257
+ this.upload(passThrough, name, mime, onProgress).then(onEnd)
258
+ .catch(onError);
259
+ }
260
+ return passThrough;
261
+ };
508
262
  async upload(file, name, mime, onProgress) {
509
263
  return new Promise(async (resolve, reject) => {
510
264
  if (!file) {
@@ -573,6 +327,54 @@ class FileManager {
573
327
  }
574
328
  });
575
329
  }
330
+ uploadAsMedia = async (params) => {
331
+ const { item, imageOptions } = params;
332
+ const { name, data, content_type, extension } = item;
333
+ if (!data)
334
+ throw "No file provided";
335
+ if (!name || typeof name !== "string")
336
+ throw "Expecting a string name";
337
+ // const type = await this.getMIME(data, name, allowedExtensions, dissallowedExtensions);
338
+ let _data = data;
339
+ /** Resize/compress/remove exif from photos */
340
+ if (content_type.startsWith("image") && extension.toLowerCase() !== "gif") {
341
+ const compression = imageOptions?.compression;
342
+ if (compression) {
343
+ console.log("Resizing image");
344
+ let opts;
345
+ if ("contain" in compression) {
346
+ opts = {
347
+ fit: sharp.fit.contain,
348
+ ...compression.contain
349
+ };
350
+ }
351
+ else if ("inside" in compression) {
352
+ opts = {
353
+ fit: sharp.fit.inside,
354
+ ...compression.inside
355
+ };
356
+ }
357
+ _data = await sharp(data)
358
+ .resize(opts)
359
+ .withMetadata(Boolean(imageOptions?.keepMetadata))
360
+ // .jpeg({ quality: 80 })
361
+ .toBuffer();
362
+ }
363
+ else if (!imageOptions?.keepMetadata) {
364
+ /**
365
+ * Remove exif
366
+ */
367
+ // const metadata = await simg.metadata();
368
+ // const simg = await sharp(data);
369
+ _data = await sharp(data).clone().withMetadata({
370
+ exif: {}
371
+ })
372
+ .toBuffer();
373
+ }
374
+ }
375
+ const res = await this.upload(_data, name, content_type);
376
+ return res;
377
+ };
576
378
  async getFileS3URL(fileName, expiresInSeconds = 30 * 60) {
577
379
  const params = {
578
380
  Bucket: this.config.bucket,
@@ -581,18 +383,221 @@ class FileManager {
581
383
  };
582
384
  return await this.s3Client?.getSignedUrlPromise("getObject", params);
583
385
  }
386
+ parseSQLIdentifier = async (name) => (0, exports.asSQLIdentifier)(name, this.prostgles.db); // this.prostgles.dbo.sql<"value">("select format('%I', $1)", [name], { returnType: "value" } )
387
+ getColInfo = (args) => {
388
+ const { colName, tableName } = args;
389
+ const tableConfig = this.prostgles?.opts.fileTable?.referencedTables?.[tableName];
390
+ const isReferencingFileTable = this.dbo[tableName]?.columns?.some(c => c.name === colName && c.references && c.references?.some(({ ftable }) => ftable === this.tableName));
391
+ if (isReferencingFileTable) {
392
+ if (tableConfig && typeof tableConfig !== "string") {
393
+ return tableConfig.referenceColumns[colName];
394
+ }
395
+ return { acceptedContent: "*" };
396
+ }
397
+ return undefined;
398
+ };
399
+ init = async (prg) => {
400
+ this.prostgles = prg;
401
+ // const { dbo, db, opts } = prg;
402
+ const { fileTable } = prg.opts;
403
+ if (!fileTable)
404
+ throw "fileTable missing";
405
+ const { tableName = "media", referencedTables = {} } = fileTable;
406
+ this.tableName = tableName;
407
+ const maxBfSizeMB = (prg.opts.io?.engine?.opts?.maxHttpBufferSize || 1e6) / 1e6;
408
+ console.log(`Prostgles: Initiated file manager. Max allowed file size: ${maxBfSizeMB}MB (maxHttpBufferSize = 1e6). To increase this set maxHttpBufferSize in socket.io server init options`);
409
+ // throw `this.db.tx(d => do everything in a transaction pls!!!!`;
410
+ const canCreate = await (0, runSQL_1.canCreateTables)(this.db);
411
+ const runQuery = (q) => {
412
+ if (!canCreate)
413
+ throw "File table creation failed. Your postgres user does not have CREATE table privileges";
414
+ return this.db.any(q);
415
+ };
416
+ /**
417
+ * 1. Create media table
418
+ */
419
+ if (!this.dbo[tableName]) {
420
+ console.log(`Creating fileTable ${(0, prostgles_types_1.asName)(tableName)} ...`);
421
+ await runQuery(`CREATE EXTENSION IF NOT EXISTS pgcrypto `);
422
+ await runQuery(`CREATE TABLE IF NOT EXISTS ${(0, prostgles_types_1.asName)(tableName)} (
423
+ url TEXT NOT NULL,
424
+ original_name TEXT NOT NULL,
425
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
426
+ name TEXT NOT NULL,
427
+ extension TEXT NOT NULL,
428
+ content_type TEXT NOT NULL,
429
+ content_length BIGINT NOT NULL DEFAULT 0,
430
+ added TIMESTAMP NOT NULL DEFAULT NOW(),
431
+ description TEXT,
432
+ s3_url TEXT,
433
+ signed_url TEXT,
434
+ signed_url_expires BIGINT,
435
+ etag TEXT,
436
+ deleted BIGINT,
437
+ deleted_from_storage BIGINT,
438
+ UNIQUE(id),
439
+ UNIQUE(name)
440
+ )`);
441
+ console.log(`Created fileTable ${(0, prostgles_types_1.asName)(tableName)}`);
442
+ await prg.refreshDBO();
443
+ }
444
+ /**
445
+ * 2. Create media lookup tables
446
+ */
447
+ await Promise.all((0, prostgles_types_1.getKeys)(referencedTables).map(async (refTable) => {
448
+ if (!this.dbo[refTable])
449
+ throw `Referenced table (${refTable}) from fileTable.referencedTables prostgles init config does not exist`;
450
+ const cols = await this.dbo[refTable].getColumns();
451
+ const tableConfig = referencedTables[refTable];
452
+ if (typeof tableConfig !== "string") {
453
+ for await (const colName of (0, prostgles_types_1.getKeys)(tableConfig.referenceColumns)) {
454
+ const existingCol = cols.find(c => c.name === colName);
455
+ if (existingCol) {
456
+ if (existingCol.references?.some(({ ftable }) => ftable === tableName)) {
457
+ // All ok
458
+ }
459
+ else {
460
+ if (existingCol.udt_name === "uuid") {
461
+ try {
462
+ const query = `ALTER TABLE ${(0, prostgles_types_1.asName)(refTable)} ADD FOREIGN KEY (${(0, prostgles_types_1.asName)(colName)}) REFERENCES ${(0, prostgles_types_1.asName)(tableName)} (id);`;
463
+ console.log(`Referenced file column ${refTable} (${colName}) exists but is not referencing file table. Trying to add REFERENCE constraing...\n${query}`);
464
+ await runQuery(query);
465
+ console.log("SUCCESS: " + query);
466
+ }
467
+ catch (e) {
468
+ console.error(`Could not add constraing. Err: ${e instanceof Error ? e.message : JSON.stringify(e)}`);
469
+ }
470
+ }
471
+ else {
472
+ console.error(`Referenced file column ${refTable} (${colName}) exists but is not of required type (UUID). Choose a different column name or ALTER the existing column to match the type and the data found in file table ${tableName}(id)`);
473
+ }
474
+ }
475
+ }
476
+ else {
477
+ try {
478
+ const query = `ALTER TABLE ${(0, prostgles_types_1.asName)(refTable)} ADD COLUMN ${(0, prostgles_types_1.asName)(colName)} UUID REFERENCES ${(0, prostgles_types_1.asName)(tableName)} (id);`;
479
+ console.log(`Creating referenced file column ${refTable} (${colName})...\n${query}`);
480
+ await runQuery(query);
481
+ console.log("SUCCESS: " + query);
482
+ }
483
+ catch (e) {
484
+ console.error(`FAILED. Err: ${e instanceof Error ? e.message : JSON.stringify(e)}`);
485
+ }
486
+ }
487
+ }
488
+ }
489
+ else {
490
+ const lookupTableName = await this.parseSQLIdentifier(`prostgles_lookup_${tableName}_${refTable}`);
491
+ const pKeyFields = cols.filter(f => f.is_pkey);
492
+ if (pKeyFields.length !== 1) {
493
+ console.error(`Could not make link table for ${refTable}. ${pKeyFields} must have exactly one primary key column. Current pkeys: ${pKeyFields.map(f => f.name)}`);
494
+ }
495
+ const pkField = pKeyFields[0];
496
+ const refType = referencedTables[refTable];
497
+ if (!this.dbo[lookupTableName]) {
498
+ // if(!(await dbo[lookupTableName].count())) await db.any(`DROP TABLE IF EXISTS ${lookupTableName};`);
499
+ const action = ` (${tableName} <-> ${refTable}) join table ${lookupTableName}`; // PRIMARY KEY
500
+ const query = `
501
+ CREATE TABLE ${lookupTableName} (
502
+ foreign_id ${pkField.udt_name} ${refType === "one" ? " PRIMARY KEY " : ""} REFERENCES ${(0, prostgles_types_1.asName)(refTable)}(${(0, prostgles_types_1.asName)(pkField.name)}),
503
+ media_id UUID NOT NULL REFERENCES ${(0, prostgles_types_1.asName)(tableName)}(id)
504
+ )
505
+ `;
506
+ console.log(`Creating ${action} ...`, lookupTableName);
507
+ await runQuery(query);
508
+ console.log(`Created ${action}`);
509
+ }
510
+ else {
511
+ const cols = await this.dbo[lookupTableName].getColumns();
512
+ const badCols = cols.filter(c => !c.references);
513
+ await Promise.all(badCols.map(async (badCol) => {
514
+ console.error(`Prostgles: media ${lookupTableName} joining table has lost a reference constraint for column ${badCol.name}.` +
515
+ ` This may have been caused by a DROP TABLE ... CASCADE.`);
516
+ let q = ` ALTER TABLE ${(0, prostgles_types_1.asName)(lookupTableName)} ADD FOREIGN KEY (${badCol.name}) `;
517
+ console.log("Trying to add the missing constraint back");
518
+ if (badCol.name === "foreign_id") {
519
+ q += `REFERENCES ${(0, prostgles_types_1.asName)(refTable)}(${(0, prostgles_types_1.asName)(pkField.name)}) `;
520
+ }
521
+ else if (badCol.name === "media_id") {
522
+ q += `REFERENCES ${(0, prostgles_types_1.asName)(tableName)}(id) `;
523
+ }
524
+ if (q) {
525
+ try {
526
+ await runQuery(q);
527
+ console.log("Added missing constraint back");
528
+ }
529
+ catch (e) {
530
+ console.error("Failed to add missing constraint", e);
531
+ }
532
+ }
533
+ }));
534
+ }
535
+ }
536
+ await prg.refreshDBO();
537
+ return true;
538
+ }));
539
+ /**
540
+ * 4. Serve media through express
541
+ */
542
+ const { fileServeRoute = `/${tableName}`, expressApp: app } = fileTable;
543
+ if (fileServeRoute.endsWith("/")) {
544
+ throw `fileServeRoute must not end with a '/'`;
545
+ }
546
+ this.fileRoute = fileServeRoute;
547
+ if (app) {
548
+ app.get(this.fileRouteExpress, async (req, res) => {
549
+ if (!this.dbo[tableName]) {
550
+ res.status(500).json({ err: `Internal error: media table (${tableName}) not valid` });
551
+ return false;
552
+ }
553
+ const mediaTable = this.dbo[tableName];
554
+ try {
555
+ const { name } = req.params;
556
+ if (typeof name !== "string" || !name)
557
+ throw "Invalid media name";
558
+ const media = await mediaTable.findOne({ name }, { select: { id: 1, name: 1, signed_url: 1, signed_url_expires: 1, content_type: 1 } }, { httpReq: req });
559
+ if (!media) {
560
+ /**
561
+ * Redirect to login !??
562
+ */
563
+ // const mediaExists = await mediaTable.count({ name });
564
+ // if(mediaExists && this.prostgles.authHandler){
565
+ // } else {
566
+ // throw "Invalid media";
567
+ // }
568
+ throw "Invalid media";
569
+ }
570
+ if (this.s3Client) {
571
+ let url = media.signed_url;
572
+ const expires = +(media.signed_url_expires || 0);
573
+ const EXPIRES = Date.now() + HOUR;
574
+ if (!url || expires < EXPIRES) {
575
+ url = await this.getFileS3URL(media.name, 60 * 60);
576
+ await mediaTable.update({ name }, { signed_url: url, signed_url_expires: EXPIRES });
577
+ }
578
+ res.redirect(url);
579
+ }
580
+ else {
581
+ const pth = `${this.config.localFolderPath}/${media.name}`;
582
+ if (!fs.existsSync(pth)) {
583
+ throw new Error("File not found");
584
+ }
585
+ res.contentType(media.content_type);
586
+ res.sendFile(pth);
587
+ }
588
+ }
589
+ catch (e) {
590
+ console.log(e);
591
+ res.status(404).json({ err: "Invalid/missing media" });
592
+ }
593
+ });
594
+ }
595
+ };
596
+ destroy = () => {
597
+ (0, exports.removeExpressRoute)(this.prostgles?.opts.fileTable?.expressApp, [this.fileRouteExpress]);
598
+ };
584
599
  }
585
600
  exports.default = FileManager;
586
- _a = FileManager;
587
- FileManager.testCredentials = async (accessKeyId, secretAccessKey) => {
588
- const sts = new aws_sdk_2.default.STS();
589
- aws_sdk_2.default.config.credentials = {
590
- accessKeyId,
591
- secretAccessKey
592
- };
593
- const ident = await sts.getCallerIdentity({}).promise();
594
- return ident;
595
- };
596
601
  const removeExpressRoute = (app, routePaths) => {
597
602
  const routes = app?._router?.stack;
598
603
  if (routes) {