prostgles-server 4.2.159 → 4.2.161
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.
- package/dist/Auth/setEmailProvider.js +2 -2
- package/dist/Auth/setEmailProvider.js.map +1 -1
- package/lib/Auth/AuthHandler.ts +436 -0
- package/lib/Auth/AuthTypes.ts +280 -0
- package/lib/Auth/getSafeReturnURL.ts +35 -0
- package/lib/Auth/sendEmail.ts +83 -0
- package/lib/Auth/setAuthProviders.ts +128 -0
- package/lib/Auth/setEmailProvider.ts +85 -0
- package/lib/Auth/setupAuthRoutes.ts +161 -0
- package/lib/DBEventsManager.ts +178 -0
- package/lib/DBSchemaBuilder.ts +225 -0
- package/lib/DboBuilder/DboBuilder.ts +319 -0
- package/lib/DboBuilder/DboBuilderTypes.ts +361 -0
- package/lib/DboBuilder/QueryBuilder/Functions.ts +1153 -0
- package/lib/DboBuilder/QueryBuilder/QueryBuilder.ts +288 -0
- package/lib/DboBuilder/QueryBuilder/getJoinQuery.ts +263 -0
- package/lib/DboBuilder/QueryBuilder/getNewQuery.ts +271 -0
- package/lib/DboBuilder/QueryBuilder/getSelectQuery.ts +136 -0
- package/lib/DboBuilder/QueryBuilder/prepareHaving.ts +22 -0
- package/lib/DboBuilder/QueryStreamer.ts +250 -0
- package/lib/DboBuilder/TableHandler/DataValidator.ts +428 -0
- package/lib/DboBuilder/TableHandler/TableHandler.ts +205 -0
- package/lib/DboBuilder/TableHandler/delete.ts +115 -0
- package/lib/DboBuilder/TableHandler/insert.ts +183 -0
- package/lib/DboBuilder/TableHandler/insertTest.ts +78 -0
- package/lib/DboBuilder/TableHandler/onDeleteFromFileTable.ts +62 -0
- package/lib/DboBuilder/TableHandler/runInsertUpdateQuery.ts +134 -0
- package/lib/DboBuilder/TableHandler/update.ts +126 -0
- package/lib/DboBuilder/TableHandler/updateBatch.ts +49 -0
- package/lib/DboBuilder/TableHandler/updateFile.ts +48 -0
- package/lib/DboBuilder/TableHandler/upsert.ts +34 -0
- package/lib/DboBuilder/ViewHandler/ViewHandler.ts +393 -0
- package/lib/DboBuilder/ViewHandler/count.ts +38 -0
- package/lib/DboBuilder/ViewHandler/find.ts +153 -0
- package/lib/DboBuilder/ViewHandler/getExistsCondition.ts +73 -0
- package/lib/DboBuilder/ViewHandler/getExistsFilters.ts +74 -0
- package/lib/DboBuilder/ViewHandler/getInfo.ts +32 -0
- package/lib/DboBuilder/ViewHandler/getTableJoinQuery.ts +84 -0
- package/lib/DboBuilder/ViewHandler/parseComplexFilter.ts +96 -0
- package/lib/DboBuilder/ViewHandler/parseFieldFilter.ts +105 -0
- package/lib/DboBuilder/ViewHandler/parseJoinPath.ts +208 -0
- package/lib/DboBuilder/ViewHandler/prepareSortItems.ts +163 -0
- package/lib/DboBuilder/ViewHandler/prepareWhere.ts +90 -0
- package/lib/DboBuilder/ViewHandler/size.ts +37 -0
- package/lib/DboBuilder/ViewHandler/subscribe.ts +118 -0
- package/lib/DboBuilder/ViewHandler/validateViewRules.ts +70 -0
- package/lib/DboBuilder/dboBuilderUtils.ts +222 -0
- package/lib/DboBuilder/getColumns.ts +114 -0
- package/lib/DboBuilder/getCondition.ts +201 -0
- package/lib/DboBuilder/getSubscribeRelatedTables.ts +190 -0
- package/lib/DboBuilder/getTablesForSchemaPostgresSQL.ts +426 -0
- package/lib/DboBuilder/insertNestedRecords.ts +355 -0
- package/lib/DboBuilder/parseUpdateRules.ts +187 -0
- package/lib/DboBuilder/prepareShortestJoinPaths.ts +186 -0
- package/lib/DboBuilder/runSQL.ts +182 -0
- package/lib/DboBuilder/runTransaction.ts +50 -0
- package/lib/DboBuilder/sqlErrCodeToMsg.ts +254 -0
- package/lib/DboBuilder/uploadFile.ts +69 -0
- package/lib/Event_Trigger_Tags.ts +118 -0
- package/lib/FileManager/FileManager.ts +358 -0
- package/lib/FileManager/getValidatedFileType.ts +69 -0
- package/lib/FileManager/initFileManager.ts +187 -0
- package/lib/FileManager/upload.ts +62 -0
- package/lib/FileManager/uploadStream.ts +79 -0
- package/lib/Filtering.ts +463 -0
- package/lib/JSONBValidation/validate_jsonb_schema_sql.ts +502 -0
- package/lib/JSONBValidation/validation.ts +143 -0
- package/lib/Logging.ts +127 -0
- package/lib/PostgresNotifListenManager.ts +143 -0
- package/lib/Prostgles.ts +485 -0
- package/lib/ProstglesTypes.ts +196 -0
- package/lib/PubSubManager/PubSubManager.ts +609 -0
- package/lib/PubSubManager/addSub.ts +138 -0
- package/lib/PubSubManager/addSync.ts +141 -0
- package/lib/PubSubManager/getCreatePubSubManagerError.ts +72 -0
- package/lib/PubSubManager/getPubSubManagerInitQuery.ts +662 -0
- package/lib/PubSubManager/initPubSubManager.ts +79 -0
- package/lib/PubSubManager/notifListener.ts +173 -0
- package/lib/PubSubManager/orphanTriggerCheck.ts +70 -0
- package/lib/PubSubManager/pushSubData.ts +55 -0
- package/lib/PublishParser/PublishParser.ts +162 -0
- package/lib/PublishParser/getFileTableRules.ts +124 -0
- package/lib/PublishParser/getSchemaFromPublish.ts +141 -0
- package/lib/PublishParser/getTableRulesWithoutFileTable.ts +177 -0
- package/lib/PublishParser/publishTypesAndUtils.ts +399 -0
- package/lib/RestApi.ts +127 -0
- package/lib/SchemaWatch/SchemaWatch.ts +90 -0
- package/lib/SchemaWatch/createSchemaWatchEventTrigger.ts +3 -0
- package/lib/SchemaWatch/getValidatedWatchSchemaType.ts +45 -0
- package/lib/SchemaWatch/getWatchSchemaTagList.ts +27 -0
- package/lib/SyncReplication.ts +557 -0
- package/lib/TableConfig/TableConfig.ts +468 -0
- package/lib/TableConfig/getColumnDefinitionQuery.ts +111 -0
- package/lib/TableConfig/getConstraintDefinitionQueries.ts +95 -0
- package/lib/TableConfig/getFutureTableSchema.ts +64 -0
- package/lib/TableConfig/getPGIndexes.ts +53 -0
- package/lib/TableConfig/getTableColumnQueries.ts +129 -0
- package/lib/TableConfig/initTableConfig.ts +326 -0
- package/lib/index.ts +13 -0
- package/lib/initProstgles.ts +319 -0
- package/lib/onSocketConnected.ts +102 -0
- package/lib/runClientRequest.ts +129 -0
- package/lib/shortestPath.ts +122 -0
- package/lib/typeTests/DBoGenerated.d.ts +320 -0
- package/lib/typeTests/dboTypeCheck.ts +81 -0
- package/lib/utils.ts +15 -0
- package/package.json +1 -1
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
|
|
2
|
+
import * as fs from 'fs';
|
|
3
|
+
import * as stream from 'stream';
|
|
4
|
+
|
|
5
|
+
// import * as sharp from "sharp";
|
|
6
|
+
import checkDiskSpace from 'check-disk-space';
|
|
7
|
+
|
|
8
|
+
import { DB, DBHandlerServer, Prostgles } from '../Prostgles';
|
|
9
|
+
import { ALLOWED_CONTENT_TYPE, ALLOWED_EXTENSION, CONTENT_TYPE_TO_EXT, getKeys, isDefined, ValidatedColumnInfo } from 'prostgles-types';
|
|
10
|
+
|
|
11
|
+
import * as path from "path";
|
|
12
|
+
import { initFileManager } from "./initFileManager";
|
|
13
|
+
import { getValidatedFileType } from "./getValidatedFileType";
|
|
14
|
+
import { upload } from "./upload";
|
|
15
|
+
import { uploadStream } from "./uploadStream";
|
|
16
|
+
import { ExpressApp } from "../RestApi";
|
|
17
|
+
|
|
18
|
+
export const HOUR = 3600 * 1000;
|
|
19
|
+
|
|
20
|
+
export const asSQLIdentifier = async (name: string, db: DB): Promise<string> => {
|
|
21
|
+
return (await db.one("select format('%I', $1) as name", [name]))?.name
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type OnProgress = (progress: { total: number; loaded: number; }) => void
|
|
25
|
+
|
|
26
|
+
export type ImageOptions = {
|
|
27
|
+
keepMetadata?: boolean;
|
|
28
|
+
compression?:
|
|
29
|
+
/**
|
|
30
|
+
* Will resize image maintaing scale ratio
|
|
31
|
+
*/
|
|
32
|
+
| { inside: { width: number; height: number } }
|
|
33
|
+
| { contain:
|
|
34
|
+
| { width: number }
|
|
35
|
+
| { height: number }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type UploadedCloudFile = {
|
|
40
|
+
cloud_url: string;
|
|
41
|
+
etag: string;
|
|
42
|
+
content_length: number;
|
|
43
|
+
};
|
|
44
|
+
export type FileUploadArgs = {
|
|
45
|
+
fileName: string;
|
|
46
|
+
contentType: string;
|
|
47
|
+
file: string | Buffer | stream.PassThrough;
|
|
48
|
+
onFinish: (...args: [error: Error, result: undefined] | [error: undefined, result: UploadedCloudFile]) => void;
|
|
49
|
+
onProgress?: (bytesUploaded: number) => void;
|
|
50
|
+
}
|
|
51
|
+
export type CloudClient = {
|
|
52
|
+
upload: (file: FileUploadArgs) => Promise<void>;
|
|
53
|
+
downloadAsStream: (name: string) => Promise<stream.Readable>;
|
|
54
|
+
delete: (fileName: string) => Promise<void>;
|
|
55
|
+
getSignedUrlForDownload: (fileName: string, expiresInSeconds: number) => Promise<string>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type LocalConfig = {
|
|
59
|
+
/**
|
|
60
|
+
* example: path.join(__dirname+'/media')
|
|
61
|
+
* note that this location will be relative to the compiled file location
|
|
62
|
+
*/
|
|
63
|
+
localFolderPath: string;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Minimum amount of free bytes available to allow saving files
|
|
67
|
+
* Defaults to 100MB
|
|
68
|
+
*/
|
|
69
|
+
minFreeBytes?: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type UploadItem = {
|
|
73
|
+
name: string;
|
|
74
|
+
content_type: string;
|
|
75
|
+
data: Buffer;
|
|
76
|
+
extension: string;
|
|
77
|
+
};
|
|
78
|
+
export type UploadedItem = {
|
|
79
|
+
/**
|
|
80
|
+
* Url that is passed to client
|
|
81
|
+
*/
|
|
82
|
+
url: string;
|
|
83
|
+
filePath?: string;
|
|
84
|
+
etag: string;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Cloud url of the resource
|
|
88
|
+
*/
|
|
89
|
+
cloud_url?: string;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Total uploaded file size in bytes
|
|
93
|
+
*/
|
|
94
|
+
content_length: number;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
export class FileManager {
|
|
98
|
+
|
|
99
|
+
cloudClient?: CloudClient;
|
|
100
|
+
|
|
101
|
+
config: CloudClient | LocalConfig;
|
|
102
|
+
imageOptions?: ImageOptions;
|
|
103
|
+
|
|
104
|
+
prostgles?: Prostgles;
|
|
105
|
+
get dbo(): DBHandlerServer {
|
|
106
|
+
if(!this.prostgles?.dbo) {
|
|
107
|
+
throw "this.prostgles.dbo missing";
|
|
108
|
+
}
|
|
109
|
+
return this.prostgles.dbo
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
get db(): DB {
|
|
113
|
+
if(!this.prostgles?.db) throw "this.prostgles.db missing"
|
|
114
|
+
return this.prostgles.db
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
tableName?: string;
|
|
118
|
+
|
|
119
|
+
fileRoute?: string;
|
|
120
|
+
get fileRouteExpress (){
|
|
121
|
+
return this.fileRoute + "/:name";
|
|
122
|
+
}
|
|
123
|
+
private checkInterval?: NodeJS.Timeout;
|
|
124
|
+
|
|
125
|
+
constructor(config: FileManager["config"], imageOptions?: ImageOptions){
|
|
126
|
+
this.config = config;
|
|
127
|
+
this.imageOptions = imageOptions;
|
|
128
|
+
|
|
129
|
+
if("upload" in config){
|
|
130
|
+
this.cloudClient = config;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const fullConfig = this.prostgles?.opts.fileTable;
|
|
134
|
+
if(fullConfig?.delayedDelete){
|
|
135
|
+
this.checkInterval = setInterval(async () => {
|
|
136
|
+
const fileTable = fullConfig.tableName;
|
|
137
|
+
const daysDelay = fullConfig.delayedDelete?.deleteAfterNDays ?? 0;
|
|
138
|
+
if(fileTable && this.dbo[fileTable]?.delete && daysDelay){
|
|
139
|
+
const filesToDelete = await this.dbo[fileTable]?.find?.({ deleted_from_storage: null, deleted: { ">": Date.now() - (daysDelay * HOUR * 24) } }) ?? [];
|
|
140
|
+
for await(const file of filesToDelete){
|
|
141
|
+
await this.deleteFile(file.name)
|
|
142
|
+
}
|
|
143
|
+
} else {
|
|
144
|
+
console.error("FileManager checkInterval delayedDelete FAIL: Could not access file table tableHandler.delete()")
|
|
145
|
+
}
|
|
146
|
+
}, Math.max(10000, (fullConfig.delayedDelete.checkIntervalHours || 0) * HOUR))
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async getFileStream(name: string): Promise<stream.Readable> {
|
|
151
|
+
if(this.cloudClient){
|
|
152
|
+
return this.cloudClient.downloadAsStream(name)
|
|
153
|
+
} else if("localFolderPath" in this.config){
|
|
154
|
+
const filePath = path.resolve(`${this.config.localFolderPath}/${name}`);
|
|
155
|
+
if(!fs.existsSync(filePath)){
|
|
156
|
+
throw `File ${filePath} could not be found`;
|
|
157
|
+
}
|
|
158
|
+
return fs.createReadStream(filePath, { encoding: undefined })
|
|
159
|
+
} else throw new Error("Not expected");
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async deleteFile(name: string) {
|
|
163
|
+
if(this.cloudClient){
|
|
164
|
+
const res = await this.cloudClient?.delete(name);
|
|
165
|
+
return res;
|
|
166
|
+
} else if("localFolderPath" in this.config){
|
|
167
|
+
const path = `${this.config.localFolderPath}/${name}`;
|
|
168
|
+
if(!fs.existsSync(path)){
|
|
169
|
+
throw `File ${path} could not be found`;
|
|
170
|
+
}
|
|
171
|
+
fs.unlinkSync(path);
|
|
172
|
+
if(fs.existsSync(path)) throw new Error("Could not delete file");
|
|
173
|
+
}
|
|
174
|
+
return true
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
getValidatedFileType = getValidatedFileType.bind(this);
|
|
178
|
+
|
|
179
|
+
getLocalFileUrl = (name: string) => this.fileRoute? `${this.fileRoute}/${name}` : "";
|
|
180
|
+
|
|
181
|
+
checkFreeSpace = async (folderPath: string, fileSize = 0) => {
|
|
182
|
+
if(!this.cloudClient && "localFolderPath" in this.config) {
|
|
183
|
+
const { minFreeBytes = 1.048e6 } = this.config;
|
|
184
|
+
const required = Math.max(fileSize, minFreeBytes)
|
|
185
|
+
if(required){
|
|
186
|
+
const diskSpace = await checkDiskSpace(folderPath);
|
|
187
|
+
if(diskSpace.free < required){
|
|
188
|
+
const err = `There is not enough space on the server to save files.\nTotal: ${bytesToSize(diskSpace.size)} \nRemaning: ${bytesToSize(diskSpace.free)} \nRequired: ${bytesToSize(required)}`
|
|
189
|
+
throw new Error(err);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
uploadStream = uploadStream.bind(this);
|
|
196
|
+
|
|
197
|
+
upload = upload.bind(this);
|
|
198
|
+
|
|
199
|
+
uploadAsMedia = async (params: {
|
|
200
|
+
item: UploadItem;
|
|
201
|
+
allowedExtensions?: Array<ALLOWED_EXTENSION>;
|
|
202
|
+
dissallowedExtensions?: Array<ALLOWED_EXTENSION>;
|
|
203
|
+
imageOptions?: ImageOptions;
|
|
204
|
+
}): Promise<UploadedItem> => {
|
|
205
|
+
const { item, imageOptions } = params;
|
|
206
|
+
const { name, data, content_type, extension } = item;
|
|
207
|
+
if(!data) throw "No file provided";
|
|
208
|
+
if(!name || typeof name !== "string") throw "Expecting a string name";
|
|
209
|
+
|
|
210
|
+
// const type = await this.getMIME(data, name, allowedExtensions, dissallowedExtensions);
|
|
211
|
+
|
|
212
|
+
const _data = data;
|
|
213
|
+
|
|
214
|
+
/** Resize/compress/remove exif from photos */
|
|
215
|
+
// if(content_type.startsWith("image") && extension.toLowerCase() !== "gif"){
|
|
216
|
+
|
|
217
|
+
// const compression = imageOptions?.compression
|
|
218
|
+
// if(compression){
|
|
219
|
+
// console.log("Resizing image")
|
|
220
|
+
// let opts;
|
|
221
|
+
// if("contain" in compression){
|
|
222
|
+
// opts = {
|
|
223
|
+
// fit: sharp.fit.contain,
|
|
224
|
+
// ...compression.contain
|
|
225
|
+
// }
|
|
226
|
+
// } else if("inside" in compression){
|
|
227
|
+
// opts = {
|
|
228
|
+
// fit: sharp.fit.inside,
|
|
229
|
+
// ...compression.inside
|
|
230
|
+
// }
|
|
231
|
+
// }
|
|
232
|
+
// _data = await sharp(data)
|
|
233
|
+
// .resize(opts as any)
|
|
234
|
+
// .withMetadata(Boolean(imageOptions?.keepMetadata) as any)
|
|
235
|
+
// // .jpeg({ quality: 80 })
|
|
236
|
+
// .toBuffer()
|
|
237
|
+
// } else if(!imageOptions?.keepMetadata) {
|
|
238
|
+
// /**
|
|
239
|
+
// * Remove exif
|
|
240
|
+
// */
|
|
241
|
+
// // const metadata = await simg.metadata();
|
|
242
|
+
// // const simg = await sharp(data);
|
|
243
|
+
|
|
244
|
+
// _data = await sharp(data).clone().withMetadata({
|
|
245
|
+
// exif: {}
|
|
246
|
+
// })
|
|
247
|
+
// .toBuffer()
|
|
248
|
+
// }
|
|
249
|
+
// }
|
|
250
|
+
|
|
251
|
+
const res = await this.upload(_data, name, content_type);
|
|
252
|
+
|
|
253
|
+
return res
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async getFileCloudDownloadURL(fileName: string, expiresInSecondsRaw: number = 30 * 60){
|
|
257
|
+
const expiresInSeconds = Math.max(1, Math.round(expiresInSecondsRaw));
|
|
258
|
+
return await this.cloudClient?.getSignedUrlForDownload(fileName, expiresInSeconds);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
parseSQLIdentifier = async (name: string ) => asSQLIdentifier(name, this.prostgles!.db!);// this.prostgles.dbo.sql<"value">("select format('%I', $1)", [name], { returnType: "value" } )
|
|
262
|
+
|
|
263
|
+
getColInfo = (args: { tableName: string; colName: string }): ValidatedColumnInfo["file"] | undefined => {
|
|
264
|
+
const { colName, tableName } = args;
|
|
265
|
+
const tableConfig = this.prostgles?.opts.fileTable?.referencedTables?.[tableName];
|
|
266
|
+
const isReferencingFileTable = this.dbo[tableName]?.columns?.some(c => c.name === colName && c.references && c.references?.some(({ ftable }) => ftable === this.tableName ));
|
|
267
|
+
const allowAllFiles = { acceptedContent: "*" } as const;
|
|
268
|
+
if(isReferencingFileTable){
|
|
269
|
+
if(tableConfig && typeof tableConfig !== "string"){
|
|
270
|
+
return tableConfig.referenceColumns[colName] ?? allowAllFiles;
|
|
271
|
+
}
|
|
272
|
+
return allowAllFiles;
|
|
273
|
+
}
|
|
274
|
+
return undefined;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
init = initFileManager.bind(this);
|
|
278
|
+
|
|
279
|
+
destroy = () => {
|
|
280
|
+
removeExpressRoute(this.prostgles?.opts.fileTable?.expressApp, [this.fileRouteExpress]);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export const removeExpressRoute = (app: ExpressApp | undefined, routePaths: (string | undefined)[]) => {
|
|
285
|
+
|
|
286
|
+
const routes = app?._router?.stack;
|
|
287
|
+
if(routes){
|
|
288
|
+
routes.forEach((route, i) => {
|
|
289
|
+
if(routePaths.filter(isDefined).includes(route.route?.path as any)){
|
|
290
|
+
routes.splice(i, 1);
|
|
291
|
+
}
|
|
292
|
+
})
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export const removeExpressRouteByName = (app: ExpressApp | undefined, name: string) => {
|
|
297
|
+
const routes = app?._router?.stack;
|
|
298
|
+
if(routes){
|
|
299
|
+
routes.forEach((route, i) => {
|
|
300
|
+
if(route.name === name){
|
|
301
|
+
routes.splice(i, 1);
|
|
302
|
+
}
|
|
303
|
+
})
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export const getFileTypeFromFilename = (fileName: string): { mime: ALLOWED_CONTENT_TYPE; ext: ALLOWED_EXTENSION | string } | undefined => {
|
|
308
|
+
|
|
309
|
+
const nameParts = fileName.split(".");
|
|
310
|
+
|
|
311
|
+
if(nameParts.length < 2) return undefined;
|
|
312
|
+
|
|
313
|
+
const nameExt = nameParts.at(-1)!.toLowerCase(),
|
|
314
|
+
mime = getKeys(CONTENT_TYPE_TO_EXT).find(k => (CONTENT_TYPE_TO_EXT[k] as readonly string[]).includes(nameExt));
|
|
315
|
+
|
|
316
|
+
if(!mime) return undefined;
|
|
317
|
+
|
|
318
|
+
return {
|
|
319
|
+
mime,
|
|
320
|
+
ext: nameExt as ALLOWED_EXTENSION,
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// const fileType = require("file-type");
|
|
325
|
+
// const res = await fileType.fromBuffer(typeof file === "string"? Buffer.from(file, 'utf8') : file);
|
|
326
|
+
|
|
327
|
+
export const getFileType = async (file: Buffer | string, fileName: string): Promise<{ mime: ALLOWED_CONTENT_TYPE; ext: ALLOWED_EXTENSION }> => {
|
|
328
|
+
|
|
329
|
+
const { fileTypeFromBuffer } = await (eval('import("file-type")') as Promise<typeof import('file-type')>);
|
|
330
|
+
|
|
331
|
+
const fileNameMime = getFileTypeFromFilename(fileName);
|
|
332
|
+
if(!fileNameMime?.ext) throw new Error("File name must contain extenion")
|
|
333
|
+
const res = await fileTypeFromBuffer(typeof file === "string"? Buffer.from(file, 'utf8') : file);
|
|
334
|
+
|
|
335
|
+
if(!res) {
|
|
336
|
+
|
|
337
|
+
/* Set correct/missing extension */
|
|
338
|
+
const nameExt = fileNameMime?.ext;
|
|
339
|
+
if(["xml", "txt", "csv", "tsv", "svg", "sql"].includes(nameExt) && fileNameMime.mime){
|
|
340
|
+
return fileNameMime as any;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
throw new Error("Could not get the file type from file buffer");
|
|
344
|
+
} else {
|
|
345
|
+
|
|
346
|
+
if(!res.ext || fileNameMime?.ext.toLowerCase() !== res.ext.toLowerCase()){
|
|
347
|
+
throw new Error(`There is a mismatch between file name extension and actual buffer extension: ${fileNameMime?.ext } vs ${res.ext}`)
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
return res as any;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export function bytesToSize(bytes: number) {
|
|
354
|
+
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
|
355
|
+
if (bytes == 0) return '0 Byte';
|
|
356
|
+
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)) + "");
|
|
357
|
+
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
|
|
358
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { ALLOWED_CONTENT_TYPE, ALLOWED_EXTENSION, CONTENT_TYPE_TO_EXT, getKeys, isObject } from "prostgles-types";
|
|
2
|
+
import { parseFieldFilter } from "../DboBuilder/ViewHandler/parseFieldFilter";
|
|
3
|
+
import { FileManager, getFileType, getFileTypeFromFilename } from "./FileManager";
|
|
4
|
+
|
|
5
|
+
type Args = {
|
|
6
|
+
file: Buffer | string;
|
|
7
|
+
fileName: string;
|
|
8
|
+
colName?: string;
|
|
9
|
+
tableName?: string;
|
|
10
|
+
};
|
|
11
|
+
export async function getValidatedFileType(this: FileManager, args: Args): Promise<{
|
|
12
|
+
mime: string | ALLOWED_CONTENT_TYPE;
|
|
13
|
+
ext: string | ALLOWED_EXTENSION;
|
|
14
|
+
|
|
15
|
+
/** File name is not returned because we fail if the extensions do not match */
|
|
16
|
+
// fileName: string;
|
|
17
|
+
}> {
|
|
18
|
+
const { file, fileName, tableName, colName } = args;
|
|
19
|
+
const config = this.prostgles?.opts.fileTable;
|
|
20
|
+
if(!config) throw new Error("File table config missing");
|
|
21
|
+
|
|
22
|
+
const buffer = typeof file === "string"? Buffer.from(file, 'utf8') : file;
|
|
23
|
+
|
|
24
|
+
const result = await getFileTypeFromFilename(fileName);
|
|
25
|
+
if(tableName && colName){
|
|
26
|
+
const tableConfig = config.referencedTables?.[tableName];
|
|
27
|
+
|
|
28
|
+
if(tableConfig && isObject(tableConfig) && tableConfig.referenceColumns[colName]){
|
|
29
|
+
const colConfig = tableConfig.referenceColumns[colName]!;
|
|
30
|
+
if(colConfig.maxFileSizeMB){
|
|
31
|
+
const actualBufferSize = Buffer.byteLength(buffer);
|
|
32
|
+
if((actualBufferSize/1e6) > colConfig.maxFileSizeMB){
|
|
33
|
+
throw new Error(`Provided file is larger than the ${colConfig.maxFileSizeMB}MB limit`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if("acceptedContent" in colConfig && colConfig.acceptedContent && colConfig.acceptedContent !== "*"){
|
|
38
|
+
const mime = await getFileType(buffer, fileName);
|
|
39
|
+
const CONTENTS = [
|
|
40
|
+
"image",
|
|
41
|
+
"audio",
|
|
42
|
+
"video",
|
|
43
|
+
"text",
|
|
44
|
+
"application",
|
|
45
|
+
];
|
|
46
|
+
const allowedContent = parseFieldFilter(colConfig.acceptedContent, false, CONTENTS);
|
|
47
|
+
if(!allowedContent.some(c => mime.mime.startsWith(c))){
|
|
48
|
+
throw new Error(`Dissallowed content type provided: ${mime.mime.split("/")[0]}. Allowed content types: ${allowedContent} `)
|
|
49
|
+
}
|
|
50
|
+
} else if("acceptedContentType" in colConfig && colConfig.acceptedContentType && colConfig.acceptedContentType !== "*"){
|
|
51
|
+
const mime = await getFileType(buffer, fileName);
|
|
52
|
+
const allowedContentTypes = parseFieldFilter(colConfig.acceptedContentType, false, getKeys(CONTENT_TYPE_TO_EXT));
|
|
53
|
+
|
|
54
|
+
if(!allowedContentTypes.some(c => c === mime.mime)){
|
|
55
|
+
throw new Error(`Dissallowed MIME provided: ${mime.mime}. Allowed MIME values: ${allowedContentTypes} `)
|
|
56
|
+
}
|
|
57
|
+
} else if("acceptedFileTypes" in colConfig && colConfig.acceptedFileTypes && colConfig.acceptedFileTypes !== "*"){
|
|
58
|
+
const mime = await getFileType(buffer, fileName);
|
|
59
|
+
const allowedExtensions = parseFieldFilter(colConfig.acceptedFileTypes, false, Object.values(CONTENT_TYPE_TO_EXT).flat());
|
|
60
|
+
|
|
61
|
+
if(!allowedExtensions.some(c => c === mime.ext)){
|
|
62
|
+
throw new Error(`Dissallowed extension provided: ${mime.ext}. Allowed extension values: ${allowedExtensions} `)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if(!result?.mime) throw `File MIME type not found for the provided extension: ${result?.ext}`;
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import { asName, tryCatch } from "prostgles-types";
|
|
3
|
+
import { TableHandler } from "../DboBuilder/TableHandler/TableHandler";
|
|
4
|
+
import { canCreateTables } from "../DboBuilder/runSQL";
|
|
5
|
+
import { Prostgles } from "../Prostgles";
|
|
6
|
+
import { FileManager, HOUR, LocalConfig } from "./FileManager";
|
|
7
|
+
import { runClientRequest } from "../runClientRequest";
|
|
8
|
+
import { HTTPCODES } from "../Auth/AuthHandler";
|
|
9
|
+
|
|
10
|
+
export async function initFileManager(this: FileManager, prg: Prostgles){
|
|
11
|
+
this.prostgles = prg;
|
|
12
|
+
|
|
13
|
+
const { fileTable } = prg.opts;
|
|
14
|
+
if(!fileTable) {
|
|
15
|
+
throw "fileTable missing";
|
|
16
|
+
}
|
|
17
|
+
const { tableName = "files", referencedTables = {} } = fileTable;
|
|
18
|
+
this.tableName = tableName;
|
|
19
|
+
|
|
20
|
+
const maxBfSizeMB = (prg.opts.io?.engine?.opts?.maxHttpBufferSize || 1e6)/1e6;
|
|
21
|
+
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`);
|
|
22
|
+
|
|
23
|
+
const canCreate = await canCreateTables(this.db);
|
|
24
|
+
const runQuery = async (q: string, debugInfo: string): Promise<void> => {
|
|
25
|
+
const res = await tryCatch(async () => {
|
|
26
|
+
if(!canCreate) throw "File table creation failed. Your postgres user does not have CREATE table privileges";
|
|
27
|
+
await this.db.any(q);
|
|
28
|
+
});
|
|
29
|
+
await this.prostgles?.opts.onLog?.({ type: "debug", command: "initFileManager.runQuery", ...res, data: { debugInfo } });
|
|
30
|
+
if(res.error) {
|
|
31
|
+
throw res.error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* 1. Create media table
|
|
36
|
+
*/
|
|
37
|
+
if(!this.dbo[tableName]){
|
|
38
|
+
await runQuery(`
|
|
39
|
+
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
40
|
+
CREATE TABLE IF NOT EXISTS ${asName(tableName)} (
|
|
41
|
+
name TEXT NOT NULL,
|
|
42
|
+
extension TEXT NOT NULL,
|
|
43
|
+
content_type TEXT NOT NULL,
|
|
44
|
+
content_length BIGINT NOT NULL DEFAULT 0,
|
|
45
|
+
added TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
46
|
+
url TEXT NOT NULL,
|
|
47
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
48
|
+
original_name TEXT NOT NULL,
|
|
49
|
+
description TEXT,
|
|
50
|
+
cloud_url TEXT,
|
|
51
|
+
signed_url TEXT,
|
|
52
|
+
signed_url_expires BIGINT,
|
|
53
|
+
etag TEXT,
|
|
54
|
+
deleted BIGINT,
|
|
55
|
+
deleted_from_storage BIGINT,
|
|
56
|
+
UNIQUE(id),
|
|
57
|
+
UNIQUE(name)
|
|
58
|
+
)`, `Create fileTable ${asName(tableName)}`);
|
|
59
|
+
await prg.refreshDBO();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 2. Create media lookup tables
|
|
64
|
+
*/
|
|
65
|
+
for(const refTable in referencedTables){
|
|
66
|
+
|
|
67
|
+
if(!this.dbo[refTable]) {
|
|
68
|
+
throw `Referenced table (${refTable}) from fileTable.referencedTables prostgles init config does not exist`;
|
|
69
|
+
}
|
|
70
|
+
const cols = await (this.dbo[refTable] as TableHandler).getColumns();
|
|
71
|
+
|
|
72
|
+
const tableConfig = referencedTables[refTable]!;
|
|
73
|
+
|
|
74
|
+
for (const [colName] of Object.entries(tableConfig.referenceColumns)){
|
|
75
|
+
const existingCol = cols.find(c => c.name === colName);
|
|
76
|
+
if(existingCol){
|
|
77
|
+
if(existingCol.references?.some(({ ftable }) => ftable === tableName)){
|
|
78
|
+
// All ok
|
|
79
|
+
} else {
|
|
80
|
+
if(existingCol.udt_name === "uuid"){
|
|
81
|
+
try {
|
|
82
|
+
const query = `ALTER TABLE ${asName(refTable)} ADD FOREIGN KEY (${asName(colName)}) REFERENCES ${asName(tableName)} (id) ;`;
|
|
83
|
+
const msg = `Referenced file column ${refTable} (${colName}) exists but is not referencing file table. Add REFERENCE constraint...\n${query}`;
|
|
84
|
+
await runQuery(query, msg);
|
|
85
|
+
} catch(e){
|
|
86
|
+
console.error(`Could not add constraing. Err: ${e instanceof Error? e.message : JSON.stringify(e)}`)
|
|
87
|
+
}
|
|
88
|
+
} else {
|
|
89
|
+
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)`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
} else {
|
|
93
|
+
const query = `ALTER TABLE ${asName(refTable)} ADD COLUMN ${asName(colName)} UUID REFERENCES ${asName(tableName)} (id);`
|
|
94
|
+
// const createColumn = async () => {
|
|
95
|
+
// try {
|
|
96
|
+
// const msg = `Create referenced file column ${refTable} (${colName})...\n${query}`;
|
|
97
|
+
// await runQuery(query, msg);
|
|
98
|
+
// } catch(e){
|
|
99
|
+
// console.error(`FAILED. Err: ${e instanceof Error? e.message : JSON.stringify(e)}`)
|
|
100
|
+
// }
|
|
101
|
+
// }
|
|
102
|
+
// await createColumn();
|
|
103
|
+
console.error(`Referenced file column ${refTable} (${colName}) does not exist. Create it using this query:\n${query}`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
await prg.refreshDBO();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 4. Serve media through express
|
|
114
|
+
*/
|
|
115
|
+
const {
|
|
116
|
+
fileServeRoute = `/${tableName}`,
|
|
117
|
+
expressApp: app
|
|
118
|
+
} = fileTable;
|
|
119
|
+
|
|
120
|
+
if(fileServeRoute.endsWith("/")){
|
|
121
|
+
throw `fileServeRoute must not end with a '/'`
|
|
122
|
+
}
|
|
123
|
+
this.fileRoute = fileServeRoute;
|
|
124
|
+
|
|
125
|
+
if(app){
|
|
126
|
+
app.get(this.fileRouteExpress, async (req, res) => {
|
|
127
|
+
if(!this.dbo[tableName]){
|
|
128
|
+
res.status(HTTPCODES.INTERNAL_SERVER_ERROR).json(`Internal error: media table (${tableName}) not valid`);
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const mediaTable = this.dbo[tableName] as unknown as TableHandler;
|
|
133
|
+
|
|
134
|
+
try {
|
|
135
|
+
|
|
136
|
+
const { name } = req.params;
|
|
137
|
+
if(typeof name !== "string" || !name) {
|
|
138
|
+
throw "Invalid media name";
|
|
139
|
+
}
|
|
140
|
+
if(!this.prostgles) {
|
|
141
|
+
throw "Prostgles instance missing";
|
|
142
|
+
}
|
|
143
|
+
const id = name.slice(0, 36);
|
|
144
|
+
const selectParams = { select: { id: 1, name: 1, signed_url: 1, signed_url_expires: 1, content_type: 1 } }
|
|
145
|
+
const media = await runClientRequest.bind(this.prostgles)({
|
|
146
|
+
type: "http",
|
|
147
|
+
httpReq: req,
|
|
148
|
+
command: "findOne",
|
|
149
|
+
tableName,
|
|
150
|
+
param1: { id },
|
|
151
|
+
param2: selectParams,
|
|
152
|
+
param3: undefined
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
if(!media) {
|
|
156
|
+
res.status(HTTPCODES.NOT_FOUND).send("File not found or not allowed");
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if(this.cloudClient){
|
|
161
|
+
let url = media.signed_url;
|
|
162
|
+
const expires = +(media.signed_url_expires || 0);
|
|
163
|
+
|
|
164
|
+
const EXPIRES = Date.now() + HOUR;
|
|
165
|
+
if(!url || expires < EXPIRES){
|
|
166
|
+
url = await this.getFileCloudDownloadURL(media.name, 60 * 60);
|
|
167
|
+
await mediaTable.update({ name }, { signed_url: url, signed_url_expires: EXPIRES });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
res.redirect(url);
|
|
171
|
+
|
|
172
|
+
} else {
|
|
173
|
+
const pth = `${(this.config as LocalConfig).localFolderPath}/${media.name}`;
|
|
174
|
+
if(!fs.existsSync(pth)){
|
|
175
|
+
throw new Error("File not found");
|
|
176
|
+
}
|
|
177
|
+
res.contentType(media.content_type);
|
|
178
|
+
res.sendFile(pth);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
} catch(e){
|
|
182
|
+
console.log(e)
|
|
183
|
+
res.status(HTTPCODES.BAD_REQUEST).send("Invalid/disallowed file");
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { FileManager, LocalConfig, OnProgress, UploadedItem } from "./FileManager";
|
|
2
|
+
import * as stream from 'stream';
|
|
3
|
+
import * as fs from 'fs';
|
|
4
|
+
|
|
5
|
+
export async function upload(
|
|
6
|
+
this: FileManager,
|
|
7
|
+
file: Buffer | string | stream.PassThrough,
|
|
8
|
+
name: string,
|
|
9
|
+
mime: string,
|
|
10
|
+
onProgress?: OnProgress
|
|
11
|
+
): Promise<UploadedItem> {
|
|
12
|
+
|
|
13
|
+
return new Promise(async (resolve, reject) => {
|
|
14
|
+
if(!file){
|
|
15
|
+
throw "No file. Expecting: Buffer | String | stream.PassThrough";
|
|
16
|
+
}
|
|
17
|
+
if(!name){
|
|
18
|
+
throw "No file name. Expecting: String";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const url = this.getLocalFileUrl(name);
|
|
22
|
+
if(!this.cloudClient){
|
|
23
|
+
if(file instanceof stream.PassThrough){
|
|
24
|
+
throw new Error("S3 config missing. Can only upload streams to S3");
|
|
25
|
+
}
|
|
26
|
+
const config = this.config as LocalConfig;
|
|
27
|
+
try {
|
|
28
|
+
await fs.promises.mkdir(config.localFolderPath, { recursive: true });
|
|
29
|
+
const filePath = `${config.localFolderPath}/${name}`;
|
|
30
|
+
fs.writeFileSync(filePath, file);
|
|
31
|
+
resolve({
|
|
32
|
+
url,
|
|
33
|
+
etag: `none`,
|
|
34
|
+
content_length: fs.statSync(filePath).size
|
|
35
|
+
});
|
|
36
|
+
} catch(err){
|
|
37
|
+
console.error("Error saving file locally", err);
|
|
38
|
+
reject("Internal error")
|
|
39
|
+
}
|
|
40
|
+
} else {
|
|
41
|
+
|
|
42
|
+
let content_length = 0;
|
|
43
|
+
this.cloudClient.upload({
|
|
44
|
+
fileName: name,
|
|
45
|
+
contentType: mime,
|
|
46
|
+
file,
|
|
47
|
+
onFinish: (err, uploaded) => {
|
|
48
|
+
if(err){
|
|
49
|
+
reject(err.toString());
|
|
50
|
+
} else {
|
|
51
|
+
resolve({ ...uploaded, url });
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
onProgress: loaded => {
|
|
55
|
+
content_length = loaded;
|
|
56
|
+
onProgress?.({ loaded, total: content_length });
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
});
|
|
62
|
+
}
|