-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.mjs
More file actions
131 lines (114 loc) · 2.21 KB
/
main.mjs
File metadata and controls
131 lines (114 loc) · 2.21 KB
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
import express from 'express'
import { mkdirSync } from 'fs'
import { join } from 'path'
import { screenshot } from './lib/browse.mjs'
import { data } from './lib/data.mjs'
import { randomId } from './lib/randomId.mjs'
const STATIC_PATH = join(
import.meta.dirname,
'public'
)
const DATA_PATH = join(
import.meta.dirname,
'public',
'data'
)
mkdirSync(DATA_PATH, { recursive: true })
const IMG_PATH = join(
import.meta.dirname,
'public',
'img'
)
mkdirSync(IMG_PATH, { recursive: true })
const appData = data(DATA_PATH)
const app = express()
app.use(express.json())
async function readSessions() {
return (await appData.read('sessions')) ?? []
}
async function updateSession({
id,
events,
url,
}) {
const sessionData = await readSessions()
let session = sessionData.find(
(x) => x.id === id
)
if (!session) {
session = {
id,
time: Date.now(),
url,
}
sessionData.push(session)
await appData.write('sessions', sessionData)
}
const sessionKey = `session.${session.id}`
session = Object.assign(
{},
session,
await appData.read(sessionKey)
)
const {
pageData,
url: updatedUrl,
imageUrl: image,
thumbUrl: thumbImage,
} = await screenshot(
IMG_PATH,
url,
session.id,
events
)
if (!('history' in session)) {
session.history = []
}
if (
session.url?.length > 0 &&
session.history[session.history.length - 1]
?.url !== session.url
) {
session.history.push({
data: session.data,
url: session.url,
image: session.image,
thumbImage: session.thumbImage,
})
}
session.data = pageData
session.url = updatedUrl
session.image = image
session.thumbImage = thumbImage
await appData.write(sessionKey, session)
return session
}
app.post(
'/sessions',
async function (req, res) {
if ('id' in req.body) {
return res.json(
await updateSession(req.body)
)
}
const newSession = {
id: randomId(),
time: Date.now(),
url: req.body?.url ?? '',
}
await appData.write('sessions', [
...(await readSessions()),
newSession,
])
res.json(newSession)
}
)
app.use(express.static(STATIC_PATH))
app.listen(7000, function () {
console.log(
'Server running on http://localhost:7000'
)
console.log(
`Static content served from ${STATIC_PATH}`
)
})