2023-05-14 13:52:47 +02:00
|
|
|
import { readFile, stat } from 'node:fs/promises'
|
|
|
|
import { basename } from 'node:path'
|
|
|
|
|
2023-05-23 09:39:00 +02:00
|
|
|
import { Adapters, BASE, create, FileDTO, Note, NoteMeta } from '@cryptgeon/shared'
|
2023-05-14 13:52:47 +02:00
|
|
|
import mime from 'mime'
|
2024-03-03 01:22:39 +01:00
|
|
|
import { AES, Hex } from 'occulto'
|
2023-05-14 13:52:47 +02:00
|
|
|
|
2024-03-04 15:15:47 +01:00
|
|
|
export type UploadOptions = Pick<Note, 'views' | 'expiration'> & { password?: string }
|
2023-05-14 13:52:47 +02:00
|
|
|
|
2024-03-03 01:22:39 +01:00
|
|
|
export async function upload(input: string | string[], options: UploadOptions): Promise<string> {
|
|
|
|
const { password, ...noteOptions } = options
|
|
|
|
const derived = options.password ? await AES.derive(options.password) : undefined
|
|
|
|
const key = derived ? derived[0] : await AES.generateKey()
|
2023-05-23 09:39:00 +02:00
|
|
|
|
2024-03-03 01:22:39 +01:00
|
|
|
let contents: string
|
|
|
|
let type: NoteMeta['type']
|
|
|
|
if (typeof input === 'string') {
|
|
|
|
contents = await Adapters.Text.encrypt(input, key)
|
|
|
|
type = 'text'
|
|
|
|
} else {
|
|
|
|
const files: FileDTO[] = await Promise.all(
|
|
|
|
input.map(async (path) => {
|
|
|
|
const data = new Uint8Array(await readFile(path))
|
|
|
|
const stats = await stat(path)
|
|
|
|
const extension = path.substring(path.indexOf('.') + 1)
|
|
|
|
const type = mime.getType(extension) ?? 'application/octet-stream'
|
|
|
|
return {
|
|
|
|
name: basename(path),
|
|
|
|
size: stats.size,
|
|
|
|
contents: data,
|
|
|
|
type,
|
|
|
|
} satisfies FileDTO
|
|
|
|
})
|
|
|
|
)
|
|
|
|
contents = await Adapters.Files.encrypt(files, key)
|
|
|
|
type = 'file'
|
2023-05-14 13:52:47 +02:00
|
|
|
}
|
2024-03-03 01:22:39 +01:00
|
|
|
|
|
|
|
// Create the actual note and upload it.
|
|
|
|
const note: Note = { ...noteOptions, contents, meta: { type, derivation: derived?.[1] } }
|
|
|
|
const result = await create(note)
|
|
|
|
let url = `${BASE}/note/${result.id}`
|
|
|
|
if (!derived) url += `#${Hex.encode(key)}`
|
|
|
|
return url
|
2023-05-14 13:52:47 +02:00
|
|
|
}
|