document.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. "github.com/astaxie/beego"
  15. "github.com/astaxie/beego/orm"
  16. "github.com/boombuler/barcode"
  17. "github.com/boombuler/barcode/qr"
  18. "github.com/lifei6671/godoc/conf"
  19. "github.com/lifei6671/godoc/models"
  20. "github.com/lifei6671/godoc/utils/wkhtmltopdf"
  21. "github.com/lifei6671/godoc/utils"
  22. )
  23. //DocumentController struct.
  24. type DocumentController struct {
  25. BaseController
  26. }
  27. //判断用户是否可以阅读文档.
  28. func isReadable(identify, token string, c *DocumentController) *models.BookResult {
  29. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  30. if err != nil {
  31. beego.Error(err)
  32. c.Abort("500")
  33. }
  34. if c.Member != nil && c.Member.Role == conf.MemberSuperRole {
  35. bookResult := book.ToBookResult()
  36. return bookResult
  37. }
  38. //如果文档是私有的
  39. if book.PrivatelyOwned == 1 {
  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"] = 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. if c.IsAjax() {
  144. var data struct {
  145. DocTitle string `json:"doc_title"`
  146. Body string `json:"body"`
  147. Title string `json:"title"`
  148. }
  149. data.DocTitle = doc.DocumentName
  150. data.Body = doc.Release
  151. data.Title = doc.DocumentName + " - Powered by MinDoc"
  152. c.JsonResult(0, "ok", data)
  153. }
  154. tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, doc.DocumentId)
  155. if err != nil {
  156. beego.Error(err)
  157. c.Abort("500")
  158. }
  159. c.Data["Model"] = bookResult
  160. c.Data["Result"] = template.HTML(tree)
  161. c.Data["Title"] = doc.DocumentName
  162. c.Data["Content"] = template.HTML(doc.Release)
  163. }
  164. //编辑文档.
  165. func (c *DocumentController) Edit() {
  166. c.Prepare()
  167. identify := c.Ctx.Input.Param(":key")
  168. if identify == "" {
  169. c.Abort("404")
  170. }
  171. bookResult := models.NewBookResult()
  172. var err error
  173. //如果是超级管理者,则不判断权限
  174. if c.Member.Role == conf.MemberSuperRole {
  175. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  176. if err != nil {
  177. c.JsonResult(6002, "项目不存在或权限不足")
  178. }
  179. bookResult = book.ToBookResult()
  180. } else {
  181. bookResult, err = models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  182. if err != nil {
  183. beego.Error("DocumentController.Edit => ", err)
  184. c.Abort("403")
  185. }
  186. if bookResult.RoleId == conf.BookObserver {
  187. c.JsonResult(6002, "项目不存在或权限不足")
  188. }
  189. }
  190. //根据不同编辑器类型加载编辑器
  191. if bookResult.Editor == "markdown" {
  192. c.TplName = "document/markdown_edit_template.tpl"
  193. } else if bookResult.Editor == "html" {
  194. c.TplName = "document/html_edit_template.tpl"
  195. } else {
  196. c.TplName = "document/" + bookResult.Editor + "_edit_template.tpl"
  197. }
  198. c.Data["Model"] = bookResult
  199. r, _ := json.Marshal(bookResult)
  200. c.Data["ModelResult"] = template.JS(string(r))
  201. c.Data["Result"] = template.JS("[]")
  202. trees, err := models.NewDocument().FindDocumentTree(bookResult.BookId)
  203. if err != nil {
  204. beego.Error("FindDocumentTree => ", err)
  205. } else {
  206. if len(trees) > 0 {
  207. if jtree, err := json.Marshal(trees); err == nil {
  208. c.Data["Result"] = template.JS(string(jtree))
  209. }
  210. } else {
  211. c.Data["Result"] = template.JS("[]")
  212. }
  213. }
  214. c.Data["BaiDuMapKey"] = beego.AppConfig.DefaultString("baidumapkey", "")
  215. }
  216. //创建一个文档.
  217. func (c *DocumentController) Create() {
  218. identify := c.GetString("identify")
  219. doc_identify := c.GetString("doc_identify")
  220. doc_name := c.GetString("doc_name")
  221. parent_id, _ := c.GetInt("parent_id", 0)
  222. doc_id, _ := c.GetInt("doc_id", 0)
  223. if identify == "" {
  224. c.JsonResult(6001, "参数错误")
  225. }
  226. if doc_name == "" {
  227. c.JsonResult(6004, "文档名称不能为空")
  228. }
  229. if doc_identify != "" {
  230. if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, doc_identify); !ok || err != nil {
  231. c.JsonResult(6003, "文档标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  232. }
  233. d, _ := models.NewDocument().FindByFieldFirst("identify", doc_identify)
  234. if d.DocumentId > 0 && d.DocumentId != doc_id {
  235. c.JsonResult(6006, "文档标识已被使用")
  236. }
  237. }
  238. book_id := 0
  239. //如果是超级管理员则不判断权限
  240. if c.Member.Role == conf.MemberSuperRole {
  241. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  242. if err != nil {
  243. beego.Error(err)
  244. c.JsonResult(6002, "项目不存在或权限不足")
  245. }
  246. book_id = book.BookId
  247. } else {
  248. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  249. if err != nil || bookResult.RoleId == conf.BookObserver {
  250. beego.Error("FindByIdentify => ", err)
  251. c.JsonResult(6002, "项目不存在或权限不足")
  252. }
  253. book_id = bookResult.BookId
  254. }
  255. if parent_id > 0 {
  256. doc, err := models.NewDocument().Find(parent_id)
  257. if err != nil || doc.BookId != book_id {
  258. c.JsonResult(6003, "父分类不存在")
  259. }
  260. }
  261. document, _ := models.NewDocument().Find(doc_id)
  262. document.MemberId = c.Member.MemberId
  263. document.BookId = book_id
  264. if doc_identify != "" {
  265. document.Identify = doc_identify
  266. }
  267. document.Version = time.Now().Unix()
  268. document.DocumentName = doc_name
  269. document.ParentId = parent_id
  270. if err := document.InsertOrUpdate(); err != nil {
  271. beego.Error("InsertOrUpdate => ", err)
  272. c.JsonResult(6005, "保存失败")
  273. } else {
  274. c.JsonResult(0, "ok", document)
  275. }
  276. }
  277. //上传附件或图片.
  278. func (c *DocumentController) Upload() {
  279. identify := c.GetString("identify")
  280. doc_id, _ := c.GetInt("doc_id")
  281. is_attach := true
  282. if identify == "" {
  283. c.JsonResult(6001, "参数错误")
  284. }
  285. name := "editormd-file-file"
  286. file, moreFile, err := c.GetFile(name)
  287. if err == http.ErrMissingFile {
  288. name = "editormd-image-file"
  289. file, moreFile, err = c.GetFile(name)
  290. if err == http.ErrMissingFile {
  291. c.JsonResult(6003, "没有发现需要上传的文件")
  292. }
  293. }
  294. if err != nil {
  295. c.JsonResult(6002, err.Error())
  296. }
  297. defer file.Close()
  298. ext := filepath.Ext(moreFile.Filename)
  299. if ext == "" {
  300. c.JsonResult(6003, "无法解析文件的格式")
  301. }
  302. if !conf.IsAllowUploadFileExt(ext) {
  303. c.JsonResult(6004, "不允许的文件类型")
  304. }
  305. book_id := 0
  306. //如果是超级管理员,则不判断权限
  307. if c.Member.Role == conf.MemberSuperRole {
  308. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  309. if err != nil {
  310. c.JsonResult(6006, "文档不存在或权限不足")
  311. }
  312. book_id = book.BookId
  313. } else {
  314. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  315. if err != nil {
  316. beego.Error("DocumentController.Edit => ", err)
  317. if err == orm.ErrNoRows {
  318. c.JsonResult(6006, "权限不足")
  319. }
  320. c.JsonResult(6001, err.Error())
  321. }
  322. //如果没有编辑权限
  323. if book.RoleId != conf.BookEditor && book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  324. c.JsonResult(6006, "权限不足")
  325. }
  326. book_id = book.BookId
  327. }
  328. if doc_id > 0 {
  329. doc, err := models.NewDocument().Find(doc_id)
  330. if err != nil {
  331. c.JsonResult(6007, "文档不存在")
  332. }
  333. if doc.BookId != book_id {
  334. c.JsonResult(6008, "文档不属于指定的项目")
  335. }
  336. }
  337. fileName := "attach_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  338. filePath := "uploads/" + time.Now().Format("200601") + "/" + fileName + ext
  339. path := filepath.Dir(filePath)
  340. os.MkdirAll(path, os.ModePerm)
  341. err = c.SaveToFile(name, filePath)
  342. if err != nil {
  343. beego.Error("SaveToFile => ", err)
  344. c.JsonResult(6005, "保存文件失败")
  345. }
  346. attachment := models.NewAttachment()
  347. attachment.BookId = book_id
  348. attachment.FileName = moreFile.Filename
  349. attachment.CreateAt = c.Member.MemberId
  350. attachment.FileExt = ext
  351. attachment.FilePath = filePath
  352. attachment.DocumentId = doc_id
  353. if fileInfo, err := os.Stat(filePath); err == nil {
  354. attachment.FileSize = float64(fileInfo.Size())
  355. }
  356. if doc_id > 0 {
  357. attachment.DocumentId = doc_id
  358. }
  359. if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") || strings.EqualFold(ext, "png") || strings.EqualFold(ext, "gif") {
  360. attachment.HttpPath = "/" + filePath
  361. is_attach = false
  362. }
  363. err = attachment.Insert()
  364. if err != nil {
  365. os.Remove(filePath)
  366. beego.Error("Attachment Insert => ", err)
  367. c.JsonResult(6006, "文件保存失败")
  368. }
  369. if attachment.HttpPath == "" {
  370. attachment.HttpPath = beego.URLFor("DocumentController.DownloadAttachment", ":key", identify, ":attach_id", attachment.AttachmentId)
  371. if err := attachment.Update(); err != nil {
  372. beego.Error("SaveToFile => ", err)
  373. c.JsonResult(6005, "保存文件失败")
  374. }
  375. }
  376. result := map[string]interface{}{
  377. "errcode": 0,
  378. "success": 1,
  379. "message": "ok",
  380. "url": attachment.HttpPath,
  381. "alt": attachment.FileName,
  382. "is_attach": is_attach,
  383. "attach": attachment,
  384. }
  385. //c.Data["json"] = result
  386. //c.ServeJSON(true)
  387. //c.StopRun()
  388. //
  389. //returnJSON, err := json.Marshal(result)
  390. //
  391. //if err != nil {
  392. // beego.Error(err)
  393. //}
  394. //
  395. //c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8")
  396. //fmt.Fprint(c.Ctx.ResponseWriter,string(returnJSON))
  397. c.Ctx.Output.JSON(result, true, false)
  398. c.StopRun()
  399. }
  400. //DownloadAttachment 下载附件.
  401. func (c *DocumentController) DownloadAttachment() {
  402. c.Prepare()
  403. identify := c.Ctx.Input.Param(":key")
  404. attach_id, _ := strconv.Atoi(c.Ctx.Input.Param(":attach_id"))
  405. token := c.GetString("token")
  406. member_id := 0
  407. if c.Member != nil {
  408. member_id = c.Member.MemberId
  409. }
  410. book_id := 0
  411. //判断用户是否参与了项目
  412. bookResult, err := models.NewBookResult().FindByIdentify(identify, member_id)
  413. if err != nil {
  414. //判断项目公开状态
  415. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  416. if err != nil {
  417. c.Abort("404")
  418. }
  419. //如果不是超级管理员则判断权限
  420. if c.Member == nil || c.Member.Role != conf.MemberSuperRole {
  421. //如果项目是私有的,并且token不正确
  422. if (book.PrivatelyOwned == 1 && token == "") || (book.PrivatelyOwned == 1 && book.PrivateToken != token) {
  423. c.Abort("403")
  424. }
  425. }
  426. book_id = book.BookId
  427. } else {
  428. book_id = bookResult.BookId
  429. }
  430. //查找附件
  431. attachment, err := models.NewAttachment().Find(attach_id)
  432. if err != nil {
  433. beego.Error("DownloadAttachment => ", err)
  434. if err == orm.ErrNoRows {
  435. c.Abort("404")
  436. } else {
  437. c.Abort("500")
  438. }
  439. }
  440. if attachment.BookId != book_id {
  441. c.Abort("404")
  442. }
  443. c.Ctx.Output.Download(attachment.FilePath, attachment.FileName)
  444. c.StopRun()
  445. }
  446. //删除附件.
  447. func (c *DocumentController) RemoveAttachment() {
  448. c.Prepare()
  449. attach_id, _ := c.GetInt("attach_id")
  450. if attach_id <= 0 {
  451. c.JsonResult(6001, "参数错误")
  452. }
  453. attach, err := models.NewAttachment().Find(attach_id)
  454. if err != nil {
  455. beego.Error(err)
  456. c.JsonResult(6002, "附件不存在")
  457. }
  458. document, err := models.NewDocument().Find(attach.DocumentId)
  459. if err != nil {
  460. beego.Error(err)
  461. c.JsonResult(6003, "文档不存在")
  462. }
  463. if c.Member.Role != conf.MemberSuperRole {
  464. rel, err := models.NewRelationship().FindByBookIdAndMemberId(document.BookId, c.Member.MemberId)
  465. if err != nil {
  466. beego.Error(err)
  467. c.JsonResult(6004, "权限不足")
  468. }
  469. if rel.RoleId == conf.BookObserver {
  470. c.JsonResult(6004, "权限不足")
  471. }
  472. }
  473. err = attach.Delete()
  474. if err != nil {
  475. beego.Error(err)
  476. c.JsonResult(6005, "删除失败")
  477. }
  478. c.JsonResult(0, "ok", attach)
  479. }
  480. //删除文档.
  481. func (c *DocumentController) Delete() {
  482. c.Prepare()
  483. identify := c.GetString("identify")
  484. doc_id, err := c.GetInt("doc_id", 0)
  485. book_id := 0
  486. //如果是超级管理员则忽略权限判断
  487. if c.Member.Role == conf.MemberSuperRole {
  488. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  489. if err != nil {
  490. beego.Error("FindByIdentify => ", err)
  491. c.JsonResult(6002, "项目不存在或权限不足")
  492. }
  493. book_id = book.BookId
  494. } else {
  495. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  496. if err != nil || bookResult.RoleId == conf.BookObserver {
  497. beego.Error("FindByIdentify => ", err)
  498. c.JsonResult(6002, "项目不存在或权限不足")
  499. }
  500. book_id = bookResult.BookId
  501. }
  502. if doc_id <= 0 {
  503. c.JsonResult(6001, "参数错误")
  504. }
  505. doc, err := models.NewDocument().Find(doc_id)
  506. if err != nil {
  507. beego.Error("Delete => ", err)
  508. c.JsonResult(6003, "删除失败")
  509. }
  510. //如果文档所属项目错误
  511. if doc.BookId != book_id {
  512. c.JsonResult(6004, "参数错误")
  513. }
  514. //递归删除项目下的文档以及子文档
  515. err = doc.RecursiveDocument(doc.DocumentId)
  516. if err != nil {
  517. c.JsonResult(6005, "删除失败")
  518. }
  519. //重置文档数量统计
  520. models.NewBook().ResetDocumentNumber(doc.BookId)
  521. c.JsonResult(0, "ok")
  522. }
  523. //获取文档内容.
  524. func (c *DocumentController) Content() {
  525. c.Prepare()
  526. identify := c.Ctx.Input.Param(":key")
  527. doc_id, err := c.GetInt("doc_id")
  528. if err != nil {
  529. doc_id, _ = strconv.Atoi(c.Ctx.Input.Param(":id"))
  530. }
  531. book_id := 0
  532. //如果是超级管理员,则忽略权限
  533. if c.Member.Role == conf.MemberSuperRole {
  534. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  535. if err != nil {
  536. c.JsonResult(6002, "项目不存在或权限不足")
  537. }
  538. book_id = book.BookId
  539. } else {
  540. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  541. if err != nil || bookResult.RoleId == conf.BookObserver {
  542. beego.Error("FindByIdentify => ", err)
  543. c.JsonResult(6002, "项目不存在或权限不足")
  544. }
  545. book_id = bookResult.BookId
  546. }
  547. if doc_id <= 0 {
  548. c.JsonResult(6001, "参数错误")
  549. }
  550. if c.Ctx.Input.IsPost() {
  551. markdown := strings.TrimSpace(c.GetString("markdown", ""))
  552. content := c.GetString("html")
  553. version, _ := c.GetInt64("version", 0)
  554. is_cover := c.GetString("cover")
  555. doc, err := models.NewDocument().Find(doc_id)
  556. if err != nil {
  557. c.JsonResult(6003, "读取文档错误")
  558. }
  559. if doc.BookId != book_id {
  560. c.JsonResult(6004, "保存的文档不属于指定项目")
  561. }
  562. if doc.Version != version && !strings.EqualFold(is_cover, "yes") {
  563. beego.Info("%d|", version, doc.Version)
  564. c.JsonResult(6005, "文档已被修改确定要覆盖吗?")
  565. }
  566. history := models.NewDocumentHistory()
  567. history.DocumentId = doc_id
  568. history.Content = doc.Content
  569. history.Markdown = doc.Markdown
  570. history.DocumentName = doc.DocumentName
  571. history.ModifyAt = c.Member.MemberId
  572. history.MemberId = doc.MemberId
  573. history.ParentId = doc.ParentId
  574. history.Version = time.Now().Unix()
  575. history.Action = "modify"
  576. history.ActionName = "修改文档"
  577. if markdown == "" && content != "" {
  578. doc.Markdown = content
  579. } else {
  580. doc.Markdown = markdown
  581. }
  582. doc.Version = time.Now().Unix()
  583. doc.Content = content
  584. if err := doc.InsertOrUpdate(); err != nil {
  585. beego.Error("InsertOrUpdate => ", err)
  586. c.JsonResult(6006, "保存失败")
  587. }
  588. //如果启用了文档历史,则添加历史文档
  589. if c.EnableDocumentHistory {
  590. _,err = history.InsertOrUpdate()
  591. if err != nil {
  592. beego.Error("DocumentHistory InsertOrUpdate => ",err)
  593. }
  594. }
  595. c.JsonResult(0, "ok", doc)
  596. }
  597. doc, err := models.NewDocument().Find(doc_id)
  598. if err != nil {
  599. c.JsonResult(6003, "文档不存在")
  600. }
  601. attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
  602. if err == nil {
  603. doc.AttachList = attach
  604. }
  605. c.JsonResult(0, "ok", doc)
  606. }
  607. //导出文件
  608. func (c *DocumentController) Export() {
  609. c.Prepare()
  610. c.TplName = "document/export.tpl"
  611. identify := c.Ctx.Input.Param(":key")
  612. output := c.GetString("output")
  613. token := c.GetString("token")
  614. if identify == "" {
  615. c.Abort("404")
  616. }
  617. //如果没有开启你们访问则跳转到登录
  618. if !c.EnableAnonymous && c.Member == nil {
  619. c.Redirect(beego.URLFor("AccountController.Login"), 302)
  620. return
  621. }
  622. bookResult := models.NewBookResult()
  623. if c.Member != nil && c.Member.Role == conf.MemberSuperRole {
  624. book, err := models.NewBook().FindByIdentify(identify)
  625. if err != nil {
  626. beego.Error(err)
  627. c.Abort("500")
  628. }
  629. bookResult = book.ToBookResult()
  630. } else {
  631. bookResult = isReadable(identify, token, c)
  632. }
  633. docs, err := models.NewDocument().FindListByBookId(bookResult.BookId)
  634. if err != nil {
  635. beego.Error(err)
  636. c.Abort("500")
  637. }
  638. if output == "pdf" {
  639. exe := beego.AppConfig.String("wkhtmltopdf")
  640. if exe == "" {
  641. c.TplName = "errors/error.tpl"
  642. c.Data["ErrorMessage"] = "没有配置PDF导出程序"
  643. c.Data["ErrorCode"] = 50010
  644. return
  645. }
  646. dpath := "cache/" + bookResult.Identify
  647. os.MkdirAll(dpath, 0766)
  648. pathList := list.New()
  649. RecursiveFun(0, "", dpath, c, bookResult, docs, pathList)
  650. defer os.RemoveAll(dpath)
  651. os.MkdirAll("./cache", 0766)
  652. pdfpath := "cache/" + identify + "_" + c.CruSession.SessionID() + ".pdf"
  653. if _, err := os.Stat(pdfpath); os.IsNotExist(err) {
  654. wkhtmltopdf.SetPath(beego.AppConfig.String("wkhtmltopdf"))
  655. pdfg, err := wkhtmltopdf.NewPDFGenerator()
  656. pdfg.MarginBottom.Set(35)
  657. if err != nil {
  658. beego.Error(err)
  659. c.Abort("500")
  660. }
  661. for e := pathList.Front(); e != nil; e = e.Next() {
  662. if page, ok := e.Value.(string); ok {
  663. pdfg.AddPage(wkhtmltopdf.NewPage(page))
  664. }
  665. }
  666. err = pdfg.Create()
  667. if err != nil {
  668. beego.Error(err)
  669. c.Abort("500")
  670. }
  671. err = pdfg.WriteFile(pdfpath)
  672. if err != nil {
  673. beego.Error(err)
  674. }
  675. }
  676. c.Ctx.Output.Download(pdfpath, identify+".pdf")
  677. defer os.Remove(pdfpath)
  678. c.StopRun()
  679. }
  680. c.Abort("404")
  681. }
  682. //生成项目访问的二维码.
  683. func (c *DocumentController) QrCode() {
  684. c.Prepare()
  685. identify := c.GetString(":key")
  686. book, err := models.NewBook().FindByIdentify(identify)
  687. if err != nil || book.BookId <= 0 {
  688. c.Abort("404")
  689. }
  690. uri := c.BaseUrl() + beego.URLFor("DocumentController.Index", ":key", identify)
  691. code, err := qr.Encode(uri, qr.L, qr.Unicode)
  692. if err != nil {
  693. beego.Error(err)
  694. c.Abort("500")
  695. }
  696. code, err = barcode.Scale(code, 150, 150)
  697. if err != nil {
  698. beego.Error(err)
  699. c.Abort("500")
  700. }
  701. c.Ctx.ResponseWriter.Header().Set("Content-Type", "image/png")
  702. //imgpath := filepath.Join("cache","qrcode",identify + ".png")
  703. err = png.Encode(c.Ctx.ResponseWriter, code)
  704. if err != nil {
  705. beego.Error(err)
  706. c.Abort("500")
  707. }
  708. }
  709. //项目内搜索.
  710. func (c *DocumentController) Search() {
  711. c.Prepare()
  712. identify := c.Ctx.Input.Param(":key")
  713. token := c.GetString("token")
  714. keyword := strings.TrimSpace(c.GetString("keyword"))
  715. if identify == ""{
  716. c.JsonResult(6001,"参数错误")
  717. }
  718. if !c.EnableAnonymous && c.Member == nil {
  719. c.Redirect(beego.URLFor("AccountController.Login"), 302)
  720. return
  721. }
  722. bookResult := isReadable(identify,token,c)
  723. docs,err := models.NewDocumentSearchResult().SearchDocument(keyword,bookResult.BookId)
  724. if err != nil {
  725. beego.Error(err)
  726. c.JsonResult(6002,"搜索结果错误")
  727. }
  728. if len(docs) < 0 {
  729. c.JsonResult(404,"没有数据库")
  730. }
  731. for _,doc := range docs {
  732. doc.BookId = bookResult.BookId
  733. doc.BookName = bookResult.BookName
  734. doc.Description = bookResult.Description
  735. doc.BookIdentify = bookResult.Identify
  736. }
  737. c.JsonResult(0,"ok",docs)
  738. }
  739. //文档历史列表.
  740. func (c *DocumentController) History() {
  741. c.Prepare()
  742. identify := c.GetString("identify")
  743. doc_id, err := c.GetInt("doc_id", 0)
  744. pageIndex, _ := c.GetInt("page", 1)
  745. book_id := 0
  746. //如果是超级管理员则忽略权限判断
  747. if c.Member.Role == conf.MemberSuperRole {
  748. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  749. if err != nil {
  750. beego.Error("FindByIdentify => ", err)
  751. c.JsonResult(6002, "项目不存在或权限不足")
  752. }
  753. book_id = book.BookId
  754. } else {
  755. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  756. if err != nil || bookResult.RoleId == conf.BookObserver {
  757. beego.Error("FindByIdentify => ", err)
  758. c.JsonResult(6002, "项目不存在或权限不足")
  759. }
  760. book_id = bookResult.BookId
  761. }
  762. if doc_id <= 0 {
  763. c.JsonResult(6001, "参数错误")
  764. }
  765. doc, err := models.NewDocument().Find(doc_id)
  766. if err != nil {
  767. beego.Error("Delete => ", err)
  768. c.JsonResult(6003, "获取历史失败")
  769. }
  770. //如果文档所属项目错误
  771. if doc.BookId != book_id {
  772. c.JsonResult(6004, "参数错误")
  773. }
  774. historis,totalCount,err := models.NewDocumentHistory().FindToPager(doc_id,pageIndex,conf.PageSize)
  775. if err != nil {
  776. c.JsonResult(6005,"获取历史失败")
  777. }
  778. var data struct {
  779. PageHtml string `json:"page_html"`
  780. List []*models.DocumentHistorySimpleResult `json:"lists"`
  781. }
  782. data.List = historis
  783. if totalCount > 0 {
  784. html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, conf.PageSize, totalCount)
  785. data.PageHtml = string(html)
  786. }else {
  787. data.PageHtml = ""
  788. }
  789. c.JsonResult(0,"ok",data)
  790. }
  791. //递归生成文档序列数组.
  792. func RecursiveFun(parent_id int, prefix, dpath string, c *DocumentController, book *models.BookResult, docs []*models.Document, paths *list.List) {
  793. for _, item := range docs {
  794. if item.ParentId == parent_id {
  795. name := prefix + strconv.Itoa(item.ParentId) + strconv.Itoa(item.OrderSort) + strconv.Itoa(item.DocumentId)
  796. fpath := dpath + "/" + name + ".html"
  797. paths.PushBack(fpath)
  798. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0777)
  799. if err != nil {
  800. beego.Error(err)
  801. c.Abort("500")
  802. }
  803. html, err := c.ExecuteViewPathTemplate("document/export.tpl", map[string]interface{}{"Model": book, "Lists": item, "BaseUrl": c.BaseUrl()})
  804. if err != nil {
  805. f.Close()
  806. beego.Error(err)
  807. c.Abort("500")
  808. }
  809. //beego.Info(fpath,html)
  810. f.WriteString(html)
  811. f.Close()
  812. for _, sub := range docs {
  813. if sub.ParentId == item.DocumentId {
  814. RecursiveFun(item.DocumentId, name, dpath, c, book, docs, paths)
  815. break
  816. }
  817. }
  818. }
  819. }
  820. }