DocumentController.go 33 KB

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