BookController.go 26 KB

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