DocumentController.go 34 KB

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