DocumentController.go 33 KB

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