BookController.go 28 KB

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