DocumentController.go 33 KB

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