DocumentController.go 36 KB

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