-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmod.ts
189 lines (186 loc) · 6.4 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { ensureDir, ensureDirSync, v4, move, MultipartReader, SEP, join } from "./deps.ts";
interface UploadOptions {
extensions?: Array<string>;
maxSizeBytes?: number;
maxFileSizeBytes?: number;
saveFile?: boolean;
readFile?: boolean;
useCurrentDir?: boolean;
useDateTimeSubDir?: boolean;
}
const defaultUploadOptions: UploadOptions = {
extensions: [],
maxSizeBytes: Number.MAX_SAFE_INTEGER,
maxFileSizeBytes: Number.MAX_SAFE_INTEGER,
saveFile: true,
readFile: false,
useCurrentDir: true,
useDateTimeSubDir: true,
}
const upload = function (
path: string,
options: UploadOptions = defaultUploadOptions
) {
const mergedOptions = Object.assign({}, defaultUploadOptions, options);
const { extensions, maxSizeBytes, maxFileSizeBytes, saveFile, readFile, useCurrentDir, useDateTimeSubDir } = mergedOptions;
ensureDirSync(join(Deno.cwd(), 'temp_uploads'));
return async (context: any, next: any) => {
const req = context.request.originalRequest;
if (
parseInt(req.headers.get("content-length")) > maxSizeBytes!
) {
context.throw(
422,
`Maximum total upload size exceeded, size: ${
req.headers.get("content-length")
} bytes, maximum: ${maxSizeBytes} bytes. `,
);
await next();
}
const boundaryRegex = /^multipart\/form-data;\sboundary=(?<boundary>.*)$/;
let match: RegExpMatchArray | null;
if (
req.headers.get("content-type") &&
(match = req.headers.get("content-type")!.match(
boundaryRegex,
))
) {
const formBoundary: string = match.groups!.boundary;
const mr = new MultipartReader(
req.body,
formBoundary,
);
const form = await mr.readForm(0);
let res: any = {};
let entries: any = Array.from(form.entries());
let validations = "";
for (const item of entries) {
let values: any = [].concat(item[1]);
for (const val of values) {
if (val.filename !== undefined) {
if (extensions!.length > 0) {
let ext = val.filename.split(".").pop();
if (!extensions!.includes(ext)) {
validations +=
`The file extension is not allowed (${ext} in ${val.filename}), allowed extensions: ${extensions}. `;
}
}
if (val.size > maxFileSizeBytes!) {
validations +=
`Maximum file upload size exceeded, file: ${val.filename}, size: ${val.size} bytes, maximum: ${maxFileSizeBytes} bytes. `;
}
}
}
}
if (validations != "") {
await form.removeAll();
context.throw(422, validations);
await next();
}
for (const item of entries) {
let formField: any = item[0];
let filesData: any = [].concat(item[1]);
for (const fileData of filesData) {
if (fileData.tempfile !== undefined) {
let resData = fileData;
if (readFile) {
resData["data"] = await Deno.readFile(resData["tempfile"]);
}
if (saveFile) {
let uploadPath = path;
let uuid = '';
if (useDateTimeSubDir) {
const d = new Date();
uuid = join(
d.getFullYear().toString(),
(d.getMonth()+1).toString(),
d.getDate().toString(),
d.getHours().toString(),
d.getMinutes().toString(),
d.getSeconds().toString(),
v4.generate() //TODO improve to use of v5
);
uploadPath = join(path,uuid);
};
let fullPath = uploadPath;
if (useCurrentDir) {
fullPath = join(Deno.cwd(),fullPath);
}
await ensureDir(fullPath);
await move(
fileData.tempfile,
join(fullPath,fileData.filename),
);
delete resData["tempfile"];
resData["id"] = uuid.replace(/\\/g, "/");
resData["url"] = encodeURI(
join(uploadPath,fileData.filename).replace(/\\/g, "/"),
);
resData["uri"] = join(fullPath,fileData.filename);
} else {
let tempFileName = resData.tempfile.split(SEP).pop();
let pathTempFile = join(Deno.cwd(),'temp_uploads',tempFileName)
await move(
resData.tempfile,
pathTempFile,
);
resData.tempfile = pathTempFile;
}
if (res[formField] !== undefined) {
if (Array.isArray(res[formField])) {
res[formField].push(resData);
} else {
res[formField] = [res[formField], resData];
}
} else {
res[formField] = resData;
}
}
}
}
context["uploadedFiles"] = res;
} else {
context.throw(
422,
'Invalid upload data, request must contains a body with form "multipart/form-data", and inputs with type="file". ',
);
}
await next();
};
};
const preUploadValidate = function (
extensions: Array<string> = [],
maxSizeBytes: number = Number.MAX_SAFE_INTEGER,
maxFileSizeBytes: number = Number.MAX_SAFE_INTEGER,
) {
return async (context: any, next: any) => {
let jsonData = await context.request.body();
jsonData = jsonData["value"];
let totalBytes = 0;
let validations = "";
for (const iName in jsonData) {
let files: any = [].concat(jsonData[iName]);
for (const file of files) {
totalBytes += jsonData[iName].size;
if (file.size > maxFileSizeBytes) {
validations +=
`Maximum file upload size exceeded, file: ${file.name}, size: ${file.size} bytes, maximum: ${maxFileSizeBytes} bytes. `;
}
if (!extensions.includes(file.name.split(".").pop())) {
validations += `The file extension is not allowed (${
file.name.split(".").pop()
} in ${file.name}), allowed extensions: ${extensions}. `;
}
}
}
if (totalBytes > maxSizeBytes) {
validations +=
`Maximum total upload size exceeded, size: ${totalBytes} bytes, maximum: ${maxSizeBytes} bytes. `;
}
if (validations != "") {
context.throw(422, validations);
}
await next();
};
};
export { upload, preUploadValidate };