DocumentController.go 34 KB

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