1
0

BookController.go 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/lifei6671/mindoc/utils/sqltil"
  7. "html/template"
  8. "os"
  9. "path/filepath"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "net/http"
  15. "github.com/astaxie/beego"
  16. "github.com/astaxie/beego/logs"
  17. "github.com/astaxie/beego/orm"
  18. "github.com/lifei6671/mindoc/conf"
  19. "github.com/lifei6671/mindoc/graphics"
  20. "github.com/lifei6671/mindoc/models"
  21. "github.com/lifei6671/mindoc/utils"
  22. "github.com/lifei6671/mindoc/utils/pagination"
  23. "gopkg.in/russross/blackfriday.v2"
  24. )
  25. type BookController struct {
  26. BaseController
  27. }
  28. func (c *BookController) Index() {
  29. c.Prepare()
  30. c.TplName = "book/index.tpl"
  31. pageIndex, _ := c.GetInt("page", 1)
  32. books, totalCount, err := models.NewBook().FindToPager(pageIndex, conf.PageSize, c.Member.MemberId)
  33. if err != nil {
  34. logs.Error("BookController.Index => ", err)
  35. c.Abort("500")
  36. }
  37. for i, book := range books {
  38. books[i].Description = utils.StripTags(string(blackfriday.Run([]byte(book.Description))))
  39. books[i].ModifyTime = book.ModifyTime.Local()
  40. books[i].CreateTime = book.CreateTime.Local()
  41. }
  42. if totalCount > 0 {
  43. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  44. c.Data["PageHtml"] = pager.HtmlPages()
  45. } else {
  46. c.Data["PageHtml"] = ""
  47. }
  48. b, err := json.Marshal(books)
  49. if err != nil || len(books) <= 0 {
  50. c.Data["Result"] = template.JS("[]")
  51. } else {
  52. c.Data["Result"] = template.JS(string(b))
  53. }
  54. if itemsets, err := models.NewItemsets().First(1); err == nil {
  55. c.Data["Item"] = itemsets
  56. }
  57. }
  58. // Dashboard 项目概要 .
  59. func (c *BookController) Dashboard() {
  60. c.Prepare()
  61. c.TplName = "book/dashboard.tpl"
  62. key := c.Ctx.Input.Param(":key")
  63. if key == "" {
  64. c.Abort("404")
  65. }
  66. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  67. if err != nil {
  68. if err == models.ErrPermissionDenied {
  69. c.Abort("403")
  70. }
  71. c.Abort("500")
  72. }
  73. c.Data["Description"] = template.HTML(blackfriday.Run([]byte(book.Description)))
  74. c.Data["Model"] = *book
  75. }
  76. // Setting 项目设置 .
  77. func (c *BookController) Setting() {
  78. c.Prepare()
  79. c.TplName = "book/setting.tpl"
  80. key := c.Ctx.Input.Param(":key")
  81. if key == "" {
  82. c.Abort("404")
  83. }
  84. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  85. if err != nil {
  86. if err == orm.ErrNoRows {
  87. c.Abort("404")
  88. }
  89. if err == models.ErrPermissionDenied {
  90. c.Abort("403")
  91. }
  92. c.Abort("500")
  93. }
  94. //如果不是创始人也不是管理员则不能操作
  95. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  96. c.Abort("403")
  97. }
  98. if book.PrivateToken != "" {
  99. book.PrivateToken = conf.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken)
  100. }
  101. c.Data["Model"] = book
  102. }
  103. //保存项目信息
  104. func (c *BookController) SaveBook() {
  105. bookResult, err := c.IsPermission()
  106. if err != nil {
  107. c.JsonResult(6001, err.Error())
  108. }
  109. book, err := models.NewBook().Find(bookResult.BookId)
  110. if err != nil {
  111. logs.Error("SaveBook => ", err)
  112. c.JsonResult(6002, err.Error())
  113. }
  114. bookName := strings.TrimSpace(c.GetString("book_name"))
  115. description := strings.TrimSpace(c.GetString("description", ""))
  116. commentStatus := c.GetString("comment_status")
  117. tag := strings.TrimSpace(c.GetString("label"))
  118. editor := strings.TrimSpace(c.GetString("editor"))
  119. autoRelease := strings.TrimSpace(c.GetString("auto_release")) == "on"
  120. publisher := strings.TrimSpace(c.GetString("publisher"))
  121. historyCount, _ := c.GetInt("history_count", 0)
  122. isDownload := strings.TrimSpace(c.GetString("is_download")) == "on"
  123. enableShare := strings.TrimSpace(c.GetString("enable_share")) == "on"
  124. isUseFirstDocument := strings.TrimSpace(c.GetString("is_use_first_document")) == "on"
  125. autoSave := strings.TrimSpace(c.GetString("auto_save")) == "on"
  126. itemId, _ := c.GetInt("itemId")
  127. if strings.Count(description, "") > 500 {
  128. c.JsonResult(6004, "项目描述不能大于500字")
  129. }
  130. if commentStatus != "open" && commentStatus != "closed" && commentStatus != "group_only" && commentStatus != "registered_only" {
  131. commentStatus = "closed"
  132. }
  133. if tag != "" {
  134. tags := strings.Split(tag, ",")
  135. if len(tags) > 10 {
  136. c.JsonResult(6005, "最多允许添加10个标签")
  137. }
  138. }
  139. if !models.NewItemsets().Exist(itemId) {
  140. c.JsonResult(6006, "项目空间不存在")
  141. }
  142. if editor != "markdown" && editor != "html" {
  143. editor = "markdown"
  144. }
  145. book.BookName = bookName
  146. book.Description = description
  147. book.CommentStatus = commentStatus
  148. book.Publisher = publisher
  149. book.Label = tag
  150. book.Editor = editor
  151. book.HistoryCount = historyCount
  152. book.IsDownload = 0
  153. book.BookPassword = strings.TrimSpace(c.GetString("bPassword"))
  154. book.ItemId = itemId
  155. if autoRelease {
  156. book.AutoRelease = 1
  157. } else {
  158. book.AutoRelease = 0
  159. }
  160. if isDownload {
  161. book.IsDownload = 0
  162. } else {
  163. book.IsDownload = 1
  164. }
  165. if enableShare {
  166. book.IsEnableShare = 0
  167. } else {
  168. book.IsEnableShare = 1
  169. }
  170. if isUseFirstDocument {
  171. book.IsUseFirstDocument = 1
  172. } else {
  173. book.IsUseFirstDocument = 0
  174. }
  175. if autoSave {
  176. book.AutoSave = 1
  177. } else {
  178. book.AutoSave = 0
  179. }
  180. if err := book.Update(); err != nil {
  181. c.JsonResult(6006, "保存失败")
  182. }
  183. bookResult.BookName = bookName
  184. bookResult.Description = description
  185. bookResult.CommentStatus = commentStatus
  186. bookResult.Label = tag
  187. beego.Info("用户 [", c.Member.Account, "] 修改了项目 ->", book)
  188. c.JsonResult(0, "ok", bookResult)
  189. }
  190. //设置项目私有状态.
  191. func (c *BookController) PrivatelyOwned() {
  192. status := c.GetString("status")
  193. if status != "open" && status != "close" {
  194. c.JsonResult(6003, "参数错误")
  195. }
  196. state := 0
  197. if status == "open" {
  198. state = 0
  199. } else {
  200. state = 1
  201. }
  202. bookResult, err := c.IsPermission()
  203. if err != nil {
  204. c.JsonResult(6001, err.Error())
  205. }
  206. //只有创始人才能变更私有状态
  207. if bookResult.RoleId != conf.BookFounder {
  208. c.JsonResult(6002, "权限不足")
  209. }
  210. book, err := models.NewBook().Find(bookResult.BookId)
  211. if err != nil {
  212. c.JsonResult(6005, "项目不存在")
  213. }
  214. book.PrivatelyOwned = state
  215. err = book.Update()
  216. if err != nil {
  217. logs.Error("PrivatelyOwned => ", err)
  218. c.JsonResult(6004, "保存失败")
  219. }
  220. beego.Info("用户 【", c.Member.Account, "]修改了项目权限 ->", state)
  221. c.JsonResult(0, "ok")
  222. }
  223. // Transfer 转让项目.
  224. func (c *BookController) Transfer() {
  225. c.Prepare()
  226. account := c.GetString("account")
  227. if account == "" {
  228. c.JsonResult(6004, "接受者账号不能为空")
  229. }
  230. member, err := models.NewMember().FindByAccount(account)
  231. if err != nil {
  232. logs.Error("FindByAccount => ", err)
  233. c.JsonResult(6005, "接受用户不存在")
  234. }
  235. if member.Status != 0 {
  236. c.JsonResult(6006, "接受用户已被禁用")
  237. }
  238. if member.MemberId == c.Member.MemberId {
  239. c.JsonResult(6007, "不能转让给自己")
  240. }
  241. bookResult, err := c.IsPermission()
  242. if err != nil {
  243. c.JsonResult(6001, err.Error())
  244. }
  245. err = models.NewRelationship().Transfer(bookResult.BookId, c.Member.MemberId, member.MemberId)
  246. if err != nil {
  247. logs.Error("转让项目失败 -> ", err)
  248. c.JsonResult(6008, err.Error())
  249. }
  250. c.JsonResult(0, "ok")
  251. }
  252. //上传项目封面.
  253. func (c *BookController) UploadCover() {
  254. bookResult, err := c.IsPermission()
  255. if err != nil {
  256. c.JsonResult(6001, err.Error())
  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. }
  268. defer file.Close()
  269. ext := filepath.Ext(moreFile.Filename)
  270. if !strings.EqualFold(ext, ".png") && !strings.EqualFold(ext, ".jpg") && !strings.EqualFold(ext, ".gif") && !strings.EqualFold(ext, ".jpeg") {
  271. c.JsonResult(500, "不支持的图片格式")
  272. }
  273. x1, _ := strconv.ParseFloat(c.GetString("x"), 10)
  274. y1, _ := strconv.ParseFloat(c.GetString("y"), 10)
  275. w1, _ := strconv.ParseFloat(c.GetString("width"), 10)
  276. h1, _ := strconv.ParseFloat(c.GetString("height"), 10)
  277. x := int(x1)
  278. y := int(y1)
  279. width := int(w1)
  280. height := int(h1)
  281. fileName := "cover_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  282. //附件路径按照项目组织
  283. filePath := filepath.Join("uploads", book.Identify, "images", fileName+ext)
  284. path := filepath.Dir(filePath)
  285. os.MkdirAll(path, os.ModePerm)
  286. err = c.SaveToFile("image-file", filePath)
  287. if err != nil {
  288. logs.Error("", err)
  289. c.JsonResult(500, "图片保存失败")
  290. }
  291. defer func(filePath string) {
  292. os.Remove(filePath)
  293. }(filePath)
  294. //剪切图片
  295. subImg, err := graphics.ImageCopyFromFile(filePath, x, y, width, height)
  296. if err != nil {
  297. logs.Error("graphics.ImageCopyFromFile => ", err)
  298. c.JsonResult(500, "图片剪切")
  299. }
  300. filePath = filepath.Join(conf.WorkingDirectory, "uploads", time.Now().Format("200601"), fileName+"_small"+ext)
  301. //生成缩略图并保存到磁盘
  302. err = graphics.ImageResizeSaveFile(subImg, 350, 460, filePath)
  303. if err != nil {
  304. logs.Error("ImageResizeSaveFile => ", err.Error())
  305. c.JsonResult(500, "保存图片失败")
  306. }
  307. url := "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
  308. if strings.HasPrefix(url, "//") {
  309. url = string(url[1:])
  310. }
  311. oldCover := book.Cover
  312. book.Cover = conf.URLForWithCdnImage(url)
  313. if err := book.Update(); err != nil {
  314. c.JsonResult(6001, "保存图片失败")
  315. }
  316. //如果原封面不是默认封面则删除
  317. if oldCover != conf.GetDefaultCover() {
  318. os.Remove("." + oldCover)
  319. }
  320. beego.Info("用户[", c.Member.Account, "]上传了项目封面 ->", book.BookName, book.BookId, book.Cover)
  321. c.JsonResult(0, "ok", url)
  322. }
  323. // Users 用户列表.
  324. func (c *BookController) Users() {
  325. c.Prepare()
  326. c.TplName = "book/users.tpl"
  327. key := c.Ctx.Input.Param(":key")
  328. pageIndex, _ := c.GetInt("page", 1)
  329. if key == "" {
  330. c.ShowErrorPage(404, "项目不存在或已删除")
  331. }
  332. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  333. if err != nil {
  334. if err == models.ErrPermissionDenied {
  335. c.Abort("403")
  336. }
  337. c.Abort("500")
  338. }
  339. //如果不是创始人也不是管理员则不能操作
  340. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  341. c.Abort("403")
  342. }
  343. c.Data["Model"] = *book
  344. members, totalCount, err := models.NewMemberRelationshipResult().FindForUsersByBookId(book.BookId, pageIndex, conf.PageSize)
  345. if totalCount > 0 {
  346. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  347. c.Data["PageHtml"] = pager.HtmlPages()
  348. } else {
  349. c.Data["PageHtml"] = ""
  350. }
  351. b, err := json.Marshal(members)
  352. if err != nil {
  353. c.Data["Result"] = template.JS("[]")
  354. } else {
  355. c.Data["Result"] = template.JS(string(b))
  356. }
  357. }
  358. // Create 创建项目.
  359. func (c *BookController) Create() {
  360. if c.Ctx.Input.IsPost() {
  361. bookName := strings.TrimSpace(c.GetString("book_name", ""))
  362. identify := strings.TrimSpace(c.GetString("identify", ""))
  363. description := strings.TrimSpace(c.GetString("description", ""))
  364. privatelyOwned, _ := strconv.Atoi(c.GetString("privately_owned"))
  365. commentStatus := c.GetString("comment_status")
  366. itemId, _ := c.GetInt("itemId")
  367. if bookName == "" {
  368. c.JsonResult(6001, "项目名称不能为空")
  369. }
  370. if identify == "" {
  371. c.JsonResult(6002, "项目标识不能为空")
  372. }
  373. if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, identify); !ok || err != nil {
  374. c.JsonResult(6003, "项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  375. }
  376. if strings.Count(identify, "") > 50 {
  377. c.JsonResult(6004, "文档标识不能超过50字")
  378. }
  379. if strings.Count(description, "") > 500 {
  380. c.JsonResult(6004, "项目描述不能大于500字")
  381. }
  382. if privatelyOwned != 0 && privatelyOwned != 1 {
  383. privatelyOwned = 1
  384. }
  385. if !models.NewItemsets().Exist(itemId) {
  386. c.JsonResult(6005, "项目空间不存在")
  387. }
  388. if commentStatus != "open" && commentStatus != "closed" && commentStatus != "group_only" && commentStatus != "registered_only" {
  389. commentStatus = "closed"
  390. }
  391. book := models.NewBook()
  392. book.Cover = conf.GetDefaultCover()
  393. //如果客户端上传了项目封面则直接保存
  394. if file, moreFile, err := c.GetFile("image-file"); err == nil {
  395. defer file.Close()
  396. ext := filepath.Ext(moreFile.Filename)
  397. //如果上传的是图片
  398. if strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".gif") || strings.EqualFold(ext, ".jpeg") {
  399. fileName := "cover_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  400. filePath := filepath.Join("uploads", time.Now().Format("200601"), fileName+ext)
  401. path := filepath.Dir(filePath)
  402. os.MkdirAll(path, os.ModePerm)
  403. if err := c.SaveToFile("image-file", filePath); err == nil {
  404. url := "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
  405. if strings.HasPrefix(url, "//") {
  406. url = string(url[1:])
  407. }
  408. book.Cover = url
  409. }
  410. }
  411. }
  412. if books, _ := book.FindByField("identify", identify, "book_id"); len(books) > 0 {
  413. c.JsonResult(6006, "项目标识已存在")
  414. }
  415. book.BookName = bookName
  416. book.Description = description
  417. book.CommentCount = 0
  418. book.PrivatelyOwned = privatelyOwned
  419. book.CommentStatus = commentStatus
  420. book.Identify = identify
  421. book.DocCount = 0
  422. book.MemberId = c.Member.MemberId
  423. book.CommentCount = 0
  424. book.Version = time.Now().Unix()
  425. book.IsEnableShare = 0
  426. book.IsUseFirstDocument = 1
  427. book.IsDownload = 1
  428. book.AutoRelease = 0
  429. book.ItemId = itemId
  430. book.Editor = "markdown"
  431. book.Theme = "default"
  432. if err := book.Insert(); err != nil {
  433. logs.Error("Insert => ", err)
  434. c.JsonResult(6005, "保存项目失败")
  435. }
  436. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  437. if err != nil {
  438. beego.Error(err)
  439. }
  440. beego.Info("用户[", c.Member.Account, "]创建了项目 ->", book)
  441. c.JsonResult(0, "ok", bookResult)
  442. }
  443. c.JsonResult(6001, "error")
  444. }
  445. //复制项目
  446. func (c *BookController) Copy() {
  447. if c.Ctx.Input.IsPost() {
  448. //检查是否有复制项目的权限
  449. if _, err := c.IsPermission(); err != nil {
  450. c.JsonResult(500, err.Error())
  451. }
  452. identify := strings.TrimSpace(c.GetString("identify", ""))
  453. if identify == "" {
  454. c.JsonResult(6001, "参数错误")
  455. }
  456. book := models.NewBook()
  457. err := book.Copy(identify)
  458. if err != nil {
  459. c.JsonResult(6002, "复制项目出错")
  460. } else {
  461. bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
  462. if err != nil {
  463. beego.Error("查询失败")
  464. }
  465. c.JsonResult(0, "ok", bookResult)
  466. }
  467. }
  468. }
  469. //导入zip压缩包
  470. func (c *BookController) Import() {
  471. file, moreFile, err := c.GetFile("import-file")
  472. if err == http.ErrMissingFile {
  473. c.JsonResult(6003, "没有发现需要上传的文件")
  474. }
  475. defer file.Close()
  476. bookName := strings.TrimSpace(c.GetString("book_name"))
  477. identify := strings.TrimSpace(c.GetString("identify"))
  478. description := strings.TrimSpace(c.GetString("description", ""))
  479. privatelyOwned, _ := strconv.Atoi(c.GetString("privately_owned"))
  480. itemId, _ := c.GetInt("itemId")
  481. if bookName == "" {
  482. c.JsonResult(6001, "项目名称不能为空")
  483. }
  484. if len([]rune(bookName)) > 500 {
  485. c.JsonResult(6002, "项目名称不能大于500字")
  486. }
  487. if identify == "" {
  488. c.JsonResult(6002, "项目标识不能为空")
  489. }
  490. if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, identify); !ok || err != nil {
  491. c.JsonResult(6003, "项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  492. }
  493. if !models.NewItemsets().Exist(itemId) {
  494. c.JsonResult(6007, "项目空间不存在")
  495. }
  496. if strings.Count(identify, "") > 50 {
  497. c.JsonResult(6004, "文档标识不能超过50字")
  498. }
  499. ext := filepath.Ext(moreFile.Filename)
  500. if !strings.EqualFold(ext, ".zip") {
  501. c.JsonResult(6004, "不支持的文件类型")
  502. }
  503. if books, _ := models.NewBook().FindByField("identify", identify, "book_id"); len(books) > 0 {
  504. c.JsonResult(6006, "项目标识已存在")
  505. }
  506. tempPath := filepath.Join(os.TempDir(), c.CruSession.SessionID())
  507. os.MkdirAll(tempPath, 0766)
  508. tempPath = filepath.Join(tempPath, moreFile.Filename)
  509. err = c.SaveToFile("import-file", tempPath)
  510. book := models.NewBook()
  511. book.MemberId = c.Member.MemberId
  512. book.Cover = conf.GetDefaultCover()
  513. book.BookName = bookName
  514. book.Description = description
  515. book.CommentCount = 0
  516. book.PrivatelyOwned = privatelyOwned
  517. book.CommentStatus = "closed"
  518. book.Identify = identify
  519. book.DocCount = 0
  520. book.MemberId = c.Member.MemberId
  521. book.CommentCount = 0
  522. book.Version = time.Now().Unix()
  523. book.ItemId = itemId
  524. book.Editor = "markdown"
  525. book.Theme = "default"
  526. go book.ImportBook(tempPath)
  527. beego.Info("用户[", c.Member.Account, "]导入了项目 ->", book)
  528. c.JsonResult(0, "项目正在后台转换中,请稍后查看")
  529. }
  530. // CreateToken 创建访问来令牌.
  531. func (c *BookController) CreateToken() {
  532. action := c.GetString("action")
  533. bookResult, err := c.IsPermission()
  534. if err != nil {
  535. if err == models.ErrPermissionDenied {
  536. c.JsonResult(403, "权限不足")
  537. }
  538. if err == orm.ErrNoRows {
  539. c.JsonResult(404, "项目不存在")
  540. }
  541. logs.Error("生成阅读令牌失败 =>", err)
  542. c.JsonResult(6002, err.Error())
  543. }
  544. book := models.NewBook()
  545. if _, err := book.Find(bookResult.BookId); err != nil {
  546. c.JsonResult(6001, "项目不存在")
  547. }
  548. if action == "create" {
  549. if bookResult.PrivatelyOwned == 0 {
  550. c.JsonResult(6001, "公开项目不能创建阅读令牌")
  551. }
  552. book.PrivateToken = string(utils.Krand(conf.GetTokenSize(), utils.KC_RAND_KIND_ALL))
  553. if err := book.Update(); err != nil {
  554. logs.Error("生成阅读令牌失败 => ", err)
  555. c.JsonResult(6003, "生成阅读令牌失败")
  556. }
  557. beego.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken)
  558. c.JsonResult(0, "ok", conf.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken))
  559. } else {
  560. book.PrivateToken = ""
  561. if err := book.Update(); err != nil {
  562. logs.Error("CreateToken => ", err)
  563. c.JsonResult(6004, "删除令牌失败")
  564. }
  565. beego.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken)
  566. c.JsonResult(0, "ok", "")
  567. }
  568. }
  569. // Delete 删除项目.
  570. func (c *BookController) Delete() {
  571. c.Prepare()
  572. bookResult, err := c.IsPermission()
  573. if err != nil {
  574. c.JsonResult(6001, err.Error())
  575. }
  576. if bookResult.RoleId != conf.BookFounder {
  577. c.JsonResult(6002, "只有创始人才能删除项目")
  578. }
  579. err = models.NewBook().ThoroughDeleteBook(bookResult.BookId)
  580. if err == orm.ErrNoRows {
  581. c.JsonResult(6002, "项目不存在")
  582. }
  583. if err != nil {
  584. logs.Error("删除项目 => ", err)
  585. c.JsonResult(6003, "删除失败")
  586. }
  587. beego.Info("用户[", c.Member.Account, "]删除了项目 ->", bookResult)
  588. c.JsonResult(0, "ok")
  589. }
  590. //发布项目.
  591. func (c *BookController) Release() {
  592. c.Prepare()
  593. identify := c.GetString("identify")
  594. bookId := 0
  595. if c.Member.IsAdministrator() {
  596. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  597. if err != nil {
  598. }
  599. bookId = book.BookId
  600. } else {
  601. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  602. if err != nil {
  603. if err == models.ErrPermissionDenied {
  604. c.JsonResult(6001, "权限不足")
  605. }
  606. if err == orm.ErrNoRows {
  607. c.JsonResult(6002, "项目不存在")
  608. }
  609. beego.Error(err)
  610. c.JsonResult(6003, "未知错误")
  611. }
  612. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor {
  613. c.JsonResult(6003, "权限不足")
  614. }
  615. bookId = book.BookId
  616. }
  617. go func(identify string) {
  618. models.NewBook().ReleaseContent(bookId)
  619. //当文档发布后,需要删除已缓存的转换项目
  620. outputPath := filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(bookId))
  621. os.RemoveAll(outputPath)
  622. }(identify)
  623. c.JsonResult(0, "发布任务已推送到任务队列,稍后将在后台执行。")
  624. }
  625. //文档排序.
  626. func (c *BookController) SaveSort() {
  627. c.Prepare()
  628. identify := c.Ctx.Input.Param(":key")
  629. if identify == "" {
  630. c.Abort("404")
  631. }
  632. book_id := 0
  633. if c.Member.IsAdministrator() {
  634. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  635. if err != nil {
  636. }
  637. book_id = book.BookId
  638. } else {
  639. bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  640. if err != nil {
  641. beego.Error("DocumentController.Edit => ", err)
  642. c.Abort("403")
  643. }
  644. if bookResult.RoleId == conf.BookObserver {
  645. c.JsonResult(6002, "项目不存在或权限不足")
  646. }
  647. book_id = bookResult.BookId
  648. }
  649. content := c.Ctx.Input.RequestBody
  650. var docs []map[string]interface{}
  651. err := json.Unmarshal(content, &docs)
  652. if err != nil {
  653. beego.Error(err)
  654. c.JsonResult(6003, "数据错误")
  655. }
  656. for _, item := range docs {
  657. if doc_id, ok := item["id"].(float64); ok {
  658. doc, err := models.NewDocument().Find(int(doc_id))
  659. if err != nil {
  660. beego.Error(err)
  661. continue
  662. }
  663. if doc.BookId != book_id {
  664. logs.Info("%s", "权限错误")
  665. continue
  666. }
  667. sort, ok := item["sort"].(float64)
  668. if !ok {
  669. beego.Info("排序数字转换失败 => ", item)
  670. continue
  671. }
  672. parent_id, ok := item["parent"].(float64)
  673. if !ok {
  674. beego.Info("父分类转换失败 => ", item)
  675. continue
  676. }
  677. if parent_id > 0 {
  678. if parent, err := models.NewDocument().Find(int(parent_id)); err != nil || parent.BookId != book_id {
  679. continue
  680. }
  681. }
  682. doc.OrderSort = int(sort)
  683. doc.ParentId = int(parent_id)
  684. if err := doc.InsertOrUpdate(); err != nil {
  685. fmt.Printf("%s", err.Error())
  686. beego.Error(err)
  687. }
  688. } else {
  689. fmt.Printf("文档ID转换失败 => %+v", item)
  690. }
  691. }
  692. c.JsonResult(0, "ok")
  693. }
  694. func (c *BookController) Team() {
  695. c.Prepare()
  696. c.TplName = "book/team.tpl"
  697. key := c.Ctx.Input.Param(":key")
  698. pageIndex, _ := c.GetInt("page", 1)
  699. if key == "" {
  700. c.ShowErrorPage(404, "项目不存在或已删除")
  701. }
  702. book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
  703. if err != nil {
  704. if err == models.ErrPermissionDenied {
  705. c.ShowErrorPage(403, "权限不足")
  706. }
  707. c.ShowErrorPage(500, "系统错误")
  708. }
  709. //如果不是创始人也不是管理员则不能操作
  710. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  711. c.Abort("403")
  712. }
  713. c.Data["Model"] = book
  714. members, totalCount, err := models.NewTeamRelationship().FindByBookToPager(book.BookId, pageIndex, conf.PageSize)
  715. if totalCount > 0 {
  716. pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
  717. c.Data["PageHtml"] = pager.HtmlPages()
  718. } else {
  719. c.Data["PageHtml"] = ""
  720. }
  721. b, err := json.Marshal(members)
  722. if err != nil {
  723. c.Data["Result"] = template.JS("[]")
  724. } else {
  725. c.Data["Result"] = template.JS(string(b))
  726. }
  727. }
  728. func (c *BookController) TeamAdd() {
  729. c.Prepare()
  730. teamId, _ := c.GetInt("teamId")
  731. book, err := c.IsPermission()
  732. if err != nil {
  733. c.JsonResult(500, err.Error())
  734. }
  735. //如果不是创始人也不是管理员则不能操作
  736. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  737. c.Abort("403")
  738. }
  739. _, err = models.NewTeam().First(teamId, "team_id")
  740. if err != nil {
  741. if err == orm.ErrNoRows {
  742. c.JsonResult(500, "团队不存在")
  743. }
  744. c.JsonResult(5002, err.Error())
  745. }
  746. if _, err := models.NewTeamRelationship().FindByBookId(book.BookId, teamId); err == nil {
  747. c.JsonResult(5003, "团队已加入当前项目")
  748. }
  749. teamRel := models.NewTeamRelationship()
  750. teamRel.BookId = book.BookId
  751. teamRel.TeamId = teamId
  752. err = teamRel.Save()
  753. if err != nil {
  754. c.JsonResult(5004, "加入项目失败")
  755. }
  756. teamRel.Include()
  757. c.JsonResult(0, "OK", teamRel)
  758. }
  759. //删除项目的团队.
  760. func (c *BookController) TeamDelete() {
  761. c.Prepare()
  762. teamId, _ := c.GetInt("teamId")
  763. if teamId <= 0 {
  764. c.JsonResult(5001, "参数错误")
  765. }
  766. book, err := c.IsPermission()
  767. if err != nil {
  768. c.JsonResult(5002, err.Error())
  769. }
  770. //如果不是创始人也不是管理员则不能操作
  771. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  772. c.Abort("403")
  773. }
  774. err = models.NewTeamRelationship().DeleteByBookId(book.BookId, teamId)
  775. if err != nil {
  776. if err == orm.ErrNoRows {
  777. c.JsonResult(5003, "团队未加入项目")
  778. }
  779. c.JsonResult(5004, err.Error())
  780. }
  781. c.JsonResult(0, "OK")
  782. }
  783. //团队搜索.
  784. func (c *BookController) TeamSearch() {
  785. c.Prepare()
  786. keyword := strings.TrimSpace(c.GetString("q"))
  787. book, err := c.IsPermission()
  788. if err != nil {
  789. c.JsonResult(500, err.Error())
  790. }
  791. keyword = sqltil.EscapeLike(keyword)
  792. searchResult, err := models.NewTeamRelationship().FindNotJoinBookByBookIdentify(book.BookId, keyword, 10)
  793. if err != nil {
  794. c.JsonResult(500, err.Error(), searchResult)
  795. }
  796. c.JsonResult(0, "OK", searchResult)
  797. }
  798. //项目空间搜索.
  799. func (c *BookController) ItemsetsSearch() {
  800. c.Prepare()
  801. keyword := strings.TrimSpace(c.GetString("q"))
  802. keyword = sqltil.EscapeLike(keyword)
  803. searchResult, err := models.NewItemsets().FindItemsetsByName(keyword, 10)
  804. if err != nil {
  805. c.JsonResult(500, err.Error(), searchResult)
  806. }
  807. c.JsonResult(0, "OK", searchResult)
  808. }
  809. func (c *BookController) IsPermission() (*models.BookResult, error) {
  810. identify := c.GetString("identify")
  811. if identify == "" {
  812. return nil, errors.New("参数错误")
  813. }
  814. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  815. if err != nil {
  816. if err == models.ErrPermissionDenied {
  817. return book, errors.New("权限不足")
  818. }
  819. if err == orm.ErrNoRows {
  820. return book, errors.New("项目不存在")
  821. }
  822. return book, err
  823. }
  824. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  825. return book, errors.New("权限不足")
  826. }
  827. return book, nil
  828. }