prostgles-server 4.0.16 → 4.0.18
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/AuthHandler.js +214 -210
- package/dist/AuthHandler.js.map +1 -1
- package/dist/DBEventsManager.js +34 -31
- package/dist/DBEventsManager.js.map +1 -1
- package/dist/DBSchemaBuilder.js +3 -2
- package/dist/DBSchemaBuilder.js.map +1 -1
- package/dist/DboBuilder/QueryBuilder/QueryBuilder.d.ts +19 -14
- package/dist/DboBuilder/QueryBuilder/QueryBuilder.d.ts.map +1 -1
- package/dist/DboBuilder/QueryBuilder/QueryBuilder.js +159 -151
- package/dist/DboBuilder/QueryBuilder/QueryBuilder.js.map +1 -1
- package/dist/DboBuilder/TableHandler.d.ts +9 -14
- package/dist/DboBuilder/TableHandler.d.ts.map +1 -1
- package/dist/DboBuilder/TableHandler.js +21 -41
- package/dist/DboBuilder/TableHandler.js.map +1 -1
- package/dist/DboBuilder/ViewHandler.d.ts +3 -3
- package/dist/DboBuilder/ViewHandler.d.ts.map +1 -1
- package/dist/DboBuilder/ViewHandler.js +24 -9
- package/dist/DboBuilder/ViewHandler.js.map +1 -1
- package/dist/DboBuilder/getSubscribeRelatedTables.d.ts +1 -1
- package/dist/DboBuilder/getSubscribeRelatedTables.d.ts.map +1 -1
- package/dist/DboBuilder/parseUpdateRules.d.ts.map +1 -1
- package/dist/DboBuilder/parseUpdateRules.js.map +1 -1
- package/dist/DboBuilder/runSQL.js +5 -5
- package/dist/DboBuilder/runSQL.js.map +1 -1
- package/dist/DboBuilder.d.ts.map +1 -1
- package/dist/DboBuilder.js +85 -78
- package/dist/DboBuilder.js.map +1 -1
- package/dist/FileManager/FileManager.d.ts +143 -0
- package/dist/FileManager/FileManager.d.ts.map +1 -0
- package/dist/FileManager/FileManager.js +278 -0
- package/dist/FileManager/FileManager.js.map +1 -0
- package/dist/FileManager/initFileManager.d.ts +4 -0
- package/dist/FileManager/initFileManager.d.ts.map +1 -0
- package/dist/FileManager/initFileManager.js +209 -0
- package/dist/FileManager/initFileManager.js.map +1 -0
- package/dist/FileManager/parseFile.d.ts +15 -0
- package/dist/FileManager/parseFile.d.ts.map +1 -0
- package/dist/FileManager/parseFile.js +59 -0
- package/dist/FileManager/parseFile.js.map +1 -0
- package/dist/FileManager/upload.d.ts +6 -0
- package/dist/FileManager/upload.d.ts.map +1 -0
- package/dist/FileManager/upload.js +76 -0
- package/dist/FileManager/upload.js.map +1 -0
- package/dist/FileManager/uploadStream.d.ts +5 -0
- package/dist/FileManager/uploadStream.d.ts.map +1 -0
- package/dist/FileManager/uploadStream.js +70 -0
- package/dist/FileManager/uploadStream.js.map +1 -0
- package/dist/Filtering.d.ts +1 -1
- package/dist/Filtering.d.ts.map +1 -1
- package/dist/PostgresNotifListenManager.js +26 -20
- package/dist/PostgresNotifListenManager.js.map +1 -1
- package/dist/Prostgles.d.ts +2 -2
- package/dist/Prostgles.d.ts.map +1 -1
- package/dist/Prostgles.js +192 -172
- package/dist/Prostgles.js.map +1 -1
- package/dist/PubSubManager/PubSubManager.d.ts +3 -3
- package/dist/PubSubManager/PubSubManager.js +164 -154
- package/dist/PubSubManager/PubSubManager.js.map +1 -1
- package/dist/PublishParser.d.ts +13 -13
- package/dist/PublishParser.d.ts.map +1 -1
- package/dist/PublishParser.js +8 -2
- package/dist/PublishParser.js.map +1 -1
- package/dist/SchemaWatch.js +2 -1
- package/dist/SchemaWatch.js.map +1 -1
- package/dist/TableConfig/TableConfig.d.ts.map +1 -1
- package/dist/TableConfig/TableConfig.js +100 -92
- package/dist/TableConfig/TableConfig.js.map +1 -1
- package/lib/AuthHandler.js +1 -1
- package/lib/AuthHandler.ts +1 -1
- package/lib/DBSchemaBuilder.js +3 -2
- package/lib/DBSchemaBuilder.ts +3 -2
- package/lib/DboBuilder/TableHandler.d.ts +4 -9
- package/lib/DboBuilder/TableHandler.d.ts.map +1 -1
- package/lib/DboBuilder/TableHandler.js +1 -22
- package/lib/DboBuilder/TableHandler.ts +3 -31
- package/lib/DboBuilder/ViewHandler.ts +1 -1
- package/lib/DboBuilder/getSubscribeRelatedTables.d.ts +1 -1
- package/lib/DboBuilder/getSubscribeRelatedTables.d.ts.map +1 -1
- package/lib/DboBuilder/getSubscribeRelatedTables.ts +1 -1
- package/lib/DboBuilder/parseUpdateRules.d.ts.map +1 -1
- package/lib/DboBuilder/parseUpdateRules.ts +2 -2
- package/lib/DboBuilder.d.ts.map +1 -1
- package/lib/DboBuilder.js +0 -13
- package/lib/DboBuilder.ts +1 -16
- package/lib/{FileManager.d.ts → FileManager/FileManager.d.ts} +12 -20
- package/lib/FileManager/FileManager.d.ts.map +1 -0
- package/lib/FileManager/FileManager.js +303 -0
- package/lib/FileManager/FileManager.ts +378 -0
- package/lib/FileManager/initFileManager.d.ts +4 -0
- package/lib/FileManager/initFileManager.d.ts.map +1 -0
- package/lib/FileManager/initFileManager.js +231 -0
- package/lib/FileManager/initFileManager.ts +236 -0
- package/lib/FileManager/parseFile.d.ts +15 -0
- package/lib/FileManager/parseFile.d.ts.map +1 -0
- package/lib/FileManager/parseFile.js +58 -0
- package/lib/FileManager/parseFile.ts +69 -0
- package/lib/FileManager/upload.d.ts +6 -0
- package/lib/FileManager/upload.d.ts.map +1 -0
- package/lib/FileManager/upload.js +98 -0
- package/lib/FileManager/upload.ts +83 -0
- package/lib/FileManager/uploadStream.d.ts +5 -0
- package/lib/FileManager/uploadStream.d.ts.map +1 -0
- package/lib/FileManager/uploadStream.js +92 -0
- package/lib/FileManager/uploadStream.ts +80 -0
- package/lib/Filtering.d.ts +1 -1
- package/lib/Filtering.d.ts.map +1 -1
- package/lib/Filtering.ts +1 -1
- package/lib/JSONBValidation/validate_jsonb_schema_sql.ts +1 -1
- package/lib/Prostgles.d.ts +2 -2
- package/lib/Prostgles.d.ts.map +1 -1
- package/lib/Prostgles.js +8 -5
- package/lib/Prostgles.ts +10 -6
- package/lib/PublishParser.d.ts +13 -13
- package/lib/PublishParser.d.ts.map +1 -1
- package/lib/PublishParser.js +1 -0
- package/lib/PublishParser.ts +13 -12
- package/lib/TableConfig/TableConfig.d.ts.map +1 -1
- package/lib/TableConfig/TableConfig.js +12 -7
- package/lib/TableConfig/TableConfig.ts +13 -8
- package/package.json +3 -3
- package/tests/client/PID.txt +1 -1
- package/tests/client/index.d.ts.map +1 -1
- package/tests/client/index.ts +1 -3
- package/tests/client/package-lock.json +31 -4561
- package/tests/client/package.json +2 -2
- package/tests/client/tsconfig.json +1 -0
- package/tests/isomorphic_queries.d.ts.map +1 -1
- package/tests/isomorphic_queries.ts +3 -3
- package/tests/server/package-lock.json +13 -13
- package/tests/server/package.json +1 -1
- package/tests/server/tsconfig.json +1 -0
- package/tsconfig.json +3 -2
- package/lib/FileManager.d.ts.map +0 -1
- package/lib/FileManager.js +0 -676
- package/lib/FileManager.ts +0 -811
package/lib/FileManager.ts
DELETED
|
@@ -1,811 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
import { S3, IAM } from 'aws-sdk';
|
|
3
|
-
import { ManagedUpload } from 'aws-sdk/clients/s3';
|
|
4
|
-
// import { PutObjectCommand, S3 } from "@aws-sdk/client-s3";
|
|
5
|
-
import * as fs from 'fs';
|
|
6
|
-
import * as stream from 'stream';
|
|
7
|
-
|
|
8
|
-
import * as sharp from "sharp";
|
|
9
|
-
import checkDiskSpace from 'check-disk-space';
|
|
10
|
-
|
|
11
|
-
import { DB, DBHandlerServer, ExpressApp, Prostgles } from './Prostgles';
|
|
12
|
-
import { ALLOWED_CONTENT_TYPE, ALLOWED_EXTENSION, asName, CONTENT_TYPE_TO_EXT, getKeys, isDefined, isObject, ValidatedColumnInfo } from 'prostgles-types';
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
const HOUR = 3600 * 1000;
|
|
16
|
-
|
|
17
|
-
export const asSQLIdentifier = async (name: string, db: DB): Promise<string> => {
|
|
18
|
-
return (await db.one("select format('%I', $1) as name", [name]))?.name
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
type OnProgress = (progress: S3.ManagedUpload.Progress) => void
|
|
22
|
-
|
|
23
|
-
export type ImageOptions = {
|
|
24
|
-
keepMetadata?: boolean;
|
|
25
|
-
compression?:
|
|
26
|
-
/**
|
|
27
|
-
* Will resize image maintaing scale ratio
|
|
28
|
-
*/
|
|
29
|
-
| { inside: { width: number; height: number } }
|
|
30
|
-
| { contain:
|
|
31
|
-
| { width: number }
|
|
32
|
-
| { height: number }
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export type S3Config = {
|
|
37
|
-
region: string;
|
|
38
|
-
bucket: string;
|
|
39
|
-
accessKeyId: string;
|
|
40
|
-
secretAccessKey: string;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export type LocalConfig = {
|
|
44
|
-
/**
|
|
45
|
-
* example: path.join(__dirname+'/media')
|
|
46
|
-
* note that this location will be relative to the compiled file location
|
|
47
|
-
*/
|
|
48
|
-
localFolderPath: string;
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Minimum amount of free bytes available to allow saving files
|
|
52
|
-
* Defaults to 100MB
|
|
53
|
-
*/
|
|
54
|
-
minFreeBytes?: number;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export type UploadItem = {
|
|
58
|
-
name: string;
|
|
59
|
-
content_type: string;
|
|
60
|
-
data: Buffer;
|
|
61
|
-
extension: string;
|
|
62
|
-
};
|
|
63
|
-
export type UploadedItem = {
|
|
64
|
-
/**
|
|
65
|
-
* Url that is passed to client
|
|
66
|
-
*/
|
|
67
|
-
url: string;
|
|
68
|
-
filePath?: string;
|
|
69
|
-
etag: string;
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* S3 url of the resource
|
|
73
|
-
*/
|
|
74
|
-
s3_url?: string;
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Total uploaded file size in bytes
|
|
78
|
-
*/
|
|
79
|
-
content_length: number;
|
|
80
|
-
};
|
|
81
|
-
import AWS from 'aws-sdk';
|
|
82
|
-
import { canCreateTables } from "./DboBuilder/runSQL";
|
|
83
|
-
import * as path from "path";
|
|
84
|
-
import { TableHandler } from "./DboBuilder/TableHandler";
|
|
85
|
-
import { ViewHandler } from "./DboBuilder/ViewHandler";
|
|
86
|
-
export default class FileManager {
|
|
87
|
-
|
|
88
|
-
static testCredentials = async (accessKeyId: string, secretAccessKey: string) => {
|
|
89
|
-
const sts = new AWS.STS();
|
|
90
|
-
AWS.config.credentials = {
|
|
91
|
-
accessKeyId,
|
|
92
|
-
secretAccessKey
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const ident = await sts.getCallerIdentity({}).promise();
|
|
96
|
-
return ident;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
s3Client?: S3;
|
|
100
|
-
|
|
101
|
-
config: S3Config | LocalConfig;
|
|
102
|
-
imageOptions?: ImageOptions;
|
|
103
|
-
|
|
104
|
-
prostgles?: Prostgles;
|
|
105
|
-
get dbo(): DBHandlerServer {
|
|
106
|
-
if(!this.prostgles?.dbo) {
|
|
107
|
-
// this.prostgles?.refreshDBO();
|
|
108
|
-
throw "this.prostgles.dbo missing"
|
|
109
|
-
}
|
|
110
|
-
return this.prostgles.dbo
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
get db(): DB {
|
|
114
|
-
if(!this.prostgles?.db) throw "this.prostgles.db missing"
|
|
115
|
-
return this.prostgles.db
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
tableName?: string;
|
|
119
|
-
|
|
120
|
-
private fileRoute?: string;
|
|
121
|
-
get fileRouteExpress (){
|
|
122
|
-
return this.fileRoute + "/:name";
|
|
123
|
-
}
|
|
124
|
-
private checkInterval?: NodeJS.Timeout;
|
|
125
|
-
|
|
126
|
-
constructor(config: FileManager["config"], imageOptions?: ImageOptions){
|
|
127
|
-
this.config = config;
|
|
128
|
-
this.imageOptions = imageOptions;
|
|
129
|
-
|
|
130
|
-
if("region" in config){
|
|
131
|
-
const { region, accessKeyId, secretAccessKey } = config;
|
|
132
|
-
this.s3Client = new S3({
|
|
133
|
-
region,
|
|
134
|
-
credentials: { accessKeyId, secretAccessKey },
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const fullConfig = this.prostgles?.opts.fileTable;
|
|
139
|
-
if(fullConfig?.delayedDelete){
|
|
140
|
-
this.checkInterval = setInterval(async () => {
|
|
141
|
-
const fileTable = fullConfig.tableName;
|
|
142
|
-
const daysDelay = fullConfig.delayedDelete?.deleteAfterNDays ?? 0;
|
|
143
|
-
if(fileTable && this.dbo[fileTable]?.delete && daysDelay){
|
|
144
|
-
const filesToDelete = await this.dbo[fileTable]?.find?.({ deleted_from_storage: null, deleted: { ">": Date.now() - (daysDelay * HOUR * 24) } }) ?? [];
|
|
145
|
-
for await(const file of filesToDelete){
|
|
146
|
-
await this.deleteFile(file.name)
|
|
147
|
-
}
|
|
148
|
-
} else {
|
|
149
|
-
console.error("FileManager checkInterval delayedDelete FAIL: Could not access file table tableHandler.delete()")
|
|
150
|
-
}
|
|
151
|
-
}, Math.max(10000, (fullConfig.delayedDelete.checkIntervalHours || 0) * HOUR))
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
async getFileStream(name: string): Promise<stream.Readable> {
|
|
156
|
-
if("bucket" in this.config && this.s3Client){
|
|
157
|
-
return this.s3Client.getObject({ Key: name, Bucket: this.config.bucket }).createReadStream()
|
|
158
|
-
} else if("localFolderPath" in this.config){
|
|
159
|
-
const filePath = path.resolve(`${this.config.localFolderPath}/${name}`);
|
|
160
|
-
if(!fs.existsSync(filePath)){
|
|
161
|
-
throw `File ${filePath} could not be found`;
|
|
162
|
-
}
|
|
163
|
-
return fs.createReadStream(filePath, { encoding: undefined })
|
|
164
|
-
} else throw new Error("Not expected");
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
async deleteFile(name: string) {
|
|
168
|
-
if("bucket" in this.config && this.s3Client){
|
|
169
|
-
const res = await this.s3Client?.deleteObject({ Bucket: this.config.bucket, Key: name }).promise();
|
|
170
|
-
return res;
|
|
171
|
-
} else if("localFolderPath" in this.config){
|
|
172
|
-
const path = `${this.config.localFolderPath}/${name}`;
|
|
173
|
-
if(!fs.existsSync(path)){
|
|
174
|
-
throw `File ${path} could not be found`;
|
|
175
|
-
}
|
|
176
|
-
fs.unlinkSync(path);
|
|
177
|
-
if(fs.existsSync(path)) throw new Error("Could not delete file");
|
|
178
|
-
}
|
|
179
|
-
return true
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
async parseFile(args: {
|
|
183
|
-
file: Buffer | string;
|
|
184
|
-
fileName: string;
|
|
185
|
-
colName?: string;
|
|
186
|
-
tableName?: string;
|
|
187
|
-
}): Promise<{
|
|
188
|
-
mime: string | ALLOWED_CONTENT_TYPE;
|
|
189
|
-
ext: string | ALLOWED_EXTENSION;
|
|
190
|
-
|
|
191
|
-
/** File name is not returned because we fail if the extensions do not match */
|
|
192
|
-
// fileName: string;
|
|
193
|
-
}> {
|
|
194
|
-
const { file, fileName, tableName, colName } = args;
|
|
195
|
-
const config = this.prostgles?.opts.fileTable;
|
|
196
|
-
if(!config) throw new Error("File table config missing");
|
|
197
|
-
|
|
198
|
-
const buffer = typeof file === "string"? Buffer.from(file, 'utf8') : file;
|
|
199
|
-
|
|
200
|
-
const result = await getFileTypeFromFilename(fileName);
|
|
201
|
-
if(tableName && colName){
|
|
202
|
-
const tableConfig = config.referencedTables?.[tableName];
|
|
203
|
-
|
|
204
|
-
if(tableConfig && isObject(tableConfig) && tableConfig.referenceColumns[colName]){
|
|
205
|
-
const colConfig = tableConfig.referenceColumns[colName]!;
|
|
206
|
-
if(colConfig.maxFileSizeMB){
|
|
207
|
-
const actualBufferSize = Buffer.byteLength(buffer);
|
|
208
|
-
if((actualBufferSize/1e6) > colConfig.maxFileSizeMB){
|
|
209
|
-
throw new Error(`Provided file is larger than the ${colConfig.maxFileSizeMB}MB limit`);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
if("acceptedContent" in colConfig && colConfig.acceptedContent && colConfig.acceptedContent !== "*"){
|
|
214
|
-
const mime = await getFileType(buffer, fileName);
|
|
215
|
-
const CONTENTS = [
|
|
216
|
-
"image",
|
|
217
|
-
"audio",
|
|
218
|
-
"video",
|
|
219
|
-
"text",
|
|
220
|
-
"application",
|
|
221
|
-
];
|
|
222
|
-
const allowedContent = ViewHandler._parseFieldFilter(colConfig.acceptedContent, false, CONTENTS);
|
|
223
|
-
if(!allowedContent.some(c => mime.mime.startsWith(c))){
|
|
224
|
-
throw new Error(`Dissallowed content type provided: ${mime.mime.split("/")[0]}. Allowed content types: ${allowedContent} `)
|
|
225
|
-
}
|
|
226
|
-
} else if("acceptedContentType" in colConfig && colConfig.acceptedContentType && colConfig.acceptedContentType !== "*"){
|
|
227
|
-
const mime = await getFileType(buffer, fileName);
|
|
228
|
-
const allowedContentTypes = ViewHandler._parseFieldFilter(colConfig.acceptedContentType, false, getKeys(CONTENT_TYPE_TO_EXT));
|
|
229
|
-
|
|
230
|
-
if(!allowedContentTypes.some(c => c === mime.mime)){
|
|
231
|
-
throw new Error(`Dissallowed MIME provided: ${mime.mime}. Allowed MIME values: ${allowedContentTypes} `)
|
|
232
|
-
}
|
|
233
|
-
} else if("acceptedFileTypes" in colConfig && colConfig.acceptedFileTypes && colConfig.acceptedFileTypes !== "*"){
|
|
234
|
-
const mime = await getFileType(buffer, fileName);
|
|
235
|
-
const allowedExtensions = ViewHandler._parseFieldFilter(colConfig.acceptedFileTypes, false, Object.values(CONTENT_TYPE_TO_EXT).flat());
|
|
236
|
-
|
|
237
|
-
if(!allowedExtensions.some(c => c === mime.ext)){
|
|
238
|
-
throw new Error(`Dissallowed extension provided: ${mime.ext}. Allowed extension values: ${allowedExtensions} `)
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
if(!result?.mime) throw `File MIME type not found for the provided extension: ${result?.ext}`;
|
|
244
|
-
return result;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
getFileUrl = (name: string) => this.fileRoute? `${this.fileRoute}/${name}` : "";
|
|
248
|
-
|
|
249
|
-
checkFreeSpace = async (folderPath: string, fileSize = 0) => {
|
|
250
|
-
if(!this.s3Client && "localFolderPath" in this.config) {
|
|
251
|
-
const { minFreeBytes = 1.048e6 } = this.config;
|
|
252
|
-
const required = Math.max(fileSize, minFreeBytes)
|
|
253
|
-
if(required){
|
|
254
|
-
const diskSpace = await checkDiskSpace(folderPath);
|
|
255
|
-
if(diskSpace.free < required){
|
|
256
|
-
const err = `There is not enough space on the server to save files.\nTotal: ${bytesToSize(diskSpace.size)} \nRemaning: ${bytesToSize(diskSpace.free)} \nRequired: ${bytesToSize(required)}`
|
|
257
|
-
throw new Error(err);
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
uploadStream = (
|
|
264
|
-
name: string,
|
|
265
|
-
mime: string,
|
|
266
|
-
onProgress?: OnProgress,
|
|
267
|
-
onError?: (error: any)=>void,
|
|
268
|
-
onEnd?: (item: UploadedItem)=>void,
|
|
269
|
-
expectedSizeBytes?: number
|
|
270
|
-
) => {
|
|
271
|
-
const passThrough = new stream.PassThrough();
|
|
272
|
-
|
|
273
|
-
if(!this.s3Client && "localFolderPath" in this.config) {
|
|
274
|
-
// throw new Error("S3 config missing. Can only upload streams to S3");
|
|
275
|
-
|
|
276
|
-
try {
|
|
277
|
-
this.checkFreeSpace(this.config.localFolderPath, expectedSizeBytes).catch(err => {
|
|
278
|
-
onError?.(err)
|
|
279
|
-
passThrough.end();
|
|
280
|
-
});
|
|
281
|
-
const url = this.getFileUrl(name)
|
|
282
|
-
fs.mkdirSync(this.config.localFolderPath, { recursive: true });
|
|
283
|
-
const filePath = path.resolve(`${this.config.localFolderPath}/${name}`);
|
|
284
|
-
const writeStream = fs.createWriteStream(filePath);
|
|
285
|
-
|
|
286
|
-
let errored = false;
|
|
287
|
-
let loaded = 0;
|
|
288
|
-
writeStream.on('error', err => {
|
|
289
|
-
errored = true;
|
|
290
|
-
onError?.(err)
|
|
291
|
-
});
|
|
292
|
-
|
|
293
|
-
let lastProgress = Date.now();
|
|
294
|
-
const throttle = 1000;
|
|
295
|
-
if(onProgress){
|
|
296
|
-
passThrough.on('data', function(chunk){
|
|
297
|
-
loaded += chunk.length;
|
|
298
|
-
const now = Date.now();
|
|
299
|
-
if(now - lastProgress > throttle){
|
|
300
|
-
lastProgress = now;
|
|
301
|
-
onProgress?.({ loaded, total: 0 });
|
|
302
|
-
}
|
|
303
|
-
});
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
if(onEnd) writeStream.on('finish', () => {
|
|
307
|
-
if(errored) return;
|
|
308
|
-
let content_length = 0;
|
|
309
|
-
try {
|
|
310
|
-
content_length = fs.statSync(filePath).size;
|
|
311
|
-
|
|
312
|
-
onEnd?.({
|
|
313
|
-
url,
|
|
314
|
-
filePath,
|
|
315
|
-
etag: `none`,
|
|
316
|
-
content_length
|
|
317
|
-
})
|
|
318
|
-
} catch (err){
|
|
319
|
-
onError?.(err)
|
|
320
|
-
}
|
|
321
|
-
})
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
passThrough.pipe(writeStream);
|
|
325
|
-
} catch(err){
|
|
326
|
-
onError?.(err)
|
|
327
|
-
}
|
|
328
|
-
} else {
|
|
329
|
-
this.upload(passThrough, name, mime, onProgress).then(onEnd)
|
|
330
|
-
.catch(onError)
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
return passThrough;
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
private async upload(
|
|
338
|
-
file: Buffer | string | stream.PassThrough,
|
|
339
|
-
name: string,
|
|
340
|
-
mime: string,
|
|
341
|
-
onProgress?: OnProgress
|
|
342
|
-
): Promise<UploadedItem> {
|
|
343
|
-
|
|
344
|
-
return new Promise(async (resolve, reject) => {
|
|
345
|
-
if(!file){
|
|
346
|
-
throw "No file. Expecting: Buffer | String | stream";
|
|
347
|
-
}
|
|
348
|
-
if(!name){
|
|
349
|
-
throw "No name. Expecting: String";
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
// let type = await this.getMIME(file, name, allowedExtensions);
|
|
353
|
-
const url = this.getFileUrl(name)
|
|
354
|
-
if(!this.s3Client){
|
|
355
|
-
if(file instanceof stream.PassThrough){
|
|
356
|
-
throw new Error("S3 config missing. Can only upload streams to S3");
|
|
357
|
-
}
|
|
358
|
-
const config = this.config as LocalConfig;
|
|
359
|
-
try {
|
|
360
|
-
await fs.promises.mkdir(config.localFolderPath, { recursive: true });
|
|
361
|
-
const filePath = `${config.localFolderPath}/${name}`;
|
|
362
|
-
fs.writeFileSync(filePath, file);
|
|
363
|
-
resolve({
|
|
364
|
-
url,
|
|
365
|
-
etag: `none`,
|
|
366
|
-
content_length: fs.statSync(filePath).size
|
|
367
|
-
})
|
|
368
|
-
} catch(err){
|
|
369
|
-
console.error("Error saving file locally", err);
|
|
370
|
-
reject("Internal error")
|
|
371
|
-
}
|
|
372
|
-
} else {
|
|
373
|
-
|
|
374
|
-
/* S3 Upload */
|
|
375
|
-
// ACL: "public-read",
|
|
376
|
-
/* ACL needs this permission:
|
|
377
|
-
"s3:PutObject",
|
|
378
|
-
"s3:PutObjectAcl",
|
|
379
|
-
"s3:GetObject",
|
|
380
|
-
"s3:GetObjectAcl",
|
|
381
|
-
*/
|
|
382
|
-
const params = {
|
|
383
|
-
Bucket: (this.config as S3Config).bucket,
|
|
384
|
-
Key: name,
|
|
385
|
-
ContentType: mime,
|
|
386
|
-
Body: file
|
|
387
|
-
};
|
|
388
|
-
|
|
389
|
-
let content_length = 0;
|
|
390
|
-
const manager = this.s3Client.upload(params, (err: Error, res: ManagedUpload.SendData) => {
|
|
391
|
-
// const manager = this.s3Client.send(new PutObjectCommand(params), (err: Error, res) => {
|
|
392
|
-
|
|
393
|
-
if(err){
|
|
394
|
-
reject(err.toString());
|
|
395
|
-
console.error(err)
|
|
396
|
-
} else {
|
|
397
|
-
// console.log("Uploaded file:", res)
|
|
398
|
-
resolve({
|
|
399
|
-
url,
|
|
400
|
-
etag: res.ETag,
|
|
401
|
-
s3_url: res.Location,
|
|
402
|
-
content_length // await fileMgr.s3Client?.headObject({ Bucket: ..., Key: ... }).promise() ).ContentLength;
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
});
|
|
406
|
-
manager.on('httpUploadProgress', prog => {
|
|
407
|
-
content_length = prog.total;
|
|
408
|
-
onProgress?.(prog);
|
|
409
|
-
});
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
});
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
uploadAsMedia = async (params: {
|
|
416
|
-
item: UploadItem;
|
|
417
|
-
allowedExtensions?: Array<ALLOWED_EXTENSION>;
|
|
418
|
-
dissallowedExtensions?: Array<ALLOWED_EXTENSION>;
|
|
419
|
-
imageOptions?: ImageOptions;
|
|
420
|
-
}): Promise<UploadedItem> => {
|
|
421
|
-
const { item, imageOptions } = params;
|
|
422
|
-
const { name, data, content_type, extension } = item;
|
|
423
|
-
if(!data) throw "No file provided";
|
|
424
|
-
if(!name || typeof name !== "string") throw "Expecting a string name";
|
|
425
|
-
|
|
426
|
-
// const type = await this.getMIME(data, name, allowedExtensions, dissallowedExtensions);
|
|
427
|
-
|
|
428
|
-
let _data = data;
|
|
429
|
-
|
|
430
|
-
/** Resize/compress/remove exif from photos */
|
|
431
|
-
if(content_type.startsWith("image") && extension.toLowerCase() !== "gif"){
|
|
432
|
-
|
|
433
|
-
const compression = imageOptions?.compression
|
|
434
|
-
if(compression){
|
|
435
|
-
console.log("Resizing image")
|
|
436
|
-
let opts;
|
|
437
|
-
if("contain" in compression){
|
|
438
|
-
opts = {
|
|
439
|
-
fit: sharp.fit.contain,
|
|
440
|
-
...compression.contain
|
|
441
|
-
}
|
|
442
|
-
} else if("inside" in compression){
|
|
443
|
-
opts = {
|
|
444
|
-
fit: sharp.fit.inside,
|
|
445
|
-
...compression.inside
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
_data = await sharp(data)
|
|
449
|
-
.resize(opts as any)
|
|
450
|
-
.withMetadata(Boolean(imageOptions?.keepMetadata) as any)
|
|
451
|
-
// .jpeg({ quality: 80 })
|
|
452
|
-
.toBuffer()
|
|
453
|
-
} else if(!imageOptions?.keepMetadata) {
|
|
454
|
-
/**
|
|
455
|
-
* Remove exif
|
|
456
|
-
*/
|
|
457
|
-
// const metadata = await simg.metadata();
|
|
458
|
-
// const simg = await sharp(data);
|
|
459
|
-
|
|
460
|
-
_data = await sharp(data).clone().withMetadata({
|
|
461
|
-
exif: {}
|
|
462
|
-
})
|
|
463
|
-
.toBuffer()
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
const res = await this.upload(_data, name, content_type);
|
|
468
|
-
|
|
469
|
-
return res
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
async getFileS3URL(fileName: string, expiresInSeconds: number = 30 * 60){
|
|
473
|
-
const params = {
|
|
474
|
-
Bucket: (this.config as S3Config).bucket,
|
|
475
|
-
Key: fileName,
|
|
476
|
-
Expires: Math.round(expiresInSeconds || 30 * 60) // Error if float
|
|
477
|
-
};
|
|
478
|
-
return await this.s3Client?.getSignedUrlPromise("getObject", params);
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
private parseSQLIdentifier = async (name: string ) => asSQLIdentifier(name, this.prostgles!.db!);// this.prostgles.dbo.sql<"value">("select format('%I', $1)", [name], { returnType: "value" } )
|
|
482
|
-
|
|
483
|
-
getColInfo = (args: { tableName: string; colName: string }): ValidatedColumnInfo["file"] | undefined => {
|
|
484
|
-
const { colName, tableName } = args;
|
|
485
|
-
const tableConfig = this.prostgles?.opts.fileTable?.referencedTables?.[tableName];
|
|
486
|
-
const isReferencingFileTable = this.dbo[tableName]?.columns?.some(c => c.name === colName && c.references && c.references?.some(({ ftable }) => ftable === this.tableName ));
|
|
487
|
-
if(isReferencingFileTable){
|
|
488
|
-
if(tableConfig && typeof tableConfig !== "string"){
|
|
489
|
-
return tableConfig.referenceColumns[colName];
|
|
490
|
-
}
|
|
491
|
-
return { acceptedContent: "*" };
|
|
492
|
-
}
|
|
493
|
-
return undefined;
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
init = async (prg: Prostgles) => {
|
|
497
|
-
this.prostgles = prg;
|
|
498
|
-
|
|
499
|
-
// const { dbo, db, opts } = prg;
|
|
500
|
-
|
|
501
|
-
const { fileTable } = prg.opts;
|
|
502
|
-
if(!fileTable) throw "fileTable missing";
|
|
503
|
-
const { tableName = "media", referencedTables = {} } = fileTable;
|
|
504
|
-
this.tableName = tableName;
|
|
505
|
-
|
|
506
|
-
const maxBfSizeMB = (prg.opts.io?.engine?.opts?.maxHttpBufferSize || 1e6)/1e6;
|
|
507
|
-
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`);
|
|
508
|
-
|
|
509
|
-
// throw `this.db.tx(d => do everything in a transaction pls!!!!`;
|
|
510
|
-
|
|
511
|
-
const canCreate = await canCreateTables(this.db);
|
|
512
|
-
const runQuery = (q: string): Promise<any[]> => {
|
|
513
|
-
if(!canCreate) throw "File table creation failed. Your postgres user does not have CREATE table privileges";
|
|
514
|
-
return this.db.any(q)
|
|
515
|
-
}
|
|
516
|
-
/**
|
|
517
|
-
* 1. Create media table
|
|
518
|
-
*/
|
|
519
|
-
if(!this.dbo[tableName]){
|
|
520
|
-
|
|
521
|
-
console.log(`Creating fileTable ${asName(tableName)} ...`);
|
|
522
|
-
await runQuery(`CREATE EXTENSION IF NOT EXISTS pgcrypto `);
|
|
523
|
-
await runQuery(`CREATE TABLE IF NOT EXISTS ${asName(tableName)} (
|
|
524
|
-
name TEXT NOT NULL,
|
|
525
|
-
extension TEXT NOT NULL,
|
|
526
|
-
content_type TEXT NOT NULL,
|
|
527
|
-
content_length BIGINT NOT NULL DEFAULT 0,
|
|
528
|
-
added TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
529
|
-
url TEXT NOT NULL,
|
|
530
|
-
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
531
|
-
original_name TEXT NOT NULL,
|
|
532
|
-
description TEXT,
|
|
533
|
-
s3_url TEXT,
|
|
534
|
-
signed_url TEXT,
|
|
535
|
-
signed_url_expires BIGINT,
|
|
536
|
-
etag TEXT,
|
|
537
|
-
deleted BIGINT,
|
|
538
|
-
deleted_from_storage BIGINT,
|
|
539
|
-
UNIQUE(id),
|
|
540
|
-
UNIQUE(name)
|
|
541
|
-
)`);
|
|
542
|
-
console.log(`Created fileTable ${asName(tableName)}`);
|
|
543
|
-
await prg.refreshDBO();
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
/**
|
|
547
|
-
* 2. Create media lookup tables
|
|
548
|
-
*/
|
|
549
|
-
await Promise.all(getKeys(referencedTables).map(async refTable => {
|
|
550
|
-
|
|
551
|
-
if(!this.dbo[refTable]) throw `Referenced table (${refTable}) from fileTable.referencedTables prostgles init config does not exist`;
|
|
552
|
-
const cols = await (this.dbo[refTable] as TableHandler).getColumns();
|
|
553
|
-
|
|
554
|
-
const tableConfig = referencedTables[refTable]!;
|
|
555
|
-
if(typeof tableConfig !== "string"){
|
|
556
|
-
|
|
557
|
-
for await (const colName of getKeys(tableConfig.referenceColumns)){
|
|
558
|
-
|
|
559
|
-
const existingCol = cols.find(c => c.name === colName);
|
|
560
|
-
if(existingCol){
|
|
561
|
-
if(existingCol.references?.some(({ ftable }) => ftable === tableName)){
|
|
562
|
-
// All ok
|
|
563
|
-
} else {
|
|
564
|
-
if(existingCol.udt_name === "uuid"){
|
|
565
|
-
try {
|
|
566
|
-
const query = `ALTER TABLE ${asName(refTable)} ADD FOREIGN KEY (${asName(colName)}) REFERENCES ${asName(tableName)} (id);`;
|
|
567
|
-
console.log(`Referenced file column ${refTable} (${colName}) exists but is not referencing file table. Trying to add REFERENCE constraing...\n${query}`);
|
|
568
|
-
await runQuery(query);
|
|
569
|
-
console.log("SUCCESS: " + query);
|
|
570
|
-
} catch(e){
|
|
571
|
-
console.error(`Could not add constraing. Err: ${e instanceof Error? e.message : JSON.stringify(e)}`)
|
|
572
|
-
}
|
|
573
|
-
} else {
|
|
574
|
-
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)`);
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
} else {
|
|
578
|
-
try {
|
|
579
|
-
const query = `ALTER TABLE ${asName(refTable)} ADD COLUMN ${asName(colName)} UUID REFERENCES ${asName(tableName)} (id);`
|
|
580
|
-
console.log(`Creating referenced file column ${refTable} (${colName})...\n${query}`);
|
|
581
|
-
await runQuery(query);
|
|
582
|
-
console.log("SUCCESS: " + query);
|
|
583
|
-
} catch(e){
|
|
584
|
-
console.error(`FAILED. Err: ${e instanceof Error? e.message : JSON.stringify(e)}`)
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
}
|
|
589
|
-
} else {
|
|
590
|
-
|
|
591
|
-
const lookupTableName = await this.parseSQLIdentifier(`prostgles_lookup_${tableName}_${refTable}`);
|
|
592
|
-
const pKeyFields = cols.filter(f => f.is_pkey);
|
|
593
|
-
|
|
594
|
-
if(pKeyFields.length !== 1) {
|
|
595
|
-
console.error(`Could not make link table for ${refTable}. ${pKeyFields} must have exactly one primary key column. Current pkeys: ${pKeyFields.map(f => f.name)}`);
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
const pkField = pKeyFields[0]!;
|
|
599
|
-
const refType = referencedTables[refTable];
|
|
600
|
-
|
|
601
|
-
if(!this.dbo[lookupTableName]){
|
|
602
|
-
// if(!(await dbo[lookupTableName].count())) await db.any(`DROP TABLE IF EXISTS ${lookupTableName};`);
|
|
603
|
-
const action = ` (${tableName} <-> ${refTable}) join table ${lookupTableName}`; // PRIMARY KEY
|
|
604
|
-
const query = `
|
|
605
|
-
CREATE TABLE ${lookupTableName} (
|
|
606
|
-
foreign_id ${pkField.udt_name} ${refType === "one"? " PRIMARY KEY " : ""} REFERENCES ${asName(refTable)}(${asName(pkField.name)}),
|
|
607
|
-
media_id UUID NOT NULL REFERENCES ${asName(tableName)}(id)
|
|
608
|
-
)
|
|
609
|
-
`;
|
|
610
|
-
console.log(`Creating ${action} ...`, lookupTableName);
|
|
611
|
-
await runQuery(query);
|
|
612
|
-
console.log(`Created ${action}`);
|
|
613
|
-
|
|
614
|
-
} else {
|
|
615
|
-
const cols = await this.dbo[lookupTableName]!.getColumns!();
|
|
616
|
-
const badCols = cols.filter(c => !c.references);
|
|
617
|
-
await Promise.all(badCols.map(async badCol => {
|
|
618
|
-
console.error(
|
|
619
|
-
`Prostgles: media ${lookupTableName} joining table has lost a reference constraint for column ${badCol.name}.` +
|
|
620
|
-
` This may have been caused by a DROP TABLE ... CASCADE.`
|
|
621
|
-
);
|
|
622
|
-
let q = ` ALTER TABLE ${asName(lookupTableName)} ADD FOREIGN KEY (${badCol.name}) `;
|
|
623
|
-
console.log("Trying to add the missing constraint back");
|
|
624
|
-
if(badCol.name === "foreign_id"){
|
|
625
|
-
q += `REFERENCES ${asName(refTable)}(${asName(pkField.name)}) `;
|
|
626
|
-
} else if(badCol.name === "media_id"){
|
|
627
|
-
q += `REFERENCES ${asName(tableName)}(id) `;
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
if(q){
|
|
631
|
-
|
|
632
|
-
try {
|
|
633
|
-
await runQuery(q)
|
|
634
|
-
console.log("Added missing constraint back");
|
|
635
|
-
|
|
636
|
-
} catch(e){
|
|
637
|
-
console.error("Failed to add missing constraint", e)
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
}));
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
await prg.refreshDBO();
|
|
647
|
-
return true;
|
|
648
|
-
}));
|
|
649
|
-
|
|
650
|
-
/**
|
|
651
|
-
* 4. Serve media through express
|
|
652
|
-
*/
|
|
653
|
-
const {
|
|
654
|
-
fileServeRoute = `/${tableName}`,
|
|
655
|
-
expressApp: app
|
|
656
|
-
} = fileTable;
|
|
657
|
-
|
|
658
|
-
if(fileServeRoute.endsWith("/")){
|
|
659
|
-
throw `fileServeRoute must not end with a '/'`
|
|
660
|
-
}
|
|
661
|
-
this.fileRoute = fileServeRoute;
|
|
662
|
-
|
|
663
|
-
if(app){
|
|
664
|
-
app.get(this.fileRouteExpress, async (req, res) => {
|
|
665
|
-
if(!this.dbo[tableName]){
|
|
666
|
-
res.status(500).json({ err: `Internal error: media table (${tableName}) not valid` });
|
|
667
|
-
return false;
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
const mediaTable = this.dbo[tableName] as unknown as TableHandler;
|
|
671
|
-
|
|
672
|
-
try {
|
|
673
|
-
|
|
674
|
-
const { name } = req.params;
|
|
675
|
-
if(typeof name !== "string" || !name) throw "Invalid media name";
|
|
676
|
-
|
|
677
|
-
const media = await mediaTable.findOne({ name }, { select: { id: 1, name: 1, signed_url: 1, signed_url_expires: 1, content_type: 1 } }, { httpReq: req } as any);
|
|
678
|
-
|
|
679
|
-
if(!media) {
|
|
680
|
-
/**
|
|
681
|
-
* Redirect to login !??
|
|
682
|
-
*/
|
|
683
|
-
// const mediaExists = await mediaTable.count({ name });
|
|
684
|
-
// if(mediaExists && this.prostgles.authHandler){
|
|
685
|
-
|
|
686
|
-
// } else {
|
|
687
|
-
// throw "Invalid media";
|
|
688
|
-
// }
|
|
689
|
-
throw "Invalid media";
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
if(this.s3Client){
|
|
693
|
-
let url = media.signed_url;
|
|
694
|
-
const expires = +(media.signed_url_expires || 0);
|
|
695
|
-
|
|
696
|
-
const EXPIRES = Date.now() + HOUR;
|
|
697
|
-
if(!url || expires < EXPIRES){
|
|
698
|
-
url = await this.getFileS3URL(media.name, 60 * 60);
|
|
699
|
-
await mediaTable.update({ name }, { signed_url: url, signed_url_expires: EXPIRES });
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
res.redirect(url);
|
|
703
|
-
|
|
704
|
-
} else {
|
|
705
|
-
const pth = `${(this.config as LocalConfig).localFolderPath}/${media.name}`;
|
|
706
|
-
if(!fs.existsSync(pth)){
|
|
707
|
-
throw new Error("File not found");
|
|
708
|
-
}
|
|
709
|
-
res.contentType(media.content_type);
|
|
710
|
-
res.sendFile(pth);
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
} catch(e){
|
|
714
|
-
console.log(e)
|
|
715
|
-
res.status(404).json({ err: "Invalid/missing media" });
|
|
716
|
-
}
|
|
717
|
-
});
|
|
718
|
-
}
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
destroy = () => {
|
|
722
|
-
removeExpressRoute(this.prostgles?.opts.fileTable?.expressApp, [this.fileRouteExpress]);
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
export const removeExpressRoute = (app: ExpressApp | undefined, routePaths: (string | undefined)[]) => {
|
|
727
|
-
|
|
728
|
-
const routes = app?._router?.stack;
|
|
729
|
-
if(routes){
|
|
730
|
-
routes.forEach((route, i) => {
|
|
731
|
-
if(routePaths.filter(isDefined).includes(route.route?.path as any)){
|
|
732
|
-
routes.splice(i, 1);
|
|
733
|
-
}
|
|
734
|
-
})
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
export const getFileTypeFromFilename = (fileName: string): { mime: ALLOWED_CONTENT_TYPE; ext: ALLOWED_EXTENSION | string } | undefined => {
|
|
739
|
-
|
|
740
|
-
const nameParts = fileName.split(".");
|
|
741
|
-
|
|
742
|
-
if(nameParts.length < 2) return undefined;
|
|
743
|
-
|
|
744
|
-
const nameExt = nameParts.at(-1)!.toLowerCase(),
|
|
745
|
-
mime = getKeys(CONTENT_TYPE_TO_EXT).find(k => (CONTENT_TYPE_TO_EXT[k] as readonly string[]).includes(nameExt));
|
|
746
|
-
|
|
747
|
-
if(!mime) return undefined;
|
|
748
|
-
|
|
749
|
-
return {
|
|
750
|
-
mime,
|
|
751
|
-
ext: nameExt as ALLOWED_EXTENSION,
|
|
752
|
-
}
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
// const fileType = require("file-type");
|
|
756
|
-
// const res = await fileType.fromBuffer(typeof file === "string"? Buffer.from(file, 'utf8') : file);
|
|
757
|
-
|
|
758
|
-
export const getFileType = async (file: Buffer | string, fileName: string): Promise<{ mime: ALLOWED_CONTENT_TYPE; ext: ALLOWED_EXTENSION }> => {
|
|
759
|
-
|
|
760
|
-
const { fileTypeFromBuffer } = await (eval('import("file-type")') as Promise<typeof import('file-type')>);
|
|
761
|
-
|
|
762
|
-
const fileNameMime = getFileTypeFromFilename(fileName);
|
|
763
|
-
if(!fileNameMime?.ext) throw new Error("File name must contain extenion")
|
|
764
|
-
const res = await fileTypeFromBuffer(typeof file === "string"? Buffer.from(file, 'utf8') : file);
|
|
765
|
-
|
|
766
|
-
if(!res) {
|
|
767
|
-
|
|
768
|
-
/* Set correct/missing extension */
|
|
769
|
-
const nameExt = fileNameMime?.ext;
|
|
770
|
-
if(["xml", "txt", "csv", "tsv", "svg", "sql"].includes(nameExt) && fileNameMime.mime){
|
|
771
|
-
return fileNameMime as any;
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
throw new Error("Could not get the file type from file buffer");
|
|
775
|
-
} else {
|
|
776
|
-
|
|
777
|
-
if(!res.ext || fileNameMime?.ext.toLowerCase() !== res.ext.toLowerCase()){
|
|
778
|
-
throw new Error(`There is a mismatch between file name extension and actual buffer extension: ${fileNameMime?.ext } vs ${res.ext}`)
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
return res as any;
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
export function bytesToSize(bytes: number) {
|
|
785
|
-
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
|
786
|
-
if (bytes == 0) return '0 Byte';
|
|
787
|
-
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)) + "");
|
|
788
|
-
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
/**
|
|
793
|
-
*
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
// if(content_type && typeof content_type !== "string") throw "Invalid content_type provided";
|
|
797
|
-
// if(title && typeof title !== "string") throw "Invalid title provided";
|
|
798
|
-
// let fExt = name.split(".").pop()
|
|
799
|
-
// if(content_type && name.split(".").length > 1 && fExt && fExt.length <= 4){
|
|
800
|
-
// type = {
|
|
801
|
-
// mime: content_type,
|
|
802
|
-
// ext: fExt,
|
|
803
|
-
// fileName: name,
|
|
804
|
-
// }
|
|
805
|
-
// } else {
|
|
806
|
-
// type = await this.getMIME(data, name);//, ["png", "jpg", "ogg", "webm", "pdf", "doc"]);
|
|
807
|
-
// }
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
*/
|