DocumentController.go 35 KB

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