File size: 10,311 Bytes
fb38ec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import { MultipartFile } from "@fastify/multipart";
import archiver from "archiver";
import { randomUUID } from "crypto";
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import * as fs from "fs";
import http from "http";
import https from "https";
import mime from "mime-types";
import { tmpdir } from "os";
import path from "path";
import { Readable } from "stream";
import { pipeline } from "stream/promises";
import { v4 as uuidv4 } from "uuid";
import { FileService } from "../../services/file.service.js";
import { getErrors } from "../../utils/errors.js";

export class FilesController {
  constructor(private fileService: FileService) {}

  private validatePath(filePath: string): boolean {
    if (path.isAbsolute(filePath)) {
      return false;
    }

    if (filePath.includes("..")) {
      return false;
    }

    if (filePath.includes("\0")) {
      return false;
    }

    const normalized = path.normalize(filePath);
    if (normalized.startsWith("..")) {
      return false;
    }

    return true;
  }

  async handleFileUpload(
    server: FastifyInstance,
    request: FastifyRequest<{ Params: { sessionId: string } }>,
    reply: FastifyReply,
  ) {
    let tempFilePath: string | null = null;

    try {
      if (!request.isMultipart()) {
        return reply.code(400).send({
          success: false,
          message: "Request must be multipart/form-data",
        });
      }

      let filePath: string | null = null;
      let fileUrl: string | null = null;
      let fileProvided: boolean = false;
      let saveFileResult: Awaited<ReturnType<typeof this.fileService.saveFile>> | null = null;

      for await (const part of request.parts()) {
        if (part.fieldname === "file") {
          if (part.type === "file") {
            const file = part as MultipartFile;
            fileProvided = true;

            tempFilePath = path.join(tmpdir(), `upload_${uuidv4()}`);

            const writeStream = fs.createWriteStream(tempFilePath);
            await pipeline(file.file, writeStream);
          } else if (part.type === "field" && typeof part.value === "string") {
            fileUrl = part.value;
          }
        } else if (
          part.fieldname === "path" &&
          part.type === "field" &&
          typeof part.value === "string"
        ) {
          filePath = part.value;
        }
      }

      if (!fileProvided && !fileUrl) {
        return reply.code(400).send({
          success: false,
          message:
            "No file provided in the multipart request. The 'file' field must contain either a file or a URL string.",
        });
      }

      let finalPath: string;

      if (fileProvided && tempFilePath) {
        if (!filePath) {
          finalPath = randomUUID();
        } else {
          if (!this.validatePath(filePath)) {
            await fs.promises.unlink(tempFilePath).catch(() => {});
            return reply.code(400).send({
              success: false,
              message: "Invalid path provided",
            });
          }
          finalPath = filePath;
        }

        const readStream = fs.createReadStream(tempFilePath);
        saveFileResult = await this.fileService.saveFile({
          filePath: finalPath,
          stream: readStream,
        });

        await fs.promises.unlink(tempFilePath).catch(() => {});
        tempFilePath = null;
      } else if (fileUrl) {
        if (!filePath) {
          const urlPath = new URL(fileUrl).pathname;
          const filename = urlPath.split("/").pop() || randomUUID();
          const sanitizedFilename = filename.replace(/[^a-zA-Z0-9._-]/g, "_");
          finalPath = sanitizedFilename;
        } else {
          if (!this.validatePath(filePath)) {
            return reply.code(400).send({
              success: false,
              message: "Invalid path provided",
            });
          }
          finalPath = filePath;
        }

        const { stream } = await this.createStreamFromUrl(fileUrl);
        saveFileResult = await this.fileService.saveFile({
          filePath: finalPath,
          stream,
        });
      }

      if (!saveFileResult) {
        return reply.code(500).send({
          success: false,
          message: "Failed to save file",
        });
      }

      return reply.send({
        path: saveFileResult.path,
        size: saveFileResult.size,
        lastModified: saveFileResult.lastModified,
      });
    } catch (e: unknown) {
      if (tempFilePath) {
        await fs.promises.unlink(tempFilePath).catch(() => {});
      }
      const error = getErrors(e);
      return reply.code(500).send({ success: false, message: error });
    }
  }

  private async createStreamFromUrl(
    url: string,
  ): Promise<{ stream: Readable; contentType?: string; name: string }> {
    return new Promise((resolve, reject) => {
      const protocol = url.startsWith("https") ? https : http;

      protocol
        .get(url, (response) => {
          if (response.statusCode !== 200) {
            return reject(new Error(`Failed to fetch file: ${response.statusCode}`));
          }

          const contentType = response.headers["content-type"];
          const disposition = response.headers["content-disposition"] || "";
          let name: string | null = null;

          const nameMatch = disposition.match(/filename="(.+)"/i);

          if (nameMatch && nameMatch[1]) {
            name = nameMatch[1];
          } else {
            name = url.split("/").pop() || "downloaded-file";
          }

          resolve({
            stream: response,
            contentType,
            name,
          });
        })
        .on("error", reject);
    });
  }

  async handleFileDownload(
    server: FastifyInstance,
    request: FastifyRequest<{ Params: { sessionId: string; "*": string } }>,
    reply: FastifyReply,
  ) {
    try {
      const { stream, size, lastModified } = await this.fileService.downloadFile({
        filePath: request.params["*"],
      });

      const name = request.params["*"].split("/").pop() || "downloaded-file";

      reply
        .header("Content-Type", mime.lookup(request.params["*"]) || "application/octet-stream")
        .header("Content-Length", size)
        .header("Content-Disposition", `attachment; filename="${encodeURIComponent(name)}"`)
        .header("Last-Modified", lastModified.toISOString());

      return reply.send(stream);
    } catch (e: unknown) {
      const error = getErrors(e);
      return reply.code(500).send({ success: false, message: error });
    }
  }

  async handleFileHead(
    server: FastifyInstance,
    request: FastifyRequest<{ Params: { sessionId: string; "*": string } }>,
    reply: FastifyReply,
  ) {
    const { size, lastModified } = await this.fileService.getFile({
      filePath: request.params["*"],
    });

    const name = request.params["*"].split("/").pop() || "downloaded-file";

    reply
      .header("Content-Length", size)
      .header("Last-Modified", lastModified.toISOString())
      .header("Content-Type", mime.lookup(request.params["*"]) || "application/octet-stream")
      .header("Content-Disposition", `attachment; filename="${encodeURIComponent(name)}"`);

    return reply.code(200).send();
  }

  async handleFileList(
    server: FastifyInstance,
    request: FastifyRequest<{
      Params: { sessionId: string };
    }>,
    reply: FastifyReply,
  ) {
    try {
      const files = await this.fileService.listFiles();

      return reply.send({
        data: files.map((file) => ({
          path: file.path,
          size: file.size,
          lastModified: file.lastModified,
        })),
      });
    } catch (e: unknown) {
      const error = getErrors(e);
      return reply.code(500).send({ success: false, message: error });
    }
  }

  async handleFileDelete(
    server: FastifyInstance,
    request: FastifyRequest<{ Params: { sessionId: string; "*": string } }>,
    reply: FastifyReply,
  ) {
    try {
      await this.fileService.deleteFile({
        filePath: request.params["*"],
      });
      return reply.code(204).send();
    } catch (e: unknown) {
      const error = getErrors(e);
      return reply.code(500).send({ success: false, message: error });
    }
  }

  async handleFileDeleteAll(
    server: FastifyInstance,
    request: FastifyRequest<{ Params: { sessionId: string } }>,
    reply: FastifyReply,
  ) {
    try {
      await this.fileService.cleanupFiles();
      return reply.code(204).send();
    } catch (e: unknown) {
      const error = getErrors(e);
      return reply.code(500).send({ success: false, message: error });
    }
  }

  async handleDownloadArchive(
    server: FastifyInstance,
    request: FastifyRequest<{ Params: { sessionId: string } }>,
    reply: FastifyReply,
  ) {
    const prebuiltArchivePath = await this.fileService.getPrebuiltArchivePath();

    try {
      const stats = await fs.promises.stat(prebuiltArchivePath);
      if (stats.isFile()) {
        server.log.info(`Serving prebuilt archive: ${prebuiltArchivePath}`);
        const stream = fs.createReadStream(prebuiltArchivePath);

        reply.header("Content-Type", "application/zip");
        reply.header("Content-Disposition", `attachment; filename="files.zip"`);
        reply.header("Content-Length", stats.size);
        reply.header("Last-Modified", stats.mtime.toUTCString());
        return reply.send(stream);
      } else {
        server.log.warn(`Prebuilt archive path exists but is not a file: ${prebuiltArchivePath}`);
      }

      server.log.info("Sending empty archive.");
      reply.header("Content-Type", "application/zip");
      reply.header("Content-Disposition", `attachment; filename="files-archive-empty.zip"`);
      const emptyArchive = archiver("zip", { zlib: { level: 9 } });

      emptyArchive.pipe(reply.raw);

      await emptyArchive.finalize();
      return;
    } catch (err: any) {
      server.log.error({ err }, "Error during handleFileArchive");
      if (!reply.sent) {
        try {
          reply.code(500).send({ message: "Failed to process archive request" });
        } catch (sendError: unknown) {
          server.log.error(
            { err: sendError },
            "Error sending 500 response after archive handling error",
          );
        }
      }
    }
  }
}