BookController.go 26 KB

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