1
0

book.go 16 KB

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