BookController.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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. book := models.NewBook()
  513. book.MemberId = c.Member.MemberId
  514. book.Cover = conf.GetDefaultCover()
  515. book.BookName = bookName
  516. book.Description = description
  517. book.CommentCount = 0
  518. book.PrivatelyOwned = privatelyOwned
  519. book.CommentStatus = "closed"
  520. book.Identify = identify
  521. book.DocCount = 0
  522. book.MemberId = c.Member.MemberId
  523. book.Version = time.Now().Unix()
  524. book.ItemId = itemId
  525. book.Editor = "markdown"
  526. book.Theme = "default"
  527. if strings.EqualFold(ext, ".zip") {
  528. go book.ImportBook(tempPath, c.Lang)
  529. } else if strings.EqualFold(ext, ".docx") {
  530. go book.ImportWordBook(tempPath, c.Lang)
  531. }
  532. logs.Info("用户[", c.Member.Account, "]导入了项目 ->", book)
  533. c.JsonResult(0, "项目正在后台转换中,请稍后查看")
  534. }
  535. // CreateToken 创建访问来令牌.
  536. //func (c *BookController) CreateToken() {
  537. //
  538. // action := c.GetString("action")
  539. //
  540. // bookResult, err := c.IsPermission()
  541. //
  542. // if err != nil {
  543. // if err == models.ErrPermissionDenied {
  544. // c.JsonResult(403, i18n.Tr(c.Lang, "message.no_permission"))
  545. // }
  546. // if err == orm.ErrNoRows {
  547. // c.JsonResult(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  548. // }
  549. // logs.Error("生成阅读令牌失败 =>", err)
  550. // c.JsonResult(6002, err.Error())
  551. // }
  552. // book := models.NewBook()
  553. //
  554. // if _, err := book.Find(bookResult.BookId); err != nil {
  555. // c.JsonResult(6001, i18n.Tr(c.Lang, "message.item_not_exist"))
  556. // }
  557. // if action == "create" {
  558. // if bookResult.PrivatelyOwned == 0 {
  559. // c.JsonResult(6001, "公开项目不能创建阅读令牌")
  560. // }
  561. //
  562. // book.PrivateToken = string(utils.Krand(conf.GetTokenSize(), utils.KC_RAND_KIND_ALL))
  563. // if err := book.Update(); err != nil {
  564. // logs.Error("生成阅读令牌失败 => ", err)
  565. // c.JsonResult(6003, "生成阅读令牌失败")
  566. // }
  567. // logs.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken)
  568. // c.JsonResult(0, "ok", conf.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken))
  569. // } else {
  570. // book.PrivateToken = ""
  571. // if err := book.Update(); err != nil {
  572. // logs.Error("CreateToken => ", err)
  573. // c.JsonResult(6004, "删除令牌失败")
  574. // }
  575. // logs.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken)
  576. // c.JsonResult(0, "ok", "")
  577. // }
  578. //}
  579. // Delete 删除项目.
  580. func (c *BookController) Delete() {
  581. c.Prepare()
  582. bookResult, err := c.IsPermission()
  583. if err != nil {
  584. c.JsonResult(6001, err.Error())
  585. return
  586. }
  587. if bookResult.RoleId != conf.BookFounder {
  588. c.JsonResult(6002, "只有创始人才能删除项目")
  589. }
  590. err = models.NewBook().ThoroughDeleteBook(bookResult.BookId)
  591. if err == orm.ErrNoRows {
  592. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist"))
  593. }
  594. if err != nil {
  595. logs.Error("删除项目 => ", err)
  596. c.JsonResult(6003, "删除失败")
  597. }
  598. logs.Info("用户[", c.Member.Account, "]删除了项目 ->", bookResult)
  599. c.JsonResult(0, "ok")
  600. }
  601. //发布项目.
  602. func (c *BookController) Release() {
  603. c.Prepare()
  604. identify := c.GetString("identify")
  605. bookId := 0
  606. if c.Member.IsAdministrator() {
  607. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  608. if err != nil {
  609. logs.Error("发布文档失败 ->", err)
  610. c.JsonResult(6003, "文档不存在")
  611. return
  612. }
  613. bookId = book.BookId
  614. } else {
  615. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  616. if err != nil {
  617. if err == models.ErrPermissionDenied {
  618. c.JsonResult(6001, i18n.Tr(c.Lang, "message.no_permission"))
  619. }
  620. if err == orm.ErrNoRows {
  621. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist"))
  622. }
  623. logs.Error(err)
  624. c.JsonResult(6003, i18n.Tr(c.Lang, "message.unknown_exception"))
  625. }
  626. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor {
  627. c.JsonResult(6003, i18n.Tr(c.Lang, "message.no_permission"))
  628. }
  629. bookId = book.BookId
  630. }
  631. go models.NewBook().ReleaseContent(bookId, c.Lang)
  632. c.JsonResult(0, i18n.Tr(c.Lang, "message.publish_to_queue"))
  633. }
  634. //文档排序.
  635. func (c *BookController) SaveSort() {
  636. c.Prepare()
  637. identify := c.Ctx.Input.Param(":key")
  638. if identify == "" {
  639. c.Abort("404")
  640. }
  641. bookId := 0
  642. if c.Member.IsAdministrator() {
  643. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  644. if err != nil || book == nil {
  645. c.JsonResult(6001, i18n.Tr(c.Lang, "message.item_not_exist"))
  646. return
  647. }
  648. bookId = book.BookId
  649. } else {
  650. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  651. if err != nil {
  652. logs.Error("DocumentController.Edit => ", err)
  653. c.Abort("403")
  654. }
  655. if bookResult.RoleId == conf.BookObserver {
  656. c.JsonResult(6002, i18n.Tr(c.Lang, "message.item_not_exist_or_no_permit"))
  657. }
  658. bookId = bookResult.BookId
  659. }
  660. content := c.Ctx.Input.RequestBody
  661. var docs []map[string]interface{}
  662. err := json.Unmarshal(content, &docs)
  663. if err != nil {
  664. logs.Error(err)
  665. c.JsonResult(6003, "数据错误")
  666. }
  667. for _, item := range docs {
  668. if docId, ok := item["id"].(float64); ok {
  669. doc, err := models.NewDocument().Find(int(docId))
  670. if err != nil {
  671. logs.Error(err)
  672. continue
  673. }
  674. if doc.BookId != bookId {
  675. logs.Info("%s", i18n.Tr(c.Lang, "message.no_permission"))
  676. continue
  677. }
  678. sort, ok := item["sort"].(float64)
  679. if !ok {
  680. logs.Info("排序数字转换失败 => ", item)
  681. continue
  682. }
  683. parentId, ok := item["parent"].(float64)
  684. if !ok {
  685. logs.Info("父分类转换失败 => ", item)
  686. continue
  687. }
  688. if parentId > 0 {
  689. if parent, err := models.NewDocument().Find(int(parentId)); err != nil || parent.BookId != bookId {
  690. continue
  691. }
  692. }
  693. doc.OrderSort = int(sort)
  694. doc.ParentId = int(parentId)
  695. if err := doc.InsertOrUpdate(); err != nil {
  696. fmt.Printf("%s", err.Error())
  697. logs.Error(err)
  698. }
  699. } else {
  700. fmt.Printf("文档ID转换失败 => %+v", item)
  701. }
  702. }
  703. c.JsonResult(0, "ok")
  704. }
  705. func (c *BookController) Team() {
  706. c.Prepare()
  707. c.TplName = "book/team.tpl"
  708. key := c.Ctx.Input.Param(":key")
  709. pageIndex, _ := c.GetInt("page", 1)
  710. if key == "" {
  711. c.ShowErrorPage(404, i18n.Tr(c.Lang, "message.item_not_exist"))
  712. }
  713. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  714. if err != nil || book == nil {
  715. if err == models.ErrPermissionDenied {
  716. c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.no_permission"))
  717. }
  718. c.ShowErrorPage(500, i18n.Tr(c.Lang, "message.system_error"))
  719. return
  720. }
  721. //如果不是创始人也不是管理员则不能操作
  722. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  723. c.Abort("403")
  724. }
  725. c.Data["Model"] = book
  726. members, totalCount, err := models.NewTeamRelationship().FindByBookToPager(book.BookId, pageIndex, conf.PageSize)
  727. if totalCount > 0 {
  728. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  729. c.Data["PageHtml"] = pager.HtmlPages()
  730. } else {
  731. c.Data["PageHtml"] = ""
  732. }
  733. b, err := json.Marshal(members)
  734. if err != nil {
  735. c.Data["Result"] = template.JS("[]")
  736. } else {
  737. c.Data["Result"] = template.JS(string(b))
  738. }
  739. }
  740. func (c *BookController) TeamAdd() {
  741. c.Prepare()
  742. teamId, _ := c.GetInt("teamId")
  743. book, err := c.IsPermission()
  744. if err != nil {
  745. c.JsonResult(500, err.Error())
  746. return
  747. }
  748. //如果不是创始人也不是管理员则不能操作
  749. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  750. c.Abort("403")
  751. }
  752. _, err = models.NewTeam().First(teamId, "team_id")
  753. if err != nil {
  754. if err == orm.ErrNoRows {
  755. c.JsonResult(500, "团队不存在")
  756. }
  757. c.JsonResult(5002, err.Error())
  758. }
  759. if _, err := models.NewTeamRelationship().FindByBookId(book.BookId, teamId); err == nil {
  760. c.JsonResult(5003, "团队已加入当前项目")
  761. }
  762. teamRel := models.NewTeamRelationship()
  763. teamRel.BookId = book.BookId
  764. teamRel.TeamId = teamId
  765. err = teamRel.Save()
  766. if err != nil {
  767. c.JsonResult(5004, "加入项目失败")
  768. return
  769. }
  770. teamRel.Include()
  771. c.JsonResult(0, "OK", teamRel)
  772. }
  773. //删除项目的团队.
  774. func (c *BookController) TeamDelete() {
  775. c.Prepare()
  776. teamId, _ := c.GetInt("teamId")
  777. if teamId <= 0 {
  778. c.JsonResult(5001, i18n.Tr(c.Lang, "message.param_error"))
  779. }
  780. book, err := c.IsPermission()
  781. if err != nil {
  782. c.JsonResult(5002, err.Error())
  783. return
  784. }
  785. //如果不是创始人也不是管理员则不能操作
  786. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  787. c.Abort("403")
  788. }
  789. err = models.NewTeamRelationship().DeleteByBookId(book.BookId, teamId)
  790. if err != nil {
  791. if err == orm.ErrNoRows {
  792. c.JsonResult(5003, "团队未加入项目")
  793. }
  794. c.JsonResult(5004, err.Error())
  795. }
  796. c.JsonResult(0, "OK")
  797. }
  798. //团队搜索.
  799. func (c *BookController) TeamSearch() {
  800. c.Prepare()
  801. keyword := strings.TrimSpace(c.GetString("q"))
  802. book, err := c.IsPermission()
  803. if err != nil {
  804. c.JsonResult(500, err.Error())
  805. }
  806. keyword = sqltil.EscapeLike(keyword)
  807. searchResult, err := models.NewTeamRelationship().FindNotJoinBookByBookIdentify(book.BookId, keyword, 10)
  808. if err != nil {
  809. c.JsonResult(500, err.Error(), searchResult)
  810. }
  811. c.JsonResult(0, "OK", searchResult)
  812. }
  813. //项目空间搜索.
  814. func (c *BookController) ItemsetsSearch() {
  815. c.Prepare()
  816. keyword := strings.TrimSpace(c.GetString("q"))
  817. keyword = sqltil.EscapeLike(keyword)
  818. searchResult, err := models.NewItemsets().FindItemsetsByName(keyword, 10)
  819. if err != nil {
  820. c.JsonResult(500, err.Error(), searchResult)
  821. }
  822. c.JsonResult(0, "OK", searchResult)
  823. }
  824. func (c *BookController) IsPermission() (*models.BookResult, error) {
  825. identify := c.GetString("identify")
  826. if identify == "" {
  827. return nil, errors.New(i18n.Tr(c.Lang, "message.param_error"))
  828. }
  829. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  830. if err != nil {
  831. if err == models.ErrPermissionDenied {
  832. return book, errors.New(i18n.Tr(c.Lang, "message.no_permission"))
  833. }
  834. if err == orm.ErrNoRows {
  835. return book, errors.New(i18n.Tr(c.Lang, "message.item_not_exist"))
  836. }
  837. return book, err
  838. }
  839. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  840. return book, errors.New(i18n.Tr(c.Lang, "message.no_permission"))
  841. }
  842. return book, nil
  843. }