BlogController.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. package controllers
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "html/template"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/beego/beego/v2/client/orm"
  15. "github.com/beego/beego/v2/core/logs"
  16. "github.com/beego/beego/v2/server/web"
  17. "github.com/beego/i18n"
  18. "github.com/mindoc-org/mindoc/conf"
  19. "github.com/mindoc-org/mindoc/models"
  20. "github.com/mindoc-org/mindoc/utils"
  21. "github.com/mindoc-org/mindoc/utils/pagination"
  22. )
  23. type BlogController struct {
  24. BaseController
  25. }
  26. func (c *BlogController) Prepare() {
  27. c.BaseController.Prepare()
  28. if !c.EnableAnonymous && c.Member == nil {
  29. c.Redirect(conf.URLFor("AccountController.Login")+"?url="+url.PathEscape(conf.BaseUrl+c.Ctx.Request.URL.RequestURI()), 302)
  30. }
  31. }
  32. // 文章阅读
  33. func (c *BlogController) Index() {
  34. c.Prepare()
  35. c.TplName = "blog/index.tpl"
  36. blogId, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
  37. if blogId <= 0 {
  38. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.page_not_existed"))
  39. }
  40. blogReadSession := fmt.Sprintf("blog:read:%d", blogId)
  41. blog, err := models.NewBlog().FindFromCache(blogId)
  42. if err != nil {
  43. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.blog_not_existed"))
  44. }
  45. if c.Ctx.Input.IsPost() {
  46. password := c.GetString("password")
  47. if blog.BlogStatus == "password" && password != blog.Password {
  48. c.JsonResult(6001, i18n.Tr(c.Lang, "message.blog_pwd_incorrect"))
  49. } else if blog.BlogStatus == "password" && password == blog.Password {
  50. // Store the session value for the next GET request.
  51. _ = c.CruSession.Set(context.TODO(), blogReadSession, blogId)
  52. c.JsonResult(0, "OK")
  53. } else {
  54. c.JsonResult(0, "OK")
  55. }
  56. } else if blog.BlogStatus == "password" && c.CruSession.Get(context.TODO(), blogReadSession) == nil && // Read session doesn't exist
  57. (c.Member == nil || (blog.MemberId != c.Member.MemberId && !c.Member.IsAdministrator())) { // User isn't author or administrator
  58. //如果不存在已输入密码的标记
  59. c.TplName = "blog/index_password.tpl"
  60. }
  61. if blog.BlogType != 1 {
  62. //加载文章附件
  63. _ = blog.LinkAttach()
  64. }
  65. c.Data["Model"] = blog
  66. c.Data["Content"] = template.HTML(blog.BlogRelease)
  67. if blog.BlogExcerpt == "" {
  68. c.Data["Description"] = utils.AutoSummary(blog.BlogRelease, 120)
  69. } else {
  70. c.Data["Description"] = blog.BlogExcerpt
  71. }
  72. if nextBlog, err := models.NewBlog().QueryNext(blogId); err == nil {
  73. c.Data["Next"] = nextBlog
  74. }
  75. if preBlog, err := models.NewBlog().QueryPrevious(blogId); err == nil {
  76. c.Data["Previous"] = preBlog
  77. }
  78. }
  79. // 文章列表
  80. func (c *BlogController) List() {
  81. c.Prepare()
  82. c.TplName = "blog/list.tpl"
  83. pageIndex, _ := c.GetInt("page", 1)
  84. var blogList []*models.Blog
  85. var totalCount int
  86. var err error
  87. blogList, totalCount, err = models.NewBlog().FindToPager(pageIndex, conf.PageSize, 0, "")
  88. if err != nil && err != orm.ErrNoRows {
  89. c.ShowErrorPage(500, err.Error())
  90. }
  91. if totalCount > 0 {
  92. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  93. c.Data["PageHtml"] = pager.HtmlPages()
  94. for _, blog := range blogList {
  95. //如果没有添加文章摘要,则自动提取
  96. if blog.BlogExcerpt == "" {
  97. blog.BlogExcerpt = utils.AutoSummary(blog.BlogRelease, 120)
  98. }
  99. blog.Link()
  100. }
  101. } else {
  102. c.Data["PageHtml"] = ""
  103. }
  104. c.Data["Lists"] = blogList
  105. }
  106. // 管理后台文章列表
  107. func (c *BlogController) ManageList() {
  108. c.Prepare()
  109. c.TplName = "blog/manage_list.tpl"
  110. pageIndex, _ := c.GetInt("page", 1)
  111. blogList, totalCount, err := models.NewBlog().FindToPager(pageIndex, conf.PageSize, c.Member.MemberId, "")
  112. if err != nil {
  113. c.ShowErrorPage(500, err.Error())
  114. }
  115. if totalCount > 0 {
  116. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  117. c.Data["PageHtml"] = pager.HtmlPages()
  118. } else {
  119. c.Data["PageHtml"] = ""
  120. }
  121. c.Data["ModelList"] = blogList
  122. }
  123. // 文章设置
  124. func (c *BlogController) ManageSetting() {
  125. c.Prepare()
  126. c.TplName = "blog/manage_setting.tpl"
  127. //如果是post请求
  128. if c.Ctx.Input.IsPost() {
  129. blogId, _ := c.GetInt("id", 0)
  130. blogTitle := c.GetString("title")
  131. blogIdentify := c.GetString("identify")
  132. orderIndex, _ := c.GetInt("order_index", 0)
  133. blogType, _ := c.GetInt("blog_type", 0)
  134. blogExcerpt := c.GetString("excerpt", "")
  135. blogStatus := c.GetString("status", "publish")
  136. blogPassword := c.GetString("password", "")
  137. documentIdentify := strings.TrimSpace(c.GetString("documentIdentify"))
  138. bookIdentify := strings.TrimSpace(c.GetString("bookIdentify"))
  139. documentId := 0
  140. if blogTitle == "" {
  141. c.JsonResult(6001, i18n.Tr(c.Lang, "message.blog_title_empty"))
  142. }
  143. if strings.Count(blogExcerpt, "") > 500 {
  144. c.JsonResult(6008, i18n.Tr(c.Lang, "message.blog_digest_tips"))
  145. }
  146. if blogStatus != "public" && blogStatus != "password" && blogStatus != "draft" {
  147. blogStatus = "public"
  148. }
  149. if blogStatus == "password" && blogPassword == "" {
  150. c.JsonResult(6010, i18n.Tr(c.Lang, "message.set_pwd_pls"))
  151. }
  152. if blogType != 0 && blogType != 1 {
  153. c.JsonResult(6005, i18n.Tr(c.Lang, "message.unknown_blog_type"))
  154. }
  155. if strings.Count(blogTitle, "") > 200 {
  156. c.JsonResult(6002, i18n.Tr(c.Lang, "message.blog_title_tips"))
  157. }
  158. //如果是关联文章,需要同步关联的文档
  159. if blogType == 1 {
  160. book, err := models.NewBook().FindByIdentify(bookIdentify)
  161. if err != nil {
  162. c.JsonResult(6011, i18n.Tr(c.Lang, "message.ref_doc_not_exist_or_no_permit"))
  163. }
  164. doc, err := models.NewDocument().FindByIdentityFirst(documentIdentify, book.BookId)
  165. if err != nil {
  166. c.JsonResult(6003, i18n.Tr(c.Lang, "message.query_failed"))
  167. }
  168. documentId = doc.DocumentId
  169. // 如果不是超级管理员,则校验权限
  170. if !c.Member.IsAdministrator() {
  171. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  172. if err != nil || bookResult.RoleId == conf.BookObserver {
  173. c.JsonResult(6002, i18n.Tr(c.Lang, "message.ref_doc_not_exist_or_no_permit"))
  174. }
  175. }
  176. }
  177. var blog *models.Blog
  178. var err error
  179. //如果文章ID存在,则从数据库中查询文章
  180. if blogId > 0 {
  181. if c.Member.IsAdministrator() {
  182. blog, err = models.NewBlog().Find(blogId)
  183. } else {
  184. blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  185. }
  186. if err != nil {
  187. c.JsonResult(6003, i18n.Tr(c.Lang, "message.blog_not_exist"))
  188. }
  189. //如果设置了文章标识
  190. if blogIdentify != "" {
  191. //如果查询到的文章标识存在并且不是当前文章的id
  192. if b, err := models.NewBlog().FindByIdentify(blogIdentify); err == nil && b.BlogId != blogId {
  193. c.JsonResult(6004, i18n.Tr(c.Lang, "message.blog_id_existed"))
  194. }
  195. }
  196. blog.Modified = time.Now()
  197. blog.ModifyAt = c.Member.MemberId
  198. } else {
  199. //如果设置了文章标识
  200. if blogIdentify != "" {
  201. if models.NewBlog().IsExist(blogIdentify) {
  202. c.JsonResult(6004, i18n.Tr(c.Lang, "message.blog_id_existed"))
  203. }
  204. }
  205. blog = models.NewBlog()
  206. blog.MemberId = c.Member.MemberId
  207. blog.Created = time.Now()
  208. }
  209. if blogIdentify == "" {
  210. blog.BlogIdentify = fmt.Sprintf("%s-%d", "post", time.Now().UnixNano())
  211. } else {
  212. blog.BlogIdentify = blogIdentify
  213. }
  214. blog.BlogTitle = blogTitle
  215. blog.OrderIndex = orderIndex
  216. blog.BlogType = blogType
  217. if blogType == 1 {
  218. blog.DocumentId = documentId
  219. }
  220. blog.BlogExcerpt = blogExcerpt
  221. blog.BlogStatus = blogStatus
  222. blog.Password = blogPassword
  223. if err := blog.Save(); err != nil {
  224. logs.Error("保存文章失败 -> ", err)
  225. c.JsonResult(6011, i18n.Tr(c.Lang, "message.failed"))
  226. } else {
  227. c.JsonResult(0, "ok", blog)
  228. }
  229. }
  230. if c.Ctx.Input.Referer() == "" {
  231. c.Data["Referer"] = "javascript:history.back();"
  232. } else {
  233. c.Data["Referer"] = c.Ctx.Input.Referer()
  234. }
  235. blogId, err := strconv.Atoi(c.Ctx.Input.Param(":id"))
  236. c.Data["DocumentIdentify"] = ""
  237. if err == nil {
  238. blog, err := models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  239. if err != nil {
  240. c.ShowErrorPage(500, err.Error())
  241. }
  242. c.Data["Model"] = blog
  243. } else {
  244. c.Data["Model"] = models.NewBlog()
  245. }
  246. }
  247. // 文章创建或编辑
  248. func (c *BlogController) ManageEdit() {
  249. c.Prepare()
  250. c.TplName = "blog/manage_edit.tpl"
  251. if c.Ctx.Input.IsPost() {
  252. blogId, _ := c.GetInt("blogId", 0)
  253. if blogId <= 0 {
  254. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  255. }
  256. blogContent := c.GetString("content", "")
  257. blogHtml := c.GetString("htmlContent", "")
  258. version, _ := c.GetInt64("version", 0)
  259. cover := c.GetString("cover")
  260. var blog *models.Blog
  261. var err error
  262. if c.Member.IsAdministrator() {
  263. blog, err = models.NewBlog().Find(blogId)
  264. } else {
  265. blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  266. }
  267. if err != nil {
  268. logs.Error("查询文章失败 ->", err)
  269. c.JsonResult(6002, i18n.Tr(c.Lang, "message.query_failed"))
  270. }
  271. if version > 0 && blog.Version != version && cover != "yes" {
  272. c.JsonResult(6005, i18n.Tr(c.Lang, "message.blog_has_modified"))
  273. }
  274. //如果是关联文章,需要同步关联的文档
  275. if blog.BlogType == 1 {
  276. doc, err := models.NewDocument().Find(blog.DocumentId)
  277. if err != nil {
  278. logs.Error("查询关联项目文档时出错 ->", err)
  279. c.JsonResult(6003, i18n.Tr(c.Lang, "message.query_failed"))
  280. }
  281. book, err := models.NewBook().Find(doc.BookId)
  282. if err != nil {
  283. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  284. }
  285. // 如果不是超级管理员,则校验权限
  286. if !c.Member.IsAdministrator() {
  287. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  288. if err != nil || bookResult.RoleId == conf.BookObserver {
  289. logs.Error("FindByIdentify => ", err)
  290. c.JsonResult(6002, i18n.Tr(c.Lang, "message.ref_doc_not_exist_or_no_permit"))
  291. }
  292. }
  293. doc.Markdown = blogContent
  294. doc.Release = blogHtml
  295. doc.Content = blogHtml
  296. doc.ModifyTime = time.Now()
  297. doc.ModifyAt = c.Member.MemberId
  298. if err := doc.InsertOrUpdate("markdown", "release", "content", "modify_time", "modify_at"); err != nil {
  299. logs.Error("保存关联文档时出错 ->", err)
  300. c.JsonResult(6004, i18n.Tr(c.Lang, "message.failed"))
  301. }
  302. }
  303. blog.BlogContent = blogContent
  304. blog.BlogRelease = blogHtml
  305. blog.ModifyAt = c.Member.MemberId
  306. blog.Modified = time.Now()
  307. if err := blog.Save("blog_content", "blog_release", "modify_at", "modify_time", "version"); err != nil {
  308. logs.Error("保存文章失败 -> ", err)
  309. c.JsonResult(6011, i18n.Tr(c.Lang, "message.failed"))
  310. } else {
  311. c.JsonResult(0, "ok", blog)
  312. }
  313. }
  314. blogId, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
  315. if blogId <= 0 {
  316. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.param_error"))
  317. }
  318. var blog *models.Blog
  319. var err error
  320. if c.Member.IsAdministrator() {
  321. blog, err = models.NewBlog().Find(blogId)
  322. } else {
  323. blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  324. }
  325. if err != nil {
  326. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.blog_not_exist"))
  327. }
  328. blog.LinkAttach()
  329. if len(blog.AttachList) > 0 {
  330. returnJSON, err := json.Marshal(blog.AttachList)
  331. if err != nil {
  332. logs.Error("序列化文章附件时出错 ->", err)
  333. } else {
  334. c.Data["AttachList"] = template.JS(string(returnJSON))
  335. }
  336. } else {
  337. c.Data["AttachList"] = template.JS("[]")
  338. }
  339. if conf.GetUploadFileSize() > 0 {
  340. c.Data["UploadFileSize"] = conf.GetUploadFileSize()
  341. } else {
  342. c.Data["UploadFileSize"] = "undefined"
  343. }
  344. c.Data["Model"] = blog
  345. }
  346. // 删除文章
  347. func (c *BlogController) ManageDelete() {
  348. c.Prepare()
  349. blogId, _ := c.GetInt("blog_id", 0)
  350. if blogId <= 0 {
  351. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  352. }
  353. var blog *models.Blog
  354. var err error
  355. if c.Member.IsAdministrator() {
  356. blog, err = models.NewBlog().Find(blogId)
  357. } else {
  358. blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  359. }
  360. if err != nil {
  361. c.JsonResult(6002, i18n.Tr(c.Lang, "message.blog_not_exist"))
  362. }
  363. if err := blog.Delete(blogId); err != nil {
  364. c.JsonResult(6003, i18n.Tr(c.Lang, "message.failed"))
  365. } else {
  366. c.JsonResult(0, i18n.Tr(c.Lang, "message.success"))
  367. }
  368. }
  369. // 上传附件或图片
  370. func (c *BlogController) Upload() {
  371. c.Prepare()
  372. blogId, _ := c.GetInt("blogId")
  373. if blogId <= 0 {
  374. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  375. }
  376. blog, err := models.NewBlog().Find(blogId)
  377. if err != nil {
  378. c.JsonResult(6010, i18n.Tr(c.Lang, "message.blog_not_exist"))
  379. }
  380. if !c.Member.IsAdministrator() && blog.MemberId != c.Member.MemberId {
  381. c.JsonResult(6011, i18n.Tr(c.Lang, "message.no_permission"))
  382. }
  383. name := "editormd-file-file"
  384. file, moreFile, err := c.GetFile(name)
  385. if err == http.ErrMissingFile {
  386. name = "editormd-image-file"
  387. file, moreFile, err = c.GetFile(name)
  388. if err == http.ErrMissingFile {
  389. c.JsonResult(6003, i18n.Tr(c.Lang, "message.upload_file_empty"))
  390. }
  391. }
  392. if err != nil {
  393. c.JsonResult(6002, err.Error())
  394. }
  395. defer file.Close()
  396. type Size interface {
  397. Size() int64
  398. }
  399. if conf.GetUploadFileSize() > 0 && moreFile.Size > conf.GetUploadFileSize() {
  400. c.JsonResult(6009, i18n.Tr(c.Lang, "message.upload_file_size_limit"))
  401. }
  402. ext := filepath.Ext(moreFile.Filename)
  403. if ext == "" {
  404. c.JsonResult(6003, i18n.Tr(c.Lang, "message.upload_file_type_error"))
  405. }
  406. //如果文件类型设置为 * 标识不限制文件类型
  407. if web.AppConfig.DefaultString("upload_file_ext", "") != "*" {
  408. if !conf.IsAllowUploadFileExt(ext) {
  409. c.JsonResult(6004, i18n.Tr(c.Lang, "message.upload_file_type_error"))
  410. }
  411. }
  412. // 如果是超级管理员,则不判断权限
  413. if c.Member.IsAdministrator() {
  414. _, err := models.NewBlog().Find(blogId)
  415. if err != nil {
  416. c.JsonResult(6006, i18n.Tr(c.Lang, "message.doc_not_exist_or_no_permit"))
  417. }
  418. } else {
  419. _, err := models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  420. if err != nil {
  421. logs.Error("查询文章时出错 -> ", err)
  422. if err == orm.ErrNoRows {
  423. c.JsonResult(6006, i18n.Tr(c.Lang, "message.no_permission"))
  424. }
  425. c.JsonResult(6001, err.Error())
  426. }
  427. }
  428. fileName := "attach_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  429. filePath := filepath.Join(conf.WorkingDirectory, "uploads", "blog", time.Now().Format("200601"), fileName+ext)
  430. path := filepath.Dir(filePath)
  431. os.MkdirAll(path, os.ModePerm)
  432. err = c.SaveToFile(name, filePath)
  433. if err != nil {
  434. logs.Error("SaveToFile => ", err)
  435. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  436. }
  437. var httpPath string
  438. result := make(map[string]interface{})
  439. //如果是图片,则当做内置图片处理,否则当做附件处理
  440. if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") || strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".gif") {
  441. httpPath = "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
  442. if strings.HasPrefix(httpPath, "//") {
  443. httpPath = conf.URLForWithCdnImage(string(httpPath[1:]))
  444. }
  445. } else {
  446. attachment := models.NewAttachment()
  447. attachment.BookId = 0
  448. attachment.FileName = moreFile.Filename
  449. attachment.CreateAt = c.Member.MemberId
  450. attachment.FileExt = ext
  451. attachment.FilePath = strings.TrimPrefix(filePath, conf.WorkingDirectory)
  452. attachment.DocumentId = blogId
  453. //如果是关联文章,则将附件设置为关联文档的文档上
  454. if blog.BlogType == 1 {
  455. attachment.BookId = blog.BookId
  456. attachment.DocumentId = blog.DocumentId
  457. }
  458. if fileInfo, err := os.Stat(filePath); err == nil {
  459. attachment.FileSize = float64(fileInfo.Size())
  460. }
  461. attachment.HttpPath = httpPath
  462. if err := attachment.Insert(); err != nil {
  463. os.Remove(filePath)
  464. logs.Error("保存文件附件失败 -> ", err)
  465. c.JsonResult(6006, i18n.Tr(c.Lang, "message.failed"))
  466. }
  467. if attachment.HttpPath == "" {
  468. attachment.HttpPath = conf.URLForNotHost("BlogController.Download", ":id", blogId, ":attach_id", attachment.AttachmentId)
  469. if err := attachment.Update(); err != nil {
  470. logs.Error("保存文件失败 -> ", attachment.FilePath, err)
  471. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  472. }
  473. }
  474. result["attach"] = attachment
  475. }
  476. result["errcode"] = 0
  477. result["success"] = 1
  478. result["message"] = "ok"
  479. result["url"] = httpPath
  480. result["alt"] = fileName
  481. c.Ctx.Output.JSON(result, true, false)
  482. c.StopRun()
  483. }
  484. // 删除附件
  485. func (c *BlogController) RemoveAttachment() {
  486. c.Prepare()
  487. attachId, _ := c.GetInt("attach_id")
  488. blogId, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
  489. if attachId <= 0 {
  490. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  491. }
  492. blog, err := models.NewBlog().Find(blogId)
  493. if err != nil {
  494. if err == orm.ErrNoRows {
  495. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.doc_not_exist"))
  496. } else {
  497. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.query_failed"))
  498. }
  499. }
  500. attach, err := models.NewAttachment().Find(attachId)
  501. if err != nil {
  502. logs.Error(err)
  503. c.JsonResult(6002, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  504. }
  505. if !c.Member.IsAdministrator() {
  506. _, err := models.NewBlog().FindByIdAndMemberId(attach.DocumentId, c.Member.MemberId)
  507. if err != nil {
  508. logs.Error(err)
  509. c.JsonResult(6003, i18n.Tr(c.Lang, "message.doc_not_exist"))
  510. }
  511. }
  512. if blog.BlogType == 1 && attach.BookId != blog.BookId && attach.DocumentId != blog.DocumentId {
  513. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  514. } else if attach.BookId != 0 || attach.DocumentId != blogId {
  515. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  516. }
  517. if err := attach.Delete(); err != nil {
  518. logs.Error(err)
  519. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  520. }
  521. os.Remove(filepath.Join(conf.WorkingDirectory, attach.FilePath))
  522. c.JsonResult(0, "ok", attach)
  523. }
  524. // 下载附件
  525. func (c *BlogController) Download() {
  526. c.Prepare()
  527. blogId, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
  528. attachId, _ := strconv.Atoi(c.Ctx.Input.Param(":attach_id"))
  529. password := c.GetString("password")
  530. blog, err := models.NewBlog().Find(blogId)
  531. if err != nil {
  532. if err == orm.ErrNoRows {
  533. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.doc_not_exist"))
  534. } else {
  535. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.query_failed"))
  536. }
  537. }
  538. blogReadSession := fmt.Sprintf("blog:read:%d", blogId)
  539. //如果没有启动匿名访问,或者设置了访问密码
  540. if (c.Member == nil && !c.EnableAnonymous) || (blog.BlogStatus == "password" && password != blog.Password && c.CruSession.Get(context.TODO(), blogReadSession) == nil) {
  541. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  542. }
  543. // 查找附件
  544. attachment, err := models.NewAttachment().Find(attachId)
  545. if err != nil {
  546. if err == orm.ErrNoRows {
  547. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  548. } else {
  549. logs.Error("查询附件时出现异常 -> ", err)
  550. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.query_failed"))
  551. }
  552. }
  553. //如果是链接的文章,需要校验文档ID是否一致,如果不是,需要保证附件的项目ID为0且文档的ID等于博文ID
  554. if blog.BlogType == 1 && attachment.DocumentId != blog.DocumentId {
  555. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  556. } else if blog.BlogType != 1 && (attachment.BookId != 0 || attachment.DocumentId != blogId) {
  557. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  558. }
  559. c.Ctx.Output.Download(filepath.Join(conf.WorkingDirectory, attachment.FilePath), attachment.FileName)
  560. c.StopRun()
  561. }