1
0

BlogController.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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, "all")
  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 c.Member.Role == conf.MemberReaderRole {
  141. c.JsonResult(6001, i18n.Tr(c.Lang, "message.no_permission"))
  142. }
  143. if blogTitle == "" {
  144. c.JsonResult(6001, i18n.Tr(c.Lang, "message.blog_title_empty"))
  145. }
  146. if strings.Count(blogExcerpt, "") > 500 {
  147. c.JsonResult(6008, i18n.Tr(c.Lang, "message.blog_digest_tips"))
  148. }
  149. if blogStatus != "private" && blogStatus != "public" && blogStatus != "password" && blogStatus != "draft" {
  150. blogStatus = "public"
  151. }
  152. if blogStatus == "password" && blogPassword == "" {
  153. c.JsonResult(6010, i18n.Tr(c.Lang, "message.set_pwd_pls"))
  154. }
  155. if blogType != 0 && blogType != 1 {
  156. c.JsonResult(6005, i18n.Tr(c.Lang, "message.unknown_blog_type"))
  157. }
  158. if strings.Count(blogTitle, "") > 200 {
  159. c.JsonResult(6002, i18n.Tr(c.Lang, "message.blog_title_tips"))
  160. }
  161. //如果是关联文章,需要同步关联的文档
  162. if blogType == 1 {
  163. book, err := models.NewBook().FindByIdentify(bookIdentify)
  164. if err != nil {
  165. c.JsonResult(6011, i18n.Tr(c.Lang, "message.ref_doc_not_exist_or_no_permit"))
  166. }
  167. doc, err := models.NewDocument().FindByIdentityFirst(documentIdentify, book.BookId)
  168. if err != nil {
  169. c.JsonResult(6003, i18n.Tr(c.Lang, "message.query_failed"))
  170. }
  171. documentId = doc.DocumentId
  172. // 如果不是超级管理员,则校验权限
  173. if !c.Member.IsAdministrator() {
  174. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  175. if err != nil || bookResult.RoleId == conf.BookObserver {
  176. c.JsonResult(6002, i18n.Tr(c.Lang, "message.ref_doc_not_exist_or_no_permit"))
  177. }
  178. }
  179. }
  180. var blog *models.Blog
  181. var err error
  182. //如果文章ID存在,则从数据库中查询文章
  183. if blogId > 0 {
  184. if c.Member.IsAdministrator() {
  185. blog, err = models.NewBlog().Find(blogId)
  186. } else {
  187. blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  188. }
  189. if err != nil {
  190. c.JsonResult(6003, i18n.Tr(c.Lang, "message.blog_not_exist"))
  191. }
  192. //如果设置了文章标识
  193. if blogIdentify != "" {
  194. //如果查询到的文章标识存在并且不是当前文章的id
  195. if b, err := models.NewBlog().FindByIdentify(blogIdentify); err == nil && b.BlogId != blogId {
  196. c.JsonResult(6004, i18n.Tr(c.Lang, "message.blog_id_existed"))
  197. }
  198. }
  199. blog.Modified = time.Now()
  200. blog.ModifyAt = c.Member.MemberId
  201. } else {
  202. //如果设置了文章标识
  203. if blogIdentify != "" {
  204. if models.NewBlog().IsExist(blogIdentify) {
  205. c.JsonResult(6004, i18n.Tr(c.Lang, "message.blog_id_existed"))
  206. }
  207. }
  208. blog = models.NewBlog()
  209. blog.MemberId = c.Member.MemberId
  210. blog.Created = time.Now()
  211. }
  212. if blogIdentify == "" {
  213. blog.BlogIdentify = fmt.Sprintf("%s-%d", "post", time.Now().UnixNano())
  214. } else {
  215. blog.BlogIdentify = blogIdentify
  216. }
  217. blog.BlogTitle = blogTitle
  218. blog.OrderIndex = orderIndex
  219. blog.BlogType = blogType
  220. if blogType == 1 {
  221. blog.DocumentId = documentId
  222. }
  223. blog.BlogExcerpt = blogExcerpt
  224. blog.BlogStatus = blogStatus
  225. blog.Password = blogPassword
  226. if err := blog.Save(); err != nil {
  227. logs.Error("保存文章失败 -> ", err)
  228. c.JsonResult(6011, i18n.Tr(c.Lang, "message.failed"))
  229. } else {
  230. c.JsonResult(0, "ok", blog)
  231. }
  232. }
  233. if c.Ctx.Input.Referer() == "" {
  234. c.Data["Referer"] = "javascript:history.back();"
  235. } else {
  236. c.Data["Referer"] = c.Ctx.Input.Referer()
  237. }
  238. blogId, err := strconv.Atoi(c.Ctx.Input.Param(":id"))
  239. c.Data["DocumentIdentify"] = ""
  240. if err == nil {
  241. blog, err := models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  242. if err != nil {
  243. c.ShowErrorPage(500, err.Error())
  244. }
  245. c.Data["Model"] = blog
  246. } else {
  247. c.Data["Model"] = models.NewBlog()
  248. }
  249. }
  250. // 文章创建或编辑
  251. func (c *BlogController) ManageEdit() {
  252. c.Prepare()
  253. c.TplName = "blog/manage_edit.tpl"
  254. if c.Member.Role == conf.MemberReaderRole {
  255. c.JsonResult(6001, i18n.Tr(c.Lang, "message.no_permission"))
  256. }
  257. if c.Ctx.Input.IsPost() {
  258. blogId, _ := c.GetInt("blogId", 0)
  259. if blogId <= 0 {
  260. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  261. }
  262. blogContent := c.GetString("content", "")
  263. blogHtml := c.GetString("htmlContent", "")
  264. version, _ := c.GetInt64("version", 0)
  265. cover := c.GetString("cover")
  266. var blog *models.Blog
  267. var err error
  268. if c.Member.IsAdministrator() {
  269. blog, err = models.NewBlog().Find(blogId)
  270. } else {
  271. blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  272. }
  273. if err != nil {
  274. logs.Error("查询文章失败 ->", err)
  275. c.JsonResult(6002, i18n.Tr(c.Lang, "message.query_failed"))
  276. }
  277. if version > 0 && blog.Version != version && cover != "yes" {
  278. c.JsonResult(6005, i18n.Tr(c.Lang, "message.blog_has_modified"))
  279. }
  280. //如果是关联文章,需要同步关联的文档
  281. if blog.BlogType == 1 {
  282. doc, err := models.NewDocument().Find(blog.DocumentId)
  283. if err != nil {
  284. logs.Error("查询关联项目文档时出错 ->", err)
  285. c.JsonResult(6003, i18n.Tr(c.Lang, "message.query_failed"))
  286. }
  287. book, err := models.NewBook().Find(doc.BookId)
  288. if err != nil {
  289. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  290. }
  291. // 如果不是超级管理员,则校验权限
  292. if !c.Member.IsAdministrator() {
  293. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  294. if err != nil || bookResult.RoleId == conf.BookObserver {
  295. logs.Error("FindByIdentify => ", err)
  296. c.JsonResult(6002, i18n.Tr(c.Lang, "message.ref_doc_not_exist_or_no_permit"))
  297. }
  298. }
  299. doc.Markdown = blogContent
  300. doc.Release = blogHtml
  301. doc.Content = blogHtml
  302. doc.ModifyTime = time.Now()
  303. doc.ModifyAt = c.Member.MemberId
  304. if err := doc.InsertOrUpdate("markdown", "release", "content", "modify_time", "modify_at"); err != nil {
  305. logs.Error("保存关联文档时出错 ->", err)
  306. c.JsonResult(6004, i18n.Tr(c.Lang, "message.failed"))
  307. }
  308. }
  309. blog.BlogContent = blogContent
  310. blog.BlogRelease = blogHtml
  311. blog.ModifyAt = c.Member.MemberId
  312. blog.Modified = time.Now()
  313. if err := blog.Save("blog_content", "blog_release", "modify_at", "modify_time", "version"); err != nil {
  314. logs.Error("保存文章失败 -> ", err)
  315. c.JsonResult(6011, i18n.Tr(c.Lang, "message.failed"))
  316. } else {
  317. c.JsonResult(0, "ok", blog)
  318. }
  319. }
  320. blogId, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
  321. if blogId <= 0 {
  322. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.param_error"))
  323. }
  324. var blog *models.Blog
  325. var err error
  326. if c.Member.IsAdministrator() {
  327. blog, err = models.NewBlog().Find(blogId)
  328. } else {
  329. blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  330. }
  331. if err != nil {
  332. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.blog_not_exist"))
  333. }
  334. blog.LinkAttach()
  335. if len(blog.AttachList) > 0 {
  336. returnJSON, err := json.Marshal(blog.AttachList)
  337. if err != nil {
  338. logs.Error("序列化文章附件时出错 ->", err)
  339. } else {
  340. c.Data["AttachList"] = template.JS(string(returnJSON))
  341. }
  342. } else {
  343. c.Data["AttachList"] = template.JS("[]")
  344. }
  345. if conf.GetUploadFileSize() > 0 {
  346. c.Data["UploadFileSize"] = conf.GetUploadFileSize()
  347. } else {
  348. c.Data["UploadFileSize"] = "undefined"
  349. }
  350. c.Data["Model"] = blog
  351. }
  352. // 删除文章
  353. func (c *BlogController) ManageDelete() {
  354. c.Prepare()
  355. blogId, _ := c.GetInt("blog_id", 0)
  356. if blogId <= 0 {
  357. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  358. }
  359. var blog *models.Blog
  360. var err error
  361. if c.Member.IsAdministrator() {
  362. blog, err = models.NewBlog().Find(blogId)
  363. } else {
  364. blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  365. }
  366. if err != nil {
  367. c.JsonResult(6002, i18n.Tr(c.Lang, "message.blog_not_exist"))
  368. }
  369. if err := blog.Delete(blogId); err != nil {
  370. c.JsonResult(6003, i18n.Tr(c.Lang, "message.failed"))
  371. } else {
  372. c.JsonResult(0, i18n.Tr(c.Lang, "message.success"))
  373. }
  374. }
  375. // 上传附件或图片
  376. func (c *BlogController) Upload() {
  377. c.Prepare()
  378. blogId, _ := c.GetInt("blogId")
  379. if blogId <= 0 {
  380. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  381. }
  382. blog, err := models.NewBlog().Find(blogId)
  383. if err != nil {
  384. c.JsonResult(6010, i18n.Tr(c.Lang, "message.blog_not_exist"))
  385. }
  386. if !c.Member.IsAdministrator() && blog.MemberId != c.Member.MemberId {
  387. c.JsonResult(6011, i18n.Tr(c.Lang, "message.no_permission"))
  388. }
  389. name := "editormd-file-file"
  390. file, moreFile, err := c.GetFile(name)
  391. if err == http.ErrMissingFile {
  392. name = "editormd-image-file"
  393. file, moreFile, err = c.GetFile(name)
  394. if err == http.ErrMissingFile {
  395. c.JsonResult(6003, i18n.Tr(c.Lang, "message.upload_file_empty"))
  396. }
  397. }
  398. if err != nil {
  399. c.JsonResult(6002, err.Error())
  400. }
  401. defer file.Close()
  402. type Size interface {
  403. Size() int64
  404. }
  405. if conf.GetUploadFileSize() > 0 && moreFile.Size > conf.GetUploadFileSize() {
  406. c.JsonResult(6009, i18n.Tr(c.Lang, "message.upload_file_size_limit"))
  407. }
  408. ext := filepath.Ext(moreFile.Filename)
  409. if ext == "" {
  410. c.JsonResult(6003, i18n.Tr(c.Lang, "message.upload_file_type_error"))
  411. }
  412. //如果文件类型设置为 * 标识不限制文件类型
  413. if web.AppConfig.DefaultString("upload_file_ext", "") != "*" {
  414. if !conf.IsAllowUploadFileExt(ext) {
  415. c.JsonResult(6004, i18n.Tr(c.Lang, "message.upload_file_type_error"))
  416. }
  417. }
  418. // 如果是超级管理员,则不判断权限
  419. if c.Member.IsAdministrator() {
  420. _, err := models.NewBlog().Find(blogId)
  421. if err != nil {
  422. c.JsonResult(6006, i18n.Tr(c.Lang, "message.doc_not_exist_or_no_permit"))
  423. }
  424. } else {
  425. _, err := models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
  426. if err != nil {
  427. logs.Error("查询文章时出错 -> ", err)
  428. if err == orm.ErrNoRows {
  429. c.JsonResult(6006, i18n.Tr(c.Lang, "message.no_permission"))
  430. }
  431. c.JsonResult(6001, err.Error())
  432. }
  433. }
  434. fileName := "attach_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  435. filePath := filepath.Join(conf.WorkingDirectory, "uploads", "blog", time.Now().Format("200601"), fileName+ext)
  436. path := filepath.Dir(filePath)
  437. os.MkdirAll(path, os.ModePerm)
  438. err = c.SaveToFile(name, filePath)
  439. if err != nil {
  440. logs.Error("SaveToFile => ", err)
  441. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  442. }
  443. var httpPath string
  444. result := make(map[string]interface{})
  445. //如果是图片,则当做内置图片处理,否则当做附件处理
  446. if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") || strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".gif") {
  447. httpPath = "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
  448. if strings.HasPrefix(httpPath, "//") {
  449. httpPath = conf.URLForWithCdnImage(string(httpPath[1:]))
  450. }
  451. } else {
  452. attachment := models.NewAttachment()
  453. attachment.BookId = 0
  454. attachment.FileName = moreFile.Filename
  455. attachment.CreateAt = c.Member.MemberId
  456. attachment.FileExt = ext
  457. attachment.FilePath = strings.TrimPrefix(filePath, conf.WorkingDirectory)
  458. attachment.DocumentId = blogId
  459. //如果是关联文章,则将附件设置为关联文档的文档上
  460. if blog.BlogType == 1 {
  461. attachment.BookId = blog.BookId
  462. attachment.DocumentId = blog.DocumentId
  463. }
  464. if fileInfo, err := os.Stat(filePath); err == nil {
  465. attachment.FileSize = float64(fileInfo.Size())
  466. }
  467. attachment.HttpPath = httpPath
  468. if err := attachment.Insert(); err != nil {
  469. os.Remove(filePath)
  470. logs.Error("保存文件附件失败 -> ", err)
  471. c.JsonResult(6006, i18n.Tr(c.Lang, "message.failed"))
  472. }
  473. if attachment.HttpPath == "" {
  474. attachment.HttpPath = conf.URLForNotHost("BlogController.Download", ":id", blogId, ":attach_id", attachment.AttachmentId)
  475. if err := attachment.Update(); err != nil {
  476. logs.Error("保存文件失败 -> ", attachment.FilePath, err)
  477. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  478. }
  479. }
  480. result["attach"] = attachment
  481. }
  482. result["errcode"] = 0
  483. result["success"] = 1
  484. result["message"] = "ok"
  485. result["url"] = httpPath
  486. result["alt"] = fileName
  487. c.Ctx.Output.JSON(result, true, false)
  488. c.StopRun()
  489. }
  490. // 删除附件
  491. func (c *BlogController) RemoveAttachment() {
  492. c.Prepare()
  493. attachId, _ := c.GetInt("attach_id")
  494. blogId, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
  495. if attachId <= 0 {
  496. c.JsonResult(6001, i18n.Tr(c.Lang, "message.param_error"))
  497. }
  498. blog, err := models.NewBlog().Find(blogId)
  499. if err != nil {
  500. if err == orm.ErrNoRows {
  501. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.doc_not_exist"))
  502. } else {
  503. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.query_failed"))
  504. }
  505. }
  506. attach, err := models.NewAttachment().Find(attachId)
  507. if err != nil {
  508. logs.Error(err)
  509. c.JsonResult(6002, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  510. }
  511. if !c.Member.IsAdministrator() {
  512. _, err := models.NewBlog().FindByIdAndMemberId(attach.DocumentId, c.Member.MemberId)
  513. if err != nil {
  514. logs.Error(err)
  515. c.JsonResult(6003, i18n.Tr(c.Lang, "message.doc_not_exist"))
  516. }
  517. }
  518. if blog.BlogType == 1 && attach.BookId != blog.BookId && attach.DocumentId != blog.DocumentId {
  519. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  520. } else if attach.BookId != 0 || attach.DocumentId != blogId {
  521. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  522. }
  523. if err := attach.Delete(); err != nil {
  524. logs.Error(err)
  525. c.JsonResult(6005, i18n.Tr(c.Lang, "message.failed"))
  526. }
  527. os.Remove(filepath.Join(conf.WorkingDirectory, attach.FilePath))
  528. c.JsonResult(0, "ok", attach)
  529. }
  530. // 下载附件
  531. func (c *BlogController) Download() {
  532. c.Prepare()
  533. blogId, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
  534. attachId, _ := strconv.Atoi(c.Ctx.Input.Param(":attach_id"))
  535. password := c.GetString("password")
  536. blog, err := models.NewBlog().Find(blogId)
  537. if err != nil {
  538. if err == orm.ErrNoRows {
  539. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.doc_not_exist"))
  540. } else {
  541. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.query_failed"))
  542. }
  543. }
  544. blogReadSession := fmt.Sprintf("blog:read:%d", blogId)
  545. //如果没有启动匿名访问,或者设置了访问密码
  546. if (c.Member == nil && !c.EnableAnonymous) || (blog.BlogStatus == "password" && password != blog.Password && c.CruSession.Get(context.TODO(), blogReadSession) == nil) {
  547. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  548. }
  549. // 查找附件
  550. attachment, err := models.NewAttachment().Find(attachId)
  551. if err != nil {
  552. if err == orm.ErrNoRows {
  553. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  554. } else {
  555. logs.Error("查询附件时出现异常 -> ", err)
  556. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.query_failed"))
  557. }
  558. }
  559. //如果是链接的文章,需要校验文档ID是否一致,如果不是,需要保证附件的项目ID为0且文档的ID等于博文ID
  560. if blog.BlogType == 1 && attachment.DocumentId != blog.DocumentId {
  561. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  562. } else if blog.BlogType != 1 && (attachment.BookId != 0 || attachment.DocumentId != blogId) {
  563. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.attachment_not_exist"))
  564. }
  565. c.Ctx.Output.Download(filepath.Join(conf.WorkingDirectory, attachment.FilePath), attachment.FileName)
  566. c.StopRun()
  567. }