BookController.go 27 KB

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