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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
|
package com.pinapelz.frontend
import io.javalin.Javalin
import com.pinapelz.Retriever
import com.pinapelz.FileSystem
import java.io.File
import java.net.URLEncoder
import java.time.ZoneId
import java.time.format.DateTimeFormatter
fun startFrontend(retriever: Retriever, fileSystem: FileSystem, webhooksFile: String) {
// Initialize WebhookManager if webhooks file exists
val webhookManager = if (File(webhooksFile).exists()) {
try {
WebhookManager(webhooksFile)
} catch (e: Exception) {
println("Warning: Failed to initialize webhook manager: ${e.message}")
null
}
} else {
println("Warning: Webhooks file not found: $webhooksFile")
null
}
val app = Javalin.create{};
app.get("/") { ctx ->
val directoryId = ctx.queryParam("dir")?.toIntOrNull() ?: 1
ctx.html(generateMainHtml(directoryId))
}
app.get("/splitter") { ctx ->
ctx.html(generateFileSplitterHtml())
}
app.post("/api/split") { ctx ->
val manager = MultipartFileManager(fileSystem, webhookManager)
val result = manager.handleSplitRequest(ctx)
ctx.json(result)
}
app.get("/api/directories") { ctx ->
val directories = mutableListOf<Map<String, Any>>()
val rs = fileSystem.getAllDirectories()
for (d in rs) {
directories.add(
mapOf(
"id" to d.directoryId,
"path" to d.path,
"fileCount" to d.fileCount,
"created" to d.createdAt.toString()
)
)
}
ctx.json(directories)
}
app.get("/api/directory/{id}") { ctx ->
val directoryId = ctx.pathParam("id").toInt()
val d = fileSystem.getDirectoryById(directoryId)
if (d != null) {
val directory = mapOf(
"id" to d.directoryId,
"path" to d.path,
"fileCount" to d.fileCount,
"created" to d.createdAt.toString()
)
ctx.json(directory)
} else {
ctx.status(404).result("Directory not found")
}
}
app.get("/api/files") { ctx ->
val directoryId = ctx.queryParam("dir")?.toIntOrNull() ?: 1
val search = ctx.queryParam("search") ?: ""
val mimeTypeFilter = ctx.queryParam("mimeType") ?: ""
val sortBy = ctx.queryParam("sortBy") ?: "created_at"
val files = mutableListOf<Map<String, Any>>()
val fileEntries = fileSystem.getFilesByDirectoryId(
directoryId,
search,
mimeTypeFilter,
sortBy
)
for (f in fileEntries) {
files.add(
mapOf(
"id" to f.fileId,
"name" to f.fileName,
"description" to (f.description ?: ""),
"size" to formatFileSize(f.size),
"mimeType" to (f.mimeType ?: "unknown"),
"created" to DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault())
.format(f.createdAt)
)
)
}
val partials = fileSystem.getGroupedPartials(directoryId, search)
for (p in partials) {
files.add(
mapOf(
"id" to "partial:${p.originalFilename}|$directoryId",
"name" to p.originalFilename,
"description" to (p.description ?: ""),
"size" to formatFileSize(p.size),
"mimeType" to (p.mimeType ?: "application/octet-stream"),
"created" to DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault())
.format(p.createdAt)
)
)
}
val html = generateFileTableHtml(files, search, mimeTypeFilter)
ctx.html(html)
ctx.header("HX-Trigger", "updateFileCount")
ctx.header("X-File-Count", files.size.toString())
}
app.get("/api/directories-html") { ctx ->
val directories = mutableListOf<Map<String, Any>>()
val directoriesResult = fileSystem.getAllDirectories()
for (d in directoriesResult) {
directories.add(
mapOf(
"id" to d.directoryId,
"path" to d.path,
"fileCount" to d.fileCount,
"created" to d.createdAt.toString()
)
)
}
val html = generateDirectoryListHtml(directories)
ctx.html(html)
}
app.post("/api/directories") { ctx ->
val path = ctx.formParam("path")
if (path.isNullOrBlank()) {
ctx.status(400).json(mapOf(
"success" to false,
"message" to "Directory path is required"
))
return@post
}
val trimmedPath = path.trim()
val validationError = validateDirectoryName(trimmedPath)
if (validationError != null) {
ctx.status(400).json(mapOf(
"success" to false,
"message" to validationError
))
return@post
}
try {
val directoryId = fileSystem.createDirectory(trimmedPath)
ctx.json(mapOf(
"success" to true,
"id" to directoryId,
"path" to trimmedPath,
"message" to "Directory created successfully"
))
} catch (e: Exception) {
ctx.status(500).json(mapOf(
"success" to false,
"message" to "Failed to create directory: ${e.message}"
))
}
}
app.delete("/api/files/{id}") { ctx ->
val idStr = ctx.pathParam("id")
try {
val deleted = if (idStr.startsWith("partial:")) {
val data = idStr.substring("partial:".length).split("|")
val filename = data[0]
val dirId = data[1].toInt()
fileSystem.deleteFilePartials(filename, dirId)
} else {
val fileId = idStr.toIntOrNull()
if (fileId == null) {
ctx.status(400).json(mapOf(
"success" to false,
"message" to "Invalid file ID"
))
return@delete
}
fileSystem.deleteFile(fileId)
}
if (deleted) {
ctx.json(mapOf(
"success" to true,
"message" to "File deleted successfully"
))
} else {
ctx.status(404).json(mapOf(
"success" to false,
"message" to "File not found"
))
}
} catch (e: Exception) {
ctx.status(500).json(mapOf(
"success" to false,
"message" to "Failed to delete file: ${e.message}"
))
}
}
app.delete("/api/directories/{id}") { ctx ->
val directoryId = ctx.pathParam("id").toIntOrNull()
if (directoryId == null) {
ctx.status(400).json(mapOf(
"success" to false,
"message" to "Invalid directory ID"
))
return@delete
}
try {
val deleted = fileSystem.deleteDirectory(directoryId)
if (deleted) {
ctx.json(mapOf(
"success" to true,
"message" to "Directory deleted successfully"
))
} else {
ctx.status(404).json(mapOf(
"success" to false,
"message" to "Directory not found"
))
}
} catch (e: Exception) {
ctx.status(500).json(mapOf(
"success" to false,
"message" to "Failed to delete directory: ${e.message}"
))
}
}
app.get("/api/reassemble") { ctx ->
val filename = ctx.queryParam("filename") ?: throw io.javalin.http.BadRequestResponse("filename required")
val dirId = ctx.queryParam("dir")?.toIntOrNull() ?: throw io.javalin.http.BadRequestResponse("dir id required")
data class PartInfo(val channelId: String, val messageId: String, val partName: String, val isWebhook: Boolean)
val parts = mutableListOf<PartInfo>()
var mimeType = "application/octet-stream"
for (p in fileSystem.getFilePartialsByOriginalFilename(filename, dirId)) {
parts.add(
PartInfo(
p.channelId,
p.messageId,
p.partName,
p.uploadedViaWebhook
)
)
mimeType = p.mimeType ?: mimeType
}
if (parts.isEmpty()) {
ctx.status(404).result("No parts found for $filename")
return@get
}
ctx.header("Content-Disposition", "attachment; filename=\"$filename\"")
ctx.contentType(mimeType)
ctx.async {
try {
val outputStream = ctx.res().outputStream
for ((index, part) in parts.withIndex()) {
var success = false
var lastError: Exception? = null
for (attempt in 1..3) {
try {
val url = retriever.getFileUrl(part.channelId, part.messageId, part.partName, part.isWebhook)
println("Fetching part ${index + 1}/${parts.size} from: $url (attempt $attempt)")
val connection = java.net.URI(url).toURL().openConnection() as java.net.HttpURLConnection
connection.requestMethod = "GET"
connection.setRequestProperty("User-Agent", "Mozilla/5.0")
connection.connectTimeout = 30000
connection.readTimeout = 30000
val responseCode = connection.responseCode
if (responseCode == 200) {
connection.inputStream.use { input ->
input.copyTo(outputStream)
}
println("Successfully fetched part ${index + 1}/${parts.size}")
success = true
break
} else {
println("HTTP $responseCode for part ${index + 1} on attempt $attempt")
lastError = Exception("HTTP $responseCode: ${connection.responseMessage}")
if (attempt < 3) Thread.sleep(1000 * attempt.toLong())
}
} catch (e: Exception) {
println("Error fetching part ${index + 1} on attempt $attempt: ${e.message}")
lastError = e
if (attempt < 3) Thread.sleep(1000 * attempt.toLong())
}
}
if (!success) {
ctx.status(500)
ctx.result("Error: Failed to retrieve part ${index + 1} after 3 attempts. ${lastError?.message}")
return@async
}
}
outputStream.flush()
} catch (e: Exception) {
println("Error during file reassembly: ${e.message}")
e.printStackTrace()
}
}
}
app.get("/fetch") { ctx ->
val fileIdStr = ctx.queryParam("fileId") ?: ""
if (fileIdStr.startsWith("partial:")) {
val data = fileIdStr.substring("partial:".length).split("|")
val filename = data[0]
val dirId = data[1]
ctx.redirect("/api/reassemble?filename=${URLEncoder.encode(filename, "UTF-8")}&dir=$dirId")
return@get
}
try {
val fileMetadata = fileSystem.getFileById(Integer.parseInt(fileIdStr))
println("Retrieving: " + fileMetadata.fileName)
val fileUrl = retriever.getFileUrl(fileMetadata.channelId.toString(),
fileMetadata.messageId.toString(), fileMetadata.fileName)
ctx.redirect(fileUrl)
} catch (e: Exception) {
println("Failed to retrieve file: ${e.message}")
ctx.status(404).result("Error: File not found or has been deleted from Discord. ${e.message}")
}
}
app.start(7070)
}
fun validateDirectoryName(path: String): String? {
if (path.length !in 1..100) {
return "Directory name must be 1-100 characters long"
}
if (!path.all { it.code <= 127 }) {
return "Directory name can only contain ASCII characters"
}
val invalidChars = Regex("[<>:\"/\\\\|?*\\x00-\\x1f#%&+@\\[\\]{}^`~;=']")
if (invalidChars.containsMatchIn(path)) {
return "Directory name contains invalid characters"
}
if (path == "." || path == "..") {
return "Invalid directory name"
}
if (path.startsWith(" ") || path.endsWith(" ") || path.endsWith(".")) {
return "Directory name cannot start/end with spaces or end with dots"
}
return null
}
fun generateMainHtml(directoryId: Int): String {
return HtmlTemplates.generateMainPage(directoryId)
}
fun generateDirectoryListHtml(directories: List<Map<String, Any>>): String {
return HtmlTemplates.generateDirectoryList(directories)
}
fun formatFileSize(bytes: Long): String {
if (bytes < 1024) return "$bytes B"
val kb = bytes / 1024.0
if (kb < 1024) return "%.1f KB".format(kb)
val mb = kb / 1024.0
if (mb < 1024) return "%.1f MB".format(mb)
val gb = mb / 1024.0
return "%.1f GB".format(gb)
}
fun generateFileTableHtml(files: List<Map<String, Any>>, search: String = "", mimeTypeFilter: String = ""): String {
return HtmlTemplates.generateFileTable(files, search, mimeTypeFilter)
}
fun generateFileSplitterHtml(): String {
return HtmlTemplates.generateFileSplitterPage()
}
|