-
Notifications
You must be signed in to change notification settings - Fork 808
/
Copy pathBookController.go
1250 lines (1067 loc) · 36.4 KB
/
BookController.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 (
"encoding/json"
"errors"
"fmt"
"html/template"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/TruthHun/BookStack/graphics"
"github.com/TruthHun/BookStack/models/store"
"github.com/russross/blackfriday"
"github.com/TruthHun/BookStack/conf"
"github.com/TruthHun/BookStack/models"
"github.com/TruthHun/BookStack/utils"
"github.com/TruthHun/BookStack/utils/html2md"
"github.com/TruthHun/gotil/filetil"
"github.com/TruthHun/gotil/mdtil"
"github.com/TruthHun/gotil/util"
"github.com/TruthHun/gotil/ziptil"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
)
type BookController struct {
BaseController
}
// 替换字符串
func (this *BookController) Replace() {
identify := this.GetString(":key")
src := this.GetString("src")
dst := this.GetString("dst")
if this.Member.MemberId == 0 {
this.JsonResult(1, "请先登录")
}
book, err := models.NewBookResult().FindByIdentify(identify, this.Member.MemberId)
if err != nil {
if err == orm.ErrNoRows {
this.JsonResult(1, "内容不存在")
}
this.JsonResult(1, err.Error())
}
models.NewBook().Replace(book.BookId, src, dst)
this.JsonResult(0, "替换成功")
}
func (this *BookController) Index() {
this.Data["SettingBook"] = true
this.TplName = "book/index.html"
private, _ := this.GetInt("private", 1) //是否是私有文档
this.Data["Private"] = private
pageIndex, _ := this.GetInt("page", 1)
books, totalCount, _ := models.NewBook().FindToPager(pageIndex, conf.PageSize, this.Member.MemberId, private)
if totalCount > 0 {
this.Data["PageHtml"] = utils.NewPaginations(conf.RollPage, totalCount, conf.PageSize, pageIndex, beego.URLFor("BookController.Index"), fmt.Sprintf("&private=%v", private))
} else {
this.Data["PageHtml"] = ""
}
//处理封面图片
for idx, book := range books {
book.Cover = utils.ShowImg(book.Cover, "cover")
books[idx] = book
}
b, err := json.Marshal(books)
if err != nil || len(books) <= 0 {
this.Data["Result"] = template.JS("[]")
} else {
this.Data["Result"] = template.JS(string(b))
}
}
//收藏书籍
func (this *BookController) Star() {
uid := this.BaseController.Member.MemberId
if uid <= 0 {
this.JsonResult(1, "收藏失败,请先登录")
}
id, _ := this.GetInt(":id")
if id <= 0 {
this.JsonResult(1, "收藏失败,书籍不存在")
}
cancel, err := new(models.Star).Star(uid, id)
data := map[string]bool{"IsCancel": cancel}
if err != nil {
beego.Error(err.Error())
if cancel {
this.JsonResult(1, "取消收藏失败", data)
}
this.JsonResult(1, "添加收藏失败", data)
}
if cancel {
this.JsonResult(0, "取消收藏成功", data)
}
this.JsonResult(0, "添加收藏成功", data)
}
// Dashboard 书籍概要 .
func (this *BookController) Dashboard() {
this.TplName = "book/dashboard.html"
key := this.Ctx.Input.Param(":key")
if key == "" {
this.Abort("404")
}
book, err := models.NewBookResult().FindByIdentify(key, this.Member.MemberId)
if err != nil {
beego.Error(err)
if err == models.ErrPermissionDenied {
this.Abort("404")
}
this.Abort("404")
}
this.Data["Model"] = *book
}
// Setting 书籍设置 .
func (this *BookController) Setting() {
key := this.Ctx.Input.Param(":key")
if key == "" {
this.Abort("404")
}
book, err := models.NewBookResult().FindByIdentify(key, this.Member.MemberId)
if err != nil && err != orm.ErrNoRows {
beego.Error(err.Error())
if err == orm.ErrNoRows {
this.Abort("404")
}
if err == models.ErrPermissionDenied {
this.Abort("404")
}
this.Abort("404")
}
//如果不是创始人也不是管理员则不能操作
if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
this.Abort("404")
}
if book.PrivateToken != "" {
//book.PrivateToken = this.BaseUrl() + beego.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken)
tipsFmt := "访问链接:%v 访问密码:%v"
book.PrivateToken = fmt.Sprintf(tipsFmt, this.BaseUrl()+beego.URLFor("DocumentController.Index", ":key", book.Identify), book.PrivateToken)
}
//查询当前书籍的分类id
if selectedCates, rows, _ := new(models.BookCategory).GetByBookId(book.BookId); rows > 0 {
var maps = make(map[int]bool)
for _, cate := range selectedCates {
maps[cate.Id] = true
}
this.Data["Maps"] = maps
}
this.Data["Cates"], _ = new(models.Category).GetCates(-1, 1)
this.Data["Model"] = book
this.TplName = "book/setting.html"
}
// SaveBook 保存书籍信息
func (this *BookController) SaveBook() {
bookResult, err := this.IsPermission()
if err != nil {
this.JsonResult(6001, err.Error())
}
book, err := models.NewBook().Find(bookResult.BookId)
if err != nil {
logs.Error("SaveBook => ", err)
this.JsonResult(6002, err.Error())
}
bookName := strings.TrimSpace(this.GetString("book_name"))
description := strings.TrimSpace(this.GetString("description", ""))
commentStatus := this.GetString("comment_status")
tag := strings.TrimSpace(this.GetString("label"))
editor := strings.TrimSpace(this.GetString("editor"))
if strings.Count(description, "") > 500 {
this.JsonResult(6004, "书籍描述不能大于500字")
}
if commentStatus != "open" && commentStatus != "closed" && commentStatus != "group_only" && commentStatus != "registered_only" {
commentStatus = "closed"
}
if tag != "" {
tags := strings.Split(tag, ",")
if len(tags) > 10 {
this.JsonResult(6005, "最多允许添加10个标签")
}
}
if editor != "markdown" && editor != "html" {
editor = "markdown"
}
book.BookName = bookName
book.Description = description
book.CommentStatus = commentStatus
book.Label = tag
book.Editor = editor
book.Author = this.GetString("author")
book.AuthorURL = this.GetString("author_url")
book.Lang = this.GetString("lang")
book.AdTitle = this.GetString("ad_title")
book.AdLink = this.GetString("ad_link")
if err := book.Update(); err != nil {
this.JsonResult(6006, "保存失败")
}
bookResult.BookName = bookName
bookResult.Description = description
bookResult.CommentStatus = commentStatus
bookResult.Label = tag
//更新书籍分类
if cids, ok := this.Ctx.Request.Form["cid"]; ok {
new(models.BookCategory).SetBookCates(book.BookId, cids)
}
go func() {
es := models.ElasticSearchData{
Id: book.BookId,
BookId: 0,
Title: book.BookName,
Keywords: book.Label,
Content: book.Description,
Vcnt: book.Vcnt,
Private: book.PrivatelyOwned,
}
client := models.NewElasticSearchClient()
if errSearch := client.BuildIndex(es); errSearch != nil && client.On {
beego.Error(errSearch.Error())
}
}()
go models.CountCategory()
this.JsonResult(0, "ok", bookResult)
}
//设置书籍私有状态.
func (this *BookController) PrivatelyOwned() {
status := this.GetString("status")
if this.forbidGeneralRole() && status == "open" {
this.JsonResult(6001, "您的角色非作者和管理员,无法将书籍设置为公开")
}
if status != "open" && status != "close" {
this.JsonResult(6003, "参数错误")
}
state := 0
if status == "open" {
state = 0
} else {
state = 1
}
bookResult, err := this.IsPermission()
if err != nil {
this.JsonResult(6001, err.Error())
}
//只有创始人才能变更私有状态
if bookResult.RoleId != conf.BookFounder {
this.JsonResult(6002, "权限不足")
}
if _, err = orm.NewOrm().QueryTable("md_books").Filter("book_id", bookResult.BookId).Update(orm.Params{
"privately_owned": state,
}); err != nil {
logs.Error("PrivatelyOwned => ", err)
this.JsonResult(6004, "保存失败")
}
go func() {
models.CountCategory()
public := true
if state == 1 {
public = false
}
client := models.NewElasticSearchClient()
if errSet := client.SetBookPublic(bookResult.BookId, public); errSet != nil && client.On {
beego.Error(errSet.Error())
}
}()
this.JsonResult(0, "ok")
}
// Transfer 转让书籍.
func (this *BookController) Transfer() {
account := this.GetString("account")
if account == "" {
this.JsonResult(6004, "接受者账号不能为空")
}
member, err := models.NewMember().FindByAccount(account)
if err != nil {
logs.Error("FindByAccount => ", err)
this.JsonResult(6005, "接受用户不存在")
}
if member.Status != 0 {
this.JsonResult(6006, "接受用户已被禁用")
}
if member.MemberId == this.Member.MemberId {
this.JsonResult(6007, "不能转让给自己")
}
bookResult, err := this.IsPermission()
if err != nil {
this.JsonResult(6001, err.Error())
}
err = models.NewRelationship().Transfer(bookResult.BookId, this.Member.MemberId, member.MemberId)
if err != nil {
logs.Error("Transfer => ", err)
this.JsonResult(6008, err.Error())
}
this.JsonResult(0, "ok")
}
//上传书籍封面.
func (this *BookController) UploadCover() {
bookResult, err := this.IsPermission()
if err != nil {
this.JsonResult(6001, err.Error())
}
book, err := models.NewBook().Find(bookResult.BookId)
if err != nil {
logs.Error("SaveBook => ", err)
this.JsonResult(6002, err.Error())
}
file, moreFile, err := this.GetFile("image-file")
if err != nil {
logs.Error("", err.Error())
this.JsonResult(500, "读取文件异常")
}
defer file.Close()
ext := filepath.Ext(moreFile.Filename)
if !strings.EqualFold(ext, ".png") && !strings.EqualFold(ext, ".jpg") && !strings.EqualFold(ext, ".gif") && !strings.EqualFold(ext, ".jpeg") {
this.JsonResult(500, "不支持的图片格式")
}
//
x1, _ := strconv.ParseFloat(this.GetString("x"), 10)
y1, _ := strconv.ParseFloat(this.GetString("y"), 10)
w1, _ := strconv.ParseFloat(this.GetString("width"), 10)
h1, _ := strconv.ParseFloat(this.GetString("height"), 10)
x := int(x1)
y := int(y1)
width := int(w1)
height := int(h1)
fileName := strconv.FormatInt(time.Now().UnixNano(), 16)
filePath := filepath.Join("uploads", time.Now().Format("200601"), fileName+ext)
path := filepath.Dir(filePath)
os.MkdirAll(path, os.ModePerm)
err = this.SaveToFile("image-file", filePath)
if err != nil {
logs.Error("", err)
this.JsonResult(500, "图片保存失败")
}
if utils.StoreType != utils.StoreLocal {
defer func(filePath string) {
os.Remove(filePath)
}(filePath)
}
//剪切图片
subImg, err := graphics.ImageCopyFromFile(filePath, x, y, width, height)
if err != nil {
logs.Error("graphics.ImageCopyFromFile => ", err)
this.JsonResult(500, "图片剪切")
}
filePath = filepath.Join("uploads", time.Now().Format("200601"), fileName+ext)
//生成缩略图并保存到磁盘
err = graphics.ImageResizeSaveFile(subImg, 175, 230, filePath)
if err != nil {
logs.Error("ImageResizeSaveFile => ", err.Error())
this.JsonResult(500, "保存图片失败")
}
url := "/" + strings.Replace(filePath, "\\", "/", -1)
if strings.HasPrefix(url, "//") {
url = string(url[1:])
}
oldCover := book.Cover
osspath := fmt.Sprintf("projects/%v/%v", book.Identify, strings.TrimLeft(url, "./"))
book.Cover = "/" + osspath
if utils.StoreType == utils.StoreLocal {
book.Cover = url
}
if err := book.Update(); err != nil {
this.JsonResult(6001, "保存图片失败")
}
//如果原封面不是默认封面则删除
if oldCover != conf.GetDefaultCover() {
os.Remove("." + oldCover)
switch utils.StoreType {
case utils.StoreOss:
store.ModelStoreOss.DelFromOss(oldCover) //从OSS执行一次删除
case utils.StoreLocal:
store.ModelStoreLocal.DelFiles(oldCover) //从本地执行一次删除
}
}
switch utils.StoreType {
case utils.StoreOss: //oss
if err := store.ModelStoreOss.MoveToOss("."+url, osspath, true, false); err != nil {
beego.Error(err.Error())
} else {
url = strings.TrimRight(beego.AppConfig.String("oss::Domain"), "/ ") + "/" + osspath + "/cover"
}
case utils.StoreLocal:
save := book.Cover
if err := store.ModelStoreLocal.MoveToStore("."+url, save); err != nil {
beego.Error(err.Error())
} else {
url = book.Cover
}
}
this.JsonResult(0, "ok", url)
}
// Users 用户列表.
func (this *BookController) Users() {
pageIndex, _ := this.GetInt("page", 1)
key := this.Ctx.Input.Param(":key")
if key == "" {
this.Abort("404")
}
book, err := models.NewBookResult().FindByIdentify(key, this.Member.MemberId)
if err != nil {
if err == models.ErrPermissionDenied {
this.Abort("404")
}
this.Abort("404")
}
this.Data["Model"] = *book
pageSize := 10
members, totalCount, _ := models.NewMemberRelationshipResult().FindForUsersByBookId(book.BookId, pageIndex, pageSize)
for idx, member := range members {
member.Avatar = utils.ShowImg(member.Avatar, "avatar")
members[idx] = member
}
if totalCount > 0 {
html := utils.GetPagerHtml(this.Ctx.Request.RequestURI, pageIndex, pageSize, totalCount)
this.Data["PageHtml"] = html
} else {
this.Data["PageHtml"] = ""
}
b, err := json.Marshal(members)
if err != nil {
this.Data["Result"] = template.JS("[]")
} else {
this.Data["Result"] = template.JS(string(b))
}
this.TplName = "book/users.html"
}
// Create 创建书籍.
func (this *BookController) Create() {
if opt, err := models.NewOption().FindByKey("ALL_CAN_WRITE_BOOK"); err == nil {
if opt.OptionValue == "false" && this.Member.Role == conf.MemberGeneralRole { // 读者无权限创建书籍
this.JsonResult(1, "普通读者无法创建书籍,如需创建书籍,请向管理员申请成为作者")
}
}
bookName := strings.TrimSpace(this.GetString("book_name", ""))
identify := strings.TrimSpace(this.GetString("identify", ""))
description := strings.TrimSpace(this.GetString("description", ""))
author := strings.TrimSpace(this.GetString("author", ""))
authorURL := strings.TrimSpace(this.GetString("author_url", ""))
privatelyOwned, _ := strconv.Atoi(this.GetString("privately_owned"))
commentStatus := this.GetString("comment_status")
if bookName == "" {
this.JsonResult(6001, "书籍名称不能为空")
}
if identify == "" {
this.JsonResult(6002, "书籍标识不能为空")
}
ok, err1 := regexp.MatchString(`^[a-zA-Z0-9_\-\.]*$`, identify)
if !ok || err1 != nil {
this.JsonResult(6003, "书籍标识只能包含字母、数字,以及“-”、“.”和“_”符号,且不能是纯数字")
}
if num, _ := strconv.Atoi(identify); strconv.Itoa(num) == identify {
this.JsonResult(6003, "书籍标识不能是纯数字")
}
if strings.Count(identify, "") > 50 {
this.JsonResult(6004, "书籍标识不能超过50字")
}
if strings.Count(description, "") > 500 {
this.JsonResult(6004, "书籍描述不能大于500字")
}
if privatelyOwned != 0 && privatelyOwned != 1 {
privatelyOwned = 1
}
if commentStatus != "open" && commentStatus != "closed" && commentStatus != "group_only" && commentStatus != "registered_only" {
commentStatus = "closed"
}
book := models.NewBook()
if books, _ := book.FindByField("identify", identify); len(books) > 0 {
this.JsonResult(6006, "书籍标识已存在")
}
book.Label = ""
book.BookName = bookName
book.Author = author
book.AuthorURL = authorURL
book.Description = description
book.CommentCount = 0
book.PrivatelyOwned = privatelyOwned
book.CommentStatus = commentStatus
book.Identify = identify
book.DocCount = 0
book.MemberId = this.Member.MemberId
book.CommentCount = 0
book.Version = time.Now().Unix()
book.Cover = conf.GetDefaultCover()
book.Editor = "markdown"
book.Theme = "default"
book.Score = 40 //默认评分,40即表示4星
//设置默认时间,因为beego的orm好像无法设置datetime的默认值
defaultTime, _ := time.Parse("2006-01-02 15:04:05", "2006-01-02 15:04:05")
book.LastClickGenerate = defaultTime
book.GenerateTime, _ = time.Parse("2006-01-02 15:04:05", "2000-01-02 15:04:05") //默认生成文档的时间
book.ReleaseTime = defaultTime
if err := book.Insert(); err != nil {
logs.Error("Insert => ", err)
this.JsonResult(6005, "保存书籍失败")
}
bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, this.Member.MemberId)
if err != nil {
beego.Error(err)
}
this.JsonResult(0, "ok", bookResult)
}
// CreateToken 创建访问来令牌.
func (this *BookController) CreateToken() {
if this.forbidGeneralRole() {
this.JsonResult(6001, "您的角色非作者和管理员,无法创建访问令牌")
}
action := this.GetString("action")
bookResult, err := this.IsPermission()
if err != nil {
if err == models.ErrPermissionDenied {
this.JsonResult(403, "权限不足")
}
if err == orm.ErrNoRows {
this.JsonResult(404, "书籍不存在")
}
logs.Error("生成阅读令牌失败 =>", err)
this.JsonResult(6002, err.Error())
}
book := models.NewBook()
if _, err := book.Find(bookResult.BookId); err != nil {
this.JsonResult(6001, "书籍不存在")
}
if action == "create" {
if bookResult.PrivatelyOwned == 0 {
this.JsonResult(6001, "公开书籍不能创建阅读令牌")
}
book.PrivateToken = string(utils.Krand(conf.GetTokenSize(), utils.KC_RAND_KIND_ALL))
if err := book.Update(); err != nil {
logs.Error("生成阅读令牌失败 => ", err)
this.JsonResult(6003, "生成阅读令牌失败")
}
//book.PrivateToken = this.BaseUrl() + beego.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken)
tipsFmt := "访问链接:%v 访问密码:%v"
privateToken := fmt.Sprintf(tipsFmt, this.BaseUrl()+beego.URLFor("DocumentController.Index", ":key", book.Identify), book.PrivateToken)
this.JsonResult(0, "ok", privateToken)
}
book.PrivateToken = ""
if err := book.Update(); err != nil {
logs.Error("CreateToken => ", err)
this.JsonResult(6004, "删除令牌失败")
}
this.JsonResult(0, "ok", "")
}
// Delete 删除书籍.
func (this *BookController) Delete() {
bookResult, err := this.IsPermission()
if err != nil {
this.JsonResult(6001, err.Error())
}
if bookResult.RoleId != conf.BookFounder {
this.JsonResult(6002, "只有创始人才能删除书籍")
}
//用户密码
pwd := this.GetString("password")
if m, err := models.NewMember().Login(this.Member.Account, pwd); err != nil || m.MemberId == 0 {
this.JsonResult(1, "书籍删除失败,您的登录密码不正确")
}
err = models.NewBook().ThoroughDeleteBook(bookResult.BookId)
if err == orm.ErrNoRows {
this.JsonResult(6002, "书籍不存在")
}
if err != nil {
logs.Error("删除书籍 => ", err)
this.JsonResult(6003, "删除失败")
}
go func() {
client := models.NewElasticSearchClient()
if errDel := client.DeleteIndex(bookResult.BookId, true); errDel != nil && client.On {
beego.Error(errDel.Error())
}
}()
go models.CountCategory()
this.JsonResult(0, "ok")
}
//发布书籍.
func (this *BookController) Release() {
identify := this.GetString("identify")
bookId := 0
if this.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
beego.Error(err)
}
bookId = book.BookId
} else {
book, err := models.NewBookResult().FindByIdentify(identify, this.Member.MemberId)
if err != nil {
if err == models.ErrPermissionDenied {
this.JsonResult(6001, "权限不足")
}
if err == orm.ErrNoRows {
this.JsonResult(6002, "书籍不存在")
}
beego.Error(err)
this.JsonResult(6003, "未知错误")
}
if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor {
this.JsonResult(6003, "权限不足")
}
bookId = book.BookId
}
if exist := utils.BooksRelease.Exist(bookId); exist {
this.JsonResult(1, "上次内容发布正在执行中,请稍后再操作")
}
go func(identify string) {
models.NewDocument().ReleaseContent(bookId, this.BaseUrl())
}(identify)
this.JsonResult(0, "发布任务已推送到任务队列,稍后将在后台执行。")
}
//生成下载文档
//加锁,防止用户不停地点击生成下载文档造成服务器资源开销.
func (this *BookController) Generate() {
identify := this.GetString(":key")
if !models.NewBook().HasProjectAccess(identify, this.Member.MemberId, conf.BookAdmin) {
this.JsonResult(1, "您没有操作权限,只有书籍创始人和书籍管理员才有权限")
}
book, err := models.NewBook().FindByIdentify(identify)
if err != nil {
beego.Error(err)
this.JsonResult(1, "书籍不存在")
}
//书籍正在生成离线文档
if isGenerating := utils.BooksGenerate.Exist(book.BookId); isGenerating {
this.JsonResult(1, "上一次下载文档生成任务正在后台执行,请您稍后再执行新的下载文档生成操作")
}
baseUrl := "http://localhost:" + beego.AppConfig.String("httpport")
go new(models.Document).GenerateBook(book, baseUrl)
this.JsonResult(0, "下载文档生成任务已交由后台执行,请您耐心等待。")
}
//文档排序.
func (this *BookController) SaveSort() {
identify := this.Ctx.Input.Param(":key")
if identify == "" {
this.Abort("404")
}
bookId := 0
if this.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
beego.Error(err)
}
bookId = book.BookId
} 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, "书籍不存在或权限不足")
}
bookId = bookResult.BookId
}
content := this.Ctx.Input.RequestBody
var docs []struct {
Id int `json:"id"`
Sort int `json:"sort"`
Parent int `json:"parent"`
}
err := json.Unmarshal(content, &docs)
if err != nil {
beego.Error(err)
this.JsonResult(6003, "数据错误")
}
qs := orm.NewOrm().QueryTable("md_documents").Filter("book_id", bookId)
now := time.Now()
for _, item := range docs {
qs.Filter("document_id", item.Id).Update(orm.Params{
"parent_id": item.Parent,
"order_sort": item.Sort,
"modify_time": now,
})
}
this.JsonResult(0, "ok")
}
// 判断是否具有管理员或管理员以上权限
func (this *BookController) IsPermission() (*models.BookResult, error) {
identify := this.GetString("identify")
book, err := models.NewBookResult().FindByIdentify(identify, this.Member.MemberId)
if err != nil {
if err == models.ErrPermissionDenied {
return book, errors.New("权限不足")
}
if err == orm.ErrNoRows {
return book, errors.New("书籍不存在")
}
return book, err
}
if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
return book, errors.New("权限不足")
}
return book, nil
}
//从github等拉取下载markdown书籍
func (this *BookController) DownloadProject() {
//处理步骤
//1、接受上传上来的zip文件,并存放到store/temp目录下
//2、解压zip到当前目录,然后移除非图片文件
//3、将文件夹移动到uploads目录下
if _, err := this.IsPermission(); err != nil {
this.JsonResult(1, err.Error())
}
//普通用户没有权限
if this.Member.Role > 1 {
this.JsonResult(1, "您没有操作权限")
}
identify := this.GetString("identify")
book, _ := models.NewBookResult().FindByIdentify(identify, this.Member.MemberId)
if book.BookId == 0 {
this.JsonResult(1, "导入失败,只有书籍创建人才有权限导入书籍")
}
//GitHub书籍链接
link := this.GetString("link")
if strings.ToLower(filepath.Ext(link)) != ".zip" {
this.JsonResult(1, "只支持拉取zip压缩的markdown书籍")
}
go func() {
if file, err := util.CrawlFile(link, "store", 60); err != nil {
beego.Error(err)
} else {
this.unzipToData(book.BookId, identify, file, filepath.Base(file))
}
}()
this.JsonResult(0, "提交成功。下载任务已交由后台执行")
}
// 从Git仓库拉取书籍
func (this *BookController) GitPull() {
//处理步骤
//1、接受上传上来的zip文件,并存放到store/temp目录下
//2、解压zip到当前目录,然后移除非图片文件
//3、将文件夹移动到uploads目录下
identify := this.GetString("identify")
if !models.NewBook().HasProjectAccess(identify, this.Member.MemberId, conf.BookEditor) {
this.JsonResult(1, "无操作权限")
}
book, _ := models.NewBookResult().FindByIdentify(identify, this.Member.MemberId)
if book.BookId == 0 {
this.JsonResult(1, "导入失败,只有书籍创建人才有权限导入书籍")
}
//GitHub书籍链接
link := this.GetString("link")
go func() {
folder := "store/" + identify
err := utils.GitClone(link, folder)
if err != nil {
this.JsonResult(1, err.Error())
}
this.loadByFolder(book.BookId, identify, folder)
}()
this.JsonResult(0, "提交成功,请耐心等待。")
}
//上传书籍
func (this *BookController) UploadProject() {
//处理步骤
//1、接受上传上来的zip文件,并存放到store/temp目录下
//2、解压zip到当前目录,然后移除非图片文件
//3、将文件夹移动到uploads目录下
identify := this.GetString("identify")
if !models.NewBook().HasProjectAccess(identify, this.Member.MemberId, conf.BookEditor) {
this.JsonResult(1, "无操作权限")
}
book, _ := models.NewBookResult().FindByIdentify(identify, this.Member.MemberId)
if book.BookId == 0 {
this.JsonResult(1, "书籍不存在")
}
f, h, err := this.GetFile("zipfile")
if err != nil {
this.JsonResult(1, err.Error())
}
defer f.Close()
if strings.ToLower(filepath.Ext(h.Filename)) != ".zip" && strings.ToLower(filepath.Ext(h.Filename)) != ".epub" {
this.JsonResult(1, "请上传指定格式文件")
}
tmpFile := "store/" + identify + ".zip" //保存的文件名
if err := this.SaveToFile("zipfile", tmpFile); err == nil {
go this.unzipToData(book.BookId, identify, tmpFile, h.Filename)
} else {
beego.Error(err.Error())
}
this.JsonResult(0, "上传成功")
}
//将zip压缩文件解压并录入数据库
//@param book_id 书籍id(其实有想不标识了可以不要这个的,但是这里的书籍标识只做目录)
//@param identify 书籍标识
//@param zipfile 压缩文件
//@param originFilename 上传文件的原始文件名
func (this *BookController) unzipToData(bookId int, identify, zipFile, originFilename string) {
//说明:
//OSS中的图片存储规则为"projects/$identify/书籍中图片原路径"
//本地存储规则为"uploads/projects/$identify/书籍中图片原路径"
projectRoot := "" //书籍根目录
//解压目录
unzipPath := "store/" + identify
//如果存在相同目录,则率先移除
if err := os.RemoveAll(unzipPath); err != nil {
beego.Error(err.Error())
}
os.MkdirAll(unzipPath, os.ModePerm)
imgMap := map[string]bool{".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".bmp": true, ".svg": true, ".webp": true}
defer func() {
os.Remove(zipFile) //最后删除上传的临时文件
os.RemoveAll(unzipPath) //删除解压后的文件夹
}()
//注意:这里的prefix必须是判断是否是GitHub之前的prefix
if err := ziptil.Unzip(zipFile, unzipPath); err != nil {
beego.Error("解压失败", zipFile, err.Error())
return
}
//读取文件,把图片文档录入oss
if files, err := filetil.ScanFiles(unzipPath); err == nil {
projectRoot = this.getProjectRoot(files)
this.replaceToAbs(projectRoot, identify)
ModelStore := new(models.DocumentStore)
//文档对应的标识
for _, file := range files {
if !file.IsDir {
ext := strings.ToLower(filepath.Ext(file.Path))
if ok, _ := imgMap[ext]; ok { //图片,录入oss
switch utils.StoreType {
case utils.StoreOss:
if err := store.ModelStoreOss.MoveToOss(file.Path, "projects/"+identify+strings.TrimPrefix(file.Path, projectRoot), false, false); err != nil {
beego.Error(err)
}
case utils.StoreLocal:
if err := store.ModelStoreLocal.MoveToStore(file.Path, "uploads/projects/"+identify+strings.TrimPrefix(file.Path, projectRoot)); err != nil {
beego.Error(err)
}
}
} else if ext == ".md" || ext == ".markdown" || ext == ".html" { //markdown文档,提取文档内容,录入数据库
doc := new(models.Document)
var mdcont string
var htmlStr string
if b, err := ioutil.ReadFile(file.Path); err == nil {
if ext == ".md" || ext == ".markdown" {
mdcont = strings.TrimSpace(string(b))
htmlStr = mdtil.Md2html(mdcont)