BookController.go 25 KB

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