document.go 30 KB

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