book.go 16 KB

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