document.go 31 KB

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