DocumentController.go 37 KB

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