| … | … | @@ -1,5 +1,74 @@ |
| 1 | import db from './db.json' with { type: 'json'} |
| 1 | 2 | import { serveDir } from 'https://deno.land/std/http/file_server.ts' |
| 3 | import { apds } from './apds.js' |
| 2 | 4 | |
| 3 | | Deno.serve((r) => { |
| 4 | | return serveDir(r, {quiet: 'True'}) |
| 5 | await apds.start('apdsv1') |
| 6 | |
| 7 | if (!await apds.pubkey()) { |
| 8 | const keypair = await apds.generate() |
| 9 | await apds.put('keypair', keypair) |
| 10 | console.log('New keypair generated, your pubkey: ' + await apds.pubkey()) |
| 11 | } else { |
| 12 | console.log('apdsbot started, your pubkey: ' + await apds.pubkey()) |
| 13 | } |
| 14 | |
| 15 | const apdsbot = async (ws) => { |
| 16 | ws.onopen = async () => { |
| 17 | console.log('CONNECTED!') |
| 18 | } |
| 19 | ws.onmessage = async (m) => { |
| 20 | console.log('RECEIVED:' + m.data) |
| 21 | if (m.data.length === 44) { |
| 22 | const latest = await apds.getLatest(m.data) |
| 23 | if (latest) { ws.send(latest.sig) } |
| 24 | const got = await apds.get(m.data) |
| 25 | if (got) { ws.send(got) } |
| 26 | } |
| 27 | if (m.data.length != 44) { |
| 28 | await apds.make(m.data) |
| 29 | await apds.add(m.data) |
| 30 | } |
| 31 | } |
| 32 | ws.onclose = () => { |
| 33 | console.log('DISCONNECTED!') |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | const directory = async (r) => { |
| 38 | const url = new URL(r.url) |
| 39 | const key = url.pathname.substring(1) |
| 40 | const header = new Headers() |
| 41 | header.append("Content-Type", "application/json") |
| 42 | header.append("Access-Control-Allow-Origin", "*") |
| 43 | if (db[key]) { |
| 44 | const ar = db[key] |
| 45 | return new Response(JSON.stringify(ar), {headers: header}) |
| 46 | } |
| 47 | if (await apds.getLatest(key)) { |
| 48 | const latest = await apds.getLatest(key) |
| 49 | if (!latest.text) { |
| 50 | const text = await apds.get(latest.opened.substring(13)) |
| 51 | latest.text = text.value |
| 52 | } |
| 53 | return new Response(JSON.stringify(latest), {headers: header}) |
| 54 | } |
| 55 | else if (key != '' && await apds.query(key)) { |
| 56 | const q = await apds.query(key) |
| 57 | return new Response(JSON.stringify(q), {headers: header}) |
| 58 | } else { |
| 59 | return serveDir(r, {quiet: 'True'}) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | Deno.serve( |
| 64 | {port: 9000}, |
| 65 | async (r) => { |
| 66 | try { |
| 67 | const { socket, response } = Deno.upgradeWebSocket(r) |
| 68 | await apdsbot(socket) |
| 69 | return response |
| 70 | } catch (err) {} |
| 71 | try { |
| 72 | return await directory(r) |
| 73 | } catch (err) {console.log(err)} |
| 5 | 74 | }) |