document.go 31 KB

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