BookController.go 27 KB

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