book.go 16 KB

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