1
0

document.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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.MarkdownBasic([]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.Find(doc_id)
  138. if err != nil {
  139. beego.Error(err)
  140. c.Abort("500")
  141. }
  142. } else {
  143. doc, err = doc.FindByFieldFirst("identify", 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. doc_id, err := c.GetInt("doc_id")
  574. if err != nil {
  575. doc_id, _ = strconv.Atoi(c.Ctx.Input.Param(":id"))
  576. }
  577. book_id := 0
  578. auto_release := 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. book_id = book.BookId
  586. auto_release = 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. book_id = bookResult.BookId
  594. auto_release = bookResult.AutoRelease
  595. }
  596. if doc_id <= 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. is_cover := c.GetString("cover")
  604. doc, err := models.NewDocument().Find(doc_id)
  605. if err != nil {
  606. c.JsonResult(6003, "读取文档错误")
  607. }
  608. if doc.BookId != book_id {
  609. c.JsonResult(6004, "保存的文档不属于指定项目")
  610. }
  611. if doc.Version != version && !strings.EqualFold(is_cover, "yes") {
  612. beego.Info("%d|", version, doc.Version)
  613. c.JsonResult(6005, "文档已被修改确定要覆盖吗?")
  614. }
  615. history := models.NewDocumentHistory()
  616. history.DocumentId = doc_id
  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 auto_release {
  646. go func(identify string) {
  647. models.NewDocument().ReleaseContent(book_id)
  648. }(identify)
  649. }
  650. c.JsonResult(0, "ok", doc)
  651. }
  652. doc, err := models.NewDocument().Find(doc_id)
  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. func (c *DocumentController) GetDocumentById(id string) (doc *models.Document, err error) {
  663. doc = models.NewDocument()
  664. if doc_id, err := strconv.Atoi(id); err == nil {
  665. doc, err = doc.Find(doc_id)
  666. if err != nil {
  667. return nil, err
  668. }
  669. } else {
  670. doc, err = doc.FindByFieldFirst("identify", id)
  671. if err != nil {
  672. return nil, err
  673. }
  674. }
  675. return doc, nil
  676. }
  677. // 导出
  678. func (c *DocumentController) Export() {
  679. c.Prepare()
  680. c.TplName = "document/export.tpl"
  681. identify := c.Ctx.Input.Param(":key")
  682. if identify == "" {
  683. c.Abort("404")
  684. }
  685. output := c.GetString("output")
  686. token := c.GetString("token")
  687. // 如果没有开启匿名访问则跳转到登录
  688. if !c.EnableAnonymous && !isUserLoggedIn(c) {
  689. promptUserToLogIn(c)
  690. return
  691. }
  692. bookResult := models.NewBookResult()
  693. if c.Member != nil && c.Member.IsAdministrator() {
  694. book, err := models.NewBook().FindByIdentify(identify)
  695. if err != nil {
  696. beego.Error(err)
  697. c.Abort("500")
  698. }
  699. bookResult = models.NewBookResult().ToBookResult(*book)
  700. } else {
  701. bookResult = isReadable(identify, token, c)
  702. }
  703. if !strings.HasPrefix(bookResult.Cover, "http:://") && !strings.HasPrefix(bookResult.Cover, "https:://") {
  704. bookResult.Cover = c.BaseUrl() + bookResult.Cover
  705. }
  706. eBookResult, err := bookResult.Converter(c.CruSession.SessionID())
  707. if err != nil {
  708. beego.Error("转换文档失败:" + bookResult.BookName + " -> " + err.Error())
  709. c.Abort("500")
  710. }
  711. if output == "pdf" {
  712. c.Ctx.Output.Download(eBookResult.PDFPath, bookResult.BookName+".pdf")
  713. c.Abort("200")
  714. } else if output == "epub" {
  715. c.Ctx.Output.Download(eBookResult.EpubPath, bookResult.BookName+".epub")
  716. c.Abort("200")
  717. } else if output == "mobi" {
  718. c.Ctx.Output.Download(eBookResult.MobiPath, bookResult.BookName+".mobi")
  719. c.Abort("200")
  720. } else if output == "docx" {
  721. c.Ctx.Output.Download(eBookResult.WordPath, bookResult.BookName+".docx")
  722. c.Abort("200")
  723. }
  724. c.Abort("404")
  725. }
  726. // 生成项目访问的二维码
  727. func (c *DocumentController) QrCode() {
  728. c.Prepare()
  729. identify := c.GetString(":key")
  730. book, err := models.NewBook().FindByIdentify(identify)
  731. if err != nil || book.BookId <= 0 {
  732. c.Abort("404")
  733. }
  734. uri := c.BaseUrl() + beego.URLFor("DocumentController.Index", ":key", identify)
  735. code, err := qr.Encode(uri, qr.L, qr.Unicode)
  736. if err != nil {
  737. beego.Error(err)
  738. c.Abort("500")
  739. }
  740. code, err = barcode.Scale(code, 150, 150)
  741. if err != nil {
  742. beego.Error(err)
  743. c.Abort("500")
  744. }
  745. c.Ctx.ResponseWriter.Header().Set("Content-Type", "image/png")
  746. // imgpath := filepath.Join("cache","qrcode",identify + ".png")
  747. err = png.Encode(c.Ctx.ResponseWriter, code)
  748. if err != nil {
  749. beego.Error(err)
  750. c.Abort("500")
  751. }
  752. }
  753. // 项目内搜索
  754. func (c *DocumentController) Search() {
  755. c.Prepare()
  756. identify := c.Ctx.Input.Param(":key")
  757. token := c.GetString("token")
  758. keyword := strings.TrimSpace(c.GetString("keyword"))
  759. if identify == "" {
  760. c.JsonResult(6001, "参数错误")
  761. }
  762. if !c.EnableAnonymous && !isUserLoggedIn(c) {
  763. promptUserToLogIn(c)
  764. return
  765. }
  766. bookResult := isReadable(identify, token, c)
  767. docs, err := models.NewDocumentSearchResult().SearchDocument(keyword, bookResult.BookId)
  768. if err != nil {
  769. beego.Error(err)
  770. c.JsonResult(6002, "搜索结果错误")
  771. }
  772. if len(docs) < 0 {
  773. c.JsonResult(404, "没有数据库")
  774. }
  775. for _, doc := range docs {
  776. doc.BookId = bookResult.BookId
  777. doc.BookName = bookResult.BookName
  778. doc.Description = bookResult.Description
  779. doc.BookIdentify = bookResult.Identify
  780. }
  781. c.JsonResult(0, "ok", docs)
  782. }
  783. // 文档历史列表
  784. func (c *DocumentController) History() {
  785. c.Prepare()
  786. c.TplName = "document/history.tpl"
  787. identify := c.GetString("identify")
  788. doc_id, err := c.GetInt("doc_id", 0)
  789. pageIndex, _ := c.GetInt("page", 1)
  790. book_id := 0
  791. // 如果是超级管理员则忽略权限判断
  792. if c.Member.IsAdministrator() {
  793. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  794. if err != nil {
  795. beego.Error("FindByIdentify => ", err)
  796. c.Data["ErrorMessage"] = "项目不存在或权限不足"
  797. return
  798. }
  799. book_id = book.BookId
  800. c.Data["Model"] = book
  801. } else {
  802. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  803. if err != nil || bookResult.RoleId == conf.BookObserver {
  804. beego.Error("FindByIdentify => ", err)
  805. c.Data["ErrorMessage"] = "项目不存在或权限不足"
  806. return
  807. }
  808. book_id = bookResult.BookId
  809. c.Data["Model"] = bookResult
  810. }
  811. if doc_id <= 0 {
  812. c.Data["ErrorMessage"] = "参数错误"
  813. return
  814. }
  815. doc, err := models.NewDocument().Find(doc_id)
  816. if err != nil {
  817. beego.Error("Delete => ", err)
  818. c.Data["ErrorMessage"] = "获取历史失败"
  819. return
  820. }
  821. // 如果文档所属项目错误
  822. if doc.BookId != book_id {
  823. c.Data["ErrorMessage"] = "参数错误"
  824. return
  825. }
  826. historis, totalCount, err := models.NewDocumentHistory().FindToPager(doc_id, pageIndex, conf.PageSize)
  827. if err != nil {
  828. beego.Error("FindToPager => ", err)
  829. c.Data["ErrorMessage"] = "获取历史失败"
  830. return
  831. }
  832. c.Data["List"] = historis
  833. c.Data["PageHtml"] = ""
  834. c.Data["Document"] = doc
  835. if totalCount > 0 {
  836. pager := pagination.NewPagination(c.Ctx.Request,totalCount,conf.PageSize)
  837. c.Data["PageHtml"] = pager.HtmlPages()
  838. }
  839. }
  840. func (c *DocumentController) DeleteHistory() {
  841. c.Prepare()
  842. c.TplName = "document/history.tpl"
  843. identify := c.GetString("identify")
  844. doc_id, err := c.GetInt("doc_id", 0)
  845. history_id, _ := c.GetInt("history_id", 0)
  846. if history_id <= 0 {
  847. c.JsonResult(6001, "参数错误")
  848. }
  849. book_id := 0
  850. // 如果是超级管理员则忽略权限判断
  851. if c.Member.IsAdministrator() {
  852. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  853. if err != nil {
  854. beego.Error("FindByIdentify => ", err)
  855. c.JsonResult(6002, "项目不存在或权限不足")
  856. }
  857. book_id = book.BookId
  858. } else {
  859. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  860. if err != nil || bookResult.RoleId == conf.BookObserver {
  861. beego.Error("FindByIdentify => ", err)
  862. c.JsonResult(6002, "项目不存在或权限不足")
  863. }
  864. book_id = bookResult.BookId
  865. }
  866. if doc_id <= 0 {
  867. c.JsonResult(6001, "参数错误")
  868. }
  869. doc, err := models.NewDocument().Find(doc_id)
  870. if err != nil {
  871. beego.Error("Delete => ", err)
  872. c.JsonResult(6001, "获取历史失败")
  873. }
  874. // 如果文档所属项目错误
  875. if doc.BookId != book_id {
  876. c.JsonResult(6001, "参数错误")
  877. }
  878. err = models.NewDocumentHistory().Delete(history_id, doc_id)
  879. if err != nil {
  880. beego.Error(err)
  881. c.JsonResult(6002, "删除失败")
  882. }
  883. c.JsonResult(0, "ok")
  884. }
  885. func (c *DocumentController) RestoreHistory() {
  886. c.Prepare()
  887. c.TplName = "document/history.tpl"
  888. identify := c.GetString("identify")
  889. doc_id, err := c.GetInt("doc_id", 0)
  890. history_id, _ := c.GetInt("history_id", 0)
  891. if history_id <= 0 {
  892. c.JsonResult(6001, "参数错误")
  893. }
  894. book_id := 0
  895. // 如果是超级管理员则忽略权限判断
  896. if c.Member.IsAdministrator() {
  897. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  898. if err != nil {
  899. beego.Error("FindByIdentify => ", err)
  900. c.JsonResult(6002, "项目不存在或权限不足")
  901. }
  902. book_id = book.BookId
  903. } else {
  904. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  905. if err != nil || bookResult.RoleId == conf.BookObserver {
  906. beego.Error("FindByIdentify => ", err)
  907. c.JsonResult(6002, "项目不存在或权限不足")
  908. }
  909. book_id = bookResult.BookId
  910. }
  911. if doc_id <= 0 {
  912. c.JsonResult(6001, "参数错误")
  913. }
  914. doc, err := models.NewDocument().Find(doc_id)
  915. if err != nil {
  916. beego.Error("Delete => ", err)
  917. c.JsonResult(6001, "获取历史失败")
  918. }
  919. // 如果文档所属项目错误
  920. if doc.BookId != book_id {
  921. c.JsonResult(6001, "参数错误")
  922. }
  923. err = models.NewDocumentHistory().Restore(history_id, doc_id, c.Member.MemberId)
  924. if err != nil {
  925. beego.Error(err)
  926. c.JsonResult(6002, "删除失败")
  927. }
  928. c.JsonResult(0, "ok", doc)
  929. }
  930. func (c *DocumentController) Compare() {
  931. c.Prepare()
  932. c.TplName = "document/compare.tpl"
  933. history_id, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
  934. identify := c.Ctx.Input.Param(":key")
  935. book_id := 0
  936. editor := "markdown"
  937. // 如果是超级管理员则忽略权限判断
  938. if c.Member.IsAdministrator() {
  939. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  940. if err != nil {
  941. beego.Error("DocumentController.Compare => ", err)
  942. c.Abort("403")
  943. return
  944. }
  945. book_id = book.BookId
  946. c.Data["Model"] = book
  947. editor = book.Editor
  948. } else {
  949. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  950. if err != nil || bookResult.RoleId == conf.BookObserver {
  951. beego.Error("FindByIdentify => ", err)
  952. c.Abort("403")
  953. return
  954. }
  955. book_id = bookResult.BookId
  956. c.Data["Model"] = bookResult
  957. editor = bookResult.Editor
  958. }
  959. if history_id <= 0 {
  960. c.ShowErrorPage(60002, "参数错误")
  961. }
  962. history, err := models.NewDocumentHistory().Find(history_id)
  963. if err != nil {
  964. beego.Error("DocumentController.Compare => ", err)
  965. c.ShowErrorPage(60003, err.Error())
  966. }
  967. doc, err := models.NewDocument().Find(history.DocumentId)
  968. if doc.BookId != book_id {
  969. c.ShowErrorPage(60002, "参数错误")
  970. }
  971. c.Data["HistoryId"] = history_id
  972. c.Data["DocumentId"] = doc.DocumentId
  973. if editor == "markdown" {
  974. c.Data["HistoryContent"] = history.Markdown
  975. c.Data["Content"] = doc.Markdown
  976. } else {
  977. c.Data["HistoryContent"] = template.HTML(history.Content)
  978. c.Data["Content"] = template.HTML(doc.Content)
  979. }
  980. }
  981. // 递归生成文档序列数组
  982. func RecursiveFun(parent_id int, prefix, dpath string, c *DocumentController, book *models.BookResult, docs []*models.Document, paths *list.List) {
  983. for _, item := range docs {
  984. if item.ParentId == parent_id {
  985. EachFun(prefix, dpath, c, book, item, paths)
  986. for _, sub := range docs {
  987. if sub.ParentId == item.DocumentId {
  988. prefix += strconv.Itoa(item.ParentId) + strconv.Itoa(item.OrderSort) + strconv.Itoa(item.DocumentId)
  989. RecursiveFun(item.DocumentId, prefix, dpath, c, book, docs, paths)
  990. break
  991. }
  992. }
  993. }
  994. }
  995. }
  996. func EachFun(prefix, dpath string, c *DocumentController, book *models.BookResult, item *models.Document, paths *list.List) {
  997. name := prefix + strconv.Itoa(item.ParentId) + strconv.Itoa(item.OrderSort) + strconv.Itoa(item.DocumentId)
  998. fpath := dpath + "/" + name + ".html"
  999. paths.PushBack(fpath)
  1000. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0777)
  1001. if err != nil {
  1002. beego.Error(err)
  1003. c.Abort("500")
  1004. }
  1005. html, err := c.ExecuteViewPathTemplate("document/export.tpl", map[string]interface{}{"Model": book, "Lists": item, "BaseUrl": c.BaseUrl()})
  1006. if err != nil {
  1007. f.Close()
  1008. beego.Error(err)
  1009. c.Abort("500")
  1010. }
  1011. buf := bytes.NewReader([]byte(html))
  1012. doc, err := goquery.NewDocumentFromReader(buf)
  1013. doc.Find("img").Each(func(i int, contentSelection *goquery.Selection) {
  1014. if src, ok := contentSelection.Attr("src"); ok && strings.HasPrefix(src, "/uploads/") {
  1015. contentSelection.SetAttr("src", c.BaseUrl()+src)
  1016. }
  1017. })
  1018. html, err = doc.Html()
  1019. if err != nil {
  1020. f.Close()
  1021. beego.Error(err)
  1022. c.Abort("500")
  1023. }
  1024. // html = strings.Replace(html, "<img src=\"/uploads", "<img src=\"" + c.BaseUrl() + "/uploads", -1)
  1025. f.WriteString(html)
  1026. f.Close()
  1027. }