BookController.go 24 KB

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