DocumentController.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. package controllers
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "html/template"
  7. "image/png"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/beego/beego/v2/client/orm"
  17. "github.com/beego/beego/v2/core/logs"
  18. "github.com/beego/beego/v2/server/web"
  19. "github.com/beego/i18n"
  20. "github.com/boombuler/barcode"
  21. "github.com/boombuler/barcode/qr"
  22. "github.com/mindoc-org/mindoc/conf"
  23. "github.com/mindoc-org/mindoc/models"
  24. "github.com/mindoc-org/mindoc/utils"
  25. "github.com/mindoc-org/mindoc/utils/cryptil"
  26. "github.com/mindoc-org/mindoc/utils/filetil"
  27. "github.com/mindoc-org/mindoc/utils/gopool"
  28. "github.com/mindoc-org/mindoc/utils/pagination"
  29. "github.com/russross/blackfriday/v2"
  30. )
  31. // DocumentController struct
  32. type DocumentController struct {
  33. BaseController
  34. }
  35. // 文档首页
  36. func (c *DocumentController) Index() {
  37. c.Prepare()
  38. identify := c.Ctx.Input.Param(":key")
  39. token := c.GetString("token")
  40. if identify == "" {
  41. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  42. }
  43. // 如果没有开启匿名访问则跳转到登录
  44. if !c.EnableAnonymous && !c.isUserLoggedIn() {
  45. promptUserToLogIn(c)
  46. return
  47. }
  48. bookResult := c.isReadable(identify, token)
  49. c.TplName = "document/" + bookResult.Theme + "_read.tpl"
  50. selected := 0
  51. if bookResult.IsUseFirstDocument {
  52. doc, err := bookResult.FindFirstDocumentByBookId(bookResult.BookId)
  53. if err == nil {
  54. selected = doc.DocumentId
  55. c.Data["Title"] = doc.DocumentName
  56. c.Data["Content"] = template.HTML(doc.Release)
  57. c.Data["Description"] = utils.AutoSummary(doc.Release, 120)
  58. }
  59. } else {
  60. c.Data["Title"] = i18n.Tr(c.Lang, "blog.summary")
  61. c.Data["Content"] = template.HTML(blackfriday.Run([]byte(bookResult.Description)))
  62. }
  63. tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, selected)
  64. if err != nil {
  65. if err == orm.ErrNoRows {
  66. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.no_doc_in_cur_proj"))
  67. } else {
  68. logs.Error("生成项目文档树时出错 -> ", err)
  69. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.build_doc_tree_error"))
  70. }
  71. }
  72. c.Data["Model"] = bookResult
  73. c.Data["Result"] = template.HTML(tree)
  74. }
  75. // 阅读文档
  76. func (c *DocumentController) Read() {
  77. c.Prepare()
  78. identify := c.Ctx.Input.Param(":key")
  79. token := c.GetString("token")
  80. id := c.GetString(":id")
  81. c.Data["DocumentId"] = id
  82. if identify == "" || id == "" {
  83. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  84. }
  85. // 如果没有开启匿名访问则跳转到登录
  86. if !c.EnableAnonymous && !c.isUserLoggedIn() {
  87. promptUserToLogIn(c)
  88. return
  89. }
  90. bookResult := c.isReadable(identify, token)
  91. c.TplName = fmt.Sprintf("document/%s_read.tpl", bookResult.Theme)
  92. doc := models.NewDocument()
  93. if docId, err := strconv.Atoi(id); err == nil {
  94. doc, err = doc.FromCacheById(docId)
  95. if err != nil || doc == nil {
  96. logs.Error("从缓存中读取文档时失败 ->", err)
  97. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.doc_not_exist"))
  98. return
  99. }
  100. } else {
  101. doc, err = doc.FromCacheByIdentify(id, bookResult.BookId)
  102. if err != nil || doc == nil {
  103. if err == orm.ErrNoRows {
  104. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.doc_not_exist"))
  105. } else {
  106. logs.Error("从数据库查询文档时出错 ->", err)
  107. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.unknown_exception"))
  108. }
  109. return
  110. }
  111. }
  112. if doc.BookId != bookResult.BookId {
  113. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.doc_not_exist"))
  114. }
  115. doc.Lang = c.Lang
  116. doc.Processor()
  117. attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
  118. if err == nil {
  119. doc.AttachList = attach
  120. }
  121. doc.IncrViewCount(doc.DocumentId)
  122. c.Data["ViewCount"] = doc.ViewCount + 1
  123. if c.IsAjax() {
  124. var data struct {
  125. DocTitle string `json:"doc_title"`
  126. Body string `json:"body"`
  127. Title string `json:"title"`
  128. Version int64 `json:"version"`
  129. ViewCount int `json:"view_count"`
  130. }
  131. data.DocTitle = doc.DocumentName
  132. data.Body = doc.Release
  133. data.Title = doc.DocumentName + " - Powered by MinDoc"
  134. data.Version = doc.Version
  135. data.ViewCount = doc.ViewCount + 1
  136. c.JsonResult(0, "ok", data)
  137. }
  138. tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, doc.DocumentId)
  139. if err != nil && err != orm.ErrNoRows {
  140. logs.Error("生成项目文档树时出错 ->", err)
  141. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.build_doc_tree_error"))
  142. }
  143. c.Data["Description"] = utils.AutoSummary(doc.Release, 120)
  144. c.Data["Model"] = bookResult
  145. c.Data["Result"] = template.HTML(tree)
  146. c.Data["Title"] = doc.DocumentName
  147. c.Data["Content"] = template.HTML(doc.Release)
  148. }
  149. // 编辑文档
  150. func (c *DocumentController) Edit() {
  151. c.Prepare()
  152. identify := c.Ctx.Input.Param(":key")
  153. if identify == "" {
  154. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.project_id_error"))
  155. }
  156. bookResult := models.NewBookResult()
  157. var err error
  158. // 如果是管理者,则不判断权限
  159. if c.Member.IsAdministrator() {
  160. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  161. if err != nil {
  162. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  163. }
  164. bookResult = models.NewBookResult().ToBookResult(*book)
  165. } else {
  166. bookResult, err = models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  167. if err != nil {
  168. if err == orm.ErrNoRows || err == models.ErrPermissionDenied {
  169. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  170. } else {
  171. logs.Error("查询项目时出错 -> ", err)
  172. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.system_error"))
  173. }
  174. return
  175. }
  176. if bookResult.RoleId == conf.BookObserver {
  177. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  178. }
  179. }
  180. // 根据不同编辑器类型加载编辑器
  181. if bookResult.Editor == "markdown" {
  182. c.TplName = "document/markdown_edit_template.tpl"
  183. } else if bookResult.Editor == "html" {
  184. c.TplName = "document/new_html_edit_template.tpl"
  185. } else {
  186. c.TplName = "document/" + bookResult.Editor + "_edit_template.tpl"
  187. }
  188. c.Data["Model"] = bookResult
  189. r, _ := json.Marshal(bookResult)
  190. c.Data["ModelResult"] = template.JS(string(r))
  191. c.Data["Result"] = template.JS("[]")
  192. trees, err := models.NewDocument().FindDocumentTree(bookResult.BookId)
  193. if err != nil {
  194. logs.Error("FindDocumentTree => ", err)
  195. } else {
  196. if len(trees) > 0 {
  197. if jtree, err := json.Marshal(trees); err == nil {
  198. c.Data["Result"] = template.JS(string(jtree))
  199. }
  200. } else {
  201. c.Data["Result"] = template.JS("[]")
  202. }
  203. }
  204. c.Data["BaiDuMapKey"] = web.AppConfig.DefaultString("baidumapkey", "")
  205. if conf.GetUploadFileSize() > 0 {
  206. c.Data["UploadFileSize"] = conf.GetUploadFileSize()
  207. } else {
  208. c.Data["UploadFileSize"] = "undefined"
  209. }
  210. }
  211. // 创建一个文档
  212. func (c *DocumentController) Create() {
  213. identify := c.GetString("identify")
  214. docIdentify := c.GetString("doc_identify")
  215. docName := c.GetString("doc_name")
  216. parentId, _ := c.GetInt("parent_id", 0)
  217. docId, _ := c.GetInt("doc_id", 0)
  218. isOpen, _ := c.GetInt("is_open", 0)
  219. if identify == "" {
  220. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  221. }
  222. if docName == "" {
  223. c.JsonResult(6004, i18n.Tr(c.Lang, "message.doc_name_empty"))
  224. }
  225. bookId := 0
  226. // 如果是超级管理员则不判断权限
  227. if c.Member.IsAdministrator() {
  228. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  229. if err != nil {
  230. logs.Error(err)
  231. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_existed_or_no_permit"))
  232. }
  233. bookId = book.BookId
  234. } else {
  235. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  236. if err != nil || bookResult.RoleId == conf.BookObserver {
  237. logs.Error("FindByIdentify => ", err)
  238. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_existed_or_no_permit"))
  239. }
  240. bookId = bookResult.BookId
  241. }
  242. if docIdentify != "" {
  243. if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, docIdentify); !ok || err != nil {
  244. c.JsonResult(6003, i18n.Tr(c.Lang, "message.project_id_tips"))
  245. }
  246. d, _ := models.NewDocument().FindByIdentityFirst(docIdentify, bookId)
  247. if d.DocumentId > 0 && d.DocumentId != docId {
  248. c.JsonResult(6006, i18n.Tr(c.Lang, "message.project_id_existed"))
  249. }
  250. }
  251. if parentId > 0 {
  252. doc, err := models.NewDocument().Find(parentId)
  253. if err != nil || doc.BookId != bookId {
  254. c.JsonResult(6003, i18n.Tr(c.Lang, "message.parent_id_not_existed"))
  255. }
  256. }
  257. document, _ := models.NewDocument().Find(docId)
  258. document.MemberId = c.Member.MemberId
  259. document.BookId = bookId
  260. document.Identify = docIdentify
  261. document.Version = time.Now().Unix()
  262. document.DocumentName = docName
  263. document.ParentId = parentId
  264. if isOpen == 1 {
  265. document.IsOpen = 1
  266. } else if isOpen == 2 {
  267. document.IsOpen = 2
  268. } else {
  269. document.IsOpen = 0
  270. }
  271. if err := document.InsertOrUpdate(); err != nil {
  272. logs.Error("添加或更新文档时出错 -> ", err)
  273. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  274. } else {
  275. c.JsonResult(0, "ok", document)
  276. }
  277. }
  278. // 上传附件或图片
  279. func (c *DocumentController) Upload() {
  280. identify := c.GetString("identify")
  281. docId, _ := c.GetInt("doc_id")
  282. isAttach := true
  283. if identify == "" {
  284. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  285. }
  286. name := "editormd-file-file"
  287. file, moreFile, err := c.GetFile(name)
  288. if err == http.ErrMissingFile || moreFile == nil {
  289. name = "editormd-image-file"
  290. file, moreFile, err = c.GetFile(name)
  291. if err == http.ErrMissingFile || moreFile == nil {
  292. c.JsonResult(6003, i18n.Tr(c.Lang, "message.upload_file_empty"))
  293. return
  294. }
  295. }
  296. if err != nil {
  297. c.JsonResult(6002, err.Error())
  298. }
  299. defer file.Close()
  300. type Size interface {
  301. Size() int64
  302. }
  303. if conf.GetUploadFileSize() > 0 && moreFile.Size > conf.GetUploadFileSize() {
  304. c.JsonResult(6009, i18n.Tr(c.Lang, "message.upload_file_size_limit"))
  305. }
  306. ext := filepath.Ext(moreFile.Filename)
  307. //文件必须带有后缀名
  308. if ext == "" {
  309. c.JsonResult(6003, i18n.Tr(c.Lang, "message.upload_file_type_error"))
  310. }
  311. //如果文件类型设置为 * 标识不限制文件类型
  312. if conf.IsAllowUploadFileExt(ext) == false {
  313. c.JsonResult(6004, i18n.Tr(c.Lang, "message.upload_file_type_error"))
  314. }
  315. bookId := 0
  316. // 如果是超级管理员,则不判断权限
  317. if c.Member.IsAdministrator() {
  318. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  319. if err != nil {
  320. c.JsonResult(6006, i18n.Tr(c.Lang, "message.doc_not_exist_or_no_permit"))
  321. }
  322. bookId = book.BookId
  323. } else {
  324. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  325. if err != nil {
  326. logs.Error("DocumentController.Edit => ", err)
  327. if err == orm.ErrNoRows {
  328. c.JsonResult(6006, i18n.Tr(c.Lang, "message.no_permission"))
  329. }
  330. c.JsonResult(6001, err.Error())
  331. }
  332. // 如果没有编辑权限
  333. if book.RoleId != conf.BookEditor && book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  334. c.JsonResult(6006, i18n.Tr(c.Lang, "message.no_permission"))
  335. }
  336. bookId = book.BookId
  337. }
  338. if docId > 0 {
  339. doc, err := models.NewDocument().Find(docId)
  340. if err != nil {
  341. c.JsonResult(6007, i18n.Tr(c.Lang, "message.doc_not_exist"))
  342. }
  343. if doc.BookId != bookId {
  344. c.JsonResult(6008, i18n.Tr(c.Lang, "message.doc_not_belong_project"))
  345. }
  346. }
  347. fileName := "m_" + cryptil.UniqueId() + "_r"
  348. filePath := filepath.Join(conf.WorkingDirectory, "uploads", identify)
  349. //将图片和文件分开存放
  350. if filetil.IsImageExt(moreFile.Filename) {
  351. filePath = filepath.Join(filePath, "images", fileName+ext)
  352. } else {
  353. filePath = filepath.Join(filePath, "files", fileName+ext)
  354. }
  355. path := filepath.Dir(filePath)
  356. _ = os.MkdirAll(path, os.ModePerm)
  357. err = c.SaveToFile(name, filePath)
  358. if err != nil {
  359. logs.Error("保存文件失败 -> ", err)
  360. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  361. }
  362. attachment := models.NewAttachment()
  363. attachment.BookId = bookId
  364. attachment.FileName = moreFile.Filename
  365. attachment.CreateAt = c.Member.MemberId
  366. attachment.FileExt = ext
  367. attachment.FilePath = strings.TrimPrefix(filePath, conf.WorkingDirectory)
  368. attachment.DocumentId = docId
  369. if fileInfo, err := os.Stat(filePath); err == nil {
  370. attachment.FileSize = float64(fileInfo.Size())
  371. }
  372. if docId > 0 {
  373. attachment.DocumentId = docId
  374. }
  375. if filetil.IsImageExt(moreFile.Filename) {
  376. attachment.HttpPath = "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
  377. if strings.HasPrefix(attachment.HttpPath, "//") {
  378. attachment.HttpPath = conf.URLForWithCdnImage(string(attachment.HttpPath[1:]))
  379. }
  380. isAttach = false
  381. }
  382. err = attachment.Insert()
  383. if err != nil {
  384. os.Remove(filePath)
  385. logs.Error("文件保存失败 ->", err)
  386. c.JsonResult(6006, i18n.Tr(c.Lang, "message.failed"))
  387. }
  388. if attachment.HttpPath == "" {
  389. attachment.HttpPath = conf.URLForNotHost("DocumentController.DownloadAttachment", ":key", identify, ":attach_id", attachment.AttachmentId)
  390. if err := attachment.Update(); err != nil {
  391. logs.Error("保存文件失败 ->", err)
  392. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  393. }
  394. }
  395. result := map[string]interface{}{
  396. "errcode": 0,
  397. "success": 1,
  398. "message": "ok",
  399. "url": attachment.HttpPath,
  400. "alt": attachment.FileName,
  401. "is_attach": isAttach,
  402. "attach": attachment,
  403. }
  404. c.Ctx.Output.JSON(result, true, false)
  405. c.StopRun()
  406. }
  407. // 下载附件
  408. func (c *DocumentController) DownloadAttachment() {
  409. c.Prepare()
  410. identify := c.Ctx.Input.Param(":key")
  411. attachId, _ := strconv.Atoi(c.Ctx.Input.Param(":attach_id"))
  412. token := c.GetString("token")
  413. memberId := 0
  414. if c.Member != nil {
  415. memberId = c.Member.MemberId
  416. }
  417. bookId := 0
  418. // 判断用户是否参与了项目
  419. bookResult, err := models.NewBookResult().FindByIdentify(identify, memberId)
  420. if err != nil {
  421. // 判断项目公开状态
  422. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  423. if err != nil {
  424. if err == orm.ErrNoRows {
  425. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  426. } else {
  427. logs.Error("查找项目时出错 ->", err)
  428. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.system_error"))
  429. }
  430. }
  431. // 如果不是超级管理员则判断权限
  432. if c.Member == nil || c.Member.Role != conf.MemberSuperRole {
  433. // 如果项目是私有的,并且 token 不正确
  434. if (book.PrivatelyOwned == 1 && token == "") || (book.PrivatelyOwned == 1 && book.PrivateToken != token) {
  435. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  436. }
  437. }
  438. bookId = book.BookId
  439. } else {
  440. bookId = bookResult.BookId
  441. }
  442. // 查找附件
  443. attachment, err := models.NewAttachment().Find(attachId)
  444. if err != nil {
  445. logs.Error("查找附件时出错 -> ", err)
  446. if err == orm.ErrNoRows {
  447. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  448. } else {
  449. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.system_error"))
  450. }
  451. }
  452. if attachment.BookId != bookId {
  453. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  454. }
  455. c.Ctx.Output.Download(filepath.Join(conf.WorkingDirectory, attachment.FilePath), attachment.FileName)
  456. c.StopRun()
  457. }
  458. // 删除附件
  459. func (c *DocumentController) RemoveAttachment() {
  460. c.Prepare()
  461. attachId, _ := c.GetInt("attach_id")
  462. if attachId <= 0 {
  463. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  464. }
  465. attach, err := models.NewAttachment().Find(attachId)
  466. if err != nil {
  467. logs.Error(err)
  468. c.JsonResult(6002, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  469. }
  470. document, err := models.NewDocument().Find(attach.DocumentId)
  471. if err != nil {
  472. logs.Error(err)
  473. c.JsonResult(6003, i18n.Tr(c.Lang, "message.doc_not_exist"))
  474. }
  475. if c.Member.Role != conf.MemberSuperRole {
  476. rel, err := models.NewRelationship().FindByBookIdAndMemberId(document.BookId, c.Member.MemberId)
  477. if err != nil {
  478. logs.Error(err)
  479. c.JsonResult(6004, i18n.Tr(c.Lang, "message.no_permission"))
  480. }
  481. if rel.RoleId == conf.BookObserver {
  482. c.JsonResult(6004, i18n.Tr(c.Lang, "message.no_permission"))
  483. }
  484. }
  485. err = attach.Delete()
  486. if err != nil {
  487. logs.Error(err)
  488. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  489. }
  490. os.Remove(filepath.Join(conf.WorkingDirectory, attach.FilePath))
  491. c.JsonResult(0, "ok", attach)
  492. }
  493. // 删除文档
  494. func (c *DocumentController) Delete() {
  495. c.Prepare()
  496. identify := c.GetString("identify")
  497. docId, err := c.GetInt("doc_id", 0)
  498. bookId := 0
  499. // 如果是超级管理员则忽略权限判断
  500. if c.Member.IsAdministrator() {
  501. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  502. if err != nil {
  503. logs.Error("FindByIdentify => ", err)
  504. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  505. }
  506. bookId = book.BookId
  507. } else {
  508. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  509. if err != nil || bookResult.RoleId == conf.BookObserver {
  510. logs.Error("FindByIdentify => ", err)
  511. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  512. }
  513. bookId = bookResult.BookId
  514. }
  515. if docId <= 0 {
  516. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  517. }
  518. doc, err := models.NewDocument().Find(docId)
  519. if err != nil {
  520. logs.Error("Delete => ", err)
  521. c.JsonResult(6003, i18n.Tr(c.Lang, "message.failed"))
  522. }
  523. // 如果文档所属项目错误
  524. if doc.BookId != bookId {
  525. c.JsonResult(6004, i18n.Tr(c.Lang, "message.param_error"))
  526. }
  527. // 递归删除项目下的文档以及子文档
  528. err = doc.RecursiveDocument(doc.DocumentId)
  529. if err != nil {
  530. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  531. }
  532. // 重置文档数量统计
  533. models.NewBook().ResetDocumentNumber(doc.BookId)
  534. c.JsonResult(0, "ok")
  535. }
  536. // 获取文档内容
  537. func (c *DocumentController) Content() {
  538. c.Prepare()
  539. identify := c.Ctx.Input.Param(":key")
  540. docId, err := c.GetInt("doc_id")
  541. if err != nil {
  542. docId, _ = strconv.Atoi(c.Ctx.Input.Param(":id"))
  543. }
  544. bookId := 0
  545. autoRelease := false
  546. // 如果是超级管理员,则忽略权限
  547. if c.Member.IsAdministrator() {
  548. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  549. if err != nil || book == nil {
  550. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  551. return
  552. }
  553. bookId = book.BookId
  554. autoRelease = book.AutoRelease == 1
  555. } else {
  556. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  557. if err != nil || bookResult.RoleId == conf.BookObserver {
  558. logs.Error("项目不存在或权限不足 -> ", err)
  559. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  560. }
  561. bookId = bookResult.BookId
  562. autoRelease = bookResult.AutoRelease
  563. }
  564. if docId <= 0 {
  565. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  566. }
  567. if c.Ctx.Input.IsPost() {
  568. markdown := strings.TrimSpace(c.GetString("markdown", ""))
  569. content := c.GetString("html")
  570. version, _ := c.GetInt64("version", 0)
  571. isCover := c.GetString("cover")
  572. doc, err := models.NewDocument().Find(docId)
  573. if err != nil || doc == nil {
  574. c.JsonResult(6003, i18n.Tr(c.Lang, "message.read_file_error"))
  575. return
  576. }
  577. if doc.BookId != bookId {
  578. c.JsonResult(6004, i18n.Tr(c.Lang, "message.dock_not_belong_project"))
  579. }
  580. if doc.Version != version && !strings.EqualFold(isCover, "yes") {
  581. logs.Info("%d|", version, doc.Version)
  582. c.JsonResult(6005, i18n.Tr(c.Lang, "message.confirm_override_doc"))
  583. }
  584. history := models.NewDocumentHistory()
  585. history.DocumentId = docId
  586. history.Content = doc.Content
  587. history.Markdown = doc.Markdown
  588. history.DocumentName = doc.DocumentName
  589. history.ModifyAt = c.Member.MemberId
  590. history.MemberId = doc.MemberId
  591. history.ParentId = doc.ParentId
  592. history.Version = time.Now().Unix()
  593. history.Action = "modify"
  594. history.ActionName = i18n.Tr(c.Lang, "doc.modify_doc")
  595. if markdown == "" && content != "" {
  596. doc.Markdown = content
  597. } else {
  598. doc.Markdown = markdown
  599. }
  600. doc.Version = time.Now().Unix()
  601. doc.Content = content
  602. doc.ModifyAt = c.Member.MemberId
  603. if err := doc.InsertOrUpdate(); err != nil {
  604. logs.Error("InsertOrUpdate => ", err)
  605. c.JsonResult(6006, i18n.Tr(c.Lang, "message.failed"))
  606. }
  607. // 如果启用了文档历史,则添加历史文档
  608. ///如果两次保存的MD5值不同则保存为历史,否则忽略
  609. go func(history *models.DocumentHistory) {
  610. if c.EnableDocumentHistory && cryptil.Md5Crypt(history.Markdown) != cryptil.Md5Crypt(doc.Markdown) {
  611. _, err = history.InsertOrUpdate()
  612. if err != nil {
  613. logs.Error("DocumentHistory InsertOrUpdate => ", err)
  614. }
  615. }
  616. }(history)
  617. //如果启用了自动发布
  618. if autoRelease {
  619. go func() {
  620. doc.Lang = c.Lang
  621. err := doc.ReleaseContent()
  622. if err == nil {
  623. logs.Informational(i18n.Tr(c.Lang, "message.doc_auto_published")+"-> document_id=%d;document_name=%s", doc.DocumentId, doc.DocumentName)
  624. }
  625. }()
  626. }
  627. c.JsonResult(0, "ok", doc)
  628. }
  629. doc, err := models.NewDocument().Find(docId)
  630. if err != nil {
  631. c.JsonResult(6003, i18n.Tr(c.Lang, "message.doc_not_exist"))
  632. return
  633. }
  634. attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
  635. if err == nil {
  636. doc.AttachList = attach
  637. }
  638. c.JsonResult(0, "ok", doc)
  639. }
  640. // Export 导出
  641. func (c *DocumentController) Export() {
  642. c.Prepare()
  643. identify := c.Ctx.Input.Param(":key")
  644. if identify == "" {
  645. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.param_error"))
  646. }
  647. output := c.GetString("output")
  648. token := c.GetString("token")
  649. // 如果没有开启匿名访问则跳转到登录
  650. if !c.EnableAnonymous && !c.isUserLoggedIn() {
  651. promptUserToLogIn(c)
  652. return
  653. }
  654. if !conf.GetEnableExport() {
  655. c.ShowErrorPage(500, i18n.Tr(c.Lang, "export_func_disable"))
  656. }
  657. bookResult := models.NewBookResult()
  658. if c.Member != nil && c.Member.IsAdministrator() {
  659. book, err := models.NewBook().FindByIdentify(identify)
  660. if err != nil {
  661. if err == orm.ErrNoRows {
  662. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  663. } else {
  664. logs.Error("查找项目时出错 ->", err)
  665. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.system_error"))
  666. }
  667. }
  668. bookResult = models.NewBookResult().ToBookResult(*book)
  669. } else {
  670. bookResult = c.isReadable(identify, token)
  671. }
  672. if !bookResult.IsDownload {
  673. c.ShowErrorPage(200, i18n.Tr(c.Lang, "message.cur_project_export_func_disable"))
  674. }
  675. if !strings.HasPrefix(bookResult.Cover, "http:://") && !strings.HasPrefix(bookResult.Cover, "https:://") {
  676. bookResult.Cover = conf.URLForWithCdnImage(bookResult.Cover)
  677. }
  678. if output == "markdown" {
  679. if bookResult.Editor != "markdown" {
  680. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.cur_project_not_support_md"))
  681. }
  682. p, err := bookResult.ExportMarkdown(c.CruSession.SessionID(context.TODO()))
  683. if err != nil {
  684. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.failed"))
  685. }
  686. c.Ctx.Output.Download(p, bookResult.BookName+".zip")
  687. c.StopRun()
  688. return
  689. }
  690. outputPath := filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(bookResult.BookId))
  691. pdfpath := filepath.Join(outputPath, "book.pdf")
  692. epubpath := filepath.Join(outputPath, "book.epub")
  693. mobipath := filepath.Join(outputPath, "book.mobi")
  694. docxpath := filepath.Join(outputPath, "book.docx")
  695. if output == "pdf" && filetil.FileExists(pdfpath) {
  696. c.Ctx.Output.Download(pdfpath, bookResult.BookName+".pdf")
  697. c.Abort("200")
  698. } else if output == "epub" && filetil.FileExists(epubpath) {
  699. c.Ctx.Output.Download(epubpath, bookResult.BookName+".epub")
  700. c.Abort("200")
  701. } else if output == "mobi" && filetil.FileExists(mobipath) {
  702. c.Ctx.Output.Download(mobipath, bookResult.BookName+".mobi")
  703. c.Abort("200")
  704. } else if output == "docx" && filetil.FileExists(docxpath) {
  705. c.Ctx.Output.Download(docxpath, bookResult.BookName+".docx")
  706. c.Abort("200")
  707. } else if output == "pdf" || output == "epub" || output == "docx" || output == "mobi" {
  708. if err := models.BackgroundConvert(c.CruSession.SessionID(context.TODO()), bookResult); err != nil && err != gopool.ErrHandlerIsExist {
  709. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.export_failed"))
  710. }
  711. c.ShowErrorPage(200, i18n.Tr(c.Lang, "message.file_converting"))
  712. } else {
  713. c.ShowErrorPage(200, i18n.Tr(c.Lang, "message.unsupport_file_type"))
  714. }
  715. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.no_exportable_file"))
  716. }
  717. // 生成项目访问的二维码
  718. func (c *DocumentController) QrCode() {
  719. c.Prepare()
  720. identify := c.GetString(":key")
  721. book, err := models.NewBook().FindByIdentify(identify)
  722. if err != nil || book.BookId <= 0 {
  723. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  724. }
  725. uri := conf.URLFor("DocumentController.Index", ":key", identify)
  726. code, err := qr.Encode(uri, qr.L, qr.Unicode)
  727. if err != nil {
  728. logs.Error("生成二维码失败 ->", err)
  729. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.gen_qrcode_failed"))
  730. }
  731. code, err = barcode.Scale(code, 150, 150)
  732. if err != nil {
  733. logs.Error("生成二维码失败 ->", err)
  734. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.gen_qrcode_failed"))
  735. }
  736. c.Ctx.ResponseWriter.Header().Set("Content-Type", "image/png")
  737. // imgpath := filepath.Join("cache","qrcode",identify + ".png")
  738. err = png.Encode(c.Ctx.ResponseWriter, code)
  739. if err != nil {
  740. logs.Error("生成二维码失败 ->", err)
  741. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.gen_qrcode_failed"))
  742. }
  743. }
  744. // 项目内搜索
  745. func (c *DocumentController) Search() {
  746. c.Prepare()
  747. identify := c.Ctx.Input.Param(":key")
  748. token := c.GetString("token")
  749. keyword := strings.TrimSpace(c.GetString("keyword"))
  750. if identify == "" {
  751. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  752. }
  753. if !c.EnableAnonymous && !c.isUserLoggedIn() {
  754. promptUserToLogIn(c)
  755. return
  756. }
  757. bookResult := c.isReadable(identify, token)
  758. docs, err := models.NewDocumentSearchResult().SearchDocument(keyword, bookResult.BookId)
  759. if err != nil {
  760. logs.Error(err)
  761. c.JsonResult(6002, i18n.Tr(c.Lang, "message.search_result_error"))
  762. }
  763. if len(docs) < 0 {
  764. c.JsonResult(404, i18n.Tr(c.Lang, "message.no_data"))
  765. }
  766. for _, doc := range docs {
  767. doc.BookId = bookResult.BookId
  768. doc.BookName = bookResult.BookName
  769. doc.Description = bookResult.Description
  770. doc.BookIdentify = bookResult.Identify
  771. }
  772. c.JsonResult(0, "ok", docs)
  773. }
  774. // 文档历史列表
  775. func (c *DocumentController) History() {
  776. c.Prepare()
  777. c.TplName = "document/history.tpl"
  778. identify := c.GetString("identify")
  779. docId, err := c.GetInt("doc_id", 0)
  780. pageIndex, _ := c.GetInt("page", 1)
  781. bookId := 0
  782. // 如果是超级管理员则忽略权限判断
  783. if c.Member.IsAdministrator() {
  784. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  785. if err != nil {
  786. logs.Error("查找项目失败 ->", err)
  787. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit")
  788. return
  789. }
  790. bookId = book.BookId
  791. c.Data["Model"] = book
  792. } else {
  793. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  794. if err != nil || bookResult.RoleId == conf.BookObserver {
  795. logs.Error("查找项目失败 ->", err)
  796. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit")
  797. return
  798. }
  799. bookId = bookResult.BookId
  800. c.Data["Model"] = bookResult
  801. }
  802. if docId <= 0 {
  803. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.param_error")
  804. return
  805. }
  806. doc, err := models.NewDocument().Find(docId)
  807. if err != nil {
  808. logs.Error("Delete => ", err)
  809. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.get_doc_his_failed")
  810. return
  811. }
  812. // 如果文档所属项目错误
  813. if doc.BookId != bookId {
  814. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.param_error")
  815. return
  816. }
  817. histories, totalCount, err := models.NewDocumentHistory().FindToPager(docId, pageIndex, conf.PageSize)
  818. if err != nil {
  819. logs.Error("分页查找文档历史失败 ->", err)
  820. c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.get_doc_his_failed")
  821. return
  822. }
  823. c.Data["List"] = histories
  824. c.Data["PageHtml"] = ""
  825. c.Data["Document"] = doc
  826. if totalCount > 0 {
  827. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  828. c.Data["PageHtml"] = pager.HtmlPages()
  829. }
  830. }
  831. func (c *DocumentController) DeleteHistory() {
  832. c.Prepare()
  833. c.TplName = "document/history.tpl"
  834. identify := c.GetString("identify")
  835. docId, err := c.GetInt("doc_id", 0)
  836. historyId, _ := c.GetInt("history_id", 0)
  837. if historyId <= 0 {
  838. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  839. }
  840. bookId := 0
  841. // 如果是超级管理员则忽略权限判断
  842. if c.Member.IsAdministrator() {
  843. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  844. if err != nil {
  845. logs.Error("查找项目失败 ->", err)
  846. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  847. }
  848. bookId = book.BookId
  849. } else {
  850. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  851. if err != nil || bookResult.RoleId == conf.BookObserver {
  852. logs.Error("查找项目失败 ->", err)
  853. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  854. }
  855. bookId = bookResult.BookId
  856. }
  857. if docId <= 0 {
  858. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  859. }
  860. doc, err := models.NewDocument().Find(docId)
  861. if err != nil {
  862. logs.Error("Delete => ", err)
  863. c.JsonResult(6001, i18n.Tr(c.Lang, "message.get_doc_his_failed"))
  864. }
  865. // 如果文档所属项目错误
  866. if doc.BookId != bookId {
  867. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  868. }
  869. err = models.NewDocumentHistory().Delete(historyId, docId)
  870. if err != nil {
  871. logs.Error(err)
  872. c.JsonResult(6002, i18n.Tr(c.Lang, "message.failed"))
  873. }
  874. c.JsonResult(0, "ok")
  875. }
  876. //通过文档历史恢复文档
  877. func (c *DocumentController) RestoreHistory() {
  878. c.Prepare()
  879. c.TplName = "document/history.tpl"
  880. identify := c.GetString("identify")
  881. docId, err := c.GetInt("doc_id", 0)
  882. historyId, _ := c.GetInt("history_id", 0)
  883. if historyId <= 0 {
  884. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  885. }
  886. bookId := 0
  887. // 如果是超级管理员则忽略权限判断
  888. if c.Member.IsAdministrator() {
  889. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  890. if err != nil {
  891. logs.Error("FindByIdentify => ", err)
  892. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  893. }
  894. bookId = book.BookId
  895. } else {
  896. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  897. if err != nil || bookResult.RoleId == conf.BookObserver {
  898. logs.Error("FindByIdentify => ", err)
  899. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  900. }
  901. bookId = bookResult.BookId
  902. }
  903. if docId <= 0 {
  904. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  905. }
  906. doc, err := models.NewDocument().Find(docId)
  907. if err != nil {
  908. logs.Error("Delete => ", err)
  909. c.JsonResult(6001, i18n.Tr(c.Lang, "message.get_doc_his_failed"))
  910. }
  911. // 如果文档所属项目错误
  912. if doc.BookId != bookId {
  913. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  914. }
  915. err = models.NewDocumentHistory().Restore(historyId, docId, c.Member.MemberId)
  916. if err != nil {
  917. logs.Error(err)
  918. c.JsonResult(6002, i18n.Tr(c.Lang, "message.failed"))
  919. }
  920. c.JsonResult(0, "ok", doc)
  921. }
  922. func (c *DocumentController) Compare() {
  923. c.Prepare()
  924. c.TplName = "document/compare.tpl"
  925. historyId, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
  926. identify := c.Ctx.Input.Param(":key")
  927. bookId := 0
  928. editor := "markdown"
  929. // 如果是超级管理员则忽略权限判断
  930. if c.Member.IsAdministrator() {
  931. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  932. if err != nil {
  933. logs.Error("DocumentController.Compare => ", err)
  934. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  935. return
  936. }
  937. bookId = book.BookId
  938. c.Data["Model"] = book
  939. editor = book.Editor
  940. } else {
  941. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  942. if err != nil || bookResult.RoleId == conf.BookObserver {
  943. logs.Error("FindByIdentify => ", err)
  944. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  945. return
  946. }
  947. bookId = bookResult.BookId
  948. c.Data["Model"] = bookResult
  949. editor = bookResult.Editor
  950. }
  951. if historyId <= 0 {
  952. c.ShowErrorPage(60002, i18n.Tr(c.Lang, "message.param_error"))
  953. }
  954. history, err := models.NewDocumentHistory().Find(historyId)
  955. if err != nil {
  956. logs.Error("DocumentController.Compare => ", err)
  957. c.ShowErrorPage(60003, err.Error())
  958. }
  959. doc, err := models.NewDocument().Find(history.DocumentId)
  960. if err != nil || doc == nil || doc.BookId != bookId {
  961. c.ShowErrorPage(60002, i18n.Tr(c.Lang, "message.doc_not_exist"))
  962. return
  963. }
  964. c.Data["HistoryId"] = historyId
  965. c.Data["DocumentId"] = doc.DocumentId
  966. if editor == "markdown" {
  967. c.Data["HistoryContent"] = history.Markdown
  968. c.Data["Content"] = doc.Markdown
  969. } else {
  970. c.Data["HistoryContent"] = template.HTML(history.Content)
  971. c.Data["Content"] = template.HTML(doc.Content)
  972. }
  973. }
  974. // 判断用户是否可以阅读文档
  975. func (c *DocumentController) isReadable(identify, token string) *models.BookResult {
  976. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  977. if err != nil {
  978. logs.Error(err)
  979. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.item_not_exist"))
  980. }
  981. bookResult := models.NewBookResult().ToBookResult(*book)
  982. isOk := false
  983. if c.isUserLoggedIn() {
  984. roleId, err := models.NewBook().FindForRoleId(book.BookId, c.Member.MemberId)
  985. if err == nil {
  986. isOk = true
  987. bookResult.MemberId = c.Member.MemberId
  988. bookResult.RoleId = roleId
  989. }
  990. }
  991. // 如果文档是私有的
  992. if book.PrivatelyOwned == 1 && (!c.isUserLoggedIn() || !c.Member.IsAdministrator()) {
  993. if s, ok := c.GetSession(identify).(string); !ok || (!strings.EqualFold(s, book.PrivateToken) && !strings.EqualFold(s, book.BookPassword)) {
  994. if book.PrivateToken != "" && !isOk && token != "" {
  995. // 如果有访问的 Token,并且该项目设置了访问 Token,并且和用户提供的相匹配,则记录到 Session 中。
  996. // 如果用户未提供 Token 且用户登录了,则判断用户是否参与了该项目。
  997. // 如果用户未登录,则从 Session 中读取 Token。
  998. if token != "" && strings.EqualFold(token, book.PrivateToken) {
  999. c.SetSession(identify, token)
  1000. } else if token, ok := c.GetSession(identify).(string); !ok || !strings.EqualFold(token, book.PrivateToken) {
  1001. logs.Info("尝试访问文档但权限不足 ->", identify, token)
  1002. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  1003. }
  1004. } else if password := c.GetString("bPassword", ""); !isOk && book.BookPassword != "" && password != "" {
  1005. //如果设置了密码,则判断密码是否正确
  1006. if book.BookPassword != password {
  1007. c.JsonResult(5001, i18n.Tr(c.Lang, "message.wrong_password"))
  1008. } else {
  1009. c.SetSession(identify, password)
  1010. c.JsonResult(0, "OK")
  1011. }
  1012. } else if !isOk {
  1013. //如果设置了密码,则显示密码输入页面
  1014. if book.BookPassword != "" {
  1015. //判断已存在的密码是否正确
  1016. if password, ok := c.GetSession(identify).(string); !ok || !strings.EqualFold(password, book.BookPassword) {
  1017. body, err := c.ExecuteViewPathTemplate("document/document_password.tpl", map[string]string{"Identify": book.Identify})
  1018. if err != nil {
  1019. logs.Error("显示密码页面失败 ->", err)
  1020. }
  1021. c.CustomAbort(200, body)
  1022. }
  1023. } else {
  1024. logs.Info("尝试访问文档但权限不足 ->", identify, token)
  1025. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  1026. }
  1027. }
  1028. }
  1029. }
  1030. return bookResult
  1031. }
  1032. func promptUserToLogIn(c *DocumentController) {
  1033. logs.Info("Access " + c.Ctx.Request.URL.RequestURI() + " not permitted.")
  1034. logs.Info(" Access will be redirected to login page(SessionId: " + c.CruSession.SessionID(context.TODO()) + ").")
  1035. if c.IsAjax() {
  1036. c.JsonResult(6000, i18n.Tr(c.Lang, "message.need_relogin"))
  1037. } else {
  1038. c.Redirect(conf.URLFor("AccountController.Login")+"?url="+url.PathEscape(conf.BaseUrl+c.Ctx.Request.URL.RequestURI()), 302)
  1039. }
  1040. }