-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.mjs
237 lines (212 loc) · 10.1 KB
/
index.mjs
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
import express from 'express'
import Sequelize from 'sequelize'
import FeedModelBuilder, { lengths } from './FeedModel.mjs'
import axios from 'axios'
import * as cheerio from 'cheerio'
import morgan from 'morgan'
import { trim, truncate, slugify, cleanify, sanitize, isValidUrl } from './strings.mjs'
import { dirname } from 'path'
import { fileURLToPath } from 'url'
import cors from 'cors'
import jschardet from 'jschardet'
import charset from 'charset'
import iconv from 'iconv-lite'
import * as env from './env.mjs'
const PORT = env.CONTAINER_EXT_PORT || env.PORT
const MINUTE = 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const cleanNameStr = (n) => slugify(truncate(cleanify(sanitize(trim(n))), lengths.name))
const cleanUrlStr = (u) => truncate(trim(u), lengths.url)
const cleanTitleStr = (t) => truncate(cleanify(trim(t)), lengths.title)
const cleanDescriptionStr = (d) => truncate(cleanify(trim(d)), lengths.description)
const cleanSearchStr = (d) => cleanify(sanitize(trim(d)))
const sequelize = new Sequelize(env.DATABASE_URL, {
timezone: env.TZ,
dialectOptions: {
timezone: env.TZ, // Duplicate because of a bug: https://github.com/sequelize/sequelize/issues/10921
},
logging: false,
})
axios.interceptors.response.use((response) => {
const chardetResult = jschardet.detect(response.data)
const encoding = chardetResult?.encoding || charset(response.headers, response.data)
response.data = iconv.decode(response.data, encoding)
return response
})
sequelize
.authenticate()
.then(() => {
console.log(`Connection to database « ${sequelize.getDatabaseName()} » has been established successfully`)
})
.catch((err) => {
console.error(`Unable to connect to database`, err)
throw err
})
.then(() => {
const { findByName, list, insert, remove, count, search, suggest } = FeedModelBuilder(sequelize)
const app = express()
app.set('view engine', 'ejs')
app.set('views', 'src/views')
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'))
app.use(cors())
const __dirname = dirname(fileURLToPath(import.meta.url))
app.use(
'/static',
express.static(__dirname + '/static', {
index: false,
maxAge: DAY * 90,
})
)
app.use('/manifest.json', express.static(__dirname + '/static/manifest.json'))
app.get('/', (req, res) => {
const name = cleanNameStr(req.query.name || req.query.n)
const title = cleanTitleStr(req.query.title || req.query.t)
const description = cleanDescriptionStr(req.query.description || req.query.d)
const url = cleanUrlStr(req.query.url || req.query.u)
const rootUrl = env.ROOT_URL || req.protocol + '://' + req.get('host')
const n = req.query.name || req.query.n
const limit = Math.abs(parseInt(req.query.limit || req.query.l, 10)) || 25
if (name && !url) {
if (n !== name) return res.redirect(302, `./?n=${name}`)
return findByName({ name, limit }).then((entries) => {
res.type('text/xml')
return res.render('rss', {
rootUrl,
public: env.PUBLIC,
title: name,
titleWithFeedName: false,
url: `/?n=${name}`,
entries,
})
})
}
res.set('Cache-control', `public, max-age=${DAY}`)
// Using share target API in Chrome sends URL in description :/ so use description field in that case and empty it
const descriptionIsUrl = !url && description.startsWith('http')
const hackUrl = descriptionIsUrl ? description : url
const hackDescription = descriptionIsUrl ? '' : description
return res.render('index', {
rootUrl,
public: env.PUBLIC,
lengths,
name,
url: hackUrl,
description: hackDescription,
title,
})
})
if (!env.PUBLIC) {
console.log('enable /list')
app.get('/list', (req, res) =>
list().then((feeds) => {
res.set('Cache-control', `public, max-age=${MINUTE}`)
res.render('list', { feeds })
})
)
console.log('enable /search')
app.get('/search', (req, res) => {
const rootUrl = env.ROOT_URL || req.protocol + '://' + req.get('host')
const query = cleanSearchStr(req.query.query || req.query.q)
if (!query) return res.status(404).end('404 : Missing query parameter')
if (query.length < 2)
return res.status(400).end('400 : query parameter should be at least 2 characters')
const limit = Math.abs(parseInt(req.query.limit || req.query.l, 10)) || 100
return search({ query, limit }).then((entries) => {
res.type('text/xml')
return res.render('rss', {
rootUrl,
public: env.PUBLIC,
title: `${entries.length} result${entries.length > 1 ? 's' : ''} for search « ${query} »`,
titleWithFeedName: true,
url: `/search?q=${query}`,
entries,
})
})
})
console.log('enable /suggest')
app.get('/suggest', (req, res) => {
const query = cleanSearchStr(req.query.query || req.query.q)
if (!query) return res.status(404).end('404 : Missing query parameter')
if (query.length < 2)
return res.status(400).end('400 : query parameter should be at least 2 characters')
return suggest({ query }).then((results) => res.json(results))
})
}
app.get('/add', (req, res) => {
const name = cleanNameStr(req.query.name || req.query.n)
const url = cleanUrlStr(req.query.url || req.query.u)
const title = cleanTitleStr(req.query.title || req.query.t)
const description = cleanDescriptionStr(req.query.description || req.query.d)
if (!name || !url) return res.status(404).end('404 : Missing name or url parameter')
const shouldLimitToWikipedia = env.PUBLIC && name === 'somename'
if (!isValidUrl(url, shouldLimitToWikipedia)) return res.status(400).end('403 : Forbidden')
return (
title
? Promise.resolve({ title, description })
: Promise.resolve().then(() =>
axios
.get(encodeURI(url), {
responseType: 'arraybuffer',
headers: {
'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0',
},
timeout: 5_000,
})
.then((response = {}) => {
const { status, data } = response
if (status === 200) {
const $ = cheerio.load(data, {
normalizeWhitespace: true,
xmlMode: false,
decodeEntities: true,
})
const titleFromPage = $('head title').text() || $('body title').text()
return {
title: truncate(cleanify(titleFromPage), lengths.title),
description: truncate(
cleanify($('head meta[name=description]').attr('content')),
lengths.description
),
}
}
})
.catch((error) => {
console.log(error)
})
)
)
.then((metas = {}) => {
const { title, description } = metas
return insert({ name, url, title: title || url, description })
})
.then(() => res.redirect(302, `./?n=${name}`))
.catch((err) => {
const msg = `Error while inserting '${url}' in '${name}'`
console.error(msg, err)
res.sendStatus(500).end(msg)
})
})
app.get('/del', (req, res) => {
const name = cleanNameStr(req.query.name || req.query.n)
const url = cleanUrlStr(req.query.url || req.query.u)
if (!name || !url) return res.status(404).end('404 : Missing name or url parameter')
if (!isValidUrl(url)) res.status(400).end('400 : not an URL')
return remove({ name, url })
.then(() => res.redirect(302, `./?n=${name}`))
.catch((err) => {
const msg = `Error while removing '${url}' in '${name}'`
console.error(msg, err)
res.sendStatus(500).end(msg)
})
})
app.get('/count', (req, res) => {
const name = cleanNameStr(req.query.name || req.query.n)
if (!name) return res.status(404).end('404 : Missing name parameter')
return count({ name }).then(([count]) => res.json(count))
})
app.listen(PORT, () => {
console.log(`rsstodolist-node-server listening at http://127.0.0.1:${PORT}`)
})
})