DocumentController.go 34 KB

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