/
DocumentController.go
1352 lines (1083 loc) · 34.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"
"net/url"
"image/png"
"fmt"
"bytes"
"github.com/PuerkitoBio/goquery"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/qr"
"github.com/lifei6671/mindoc/conf"
"github.com/lifei6671/mindoc/models"
"github.com/lifei6671/mindoc/utils"
"github.com/lifei6671/mindoc/utils/pagination"
"gopkg.in/russross/blackfriday.v2"
"github.com/lifei6671/mindoc/utils/cryptil"
"github.com/lifei6671/mindoc/utils/filetil"
"github.com/lifei6671/mindoc/utils/gopool"
"github.com/astaxie/beego/logs"
)
// DocumentController struct
type DocumentController struct {
BaseController
}
// 文档首页
func (c *DocumentController) Index() {
c.Prepare()
identify := c.Ctx.Input.Param(":key")
token := c.GetString("token")
if identify == "" {
c.ShowErrorPage(404, "项目不存在或已删除")
}
// 如果没有开启匿名访问则跳转到登录
if !c.EnableAnonymous && !isUserLoggedIn(c) {
promptUserToLogIn(c)
return
}
bookResult := isReadable(identify, token, c)
c.TplName = "document/" + bookResult.Theme + "_read.tpl"
selected := 0
if bookResult.IsUseFirstDocument {
doc, err := bookResult.FindFirstDocumentByBookId(bookResult.BookId)
if err == nil {
selected = doc.DocumentId
c.Data["Title"] = doc.DocumentName
c.Data["Content"] = template.HTML(doc.Release)
c.Data["Description"] = utils.AutoSummary(doc.Release, 120)
}
} else {
c.Data["Title"] = "概要"
c.Data["Content"] = template.HTML(blackfriday.Run([]byte(bookResult.Description)))
}
tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, selected)
if err != nil {
if err == orm.ErrNoRows {
c.ShowErrorPage(404, "当前项目没有文档")
} else {
beego.Error("生成项目文档树时出错 -> ", err)
c.ShowErrorPage(500, "生成项目文档树时出错")
}
}
c.Data["Model"] = bookResult
c.Data["Result"] = template.HTML(tree)
}
// 阅读文档
func (c *DocumentController) Read() {
c.Prepare()
identify := c.Ctx.Input.Param(":key")
token := c.GetString("token")
id := c.GetString(":id")
c.Data["DocumentId"] = id
if identify == "" || id == "" {
c.ShowErrorPage(404, "项目不存或已删除")
}
// 如果没有开启匿名访问则跳转到登录
if !c.EnableAnonymous && !isUserLoggedIn(c) {
promptUserToLogIn(c)
return
}
bookResult := isReadable(identify, token, c)
c.TplName = fmt.Sprintf("document/%s_read.tpl", bookResult.Theme)
doc := models.NewDocument()
if docId, err := strconv.Atoi(id); err == nil {
doc, err = doc.FromCacheById(docId)
if err != nil {
beego.Error("从缓存中读取文档时失败 ->", err)
c.ShowErrorPage(404, "文档不存在或已删除")
}
} else {
doc, err = doc.FromCacheByIdentify(id, bookResult.BookId)
if err != nil {
if err == orm.ErrNoRows {
c.ShowErrorPage(404, "文档不存在或已删除")
} else {
beego.Error("从缓存查询文档时出错 ->", err)
c.ShowErrorPage(500, "未知异常")
}
}
}
if doc.BookId != bookResult.BookId {
c.ShowErrorPage(404, "文档不存在或已删除")
}
doc.Processor()
attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
if err == nil {
doc.AttachList = attach
}
if c.IsAjax() {
var data struct {
DocTitle string `json:"doc_title"`
Body string `json:"body"`
Title string `json:"title"`
Version int64 `json:"version"`
}
data.DocTitle = doc.DocumentName
data.Body = doc.Release
data.Title = doc.DocumentName + " - Powered by MinDoc"
data.Version = doc.Version
c.JsonResult(0, "ok", data)
}
tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, doc.DocumentId)
if err != nil && err != orm.ErrNoRows {
beego.Error("生成项目文档树时出错 ->", err)
c.ShowErrorPage(500, "生成项目文档树时出错")
}
c.Data["Description"] = utils.AutoSummary(doc.Release, 120)
c.Data["Model"] = bookResult
c.Data["Result"] = template.HTML(tree)
c.Data["Title"] = doc.DocumentName
c.Data["Content"] = template.HTML(doc.Release)
}
// 编辑文档
func (c *DocumentController) Edit() {
c.Prepare()
identify := c.Ctx.Input.Param(":key")
if identify == "" {
c.ShowErrorPage(404, "无法解析项目标识")
}
bookResult := models.NewBookResult()
var err error
// 如果是超级管理者,则不判断权限
if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
c.JsonResult(6002, "项目不存在或权限不足")
}
bookResult = models.NewBookResult().ToBookResult(*book)
} else {
bookResult, err = models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil {
if err == orm.ErrNoRows {
c.ShowErrorPage(403, "项目不存在或没有权限")
} else {
beego.Error("查询项目时出错 -> ", err)
c.ShowErrorPage(500, "查询项目时出错")
}
}
if bookResult.RoleId == conf.BookObserver {
c.JsonResult(6002, "项目不存在或权限不足")
}
}
// 根据不同编辑器类型加载编辑器
if bookResult.Editor == "markdown" {
c.TplName = "document/markdown_edit_template.tpl"
} else if bookResult.Editor == "html" {
c.TplName = "document/new_html_edit_template.tpl"
} else {
c.TplName = "document/" + bookResult.Editor + "_edit_template.tpl"
}
c.Data["Model"] = bookResult
r, _ := json.Marshal(bookResult)
c.Data["ModelResult"] = template.JS(string(r))
c.Data["Result"] = template.JS("[]")
trees, err := models.NewDocument().FindDocumentTree(bookResult.BookId)
if err != nil {
beego.Error("FindDocumentTree => ", err)
} else {
if len(trees) > 0 {
if jtree, err := json.Marshal(trees); err == nil {
c.Data["Result"] = template.JS(string(jtree))
}
} else {
c.Data["Result"] = template.JS("[]")
}
}
c.Data["BaiDuMapKey"] = beego.AppConfig.DefaultString("baidumapkey", "")
if conf.GetUploadFileSize() > 0 {
c.Data["UploadFileSize"] = conf.GetUploadFileSize()
}else{
c.Data["UploadFileSize"] = "undefined";
}
}
// 创建一个文档
func (c *DocumentController) Create() {
identify := c.GetString("identify")
docIdentify := c.GetString("doc_identify")
docName := c.GetString("doc_name")
parentId, _ := c.GetInt("parent_id", 0)
docId, _ := c.GetInt("doc_id", 0)
isOpen, _ := c.GetInt("is_open", 0)
if identify == "" {
c.JsonResult(6001, "参数错误")
}
if docName == "" {
c.JsonResult(6004, "文档名称不能为空")
}
bookId := 0
// 如果是超级管理员则不判断权限
if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
beego.Error(err)
c.JsonResult(6002, "项目不存在或权限不足")
}
bookId = book.BookId
} else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("FindByIdentify => ", err)
c.JsonResult(6002, "项目不存在或权限不足")
}
bookId = bookResult.BookId
}
if docIdentify != "" {
if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, docIdentify); !ok || err != nil {
c.JsonResult(6003, "文档标识只能包含小写字母、数字,以及“-”、“.”和“_”符号")
}
d, _ := models.NewDocument().FindByIdentityFirst(docIdentify, bookId)
if d.DocumentId > 0 && d.DocumentId != docId {
c.JsonResult(6006, "文档标识已被使用")
}
}
if parentId > 0 {
doc, err := models.NewDocument().Find(parentId)
if err != nil || doc.BookId != bookId {
c.JsonResult(6003, "父分类不存在")
}
}
document, _ := models.NewDocument().Find(docId)
document.MemberId = c.Member.MemberId
document.BookId = bookId
document.Identify = docIdentify
document.Version = time.Now().Unix()
document.DocumentName = docName
document.ParentId = parentId
if isOpen == 1 {
document.IsOpen = 1
} else {
document.IsOpen = 0
}
if err := document.InsertOrUpdate(); err != nil {
beego.Error("添加或更新文档时出错 -> ", err)
c.JsonResult(6005, "保存失败")
} else {
c.JsonResult(0, "ok", document)
}
}
// 上传附件或图片
func (c *DocumentController) Upload() {
identify := c.GetString("identify")
docId, _ := c.GetInt("doc_id")
isAttach := true
if identify == "" {
c.JsonResult(6001, "参数错误")
}
name := "editormd-file-file"
file, moreFile, err := c.GetFile(name)
if err == http.ErrMissingFile {
name = "editormd-image-file"
file, moreFile, err = c.GetFile(name)
if err == http.ErrMissingFile {
c.JsonResult(6003, "没有发现需要上传的文件")
}
}
if err != nil {
c.JsonResult(6002, err.Error())
}
defer file.Close()
type Size interface {
Size() int64
}
if conf.GetUploadFileSize() > 0 && moreFile.Size > conf.GetUploadFileSize() {
c.JsonResult(6009, "文件大小超过了限定的最大值")
}
ext := filepath.Ext(moreFile.Filename)
//文件必须带有后缀名
if ext == "" {
c.JsonResult(6003, "无法解析文件的格式")
}
//如果文件类型设置为 * 标识不限制文件类型
if conf.IsAllowUploadFileExt(ext) == false {
c.JsonResult(6004, "不允许的文件类型")
}
bookId := 0
// 如果是超级管理员,则不判断权限
if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
c.JsonResult(6006, "文档不存在或权限不足")
}
bookId = book.BookId
} else {
book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil {
beego.Error("DocumentController.Edit => ", err)
if err == orm.ErrNoRows {
c.JsonResult(6006, "权限不足")
}
c.JsonResult(6001, err.Error())
}
// 如果没有编辑权限
if book.RoleId != conf.BookEditor && book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
c.JsonResult(6006, "权限不足")
}
bookId = book.BookId
}
if docId > 0 {
doc, err := models.NewDocument().Find(docId)
if err != nil {
c.JsonResult(6007, "文档不存在")
}
if doc.BookId != bookId {
c.JsonResult(6008, "文档不属于指定的项目")
}
}
fileName := "m_" + cryptil.UniqueId() + "_r"
filePath := filepath.Join(conf.WorkingDirectory, "uploads", identify)
//将图片和文件分开存放
if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") || strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".gif") {
filePath = filepath.Join(filePath, "images", fileName+ext)
} else {
filePath = filepath.Join(filePath, "files", fileName+ext)
}
path := filepath.Dir(filePath)
os.MkdirAll(path, os.ModePerm)
err = c.SaveToFile(name, filePath)
if err != nil {
beego.Error("保存文件失败 -> ", err)
c.JsonResult(6005, "保存文件失败")
}
attachment := models.NewAttachment()
attachment.BookId = bookId
attachment.FileName = moreFile.Filename
attachment.CreateAt = c.Member.MemberId
attachment.FileExt = ext
attachment.FilePath = strings.TrimPrefix(filePath, conf.WorkingDirectory)
attachment.DocumentId = docId
if fileInfo, err := os.Stat(filePath); err == nil {
attachment.FileSize = float64(fileInfo.Size())
}
if docId > 0 {
attachment.DocumentId = docId
}
if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") || strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".gif") {
attachment.HttpPath = "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
if strings.HasPrefix(attachment.HttpPath, "//") {
attachment.HttpPath = conf.URLForWithCdnImage(string(attachment.HttpPath[1:]))
}
isAttach = false
}
err = attachment.Insert()
if err != nil {
os.Remove(filePath)
beego.Error("文件保存失败 ->", err)
c.JsonResult(6006, "文件保存失败")
}
if attachment.HttpPath == "" {
attachment.HttpPath = conf.URLFor("DocumentController.DownloadAttachment", ":key", identify, ":attach_id", attachment.AttachmentId)
if err := attachment.Update(); err != nil {
beego.Error("保存文件失败 ->", err)
c.JsonResult(6005, "保存文件失败")
}
}
result := map[string]interface{}{
"errcode": 0,
"success": 1,
"message": "ok",
"url": attachment.HttpPath,
"alt": attachment.FileName,
"is_attach": isAttach,
"attach": attachment,
}
c.Ctx.Output.JSON(result, true, false)
c.StopRun()
}
// 下载附件
func (c *DocumentController) DownloadAttachment() {
c.Prepare()
identify := c.Ctx.Input.Param(":key")
attachId, _ := strconv.Atoi(c.Ctx.Input.Param(":attach_id"))
token := c.GetString("token")
memberId := 0
if c.Member != nil {
memberId = c.Member.MemberId
}
bookId := 0
// 判断用户是否参与了项目
bookResult, err := models.NewBookResult().FindByIdentify(identify, memberId)
if err != nil {
// 判断项目公开状态
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
if err == orm.ErrNoRows {
c.ShowErrorPage(404, "项目不存在或已删除")
} else {
beego.Error("查找项目时出错 ->", err)
c.ShowErrorPage(500, "系统错误")
}
}
// 如果不是超级管理员则判断权限
if c.Member == nil || c.Member.Role != conf.MemberSuperRole {
// 如果项目是私有的,并且 token 不正确
if (book.PrivatelyOwned == 1 && token == "") || (book.PrivatelyOwned == 1 && book.PrivateToken != token) {
c.ShowErrorPage(403, "权限不足")
}
}
bookId = book.BookId
} else {
bookId = bookResult.BookId
}
// 查找附件
attachment, err := models.NewAttachment().Find(attachId)
if err != nil {
beego.Error("查找附件时出错 -> ", err)
if err == orm.ErrNoRows {
c.ShowErrorPage(404, "附件不存在或已删除")
} else {
c.ShowErrorPage(500, "查找附件时出错")
}
}
if attachment.BookId != bookId {
c.ShowErrorPage(404, "附件不存在或已删除")
}
c.Ctx.Output.Download(filepath.Join(conf.WorkingDirectory, attachment.FilePath), attachment.FileName)
c.StopRun()
}
// 删除附件
func (c *DocumentController) RemoveAttachment() {
c.Prepare()
attachId, _ := c.GetInt("attach_id")
if attachId <= 0 {
c.JsonResult(6001, "参数错误")
}
attach, err := models.NewAttachment().Find(attachId)
if err != nil {
beego.Error(err)
c.JsonResult(6002, "附件不存在")
}
document, err := models.NewDocument().Find(attach.DocumentId)
if err != nil {
beego.Error(err)
c.JsonResult(6003, "文档不存在")
}
if c.Member.Role != conf.MemberSuperRole {
rel, err := models.NewRelationship().FindByBookIdAndMemberId(document.BookId, c.Member.MemberId)
if err != nil {
beego.Error(err)
c.JsonResult(6004, "权限不足")
}
if rel.RoleId == conf.BookObserver {
c.JsonResult(6004, "权限不足")
}
}
err = attach.Delete()
if err != nil {
beego.Error(err)
c.JsonResult(6005, "删除失败")
}
os.Remove(filepath.Join(conf.WorkingDirectory, attach.FilePath))
c.JsonResult(0, "ok", attach)
}
// 删除文档
func (c *DocumentController) Delete() {
c.Prepare()
identify := c.GetString("identify")
docId, err := c.GetInt("doc_id", 0)
bookId := 0
// 如果是超级管理员则忽略权限判断
if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
beego.Error("FindByIdentify => ", err)
c.JsonResult(6002, "项目不存在或权限不足")
}
bookId = book.BookId
} else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("FindByIdentify => ", err)
c.JsonResult(6002, "项目不存在或权限不足")
}
bookId = bookResult.BookId
}
if docId <= 0 {
c.JsonResult(6001, "参数错误")
}
doc, err := models.NewDocument().Find(docId)
if err != nil {
beego.Error("Delete => ", err)
c.JsonResult(6003, "删除失败")
}
// 如果文档所属项目错误
if doc.BookId != bookId {
c.JsonResult(6004, "参数错误")
}
// 递归删除项目下的文档以及子文档
err = doc.RecursiveDocument(doc.DocumentId)
if err != nil {
c.JsonResult(6005, "删除失败")
}
// 重置文档数量统计
models.NewBook().ResetDocumentNumber(doc.BookId)
c.JsonResult(0, "ok")
}
// 获取文档内容
func (c *DocumentController) Content() {
c.Prepare()
identify := c.Ctx.Input.Param(":key")
docId, err := c.GetInt("doc_id")
if err != nil {
docId, _ = strconv.Atoi(c.Ctx.Input.Param(":id"))
}
bookId := 0
autoRelease := false
// 如果是超级管理员,则忽略权限
if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
c.JsonResult(6002, "项目不存在或权限不足")
}
bookId = book.BookId
autoRelease = book.AutoRelease == 1
} else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("FindByIdentify => ", err)
c.JsonResult(6002, "项目不存在或权限不足")
}
bookId = bookResult.BookId
autoRelease = bookResult.AutoRelease
}
if docId <= 0 {
c.JsonResult(6001, "参数错误")
}
if c.Ctx.Input.IsPost() {
markdown := strings.TrimSpace(c.GetString("markdown", ""))
content := c.GetString("html")
version, _ := c.GetInt64("version", 0)
isCover := c.GetString("cover")
doc, err := models.NewDocument().Find(docId)
if err != nil {
c.JsonResult(6003, "读取文档错误")
}
if doc.BookId != bookId {
c.JsonResult(6004, "保存的文档不属于指定项目")
}
if doc.Version != version && !strings.EqualFold(isCover, "yes") {
beego.Info("%d|", version, doc.Version)
c.JsonResult(6005, "文档已被修改确定要覆盖吗?")
}
history := models.NewDocumentHistory()
history.DocumentId = docId
history.Content = doc.Content
history.Markdown = doc.Markdown
history.DocumentName = doc.DocumentName
history.ModifyAt = c.Member.MemberId
history.MemberId = doc.MemberId
history.ParentId = doc.ParentId
history.Version = time.Now().Unix()
history.Action = "modify"
history.ActionName = "修改文档"
if markdown == "" && content != "" {
doc.Markdown = content
} else {
doc.Markdown = markdown
}
doc.Version = time.Now().Unix()
doc.Content = content
if err := doc.InsertOrUpdate(); err != nil {
beego.Error("InsertOrUpdate => ", err)
c.JsonResult(6006, "保存失败")
}
// 如果启用了文档历史,则添加历史文档
///如果两次保存的MD5值不同则保存为历史,否则忽略
go func(history *models.DocumentHistory) {
if c.EnableDocumentHistory && cryptil.Md5Crypt(history.Markdown) != cryptil.Md5Crypt(doc.Markdown) {
_, err = history.InsertOrUpdate()
if err != nil {
beego.Error("DocumentHistory InsertOrUpdate => ", err)
}
}
}(history)
//如果启用了自动发布
if autoRelease {
go func() {
err := doc.ReleaseContent()
if err == nil {
logs.Informational("文档自动发布成功 -> document_id=%d;document_name=%s", doc.DocumentId, doc.DocumentName)
}
}()
}
c.JsonResult(0, "ok", doc)
}
doc, err := models.NewDocument().Find(docId)
if err != nil {
c.JsonResult(6003, "文档不存在")
}
attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
if err == nil {
doc.AttachList = attach
}
c.JsonResult(0, "ok", doc)
}
//
//func (c *DocumentController) GetDocumentById(id string) (doc *models.Document, err error) {
// doc = models.NewDocument()
// if doc_id, err := strconv.Atoi(id); err == nil {
// doc, err = doc.Find(doc_id)
// if err != nil {
// return nil, err
// }
// } else {
// doc, err = doc.FindByFieldFirst("identify", id)
// if err != nil {
// return nil, err
// }
// }
//
// return doc, nil
//}
// 导出
func (c *DocumentController) Export() {
c.Prepare()
identify := c.Ctx.Input.Param(":key")
if identify == "" {
c.ShowErrorPage(500, "参数错误")
}
output := c.GetString("output")
token := c.GetString("token")
// 如果没有开启匿名访问则跳转到登录
if !c.EnableAnonymous && !isUserLoggedIn(c) {
promptUserToLogIn(c)
return
}
if !conf.GetEnableExport() {
c.ShowErrorPage(500, "系统没有开启导出功能")
}
bookResult := models.NewBookResult()
if c.Member != nil && c.Member.IsAdministrator() {
book, err := models.NewBook().FindByIdentify(identify)
if err != nil {
if err == orm.ErrNoRows {
c.ShowErrorPage(404, "项目不存在")
} else {
beego.Error("查找项目时出错 ->", err)
c.ShowErrorPage(500, "查找项目时出错")
}
}
bookResult = models.NewBookResult().ToBookResult(*book)
} else {
bookResult = isReadable(identify, token, c)
}
if !bookResult.IsDownload {
c.ShowErrorPage(200, "当前项目没有开启导出功能")
}
if !strings.HasPrefix(bookResult.Cover, "http:://") && !strings.HasPrefix(bookResult.Cover, "https:://") {
bookResult.Cover = conf.URLForWithCdnImage(bookResult.Cover)
}
if output == "markdown" {
if bookResult.Editor != "markdown" {
c.ShowErrorPage(500, "当前项目不支持Markdown编辑器")
}
p, err := bookResult.ExportMarkdown(c.CruSession.SessionID())
if err != nil {
c.ShowErrorPage(500, "导出文档失败")
}
c.Ctx.Output.Download(p, bookResult.BookName+".zip")
c.StopRun()
return
}
outputPath := filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(bookResult.BookId))
pdfpath := filepath.Join(outputPath, "book.pdf")
epubpath := filepath.Join(outputPath, "book.epub")
mobipath := filepath.Join(outputPath, "book.mobi")
docxpath := filepath.Join(outputPath, "book.docx")
if output == "pdf" && filetil.FileExists(pdfpath) {
c.Ctx.Output.Download(pdfpath, bookResult.BookName+".pdf")
c.Abort("200")
} else if output == "epub" && filetil.FileExists(epubpath) {
c.Ctx.Output.Download(epubpath, bookResult.BookName+".epub")
c.Abort("200")
} else if output == "mobi" && filetil.FileExists(mobipath) {
c.Ctx.Output.Download(mobipath, bookResult.BookName+".mobi")
c.Abort("200")
} else if output == "docx" && filetil.FileExists(docxpath) {
c.Ctx.Output.Download(docxpath, bookResult.BookName+".docx")
c.Abort("200")
} else if output == "pdf" || output == "epub" || output == "docx" || output == "mobi" {
if err := models.BackgroupConvert(c.CruSession.SessionID(), bookResult); err != nil && err != gopool.ErrHandlerIsExist {
c.ShowErrorPage(500, "导出失败,请查看系统日志")
}
c.ShowErrorPage(200, "文档正在后台转换,请稍后再下载")
} else {
c.ShowErrorPage(200, "不支持的文件格式")
}
c.ShowErrorPage(404, "项目没有导出文件")
}
// 生成项目访问的二维码
func (c *DocumentController) QrCode() {
c.Prepare()
identify := c.GetString(":key")
book, err := models.NewBook().FindByIdentify(identify)
if err != nil || book.BookId <= 0 {
c.ShowErrorPage(404, "项目不存在")
}
uri := conf.URLFor("DocumentController.Index", ":key", identify)
code, err := qr.Encode(uri, qr.L, qr.Unicode)
if err != nil {
beego.Error("生成二维码失败 ->", err)
c.ShowErrorPage(500, "生成二维码失败")
}
code, err = barcode.Scale(code, 150, 150)
if err != nil {
beego.Error("生成二维码失败 ->", err)
c.ShowErrorPage(500, "生成二维码失败")
}
c.Ctx.ResponseWriter.Header().Set("Content-Type", "image/png")
// imgpath := filepath.Join("cache","qrcode",identify + ".png")
err = png.Encode(c.Ctx.ResponseWriter, code)
if err != nil {
beego.Error("生成二维码失败 ->", err)
c.ShowErrorPage(500, "生成二维码失败")
}
}
// 项目内搜索
func (c *DocumentController) Search() {
c.Prepare()
identify := c.Ctx.Input.Param(":key")
token := c.GetString("token")
keyword := strings.TrimSpace(c.GetString("keyword"))
if identify == "" {
c.JsonResult(6001, "参数错误")
}
if !c.EnableAnonymous && !isUserLoggedIn(c) {
promptUserToLogIn(c)
return
}
bookResult := isReadable(identify, token, c)
docs, err := models.NewDocumentSearchResult().SearchDocument(keyword, bookResult.BookId)
if err != nil {
beego.Error(err)
c.JsonResult(6002, "搜索结果错误")
}
if len(docs) < 0 {
c.JsonResult(404, "没有数据库")
}
for _, doc := range docs {
doc.BookId = bookResult.BookId
doc.BookName = bookResult.BookName
doc.Description = bookResult.Description
doc.BookIdentify = bookResult.Identify
}
c.JsonResult(0, "ok", docs)
}
// 文档历史列表
func (c *DocumentController) History() {
c.Prepare()
c.TplName = "document/history.tpl"
identify := c.GetString("identify")
docId, err := c.GetInt("doc_id", 0)
pageIndex, _ := c.GetInt("page", 1)
bookId := 0
// 如果是超级管理员则忽略权限判断
if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
beego.Error("查找项目失败 ->", err)
c.Data["ErrorMessage"] = "项目不存在或权限不足"
return
}
bookId = book.BookId
c.Data["Model"] = book
} else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("查找项目失败 ->", err)