document.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  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/godoc/commands"
  21. "github.com/lifei6671/godoc/conf"
  22. "github.com/lifei6671/godoc/models"
  23. "github.com/lifei6671/godoc/utils"
  24. "github.com/lifei6671/godoc/utils/wkhtmltopdf"
  25. )
  26. //DocumentController struct.
  27. type DocumentController struct {
  28. BaseController
  29. }
  30. //判断用户是否可以阅读文档.
  31. func isReadable(identify, token string, c *DocumentController) *models.BookResult {
  32. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  33. if err != nil {
  34. beego.Error(err)
  35. c.Abort("500")
  36. }
  37. if c.Member != nil && c.Member.IsAdministrator() {
  38. bookResult := book.ToBookResult()
  39. return bookResult
  40. }
  41. //如果文档是私有的
  42. if book.PrivatelyOwned == 1 {
  43. is_ok := false
  44. if c.Member != nil {
  45. _, err := models.NewRelationship().FindForRoleId(book.BookId, c.Member.MemberId)
  46. if err == nil {
  47. is_ok = true
  48. }
  49. }
  50. if book.PrivateToken != "" && !is_ok {
  51. //如果有访问的Token,并且该项目设置了访问Token,并且和用户提供的相匹配,则记录到Session中.
  52. //如果用户未提供Token且用户登录了,则判断用户是否参与了该项目.
  53. //如果用户未登录,则从Session中读取Token.
  54. if token != "" && strings.EqualFold(token, book.PrivateToken) {
  55. c.SetSession(identify, token)
  56. } else if token, ok := c.GetSession(identify).(string); !ok || !strings.EqualFold(token, book.PrivateToken) {
  57. c.Abort("403")
  58. }
  59. } else if !is_ok {
  60. c.Abort("403")
  61. }
  62. }
  63. bookResult := book.ToBookResult()
  64. if c.Member != nil {
  65. rel, err := models.NewRelationship().FindByBookIdAndMemberId(bookResult.BookId, c.Member.MemberId)
  66. if err == nil {
  67. bookResult.MemberId = rel.MemberId
  68. bookResult.RoleId = rel.RoleId
  69. bookResult.RelationshipId = rel.RelationshipId
  70. }
  71. }
  72. //判断是否需要显示评论框
  73. if bookResult.CommentStatus == "closed" {
  74. bookResult.IsDisplayComment = false
  75. } else if bookResult.CommentStatus == "open" {
  76. bookResult.IsDisplayComment = true
  77. } else if bookResult.CommentStatus == "group_only" {
  78. bookResult.IsDisplayComment = bookResult.RelationshipId > 0
  79. } else if bookResult.CommentStatus == "registered_only" {
  80. bookResult.IsDisplayComment = true
  81. }
  82. return bookResult
  83. }
  84. //文档首页.
  85. func (c *DocumentController) Index() {
  86. c.Prepare()
  87. identify := c.Ctx.Input.Param(":key")
  88. token := c.GetString("token")
  89. if identify == "" {
  90. c.Abort("404")
  91. }
  92. //如果没有开启你们访问则跳转到登录
  93. if !c.EnableAnonymous && c.Member == nil {
  94. c.Redirect(beego.URLFor("AccountController.Login"), 302)
  95. return
  96. }
  97. bookResult := isReadable(identify, token, c)
  98. c.TplName = "document/" + bookResult.Theme + "_read.tpl"
  99. tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, 0)
  100. if err != nil {
  101. beego.Error(err)
  102. c.Abort("500")
  103. }
  104. c.Data["Model"] = bookResult
  105. c.Data["Result"] = template.HTML(tree)
  106. c.Data["Title"] = "概要"
  107. c.Data["Content"] = bookResult.Description
  108. }
  109. //阅读文档.
  110. func (c *DocumentController) Read() {
  111. c.Prepare()
  112. identify := c.Ctx.Input.Param(":key")
  113. token := c.GetString("token")
  114. id := c.GetString(":id")
  115. if identify == "" || id == "" {
  116. c.Abort("404")
  117. }
  118. //如果没有开启你们访问则跳转到登录
  119. if !c.EnableAnonymous && c.Member == nil {
  120. c.Redirect(beego.URLFor("AccountController.Login"), 302)
  121. return
  122. }
  123. bookResult := isReadable(identify, token, c)
  124. c.TplName = "document/" + bookResult.Theme + "_read.tpl"
  125. doc := models.NewDocument()
  126. if doc_id, err := strconv.Atoi(id); err == nil {
  127. doc, err = doc.Find(doc_id)
  128. if err != nil {
  129. beego.Error(err)
  130. c.Abort("500")
  131. }
  132. } else {
  133. doc, err = doc.FindByFieldFirst("identify", id)
  134. if err != nil {
  135. beego.Error(err)
  136. c.Abort("500")
  137. }
  138. }
  139. if doc.BookId != bookResult.BookId {
  140. c.Abort("403")
  141. }
  142. attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
  143. if err == nil {
  144. doc.AttachList = attach
  145. }
  146. cdnimg := beego.AppConfig.String("cdnimg")
  147. if doc.Release != "" && cdnimg != "" {
  148. query, err := goquery.NewDocumentFromReader(bytes.NewBufferString(doc.Release))
  149. if err != nil {
  150. beego.Error(err)
  151. } else {
  152. query.Find("img").Each(func(i int, contentSelection *goquery.Selection) {
  153. if src, ok := contentSelection.Attr("src"); ok && strings.HasPrefix(src, "/uploads/") {
  154. contentSelection.SetAttr("src", utils.JoinURI(cdnimg, src))
  155. }
  156. })
  157. html, err := query.Html()
  158. if err != nil {
  159. beego.Error(err)
  160. } else {
  161. doc.Release = html
  162. }
  163. }
  164. }
  165. if c.IsAjax() {
  166. var data struct {
  167. DocTitle string `json:"doc_title"`
  168. Body string `json:"body"`
  169. Title string `json:"title"`
  170. }
  171. data.DocTitle = doc.DocumentName
  172. data.Body = doc.Release
  173. data.Title = doc.DocumentName + " - Powered by MinDoc"
  174. c.JsonResult(0, "ok", data)
  175. }
  176. tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, doc.DocumentId)
  177. if err != nil {
  178. beego.Error(err)
  179. c.Abort("500")
  180. }
  181. c.Data["Model"] = bookResult
  182. c.Data["Result"] = template.HTML(tree)
  183. c.Data["Title"] = doc.DocumentName
  184. c.Data["Content"] = template.HTML(doc.Release)
  185. }
  186. //编辑文档.
  187. func (c *DocumentController) Edit() {
  188. c.Prepare()
  189. identify := c.Ctx.Input.Param(":key")
  190. if identify == "" {
  191. c.Abort("404")
  192. }
  193. bookResult := models.NewBookResult()
  194. var err error
  195. //如果是超级管理者,则不判断权限
  196. if c.Member.IsAdministrator() {
  197. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  198. if err != nil {
  199. c.JsonResult(6002, "项目不存在或权限不足")
  200. }
  201. bookResult = book.ToBookResult()
  202. } else {
  203. bookResult, err = models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  204. if err != nil {
  205. beego.Error("DocumentController.Edit => ", err)
  206. c.Abort("403")
  207. }
  208. if bookResult.RoleId == conf.BookObserver {
  209. c.JsonResult(6002, "项目不存在或权限不足")
  210. }
  211. }
  212. //根据不同编辑器类型加载编辑器
  213. if bookResult.Editor == "markdown" {
  214. c.TplName = "document/markdown_edit_template.tpl"
  215. } else if bookResult.Editor == "html" {
  216. c.TplName = "document/html_edit_template.tpl"
  217. } else {
  218. c.TplName = "document/" + bookResult.Editor + "_edit_template.tpl"
  219. }
  220. c.Data["Model"] = bookResult
  221. r, _ := json.Marshal(bookResult)
  222. c.Data["ModelResult"] = template.JS(string(r))
  223. c.Data["Result"] = template.JS("[]")
  224. trees, err := models.NewDocument().FindDocumentTree(bookResult.BookId)
  225. if err != nil {
  226. beego.Error("FindDocumentTree => ", err)
  227. } else {
  228. if len(trees) > 0 {
  229. if jtree, err := json.Marshal(trees); err == nil {
  230. c.Data["Result"] = template.JS(string(jtree))
  231. }
  232. } else {
  233. c.Data["Result"] = template.JS("[]")
  234. }
  235. }
  236. c.Data["BaiDuMapKey"] = beego.AppConfig.DefaultString("baidumapkey", "")
  237. }
  238. //创建一个文档.
  239. func (c *DocumentController) Create() {
  240. identify := c.GetString("identify")
  241. doc_identify := c.GetString("doc_identify")
  242. doc_name := c.GetString("doc_name")
  243. parent_id, _ := c.GetInt("parent_id", 0)
  244. doc_id, _ := c.GetInt("doc_id", 0)
  245. if identify == "" {
  246. c.JsonResult(6001, "参数错误")
  247. }
  248. if doc_name == "" {
  249. c.JsonResult(6004, "文档名称不能为空")
  250. }
  251. if doc_identify != "" {
  252. if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, doc_identify); !ok || err != nil {
  253. c.JsonResult(6003, "文档标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  254. }
  255. d, _ := models.NewDocument().FindByFieldFirst("identify", doc_identify)
  256. if d.DocumentId > 0 && d.DocumentId != doc_id {
  257. c.JsonResult(6006, "文档标识已被使用")
  258. }
  259. }
  260. book_id := 0
  261. //如果是超级管理员则不判断权限
  262. if c.Member.IsAdministrator() {
  263. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  264. if err != nil {
  265. beego.Error(err)
  266. c.JsonResult(6002, "项目不存在或权限不足")
  267. }
  268. book_id = book.BookId
  269. } else {
  270. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  271. if err != nil || bookResult.RoleId == conf.BookObserver {
  272. beego.Error("FindByIdentify => ", err)
  273. c.JsonResult(6002, "项目不存在或权限不足")
  274. }
  275. book_id = bookResult.BookId
  276. }
  277. if parent_id > 0 {
  278. doc, err := models.NewDocument().Find(parent_id)
  279. if err != nil || doc.BookId != book_id {
  280. c.JsonResult(6003, "父分类不存在")
  281. }
  282. }
  283. document, _ := models.NewDocument().Find(doc_id)
  284. document.MemberId = c.Member.MemberId
  285. document.BookId = book_id
  286. if doc_identify != "" {
  287. document.Identify = doc_identify
  288. }
  289. document.Version = time.Now().Unix()
  290. document.DocumentName = doc_name
  291. document.ParentId = parent_id
  292. if err := document.InsertOrUpdate(); err != nil {
  293. beego.Error("InsertOrUpdate => ", err)
  294. c.JsonResult(6005, "保存失败")
  295. } else {
  296. c.JsonResult(0, "ok", document)
  297. }
  298. }
  299. //上传附件或图片.
  300. func (c *DocumentController) Upload() {
  301. identify := c.GetString("identify")
  302. doc_id, _ := c.GetInt("doc_id")
  303. is_attach := true
  304. if identify == "" {
  305. c.JsonResult(6001, "参数错误")
  306. }
  307. name := "editormd-file-file"
  308. file, moreFile, err := c.GetFile(name)
  309. if err == http.ErrMissingFile {
  310. name = "editormd-image-file"
  311. file, moreFile, err = c.GetFile(name)
  312. if err == http.ErrMissingFile {
  313. c.JsonResult(6003, "没有发现需要上传的文件")
  314. }
  315. }
  316. if err != nil {
  317. c.JsonResult(6002, err.Error())
  318. }
  319. defer file.Close()
  320. ext := filepath.Ext(moreFile.Filename)
  321. if ext == "" {
  322. c.JsonResult(6003, "无法解析文件的格式")
  323. }
  324. if !conf.IsAllowUploadFileExt(ext) {
  325. c.JsonResult(6004, "不允许的文件类型")
  326. }
  327. book_id := 0
  328. //如果是超级管理员,则不判断权限
  329. if c.Member.IsAdministrator() {
  330. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  331. if err != nil {
  332. c.JsonResult(6006, "文档不存在或权限不足")
  333. }
  334. book_id = book.BookId
  335. } else {
  336. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  337. if err != nil {
  338. beego.Error("DocumentController.Edit => ", err)
  339. if err == orm.ErrNoRows {
  340. c.JsonResult(6006, "权限不足")
  341. }
  342. c.JsonResult(6001, err.Error())
  343. }
  344. //如果没有编辑权限
  345. if book.RoleId != conf.BookEditor && book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  346. c.JsonResult(6006, "权限不足")
  347. }
  348. book_id = book.BookId
  349. }
  350. if doc_id > 0 {
  351. doc, err := models.NewDocument().Find(doc_id)
  352. if err != nil {
  353. c.JsonResult(6007, "文档不存在")
  354. }
  355. if doc.BookId != book_id {
  356. c.JsonResult(6008, "文档不属于指定的项目")
  357. }
  358. }
  359. fileName := "attach_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  360. filePath := filepath.Join(commands.WorkingDirectory, "uploads", time.Now().Format("200601"), fileName+ext)
  361. path := filepath.Dir(filePath)
  362. os.MkdirAll(path, os.ModePerm)
  363. err = c.SaveToFile(name, filePath)
  364. if err != nil {
  365. beego.Error("SaveToFile => ", err)
  366. c.JsonResult(6005, "保存文件失败")
  367. }
  368. attachment := models.NewAttachment()
  369. attachment.BookId = book_id
  370. attachment.FileName = moreFile.Filename
  371. attachment.CreateAt = c.Member.MemberId
  372. attachment.FileExt = ext
  373. attachment.FilePath = strings.TrimPrefix(filePath, commands.WorkingDirectory)
  374. attachment.DocumentId = doc_id
  375. if fileInfo, err := os.Stat(filePath); err == nil {
  376. attachment.FileSize = float64(fileInfo.Size())
  377. }
  378. if doc_id > 0 {
  379. attachment.DocumentId = doc_id
  380. }
  381. if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") || strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".gif") {
  382. attachment.HttpPath = "/" + strings.Replace(strings.TrimPrefix(filePath, commands.WorkingDirectory), "\\", "/", -1)
  383. if strings.HasPrefix(attachment.HttpPath, "//") {
  384. attachment.HttpPath = string(attachment.HttpPath[1:])
  385. }
  386. is_attach = false
  387. }
  388. err = attachment.Insert()
  389. if err != nil {
  390. os.Remove(filePath)
  391. beego.Error("Attachment Insert => ", err)
  392. c.JsonResult(6006, "文件保存失败")
  393. }
  394. if attachment.HttpPath == "" {
  395. attachment.HttpPath = beego.URLFor("DocumentController.DownloadAttachment", ":key", identify, ":attach_id", attachment.AttachmentId)
  396. if err := attachment.Update(); err != nil {
  397. beego.Error("SaveToFile => ", err)
  398. c.JsonResult(6005, "保存文件失败")
  399. }
  400. }
  401. result := map[string]interface{}{
  402. "errcode": 0,
  403. "success": 1,
  404. "message": "ok",
  405. "url": attachment.HttpPath,
  406. "alt": attachment.FileName,
  407. "is_attach": is_attach,
  408. "attach": attachment,
  409. }
  410. c.Ctx.Output.JSON(result, true, false)
  411. c.StopRun()
  412. }
  413. //DownloadAttachment 下载附件.
  414. func (c *DocumentController) DownloadAttachment() {
  415. c.Prepare()
  416. identify := c.Ctx.Input.Param(":key")
  417. attach_id, _ := strconv.Atoi(c.Ctx.Input.Param(":attach_id"))
  418. token := c.GetString("token")
  419. member_id := 0
  420. if c.Member != nil {
  421. member_id = c.Member.MemberId
  422. }
  423. book_id := 0
  424. //判断用户是否参与了项目
  425. bookResult, err := models.NewBookResult().FindByIdentify(identify, member_id)
  426. if err != nil {
  427. //判断项目公开状态
  428. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  429. if err != nil {
  430. c.Abort("404")
  431. }
  432. //如果不是超级管理员则判断权限
  433. if c.Member == nil || c.Member.Role != conf.MemberSuperRole {
  434. //如果项目是私有的,并且token不正确
  435. if (book.PrivatelyOwned == 1 && token == "") || (book.PrivatelyOwned == 1 && book.PrivateToken != token) {
  436. c.Abort("403")
  437. }
  438. }
  439. book_id = book.BookId
  440. } else {
  441. book_id = bookResult.BookId
  442. }
  443. //查找附件
  444. attachment, err := models.NewAttachment().Find(attach_id)
  445. if err != nil {
  446. beego.Error("DownloadAttachment => ", err)
  447. if err == orm.ErrNoRows {
  448. c.Abort("404")
  449. } else {
  450. c.Abort("500")
  451. }
  452. }
  453. if attachment.BookId != book_id {
  454. c.Abort("404")
  455. }
  456. c.Ctx.Output.Download(filepath.Join(commands.WorkingDirectory, attachment.FilePath), attachment.FileName)
  457. c.StopRun()
  458. }
  459. //删除附件.
  460. func (c *DocumentController) RemoveAttachment() {
  461. c.Prepare()
  462. attach_id, _ := c.GetInt("attach_id")
  463. if attach_id <= 0 {
  464. c.JsonResult(6001, "参数错误")
  465. }
  466. attach, err := models.NewAttachment().Find(attach_id)
  467. if err != nil {
  468. beego.Error(err)
  469. c.JsonResult(6002, "附件不存在")
  470. }
  471. document, err := models.NewDocument().Find(attach.DocumentId)
  472. if err != nil {
  473. beego.Error(err)
  474. c.JsonResult(6003, "文档不存在")
  475. }
  476. if c.Member.Role != conf.MemberSuperRole {
  477. rel, err := models.NewRelationship().FindByBookIdAndMemberId(document.BookId, c.Member.MemberId)
  478. if err != nil {
  479. beego.Error(err)
  480. c.JsonResult(6004, "权限不足")
  481. }
  482. if rel.RoleId == conf.BookObserver {
  483. c.JsonResult(6004, "权限不足")
  484. }
  485. }
  486. err = attach.Delete()
  487. if err != nil {
  488. beego.Error(err)
  489. c.JsonResult(6005, "删除失败")
  490. }
  491. os.Remove(filepath.Join(commands.WorkingDirectory, attach.FilePath))
  492. c.JsonResult(0, "ok", attach)
  493. }
  494. //删除文档.
  495. func (c *DocumentController) Delete() {
  496. c.Prepare()
  497. identify := c.GetString("identify")
  498. doc_id, err := c.GetInt("doc_id", 0)
  499. book_id := 0
  500. //如果是超级管理员则忽略权限判断
  501. if c.Member.IsAdministrator() {
  502. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  503. if err != nil {
  504. beego.Error("FindByIdentify => ", err)
  505. c.JsonResult(6002, "项目不存在或权限不足")
  506. }
  507. book_id = book.BookId
  508. } else {
  509. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  510. if err != nil || bookResult.RoleId == conf.BookObserver {
  511. beego.Error("FindByIdentify => ", err)
  512. c.JsonResult(6002, "项目不存在或权限不足")
  513. }
  514. book_id = bookResult.BookId
  515. }
  516. if doc_id <= 0 {
  517. c.JsonResult(6001, "参数错误")
  518. }
  519. doc, err := models.NewDocument().Find(doc_id)
  520. if err != nil {
  521. beego.Error("Delete => ", err)
  522. c.JsonResult(6003, "删除失败")
  523. }
  524. //如果文档所属项目错误
  525. if doc.BookId != book_id {
  526. c.JsonResult(6004, "参数错误")
  527. }
  528. //递归删除项目下的文档以及子文档
  529. err = doc.RecursiveDocument(doc.DocumentId)
  530. if err != nil {
  531. c.JsonResult(6005, "删除失败")
  532. }
  533. //重置文档数量统计
  534. models.NewBook().ResetDocumentNumber(doc.BookId)
  535. c.JsonResult(0, "ok")
  536. }
  537. //获取文档内容.
  538. func (c *DocumentController) Content() {
  539. c.Prepare()
  540. identify := c.Ctx.Input.Param(":key")
  541. doc_id, err := c.GetInt("doc_id")
  542. if err != nil {
  543. doc_id, _ = strconv.Atoi(c.Ctx.Input.Param(":id"))
  544. }
  545. book_id := 0
  546. //如果是超级管理员,则忽略权限
  547. if c.Member.IsAdministrator() {
  548. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  549. if err != nil {
  550. c.JsonResult(6002, "项目不存在或权限不足")
  551. }
  552. book_id = book.BookId
  553. } else {
  554. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  555. if err != nil || bookResult.RoleId == conf.BookObserver {
  556. beego.Error("FindByIdentify => ", err)
  557. c.JsonResult(6002, "项目不存在或权限不足")
  558. }
  559. book_id = bookResult.BookId
  560. }
  561. if doc_id <= 0 {
  562. c.JsonResult(6001, "参数错误")
  563. }
  564. if c.Ctx.Input.IsPost() {
  565. markdown := strings.TrimSpace(c.GetString("markdown", ""))
  566. content := c.GetString("html")
  567. version, _ := c.GetInt64("version", 0)
  568. is_cover := c.GetString("cover")
  569. doc, err := models.NewDocument().Find(doc_id)
  570. if err != nil {
  571. c.JsonResult(6003, "读取文档错误")
  572. }
  573. if doc.BookId != book_id {
  574. c.JsonResult(6004, "保存的文档不属于指定项目")
  575. }
  576. if doc.Version != version && !strings.EqualFold(is_cover, "yes") {
  577. beego.Info("%d|", version, doc.Version)
  578. c.JsonResult(6005, "文档已被修改确定要覆盖吗?")
  579. }
  580. history := models.NewDocumentHistory()
  581. history.DocumentId = doc_id
  582. history.Content = doc.Content
  583. history.Markdown = doc.Markdown
  584. history.DocumentName = doc.DocumentName
  585. history.ModifyAt = c.Member.MemberId
  586. history.MemberId = doc.MemberId
  587. history.ParentId = doc.ParentId
  588. history.Version = time.Now().Unix()
  589. history.Action = "modify"
  590. history.ActionName = "修改文档"
  591. if markdown == "" && content != "" {
  592. doc.Markdown = content
  593. } else {
  594. doc.Markdown = markdown
  595. }
  596. doc.Version = time.Now().Unix()
  597. doc.Content = content
  598. if err := doc.InsertOrUpdate(); err != nil {
  599. beego.Error("InsertOrUpdate => ", err)
  600. c.JsonResult(6006, "保存失败")
  601. }
  602. //如果启用了文档历史,则添加历史文档
  603. if c.EnableDocumentHistory {
  604. _, err = history.InsertOrUpdate()
  605. if err != nil {
  606. beego.Error("DocumentHistory InsertOrUpdate => ", err)
  607. }
  608. }
  609. c.JsonResult(0, "ok", doc)
  610. }
  611. doc, err := models.NewDocument().Find(doc_id)
  612. if err != nil {
  613. c.JsonResult(6003, "文档不存在")
  614. }
  615. attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
  616. if err == nil {
  617. doc.AttachList = attach
  618. }
  619. c.JsonResult(0, "ok", doc)
  620. }
  621. //导出文件
  622. func (c *DocumentController) Export() {
  623. c.Prepare()
  624. c.TplName = "document/export.tpl"
  625. identify := c.Ctx.Input.Param(":key")
  626. output := c.GetString("output")
  627. token := c.GetString("token")
  628. if identify == "" {
  629. c.Abort("404")
  630. }
  631. //如果没有开启你们访问则跳转到登录
  632. if !c.EnableAnonymous && c.Member == nil {
  633. c.Redirect(beego.URLFor("AccountController.Login"), 302)
  634. return
  635. }
  636. bookResult := models.NewBookResult()
  637. if c.Member != nil && c.Member.IsAdministrator() {
  638. book, err := models.NewBook().FindByIdentify(identify)
  639. if err != nil {
  640. beego.Error(err)
  641. c.Abort("500")
  642. }
  643. bookResult = book.ToBookResult()
  644. } else {
  645. bookResult = isReadable(identify, token, c)
  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. }