DocumentController.go 33 KB

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