document.go 30 KB

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