BookController.go 28 KB

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