BookController.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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. "net/http"
  14. "github.com/astaxie/beego"
  15. "github.com/astaxie/beego/logs"
  16. "github.com/astaxie/beego/orm"
  17. "github.com/lifei6671/mindoc/conf"
  18. "github.com/lifei6671/mindoc/graphics"
  19. "github.com/lifei6671/mindoc/models"
  20. "github.com/lifei6671/mindoc/utils"
  21. "github.com/lifei6671/mindoc/utils/pagination"
  22. "gopkg.in/russross/blackfriday.v2"
  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. for i, book := range books {
  37. books[i].Description = utils.StripTags(string(blackfriday.Run([]byte(book.Description))))
  38. books[i].ModifyTime = book.ModifyTime.Local()
  39. books[i].CreateTime = book.CreateTime.Local()
  40. }
  41. if totalCount > 0 {
  42. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  43. c.Data["PageHtml"] = pager.HtmlPages()
  44. } else {
  45. c.Data["PageHtml"] = ""
  46. }
  47. b, err := json.Marshal(books)
  48. if err != nil || len(books) <= 0 {
  49. c.Data["Result"] = template.JS("[]")
  50. } else {
  51. c.Data["Result"] = template.JS(string(b))
  52. }
  53. if itemsets, err := models.NewItemsets().First(1); err == nil {
  54. c.Data["Item"] = itemsets
  55. }
  56. }
  57. // Dashboard 项目概要 .
  58. func (c *BookController) Dashboard() {
  59. c.Prepare()
  60. c.TplName = "book/dashboard.tpl"
  61. key := c.Ctx.Input.Param(":key")
  62. if key == "" {
  63. c.Abort("404")
  64. }
  65. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  66. if err != nil {
  67. if err == models.ErrPermissionDenied {
  68. c.Abort("403")
  69. }
  70. c.Abort("500")
  71. }
  72. c.Data["Description"] = template.HTML(blackfriday.Run([]byte(book.Description)))
  73. c.Data["Model"] = *book
  74. }
  75. // Setting 项目设置 .
  76. func (c *BookController) Setting() {
  77. c.Prepare()
  78. c.TplName = "book/setting.tpl"
  79. key := c.Ctx.Input.Param(":key")
  80. if key == "" {
  81. c.Abort("404")
  82. }
  83. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  84. if err != nil {
  85. if err == orm.ErrNoRows {
  86. c.Abort("404")
  87. }
  88. if err == models.ErrPermissionDenied {
  89. c.Abort("403")
  90. }
  91. c.Abort("500")
  92. }
  93. //如果不是创始人也不是管理员则不能操作
  94. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  95. c.Abort("403")
  96. }
  97. if book.PrivateToken != "" {
  98. book.PrivateToken = conf.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken)
  99. }
  100. c.Data["Model"] = book
  101. }
  102. //保存项目信息
  103. func (c *BookController) SaveBook() {
  104. bookResult, err := c.IsPermission()
  105. if err != nil {
  106. c.JsonResult(6001, err.Error())
  107. }
  108. book, err := models.NewBook().Find(bookResult.BookId)
  109. if err != nil {
  110. logs.Error("SaveBook => ", err)
  111. c.JsonResult(6002, err.Error())
  112. }
  113. bookName := strings.TrimSpace(c.GetString("book_name"))
  114. description := strings.TrimSpace(c.GetString("description", ""))
  115. commentStatus := c.GetString("comment_status")
  116. tag := strings.TrimSpace(c.GetString("label"))
  117. editor := strings.TrimSpace(c.GetString("editor"))
  118. autoRelease := strings.TrimSpace(c.GetString("auto_release")) == "on"
  119. publisher := strings.TrimSpace(c.GetString("publisher"))
  120. historyCount, _ := c.GetInt("history_count", 0)
  121. isDownload := strings.TrimSpace(c.GetString("is_download")) == "on"
  122. enableShare := strings.TrimSpace(c.GetString("enable_share")) == "on"
  123. isUseFirstDocument := strings.TrimSpace(c.GetString("is_use_first_document")) == "on"
  124. autoSave := strings.TrimSpace(c.GetString("auto_save")) == "on"
  125. itemId, _ := c.GetInt("itemId")
  126. if strings.Count(description, "") > 500 {
  127. c.JsonResult(6004, "项目描述不能大于500字")
  128. }
  129. if commentStatus != "open" && commentStatus != "closed" && commentStatus != "group_only" && commentStatus != "registered_only" {
  130. commentStatus = "closed"
  131. }
  132. if tag != "" {
  133. tags := strings.Split(tag, ",")
  134. if len(tags) > 10 {
  135. c.JsonResult(6005, "最多允许添加10个标签")
  136. }
  137. }
  138. if !models.NewItemsets().Exist(itemId) {
  139. c.JsonResult(6006, "项目空间不存在")
  140. }
  141. if editor != "markdown" && editor != "html" {
  142. editor = "markdown"
  143. }
  144. book.BookName = bookName
  145. book.Description = description
  146. book.CommentStatus = commentStatus
  147. book.Publisher = publisher
  148. book.Label = tag
  149. book.Editor = editor
  150. book.HistoryCount = historyCount
  151. book.IsDownload = 0
  152. book.BookPassword = strings.TrimSpace(c.GetString("bPassword"))
  153. book.ItemId = itemId
  154. if autoRelease {
  155. book.AutoRelease = 1
  156. } else {
  157. book.AutoRelease = 0
  158. }
  159. if isDownload {
  160. book.IsDownload = 0
  161. } else {
  162. book.IsDownload = 1
  163. }
  164. if enableShare {
  165. book.IsEnableShare = 0
  166. } else {
  167. book.IsEnableShare = 1
  168. }
  169. if isUseFirstDocument {
  170. book.IsUseFirstDocument = 1
  171. } else {
  172. book.IsUseFirstDocument = 0
  173. }
  174. if autoSave {
  175. book.AutoSave = 1
  176. } else {
  177. book.AutoSave = 0
  178. }
  179. if err := book.Update(); err != nil {
  180. c.JsonResult(6006, "保存失败")
  181. }
  182. bookResult.BookName = bookName
  183. bookResult.Description = description
  184. bookResult.CommentStatus = commentStatus
  185. bookResult.Label = tag
  186. beego.Info("用户 [", c.Member.Account, "] 修改了项目 ->", book)
  187. c.JsonResult(0, "ok", bookResult)
  188. }
  189. //设置项目私有状态.
  190. func (c *BookController) PrivatelyOwned() {
  191. status := c.GetString("status")
  192. if status != "open" && status != "close" {
  193. c.JsonResult(6003, "参数错误")
  194. }
  195. state := 0
  196. if status == "open" {
  197. state = 0
  198. } else {
  199. state = 1
  200. }
  201. bookResult, err := c.IsPermission()
  202. if err != nil {
  203. c.JsonResult(6001, err.Error())
  204. }
  205. //只有创始人才能变更私有状态
  206. if bookResult.RoleId != conf.BookFounder {
  207. c.JsonResult(6002, "权限不足")
  208. }
  209. book, err := models.NewBook().Find(bookResult.BookId)
  210. if err != nil {
  211. c.JsonResult(6005, "项目不存在")
  212. }
  213. book.PrivatelyOwned = state
  214. err = book.Update()
  215. if err != nil {
  216. logs.Error("PrivatelyOwned => ", err)
  217. c.JsonResult(6004, "保存失败")
  218. }
  219. beego.Info("用户 【", c.Member.Account, "]修改了项目权限 ->", state)
  220. c.JsonResult(0, "ok")
  221. }
  222. // Transfer 转让项目.
  223. func (c *BookController) Transfer() {
  224. c.Prepare()
  225. account := c.GetString("account")
  226. if account == "" {
  227. c.JsonResult(6004, "接受者账号不能为空")
  228. }
  229. member, err := models.NewMember().FindByAccount(account)
  230. if err != nil {
  231. logs.Error("FindByAccount => ", err)
  232. c.JsonResult(6005, "接受用户不存在")
  233. }
  234. if member.Status != 0 {
  235. c.JsonResult(6006, "接受用户已被禁用")
  236. }
  237. if member.MemberId == c.Member.MemberId {
  238. c.JsonResult(6007, "不能转让给自己")
  239. }
  240. bookResult, err := c.IsPermission()
  241. if err != nil {
  242. c.JsonResult(6001, err.Error())
  243. }
  244. err = models.NewRelationship().Transfer(bookResult.BookId, c.Member.MemberId, member.MemberId)
  245. if err != nil {
  246. logs.Error("转让项目失败 -> ", err)
  247. c.JsonResult(6008, err.Error())
  248. }
  249. c.JsonResult(0, "ok")
  250. }
  251. //上传项目封面.
  252. func (c *BookController) UploadCover() {
  253. bookResult, err := c.IsPermission()
  254. if err != nil {
  255. c.JsonResult(6001, err.Error())
  256. }
  257. book, err := models.NewBook().Find(bookResult.BookId)
  258. if err != nil {
  259. logs.Error("SaveBook => ", err)
  260. c.JsonResult(6002, err.Error())
  261. }
  262. file, moreFile, err := c.GetFile("image-file")
  263. if err != nil {
  264. logs.Error("获取上传文件失败 ->", err.Error())
  265. c.JsonResult(500, "读取文件异常")
  266. }
  267. defer file.Close()
  268. ext := filepath.Ext(moreFile.Filename)
  269. if !strings.EqualFold(ext, ".png") && !strings.EqualFold(ext, ".jpg") && !strings.EqualFold(ext, ".gif") && !strings.EqualFold(ext, ".jpeg") {
  270. c.JsonResult(500, "不支持的图片格式")
  271. }
  272. x1, _ := strconv.ParseFloat(c.GetString("x"), 10)
  273. y1, _ := strconv.ParseFloat(c.GetString("y"), 10)
  274. w1, _ := strconv.ParseFloat(c.GetString("width"), 10)
  275. h1, _ := strconv.ParseFloat(c.GetString("height"), 10)
  276. x := int(x1)
  277. y := int(y1)
  278. width := int(w1)
  279. height := int(h1)
  280. fileName := "cover_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  281. //附件路径按照项目组织
  282. filePath := filepath.Join("uploads", book.Identify, "images", fileName+ext)
  283. path := filepath.Dir(filePath)
  284. os.MkdirAll(path, os.ModePerm)
  285. err = c.SaveToFile("image-file", filePath)
  286. if err != nil {
  287. logs.Error("", err)
  288. c.JsonResult(500, "图片保存失败")
  289. }
  290. defer func(filePath string) {
  291. os.Remove(filePath)
  292. }(filePath)
  293. //剪切图片
  294. subImg, err := graphics.ImageCopyFromFile(filePath, x, y, width, height)
  295. if err != nil {
  296. logs.Error("graphics.ImageCopyFromFile => ", err)
  297. c.JsonResult(500, "图片剪切")
  298. }
  299. filePath = filepath.Join(conf.WorkingDirectory, "uploads", time.Now().Format("200601"), fileName+"_small"+ext)
  300. //生成缩略图并保存到磁盘
  301. err = graphics.ImageResizeSaveFile(subImg, 350, 460, filePath)
  302. if err != nil {
  303. logs.Error("ImageResizeSaveFile => ", err.Error())
  304. c.JsonResult(500, "保存图片失败")
  305. }
  306. url := "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
  307. if strings.HasPrefix(url, "//") {
  308. url = string(url[1:])
  309. }
  310. oldCover := book.Cover
  311. book.Cover = conf.URLForWithCdnImage(url)
  312. if err := book.Update(); err != nil {
  313. c.JsonResult(6001, "保存图片失败")
  314. }
  315. //如果原封面不是默认封面则删除
  316. if oldCover != conf.GetDefaultCover() {
  317. os.Remove("." + oldCover)
  318. }
  319. beego.Info("用户[", c.Member.Account, "]上传了项目封面 ->", book.BookName, book.BookId, book.Cover)
  320. c.JsonResult(0, "ok", url)
  321. }
  322. // Users 用户列表.
  323. func (c *BookController) Users() {
  324. c.Prepare()
  325. c.TplName = "book/users.tpl"
  326. key := c.Ctx.Input.Param(":key")
  327. pageIndex, _ := c.GetInt("page", 1)
  328. if key == "" {
  329. c.ShowErrorPage(404, "项目不存在或已删除")
  330. }
  331. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  332. if err != nil {
  333. if err == models.ErrPermissionDenied {
  334. c.Abort("403")
  335. }
  336. c.Abort("500")
  337. }
  338. c.Data["Model"] = *book
  339. members, totalCount, err := models.NewMemberRelationshipResult().FindForUsersByBookId(book.BookId, pageIndex, conf.PageSize)
  340. if totalCount > 0 {
  341. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  342. c.Data["PageHtml"] = pager.HtmlPages()
  343. } else {
  344. c.Data["PageHtml"] = ""
  345. }
  346. b, err := json.Marshal(members)
  347. if err != nil {
  348. c.Data["Result"] = template.JS("[]")
  349. } else {
  350. c.Data["Result"] = template.JS(string(b))
  351. }
  352. }
  353. // Create 创建项目.
  354. func (c *BookController) Create() {
  355. if c.Ctx.Input.IsPost() {
  356. bookName := strings.TrimSpace(c.GetString("book_name", ""))
  357. identify := strings.TrimSpace(c.GetString("identify", ""))
  358. description := strings.TrimSpace(c.GetString("description", ""))
  359. privatelyOwned, _ := strconv.Atoi(c.GetString("privately_owned"))
  360. commentStatus := c.GetString("comment_status")
  361. itemId, _ := c.GetInt("itemId")
  362. if bookName == "" {
  363. c.JsonResult(6001, "项目名称不能为空")
  364. }
  365. if identify == "" {
  366. c.JsonResult(6002, "项目标识不能为空")
  367. }
  368. if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, identify); !ok || err != nil {
  369. c.JsonResult(6003, "项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  370. }
  371. if strings.Count(identify, "") > 50 {
  372. c.JsonResult(6004, "文档标识不能超过50字")
  373. }
  374. if strings.Count(description, "") > 500 {
  375. c.JsonResult(6004, "项目描述不能大于500字")
  376. }
  377. if privatelyOwned != 0 && privatelyOwned != 1 {
  378. privatelyOwned = 1
  379. }
  380. if !models.NewItemsets().Exist(itemId) {
  381. c.JsonResult(6005, "项目空间不存在")
  382. }
  383. if commentStatus != "open" && commentStatus != "closed" && commentStatus != "group_only" && commentStatus != "registered_only" {
  384. commentStatus = "closed"
  385. }
  386. book := models.NewBook()
  387. book.Cover = conf.GetDefaultCover()
  388. //如果客户端上传了项目封面则直接保存
  389. if file, moreFile, err := c.GetFile("image-file"); err == nil {
  390. defer file.Close()
  391. ext := filepath.Ext(moreFile.Filename)
  392. //如果上传的是图片
  393. if strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".gif") || strings.EqualFold(ext, ".jpeg") {
  394. fileName := "cover_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  395. filePath := filepath.Join("uploads", time.Now().Format("200601"), fileName+ext)
  396. path := filepath.Dir(filePath)
  397. os.MkdirAll(path, os.ModePerm)
  398. if err := c.SaveToFile("image-file", filePath); err == nil {
  399. url := "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
  400. if strings.HasPrefix(url, "//") {
  401. url = string(url[1:])
  402. }
  403. book.Cover = url
  404. }
  405. }
  406. }
  407. if books, _ := book.FindByField("identify", identify, "book_id"); len(books) > 0 {
  408. c.JsonResult(6006, "项目标识已存在")
  409. }
  410. book.BookName = bookName
  411. book.Description = description
  412. book.CommentCount = 0
  413. book.PrivatelyOwned = privatelyOwned
  414. book.CommentStatus = commentStatus
  415. book.Identify = identify
  416. book.DocCount = 0
  417. book.MemberId = c.Member.MemberId
  418. book.CommentCount = 0
  419. book.Version = time.Now().Unix()
  420. book.IsEnableShare = 0
  421. book.IsUseFirstDocument = 1
  422. book.IsDownload = 1
  423. book.AutoRelease = 0
  424. book.ItemId = itemId
  425. book.Editor = "markdown"
  426. book.Theme = "default"
  427. if err := book.Insert(); err != nil {
  428. logs.Error("Insert => ", err)
  429. c.JsonResult(6005, "保存项目失败")
  430. }
  431. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  432. if err != nil {
  433. beego.Error(err)
  434. }
  435. beego.Info("用户[", c.Member.Account, "]创建了项目 ->", book)
  436. c.JsonResult(0, "ok", bookResult)
  437. }
  438. c.JsonResult(6001, "error")
  439. }
  440. //复制项目
  441. func (c *BookController) Copy() {
  442. if c.Ctx.Input.IsPost() {
  443. //检查是否有复制项目的权限
  444. if _, err := c.IsPermission(); err != nil {
  445. c.JsonResult(500, err.Error())
  446. }
  447. identify := strings.TrimSpace(c.GetString("identify", ""))
  448. if identify == "" {
  449. c.JsonResult(6001, "参数错误")
  450. }
  451. book := models.NewBook()
  452. err := book.Copy(identify)
  453. if err != nil {
  454. c.JsonResult(6002, "复制项目出错")
  455. } else {
  456. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  457. if err != nil {
  458. beego.Error("查询失败")
  459. }
  460. c.JsonResult(0, "ok", bookResult)
  461. }
  462. }
  463. }
  464. //导入zip压缩包
  465. func (c *BookController) Import() {
  466. file, moreFile, err := c.GetFile("import-file")
  467. if err == http.ErrMissingFile {
  468. c.JsonResult(6003, "没有发现需要上传的文件")
  469. }
  470. defer file.Close()
  471. bookName := strings.TrimSpace(c.GetString("book_name"))
  472. identify := strings.TrimSpace(c.GetString("identify"))
  473. description := strings.TrimSpace(c.GetString("description", ""))
  474. privatelyOwned, _ := strconv.Atoi(c.GetString("privately_owned"))
  475. itemId, _ := c.GetInt("itemId")
  476. if bookName == "" {
  477. c.JsonResult(6001, "项目名称不能为空")
  478. }
  479. if len([]rune(bookName)) > 500 {
  480. c.JsonResult(6002, "项目名称不能大于500字")
  481. }
  482. if identify == "" {
  483. c.JsonResult(6002, "项目标识不能为空")
  484. }
  485. if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, identify); !ok || err != nil {
  486. c.JsonResult(6003, "项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  487. }
  488. if !models.NewItemsets().Exist(itemId) {
  489. c.JsonResult(6007, "项目空间不存在")
  490. }
  491. if strings.Count(identify, "") > 50 {
  492. c.JsonResult(6004, "文档标识不能超过50字")
  493. }
  494. ext := filepath.Ext(moreFile.Filename)
  495. if !strings.EqualFold(ext, ".zip") {
  496. c.JsonResult(6004, "不支持的文件类型")
  497. }
  498. if books, _ := models.NewBook().FindByField("identify", identify, "book_id"); len(books) > 0 {
  499. c.JsonResult(6006, "项目标识已存在")
  500. }
  501. tempPath := filepath.Join(os.TempDir(), c.CruSession.SessionID())
  502. os.MkdirAll(tempPath, 0766)
  503. tempPath = filepath.Join(tempPath, moreFile.Filename)
  504. err = c.SaveToFile("import-file", tempPath)
  505. book := models.NewBook()
  506. book.MemberId = c.Member.MemberId
  507. book.Cover = conf.GetDefaultCover()
  508. book.BookName = bookName
  509. book.Description = description
  510. book.CommentCount = 0
  511. book.PrivatelyOwned = privatelyOwned
  512. book.CommentStatus = "closed"
  513. book.Identify = identify
  514. book.DocCount = 0
  515. book.MemberId = c.Member.MemberId
  516. book.CommentCount = 0
  517. book.Version = time.Now().Unix()
  518. book.ItemId = itemId
  519. book.Editor = "markdown"
  520. book.Theme = "default"
  521. go book.ImportBook(tempPath)
  522. beego.Info("用户[", c.Member.Account, "]导入了项目 ->", book)
  523. c.JsonResult(0, "项目正在后台转换中,请稍后查看")
  524. }
  525. // CreateToken 创建访问来令牌.
  526. func (c *BookController) CreateToken() {
  527. action := c.GetString("action")
  528. bookResult, err := c.IsPermission()
  529. if err != nil {
  530. if err == models.ErrPermissionDenied {
  531. c.JsonResult(403, "权限不足")
  532. }
  533. if err == orm.ErrNoRows {
  534. c.JsonResult(404, "项目不存在")
  535. }
  536. logs.Error("生成阅读令牌失败 =>", err)
  537. c.JsonResult(6002, err.Error())
  538. }
  539. book := models.NewBook()
  540. if _, err := book.Find(bookResult.BookId); err != nil {
  541. c.JsonResult(6001, "项目不存在")
  542. }
  543. if action == "create" {
  544. if bookResult.PrivatelyOwned == 0 {
  545. c.JsonResult(6001, "公开项目不能创建阅读令牌")
  546. }
  547. book.PrivateToken = string(utils.Krand(conf.GetTokenSize(), utils.KC_RAND_KIND_ALL))
  548. if err := book.Update(); err != nil {
  549. logs.Error("生成阅读令牌失败 => ", err)
  550. c.JsonResult(6003, "生成阅读令牌失败")
  551. }
  552. beego.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken)
  553. c.JsonResult(0, "ok", conf.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken))
  554. } else {
  555. book.PrivateToken = ""
  556. if err := book.Update(); err != nil {
  557. logs.Error("CreateToken => ", err)
  558. c.JsonResult(6004, "删除令牌失败")
  559. }
  560. beego.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken)
  561. c.JsonResult(0, "ok", "")
  562. }
  563. }
  564. // Delete 删除项目.
  565. func (c *BookController) Delete() {
  566. c.Prepare()
  567. bookResult, err := c.IsPermission()
  568. if err != nil {
  569. c.JsonResult(6001, err.Error())
  570. }
  571. if bookResult.RoleId != conf.BookFounder {
  572. c.JsonResult(6002, "只有创始人才能删除项目")
  573. }
  574. err = models.NewBook().ThoroughDeleteBook(bookResult.BookId)
  575. if err == orm.ErrNoRows {
  576. c.JsonResult(6002, "项目不存在")
  577. }
  578. if err != nil {
  579. logs.Error("删除项目 => ", err)
  580. c.JsonResult(6003, "删除失败")
  581. }
  582. beego.Info("用户[", c.Member.Account, "]删除了项目 ->", bookResult)
  583. c.JsonResult(0, "ok")
  584. }
  585. //发布项目.
  586. func (c *BookController) Release() {
  587. c.Prepare()
  588. identify := c.GetString("identify")
  589. bookId := 0
  590. if c.Member.IsAdministrator() {
  591. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  592. if err != nil {
  593. }
  594. bookId = book.BookId
  595. } else {
  596. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  597. if err != nil {
  598. if err == models.ErrPermissionDenied {
  599. c.JsonResult(6001, "权限不足")
  600. }
  601. if err == orm.ErrNoRows {
  602. c.JsonResult(6002, "项目不存在")
  603. }
  604. beego.Error(err)
  605. c.JsonResult(6003, "未知错误")
  606. }
  607. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor {
  608. c.JsonResult(6003, "权限不足")
  609. }
  610. bookId = book.BookId
  611. }
  612. go func(identify string) {
  613. models.NewBook().ReleaseContent(bookId)
  614. //当文档发布后,需要删除已缓存的转换项目
  615. outputPath := filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(bookId))
  616. os.RemoveAll(outputPath)
  617. }(identify)
  618. c.JsonResult(0, "发布任务已推送到任务队列,稍后将在后台执行。")
  619. }
  620. //文档排序.
  621. func (c *BookController) SaveSort() {
  622. c.Prepare()
  623. identify := c.Ctx.Input.Param(":key")
  624. if identify == "" {
  625. c.Abort("404")
  626. }
  627. book_id := 0
  628. if c.Member.IsAdministrator() {
  629. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  630. if err != nil {
  631. }
  632. book_id = book.BookId
  633. } else {
  634. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  635. if err != nil {
  636. beego.Error("DocumentController.Edit => ", err)
  637. c.Abort("403")
  638. }
  639. if bookResult.RoleId == conf.BookObserver {
  640. c.JsonResult(6002, "项目不存在或权限不足")
  641. }
  642. book_id = bookResult.BookId
  643. }
  644. content := c.Ctx.Input.RequestBody
  645. var docs []map[string]interface{}
  646. err := json.Unmarshal(content, &docs)
  647. if err != nil {
  648. beego.Error(err)
  649. c.JsonResult(6003, "数据错误")
  650. }
  651. for _, item := range docs {
  652. if doc_id, ok := item["id"].(float64); ok {
  653. doc, err := models.NewDocument().Find(int(doc_id))
  654. if err != nil {
  655. beego.Error(err)
  656. continue
  657. }
  658. if doc.BookId != book_id {
  659. logs.Info("%s", "权限错误")
  660. continue
  661. }
  662. sort, ok := item["sort"].(float64)
  663. if !ok {
  664. beego.Info("排序数字转换失败 => ", item)
  665. continue
  666. }
  667. parent_id, ok := item["parent"].(float64)
  668. if !ok {
  669. beego.Info("父分类转换失败 => ", item)
  670. continue
  671. }
  672. if parent_id > 0 {
  673. if parent, err := models.NewDocument().Find(int(parent_id)); err != nil || parent.BookId != book_id {
  674. continue
  675. }
  676. }
  677. doc.OrderSort = int(sort)
  678. doc.ParentId = int(parent_id)
  679. if err := doc.InsertOrUpdate(); err != nil {
  680. fmt.Printf("%s", err.Error())
  681. beego.Error(err)
  682. }
  683. } else {
  684. fmt.Printf("文档ID转换失败 => %+v", item)
  685. }
  686. }
  687. c.JsonResult(0, "ok")
  688. }
  689. func (c *BookController) Team() {
  690. c.Prepare()
  691. c.TplName = "book/team.tpl"
  692. key := c.Ctx.Input.Param(":key")
  693. pageIndex, _ := c.GetInt("page", 1)
  694. if key == "" {
  695. c.ShowErrorPage(404, "项目不存在或已删除")
  696. }
  697. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  698. if err != nil {
  699. if err == models.ErrPermissionDenied {
  700. c.ShowErrorPage(403, "权限不足")
  701. }
  702. c.ShowErrorPage(500, "系统错误")
  703. }
  704. c.Data["Model"] = book
  705. members, totalCount, err := models.NewTeamRelationship().FindByBookToPager(book.BookId, pageIndex, conf.PageSize)
  706. if totalCount > 0 {
  707. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  708. c.Data["PageHtml"] = pager.HtmlPages()
  709. } else {
  710. c.Data["PageHtml"] = ""
  711. }
  712. b, err := json.Marshal(members)
  713. if err != nil {
  714. c.Data["Result"] = template.JS("[]")
  715. } else {
  716. c.Data["Result"] = template.JS(string(b))
  717. }
  718. }
  719. func (c *BookController) TeamAdd() {
  720. c.Prepare()
  721. teamId, _ := c.GetInt("teamId")
  722. book, err := c.IsPermission()
  723. if err != nil {
  724. c.JsonResult(500, err.Error())
  725. }
  726. _, err = models.NewTeam().First(teamId, "team_id")
  727. if err != nil {
  728. if err == orm.ErrNoRows {
  729. c.JsonResult(500, "团队不存在")
  730. }
  731. c.JsonResult(5002, err.Error())
  732. }
  733. if _, err := models.NewTeamRelationship().FindByBookId(book.BookId, teamId); err == nil {
  734. c.JsonResult(5003, "团队已加入当前项目")
  735. }
  736. teamRel := models.NewTeamRelationship()
  737. teamRel.BookId = book.BookId
  738. teamRel.TeamId = teamId
  739. err = teamRel.Save()
  740. if err != nil {
  741. c.JsonResult(5004, "加入项目失败")
  742. }
  743. teamRel.Include()
  744. c.JsonResult(0, "OK", teamRel)
  745. }
  746. //删除项目的团队.
  747. func (c *BookController) TeamDelete() {
  748. c.Prepare()
  749. teamId, _ := c.GetInt("teamId")
  750. if teamId <= 0 {
  751. c.JsonResult(5001, "参数错误")
  752. }
  753. book, err := c.IsPermission()
  754. if err != nil {
  755. c.JsonResult(5002, err.Error())
  756. }
  757. beego.Error(book)
  758. err = models.NewTeamRelationship().DeleteByBookId(book.BookId, teamId)
  759. if err != nil {
  760. if err == orm.ErrNoRows {
  761. c.JsonResult(5003, "团队未加入项目")
  762. }
  763. c.JsonResult(5004, err.Error())
  764. }
  765. c.JsonResult(0, "OK")
  766. }
  767. //团队搜索.
  768. func (c *BookController) TeamSearch() {
  769. c.Prepare()
  770. keyword := strings.TrimSpace(c.GetString("q"))
  771. book, err := c.IsPermission()
  772. if err != nil {
  773. c.JsonResult(500, err.Error())
  774. }
  775. searchResult, err := models.NewTeamRelationship().FindNotJoinBookByBookIdentify(book.BookId, keyword, 10)
  776. if err != nil {
  777. c.JsonResult(500, err.Error(), searchResult)
  778. }
  779. c.JsonResult(0, "OK", searchResult)
  780. }
  781. //项目空间搜索.
  782. func (c *BookController) ItemsetsSearch() {
  783. c.Prepare()
  784. keyword := strings.TrimSpace(c.GetString("q"))
  785. searchResult, err := models.NewItemsets().FindItemsetsByName(keyword, 10)
  786. if err != nil {
  787. c.JsonResult(500, err.Error(), searchResult)
  788. }
  789. c.JsonResult(0, "OK", searchResult)
  790. }
  791. func (c *BookController) IsPermission() (*models.BookResult, error) {
  792. identify := c.GetString("identify")
  793. if identify == "" {
  794. return nil, errors.New("参数错误")
  795. }
  796. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  797. if err != nil {
  798. if err == models.ErrPermissionDenied {
  799. return book, errors.New("权限不足")
  800. }
  801. if err == orm.ErrNoRows {
  802. return book, errors.New("项目不存在")
  803. }
  804. return book, err
  805. }
  806. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  807. return book, errors.New("权限不足")
  808. }
  809. return book, nil
  810. }