BlogController.go 19 KB

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