-
Notifications
You must be signed in to change notification settings - Fork 261
/
index.js
1516 lines (1447 loc) · 43.5 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Twikoo cloudbase function v1.3.0
* (c) 2020-2021 iMaeGoo
* Released under the MIT License.
*/
// 三方依赖 / 3rd party dependencies
const tcb = require('@cloudbase/node-sdk') // 云开发 SDK
const md5 = require('blueimp-md5') // MD5 加解密
const bowser = require('bowser') // UserAgent 格式化
const nodemailer = require('nodemailer') // 发送邮件
const axios = require('axios') // 发送 REST 请求
const qs = require('querystring') // URL 参数格式化
const $ = require('cheerio') // jQuery 服务器版
const { AkismetClient } = require('akismet-api') // 反垃圾 API
const createDOMPurify = require('dompurify') // 反 XSS
const { JSDOM } = require('jsdom') // document.window 服务器版
const xml2js = require('xml2js') // XML 解析
const marked = require('marked') // Markdown 解析
const CryptoJS = require('crypto-js') // 编解码
const tencentcloud = require('tencentcloud-sdk-nodejs') // 腾讯云 API NODEJS SDK
// 云函数 SDK / tencent cloudbase sdk
const app = tcb.init({ env: tcb.SYMBOL_CURRENT_ENV })
const auth = app.auth()
const db = app.database()
const _ = db.command
// 初始化反 XSS
const window = new JSDOM('').window
const DOMPurify = createDOMPurify(window)
// 常量 / constants
const VERSION = '1.3.0'
const RES_CODE = {
SUCCESS: 0,
FAIL: 1000,
EVENT_NOT_EXIST: 1001,
PASS_EXIST: 1010,
CONFIG_NOT_EXIST: 1020,
CREDENTIALS_NOT_EXIST: 1021,
CREDENTIALS_INVALID: 1025,
PASS_NOT_EXIST: 1022,
PASS_NOT_MATCH: 1023,
NEED_LOGIN: 1024,
FORBIDDEN: 1403,
AKISMET_ERROR: 1030
}
const ADMIN_USER_ID = 'admin'
// 全局变量 / variables
// 警告:全局定义的变量,会被云函数缓存,请慎重定义全局变量
// 参考 https://docs.cloudbase.net/cloud-function/deep-principle.html 中的 “实例复用”
let config
let transporter
// 云函数入口点 / entry point
exports.main = async (event, context) => {
console.log('请求方法:', event.event)
console.log('请求参数:', event)
let res = {}
await readConfig()
try {
switch (event.event) {
case 'GET_FUNC_VERSION':
res = getFuncVersion()
break
case 'COMMENT_GET':
res = await commentGet(event)
break
case 'COMMENT_GET_FOR_ADMIN':
res = await commentGetForAdmin(event)
break
case 'COMMENT_SET_FOR_ADMIN':
res = await commentSetForAdmin(event)
break
case 'COMMENT_DELETE_FOR_ADMIN':
res = await commentDeleteForAdmin(event)
break
case 'COMMENT_IMPORT_FOR_ADMIN':
res = await commentImportForAdmin(event)
break
case 'COMMENT_LIKE':
res = await commentLike(event)
break
case 'COMMENT_SUBMIT':
res = await commentSubmit(event)
break
case 'POST_SUBMIT':
res = await postSubmit(event.comment, context)
break
case 'COUNTER_GET':
res = await counterGet(event)
break
case 'GET_PASSWORD_STATUS':
res = await getPasswordStatus()
break
case 'SET_PASSWORD':
res = await setPassword(event)
break
case 'GET_CONFIG':
res = getConfig()
break
case 'GET_CONFIG_FOR_ADMIN':
res = await getConfigForAdmin()
break
case 'SET_CONFIG':
res = await setConfig(event)
break
case 'LOGIN':
res = await login(event.password)
break
case 'GET_COMMENTS_COUNT': // >= 0.2.7
res = await getCommentsCount(event)
break
case 'GET_RECENT_COMMENTS': // >= 0.2.7
res = await getRecentComments(event)
break
default:
if (event.event) {
res.code = RES_CODE.EVENT_NOT_EXIST
res.message = '请更新 Twikoo 云函数至最新版本'
} else {
res.code = RES_CODE.SUCCESS
res.message = 'Twikoo 云函数运行正常,请参考 https://twikoo.js.org/quick-start.html#%E5%89%8D%E7%AB%AF%E9%83%A8%E7%BD%B2 完成前端的配置'
}
}
} catch (e) {
console.error('Twikoo 遇到错误,请参考以下错误信息。如有疑问,请反馈至 https://github.com/imaegoo/twikoo/issues')
console.error('请求参数:', event)
console.error('错误信息:', e)
res.code = RES_CODE.FAIL
res.message = e.message
}
console.log('请求返回:', res)
return res
}
// 获取 Twikoo 云函数版本
function getFuncVersion () {
return {
code: RES_CODE.SUCCESS,
version: VERSION
}
}
// 判断是否存在管理员密码
async function getPasswordStatus () {
return {
code: RES_CODE.SUCCESS,
status: !!config.ADMIN_PASS,
credentials: !!config.CREDENTIALS,
version: VERSION
}
}
// 写入管理密码
async function setPassword (event) {
const isAdminUser = await isAdmin()
// 如果数据库里没有密码,则写入密码
// 如果数据库里有密码,则只有管理员可以写入密码
if (config.ADMIN_PASS && !isAdminUser) {
return { code: RES_CODE.PASS_EXIST, message: '请先登录再修改密码' }
}
if (!config.CREDENTIALS && !event.credentials) {
return { code: RES_CODE.CREDENTIALS_NOT_EXIST, message: '未配置登录私钥' }
}
if (!config.CREDENTIALS && event.credentials) {
const checkResult = await checkAndSaveCredentials(event.credentials)
if (!checkResult) {
return { code: RES_CODE.CREDENTIALS_INVALID, message: '无效的私钥文件' }
}
}
const ADMIN_PASS = md5(event.password)
await writeConfig({ ADMIN_PASS })
return {
code: RES_CODE.SUCCESS
}
}
async function checkAndSaveCredentials (credentials) {
try {
const ticket = getAdminTicket(JSON.parse(credentials))
if (!ticket) return false
await writeConfig({ CREDENTIALS: credentials })
return true
} catch (e) {
console.error('私钥文件异常:', e)
return false
}
}
// 管理员登录
async function login (password) {
if (!config) {
return { code: RES_CODE.CONFIG_NOT_EXIST, message: '数据库无配置' }
}
if (!config.CREDENTIALS) {
return { code: RES_CODE.CREDENTIALS_NOT_EXIST, message: '未配置登录私钥' }
}
if (!config.ADMIN_PASS) {
return { code: RES_CODE.PASS_NOT_EXIST, message: '未配置管理密码' }
}
if (config.ADMIN_PASS !== md5(password)) {
return { code: RES_CODE.PASS_NOT_MATCH, message: '密码错误' }
}
return {
code: RES_CODE.SUCCESS,
ticket: getAdminTicket(JSON.parse(config.CREDENTIALS))
}
}
// 获取管理员登录 ticket
function getAdminTicket (credentials) {
const adminApp = tcb.init({ env: tcb.SYMBOL_CURRENT_ENV, credentials })
const ticket = adminApp.auth().createTicket(ADMIN_USER_ID, {
refresh: 3600 * 1000 // access_token的刷新时间
})
return ticket
}
// 读取评论
async function commentGet (event) {
const res = {}
try {
validate(event, ['url'])
const uid = await auth.getEndUserInfo().userInfo.uid
const isAdminUser = await isAdmin()
const limit = parseInt(config.COMMENT_PAGE_SIZE) || 8
let more = false
let condition
let query
condition = {
url: _.in(getUrlQuery(event.url)),
rid: _.in(['', null])
}
// 查询非垃圾评论 + 自己的评论
query = getCommentQuery({ condition, uid, isAdminUser })
// 读取总条数
const count = await db
.collection('comment')
.where(query)
.count()
// 读取主楼
if (event.before) {
condition.created = _.lt(event.before)
}
// 不包含置顶
condition.top = _.neq(true)
query = getCommentQuery({ condition, uid, isAdminUser })
const main = await db
.collection('comment')
.where(query)
.orderBy('created', 'desc')
// 流式分页,通过多读 1 条的方式,确认是否还有更多评论
.limit(limit + 1)
.get()
if (main.data.length > limit) {
// 还有更多评论
more = true
// 删除多读的 1 条
main.data.splice(limit, 1)
}
let top = []
if (!config.TOP_DISABLED && !event.before) {
// 查询置顶评论
query = {
...condition,
top: true
}
top = await db
.collection('comment')
.where(query)
.orderBy('updated', 'desc')
.get()
// 合并置顶评论和非置顶评论
main.data = [
...top.data,
...main.data
]
}
condition = {
rid: _.in(main.data.map((item) => item._id))
}
query = getCommentQuery({ condition, uid, isAdminUser })
// 读取回复楼
const reply = await db
.collection('comment')
.where(query)
.get()
res.data = parseComment([...main.data, ...reply.data], uid)
res.more = more
res.count = count.total
} catch (e) {
res.data = []
res.message = e.message
}
return res
}
function getCommentQuery ({ condition, uid, isAdminUser }) {
return _.or(
{ ...condition, isSpam: _.neq(isAdminUser ? 'imaegoo' : true) },
{ ...condition, uid }
)
}
// 同时查询 /path 和 /path/ 的评论
function getUrlQuery (url) {
const variantUrl = url[url.length - 1] === '/' ? url.substring(0, url.length - 1) : `${url}/`
return [url, variantUrl]
}
// 筛除隐私字段,拼接回复列表
function parseComment (comments, uid) {
const result = []
for (const comment of comments) {
if (!comment.rid) {
const replies = comments
.filter((item) => item.rid === comment._id)
.map((item) => toCommentDto(item, uid, [], comments))
.sort((a, b) => a.created - b.created)
result.push(toCommentDto(comment, uid, replies))
}
}
return result
}
// 将评论记录转换为前端需要的格式
function toCommentDto (comment, uid, replies = [], comments = []) {
let displayOs = ''
let displayBrowser = ''
try {
const ua = bowser.getParser(comment.ua)
const os = ua.getOS()
displayOs = [os.name, os.versionName ? os.versionName : os.version].join(' ')
displayBrowser = [ua.getBrowserName(), ua.getBrowserVersion()].join(' ')
} catch (e) {
console.log('bowser 错误:', e)
}
return {
id: comment._id,
nick: comment.nick,
avatar: comment.avatar,
mailMd5: comment.mailMd5 || md5(comment.mail),
link: comment.link,
comment: comment.comment,
os: displayOs,
browser: displayBrowser,
master: comment.master,
like: comment.like ? comment.like.length : 0,
liked: comment.like ? comment.like.findIndex((item) => item === uid) > -1 : false,
replies: replies,
rid: comment.rid,
pid: comment.pid,
ruser: ruser(comment.pid, comments),
top: comment.top,
isSpam: comment.isSpam,
created: comment.created,
updated: comment.updated
}
}
// 获取回复人昵称 / Get replied user nick name
function ruser (pid, comments = []) {
const comment = comments.find((item) => item._id === pid)
return comment ? comment.nick : null
}
// 管理员读取评论
async function commentGetForAdmin (event) {
const res = {}
const isAdminUser = await isAdmin()
if (isAdminUser) {
validate(event, ['per', 'page'])
const collection = db
.collection('comment')
const condition = getCommentSearchCondition(event)
const count = await collection
.where(condition)
.count()
const data = await collection
.where(condition)
.orderBy('created', 'desc')
.skip(event.per * (event.page - 1))
.limit(event.per)
.get()
res.code = RES_CODE.SUCCESS
res.count = count.total
res.data = parseCommentForAdmin(data.data)
} else {
res.code = RES_CODE.NEED_LOGIN
res.message = '请先登录'
}
return res
}
function getCommentSearchCondition (event) {
let condition = {}
if (event.type) {
switch (event.type) {
case 'VISIBLE':
condition = { isSpam: _.neq(true) }
break
case 'HIDDEN':
condition = { isSpam: true }
break
}
}
if (event.keyword) {
const regExp = new db.RegExp({
regexp: event.keyword,
options: 'i'
})
condition = _.or(
{ ...condition, nick: regExp },
{ ...condition, mail: regExp },
{ ...condition, link: regExp },
{ ...condition, ip: regExp },
{ ...condition, comment: regExp },
{ ...condition, url: regExp },
{ ...condition, href: regExp }
)
}
return condition
}
function parseCommentForAdmin (comments) {
for (const comment of comments) {
comment.commentText = $(comment.comment).text()
}
return comments
}
// 管理员修改评论
async function commentSetForAdmin (event) {
const res = {}
const isAdminUser = await isAdmin()
if (isAdminUser) {
validate(event, ['id', 'set'])
const data = await db
.collection('comment')
.doc(event.id)
.update({
...event.set,
updated: Date.now()
})
res.code = RES_CODE.SUCCESS
res.updated = data.updated
} else {
res.code = RES_CODE.NEED_LOGIN
res.message = '请先登录'
}
return res
}
// 管理员删除评论
async function commentDeleteForAdmin (event) {
const res = {}
const isAdminUser = await isAdmin()
if (isAdminUser) {
validate(event, ['id'])
const data = await db
.collection('comment')
.doc(event.id)
.delete()
res.code = RES_CODE.SUCCESS
res.deleted = data.deleted
} else {
res.code = RES_CODE.NEED_LOGIN
res.message = '请先登录'
}
return res
}
// 管理员导入评论
async function commentImportForAdmin (event) {
const res = {}
let logText = ''
const log = (message) => {
logText += `${new Date().toLocaleString()} ${message}\n`
}
const isAdminUser = await isAdmin()
if (isAdminUser) {
try {
validate(event, ['source', 'fileId'])
log(`开始导入 ${event.source}`)
switch (event.source) {
case 'valine': {
const valineDb = await readFile(event.fileId, 'json', log)
await commentImportValine(valineDb, log)
break
}
case 'disqus': {
const disqusDb = await readFile(event.fileId, 'xml', log)
await commentImportDisqus(disqusDb, log)
break
}
case 'artalk': {
const artalkDb = await readFile(event.fileId, 'json', log)
await commentImportArtalk(artalkDb, log)
break
}
default:
throw new Error(`不支持 ${event.source} 的导入,请更新 Twikoo 云函数至最新版本`)
}
// 删除导入完成的文件
await app.deleteFile({ fileList: [event.fileId] })
} catch (e) {
log(e.message)
}
res.code = RES_CODE.SUCCESS
res.log = logText
console.log(logText)
} else {
res.code = RES_CODE.NEED_LOGIN
res.message = '请先登录'
}
return res
}
// 读取云存储中的文件并转为 js object
async function readFile (fileId, type, log) {
try {
const result = await app.downloadFile({ fileID: fileId })
log('评论文件下载成功')
let content = result.fileContent.toString('utf8')
log('评论文件读取成功')
if (type === 'json') {
content = jsonParse(content)
log('评论文件 JSON 解析成功')
} else if (type === 'xml') {
content = await xml2js.parseStringPromise(content)
log('评论文件 XML 解析成功')
}
return content
} catch (e) {
log(`评论文件读取失败:${e.message}`)
}
}
// 兼容 Leancloud 两种 JSON 导出格式
function jsonParse (content) {
try {
return JSON.parse(content)
} catch (e1) {
const results = []
const lines = content.split('\n')
for (const line of lines) {
// 逐行 JSON.parse
try {
results.push(JSON.parse(line))
} catch (e2) {}
}
return { results }
}
}
// Valine 导入
async function commentImportValine (valineDb, log) {
if (!valineDb || !valineDb.results) {
log('Valine 评论文件格式有误')
return
}
const comments = []
log(`共 ${valineDb.results.length} 条评论`)
for (const comment of valineDb.results) {
try {
const parsed = {
_id: comment.objectId,
nick: comment.nick,
ip: comment.ip,
mail: comment.mail,
mailMd5: comment.mailMd5,
isSpam: comment.isSpam,
ua: comment.ua || '',
link: comment.link,
pid: comment.pid,
rid: comment.rid,
master: false,
comment: comment.comment,
url: comment.url,
created: new Date(comment.createdAt).getTime(),
updated: new Date(comment.updatedAt).getTime()
}
comments.push(parsed)
log(`${comment.objectId} 解析成功`)
} catch (e) {
log(`${comment.objectId} 解析失败:${e.message}`)
}
}
log(`解析成功 ${comments.length} 条评论`)
const ids = await bulkSaveComments(comments)
log(`导入成功 ${ids.length} 条评论`)
return comments
}
// Disqus 导入
async function commentImportDisqus (disqusDb, log) {
if (!disqusDb || !disqusDb.disqus || !disqusDb.disqus.thread || !disqusDb.disqus.post) {
log('Disqus 评论文件格式有误')
return
}
const comments = []
const getParent = (post) => {
return post.parent ? disqusDb.disqus.post.find((item) => item.$['dsq:id'] === post.parent[0].$['dsq:id']) : null
}
let threads = []
try {
threads = disqusDb.disqus.thread.map((thread) => {
return {
id: thread.$['dsq:id'],
title: thread.title[0],
url: thread.id[0],
href: thread.link[0]
}
})
} catch (e) {
log(`无法读取 thread:${e.message}`)
return
}
log(`共 ${disqusDb.disqus.post.length} 条评论`)
for (const post of disqusDb.disqus.post) {
try {
const threadId = post.thread[0].$['dsq:id']
const thread = threads.find((item) => item.id === threadId)
const parent = getParent(post)
let root
if (parent) {
let grandParent = parent
while (true) {
if (grandParent) root = grandParent
else break
grandParent = getParent(grandParent)
}
}
comments.push({
_id: post.$['dsq:id'],
nick: post.author[0].name[0],
mail: '',
link: '',
url: thread.url
? thread.url.indexOf('http') === 0
? getRelativeUrl(thread.url)
: thread.url
: getRelativeUrl(thread.href),
href: thread.href,
comment: post.message[0],
ua: '',
ip: '',
isSpam: post.isSpam[0] === 'true' || post.isDeleted[0] === 'true',
master: false,
pid: parent ? parent.$['dsq:id'] : null,
rid: root ? root.$['dsq:id'] : null,
created: new Date(post.createdAt[0]).getTime(),
updated: Date.now()
})
log(`${post.$['dsq:id']} 解析成功`)
} catch (e) {
log(`${post.$['dsq:id']} 解析失败:${e.message}`)
}
}
log(`解析成功 ${comments.length} 条评论`)
const ids = await bulkSaveComments(comments)
log(`导入成功 ${ids.length} 条评论`)
return comments
}
function getRelativeUrl (url) {
let x = url.indexOf('/')
for (let i = 0; i < 2; i++) {
x = url.indexOf('/', x + 1)
}
return url.substring(x)
}
// Artalk 导入
async function commentImportArtalk (artalkDb, log) {
const comments = []
if (!artalkDb || !artalkDb.length) {
log('Artalk 评论文件格式有误')
return
}
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: true,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: true
})
log(`共 ${artalkDb.length} 条评论`)
for (const comment of artalkDb) {
try {
const parsed = {
_id: `artalk${comment.id}`,
nick: comment.nick,
ip: comment.ip,
mail: comment.email,
mailMd5: md5(comment.email),
isSpam: false,
ua: comment.ua || '',
link: comment.link,
pid: comment.rid ? `artalk${comment.rid}` : '',
rid: comment.rid ? `artalk${comment.rid}` : '',
master: false,
comment: DOMPurify.sanitize(marked(comment.content)),
url: getRelativeUrl(comment.page_key),
href: comment.page_key,
created: new Date(comment.date).getTime(),
updated: Date.now()
}
comments.push(parsed)
log(`${comment.id} 解析成功`)
} catch (e) {
log(`${comment.id} 解析失败:${e.message}`)
}
}
log(`解析成功 ${comments.length} 条评论`)
const ids = await bulkSaveComments(comments)
log(`导入成功 ${ids.length} 条评论`)
return comments
}
// 批量导入评论
async function bulkSaveComments (comments) {
const batchRes = await db
.collection('comment')
.add(comments)
return batchRes.ids
}
// 点赞 / 取消点赞
async function commentLike (event) {
const res = {}
let uid
try {
validate(event, ['id'])
uid = await auth.getEndUserInfo().userInfo.uid
} catch (e) {
res.message = e.message
return res
}
res.updated = await like(event.id, uid)
return res
}
// 点赞 / 取消点赞
async function like (id, uid) {
const record = db
.collection('comment')
.where({ _id: id })
const comment = await record.get()
let likes = comment.data[0] && comment.data[0].like ? comment.data[0].like : []
if (likes.findIndex((item) => item === uid) === -1) {
// 赞
likes.push(uid)
} else {
// 取消赞
likes = likes.filter((item) => item !== uid)
}
const result = await record.update({ like: likes })
return result.updated
}
/**
* 提交评论。分为多个步骤
* 1. 参数校验
* 2. 预检测垃圾评论(包括限流、人工审核、违禁词检测等)
* 3. 保存到数据库
* 4. 触发异步任务(包括 IM 通知、邮件通知、第三方垃圾评论检测
* 等,因为这些任务比较耗时,所以要放在另一个线程进行)
* @param {String} event.nick 昵称
* @param {String} event.mail 邮箱
* @param {String} event.link 网址
* @param {String} event.ua UserAgent
* @param {String} event.url 评论页地址
* @param {String} event.comment 评论内容
* @param {String} event.pid 回复的 ID
* @param {String} event.rid 评论楼 ID
*/
async function commentSubmit (event) {
const res = {}
// 参数校验
validate(event, ['url', 'ua', 'comment'])
// 限流
await limitFilter()
// 预检测、转换
const data = await parse(event)
// 保存
const comment = await save(data)
res.id = comment.id
// 异步垃圾检测、发送评论通知
try {
await app.callFunction({
name: 'twikoo',
data: { event: 'POST_SUBMIT', comment }
}, { timeout: 300 }) // 设置较短的 timeout 来实现异步
} catch (e) {
console.log('开始异步垃圾检测、发送评论通知')
}
return res
}
// 保存评论
async function save (data) {
const result = await db
.collection('comment')
.add(data)
data.id = result.id
return data
}
// 异步垃圾检测、发送评论通知
async function postSubmit (comment, context) {
if (!isRecursion(context)) return { code: RES_CODE.FORBIDDEN }
// 垃圾检测
await postCheckSpam(comment)
// 发送通知
await sendNotice(comment)
return { code: RES_CODE.SUCCESS }
}
// 发送通知
async function sendNotice (comment) {
if (comment.isSpam && config.NOTIFY_SPAM === 'false') return
await Promise.all([
noticeMaster(comment),
noticeReply(comment),
noticeWeChat(comment),
noticePushPlus(comment),
noticeQQ(comment)
]).catch(err => {
console.error('邮件通知异常:', err)
})
}
// 初始化邮件插件
async function initMailer () {
try {
if (!config || !config.SMTP_USER || !config.SMTP_PASS) {
throw new Error('数据库配置不存在')
}
const transportConfig = {
auth: {
user: config.SMTP_USER,
pass: config.SMTP_PASS
}
}
if (config.SMTP_SERVICE) {
transportConfig.service = config.SMTP_SERVICE
} else if (config.SMTP_HOST) {
transportConfig.host = config.SMTP_HOST
transportConfig.port = parseInt(config.SMTP_PORT)
transportConfig.secure = config.SMTP_SECURE === 'true'
} else {
throw new Error('SMTP 服务器没有配置')
}
transporter = nodemailer.createTransport(transportConfig)
transporter.verify(function (error, success) {
if (error) throw new Error('SMTP 邮箱配置异常:', error)
else if (success) console.log('SMTP 邮箱配置正常')
})
return true
} catch (e) {
console.error('邮件初始化异常:', e.message)
return false
}
}
// 博主通知
async function noticeMaster (comment) {
if (!transporter) if (!await initMailer()) return
if (config.BLOGGER_EMAIL === comment.mail) return
const IM_PUSH_CONFIGS = [
'SC_SENDKEY',
'QM_SENDKEY',
'PUSH_PLUS_TOKEN'
]
// 判断是否存在即时消息推送配置
const hasIMPushConfig = IM_PUSH_CONFIGS.some(item => !!config[item])
// 存在即时消息推送配置,则默认不发送邮件给博主
if (hasIMPushConfig && config.SC_MAIL_NOTIFY !== 'true') return
const SITE_NAME = config.SITE_NAME
const NICK = comment.nick
const COMMENT = comment.comment
const SITE_URL = config.SITE_URL
const POST_URL = appendHashToUrl(comment.href || SITE_URL + comment.url, comment.id)
const emailSubject = config.MAIL_SUBJECT_ADMIN || `${SITE_NAME}上有新评论了`
let emailContent
if (config.MAIL_TEMPLATE_ADMIN) {
emailContent = config.MAIL_TEMPLATE_ADMIN
.replace(/\${SITE_URL}/g, SITE_URL)
.replace(/\${SITE_NAME}/g, SITE_NAME)
.replace(/\${NICK}/g, NICK)
.replace(/\${COMMENT}/g, COMMENT)
.replace(/\${POST_URL}/g, POST_URL)
} else {
emailContent = `
<div style="border-top:2px solid #12addb;box-shadow:0 1px 3px #aaaaaa;line-height:180%;padding:0 15px 12px;margin:50px auto;font-size:12px;">
<h2 style="border-bottom:1px solid #dddddd;font-size:14px;font-weight:normal;padding:13px 0 10px 8px;">
您在<a style="text-decoration:none;color: #12addb;" href="${SITE_URL}" target="_blank">${SITE_NAME}</a>上的文章有了新的评论
</h2>
<p><strong>${NICK}</strong>回复说:</p>
<div style="background-color: #f5f5f5;padding: 10px 15px;margin:18px 0;word-wrap:break-word;">${COMMENT}</div>
<p>您可以点击<a style="text-decoration:none; color:#12addb" href="${POST_URL}" target="_blank">查看回复的完整內容</a><br></p>
</div>`
}
let sendResult
try {
sendResult = await transporter.sendMail({
from: `"${config.SENDER_NAME}" <${config.SENDER_EMAIL}>`,
to: config.BLOGGER_EMAIL || config.SENDER_EMAIL,
subject: emailSubject,
html: emailContent
})
} catch (e) {
sendResult = e
}
console.log('博主通知结果:', sendResult)
return sendResult
}
// 微信通知
async function noticeWeChat (comment) {
if (!config.SC_SENDKEY) {
console.log('没有配置 server 酱,放弃微信通知')
return
}
if (config.BLOGGER_EMAIL === comment.mail) return
const pushContent = getIMPushContent(comment)
let scApiUrl = 'https://sc.ftqq.com'
let scApiParam = {
text: pushContent.subject,
desp: pushContent.content
}
if (config.SC_SENDKEY.substring(0, 3).toLowerCase() === 'sct') {
// 兼容 server 酱测试专版
scApiUrl = 'https://sctapi.ftqq.com'
scApiParam = {
title: pushContent.subject,
desp: pushContent.content
}
}
const sendResult = await axios.post(`${scApiUrl}/${config.SC_SENDKEY}.send`, qs.stringify(scApiParam), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
console.log('微信通知结果:', sendResult)
}
// pushplus 通知
async function noticePushPlus (comment) {
if (!config.PUSH_PLUS_TOKEN) {
console.log('没有配置 pushplus,放弃通知')
return
}
if (config.BLOGGER_EMAIL === comment.mail) return
const pushContent = getIMPushContent(comment)
const ppApiUrl = 'http://pushplus.hxtrip.com/send'
const ppApiParam = {
token: config.PUSH_PLUS_TOKEN,
title: pushContent.subject,
content: pushContent.content
}
const sendResult = await axios.post(ppApiUrl, ppApiParam)
console.log('pushplus 通知结果:', sendResult)
}
// QQ通知
async function noticeQQ (comment) {
if (!config.QM_SENDKEY) {
console.log('没有配置 qmsg 酱,放弃QQ通知')
return
}
if (config.BLOGGER_EMAIL === comment.mail) return
const pushContent = getIMPushContent(comment)
const qmApiUrl = 'https://qmsg.zendee.cn'
const qmApiParam = {
msg: pushContent.subject + '\n' + pushContent.content.replace(/<br>/g, '\n')
}
const sendResult = await axios.post(`${qmApiUrl}/send/${config.QM_SENDKEY}`, qs.stringify(qmApiParam), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
console.log('QQ通知结果:', sendResult)
}
// 即时消息推送内容获取
function getIMPushContent (comment) {
const SITE_NAME = config.SITE_NAME
const NICK = comment.nick
const MAIL = comment.mail
const IP = comment.ip
const COMMENT = $(comment.comment).text()
const SITE_URL = config.SITE_URL
const POST_URL = appendHashToUrl(comment.href || SITE_URL + comment.url, comment.id)
const subject = config.MAIL_SUBJECT_ADMIN || `${SITE_NAME}有新评论了`
const content = `评论人:${NICK}(${MAIL})<br>评论人IP:${IP}<br>评论内容:${COMMENT}<br>您可以点击 ${POST_URL} 查看回复的完整內容`
return {