1
0

DocumentController.go 33 KB

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