DocumentController.go 35 KB

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