summaryrefslogtreecommitdiff
path: root/views.ts
blob: ae46a9acd9f7975cec8a85e0fd62fc0f83d37b90 (plain)
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
import { config } from "./config.ts";
import { formatFileSize, getMimeType, isViewableInBrowser } from "./fileUtils.ts";

const templateCache = new Map<string, string>();

async function loadTemplate(path: string): Promise<string> {
  if (templateCache.has(path)) {
    return templateCache.get(path)!;
  }

  const content = await Deno.readTextFile(path);
  templateCache.set(path, content);
  return content;
}

function replaceVariables(template: string, vars: Record<string, string>): string {
  let result = template;
  for (const [key, value] of Object.entries(vars)) {
    result = result.replaceAll(`{{${key}}}`, value);
  }
  return result;
}

async function renderLayout(title: string, content: string, scripts = "", styles = ""): Promise<string> {
  const layout = await loadTemplate("./templates/layout.html");
  return replaceVariables(layout, {
    title,
    content,
    scripts,
    styles,
  });
}

export async function renderUploadPage(chunked = false): Promise<string> {
  const maxSizeMB = Math.floor(config.maxFileSize / (1024 * 1024));
  const expirationDays = Math.floor(config.fileExpiration / (24 * 60 * 60 * 1000));

  const uploadTemplate = await loadTemplate("./templates/upload.html");

  const scriptTemplate = chunked
    ? await loadTemplate("./templates/scripts/chunked-upload.js")
    : await loadTemplate("./templates/scripts/simple-upload.js");

  const scriptContent = replaceVariables(scriptTemplate, {
    "max-size": String(maxSizeMB),
    "chunk-size": String(config.chunkSize),
  });

  const content = replaceVariables(uploadTemplate, {
    "section-suffix": chunked ? "-js" : "-nojs",
    "upload-type": chunked ? "(Chunked)" : "",
    "nav-links": chunked
      ? '<a href="/">Simple Upload</a>'
      : '<a href="/chunked">Chunked Upload</a>',
    "form-attrs": chunked ? "" : 'action="/upload" method="POST" enctype="multipart/form-data"',
    "input-attrs": chunked ? "" : "required",
    "max-size": String(maxSizeMB),
    "expiration-days": String(expirationDays),
    "rate-limit-max": String(config.rateLimit.maxUploads),
    "rate-limit-minutes": String(config.rateLimit.windowMs / 60000),
  });

  const scripts = `<script>\n${scriptContent}\n</script>`;

  return renderLayout("File Upload", content, scripts);
}

export async function renderBrowsePage(files: Array<{ name: string; size: number; uploaded: Date }>): Promise<string> {
  const browseTemplate = await loadTemplate("./templates/browse.html");
  const fileRowTemplate = await loadTemplate("./templates/partials/file-row.html");
  const emptyFilesTemplate = await loadTemplate("./templates/partials/empty-files.html");

  const fileRows = files.map(file => {
    const mimeType = getMimeType(file.name);
    const viewable = isViewableInBrowser(mimeType);
    const encodedName = encodeURIComponent(file.name);

    const viewButton = viewable
      ? `<a href="/download/${encodedName}" target="_blank" class="button" style="margin-right: 10px; background-color: #28a745; color: white; border-color: #28a745;">View</a>`
      : '';

    return replaceVariables(fileRowTemplate, {
      "encoded-name": encodedName,
      "filename": file.name,
      "size": formatFileSize(file.size),
      "uploaded": file.uploaded.toLocaleString(),
      "view-button": viewButton,
    });
  }).join('');

  const filesContent = files.length > 0 ? `
    <table style="width: 100%; border-collapse: collapse;">
      <thead>
        <tr>
          <th>Filename</th>
          <th>Size</th>
          <th>Uploaded</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        ${fileRows}
      </tbody>
    </table>
  ` : emptyFilesTemplate;

  const content = replaceVariables(browseTemplate, {
    "files-content": filesContent,
  });

  return renderLayout("Browse Files", content);
}

export async function renderGalleryPage(files: Array<{ name: string; size: number; uploaded: Date }>): Promise<string> {
  const galleryTemplate = await loadTemplate("./templates/gallery.html");
  const galleryItemTemplate = await loadTemplate("./templates/partials/gallery-item.html");
  const emptyGalleryTemplate = await loadTemplate("./templates/partials/empty-gallery.html");

  // Filter only images and videos
  const mediaFiles = files.filter(file => {
    const mimeType = getMimeType(file.name);
    return mimeType.startsWith("image/") || mimeType.startsWith("video/");
  });

  const galleryItems = mediaFiles.map((file, index) => {
    const mimeType = getMimeType(file.name);
    const isVideo = mimeType.startsWith("video/");
    const encodedName = encodeURIComponent(file.name);

    const media = isVideo
      ? `<video src="/download/${encodedName}" style="width: 100%; height: 200px; object-fit: cover; border-radius: 4px;"></video>
         <div class="video-overlay">▶</div>`
      : `<img src="/download/${encodedName}" alt="${file.name}" style="width: 100%; height: 200px; object-fit: cover; border-radius: 4px;">`;

    return replaceVariables(galleryItemTemplate, {
      "index": String(index),
      "media": media,
      "filename": file.name,
      "size": formatFileSize(file.size),
      "uploaded": file.uploaded.toLocaleDateString(),
    });
  }).join('');

  const galleryContent = mediaFiles.length > 0
    ? `<div class="gallery-grid">\n${galleryItems}\n</div>`
    : emptyGalleryTemplate;

  const content = replaceVariables(galleryTemplate, {
    "gallery-content": galleryContent,
  });

  const mediaFilesJson = JSON.stringify(mediaFiles.map(file => ({
    name: file.name,
    isVideo: getMimeType(file.name).startsWith("video/"),
    size: formatFileSize(file.size),
    uploaded: file.uploaded.toLocaleDateString()
  })));

  const slideshowScript = await loadTemplate("./templates/scripts/slideshow.js");
  const scriptContent = replaceVariables(slideshowScript, {
    "media-files-json": mediaFilesJson,
  });

  const styles = '<link rel="stylesheet" href="/css/gallery.css">';
  const scripts = `<script>\n${scriptContent}\n</script>`;

  return renderLayout("Gallery", content, scripts, styles);
}

export async function renderError(error: string, status = 400): Promise<string> {
  const errorTemplate = await loadTemplate("./templates/error.html");

  const content = replaceVariables(errorTemplate, {
    status: String(status),
    "error-message": error,
  });

  return renderLayout("Error", content);
}