BookController.go 28 KB

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