forked from Arronlong/cfblog-plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index_plus.js
1295 lines (1173 loc) · 56.8 KB
/
index_plus.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
/**------【①.谋而后定:配置区】-----**/
'use strict';
const ACCOUNT = { //账号相关,安全性更高
"user" : "admin", //博客后台用户名
"password" : "cfblog-plus", //博客后台密码
"third_token" : "cfblog", //开放token,当前仅允许访问/admin/search.xml,/admin/sitemap.xml时可用,在cfblog_token的头信息中传递
"cacheZoneId":"935xxxxxxxxxxxx",//区域 ID
"cacheToken":"AQxxxxxxxx",//API token
"kv_var": this['CFBLOG'],//workers绑定kv时用的变量名
}
const OPT = { //网站配置
/*--前台参数--*/
"siteDomain" : "域名",// 域名(不带https 也不带/)
"siteName" : "CFBLOG-Plus",//博客名称
"siteDescription":"CFBLOG-Plus" ,//博客描述
"keyWords":"cloudflare,KV,workers,blog",//关键字
"logo":"https://cdn.jsdelivr.net/gh/Arronlong/cfblog-plus@master/themes/JustNews/files/logo2.png",//JustNews主题的logo
"theme_github_path":"https://cdn.jsdelivr.net/gh/Arronlong/cfblog-plus@master/themes/",//主题路径
"themeURL" : "https://raw.githubusercontent.com/Arronlong/cfblog-plus/master/themes/JustNews/", // 模板地址,以 "/"" 结尾
//"search_xml_url":"", //search.xml外部链接,可通过github的action自动生成,不设置则实时生成
//"sitemap_xml_url":"", //sitemap.xml外部链接,可通过github的action自动生成,不设置则实时生成
"pageSize" : 5,//每页文章数
"recentlySize" : 6,//最近文章数
"recentlyType" : 1,//最近文章类型:1-按创建时间倒序(按id倒序),2-按修改时间排序
"readMoreLength":150,//阅读更多截取长度
"cacheTime" : 60*60*24*2, //文章在浏览器的缓存时长(秒),建议=文章更新频率
"html404" : `<b>404</b>`,//404页面代码
"codeBeforHead":`
<script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
`,//其他代码,显示在</head>前
"codeBeforBody":`
`,//其他代码,显示在</body>前
"commentCode":`
<script>
//文章浏览页 添加编辑直达功能
$(".entry-info").append('<a style="float:right;margin-left:5px;" href="'+location.href.replace('/article/','/admin/edit/')+'" target="_blank">编辑</a>')
</script>
`,//评论区代码
"widgetOther":`
`,//20201224新增参数,用于右侧 小部件扩展
"otherCodeA":`热度`,//模板开发用的其他自定义变量
"otherCodeB":``,//
"otherCodeC":``,//
"otherCodeD":``,//
"otherCodeE":``,//
"copyRight" :`Powered by <a href="https://www.cloudflare.com">Cloudflare</a> & <a href="https://blog.arrontg.cf">CFBlog-Plus</a> & <a href="https://blog.gezhong.vip">CF-Blog </a>`,//自定义版权信息,建议保留大公无私的 Coudflare 和 作者 的链接
"robots":`User-agent: *
Disallow: /admin`,//robots.txt设置
/*--前后台共用参数--*/
"top_flag":`<topflag>[置顶]</topflag>`,//置顶标志
"top_flag_style":`<style>topflag {color:#ff5722}</style>`,//置顶标志的样式
/*--后台参数--*/
"hidden_flag":`<hiddenflag>[隐藏]</hiddenflag>`,//隐藏标志
"hidden_flag_style":`<style>hiddenflag {color:#000000;background-color: #ffff00;}</style>`,//隐藏标志的样式
"admin_home_idx": 1, //后台首页tab索引设置:1-我的文章,2-新建,3-设置,4-发布
"editor_page_scripts": `
//置顶设置
let top_setting=\`
<div class="form-group">
<label for="exampleInputEmail2">是否置顶</label>
<input type="hidden" class="form-control" id="top_timestamp" name="top_timestamp">
<select class="form-control" id="istop" name="istop">
<option value="0" selected >否</option>
<option value="1" >是</option>
</select>
</div>\`
$('form#addNewForm div.form-group,form#editForm div.form-group').last().after(top_setting);//新建和编辑页面添加置顶设置
$("#istop").change(function(){
$("#top_timestamp").val($(this).val()*1?new Date().getTime():0);
});
if(location.pathname.startsWith('/admin/edit')){//修改文章页面,自动设置置顶
$("#istop").val(articleJson.top_timestamp?1:0);
$("#top_timestamp").val(articleJson.top_timestamp?articleJson.top_timestamp:0);
}
$("#istop").trigger('change')
//隐藏设置
let hidden_setting=\`
<div class="form-group">
<label for="exampleInputEmail2">是否隐藏</label>
<select class="form-control" id="hidden" name="hidden">
<option value="0" selected >否</option>
<option value="1" >是</option>
</select>
</div>\`
$('form#addNewForm div.form-group,form#editForm div.form-group').last().after(hidden_setting);//新建和编辑页面添加隐藏设置
if(location.pathname.startsWith('/admin/edit')){//修改文章页面,自动设置隐藏
$("#hidden").val(articleJson.hidden?1:0);
}
let sitemapxml=\`<a tabindex="0" role="button" type="submit" id="btn_export" class="btn btn-default" href="/admin/sitemap.xml" >导出sitemap.xml</a>\`
$('form#importForm a').last().after(sitemapxml);//设置页面添加导出sitemap.xml导出按钮
let searchxml=\`<a tabindex="0" role="button" type="submit" id="btn_export" class="btn btn-default" href="/admin/search.xml" >导出search.xml</a>\`
$('form#importForm a').last().after(searchxml);//设置页面添加导出search.xml导出按钮
//关闭email匹配和@匹配,否则图片使用jsdelivr的cdn,如果有版本号会匹配成“mailto:xxx”从而导致显示异常
mdEditor.settings.emailLink=false;
mdEditor.settings.atLink=false;
//mdEditor.settings.toc=false
//mdEditor.settings.tocm=true // Using [TOCM]
//mdEditor.settings.tocContainer="#custom-toc-container" // 自定义 ToC 容器层
//mdEditor.settings.gfm=false
//mdEditor.settings.tocDropdown=true
//mdEditor.settings.markdownSourceCode=true // 是否保留 Markdown 源码,即是否删除保存源码的 Textarea 标签
mdEditor.settings.emoji=true
mdEditor.settings.taskList=true;// 默认不解析
mdEditor.settings.tex=true;// 默认不解析
mdEditor.settings.flowChart=true; // 默认不解析
mdEditor.settings.sequenceDiagram=true;// 默认不解析
//开启全局html标签解析-不推荐
//mdEditor.settings.htmlDecode=true;
window.mdEditor=mdEditor;
//editormd工具栏上添加html标签解析开关
mdEditor.getToolbarHandles().parseHtml=function(){
let ele = $(".editormd-menu li a i:last");
if(ele.hasClass('fa-toggle-off')){
ele.removeClass('fa-toggle-off').addClass('fa-toggle-on');
mdEditor.settings.htmlDecode = true;
}else if(ele.hasClass('fa-toggle-on')){
ele.removeClass('fa-toggle-on').addClass('fa-toggle-off')
mdEditor.settings.htmlDecode = false;
}
mdEditor.setMarkdown(mdEditor.getMarkdown());
}
setTimeout(function(){
$(".editormd-menu").append('<li class="divider" unselectable="on">|</li><li><a href="javascript:;" title="解析HTML标签" unselectable="on"><i class="fa fa-toggle-off" name="parseHtml" unselectable="on"> 解析HTML标签 </i></a></li>')
mdEditor.setToolbarHandler(mdEditor.getToolbarHandles())
},300)
//默认图片,工具:https://tool.lu/imageholder/
if($('#img').val()=="")$('#img').val('https://cdn.jsdelivr.net/gh/Arronlong/cdn@master/cfblog/cfblog-plus.png');
//默认时间设置为当前时间
if($('#createDate').val()=="")$('#createDate').val(new Date(new Date().getTime()+8*60*60*1000).toJSON().substr(0,16));
`, //后台编辑页面脚本
};
//---对部分配置进行处理---
{
//CFBLOG 通用变量
this.CFBLOG = ACCOUNT.kv_var;
//默认为非私密博客
if(null==OPT.privateBlog){
OPT.privateBlog=false;
}
//处理themeURL、theme_github_path参数设定
if(OPT.themeURL.substr(-1)!='/'){
OPT.themeURL=OPT.themeURL+'/';
}
if(OPT.theme_github_path.substr(-1)!='/'){
OPT.theme_github_path=OPT.theme_github_path+'/';
}
//置顶样式对于前台来说,与codeBeforHead结合即可
if(OPT.top_flag_style){
OPT.codeBeforHead += OPT.top_flag_style
}
}
/**------【②.猎杀时刻:请求处理入口】-----**/
//监听请求
addEventListener("fetch",event=>{
//处理请求
event.respondWith(handlerRequest(event))
})
// 处理请求
async function handlerRequest(event){
let request = event.request
//获取url请求对象
let url=new URL(request.url)
let paths=url.pathname.trim("/").split("/")
//校验权限
if(("admin"==paths[0]||true===OPT.privateBlog) &&!parseBasicAuth(request)){
return new Response("Unauthorized",{
headers:{
"WWW-Authenticate":'Basic realm="cfblog"',
"Access-Control-Allow-Origin":"*"
},
status:401
});
}
//组装请求url,查看是否有缓存
const D=caches.default,
M="https://"+OPT.siteDomain+url.pathname,
x=new Request(M, request);
console.log("cacheFullPath:",M);
let k=await D.match(x);
if(k){
console.log("hit cache!")
return k;
}
switch(paths[0]){
case "favicon.ico": //图标
k = await handle_favicon(request);
break;
case "robots.txt":
k = await handle_robots(request);
break;
case "sitemap.xml":
k = await handle_sitemap(request);
break;
case "search.xml":
k = await handle_search(request);
break;
case "admin": //后台
k = await handle_admin(request);
break;
case "article": //文章内容页
k = await handle_article(paths[1]);
break;
case "": //文章 首页
case "page": //文章 分页
case "category": //分类 分页
case "tags": //标签 分页
k = await renderBlog(url);
break;
default:
//其他页面返回404
k= new Response(OPT.html404,{
headers:{
"content-type":"text/html;charset=UTF-8"
},
status:200
})
break;
}
//设置浏览器缓存时间:后台不缓存、只缓存前台
try{
if("admin"==paths[0]){
k.headers.set("Cache-Control","no-store")
}else{
k.headers.set("Cache-Control","public, max-age="+OPT.cacheTime),
event.waitUntil(D.put(M,k.clone()))
}
}catch(e){}
return k
}
/**------【③.分而治之:各种请求分开处理】-----**/
//访问: favicon.ico
async function handle_favicon(request){
/*
想要自定义,或者用指定的ico,可将此请求置为404,并在codeBeforHead中自行添加类似代码:
<link rel="icon" type="image/x-icon" href="https://cdn.jsdelivr.net/gh/gdtool/zhaopp/cfblog/favicon.ico" />
<link rel="Shortcut Icon" href="https://cdn.jsdelivr.net/gh/gdtool/zhaopp/cfblog/favicon.ico">
*/
/*
return new Response("404",{
headers:{
"content-type":"text/plain;charset=UTF-8"
},
status:404
});
*/
let url = new URL(request.url)
url.host="dash.cloudflare.com"
return await fetch(new Request(url, request));
}
//访问: robots.txt
async function handle_robots(request){
return new Response(OPT.robots+"\nSitemap: https://"+OPT.siteDomain+"/sitemap.xml",{
headers:{
"content-type":"text/plain;charset=UTF-8"
},
status:200
});
}
//访问: sitemap.xml
async function handle_sitemap(request){
//如果设置了参数,则使用参数指定的url
//可使用github action方式自动定期更新
let xml;
if(OPT.sitemap_xml_url){
//cf代理方式,速度可以,实时性更好
let url = new URL(request.url)
url.href = OPT.sitemap_xml_url.replace('cdn.jsdelivr.net/gh','raw.githubusercontent.com').replace('@','/');
xml = await fetch(new Request(url, request));
xml = await xml.text();
////302方式,如果使用jsdelivr作为cdn,速度快,但更新有延迟
//return new Response("",{
// headers:{
// "location":OPT.sitemap_xml_url
// },
// status:302
//});
}else{ //未配置参数,则实时获取结构
//读取文章列表,并按照特定的xml格式进行组装
let articles_all=await getArticlesList()
xml='<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
for(var i=0;i<articles_all.length;i++){
xml+="\n\t<url>",
xml+="\n\t\t<loc>https://"+OPT.siteDomain+"/article/"+articles_all[i].id+"/"+articles_all[i].link+".html</loc>",
xml+="\n\t\t<lastmod>"+articles_all[i].createDate.substr(0,10)+"</lastmod>",
xml+="\n\t\t<changefreq>"+(void 0===articles_all[i].changefreq?"daily":articles_all[i].changefreq)+"</changefreq>",
xml+="\n\t\t<priority>"+(void 0===articles_all[i].priority?"0.5":articles_all[i].priority)+"</priority>",
xml+="\n\t</url>";
}
xml+="\n</urlset>"
}
return new Response(xml,{
headers:{
"content-type":"text/xml;charset=UTF-8"
},
status:200
});
}
//访问: search.xml
async function handle_search(request){
//如果设置了参数,则使用参数指定的url
//可使用github action方式自动定期更新
let xml;
if(OPT.search_xml_url){
//cf代理方式,速度可以,实时性更好
let url = new URL(request.url)
url.href = OPT.search_xml_url.replace('cdn.jsdelivr.net/gh','raw.githubusercontent.com').replace('@','/');
xml = await fetch(new Request(url, request));
xml = await xml.text();
////302方式,如果使用jsdelivr作为cdn,速度快,但更新有延迟
//return new Response("",{
// headers:{
// "location":OPT.search_xml_url
// },
// status:302
//});
}else{ //未配置参数,则实时获取结构
//读取文章列表,并按照特定的xml格式进行组装
let articles_all=await getArticlesList()
xml='<?xml version="1.0" encoding="UTF-8"?>\n<blogs>';
for(var i=0;i<articles_all.length;i++){
xml+="\n\t<blog>",
xml+="\n\t\t<title>"+articles_all[i].title+"</title>";
let article = await getArticle(articles_all[i].id);
if(null != article){
xml+="\n\t\t<content>"+article.contentMD.replaceAll('<','<').replaceAll('>','>').replaceAll('&','&')+"</content>"
}
xml+="\n\t\t<url>https://"+OPT.siteDomain+"/article/"+articles_all[i].id+"/"+articles_all[i].link+".html</url>",
xml+="\n\t\t<time>"+articles_all[i].createDate.substr(0,10)+"</time>",
xml+="\n\t</blog>";
}
xml+="\n</blogs>"
}
return new Response(xml,{
headers:{
"content-type":"text/xml;charset=UTF-8"
},
status:200
});
}
//渲染前端博客:指定一级路径page\tags\category,二级路径value,以及页码,默认第一页
async function renderBlog(url){
console.log("---进入renderBlog函数---,path=", url.href.substr(url.origin.length))
//处理主题预览及分页
let theme=url.searchParams.get("theme"),
pageSize=url.searchParams.get("pageSize");
if(theme){
OPT.themeURL=OPT.theme_github_path+theme+"/";
}
if(pageSize){
OPT.pageSize=parseInt(pageSize);
}
//如果采用默认default主题,则改为加载default2.0主题
if(OPT.theme_github_path+"default/"==OPT.themeURL){
OPT.themeURL=OPT.theme_github_path+"default2.0/";
}
console.log("theme pageSize",OPT.pageSize,OPT.themeURL)
//获取主页模板源码
let theme_html=await getThemeHtml("index"),
//KV中读取导航栏、分类目录、标签、链接、所有文章、近期文章等配置信息
menus=await getWidgetMenu(),
categories=await getWidgetCategory(),
tags=await getWidgetTags(),
links=await getWidgetLink(),
articles_all=await getArticlesList(),
articles_recently=await getRecentlyArticles(articles_all);
/** 前台博客
* 路径格式:
* 域名/ 文章列表首页,等价于域名/page/1
* 域名/page/xxx 文章列表翻页
*
* 域名/category/xxx 分类页,等价于域名/category/xxx/page/1
* 域名/category/xxx/page/xxx 分类页+翻页
*
* 域名/tags/xxx 标签页,等价于域名/tags/xxx/page/1
* 域名/tags/xxx/page/xxx 分类页+翻页
*
*/
let paths = url.pathname.trim("/").split("/")
let articles=[],
pageNo=1
//获取文章列表
switch(paths[0]||"page"){
case "page":
articles = articles_all
pageNo = paths[1]||1
break;
case "tags":
case "category":
let category_tag = paths.slice(1).join("");//如果无分页,tags、category后面都是标签、分类名
if(paths.length>3 && paths.includes("page")){
pageNo = paths[paths.indexOf("page")+1] //分页的页码
category_tag = paths.slice(1, paths.lastIndexOf("page")-1).join("") //tags、category后,分页前的为标签、分类名
}
category_tag = decodeURIComponent(category_tag)
articles = articles_all.filter(a => a[paths[0]].includes(category_tag))
break;
}
pageNo = parseInt(pageNo)
// console.log(pageNo)
// console.log(articles)
//获取当页要显示文章列表
let articles_show = articles.slice((pageNo-1)*OPT.pageSize,pageNo*OPT.pageSize);
// console.log(articles_show)
//处理文章属性(年月日、url等)
processArticleProp(articles_show);
// console.log(url.pathname)
let url_prefix = url.pathname.replace(/(.*)\/page\/\d+/,'$1/')
if(url_prefix.substr(-1)=='/'){
url_prefix=url_prefix.substr(0,url_prefix.length-1);
}
// console.log(url_prefix)
//组装各种参数
let newer=[{title:"上一页",url:url_prefix+"/page/"+(pageNo-1)}];
if(1==pageNo){
newer=[];
}
let older=[{title:"下一页",url:url_prefix+"/page/"+(pageNo+1)}];
if(pageNo*OPT.pageSize>=articles.length){
older=[];
}
// console.log(newer)
// console.log(older)
//文章标题、关键字
let title=(pageNo>1 ? "page "+pageNo+" - " : "")+OPT.siteName,
keyWord=OPT.keyWords,
cfg={};
cfg.widgetMenuList=menus,//导航
cfg.widgetCategoryList=categories,//分类目录
cfg.widgetTagsList=tags,//标签
cfg.widgetLinkList=links,//链接
cfg.widgetRecentlyList=articles_recently,//近期文章
cfg.articleList=articles_show,//当前页文章列表
cfg.pageNewer=newer,//上翻页链接
cfg.pageOlder=older,//下翻页链接
cfg.title=title,//网页title
cfg.keyWords=keyWord;//SEO关键字
//使用mustache.js进行页面渲染(参数替换)
cfg.OPT=OPT
let html = Mustache.render(theme_html,cfg)
return new Response(html,{
headers:{
"content-type":"text/html;charset=UTF-8"
},
status:200
})
}
//渲染前端博客的文章内容页
async function handle_article(id){
//获取内容页模板源码
let theme_html=await getThemeHtml("article"),
//KV中读取导航栏、分类目录、标签、链接、近期文章等配置信息
menus=await getWidgetMenu(),
categories=await getWidgetCategory(),
tags=await getWidgetTags(),
links=await getWidgetLink(),
articles_recently=await getRecentlyArticles();
//获取上篇、本篇、下篇文章
let articles_sibling=await getSiblingArticle(id);
//处理文章属性(年月日、url等)
processArticleProp(articles_sibling);
//获取本篇文章
let article=articles_sibling[1];
//组装文章详情页各参数
let title=article.title.replace(nullToEmpty(OPT.top_flag),'').replace(nullToEmpty(OPT.hidden_flag),'')+" - "+OPT.siteName,
keyWord=article.tags.concat(article.category).join(","),
cfg={};
cfg.widgetMenuList=menus,//导航
cfg.widgetCategoryList=categories,//分类目录
cfg.widgetTagsList=tags,//标签
cfg.widgetLinkList=links,//链接
cfg.widgetRecentlyList=articles_recently,//近期文章
cfg.articleOlder=articles_sibling[0]?[articles_sibling[0]]:[],//上篇文章
cfg.articleSingle=article,//本篇文章
cfg.articleNewer=articles_sibling[2]?[articles_sibling[2]]:[],//下篇文章
cfg.title=title,//网页title
cfg.keyWords=keyWord;//SEO关键字
//使用mustache.js渲染页面(参数替换)
cfg.OPT=OPT
let html = Mustache.render(theme_html,cfg)
//以html格式返回
return new Response(html,{
headers:{
"content-type":"text/html;charset=UTF-8"
},
status:200
})
}
//后台请求处理
async function handle_admin(request){
let url = new URL(request.url),
paths = url.pathname.trim("/").split("/"),
html,//返回html
json,//返回json
file;//返回文件
//新建页
if(1==paths.length||"list"==paths[1]){
//读取主题的admin/index.html源码
let theme_html=await getThemeHtml("admin/index"),
//KV中读取导航栏、分类目录、链接、近期文章等配置信息
categoryJson=await getWidgetCategory(),
menuJson=await getWidgetMenu(),
linkJson=await getWidgetLink();
//手动替换<!--{xxx}-->格式的参数
html = theme_html.replaceHtmlPara("categoryJson",JSON.stringify(categoryJson))
.replaceHtmlPara("menuJson",JSON.stringify(menuJson))
.replaceHtmlPara("linkJson",JSON.stringify(linkJson))
//添加后台首页配置
if(OPT.admin_home_idx && OPT.admin_home_idx>=1 && OPT.admin_home_idx<=4){
html = html.replace("$('#myTab li:eq(0) 1').tab('show')","$($('#myTab a[href*=\"'+location.hash+'\"]')[0]||$('#myTab a:eq("+OPT.admin_home_idx+")')).tab('show')")
}
//添加置顶样式
if(OPT.top_flag_style){
html += OPT.top_flag_style
}
//添加隐藏样式
if(OPT.hidden_flag_style){
html += OPT.hidden_flag_style
}
}
//发布
if("publish"==paths[1]){
//KV中获取文章列表
let articles_all=await getAllArticlesList(),
tags=[]; //操作标签
//遍历所有文章,汇集所有的tag
for(var i=0;i<articles_all.length;i++){
//若文章设定了标签
if("object"==typeof articles_all[i].tags){
//将所有tags存入e中
for(var j=0;j<articles_all[i].tags.length;j++){
if(articles_all[i].tags[j]
&& articles_all[i].tags[j].length>0
&& -1==tags.indexOf(articles_all[i].tags[j])){
tags.push(articles_all[i].tags[j]);
}
}
}
}
console.log(articles_all)
//将所有标签一次性写入到KV中,并清除缓存
await saveWidgetTags(JSON.stringify(tags))
json = await purge()?'{"msg":"published ,purge Cache true","rst":true}':'{"msg":"published ,buuuuuuuuuuuut purge Cache false !!!!!!","rst":true}'
}
//文章列表
if("getList"==paths[1]){
//默认取第一页,每页20篇
let pageNo=(undefined===paths[2]) ? 1 : parseInt(paths[2]),
list=await admin_nextPage(pageNo, 20);//每次加载20个
json = JSON.stringify(list)
}
//修改文章
if("edit"==paths[1]){
let id=paths[2],
//获取主题admin/edit源码
theme_html=await getThemeHtml("admin/edit"),
//KV中读取分类
categoryJson=JSON.stringify(await getWidgetCategory()),
//KV中读取文章内容
articleJson=JSON.stringify(await getArticle(id));
//手动替换<!--{xxx}-->格式的参数
html = theme_html.replaceHtmlPara("categoryJson",categoryJson).replaceHtmlPara("articleJson",articleJson.replaceAll("script>","script>"))
}
//保存配置
if("saveConfig"==paths[1]){
const ret=await parseReq(request);
let widgetCategory=ret.WidgetCategory,//分类
widgetMenu=ret.WidgetMenu,//导航
widgetLink=ret.WidgetLink;//链接
//判断格式,写入分类、导航、链接到KV中
if(checkFormat(widgetCategory) && checkFormat(widgetMenu) && checkFormat(widgetLink)){
let success = await saveWidgetCategory(widgetCategory)
success = success && await saveWidgetMenu(widgetMenu)
success = success && await saveWidgetLink(widgetLink)
json = success ? '{"msg":"saved","rst":true}' : '{"msg":"Save Faild!!!","ret":false}'
}else{
json = '{"msg":"Not a JSON object","rst":false}'
}
}
//导入
if("import"==paths[1]){
let importJsone=(await parseReq(request)).importJson;
console.log("开始导入",typeof importJson)
if(checkFormat(importJson)){
let importJson=JSON.parse(importJson),
keys=Object.keys(importJson);
for(let i=0;i<keys.length;++i){
console.log(keys[i],importJson[keys[i]]),
await saveArticle(keys[i],importJson[keys[i]]);
}
json = '{"msg":"import success!","rst":true}'
}else{
json = '{"msg":" importJson Not a JSON object","rst":false}'
}
}
//导出
if("export"===paths[1]){
console.log("开始导出");
async function exportArticle(arr=[],cursor="",limit=1){
//分页获取文章内容
const list=await CFBLOG.list({limit:limit,cursor:cursor});
if(!1 in list) return {};
arr=arr.concat(list.keys)
console.log("导出: ",typeof list, JSON.stringify(list))
//判断是否导出完毕
if(list.list_complete){
let ret = {OPT:OPT};
for(let i=0;i<arr.length;++i){
const article = await CFBLOG.get(arr[i].name);
if(null != article){
ret[arr[i].name] = checkFormat(article)?JSON.parse(article):article
}
}
return ret
}
return await exportArticle(arr,list.cursor,limit)
}
let articles=await exportArticle();
file = {
name: "cfblog-"+new Date().getTime()+".json",
content: JSON.stringify(articles)
}
}
//导出search.xml
if("search.xml"===paths[1]){
console.log("开始导出");
//读取文章列表,并按照特定的xml格式进行组装
let articles_all=await getArticlesList()
let xml='<?xml version="1.0" encoding="UTF-8"?>\n<blogs>';
for(var i=0;i<articles_all.length;i++){
xml+="\n\t<blog>",
xml+="\n\t\t<title>"+articles_all[i].title+"</title>";
let article = await getArticle(articles_all[i].id);
if(null != article){
xml+="\n\t\t<content>"+article.contentMD.replaceAll('<','<').replaceAll('>','>').replaceAll('&','&')+"</content>"
}
xml+="\n\t\t<url>https://"+OPT.siteDomain+"/article/"+articles_all[i].id+"/"+articles_all[i].link+".html</url>",
xml+="\n\t\t<time>"+articles_all[i].createDate.substr(0,10)+"</time>",
xml+="\n\t</blog>";
}
xml+="\n</blogs>"
file = {
name: "search.xml",
content: xml
}
}
//导出sitemap.xml
if("sitemap.xml"===paths[1]){
console.log("开始导出");
//读取文章列表,并按照特定的xml格式进行组装
let articles_all=await getArticlesList()
let xml='<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
for(var i=0;i<articles_all.length;i++){
xml+="\n\t<url>",
xml+="\n\t\t<loc>https://"+OPT.siteDomain+"/article/"+articles_all[i].id+"/"+articles_all[i].link+".html</loc>",
xml+="\n\t\t<lastmod>"+articles_all[i].createDate.substr(0,10)+"</lastmod>",
xml+="\n\t\t<changefreq>"+(void 0===articles_all[i].changefreq?"daily":articles_all[i].changefreq)+"</changefreq>",
xml+="\n\t\t<priority>"+(void 0===articles_all[i].priority?"0.5":articles_all[i].priority)+"</priority>",
xml+="\n\t</url>";
}
xml+="\n</urlset>"
file = {
name: "sitemap.xml",
content: xml
}
}
//新建文章
if("saveAddNew"==paths[1]){
const ret=await parseReq(request);
let title=ret.title,//文章标题
img=ret.img,//插图
link=ret.link,//永久链接
createDate=ret.createDate.replace('T',' '),//发布日期
category=ret.category,//分类
tags=ret.tags,//标签
priority=void 0===ret.priority?"0.5":ret.priority,//权重
changefreq=void 0===ret.changefreq?"daily":ret.changefreq,//更新频率
contentMD=ret["content-markdown-doc"],//文章内容-md格式
contentHtml=ret["content-html-code"],//文章内容-html格式
contentText="",//文章摘要
top_timestamp=ret.top_timestamp*1,//置顶时间戳,不置顶时为0
modify_timestamp=new Date().getTime()+8*60*60*1000,//修改时间戳
hidden=ret.hidden*1,//是否隐藏
id="";//文章id
//校验参数完整性
if(title.length>0
&& createDate.length>0
&& category.length>0
&& contentMD.length>0
&& contentHtml.length>0){
id=await generateId(),
contentText=contentHtml.replace(/<\/?[^>]*>/g,"").trim().substring(0,OPT.readMoreLength);//摘要
//组装文章json
let article={
id:id,
title:title,
img:img,
link:link,
createDate:createDate,
category:category,
tags:tags,
contentMD:contentMD,
contentHtml:contentHtml,
contentText:contentText,
priority:priority,
top_timestamp:top_timestamp,
modify_timestamp:modify_timestamp,
hidden:hidden,
changefreq:changefreq
};
//将文章json写入KV(key为文章id,value为文章json字符串)
await saveArticle(id,JSON.stringify(article));
//组装文章json
let articleWithoutHtml={
id:id,
title:title,
img:img,
link:link,
createDate:createDate,
category:category,
tags:tags,
contentText:contentText,
priority:priority,
top_timestamp:top_timestamp,
modify_timestamp:modify_timestamp,
hidden:hidden,
changefreq:changefreq
},
articles_all_old=await getAllArticlesList(),//读取文章列表
articles_all=[];
//将最新的文章写入文章列表中,并按id排序后,再次回写到KV中
articles_all.push(articleWithoutHtml),
articles_all=articles_all.concat(articles_all_old),
articles_all=sortArticle(articles_all),
await saveArticlesList(JSON.stringify(articles_all))
json = '{"msg":"added OK","rst":true,"id":"'+id+'"}'
}else{
json = '{"msg":"信息不全","rst":false}'
}
}
//删除
if("delete"==paths[1]){
let id=paths[2]
if(6==id.length){
await CFBLOG.delete(id);
let e=await getAllArticlesList();
for(r=0;r<e.length;r++){
if(id==e[r].id){
e.splice(r,1);
await saveArticlesList(JSON.stringify(e))
json = '{"msg":"Delete ('+id+') OK","rst":true,"id":"'+id+'"}'
break;
}
}
}else{
json = '{"msg":"Delete false ","rst":false,"id":"'+id+'"}'
}
}
//保存编辑的文章
if("saveEdit"==paths[1]){
const ret=await parseReq(request);
let title=ret.title,//文章标题
img=ret.img,//插图
link=ret.link,//永久链接
createDate=ret.createDate.replace('T',' '),//发布日期
category=ret.category,//分类
tags=ret.tags,//标签
priority=void 0===ret.priority?"0.5":ret.priority,//权重
changefreq=void 0===ret.changefreq?"daily":ret.changefreq,//更新频率
contentMD=ret["content-markdown-doc"],//文章内容-md格式
contentHtml=ret["content-html-code"],//文章内容-html格式
contentText="",//文章摘要
top_timestamp=ret.top_timestamp*1,//置顶则设置时间戳,不置顶时为0
modify_timestamp=new Date().getTime()+8*60*60*1000,//修改时间戳
hidden=ret.hidden*1,//是否隐藏
id=ret.id;//文章id
//校验参数完整性
if(title.length>0
&& createDate.length>0
&& category.length>0
&& contentMD.length>0
&& contentHtml.length>0){
contentText=contentHtml.replace(/<\/?[^>]*>/g,"").trim().substring(0,OPT.readMoreLength);//摘要
//组装文章json
let article={
id:id,
title:title,
img:img,
link:link,
createDate:createDate,
category:category,
tags:tags,
contentMD:contentMD,
contentHtml:contentHtml,
contentText:contentText,
priority:priority,
top_timestamp:top_timestamp,
modify_timestamp:modify_timestamp,
hidden:hidden,
changefreq:changefreq
};
//将文章json写入KV(key为文章id,value为文章json字符串)
await saveArticle(id,JSON.stringify(article));
//组装文章json
let articleWithoutHtml={
id:id,
title:title,
img:img,
link:link,
createDate:createDate,
category:category,
tags:tags,
contentText:contentText,
priority:priority,
top_timestamp:top_timestamp,
modify_timestamp:modify_timestamp,
hidden:hidden,
changefreq:changefreq
},
articles_all=await getAllArticlesList();//读取文章列表
//console.log(articles_all)
//将原对象删掉,将最新的文章加入文章列表中,并重新按id排序后,再次回写到KV中
for(var i=articles_all.length-1;i>=0;i--){//按索引删除,要倒序,否则索引值会变
if(articles_all[i].id == id){
articles_all.splice(i,1);
break;
}
}
articles_all.push(articleWithoutHtml),
articles_all=sortArticle(articles_all),
await saveArticlesList(JSON.stringify(articles_all))
json = '{"msg":"Edit OK","rst":true,"id":"'+id+'"}'
}else{
json = '{"msg":"信息不全","rst":false}'
}
}
//返回结果
if(!json &&!html && !file){
json = '{"msg":"some errors","rst":false}'
}
if(file){
return new Response(file.content,{
headers:{
"content-type":"application/octet-stream;charset=utf-8",
"Content-Disposition":"attachment; filename="+file.name
},
status:200
})
}
if(html){
return new Response(html,{
headers:{
"content-type":"text/html;charset=UTF-8"
},
status:200
})
}
if(json){
return new Response(json ,{
headers:{
"content-type":"application/json;charset=UTF-8"
},
status:200
})
}
}
/**------【④.抽丝剥茧,抽取公用的业务方法】-----**/
//访问管理后台或私密博客,则进行Base Auth
function parseBasicAuth(request){
const auth=request.headers.get("Authorization");
if(!auth||!/^Basic [A-Za-z0-9._~+/-]+=*$/i.test(auth)){
const token = request.headers.get("cfblog_token");
if(token){
//获取url请求对象
let url=new URL(request.url)
let paths=url.pathname.trim("/").split("/")
//校验权限
if("admin"==paths[0] && ("search.xml"==paths[1]||"sitemap.xml"==paths[1])){
return token === ACCOUNT.third_token
}
}
return false;
}
const[user,pwd]=atob(auth.split(" ").pop()).split(":");
console.log("-----parseBasicAuth----- ", user, pwd)
return user===ACCOUNT.user && pwd===ACCOUNT.password
}
//获取所有【公开】文章:仅前台使用
async function getArticlesList(){
let articles_all = await getAllArticlesList();
for(var i=0;i<articles_all.length;i++)
if(articles_all[i].hidden){
articles_all.splice(i,1);
}
return articles_all;
}
//文章排序:先按id倒排,再按置顶时间倒排
function sortArticle(articles){
return sort(sort(articles,'id'),'top_timestamp');
}
//获取近期文章列表