forked from TruthHun/BookStack
/
DocumentController.go
1619 lines (1412 loc) · 46.4 KB
/
DocumentController.go
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
package controllers
import (
"container/list"
"encoding/json"
"html/template"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/TruthHun/BookStack/utils/html2md"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"image/png"
"bytes"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/TruthHun/BookStack/conf"
"github.com/TruthHun/BookStack/models"
"github.com/TruthHun/BookStack/models/store"
"github.com/TruthHun/BookStack/utils"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/qr"
)
var (
videoBoxFmt = `<div class="video-box">
<div class="video-main">
<div class="video-heading">
<div class="video-title">%v</div>
<div class="video-playbackrate">
<select>
<option value="0.7">0.7 倍</option>
<option value="1.0" selected>1.0 倍</option>
<option value="1.2">1.2 倍</option>
<option value="1.5">1.5 倍</option>
<option value="2.0">2.0 倍</option>
</select>
</div>
</div>
<video controls poster="%v" src="%v" controlslist="nodownload" preload="true">%v</video>
</div>
</div>
`
)
//DocumentController struct.
type DocumentController struct {
BaseController
}
func (this *DocumentController) Abort404(bookName, bookLink string) {
this.Ctx.ResponseWriter.WriteHeader(404)
this.Data["BookName"] = bookName
this.Data["BookLink"] = bookLink
this.TplName = "errors/404.html"
b, err := this.RenderBytes()
if err != nil {
this.Abort("404")
}
this.Ctx.ResponseWriter.Write(b)
this.StopRun()
}
// 解析并提取版本控制的commit内容
func parseGitCommit(str string) (cont, commit string) {
var slice []string
arr := strings.Split(str, "<bookstack-git>")
if len(arr) > 1 {
slice = append(slice, arr[0])
str = strings.Join(arr[1:], "")
}
arr = strings.Split(str, "</bookstack-git>")
if len(arr) > 1 {
slice = append(slice, arr[1:]...)
commit = arr[0]
}
if len(slice) > 0 {
cont = strings.Join(slice, "")
} else {
cont = str
}
return
}
//判断用户是否可以阅读文档.
func isReadable(identify, token string, this *DocumentController) *models.BookResult {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
beego.Error(err)
this.Abort("404")
}
//如果文档是私有的
if book.PrivatelyOwned == 1 && !this.Member.IsAdministrator() {
isOk := false
if this.Member != nil {
_, err := models.NewRelationship().FindForRoleId(book.BookId, this.Member.MemberId)
if err == nil {
isOk = true
}
}
if book.PrivateToken != "" && !isOk {
//如果有访问的Token,并且该书籍设置了访问Token,并且和用户提供的相匹配,则记录到Session中.
//如果用户未提供Token且用户登录了,则判断用户是否参与了该书籍.
//如果用户未登录,则从Session中读取Token.
if token != "" && strings.EqualFold(token, book.PrivateToken) {
this.SetSession(identify, token)
} else if token, ok := this.GetSession(identify).(string); !ok || !strings.EqualFold(token, book.PrivateToken) {
hasErr := ""
if this.Ctx.Request.Method == "POST" {
hasErr = "true"
}
this.Redirect(beego.URLFor("DocumentController.Index", ":key", identify)+"?with-password=true&err="+hasErr, 302)
this.StopRun()
}
} else if !isOk {
this.Abort("404")
}
}
bookResult := book.ToBookResult()
if this.Member != nil {
rel, err := models.NewRelationship().FindByBookIdAndMemberId(bookResult.BookId, this.Member.MemberId)
if err == nil {
bookResult.MemberId = book.MemberId
bookResult.RoleId = rel.RoleId
bookResult.RelationshipId = rel.RelationshipId
}
}
//判断是否需要显示评论框
switch bookResult.CommentStatus {
case "closed":
bookResult.IsDisplayComment = false
case "open":
bookResult.IsDisplayComment = true
case "group_only":
bookResult.IsDisplayComment = bookResult.RelationshipId > 0
case "registered_only":
bookResult.IsDisplayComment = true
}
return bookResult
}
//文档首页.
func (this *DocumentController) Index() {
identify := this.Ctx.Input.Param(":key")
if identify == "" {
this.Abort("404")
}
token := this.GetString("token")
if len(strings.TrimSpace(this.GetString("with-password"))) > 0 {
this.indexWithPassword()
return
}
tab := strings.ToLower(this.GetString("tab"))
bookResult := isReadable(identify, token, this)
if bookResult.BookId == 0 { //没有阅读权限
this.Redirect(beego.URLFor("HomeController.Index"), 302)
return
}
this.TplName = "document/intro.html"
bookResult.Lang = utils.GetLang(bookResult.Lang)
this.Data["Book"] = bookResult
switch tab {
case "comment", "score":
default:
tab = "default"
}
this.Data["Qrcode"] = new(models.Member).GetQrcodeByUid(bookResult.MemberId)
this.Data["MyScore"] = new(models.Score).BookScoreByUid(this.Member.MemberId, bookResult.BookId)
this.Data["Tab"] = tab
if beego.AppConfig.DefaultBool("showWechatCode", false) && bookResult.PrivatelyOwned == 0 {
wechatCode := models.NewWechatCode()
go wechatCode.CreateWechatCode(bookResult.BookId) //如果已经生成了小程序码,则不会再生成
this.Data["Wxacode"] = wechatCode.GetCode(bookResult.BookId)
}
//当前默认展示100条评论
this.Data["Comments"], _ = new(models.Comments).Comments(1, 100, bookResult.BookId, 1)
this.Data["Menu"], _ = new(models.Document).GetMenuTop(bookResult.BookId)
title := "《" + bookResult.BookName + "》"
if tab == "comment" {
title = "点评 - " + title
}
this.GetSeoByPage("book_info", map[string]string{
"title": title,
"keywords": bookResult.Label,
"description": bookResult.Description,
})
this.Data["RelateBooks"] = models.NewRelateBook().Lists(bookResult.BookId)
}
//文档首页.
func (this *DocumentController) indexWithPassword() {
identify := this.Ctx.Input.Param(":key")
if identify == "" {
this.Abort("404")
}
this.TplName = "document/read-with-password.html"
this.GetSeoByPage("book_info", map[string]string{
"title": "密码访问",
"keywords": "密码访问",
"description": "密码访问",
})
this.Data["ShowErrTips"] = this.GetString("err") != ""
this.Data["Identify"] = identify
}
//阅读文档.
func (this *DocumentController) Read() {
identify := this.Ctx.Input.Param(":key")
token := this.GetString("token")
id := this.GetString(":id")
if identify == "" || id == "" {
this.Abort("404")
}
//如果没有开启你们匿名则跳转到登录
if !this.EnableAnonymous && this.Member == nil {
this.Redirect(beego.URLFor("AccountController.Login"), 302)
return
}
bookResult := isReadable(identify, token, this)
bookName := bookResult.BookName
bookLink := beego.URLFor("DocumentController.Index", ":key", bookResult.Identify)
this.TplName = "document/" + bookResult.Theme + "_read.html"
var err error
doc := models.NewDocument()
if docId, _ := strconv.Atoi(id); docId > 0 {
doc, err = doc.Find(docId) //文档id
if err != nil {
beego.Error(err)
this.Abort404(bookName, bookLink)
}
} else {
//此处的id是字符串,标识文档标识,根据文档标识和文档所属的书的id作为key去查询
doc, err = doc.FindByBookIdAndDocIdentify(bookResult.BookId, id) //文档标识
if err != nil {
if err != orm.ErrNoRows {
beego.Error(err, docId, id, bookResult)
}
this.Abort404(bookName, bookLink)
}
}
if doc.BookId != bookResult.BookId {
this.Abort404(bookName, bookLink)
}
bodyText := ""
authHTTPS := strings.ToLower(models.GetOptionValue("AUTO_HTTPS", "false")) == "true"
if doc.Release != "" {
query, err := goquery.NewDocumentFromReader(bytes.NewBufferString(doc.Release))
if err != nil {
beego.Error(err)
} else {
query.Find("img").Each(func(i int, contentSelection *goquery.Selection) {
src, ok := contentSelection.Attr("src")
if ok {
if utils.StoreType == utils.StoreOss && !(strings.HasPrefix(src, "https://") || strings.HasPrefix(src, "http://")) {
src = this.OssDomain + "/" + strings.TrimLeft(src, "./")
}
}
if authHTTPS {
if srcArr := strings.Split(src, "://"); len(srcArr) > 1 {
src = "https://" + strings.Join(srcArr[1:], "://")
}
}
contentSelection.SetAttr("src", src)
if alt, _ := contentSelection.Attr("alt"); alt == "" {
contentSelection.SetAttr("alt", doc.DocumentName+" - 图"+fmt.Sprint(i+1))
}
})
medias := []string{"video", "audio"}
for _, item := range medias {
query.Find(item).Each(func(idx int, sel *goquery.Selection) {
title := strings.TrimSpace(sel.Text())
poster, _ := sel.Attr("poster")
src, _ := sel.Attr("src")
if !(strings.HasPrefix(src, "https://") || strings.HasPrefix(src, "http://")) {
sign, _ := utils.GenerateMediaSign(src, time.Now().UnixNano(), time.Duration(utils.MediaDuration)*time.Second)
if strings.Contains(src, "?") {
src = src + "&sign=" + sign
} else {
src = src + "?sign=" + sign
}
}
if item == "video" {
sel.BeforeHtml(fmt.Sprintf(videoBoxFmt, title, poster, src, title))
sel.Remove()
} else {
sel.SetAttr("preload", "true")
sel.SetAttr("controlslist", "nodownload")
sel.SetAttr("src", src)
}
})
}
html, err := query.Find("body").Html()
if err != nil {
beego.Error(err)
} else {
doc.Release = html
}
}
bodyText = query.Find(".markdown-toc").Text()
}
attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
if err == nil {
doc.AttachList = attach
if len(attach) > 0 {
content := bytes.NewBufferString("<div class=\"attach-list\"><strong>附件</strong><ul>")
for _, item := range attach {
li := fmt.Sprintf("<li><a href=\"%s\" target=\"_blank\" title=\"%s\">%s</a></li>", item.HttpPath, item.FileName, item.FileName)
content.WriteString(li)
}
content.WriteString("</ul></div>")
doc.Release += content.String()
}
}
//文档阅读人次+1
if err := models.SetIncreAndDecre("md_documents", "vcnt",
fmt.Sprintf("document_id=%v", doc.DocumentId),
true, 1,
); err != nil {
beego.Error(err.Error())
}
//书籍阅读人次+1
if err := models.SetIncreAndDecre("md_books", "vcnt",
fmt.Sprintf("book_id=%v", doc.BookId),
true, 1,
); err != nil {
beego.Error(err.Error())
}
if this.Member.MemberId > 0 { //增加用户阅读记录
if err := new(models.ReadRecord).Add(doc.DocumentId, this.Member.MemberId); err != nil {
beego.Error(err.Error())
}
}
parentTitle := doc.GetParentTitle(doc.ParentId)
seo := map[string]string{
"title": doc.DocumentName + " - 《" + bookResult.BookName + "》",
"keywords": bookResult.Label,
"description": beego.Substr(bodyText+" "+bookResult.Description, 0, 200),
}
if len(parentTitle) > 0 {
seo["title"] = parentTitle + " - " + doc.DocumentName + " - 《" + bookResult.BookName + "》"
}
//SEO
this.GetSeoByPage("book_read", seo)
existBookmark := new(models.Bookmark).Exist(this.Member.MemberId, doc.DocumentId)
doc.Vcnt = doc.Vcnt + 1
models.NewBookCounter().Increase(bookResult.BookId, true)
if this.IsAjax() {
var data struct {
Id int `json:"doc_id"`
DocTitle string `json:"doc_title"`
Body string `json:"body"`
Title string `json:"title"`
Bookmark bool `json:"bookmark"` //是否已经添加了书签
View int `json:"view"`
UpdatedAt string `json:"updated_at"`
}
data.DocTitle = doc.DocumentName
data.Body = doc.Release
data.Id = doc.DocumentId
data.Title = this.Data["SeoTitle"].(string)
data.Bookmark = existBookmark
data.View = doc.Vcnt
data.UpdatedAt = doc.ModifyTime.Format("2006-01-02 15:04:05")
//data.Body = doc.Markdown
this.JsonResult(0, "ok", data)
}
tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, doc.DocumentId)
if err != nil {
beego.Error(err)
this.Abort404(bookName, bookLink)
}
// 查询用户哪些文档阅读了
var readMap = make(map[string]bool)
if this.Member.MemberId > 0 {
modelRecord := new(models.ReadRecord)
lists, cnt, _ := modelRecord.List(this.Member.MemberId, bookResult.BookId)
if cnt > 0 {
for _, item := range lists {
readMap[strconv.Itoa(item.DocId)] = true
}
}
}
this.Data["ToggleMenu"] = false
if menuDoc, err := goquery.NewDocumentFromReader(strings.NewReader(tree)); err == nil {
menuDoc.Find("li").Each(func(i int, selection *goquery.Selection) {
if id, exist := selection.Attr("id"); exist {
if _, ok := readMap[id]; ok {
selection.AddClass("readed")
}
}
})
hide := models.GetOptionValue("COLLAPSE_HIDE", "true") == "true"
menuDoc.Find("ul").Each(func(i int, selection *goquery.Selection) {
if selection.Parent().Is("li") {
selection.Parent().AddClass("collapse-node")
selection.Parent().PrependHtml("<span></span>")
this.Data["ToggleMenu"] = true
if hide {
selection.Parent().AddClass("collapse-hide")
}
}
})
menuDoc.Find(".jstree-clicked").Parents().RemoveClass("collapse-hide")
tree, _ = menuDoc.Find("body").Html()
}
if beego.AppConfig.DefaultBool("showWechatCode", false) && bookResult.PrivatelyOwned == 0 {
wechatCode := models.NewWechatCode()
go wechatCode.CreateWechatCode(bookResult.BookId) //如果已经生成了小程序码,则不会再生成
this.Data["Wxacode"] = wechatCode.GetCode(bookResult.BookId)
}
if wd := this.GetString("wd"); strings.TrimSpace(wd) != "" {
this.Data["Keywords"] = models.NewElasticSearchClient().SegWords(wd)
}
this.Data["Bookmark"] = existBookmark
this.Data["Model"] = bookResult
this.Data["Book"] = bookResult //文档下载需要用到Book变量
this.Data["Result"] = template.HTML(tree)
this.Data["Title"] = doc.DocumentName
this.Data["DocId"] = doc.DocumentId
this.Data["Content"] = template.HTML(doc.Release)
this.Data["View"] = doc.Vcnt
this.Data["UpdatedAt"] = doc.ModifyTime.Format("2006-01-02 15:04:05")
}
//编辑文档.
func (this *DocumentController) Edit() {
docId := 0 // 文档id
identify := this.Ctx.Input.Param(":key")
if identify == "" {
this.Abort("404")
}
bookResult := models.NewBookResult()
var err error
//如果是超级管理者,则不判断权限
if this.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
this.JsonResult(6002, "书籍不存在或权限不足")
}
bookResult = book.ToBookResult()
} else {
bookResult, err = models.NewBookResult().FindByIdentify(identify, this.Member.MemberId)
if err != nil {
beego.Error("DocumentController.Edit => ", err)
this.Abort("404")
}
if bookResult.RoleId == conf.BookObserver {
this.JsonResult(6002, "书籍不存在或权限不足")
}
}
//根据不同编辑器类型加载编辑器【注:现在只支持markdown】
this.TplName = "document/markdown_edit_template.html"
this.Data["Model"] = bookResult
r, _ := json.Marshal(bookResult)
this.Data["ModelResult"] = template.JS(string(r))
this.Data["Result"] = template.JS("[]")
// 编辑的文档
if id := this.GetString(":id"); id != "" {
if num, _ := strconv.Atoi(id); num > 0 {
docId = num
} else { //字符串
var doc = models.NewDocument()
orm.NewOrm().QueryTable(doc).Filter("identify", id).Filter("book_id", bookResult.BookId).One(doc, "document_id")
docId = doc.DocumentId
}
}
trees, err := models.NewDocument().FindDocumentTree(bookResult.BookId, docId, true)
if err != nil {
beego.Error("FindDocumentTree => ", err)
} else {
if len(trees) > 0 {
if jsTree, err := json.Marshal(trees); err == nil {
this.Data["Result"] = template.JS(string(jsTree))
}
} else {
this.Data["Result"] = template.JS("[]")
}
}
this.Data["BaiDuMapKey"] = beego.AppConfig.DefaultString("baidumapkey", "")
}
//创建一个文档.
func (this *DocumentController) Create() {
identify := this.GetString("identify") //书籍书籍标识
docIdentify := this.GetString("doc_identify") //新建的文档标识
docName := this.GetString("doc_name")
parentId, _ := this.GetInt("parent_id", 0)
docId, _ := this.GetInt("doc_id", 0)
bookIdentify := strings.TrimSpace(this.GetString(":key"))
o := orm.NewOrm()
if identify == "" {
this.JsonResult(6001, "参数错误")
}
if docName == "" {
this.JsonResult(6004, "文档名称不能为空")
}
if docIdentify != "" {
if ok, err := regexp.MatchString(`^[a-zA-Z0-9_\-\.]*$`, docIdentify); !ok || err != nil {
this.JsonResult(6003, "文档标识只能是数字、字母,以及“-”、“_”和“.”等字符,并且不能是纯数字")
}
if num, _ := strconv.Atoi(docIdentify); docIdentify == "0" || strconv.Itoa(num) == docIdentify { //不能是纯数字
this.JsonResult(6005, "文档标识只能是数字、字母,以及“-”、“_”和“.”等字符,并且不能是纯数字")
}
if bookIdentify == "" {
this.JsonResult(1, "书籍参数不正确")
}
var book models.Book
o.QueryTable("md_books").Filter("Identify", bookIdentify).One(&book, "BookId")
if book.BookId == 0 {
this.JsonResult(1, "书籍未创建")
}
d, _ := models.NewDocument().FindByBookIdAndDocIdentify(book.BookId, docIdentify)
if d.DocumentId > 0 && d.DocumentId != docId {
this.JsonResult(6006, "文档标识已被使用")
}
} else {
docIdentify = fmt.Sprintf("date-%v", time.Now().Format("2006.01.02.15.04.05"))
}
bookId := 0
//如果是超级管理员则不判断权限
if this.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
beego.Error(err)
this.JsonResult(6002, "书籍不存在或权限不足")
}
bookId = book.BookId
} else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, this.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("FindByIdentify => ", err)
this.JsonResult(6002, "书籍不存在或权限不足")
}
bookId = bookResult.BookId
}
if parentId > 0 {
doc, err := models.NewDocument().Find(parentId)
if err != nil || doc.BookId != bookId {
this.JsonResult(6003, "父分类不存在")
}
}
document, _ := models.NewDocument().Find(docId)
document.MemberId = this.Member.MemberId
document.BookId = bookId
if docIdentify != "" {
document.Identify = docIdentify
}
document.Version = time.Now().Unix()
document.DocumentName = docName
document.ParentId = parentId
docIdInt64, err := document.InsertOrUpdate()
if err != nil {
beego.Error("InsertOrUpdate => ", err)
this.JsonResult(6005, "保存失败")
}
ModelStore := new(models.DocumentStore)
if ModelStore.GetFiledById(docIdInt64, "markdown") == "" {
//因为创建和更新文档基本信息都调用的这个接口,先判断markdown是否有内容,没有内容则添加默认内容
if err := ModelStore.InsertOrUpdate(models.DocumentStore{DocumentId: int(docIdInt64), Markdown: "[TOC]\n\r\n\r"}); err != nil {
beego.Error(err)
}
}
this.JsonResult(0, "ok", document)
}
//批量创建文档
func (this *DocumentController) CreateMulti() {
bookId, _ := this.GetInt("book_id")
if !(this.Member.MemberId > 0 && bookId > 0) {
this.JsonResult(1, "操作失败:只有书籍创始人才能批量添加")
}
var book models.Book
o := orm.NewOrm()
o.QueryTable("md_books").Filter("book_id", bookId).Filter("member_id", this.Member.MemberId).One(&book, "book_id")
if book.BookId > 0 {
content := this.GetString("content")
slice := strings.Split(content, "\n")
if len(slice) > 0 {
ModelStore := new(models.DocumentStore)
for _, row := range slice {
if chapter := strings.Split(strings.TrimSpace(row), " "); len(chapter) > 1 {
if ok, err := regexp.MatchString(`^[a-zA-Z0-9_\-\.]*$`, chapter[0]); ok && err == nil {
i, _ := strconv.Atoi(chapter[0])
if chapter[0] != "0" && strconv.Itoa(i) != chapter[0] { //不为纯数字
doc := models.Document{
DocumentName: strings.Join(chapter[1:], " "),
Identify: chapter[0],
BookId: bookId,
//Markdown: "[TOC]\n\r",
MemberId: this.Member.MemberId,
}
if docId, err := doc.InsertOrUpdate(); err == nil {
if err := ModelStore.InsertOrUpdate(models.DocumentStore{DocumentId: int(docId), Markdown: "[TOC]\n\r\n\r"}); err != nil {
beego.Error(err.Error())
}
} else {
beego.Error(err)
}
}
}
}
}
}
}
this.JsonResult(0, "添加成功")
}
//上传附件或图片.
func (this *DocumentController) Upload() {
identify := this.GetString("identify")
docId, _ := this.GetInt("doc_id")
fileType := this.GetString("type")
if identify == "" {
this.JsonResult(6001, "参数错误")
}
name := "editormd-file-file"
if docId == 0 {
if fileType != "" && !strings.Contains(fileType, "/") {
name = "editormd-" + fileType + "-file"
} else {
fileType = strings.Split(fileType, "/")[0]
}
}
file, moreFile, err := this.GetFile(name)
if err == http.ErrMissingFile {
name = "editormd-image-file"
file, moreFile, err = this.GetFile(name)
if err == http.ErrMissingFile {
this.JsonResult(6003, "没有发现需要上传的文件")
}
}
if err != nil {
this.JsonResult(6002, err.Error())
}
defer file.Close()
ext := filepath.Ext(moreFile.Filename)
if ext == "" {
this.JsonResult(6003, "无法解析文件的格式")
}
if !conf.IsAllowUploadFileExt(ext, fileType) {
this.JsonResult(6004, "不允许的文件类型")
}
bookId := 0
bookIdentify := ""
//如果是超级管理员,则不判断权限
if this.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
this.JsonResult(6006, "文档不存在或权限不足")
}
bookId = book.BookId
bookIdentify = book.Identify
} else {
book, err := models.NewBookResult().FindByIdentify(identify, this.Member.MemberId)
if err != nil {
beego.Error("DocumentController.Edit => ", err)
if err == orm.ErrNoRows {
this.JsonResult(6006, "权限不足")
}
this.JsonResult(6001, err.Error())
}
//如果没有编辑权限
if book.RoleId != conf.BookEditor && book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
this.JsonResult(6006, "权限不足")
}
bookId = book.BookId
bookIdentify = book.Identify
}
if docId > 0 {
doc, err := models.NewDocument().Find(docId)
if err != nil {
this.JsonResult(6007, "文档不存在")
}
if doc.BookId != bookId {
this.JsonResult(6008, "文档不属于指定的书籍")
}
} else {
identify := filepath.Base(this.Ctx.Request.Header.Get("referer"))
doc, err := models.NewDocument().FindByBookIdAndDocIdentify(bookId, identify)
if err != nil {
this.JsonResult(6007, "文档不存在")
}
docId = doc.DocumentId
}
fileName := strconv.FormatInt(time.Now().UnixNano(), 16)
tmpPath := fmt.Sprintf("cache/%v-%v-%v", bookIdentify, time.Now().Format("200601"), fileName+ext)
err = this.SaveToFile(name, tmpPath)
if err != nil {
beego.Error("SaveToFile => ", err)
this.JsonResult(6005, "保存文件失败")
}
defer func() { os.Remove(tmpPath) }()
prefix := "uploads"
savePath := filepath.Join("projects", bookIdentify, time.Now().Format("200601"), fileName+ext)
if utils.StoreType != utils.StoreOss {
savePath = filepath.Join(prefix, savePath)
os.MkdirAll(filepath.Dir(savePath), os.ModePerm)
os.Rename(tmpPath, savePath)
}
savePath = strings.ReplaceAll(savePath, "\\", "/")
attachment := models.NewAttachment()
attachment.BookId = bookId
attachment.FileName = moreFile.Filename
attachment.CreateAt = this.Member.MemberId
attachment.FileExt = ext
attachment.FilePath = "/" + savePath
attachment.HttpPath = attachment.FilePath
attachment.DocumentId = docId
// 非附件
if name != "editormd-file-file" {
attachment.DocumentId = 0
}
if fileInfo, err := os.Stat(savePath); err == nil {
attachment.FileSize = float64(fileInfo.Size())
}
// 数据入库
if err = attachment.Insert(); err != nil {
os.Remove(savePath)
beego.Error("Attachment Insert => ", err)
this.JsonResult(6006, "文件保存失败")
}
if utils.StoreType == utils.StoreOss {
if err := store.ModelStoreOss.MoveToOss(tmpPath, savePath, true, false); err != nil {
beego.Error(err.Error())
} else {
if fileType == "video" || fileType == "audio" {
if bucket, err := store.ModelStoreOss.GetBucket(); err == nil {
bucket.SetObjectACL(savePath, oss.ACLPrivate)
}
}
}
}
result := map[string]interface{}{
"errcode": 0,
"success": 1,
"message": "ok",
"url": attachment.HttpPath,
"alt": attachment.FileName,
"is_attach": attachment.DocumentId > 0,
"attach": attachment,
}
this.Ctx.Output.JSON(result, true, false)
this.StopRun()
}
//DownloadAttachment 下载附件.
func (this *DocumentController) DownloadAttachment() {
identify := this.Ctx.Input.Param(":key")
attachId, _ := strconv.Atoi(this.Ctx.Input.Param(":attach_id"))
token := this.GetString("token")
memberId := 0
if this.Member != nil {
memberId = this.Member.MemberId
}
bookId := 0
//判断用户是否参与了书籍
bookResult, err := models.NewBookResult().FindByIdentify(identify, memberId)
if err != nil {
//判断书籍公开状态
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
this.Abort("404")
}
//如果不是超级管理员则判断权限
if this.Member == nil || this.Member.Role != conf.MemberSuperRole {
//如果书籍是私有的,并且token不正确
if (book.PrivatelyOwned == 1 && token == "") || (book.PrivatelyOwned == 1 && book.PrivateToken != token) {
this.Abort("404")
}
}
bookId = book.BookId
} else {
bookId = bookResult.BookId
}
//查找附件
attachment, err := models.NewAttachment().Find(attachId)
if err != nil {
beego.Error("DownloadAttachment => ", err)
if err == orm.ErrNoRows {
this.Abort("404")
} else {
this.Abort("404")
}
}
if attachment.BookId != bookId {
this.Abort("404")
}
this.Ctx.Output.Download(strings.TrimLeft(attachment.FilePath, "./"), attachment.FileName)
this.StopRun()
}
//删除附件.
func (this *DocumentController) RemoveAttachment() {
attachId, _ := this.GetInt("attach_id")
if attachId <= 0 {
this.JsonResult(6001, "参数错误")
}
attach, err := models.NewAttachment().Find(attachId)
if err != nil {
beego.Error(err)
this.JsonResult(6002, "附件不存在")
}
document, err := models.NewDocument().Find(attach.DocumentId)
if err != nil {
beego.Error(err)
this.JsonResult(6003, "文档不存在")
}
if this.Member.Role != conf.MemberSuperRole {
rel, err := models.NewRelationship().FindByBookIdAndMemberId(document.BookId, this.Member.MemberId)
if err != nil {
beego.Error(err)
this.JsonResult(6004, "权限不足")
}
if rel.RoleId == conf.BookObserver {
this.JsonResult(6004, "权限不足")
}
}
if err = attach.Delete(); err != nil {
beego.Error(err)
this.JsonResult(6005, "删除失败")
}
os.Remove(strings.TrimLeft(attach.FilePath, "./"))
this.JsonResult(0, "ok", attach)
}
//删除文档.
func (this *DocumentController) Delete() {
identify := this.GetString("identify")
docId, _ := this.GetInt("doc_id", 0)
bookId := 0
//如果是超级管理员则忽略权限判断
if this.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
beego.Error("FindByIdentify => ", err)
this.JsonResult(6002, "书籍不存在或权限不足")
}
bookId = book.BookId
} else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, this.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("FindByIdentify => ", err)
this.JsonResult(6002, "书籍不存在或权限不足")
}
bookId = bookResult.BookId
}
if docId <= 0 {
this.JsonResult(6001, "参数错误")
}
doc, err := models.NewDocument().Find(docId)
if err != nil {
beego.Error("Delete => ", err)
this.JsonResult(6003, "删除失败")
}
//如果文档所属书籍错误
if doc.BookId != bookId {
this.JsonResult(6004, "参数错误")
}
//递归删除书籍下的文档以及子文档
err = doc.RecursiveDocument(doc.DocumentId)
if err != nil {
beego.Error(err.Error())
this.JsonResult(6005, "删除失败")
}
//重置文档数量统计
models.NewBook().ResetDocumentNumber(doc.BookId)
go func() {
// 删除文档的索引
client := models.NewElasticSearchClient()
if errDel := client.DeleteIndex(docId, false); errDel != nil && client.On {
beego.Error(errDel.Error())
}
}()
this.JsonResult(0, "ok")
}
// 获取或更新文档内容.
func (this *DocumentController) Content() {
identify := this.Ctx.Input.Param(":key")
docId, err := this.GetInt("doc_id")
errMsg := "ok"
if err != nil {
docId, _ = strconv.Atoi(this.Ctx.Input.Param(":id"))
}
bookId := 0
//如果是超级管理员,则忽略权限
if this.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {