DocumentController.go 36 KB

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