book.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "html/template"
  7. "os"
  8. "path/filepath"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/astaxie/beego"
  14. "github.com/astaxie/beego/logs"
  15. "github.com/astaxie/beego/orm"
  16. "github.com/lifei6671/mindoc/conf"
  17. "github.com/lifei6671/mindoc/graphics"
  18. "github.com/lifei6671/mindoc/models"
  19. "github.com/lifei6671/mindoc/utils"
  20. "github.com/lifei6671/mindoc/utils/pagination"
  21. )
  22. type BookController struct {
  23. BaseController
  24. }
  25. func (c *BookController) Index() {
  26. c.Prepare()
  27. c.TplName = "book/index.tpl"
  28. pageIndex, _ := c.GetInt("page", 1)
  29. books, totalCount, err := models.NewBook().FindToPager(pageIndex, conf.PageSize, c.Member.MemberId)
  30. if err != nil {
  31. logs.Error("BookController.Index => ", err)
  32. c.Abort("500")
  33. }
  34. if totalCount > 0 {
  35. pager := pagination.NewPagination(c.Ctx.Request,totalCount,conf.PageSize)
  36. c.Data["PageHtml"] = pager.HtmlPages()
  37. } else {
  38. c.Data["PageHtml"] = ""
  39. }
  40. b, err := json.Marshal(books)
  41. if err != nil || len(books) <= 0 {
  42. c.Data["Result"] = template.JS("[]")
  43. } else {
  44. c.Data["Result"] = template.JS(string(b))
  45. }
  46. }
  47. // Dashboard 项目概要 .
  48. func (c *BookController) Dashboard() {
  49. c.Prepare()
  50. c.TplName = "book/dashboard.tpl"
  51. key := c.Ctx.Input.Param(":key")
  52. if key == "" {
  53. c.Abort("404")
  54. }
  55. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  56. if err != nil {
  57. if err == models.ErrPermissionDenied {
  58. c.Abort("403")
  59. }
  60. beego.Error(err)
  61. c.Abort("500")
  62. }
  63. c.Data["Model"] = *book
  64. }
  65. // Setting 项目设置 .
  66. func (c *BookController) Setting() {
  67. c.Prepare()
  68. c.TplName = "book/setting.tpl"
  69. key := c.Ctx.Input.Param(":key")
  70. if key == "" {
  71. c.Abort("404")
  72. }
  73. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  74. if err != nil {
  75. if err == orm.ErrNoRows {
  76. c.Abort("404")
  77. }
  78. if err == models.ErrPermissionDenied {
  79. c.Abort("403")
  80. }
  81. c.Abort("500")
  82. }
  83. //如果不是创始人也不是管理员则不能操作
  84. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  85. c.Abort("403")
  86. }
  87. if book.PrivateToken != "" {
  88. book.PrivateToken = c.BaseUrl() + beego.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken)
  89. }
  90. c.Data["Model"] = book
  91. }
  92. //保存项目信息
  93. func (c *BookController) SaveBook() {
  94. bookResult, err := c.IsPermission()
  95. if err != nil {
  96. c.JsonResult(6001, err.Error())
  97. }
  98. book, err := models.NewBook().Find(bookResult.BookId)
  99. if err != nil {
  100. logs.Error("SaveBook => ", err)
  101. c.JsonResult(6002, err.Error())
  102. }
  103. book_name := strings.TrimSpace(c.GetString("book_name"))
  104. description := strings.TrimSpace(c.GetString("description", ""))
  105. comment_status := c.GetString("comment_status")
  106. tag := strings.TrimSpace(c.GetString("label"))
  107. editor := strings.TrimSpace(c.GetString("editor"))
  108. auto_release := strings.TrimSpace(c.GetString("auto_release")) == "on"
  109. if strings.Count(description, "") > 500 {
  110. c.JsonResult(6004, "项目描述不能大于500字")
  111. }
  112. if comment_status != "open" && comment_status != "closed" && comment_status != "group_only" && comment_status != "registered_only" {
  113. comment_status = "closed"
  114. }
  115. if tag != "" {
  116. tags := strings.Split(tag, ",")
  117. if len(tags) > 10 {
  118. c.JsonResult(6005, "最多允许添加10个标签")
  119. }
  120. }
  121. if editor != "markdown" && editor != "html" {
  122. editor = "markdown"
  123. }
  124. book.BookName = book_name
  125. book.Description = description
  126. book.CommentStatus = comment_status
  127. book.Label = tag
  128. book.Editor = editor
  129. if auto_release {
  130. book.AutoRelease = 1
  131. } else {
  132. book.AutoRelease = 0
  133. }
  134. if err := book.Update(); err != nil {
  135. c.JsonResult(6006, "保存失败")
  136. }
  137. bookResult.BookName = book_name
  138. bookResult.Description = description
  139. bookResult.CommentStatus = comment_status
  140. bookResult.Label = tag
  141. c.JsonResult(0, "ok", bookResult)
  142. }
  143. //设置项目私有状态.
  144. func (c *BookController) PrivatelyOwned() {
  145. status := c.GetString("status")
  146. if status != "open" && status != "close" {
  147. c.JsonResult(6003, "参数错误")
  148. }
  149. state := 0
  150. if status == "open" {
  151. state = 0
  152. } else {
  153. state = 1
  154. }
  155. bookResult, err := c.IsPermission()
  156. if err != nil {
  157. c.JsonResult(6001, err.Error())
  158. }
  159. //只有创始人才能变更私有状态
  160. if bookResult.RoleId != conf.BookFounder {
  161. c.JsonResult(6002, "权限不足")
  162. }
  163. book, err := models.NewBook().Find(bookResult.BookId)
  164. if err != nil {
  165. c.JsonResult(6005, "项目不存在")
  166. }
  167. book.PrivatelyOwned = state
  168. err = book.Update()
  169. if err != nil {
  170. logs.Error("PrivatelyOwned => ", err)
  171. c.JsonResult(6004, "保存失败")
  172. }
  173. c.JsonResult(0, "ok")
  174. }
  175. // Transfer 转让项目.
  176. func (c *BookController) Transfer() {
  177. c.Prepare()
  178. account := c.GetString("account")
  179. if account == "" {
  180. c.JsonResult(6004, "接受者账号不能为空")
  181. }
  182. member, err := models.NewMember().FindByAccount(account)
  183. if err != nil {
  184. logs.Error("FindByAccount => ", err)
  185. c.JsonResult(6005, "接受用户不存在")
  186. }
  187. if member.Status != 0 {
  188. c.JsonResult(6006, "接受用户已被禁用")
  189. }
  190. if member.MemberId == c.Member.MemberId {
  191. c.JsonResult(6007, "不能转让给自己")
  192. }
  193. bookResult, err := c.IsPermission()
  194. if err != nil {
  195. c.JsonResult(6001, err.Error())
  196. }
  197. err = models.NewRelationship().Transfer(bookResult.BookId, c.Member.MemberId, member.MemberId)
  198. if err != nil {
  199. logs.Error("Transfer => ", err)
  200. c.JsonResult(6008, err.Error())
  201. }
  202. c.JsonResult(0, "ok")
  203. }
  204. //上传项目封面.
  205. func (c *BookController) UploadCover() {
  206. bookResult, err := c.IsPermission()
  207. if err != nil {
  208. c.JsonResult(6001, err.Error())
  209. }
  210. book, err := models.NewBook().Find(bookResult.BookId)
  211. if err != nil {
  212. logs.Error("SaveBook => ", err)
  213. c.JsonResult(6002, err.Error())
  214. }
  215. file, moreFile, err := c.GetFile("image-file")
  216. defer file.Close()
  217. if err != nil {
  218. logs.Error("", err.Error())
  219. c.JsonResult(500, "读取文件异常")
  220. }
  221. ext := filepath.Ext(moreFile.Filename)
  222. if !strings.EqualFold(ext, ".png") && !strings.EqualFold(ext, ".jpg") && !strings.EqualFold(ext, ".gif") && !strings.EqualFold(ext, ".jpeg") {
  223. c.JsonResult(500, "不支持的图片格式")
  224. }
  225. x1, _ := strconv.ParseFloat(c.GetString("x"), 10)
  226. y1, _ := strconv.ParseFloat(c.GetString("y"), 10)
  227. w1, _ := strconv.ParseFloat(c.GetString("width"), 10)
  228. h1, _ := strconv.ParseFloat(c.GetString("height"), 10)
  229. x := int(x1)
  230. y := int(y1)
  231. width := int(w1)
  232. height := int(h1)
  233. fileName := "cover_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  234. filePath := filepath.Join("uploads", time.Now().Format("200601"), fileName+ext)
  235. path := filepath.Dir(filePath)
  236. os.MkdirAll(path, os.ModePerm)
  237. err = c.SaveToFile("image-file", filePath)
  238. if err != nil {
  239. logs.Error("", err)
  240. c.JsonResult(500, "图片保存失败")
  241. }
  242. defer func(filePath string) {
  243. os.Remove(filePath)
  244. }(filePath)
  245. //剪切图片
  246. subImg, err := graphics.ImageCopyFromFile(filePath, x, y, width, height)
  247. if err != nil {
  248. logs.Error("graphics.ImageCopyFromFile => ", err)
  249. c.JsonResult(500, "图片剪切")
  250. }
  251. filePath = filepath.Join(conf.WorkingDirectory, "uploads", time.Now().Format("200601"), fileName+"_small"+ext)
  252. //生成缩略图并保存到磁盘
  253. err = graphics.ImageResizeSaveFile(subImg, 175, 230, filePath)
  254. if err != nil {
  255. logs.Error("ImageResizeSaveFile => ", err.Error())
  256. c.JsonResult(500, "保存图片失败")
  257. }
  258. url := "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
  259. if strings.HasPrefix(url, "//") {
  260. url = string(url[1:])
  261. }
  262. old_cover := book.Cover
  263. book.Cover = url
  264. if err := book.Update(); err != nil {
  265. c.JsonResult(6001, "保存图片失败")
  266. }
  267. //如果原封面不是默认封面则删除
  268. if old_cover != conf.GetDefaultCover() {
  269. os.Remove("." + old_cover)
  270. }
  271. c.JsonResult(0, "ok", url)
  272. }
  273. // Users 用户列表.
  274. func (c *BookController) Users() {
  275. c.Prepare()
  276. c.TplName = "book/users.tpl"
  277. key := c.Ctx.Input.Param(":key")
  278. pageIndex, _ := c.GetInt("page", 1)
  279. if key == "" {
  280. c.Abort("404")
  281. }
  282. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  283. if err != nil {
  284. if err == models.ErrPermissionDenied {
  285. c.Abort("403")
  286. }
  287. c.Abort("500")
  288. }
  289. c.Data["Model"] = *book
  290. members, totalCount, err := models.NewMemberRelationshipResult().FindForUsersByBookId(book.BookId, pageIndex, 15)
  291. if totalCount > 0 {
  292. pager := pagination.NewPagination(c.Ctx.Request,totalCount,conf.PageSize)
  293. c.Data["PageHtml"] = pager.HtmlPages()
  294. } else {
  295. c.Data["PageHtml"] = ""
  296. }
  297. b, err := json.Marshal(members)
  298. if err != nil {
  299. c.Data["Result"] = template.JS("[]")
  300. } else {
  301. c.Data["Result"] = template.JS(string(b))
  302. }
  303. }
  304. // Create 创建项目.
  305. func (c *BookController) Create() {
  306. if c.Ctx.Input.IsPost() {
  307. book_name := strings.TrimSpace(c.GetString("book_name", ""))
  308. identify := strings.TrimSpace(c.GetString("identify", ""))
  309. description := strings.TrimSpace(c.GetString("description", ""))
  310. privately_owned, _ := strconv.Atoi(c.GetString("privately_owned"))
  311. comment_status := c.GetString("comment_status")
  312. if book_name == "" {
  313. c.JsonResult(6001, "项目名称不能为空")
  314. }
  315. if identify == "" {
  316. c.JsonResult(6002, "项目标识不能为空")
  317. }
  318. if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, identify); !ok || err != nil {
  319. c.JsonResult(6003, "项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  320. }
  321. if strings.Count(identify, "") > 50 {
  322. c.JsonResult(6004, "文档标识不能超过50字")
  323. }
  324. if strings.Count(description, "") > 500 {
  325. c.JsonResult(6004, "项目描述不能大于500字")
  326. }
  327. if privately_owned != 0 && privately_owned != 1 {
  328. privately_owned = 1
  329. }
  330. if comment_status != "open" && comment_status != "closed" && comment_status != "group_only" && comment_status != "registered_only" {
  331. comment_status = "closed"
  332. }
  333. book := models.NewBook()
  334. if books, _ := book.FindByField("identify", identify); len(books) > 0 {
  335. c.JsonResult(6006, "项目标识已存在")
  336. }
  337. book.BookName = book_name
  338. book.Description = description
  339. book.CommentCount = 0
  340. book.PrivatelyOwned = privately_owned
  341. book.CommentStatus = comment_status
  342. book.Identify = identify
  343. book.DocCount = 0
  344. book.MemberId = c.Member.MemberId
  345. book.CommentCount = 0
  346. book.Version = time.Now().Unix()
  347. book.Cover = conf.GetDefaultCover()
  348. book.Editor = "markdown"
  349. book.Theme = "default"
  350. err := book.Insert()
  351. if err != nil {
  352. logs.Error("Insert => ", err)
  353. c.JsonResult(6005, "保存项目失败")
  354. }
  355. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  356. if err != nil {
  357. beego.Error(err)
  358. }
  359. c.JsonResult(0, "ok", bookResult)
  360. }
  361. c.JsonResult(6001, "error")
  362. }
  363. // CreateToken 创建访问来令牌.
  364. func (c *BookController) CreateToken() {
  365. action := c.GetString("action")
  366. bookResult, err := c.IsPermission()
  367. if err != nil {
  368. if err == models.ErrPermissionDenied {
  369. c.JsonResult(403, "权限不足")
  370. }
  371. if err == orm.ErrNoRows {
  372. c.JsonResult(404, "项目不存在")
  373. }
  374. logs.Error("生成阅读令牌失败 =>", err)
  375. c.JsonResult(6002, err.Error())
  376. }
  377. book := models.NewBook()
  378. if _, err := book.Find(bookResult.BookId); err != nil {
  379. c.JsonResult(6001, "项目不存在")
  380. }
  381. if action == "create" {
  382. if bookResult.PrivatelyOwned == 0 {
  383. c.JsonResult(6001, "公开项目不能创建阅读令牌")
  384. }
  385. book.PrivateToken = string(utils.Krand(conf.GetTokenSize(), utils.KC_RAND_KIND_ALL))
  386. if err := book.Update(); err != nil {
  387. logs.Error("生成阅读令牌失败 => ", err)
  388. c.JsonResult(6003, "生成阅读令牌失败")
  389. }
  390. c.JsonResult(0, "ok", c.BaseUrl()+beego.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken))
  391. } else {
  392. book.PrivateToken = ""
  393. if err := book.Update(); err != nil {
  394. logs.Error("CreateToken => ", err)
  395. c.JsonResult(6004, "删除令牌失败")
  396. }
  397. c.JsonResult(0, "ok", "")
  398. }
  399. }
  400. // Delete 删除项目.
  401. func (c *BookController) Delete() {
  402. c.Prepare()
  403. bookResult, err := c.IsPermission()
  404. if err != nil {
  405. c.JsonResult(6001, err.Error())
  406. }
  407. if bookResult.RoleId != conf.BookFounder {
  408. c.JsonResult(6002, "只有创始人才能删除项目")
  409. }
  410. err = models.NewBook().ThoroughDeleteBook(bookResult.BookId)
  411. if err == orm.ErrNoRows {
  412. c.JsonResult(6002, "项目不存在")
  413. }
  414. if err != nil {
  415. logs.Error("删除项目 => ", err)
  416. c.JsonResult(6003, "删除失败")
  417. }
  418. c.JsonResult(0, "ok")
  419. }
  420. //发布项目.
  421. func (c *BookController) Release() {
  422. c.Prepare()
  423. identify := c.GetString("identify")
  424. bookId := 0
  425. if c.Member.IsAdministrator() {
  426. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  427. if err != nil {
  428. }
  429. bookId = book.BookId
  430. } else {
  431. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  432. if err != nil {
  433. if err == models.ErrPermissionDenied {
  434. c.JsonResult(6001, "权限不足")
  435. }
  436. if err == orm.ErrNoRows {
  437. c.JsonResult(6002, "项目不存在")
  438. }
  439. beego.Error(err)
  440. c.JsonResult(6003, "未知错误")
  441. }
  442. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor {
  443. c.JsonResult(6003, "权限不足")
  444. }
  445. bookId = book.BookId
  446. }
  447. go func(identify string) {
  448. models.NewDocument().ReleaseContent(bookId)
  449. //当文档发布后,需要删除已缓存的转换项目
  450. outputPath := filepath.Join(beego.AppConfig.DefaultString("book_output_path", "cache"), strconv.Itoa(bookId))
  451. os.RemoveAll(outputPath)
  452. }(identify)
  453. c.JsonResult(0, "发布任务已推送到任务队列,稍后将在后台执行。")
  454. }
  455. //文档排序.
  456. func (c *BookController) SaveSort() {
  457. c.Prepare()
  458. identify := c.Ctx.Input.Param(":key")
  459. if identify == "" {
  460. c.Abort("404")
  461. }
  462. book_id := 0
  463. if c.Member.IsAdministrator() {
  464. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  465. if err != nil {
  466. }
  467. book_id = book.BookId
  468. } else {
  469. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  470. if err != nil {
  471. beego.Error("DocumentController.Edit => ", err)
  472. c.Abort("403")
  473. }
  474. if bookResult.RoleId == conf.BookObserver {
  475. c.JsonResult(6002, "项目不存在或权限不足")
  476. }
  477. book_id = bookResult.BookId
  478. }
  479. content := c.Ctx.Input.RequestBody
  480. var docs []map[string]interface{}
  481. err := json.Unmarshal(content, &docs)
  482. if err != nil {
  483. beego.Error(err)
  484. c.JsonResult(6003, "数据错误")
  485. }
  486. for _, item := range docs {
  487. if doc_id, ok := item["id"].(float64); ok {
  488. doc, err := models.NewDocument().Find(int(doc_id))
  489. if err != nil {
  490. beego.Error(err)
  491. continue
  492. }
  493. if doc.BookId != book_id {
  494. logs.Info("%s", "权限错误")
  495. continue
  496. }
  497. sort, ok := item["sort"].(float64)
  498. if !ok {
  499. beego.Info("排序数字转换失败 => ", item)
  500. continue
  501. }
  502. parent_id, ok := item["parent"].(float64)
  503. if !ok {
  504. beego.Info("父分类转换失败 => ", item)
  505. continue
  506. }
  507. if parent_id > 0 {
  508. if parent, err := models.NewDocument().Find(int(parent_id)); err != nil || parent.BookId != book_id {
  509. continue
  510. }
  511. }
  512. doc.OrderSort = int(sort)
  513. doc.ParentId = int(parent_id)
  514. if err := doc.InsertOrUpdate(); err != nil {
  515. fmt.Printf("%s", err.Error())
  516. beego.Error(err)
  517. }
  518. } else {
  519. fmt.Printf("文档ID转换失败 => %+v", item)
  520. }
  521. }
  522. c.JsonResult(0, "ok")
  523. }
  524. func (c *BookController) IsPermission() (*models.BookResult, error) {
  525. identify := c.GetString("identify")
  526. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  527. if err != nil {
  528. if err == models.ErrPermissionDenied {
  529. return book, errors.New("权限不足")
  530. }
  531. if err == orm.ErrNoRows {
  532. return book, errors.New("项目不存在")
  533. }
  534. return book, err
  535. }
  536. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  537. return book, errors.New("权限不足")
  538. }
  539. return book, nil
  540. }