|
| 1 | +/* |
| 2 | +Support user uploading a blob directly from their browser to the CoCalc database, |
| 3 | +mainly for markdown documents. This is meant to be very similar to how GitHub |
| 4 | +allows for attaching files to github issue comments. |
| 5 | +
|
| 6 | +
|
| 7 | +*/ |
| 8 | + |
| 9 | +// Note that github has a 10MB limit -- https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/attaching-files |
| 10 | +const MAX_BLOB_SIZE_MB = 10; |
| 11 | + |
| 12 | +// some throttling -- note that after a bit, most blobs end up longterm |
| 13 | +// cloud storage and are never accessed. |
| 14 | +// this is just a limit to prevent abuse, and it's done on a per-hub |
| 15 | +// basis using an in-memory data structure. |
| 16 | +const MAX_BLOBS_SIZE_MB_PER_USER_PER_DAY = 250; |
| 17 | + |
| 18 | +import { Router } from "express"; |
| 19 | +import { database } from "../database"; |
| 20 | +import { is_valid_uuid_string } from "@cocalc/util/misc"; |
| 21 | +import { database_is_working } from "@cocalc/hub/hub_register"; |
| 22 | +import { callback2 } from "@cocalc/util/async-utils"; |
| 23 | +import { getLogger } from "@cocalc/hub/logger"; |
| 24 | + |
| 25 | +const logger = getLogger("hub:servers:app:blobs"); |
| 26 | +export default function init(router: Router) { |
| 27 | + // return uuid-indexed blobs (mainly used for graphics) |
| 28 | + router.post("/blobs", async (req, res) => { |
| 29 | + logger.debug(`${JSON.stringify(req.query)}, ${req.path}`); |
| 30 | + const uuid = `${req.query.uuid}`; |
| 31 | + if (!is_valid_uuid_string(uuid)) { |
| 32 | + res.status(404).send(`invalid uuid=${uuid}`); |
| 33 | + return; |
| 34 | + } |
| 35 | + if (!database_is_working()) { |
| 36 | + res.status(404).send("can't get blob -- not connected to database"); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + try { |
| 41 | + const data = await callback2(database.get_blob, { uuid }); |
| 42 | + if (data == null) { |
| 43 | + res.status(404).send(`blob ${uuid} not found`); |
| 44 | + } else { |
| 45 | + const filename = req.path.slice(req.path.lastIndexOf("/") + 1); |
| 46 | + if (req.query.download != null) { |
| 47 | + // tell browser to download the link as a file instead |
| 48 | + // of displaying it in browser |
| 49 | + res.attachment(filename); |
| 50 | + } else { |
| 51 | + res.type(filename); |
| 52 | + } |
| 53 | + res.send(data); |
| 54 | + } |
| 55 | + } catch (err) { |
| 56 | + logger.error(`internal error ${err} getting blob ${uuid}`); |
| 57 | + res.status(500).send(`internal error: ${err}`); |
| 58 | + } |
| 59 | + }); |
| 60 | +} |
0 commit comments