document.go 31 KB

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