DocumentController.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  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. if strings.TrimSpace(doc.Release) != "" {
  56. doc.Release += "<div class=\"wiki-bottom\">文档更新时间: " + doc.ModifyTime.Local().Format("2006-01-02 15:04") + "</div>";
  57. }
  58. selected = doc.DocumentId
  59. c.Data["Title"] = doc.DocumentName
  60. c.Data["Content"] = template.HTML(doc.Release)
  61. c.Data["Description"] = utils.AutoSummary(doc.Release, 120)
  62. }
  63. } else {
  64. c.Data["Title"] = "概要"
  65. c.Data["Content"] = template.HTML(blackfriday.Run([]byte(bookResult.Description)))
  66. }
  67. tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, selected)
  68. if err != nil {
  69. if err == orm.ErrNoRows {
  70. c.ShowErrorPage(404, "生成项目文档树时出错")
  71. } else {
  72. beego.Error("生成项目文档树时出错 -> ", err)
  73. c.ShowErrorPage(500, "生成项目文档树时出错")
  74. }
  75. }
  76. c.Data["Model"] = bookResult
  77. c.Data["Result"] = template.HTML(tree)
  78. }
  79. // 阅读文档
  80. func (c *DocumentController) Read() {
  81. c.Prepare()
  82. identify := c.Ctx.Input.Param(":key")
  83. token := c.GetString("token")
  84. id := c.GetString(":id")
  85. c.Data["DocumentId"] = id
  86. if identify == "" || id == "" {
  87. c.ShowErrorPage(404, "项目不存或已删除")
  88. }
  89. // 如果没有开启匿名访问则跳转到登录
  90. if !c.EnableAnonymous && !isUserLoggedIn(c) {
  91. promptUserToLogIn(c)
  92. return
  93. }
  94. bookResult := isReadable(identify, token, c)
  95. c.TplName = fmt.Sprintf("document/%s_read.tpl", bookResult.Theme)
  96. doc := models.NewDocument()
  97. if docId, err := strconv.Atoi(id); err == nil {
  98. doc, err = doc.FromCacheById(docId)
  99. if err != nil {
  100. beego.Error("从缓存中读取文档时失败 ->", err)
  101. c.ShowErrorPage(500, "文档不存在或已删除")
  102. }
  103. } else {
  104. doc, err = doc.FromCacheByIdentify(id, bookResult.BookId)
  105. if err != nil {
  106. if err == orm.ErrNoRows {
  107. c.ShowErrorPage(404, "文档不存在或已删除")
  108. } else {
  109. beego.Error("从缓存查询文档时出错 ->", err)
  110. c.ShowErrorPage(500, "未知异常")
  111. }
  112. }
  113. }
  114. if doc.BookId != bookResult.BookId {
  115. c.ShowErrorPage(404, "文档不存在或已删除")
  116. }
  117. attach, err := models.NewAttachment().FindListByDocumentId(doc.DocumentId)
  118. if err == nil {
  119. doc.AttachList = attach
  120. }
  121. cdnimg := beego.AppConfig.String("cdnimg")
  122. if doc.Release != "" && cdnimg != "" {
  123. query, err := goquery.NewDocumentFromReader(bytes.NewBufferString(doc.Release))
  124. if err != nil {
  125. beego.Error(err)
  126. } else {
  127. query.Find("img").Each(func(i int, contentSelection *goquery.Selection) {
  128. if src, ok := contentSelection.Attr("src"); ok && strings.HasPrefix(src, "/uploads/") {
  129. contentSelection.SetAttr("src", utils.JoinURI(cdnimg, src))
  130. }
  131. })
  132. html, err := query.Html()
  133. if err != nil {
  134. beego.Error(err)
  135. } else {
  136. doc.Release = html
  137. }
  138. }
  139. }
  140. // assemble doc info, added by dandycheung, 2017-12-20
  141. docInfo := ""
  142. docCreator, err := models.NewMember().Find(doc.MemberId)
  143. if err == nil {
  144. docInfo += docCreator.Account
  145. }
  146. docInfo += " 创建于 "
  147. docInfo += doc.CreateTime.Local().Format("2006-01-02 15:04")
  148. if doc.ModifyTime != doc.CreateTime {
  149. docInfo += ";更新于 "
  150. docInfo += doc.ModifyTime.Local().Format("2006-01-02 15:04")
  151. if strings.TrimSpace(doc.Release) != "" {
  152. doc.Release += "<div class=\"wiki-bottom\">文档更新时间: " + doc.ModifyTime.Local().Format("2006-01-02 15:04") + " &nbsp;&nbsp;作者:";
  153. if docCreator != nil {
  154. if docCreator.RealName != "" {
  155. doc.Release += docCreator.RealName
  156. } else {
  157. doc.Release += docCreator.Account
  158. }
  159. }
  160. doc.Release += "</div>"
  161. }
  162. }
  163. if c.IsAjax() {
  164. var data struct {
  165. DocTitle string `json:"doc_title"`
  166. Body string `json:"body"`
  167. Title string `json:"title"`
  168. DocInfo string `json:"doc_info"`
  169. }
  170. data.DocTitle = doc.DocumentName
  171. data.Body = doc.Release
  172. data.Title = doc.DocumentName + " - Powered by MinDoc"
  173. data.DocInfo = docInfo
  174. c.JsonResult(0, "ok", data)
  175. }
  176. tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, doc.DocumentId)
  177. if err != nil && err != orm.ErrNoRows {
  178. beego.Error("生成项目文档树时出错 ->", err)
  179. c.ShowErrorPage(500, "生成项目文档树时出错")
  180. }
  181. c.Data["Description"] = utils.AutoSummary(doc.Release, 120)
  182. c.Data["Model"] = bookResult
  183. c.Data["Result"] = template.HTML(tree)
  184. c.Data["Title"] = doc.DocumentName
  185. c.Data["Info"] = docInfo
  186. c.Data["Content"] = template.HTML(doc.Release)
  187. }
  188. // 编辑文档
  189. func (c *DocumentController) Edit() {
  190. c.Prepare()
  191. identify := c.Ctx.Input.Param(":key")
  192. if identify == "" {
  193. c.ShowErrorPage(404, "无法解析项目标识")
  194. }
  195. bookResult := models.NewBookResult()
  196. var err error
  197. // 如果是超级管理者,则不判断权限
  198. if c.Member.IsAdministrator() {
  199. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  200. if err != nil {
  201. c.JsonResult(6002, "项目不存在或权限不足")
  202. }
  203. bookResult = models.NewBookResult().ToBookResult(*book)
  204. } else {
  205. bookResult, err = models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  206. if err != nil {
  207. if err == orm.ErrNoRows {
  208. c.ShowErrorPage(403, "项目不存在或没有权限")
  209. } else {
  210. beego.Error("查询项目时出错 -> ", err)
  211. c.ShowErrorPage(500, "查询项目时出错")
  212. }
  213. }
  214. if bookResult.RoleId == conf.BookObserver {
  215. c.JsonResult(6002, "项目不存在或权限不足")
  216. }
  217. }
  218. // 根据不同编辑器类型加载编辑器
  219. if bookResult.Editor == "markdown" {
  220. c.TplName = "document/markdown_edit_template.tpl"
  221. } else if bookResult.Editor == "html" {
  222. c.TplName = "document/new_html_edit_template.tpl"
  223. } else {
  224. c.TplName = "document/" + bookResult.Editor + "_edit_template.tpl"
  225. }
  226. c.Data["Model"] = bookResult
  227. r, _ := json.Marshal(bookResult)
  228. c.Data["ModelResult"] = template.JS(string(r))
  229. c.Data["Result"] = template.JS("[]")
  230. trees, err := models.NewDocument().FindDocumentTree(bookResult.BookId)
  231. if err != nil {
  232. beego.Error("FindDocumentTree => ", err)
  233. } else {
  234. if len(trees) > 0 {
  235. if jtree, err := json.Marshal(trees); err == nil {
  236. c.Data["Result"] = template.JS(string(jtree))
  237. }
  238. } else {
  239. c.Data["Result"] = template.JS("[]")
  240. }
  241. }
  242. c.Data["BaiDuMapKey"] = beego.AppConfig.DefaultString("baidumapkey", "")
  243. }
  244. // 创建一个文档
  245. func (c *DocumentController) Create() {
  246. identify := c.GetString("identify")
  247. docIdentify := c.GetString("doc_identify")
  248. docName := c.GetString("doc_name")
  249. parentId, _ := c.GetInt("parent_id", 0)
  250. docId, _ := c.GetInt("doc_id", 0)
  251. if identify == "" {
  252. c.JsonResult(6001, "参数错误")
  253. }
  254. if docName == "" {
  255. c.JsonResult(6004, "文档名称不能为空")
  256. }
  257. bookId := 0
  258. // 如果是超级管理员则不判断权限
  259. if c.Member.IsAdministrator() {
  260. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  261. if err != nil {
  262. beego.Error(err)
  263. c.JsonResult(6002, "项目不存在或权限不足")
  264. }
  265. bookId = book.BookId
  266. } else {
  267. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  268. if err != nil || bookResult.RoleId == conf.BookObserver {
  269. beego.Error("FindByIdentify => ", err)
  270. c.JsonResult(6002, "项目不存在或权限不足")
  271. }
  272. bookId = bookResult.BookId
  273. }
  274. if docIdentify != "" {
  275. if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, docIdentify); !ok || err != nil {
  276. c.JsonResult(6003, "文档标识只能包含小写字母、数字,以及“-”、“.”和“_”符号")
  277. }
  278. d, _ := models.NewDocument().FindByIdentityFirst(docIdentify, bookId)
  279. if d.DocumentId > 0 && d.DocumentId != docId {
  280. c.JsonResult(6006, "文档标识已被使用")
  281. }
  282. }
  283. if parentId > 0 {
  284. doc, err := models.NewDocument().Find(parentId)
  285. if err != nil || doc.BookId != bookId {
  286. c.JsonResult(6003, "父分类不存在")
  287. }
  288. }
  289. document, _ := models.NewDocument().Find(docId)
  290. document.MemberId = c.Member.MemberId
  291. document.BookId = bookId
  292. document.Identify = docIdentify
  293. document.Version = time.Now().Unix()
  294. document.DocumentName = docName
  295. document.ParentId = parentId
  296. if err := document.InsertOrUpdate(); err != nil {
  297. beego.Error("InsertOrUpdate => ", err)
  298. c.JsonResult(6005, "保存失败")
  299. } else {
  300. c.JsonResult(0, "ok", document)
  301. }
  302. }
  303. // 上传附件或图片
  304. func (c *DocumentController) Upload() {
  305. identify := c.GetString("identify")
  306. docId, _ := c.GetInt("doc_id")
  307. isAttach := true
  308. if identify == "" {
  309. c.JsonResult(6001, "参数错误")
  310. }
  311. name := "editormd-file-file"
  312. file, moreFile, err := c.GetFile(name)
  313. if err == http.ErrMissingFile {
  314. name = "editormd-image-file"
  315. file, moreFile, err = c.GetFile(name)
  316. if err == http.ErrMissingFile {
  317. c.JsonResult(6003, "没有发现需要上传的文件")
  318. }
  319. }
  320. if err != nil {
  321. c.JsonResult(6002, err.Error())
  322. }
  323. defer file.Close()
  324. type Size interface {
  325. Size() int64
  326. }
  327. if conf.GetUploadFileSize() > 0 && moreFile.Size > conf.GetUploadFileSize() {
  328. c.JsonResult(6009, "查过文件允许的上传最大值")
  329. }
  330. ext := filepath.Ext(moreFile.Filename)
  331. if ext == "" {
  332. c.JsonResult(6003, "无法解析文件的格式")
  333. }
  334. //如果文件类型设置为 * 标识不限制文件类型
  335. if beego.AppConfig.DefaultString("upload_file_ext", "") != "*" {
  336. if !conf.IsAllowUploadFileExt(ext) {
  337. c.JsonResult(6004, "不允许的文件类型")
  338. }
  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("Attachment Insert => ", 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("SaveToFile => ", 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. }