DocumentController.go 35 KB

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