DocumentController.go 33 KB

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