DocumentController.go 33 KB

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