1
0

DocumentController.go 37 KB

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