BookController.go 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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. //如果不是创始人也不是管理员则不能操作
  339. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  340. c.Abort("403")
  341. }
  342. c.Data["Model"] = *book
  343. members, totalCount, err := models.NewMemberRelationshipResult().FindForUsersByBookId(book.BookId, pageIndex, conf.PageSize)
  344. if totalCount > 0 {
  345. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  346. c.Data["PageHtml"] = pager.HtmlPages()
  347. } else {
  348. c.Data["PageHtml"] = ""
  349. }
  350. b, err := json.Marshal(members)
  351. if err != nil {
  352. c.Data["Result"] = template.JS("[]")
  353. } else {
  354. c.Data["Result"] = template.JS(string(b))
  355. }
  356. }
  357. // Create 创建项目.
  358. func (c *BookController) Create() {
  359. if c.Ctx.Input.IsPost() {
  360. bookName := strings.TrimSpace(c.GetString("book_name", ""))
  361. identify := strings.TrimSpace(c.GetString("identify", ""))
  362. description := strings.TrimSpace(c.GetString("description", ""))
  363. privatelyOwned, _ := strconv.Atoi(c.GetString("privately_owned"))
  364. commentStatus := c.GetString("comment_status")
  365. itemId, _ := c.GetInt("itemId")
  366. if bookName == "" {
  367. c.JsonResult(6001, "项目名称不能为空")
  368. }
  369. if identify == "" {
  370. c.JsonResult(6002, "项目标识不能为空")
  371. }
  372. if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, identify); !ok || err != nil {
  373. c.JsonResult(6003, "项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  374. }
  375. if strings.Count(identify, "") > 50 {
  376. c.JsonResult(6004, "文档标识不能超过50字")
  377. }
  378. if strings.Count(description, "") > 500 {
  379. c.JsonResult(6004, "项目描述不能大于500字")
  380. }
  381. if privatelyOwned != 0 && privatelyOwned != 1 {
  382. privatelyOwned = 1
  383. }
  384. if !models.NewItemsets().Exist(itemId) {
  385. c.JsonResult(6005, "项目空间不存在")
  386. }
  387. if commentStatus != "open" && commentStatus != "closed" && commentStatus != "group_only" && commentStatus != "registered_only" {
  388. commentStatus = "closed"
  389. }
  390. book := models.NewBook()
  391. book.Cover = conf.GetDefaultCover()
  392. //如果客户端上传了项目封面则直接保存
  393. if file, moreFile, err := c.GetFile("image-file"); err == nil {
  394. defer file.Close()
  395. ext := filepath.Ext(moreFile.Filename)
  396. //如果上传的是图片
  397. if strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".gif") || strings.EqualFold(ext, ".jpeg") {
  398. fileName := "cover_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  399. filePath := filepath.Join("uploads", time.Now().Format("200601"), fileName+ext)
  400. path := filepath.Dir(filePath)
  401. os.MkdirAll(path, os.ModePerm)
  402. if err := c.SaveToFile("image-file", filePath); err == nil {
  403. url := "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
  404. if strings.HasPrefix(url, "//") {
  405. url = string(url[1:])
  406. }
  407. book.Cover = url
  408. }
  409. }
  410. }
  411. if books, _ := book.FindByField("identify", identify, "book_id"); len(books) > 0 {
  412. c.JsonResult(6006, "项目标识已存在")
  413. }
  414. book.BookName = bookName
  415. book.Description = description
  416. book.CommentCount = 0
  417. book.PrivatelyOwned = privatelyOwned
  418. book.CommentStatus = commentStatus
  419. book.Identify = identify
  420. book.DocCount = 0
  421. book.MemberId = c.Member.MemberId
  422. book.CommentCount = 0
  423. book.Version = time.Now().Unix()
  424. book.IsEnableShare = 0
  425. book.IsUseFirstDocument = 1
  426. book.IsDownload = 1
  427. book.AutoRelease = 0
  428. book.ItemId = itemId
  429. book.Editor = "markdown"
  430. book.Theme = "default"
  431. if err := book.Insert(); err != nil {
  432. logs.Error("Insert => ", err)
  433. c.JsonResult(6005, "保存项目失败")
  434. }
  435. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  436. if err != nil {
  437. beego.Error(err)
  438. }
  439. beego.Info("用户[", c.Member.Account, "]创建了项目 ->", book)
  440. c.JsonResult(0, "ok", bookResult)
  441. }
  442. c.JsonResult(6001, "error")
  443. }
  444. //复制项目
  445. func (c *BookController) Copy() {
  446. if c.Ctx.Input.IsPost() {
  447. //检查是否有复制项目的权限
  448. if _, err := c.IsPermission(); err != nil {
  449. c.JsonResult(500, err.Error())
  450. }
  451. identify := strings.TrimSpace(c.GetString("identify", ""))
  452. if identify == "" {
  453. c.JsonResult(6001, "参数错误")
  454. }
  455. book := models.NewBook()
  456. err := book.Copy(identify)
  457. if err != nil {
  458. c.JsonResult(6002, "复制项目出错")
  459. } else {
  460. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  461. if err != nil {
  462. beego.Error("查询失败")
  463. }
  464. c.JsonResult(0, "ok", bookResult)
  465. }
  466. }
  467. }
  468. //导入zip压缩包
  469. func (c *BookController) Import() {
  470. file, moreFile, err := c.GetFile("import-file")
  471. if err == http.ErrMissingFile {
  472. c.JsonResult(6003, "没有发现需要上传的文件")
  473. }
  474. defer file.Close()
  475. bookName := strings.TrimSpace(c.GetString("book_name"))
  476. identify := strings.TrimSpace(c.GetString("identify"))
  477. description := strings.TrimSpace(c.GetString("description", ""))
  478. privatelyOwned, _ := strconv.Atoi(c.GetString("privately_owned"))
  479. itemId, _ := c.GetInt("itemId")
  480. if bookName == "" {
  481. c.JsonResult(6001, "项目名称不能为空")
  482. }
  483. if len([]rune(bookName)) > 500 {
  484. c.JsonResult(6002, "项目名称不能大于500字")
  485. }
  486. if identify == "" {
  487. c.JsonResult(6002, "项目标识不能为空")
  488. }
  489. if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, identify); !ok || err != nil {
  490. c.JsonResult(6003, "项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  491. }
  492. if !models.NewItemsets().Exist(itemId) {
  493. c.JsonResult(6007, "项目空间不存在")
  494. }
  495. if strings.Count(identify, "") > 50 {
  496. c.JsonResult(6004, "文档标识不能超过50字")
  497. }
  498. ext := filepath.Ext(moreFile.Filename)
  499. if !strings.EqualFold(ext, ".zip") {
  500. c.JsonResult(6004, "不支持的文件类型")
  501. }
  502. if books, _ := models.NewBook().FindByField("identify", identify, "book_id"); len(books) > 0 {
  503. c.JsonResult(6006, "项目标识已存在")
  504. }
  505. tempPath := filepath.Join(os.TempDir(), c.CruSession.SessionID())
  506. os.MkdirAll(tempPath, 0766)
  507. tempPath = filepath.Join(tempPath, moreFile.Filename)
  508. err = c.SaveToFile("import-file", tempPath)
  509. book := models.NewBook()
  510. book.MemberId = c.Member.MemberId
  511. book.Cover = conf.GetDefaultCover()
  512. book.BookName = bookName
  513. book.Description = description
  514. book.CommentCount = 0
  515. book.PrivatelyOwned = privatelyOwned
  516. book.CommentStatus = "closed"
  517. book.Identify = identify
  518. book.DocCount = 0
  519. book.MemberId = c.Member.MemberId
  520. book.CommentCount = 0
  521. book.Version = time.Now().Unix()
  522. book.ItemId = itemId
  523. book.Editor = "markdown"
  524. book.Theme = "default"
  525. go book.ImportBook(tempPath)
  526. beego.Info("用户[", c.Member.Account, "]导入了项目 ->", book)
  527. c.JsonResult(0, "项目正在后台转换中,请稍后查看")
  528. }
  529. // CreateToken 创建访问来令牌.
  530. func (c *BookController) CreateToken() {
  531. action := c.GetString("action")
  532. bookResult, err := c.IsPermission()
  533. if err != nil {
  534. if err == models.ErrPermissionDenied {
  535. c.JsonResult(403, "权限不足")
  536. }
  537. if err == orm.ErrNoRows {
  538. c.JsonResult(404, "项目不存在")
  539. }
  540. logs.Error("生成阅读令牌失败 =>", err)
  541. c.JsonResult(6002, err.Error())
  542. }
  543. book := models.NewBook()
  544. if _, err := book.Find(bookResult.BookId); err != nil {
  545. c.JsonResult(6001, "项目不存在")
  546. }
  547. if action == "create" {
  548. if bookResult.PrivatelyOwned == 0 {
  549. c.JsonResult(6001, "公开项目不能创建阅读令牌")
  550. }
  551. book.PrivateToken = string(utils.Krand(conf.GetTokenSize(), utils.KC_RAND_KIND_ALL))
  552. if err := book.Update(); err != nil {
  553. logs.Error("生成阅读令牌失败 => ", err)
  554. c.JsonResult(6003, "生成阅读令牌失败")
  555. }
  556. beego.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken)
  557. c.JsonResult(0, "ok", conf.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken))
  558. } else {
  559. book.PrivateToken = ""
  560. if err := book.Update(); err != nil {
  561. logs.Error("CreateToken => ", err)
  562. c.JsonResult(6004, "删除令牌失败")
  563. }
  564. beego.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken)
  565. c.JsonResult(0, "ok", "")
  566. }
  567. }
  568. // Delete 删除项目.
  569. func (c *BookController) Delete() {
  570. c.Prepare()
  571. bookResult, err := c.IsPermission()
  572. if err != nil {
  573. c.JsonResult(6001, err.Error())
  574. }
  575. if bookResult.RoleId != conf.BookFounder {
  576. c.JsonResult(6002, "只有创始人才能删除项目")
  577. }
  578. err = models.NewBook().ThoroughDeleteBook(bookResult.BookId)
  579. if err == orm.ErrNoRows {
  580. c.JsonResult(6002, "项目不存在")
  581. }
  582. if err != nil {
  583. logs.Error("删除项目 => ", err)
  584. c.JsonResult(6003, "删除失败")
  585. }
  586. beego.Info("用户[", c.Member.Account, "]删除了项目 ->", bookResult)
  587. c.JsonResult(0, "ok")
  588. }
  589. //发布项目.
  590. func (c *BookController) Release() {
  591. c.Prepare()
  592. identify := c.GetString("identify")
  593. bookId := 0
  594. if c.Member.IsAdministrator() {
  595. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  596. if err != nil {
  597. }
  598. bookId = book.BookId
  599. } else {
  600. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  601. if err != nil {
  602. if err == models.ErrPermissionDenied {
  603. c.JsonResult(6001, "权限不足")
  604. }
  605. if err == orm.ErrNoRows {
  606. c.JsonResult(6002, "项目不存在")
  607. }
  608. beego.Error(err)
  609. c.JsonResult(6003, "未知错误")
  610. }
  611. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor {
  612. c.JsonResult(6003, "权限不足")
  613. }
  614. bookId = book.BookId
  615. }
  616. go func(identify string) {
  617. models.NewBook().ReleaseContent(bookId)
  618. //当文档发布后,需要删除已缓存的转换项目
  619. outputPath := filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(bookId))
  620. os.RemoveAll(outputPath)
  621. }(identify)
  622. c.JsonResult(0, "发布任务已推送到任务队列,稍后将在后台执行。")
  623. }
  624. //文档排序.
  625. func (c *BookController) SaveSort() {
  626. c.Prepare()
  627. identify := c.Ctx.Input.Param(":key")
  628. if identify == "" {
  629. c.Abort("404")
  630. }
  631. book_id := 0
  632. if c.Member.IsAdministrator() {
  633. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  634. if err != nil {
  635. }
  636. book_id = book.BookId
  637. } else {
  638. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  639. if err != nil {
  640. beego.Error("DocumentController.Edit => ", err)
  641. c.Abort("403")
  642. }
  643. if bookResult.RoleId == conf.BookObserver {
  644. c.JsonResult(6002, "项目不存在或权限不足")
  645. }
  646. book_id = bookResult.BookId
  647. }
  648. content := c.Ctx.Input.RequestBody
  649. var docs []map[string]interface{}
  650. err := json.Unmarshal(content, &docs)
  651. if err != nil {
  652. beego.Error(err)
  653. c.JsonResult(6003, "数据错误")
  654. }
  655. for _, item := range docs {
  656. if doc_id, ok := item["id"].(float64); ok {
  657. doc, err := models.NewDocument().Find(int(doc_id))
  658. if err != nil {
  659. beego.Error(err)
  660. continue
  661. }
  662. if doc.BookId != book_id {
  663. logs.Info("%s", "权限错误")
  664. continue
  665. }
  666. sort, ok := item["sort"].(float64)
  667. if !ok {
  668. beego.Info("排序数字转换失败 => ", item)
  669. continue
  670. }
  671. parent_id, ok := item["parent"].(float64)
  672. if !ok {
  673. beego.Info("父分类转换失败 => ", item)
  674. continue
  675. }
  676. if parent_id > 0 {
  677. if parent, err := models.NewDocument().Find(int(parent_id)); err != nil || parent.BookId != book_id {
  678. continue
  679. }
  680. }
  681. doc.OrderSort = int(sort)
  682. doc.ParentId = int(parent_id)
  683. if err := doc.InsertOrUpdate(); err != nil {
  684. fmt.Printf("%s", err.Error())
  685. beego.Error(err)
  686. }
  687. } else {
  688. fmt.Printf("文档ID转换失败 => %+v", item)
  689. }
  690. }
  691. c.JsonResult(0, "ok")
  692. }
  693. func (c *BookController) Team() {
  694. c.Prepare()
  695. c.TplName = "book/team.tpl"
  696. key := c.Ctx.Input.Param(":key")
  697. pageIndex, _ := c.GetInt("page", 1)
  698. if key == "" {
  699. c.ShowErrorPage(404, "项目不存在或已删除")
  700. }
  701. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  702. if err != nil {
  703. if err == models.ErrPermissionDenied {
  704. c.ShowErrorPage(403, "权限不足")
  705. }
  706. c.ShowErrorPage(500, "系统错误")
  707. }
  708. //如果不是创始人也不是管理员则不能操作
  709. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  710. c.Abort("403")
  711. }
  712. c.Data["Model"] = book
  713. members, totalCount, err := models.NewTeamRelationship().FindByBookToPager(book.BookId, pageIndex, conf.PageSize)
  714. if totalCount > 0 {
  715. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  716. c.Data["PageHtml"] = pager.HtmlPages()
  717. } else {
  718. c.Data["PageHtml"] = ""
  719. }
  720. b, err := json.Marshal(members)
  721. if err != nil {
  722. c.Data["Result"] = template.JS("[]")
  723. } else {
  724. c.Data["Result"] = template.JS(string(b))
  725. }
  726. }
  727. func (c *BookController) TeamAdd() {
  728. c.Prepare()
  729. teamId, _ := c.GetInt("teamId")
  730. book, err := c.IsPermission()
  731. if err != nil {
  732. c.JsonResult(500, err.Error())
  733. }
  734. //如果不是创始人也不是管理员则不能操作
  735. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  736. c.Abort("403")
  737. }
  738. _, err = models.NewTeam().First(teamId, "team_id")
  739. if err != nil {
  740. if err == orm.ErrNoRows {
  741. c.JsonResult(500, "团队不存在")
  742. }
  743. c.JsonResult(5002, err.Error())
  744. }
  745. if _, err := models.NewTeamRelationship().FindByBookId(book.BookId, teamId); err == nil {
  746. c.JsonResult(5003, "团队已加入当前项目")
  747. }
  748. teamRel := models.NewTeamRelationship()
  749. teamRel.BookId = book.BookId
  750. teamRel.TeamId = teamId
  751. err = teamRel.Save()
  752. if err != nil {
  753. c.JsonResult(5004, "加入项目失败")
  754. }
  755. teamRel.Include()
  756. c.JsonResult(0, "OK", teamRel)
  757. }
  758. //删除项目的团队.
  759. func (c *BookController) TeamDelete() {
  760. c.Prepare()
  761. teamId, _ := c.GetInt("teamId")
  762. if teamId <= 0 {
  763. c.JsonResult(5001, "参数错误")
  764. }
  765. book, err := c.IsPermission()
  766. if err != nil {
  767. c.JsonResult(5002, err.Error())
  768. }
  769. //如果不是创始人也不是管理员则不能操作
  770. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  771. c.Abort("403")
  772. }
  773. err = models.NewTeamRelationship().DeleteByBookId(book.BookId, teamId)
  774. if err != nil {
  775. if err == orm.ErrNoRows {
  776. c.JsonResult(5003, "团队未加入项目")
  777. }
  778. c.JsonResult(5004, err.Error())
  779. }
  780. c.JsonResult(0, "OK")
  781. }
  782. //团队搜索.
  783. func (c *BookController) TeamSearch() {
  784. c.Prepare()
  785. keyword := strings.TrimSpace(c.GetString("q"))
  786. book, err := c.IsPermission()
  787. if err != nil {
  788. c.JsonResult(500, err.Error())
  789. }
  790. searchResult, err := models.NewTeamRelationship().FindNotJoinBookByBookIdentify(book.BookId, keyword, 10)
  791. if err != nil {
  792. c.JsonResult(500, err.Error(), searchResult)
  793. }
  794. c.JsonResult(0, "OK", searchResult)
  795. }
  796. //项目空间搜索.
  797. func (c *BookController) ItemsetsSearch() {
  798. c.Prepare()
  799. keyword := strings.TrimSpace(c.GetString("q"))
  800. searchResult, err := models.NewItemsets().FindItemsetsByName(keyword, 10)
  801. if err != nil {
  802. c.JsonResult(500, err.Error(), searchResult)
  803. }
  804. c.JsonResult(0, "OK", searchResult)
  805. }
  806. func (c *BookController) IsPermission() (*models.BookResult, error) {
  807. identify := c.GetString("identify")
  808. if identify == "" {
  809. return nil, errors.New("参数错误")
  810. }
  811. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  812. if err != nil {
  813. if err == models.ErrPermissionDenied {
  814. return book, errors.New("权限不足")
  815. }
  816. if err == orm.ErrNoRows {
  817. return book, errors.New("项目不存在")
  818. }
  819. return book, err
  820. }
  821. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  822. return book, errors.New("权限不足")
  823. }
  824. return book, nil
  825. }