1
0

BlogController.go 16 KB

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