document.go 32 KB

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