aboutsummaryrefslogtreecommitdiffstats
path: root/packages/api/utils/assets.ts
blob: 3da32ff23607f6529635bbbc6320b3054bfd9847 (plain) (blame)
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
import { Context } from "hono";
import { stream } from "hono/streaming";

import {
  createAssetReadStream,
  getAssetSize,
  readAssetMetadata,
} from "@karakeep/shared/assetdb";

import { toWebReadableStream } from "./upload";

export async function serveAsset(c: Context, assetId: string, userId: string) {
  const [metadata, size] = await Promise.all([
    readAssetMetadata({
      userId,
      assetId,
    }),

    getAssetSize({
      userId,
      assetId,
    }),
  ]);

  // Default Headers
  c.header("Content-type", metadata.contentType);
  c.header("X-Content-Type-Options", "nosniff");
  c.header(
    "Content-Security-Policy",
    [
      "sandbox",
      "default-src 'none'",
      "base-uri 'none'",
      "form-action 'none'",
      "img-src https: data: blob:",
      "style-src 'unsafe-inline' https:",
      "connect-src 'none'",
      "media-src https: data: blob:",
      "object-src 'none'",
      "frame-src 'none'",
    ].join("; "),
  );

  const range = c.req.header("Range");
  if (range) {
    const parts = range.replace(/bytes=/, "").split("-");
    const start = parseInt(parts[0], 10);
    const end = parts[1] ? parseInt(parts[1], 10) : size - 1;

    const fStream = await createAssetReadStream({
      userId,
      assetId,
      start,
      end,
    });
    c.status(206); // Partial Content
    c.header("Content-Range", `bytes ${start}-${end}/${size}`);
    c.header("Accept-Ranges", "bytes");
    c.header("Content-Length", (end - start + 1).toString());
    return stream(c, async (stream) => {
      await stream.pipe(toWebReadableStream(fStream));
    });
  } else {
    const fStream = await createAssetReadStream({
      userId,
      assetId,
    });
    c.status(200);
    c.header("Content-Length", size.toString());
    return stream(c, async (stream) => {
      await stream.pipe(toWebReadableStream(fStream));
    });
  }
}