BlogController.go 19 KB

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