BookController.go 26 KB

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