DocumentController.go 36 KB

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