book.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. package controllers
  2. import (
  3. "strings"
  4. "regexp"
  5. "strconv"
  6. "time"
  7. "encoding/json"
  8. "html/template"
  9. "errors"
  10. "fmt"
  11. "path/filepath"
  12. "os"
  13. "github.com/lifei6671/godoc/models"
  14. "github.com/lifei6671/godoc/utils"
  15. "github.com/astaxie/beego"
  16. "github.com/astaxie/beego/orm"
  17. "github.com/astaxie/beego/logs"
  18. "github.com/lifei6671/godoc/conf"
  19. "github.com/lifei6671/godoc/graphics"
  20. )
  21. type BookController struct {
  22. BaseController
  23. }
  24. func (c *BookController) Index() {
  25. c.Prepare()
  26. c.TplName = "book/index.tpl"
  27. pageIndex, _ := c.GetInt("page", 1)
  28. books,totalCount,err := models.NewBook().FindToPager(pageIndex,conf.PageSize,c.Member.MemberId)
  29. if err != nil {
  30. logs.Error("BookController.Index => ",err)
  31. c.Abort("500")
  32. }
  33. if totalCount > 0 {
  34. html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, conf.PageSize, totalCount)
  35. c.Data["PageHtml"] = html
  36. }else {
  37. c.Data["PageHtml"] = ""
  38. }
  39. b,err := json.Marshal(books)
  40. if err != nil || len(books) <= 0{
  41. c.Data["Result"] = template.JS("[]")
  42. }else{
  43. c.Data["Result"] = template.JS(string(b))
  44. }
  45. }
  46. // Dashboard 项目概要 .
  47. func (c *BookController) Dashboard() {
  48. c.Prepare()
  49. c.TplName = "book/dashboard.tpl"
  50. key := c.Ctx.Input.Param(":key")
  51. if key == ""{
  52. c.Abort("404")
  53. }
  54. book,err := models.NewBookResult().FindByIdentify(key,c.Member.MemberId)
  55. if err != nil {
  56. if err == models.ErrPermissionDenied {
  57. c.Abort("403")
  58. }
  59. beego.Error(err)
  60. c.Abort("500")
  61. }
  62. c.Data["Model"] = *book
  63. }
  64. // Setting 项目设置 .
  65. func (c *BookController) Setting() {
  66. c.Prepare()
  67. c.TplName = "book/setting.tpl"
  68. key := c.Ctx.Input.Param(":key")
  69. if key == ""{
  70. c.Abort("404")
  71. }
  72. book,err := models.NewBookResult().FindByIdentify(key,c.Member.MemberId)
  73. if err != nil {
  74. if err == orm.ErrNoRows {
  75. c.Abort("404")
  76. }
  77. if err == models.ErrPermissionDenied {
  78. c.Abort("403")
  79. }
  80. c.Abort("500")
  81. }
  82. //如果不是创始人也不是管理员则不能操作
  83. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  84. c.Abort("403")
  85. }
  86. if book.PrivateToken != "" {
  87. book.PrivateToken = c.BaseUrl() + beego.URLFor("DocumentController.Index",":key",book.Identify,"token",book.PrivateToken)
  88. }
  89. c.Data["Model"] = book
  90. }
  91. //保存项目信息
  92. func (c *BookController) SaveBook() {
  93. bookResult,err := c.IsPermission()
  94. if err != nil {
  95. c.JsonResult(6001,err.Error())
  96. }
  97. book,err := models.NewBook().Find(bookResult.BookId)
  98. if err != nil {
  99. logs.Error("SaveBook => ",err)
  100. c.JsonResult(6002,err.Error())
  101. }
  102. book_name := strings.TrimSpace(c.GetString("book_name"))
  103. description := strings.TrimSpace(c.GetString("description",""))
  104. comment_status := c.GetString("comment_status")
  105. tag := strings.TrimSpace(c.GetString("label"))
  106. editor := strings.TrimSpace(c.GetString("editor"))
  107. if strings.Count(description,"") > 500 {
  108. c.JsonResult(6004,"项目描述不能大于500字")
  109. }
  110. if comment_status != "open" && comment_status != "closed" && comment_status != "group_only" && comment_status != "registered_only" {
  111. comment_status = "closed"
  112. }
  113. if tag != ""{
  114. tags := strings.Split(tag,";")
  115. if len(tags) > 10 {
  116. c.JsonResult(6005,"最多允许添加10个标签")
  117. }
  118. }
  119. if editor != "markdown" && editor != "html" {
  120. editor = "markdown"
  121. }
  122. book.BookName = book_name
  123. book.Description = description
  124. book.CommentStatus = comment_status
  125. book.Label = tag
  126. book.Editor = editor
  127. if err := book.Update();err != nil {
  128. c.JsonResult(6006,"保存失败")
  129. }
  130. bookResult.BookName = book_name
  131. bookResult.Description = description
  132. bookResult.CommentStatus = comment_status
  133. bookResult.Label = tag
  134. c.JsonResult(0,"ok",bookResult)
  135. }
  136. //设置项目私有状态.
  137. func (c *BookController) PrivatelyOwned() {
  138. status := c.GetString("status")
  139. if status != "open" && status != "close" {
  140. c.JsonResult(6003,"参数错误")
  141. }
  142. state := 0
  143. if status == "open" {
  144. state = 0
  145. }else{
  146. state = 1
  147. }
  148. bookResult,err := c.IsPermission()
  149. if err != nil {
  150. c.JsonResult(6001,err.Error())
  151. }
  152. //只有创始人才能变更私有状态
  153. if bookResult.RoleId != conf.BookFounder {
  154. c.JsonResult(6002,"权限不足")
  155. }
  156. book,err := models.NewBook().Find(bookResult.BookId)
  157. if err != nil {
  158. c.JsonResult(6005,"项目不存在")
  159. }
  160. book.PrivatelyOwned = state
  161. err = book.Update()
  162. if err != nil {
  163. logs.Error("PrivatelyOwned => ",err)
  164. c.JsonResult(6004,"保存失败")
  165. }
  166. c.JsonResult(0,"ok")
  167. }
  168. // Transfer 转让项目.
  169. func (c *BookController) Transfer() {
  170. c.Prepare()
  171. account := c.GetString("account")
  172. if account == "" {
  173. c.JsonResult(6004,"接受者账号不能为空")
  174. }
  175. member,err := models.NewMember().FindByAccount(account)
  176. if err != nil {
  177. logs.Error("FindByAccount => ",err)
  178. c.JsonResult(6005,"接受用户不存在")
  179. }
  180. if member.Status != 0 {
  181. c.JsonResult(6006,"接受用户已被禁用")
  182. }
  183. if member.MemberId == c.Member.MemberId {
  184. c.JsonResult(6007,"不能转让给自己")
  185. }
  186. bookResult,err := c.IsPermission()
  187. if err != nil {
  188. c.JsonResult(6001,err.Error())
  189. }
  190. err = models.NewRelationship().Transfer(bookResult.BookId,c.Member.MemberId,member.MemberId)
  191. if err != nil {
  192. logs.Error("Transfer => ",err)
  193. c.JsonResult(6008,err.Error())
  194. }
  195. c.JsonResult(0,"ok")
  196. }
  197. //上传项目封面.
  198. func (c *BookController) UploadCover() {
  199. bookResult,err := c.IsPermission()
  200. if err != nil {
  201. c.JsonResult(6001,err.Error())
  202. }
  203. book,err := models.NewBook().Find(bookResult.BookId)
  204. if err != nil {
  205. logs.Error("SaveBook => ",err)
  206. c.JsonResult(6002,err.Error())
  207. }
  208. file,moreFile,err := c.GetFile("image-file")
  209. defer file.Close()
  210. if err != nil {
  211. logs.Error("",err.Error())
  212. c.JsonResult(500,"读取文件异常")
  213. }
  214. ext := filepath.Ext(moreFile.Filename)
  215. if !strings.EqualFold(ext,".png") && !strings.EqualFold(ext,".jpg") && !strings.EqualFold(ext,".gif") && !strings.EqualFold(ext,".jpeg") {
  216. c.JsonResult(500,"不支持的图片格式")
  217. }
  218. x1 ,_ := strconv.ParseFloat(c.GetString("x"),10)
  219. y1 ,_ := strconv.ParseFloat(c.GetString("y"),10)
  220. w1 ,_ := strconv.ParseFloat(c.GetString("width"),10)
  221. h1 ,_ := strconv.ParseFloat(c.GetString("height"),10)
  222. x := int(x1)
  223. y := int(y1)
  224. width := int(w1)
  225. height := int(h1)
  226. fileName := "cover_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  227. filePath := filepath.Join("uploads",time.Now().Format("200601"),fileName + ext)
  228. path := filepath.Dir(filePath)
  229. os.MkdirAll(path, os.ModePerm)
  230. err = c.SaveToFile("image-file",filePath)
  231. if err != nil {
  232. logs.Error("",err)
  233. c.JsonResult(500,"图片保存失败")
  234. }
  235. defer func(filePath string) {
  236. os.Remove(filePath)
  237. }(filePath)
  238. //剪切图片
  239. subImg,err := graphics.ImageCopyFromFile(filePath,x,y,width,height)
  240. if err != nil{
  241. logs.Error("graphics.ImageCopyFromFile => ",err)
  242. c.JsonResult(500,"图片剪切")
  243. }
  244. filePath = filepath.Join("uploads",time.Now().Format("200601"),fileName + "_small" + ext)
  245. //生成缩略图并保存到磁盘
  246. err = graphics.ImageResizeSaveFile(subImg,175,230,filePath)
  247. if err != nil {
  248. logs.Error("ImageResizeSaveFile => ",err.Error())
  249. c.JsonResult(500,"保存图片失败")
  250. }
  251. url := "/" + strings.Replace(filePath,"\\","/",-1)
  252. old_cover := book.Cover
  253. book.Cover = url
  254. if err := book.Update() ; err != nil {
  255. c.JsonResult(6001,"保存图片失败")
  256. }
  257. //如果原封面不是默认封面则删除
  258. if old_cover != conf.GetDefaultCover() {
  259. os.Remove("." + old_cover)
  260. }
  261. c.JsonResult(0,"ok",url)
  262. }
  263. // Users 用户列表.
  264. func (c *BookController) Users() {
  265. c.Prepare()
  266. c.TplName = "book/users.tpl"
  267. key := c.Ctx.Input.Param(":key")
  268. pageIndex,_ := c.GetInt("page",1)
  269. if key == ""{
  270. c.Abort("404")
  271. }
  272. book,err := models.NewBookResult().FindByIdentify(key,c.Member.MemberId)
  273. if err != nil {
  274. if err == models.ErrPermissionDenied {
  275. c.Abort("403")
  276. }
  277. c.Abort("500")
  278. }
  279. c.Data["Model"] = *book
  280. members,totalCount,err := models.NewMemberRelationshipResult().FindForUsersByBookId(book.BookId,pageIndex,15)
  281. if totalCount > 0 {
  282. html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, 10, totalCount)
  283. c.Data["PageHtml"] = html
  284. }else{
  285. c.Data["PageHtml"] = ""
  286. }
  287. b,err := json.Marshal(members)
  288. if err != nil {
  289. c.Data["Result"] = template.JS("[]")
  290. }else{
  291. c.Data["Result"] = template.JS(string(b))
  292. }
  293. }
  294. // Create 创建项目.
  295. func (c *BookController) Create() {
  296. if c.Ctx.Input.IsPost() {
  297. book_name := strings.TrimSpace(c.GetString("book_name",""))
  298. identify := strings.TrimSpace(c.GetString("identify",""))
  299. description := strings.TrimSpace(c.GetString("description",""))
  300. privately_owned,_ := strconv.Atoi(c.GetString("privately_owned"))
  301. comment_status := c.GetString("comment_status")
  302. if book_name == "" {
  303. c.JsonResult(6001,"项目名称不能为空")
  304. }
  305. if identify == "" {
  306. c.JsonResult(6002,"项目标识不能为空")
  307. }
  308. if ok,err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`,identify); !ok || err != nil {
  309. c.JsonResult(6003,"项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  310. }
  311. if strings.Count(identify,"") > 50 {
  312. c.JsonResult(6004,"文档标识不能超过50字")
  313. }
  314. if strings.Count(description,"") > 500 {
  315. c.JsonResult(6004,"项目描述不能大于500字")
  316. }
  317. if privately_owned !=0 && privately_owned != 1 {
  318. privately_owned = 1
  319. }
  320. if comment_status != "open" && comment_status != "closed" && comment_status != "group_only" && comment_status != "registered_only" {
  321. comment_status = "closed"
  322. }
  323. book := models.NewBook()
  324. if books,_ := book.FindByField("identify",identify); len(books) > 0 {
  325. c.JsonResult(6006,"项目标识已存在")
  326. }
  327. book.BookName = book_name
  328. book.Description = description
  329. book.CommentCount = 0
  330. book.PrivatelyOwned = privately_owned
  331. book.CommentStatus = comment_status
  332. book.Identify = identify
  333. book.DocCount = 0
  334. book.MemberId = c.Member.MemberId
  335. book.CommentCount = 0
  336. book.Version = time.Now().Unix()
  337. book.Cover = conf.GetDefaultCover()
  338. book.Editor = "markdown"
  339. book.Theme = "default"
  340. err := book.Insert()
  341. if err != nil {
  342. logs.Error("Insert => ",err)
  343. c.JsonResult(6005,"保存项目失败")
  344. }
  345. bookResult,err := models.NewBookResult().FindByIdentify(book.Identify,c.Member.MemberId)
  346. if err != nil {
  347. beego.Error(err)
  348. }
  349. c.JsonResult(0,"ok",bookResult)
  350. }
  351. c.JsonResult(6001,"error")
  352. }
  353. // CreateToken 创建访问来令牌.
  354. func (c *BookController) CreateToken() {
  355. action := c.GetString("action")
  356. bookResult ,err := c.IsPermission()
  357. if err != nil {
  358. if err == models.ErrPermissionDenied {
  359. c.JsonResult(403,"权限不足")
  360. }
  361. if err == orm.ErrNoRows {
  362. c.JsonResult(404,"项目不存在")
  363. }
  364. logs.Error("生成阅读令牌失败 =>",err)
  365. c.JsonResult(6002,err.Error())
  366. }
  367. book := models.NewBook()
  368. if _,err := book.Find(bookResult.BookId);err != nil {
  369. c.JsonResult(6001,"项目不存在")
  370. }
  371. if action == "create" {
  372. if bookResult.PrivatelyOwned == 0 {
  373. c.JsonResult(6001, "公开项目不能创建阅读令牌")
  374. }
  375. book.PrivateToken = string(utils.Krand(conf.GetTokenSize(), utils.KC_RAND_KIND_ALL))
  376. if err := book.Update(); err != nil {
  377. logs.Error("生成阅读令牌失败 => ", err)
  378. c.JsonResult(6003, "生成阅读令牌失败")
  379. }
  380. c.JsonResult(0, "ok", c.BaseUrl() + beego.URLFor("DocumentController.Index",":key",book.Identify,"token",book.PrivateToken))
  381. }else{
  382. book.PrivateToken = ""
  383. if err := book.Update();err != nil {
  384. logs.Error("CreateToken => ",err)
  385. c.JsonResult(6004,"删除令牌失败")
  386. }
  387. c.JsonResult(0,"ok","")
  388. }
  389. }
  390. // Delete 删除项目.
  391. func (c *BookController) Delete() {
  392. c.Prepare()
  393. bookResult ,err := c.IsPermission()
  394. if err != nil {
  395. c.JsonResult(6001,err.Error())
  396. }
  397. if bookResult.RoleId != conf.BookFounder {
  398. c.JsonResult(6002,"只有创始人才能删除项目")
  399. }
  400. err = models.NewBook().ThoroughDeleteBook(bookResult.BookId)
  401. if err == orm.ErrNoRows {
  402. c.JsonResult(6002,"项目不存在")
  403. }
  404. if err != nil {
  405. logs.Error("删除项目 => ",err)
  406. c.JsonResult(6003,"删除失败")
  407. }
  408. c.JsonResult(0,"ok")
  409. }
  410. //发布项目.
  411. func (c *BookController) Release() {
  412. c.Prepare()
  413. identify := c.GetString("identify")
  414. book_id := 0
  415. if c.Member.IsAdministrator() {
  416. book,err := models.NewBook().FindByFieldFirst("identify",identify)
  417. if err != nil {
  418. }
  419. book_id = book.BookId
  420. }else {
  421. book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
  422. if err != nil {
  423. if err == models.ErrPermissionDenied {
  424. c.JsonResult(6001, "权限不足")
  425. }
  426. if err == orm.ErrNoRows {
  427. c.JsonResult(6002, "项目不存在")
  428. }
  429. beego.Error(err)
  430. c.JsonResult(6003, "未知错误")
  431. }
  432. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor {
  433. c.JsonResult(6003, "权限不足")
  434. }
  435. book_id = book.BookId
  436. }
  437. go func(identify string) {
  438. models.NewDocument().ReleaseContent(book_id)
  439. }(identify)
  440. c.JsonResult(0,"发布任务已推送到任务队列,稍后将在后台执行。")
  441. }
  442. //文档排序.
  443. func (c *BookController) SaveSort() {
  444. c.Prepare()
  445. identify := c.Ctx.Input.Param(":key")
  446. if identify == "" {
  447. c.Abort("404")
  448. }
  449. book_id := 0
  450. if c.Member.IsAdministrator() {
  451. book,err := models.NewBook().FindByFieldFirst("identify",identify)
  452. if err != nil {
  453. }
  454. book_id = book.BookId
  455. }else{
  456. bookResult,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
  457. if err != nil {
  458. beego.Error("DocumentController.Edit => ",err)
  459. c.Abort("403")
  460. }
  461. if bookResult.RoleId == conf.BookObserver {
  462. c.JsonResult(6002,"项目不存在或权限不足")
  463. }
  464. book_id = bookResult.BookId
  465. }
  466. content := c.Ctx.Input.RequestBody
  467. var docs []map[string]interface{}
  468. err := json.Unmarshal(content,&docs)
  469. if err != nil {
  470. beego.Error(err)
  471. c.JsonResult(6003,"数据错误")
  472. }
  473. for _,item := range docs {
  474. if doc_id,ok := item["id"].(float64);ok {
  475. doc,err := models.NewDocument().Find(int(doc_id));
  476. if err != nil {
  477. beego.Error(err)
  478. continue;
  479. }
  480. if doc.BookId != book_id {
  481. logs.Info("%s","权限错误")
  482. continue;
  483. }
  484. sort,ok := item["sort"].(float64);
  485. if !ok {
  486. beego.Info("排序数字转换失败 => ",item)
  487. continue
  488. }
  489. parent_id,ok := item["parent"].(float64)
  490. if !ok {
  491. beego.Info("父分类转换失败 => ",item)
  492. continue
  493. }
  494. if parent_id > 0 {
  495. if parent,err := models.NewDocument().Find(int(parent_id)); err != nil || parent.BookId != book_id {
  496. continue
  497. }
  498. }
  499. doc.OrderSort = int(sort)
  500. doc.ParentId = int(parent_id)
  501. if err := doc.InsertOrUpdate(); err != nil {
  502. fmt.Printf("%s",err.Error())
  503. beego.Error(err)
  504. }
  505. }else{
  506. fmt.Printf("文档ID转换失败 => %+v",item)
  507. }
  508. }
  509. c.JsonResult(0,"ok")
  510. }
  511. func (c *BookController) IsPermission() (*models.BookResult,error) {
  512. identify := c.GetString("identify")
  513. book ,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
  514. if err != nil {
  515. if err == models.ErrPermissionDenied {
  516. return book,errors.New("权限不足")
  517. }
  518. if err == orm.ErrNoRows {
  519. return book,errors.New("项目不存在")
  520. }
  521. return book,err
  522. }
  523. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  524. return book,errors.New("权限不足")
  525. }
  526. return book,nil
  527. }