DocumentController.go 35 KB

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