This repository has been archived by the owner on Oct 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
333 lines (305 loc) · 8.27 KB
/
index.js
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
'use strict';
/**
* index.js
*
* App entry point
*/
var fs = require('mz/fs')
var cuid = require('cuid')
var sharp = require('sharp')
var busboy = require('co-busboy')
var mimetypes = require('mime-types')
var mongo = require('yieldb').connect
var escapeString = require('escape-string-regexp')
var pinyin = require('pinyin')
var koa = require('koa')
var logger = require('koa-logger')
var bodyParser = require('koa-bodyparser')
var routerFactory = require('koa-router')
var staticFile = require('koa-static')
var templateLoader = require('./templates/marko-template-loader')
var homeTemplate = templateLoader('./home.marko')
var shotTemplate = templateLoader('./shot.marko')
var searchTemplate = templateLoader('./search.marko')
var recentTemplate = templateLoader('./recent.marko')
var analyticsTemplate = templateLoader('./analytics.marko')
var headerTemplate = templateLoader('./header.marko')
var searchBoxTemplate = templateLoader('./search-box.marko')
var pagingTemplate = templateLoader('./paging.marko')
var commonMetaTemplate = templateLoader('./common-meta.marko')
var tmpDirectory = 'upload-tmp/'
var uploadDirectory = 'public/upload/'
var databaseUrl = 'mongodb://localhost:27017/animeshot?w=1'
var siteDomain = 'https://as.bitinn.net'
var assetRevision = 'r3'
var app = koa()
var router = routerFactory()
var mongoConnection
app.use(logger())
// only serve file from node.js during development
if (app.env === 'dev') {
app.use(staticFile('public', {
maxage: 1000 * 60 * 60 * 24
}))
}
// database connection
app.use(function *(next) {
try {
if (!mongoConnection) {
mongoConnection = yield mongo(databaseUrl)
}
this.db = mongoConnection
} catch(err) {
this.db = false
this.app.emit('error', err, this)
}
yield next
})
// error handler
app.use(function *(next) {
if (this.db === false) {
this.status = 500
this.body = 'mongodb down'
return
}
try {
yield next
} catch (err) {
this.app.emit('error', err, this)
this.status = 500
this.body = 'internal error'
return
}
})
app.use(bodyParser())
// home page
router.get('/', function *(next) {
yield next
var db = this.db
var Shots = db.col('shots')
var result = yield Shots.find().sort({ created: -1 }).limit(4)
var data = {
shots: result
, domain: siteDomain
, analytics: analyticsTemplate
, header: headerTemplate
, searchBox: searchBoxTemplate
, meta: commonMetaTemplate
, rev: assetRevision
}
this.body = homeTemplate.renderSync(data)
})
// shot page
router.get('/shots/:id', function *(next) {
yield next
var db = this.db
var Shots = db.col('shots')
var shot = yield Shots.findOne({ sid: this.params.id })
if (!shot) {
this.redirect('/')
return
}
var data = {
text: shot.text
, sid: shot.sid
, size: ['300', '600', '1200']
, domain: siteDomain
, analytics: analyticsTemplate
, header: headerTemplate
, searchBox: searchBoxTemplate
, meta: commonMetaTemplate
, rev: assetRevision
}
this.body = shotTemplate.renderSync(data)
})
// search page
router.get('/search', function *(next) {
yield next
var db = this.db
var Shots = db.col('shots')
var result = []
if (!!this.query.q && this.query.q.length > 0 && this.query.q.length < 100) {
var normalized = [].concat.apply([], pinyin(this.query.q))
result = yield Shots.find({
normalized: {
$regex: new RegExp('(.*)' + escapeString(normalized.join(' ')) + '(.*)', 'i')
}
}).sort({ created: -1 }).limit(20)
}
var data = {
shots: result
, q: this.query.q
, domain: siteDomain
, analytics: analyticsTemplate
, header: headerTemplate
, searchBox: searchBoxTemplate
, paging: pagingTemplate
, meta: commonMetaTemplate
, rev: assetRevision
, next: result.length === 20 ? 2 : 1
, page: 'search'
}
this.body = searchTemplate.renderSync(data)
})
// search paging
router.get('/search/page/:page', function *(next) {
yield next
var db = this.db
var page = parseInt(this.params.page, 10) || 1
if (page < 1) {
this.redirect('/recent')
return
}
var Shots = db.col('shots')
var result = []
if (!!this.query.q && this.query.q.length > 0 && this.query.q.length < 100) {
var normalized = [].concat.apply([], pinyin(this.query.q))
result = yield Shots.find({
normalized: {
$regex: new RegExp('(.*)' + escapeString(normalized.join(' ')) + '(.*)', 'i')
}
}).sort({ created: -1 }).limit(20).skip((page - 1) * 20)
}
var data = {
shots: result
, q: this.query.q
, domain: siteDomain
, analytics: analyticsTemplate
, header: headerTemplate
, searchBox: searchBoxTemplate
, paging: pagingTemplate
, meta: commonMetaTemplate
, rev: assetRevision
, prev: page - 1
, next: result.length === 20 ? page + 1 : 1
, page: 'search'
}
this.body = searchTemplate.renderSync(data)
})
// recent page
router.get('/recent', function *(next) {
yield next
var db = this.db
var Shots = db.col('shots')
var result = yield Shots.find().sort({ created: -1 }).limit(20)
var data = {
shots: result
, domain: siteDomain
, analytics: analyticsTemplate
, header: headerTemplate
, searchBox: searchBoxTemplate
, paging: pagingTemplate
, meta: commonMetaTemplate
, rev: assetRevision
, next: result.length === 20 ? 2 : 1
, page: 'recent'
}
this.body = recentTemplate.renderSync(data)
})
// recent paging
router.get('/recent/page/:page', function *(next) {
yield next
var db = this.db
var page = parseInt(this.params.page, 10) || 1
if (page < 1) {
this.redirect('/recent')
return
}
var Shots = db.col('shots')
var result = yield Shots.find().sort({ created: -1 }).limit(20).skip((page - 1) * 20)
var data = {
shots: result
, domain: siteDomain
, analytics: analyticsTemplate
, header: headerTemplate
, searchBox: searchBoxTemplate
, paging: pagingTemplate
, meta: commonMetaTemplate
, rev: assetRevision
, prev: page - 1
, next: result.length === 20 ? page + 1 : 1
, page: 'recent'
}
this.body = recentTemplate.renderSync(data)
})
// file upload
router.post('/api/files', function *(next) {
yield next
var headers = this.headers
var body = busboy(this, {
autoFields: true
, checkFile: function (fn, file, name, enc, mime) {
var ext = mimetypes.extension(mime)
if (ext !== 'jpeg' && ext !== 'png') {
return new Error('file type not supported')
}
}
})
var part, p1, p2, p3, hash, s1
while (part = yield body) {
hash = cuid()
s1 = sharp().limitInputPixels(4000 * 4000)
s1 = part.pipe(s1)
p1 = s1.clone().resize(300).quality(95).toFile(tmpDirectory + hash + '.300.jpg')
p2 = s1.clone().resize(600).quality(95).toFile(tmpDirectory + hash + '.600.jpg')
p3 = s1.clone().resize(1200).quality(95).toFile(tmpDirectory + hash + '.1200.jpg')
yield Promise.all([p1, p2, p3])
}
this.body = hash
})
// create shot
router.post('/api/shots', function *(next) {
yield next
var db = this.db
var body = this.request.body
var hash = body.hash.replace(/\W/g, '').substr(0, 25)
var text = body.text.substr(0, 140)
var normalized = [].concat.apply([], pinyin(text))
var size = [300, 600, 1200]
var filename
for (var i = 0; i < size.length; i++) {
filename = hash + '.' + size[i] + '.jpg'
yield fs.rename(tmpDirectory + filename, uploadDirectory + filename)
}
var Shots = db.col('shots')
var now = new Date()
yield Shots.insert({
sid: hash
, text: text
, normalized: normalized.join(' ')
, created: now
, updated: now
})
this.body = 'done'
})
router.get('/api/shots', function *(next) {
yield next
var db = this.db
var page = parseInt(this.query.page, 10) > 1 ? parseInt(this.query.page, 10) : 1
var Shots = db.col('shots')
var search = {}
var result
if (!!this.query.q && this.query.q.length > 0 && this.query.q.length < 100) {
var normalized = [].concat.apply([], pinyin(this.query.q))
search.normalized = {
$regex: new RegExp('(.*)' + escapeString(normalized.join(' ')) + '(.*)', 'i')
}
}
result = yield Shots.find(search).sort({ created: -1 }).limit(20).skip((page - 1) * 20)
var data = result.map(function (shot) {
delete shot._id
shot.url = siteDomain + '/shots/' + shot.sid
shot.image_thumbnail = siteDomain + '/upload/' + shot.sid + '.300.jpg'
shot.image_preview = siteDomain + '/upload/' + shot.sid + '.600.jpg'
shot.image_large = siteDomain + '/upload/' + shot.sid + '.1200.jpg'
return shot
})
this.body = data
})
app.use(router.routes())
app.use(router.allowedMethods())
if (app.env === 'dev') {
app.listen(8080)
} else {
app.listen(8082)
}