book.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. c.Abort("500")
  60. }
  61. c.Data["Model"] = *book
  62. }
  63. // Setting 项目设置 .
  64. func (c *BookController) Setting() {
  65. c.Prepare()
  66. c.TplName = "book/setting.tpl"
  67. key := c.Ctx.Input.Param(":key")
  68. if key == ""{
  69. c.Abort("404")
  70. }
  71. book,err := models.NewBookResult().FindByIdentify(key,c.Member.MemberId)
  72. if err != nil {
  73. if err == orm.ErrNoRows {
  74. c.Abort("404")
  75. }
  76. if err == models.ErrPermissionDenied {
  77. c.Abort("403")
  78. }
  79. c.Abort("500")
  80. }
  81. //如果不是创始人也不是管理员则不能操作
  82. if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
  83. c.Abort("403")
  84. }
  85. if book.PrivateToken != "" {
  86. book.PrivateToken = c.BaseUrl() + beego.URLFor("DocumentController.Index",":key",book.Identify,"token",book.PrivateToken)
  87. }
  88. c.Data["Model"] = book
  89. }
  90. //保存项目信息
  91. func (c *BookController) SaveBook() {
  92. bookResult,err := c.IsPermission()
  93. if err != nil {
  94. c.JsonResult(6001,err.Error())
  95. }
  96. book,err := models.NewBook().Find(bookResult.BookId)
  97. if err != nil {
  98. logs.Error("SaveBook => ",err)
  99. c.JsonResult(6002,err.Error())
  100. }
  101. book_name := strings.TrimSpace(c.GetString("book_name"))
  102. description := strings.TrimSpace(c.GetString("description",""))
  103. comment_status := c.GetString("comment_status")
  104. tag := strings.TrimSpace(c.GetString("label"))
  105. editor := strings.TrimSpace(c.GetString("editor"))
  106. if strings.Count(description,"") > 500 {
  107. c.JsonResult(6004,"项目描述不能大于500字")
  108. }
  109. if comment_status != "open" && comment_status != "closed" && comment_status != "group_only" && comment_status != "registered_only" {
  110. comment_status = "closed"
  111. }
  112. if tag != ""{
  113. tags := strings.Split(tag,";")
  114. if len(tags) > 10 {
  115. c.JsonResult(6005,"最多允许添加10个标签")
  116. }
  117. }
  118. if editor != "markdown" && editor != "html" {
  119. editor = "markdown"
  120. }
  121. book.BookName = book_name
  122. book.Description = description
  123. book.CommentStatus = comment_status
  124. book.Label = tag
  125. book.Editor = editor
  126. if err := book.Update();err != nil {
  127. c.JsonResult(6006,"保存失败")
  128. }
  129. bookResult.BookName = book_name
  130. bookResult.Description = description
  131. bookResult.CommentStatus = comment_status
  132. bookResult.Label = tag
  133. c.JsonResult(0,"ok",bookResult)
  134. }
  135. func (c *BookController) PrivatelyOwned() {
  136. status := c.GetString("status")
  137. if status != "open" && status != "close" {
  138. c.JsonResult(6003,"参数错误")
  139. }
  140. state := 0
  141. if status == "open" {
  142. state = 0
  143. }else{
  144. state = 1
  145. }
  146. bookResult,err := c.IsPermission()
  147. if err != nil {
  148. c.JsonResult(6001,err.Error())
  149. }
  150. //只有创始人才能变更私有状态
  151. if bookResult.RoleId != conf.BookFounder {
  152. c.JsonResult(6002,"权限不足")
  153. }
  154. fmt.Printf("%+v",bookResult)
  155. book,err := models.NewBook().Find(bookResult.BookId)
  156. if err != nil {
  157. c.JsonResult(6005,"项目不存在")
  158. }
  159. book.PrivatelyOwned = state
  160. logs.Info("",state,status)
  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 := "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. //剪切图片
  236. subImg,err := graphics.ImageCopyFromFile(filePath,x,y,width,height)
  237. if err != nil{
  238. logs.Error("graphics.ImageCopyFromFile => ",err)
  239. c.JsonResult(500,"图片剪切")
  240. }
  241. //生成缩略图并保存到磁盘
  242. err = graphics.ImageResizeSaveFile(subImg,175,230,filePath)
  243. if err != nil {
  244. logs.Error("ImageResizeSaveFile => ",err.Error())
  245. c.JsonResult(500,"保存图片失败")
  246. }
  247. url := "/" + filePath
  248. old_cover := book.Cover
  249. book.Cover = url
  250. if err := book.Update() ; err != nil {
  251. c.JsonResult(6001,"保存图片失败")
  252. }
  253. //如果原封面不是默认封面则删除
  254. if old_cover != conf.GetDefaultCover() {
  255. os.Remove("." + old_cover)
  256. }
  257. c.JsonResult(0,"ok",url)
  258. }
  259. // Users 用户列表.
  260. func (c *BookController) Users() {
  261. c.Prepare()
  262. c.TplName = "book/users.tpl"
  263. key := c.Ctx.Input.Param(":key")
  264. pageIndex,_ := c.GetInt("page",1)
  265. if key == ""{
  266. c.Abort("404")
  267. }
  268. book,err := models.NewBookResult().FindByIdentify(key,c.Member.MemberId)
  269. if err != nil {
  270. if err == models.ErrPermissionDenied {
  271. c.Abort("403")
  272. }
  273. c.Abort("500")
  274. }
  275. c.Data["Model"] = *book
  276. members,totalCount,err := models.NewMemberRelationshipResult().FindForUsersByBookId(book.BookId,pageIndex,15)
  277. if totalCount > 0 {
  278. html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, 10, totalCount)
  279. c.Data["PageHtml"] = html
  280. }else{
  281. c.Data["PageHtml"] = ""
  282. }
  283. b,err := json.Marshal(members)
  284. if err != nil {
  285. c.Data["Result"] = template.JS("[]")
  286. }else{
  287. c.Data["Result"] = template.JS(string(b))
  288. }
  289. }
  290. // Create 创建项目.
  291. func (c *BookController) Create() {
  292. if c.Ctx.Input.IsPost() {
  293. book_name := strings.TrimSpace(c.GetString("book_name",""))
  294. identify := strings.TrimSpace(c.GetString("identify",""))
  295. description := strings.TrimSpace(c.GetString("description",""))
  296. privately_owned,_ := strconv.Atoi(c.GetString("privately_owned"))
  297. comment_status := c.GetString("comment_status")
  298. if book_name == "" {
  299. c.JsonResult(6001,"项目名称不能为空")
  300. }
  301. if identify == "" {
  302. c.JsonResult(6002,"项目标识不能为空")
  303. }
  304. if ok,err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`,identify); !ok || err != nil {
  305. c.JsonResult(6003,"项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  306. }
  307. if strings.Count(identify,"") > 50 {
  308. c.JsonResult(6004,"文档标识不能超过50字")
  309. }
  310. if strings.Count(description,"") > 500 {
  311. c.JsonResult(6004,"项目描述不能大于500字")
  312. }
  313. if privately_owned !=0 && privately_owned != 1 {
  314. privately_owned = 1
  315. }
  316. if comment_status != "open" && comment_status != "closed" && comment_status != "group_only" && comment_status != "registered_only" {
  317. comment_status = "closed"
  318. }
  319. book := models.NewBook()
  320. if books,_ := book.FindByField("identify",identify); len(books) > 0 {
  321. c.JsonResult(6006,"项目标识已存在")
  322. }
  323. book.BookName = book_name
  324. book.Description = description
  325. book.CommentCount = 0
  326. book.PrivatelyOwned = privately_owned
  327. book.CommentStatus = comment_status
  328. book.Identify = identify
  329. book.DocCount = 0
  330. book.MemberId = c.Member.MemberId
  331. book.CommentCount = 0
  332. book.Version = time.Now().Unix()
  333. book.Cover = conf.GetDefaultCover()
  334. book.Editor = "markdown"
  335. book.Theme = "default"
  336. err := book.Insert()
  337. if err != nil {
  338. logs.Error("Insert => ",err)
  339. c.JsonResult(6005,"保存项目失败")
  340. }
  341. bookResult,err := models.NewBookResult().FindByIdentify(book.Identify,c.Member.MemberId)
  342. if err != nil {
  343. beego.Error(err)
  344. }
  345. c.JsonResult(0,"ok",bookResult)
  346. }
  347. c.JsonResult(6001,"error")
  348. }
  349. // CreateToken 创建访问来令牌.
  350. func (c *BookController) CreateToken() {
  351. action := c.GetString("action")
  352. bookResult ,err := c.IsPermission()
  353. if err != nil {
  354. if err == models.ErrPermissionDenied {
  355. c.JsonResult(403,"权限不足")
  356. }
  357. if err == orm.ErrNoRows {
  358. c.JsonResult(404,"项目不存在")
  359. }
  360. logs.Error("生成阅读令牌失败 =>",err)
  361. c.JsonResult(6002,err.Error())
  362. }
  363. book := models.NewBook()
  364. if _,err := book.Find(bookResult.BookId);err != nil {
  365. c.JsonResult(6001,"项目不存在")
  366. }
  367. if action == "create" {
  368. if bookResult.PrivatelyOwned == 0 {
  369. c.JsonResult(6001, "公开项目不能创建阅读令牌")
  370. }
  371. book.PrivateToken = string(utils.Krand(conf.GetTokenSize(), utils.KC_RAND_KIND_ALL))
  372. if err := book.Update(); err != nil {
  373. logs.Error("生成阅读令牌失败 => ", err)
  374. c.JsonResult(6003, "生成阅读令牌失败")
  375. }
  376. c.JsonResult(0, "ok", c.BaseUrl() + beego.URLFor("DocumentController.Index",":key",book.Identify,"token",book.PrivateToken))
  377. }else{
  378. book.PrivateToken = ""
  379. if err := book.Update();err != nil {
  380. logs.Error("CreateToken => ",err)
  381. c.JsonResult(6004,"删除令牌失败")
  382. }
  383. c.JsonResult(0,"ok","")
  384. }
  385. }
  386. // Delete 删除项目.
  387. func (c *BookController) Delete() {
  388. c.Prepare()
  389. bookResult ,err := c.IsPermission()
  390. if err != nil {
  391. c.JsonResult(6001,err.Error())
  392. }
  393. if bookResult.RoleId != conf.BookFounder {
  394. c.JsonResult(6002,"只有创始人才能删除项目")
  395. }
  396. err = models.NewBook().ThoroughDeleteBook(bookResult.BookId)
  397. if err == orm.ErrNoRows {
  398. c.JsonResult(6002,"项目不存在")
  399. }
  400. if err != nil {
  401. logs.Error("删除项目 => ",err)
  402. c.JsonResult(6003,"删除失败")
  403. }
  404. c.JsonResult(0,"ok")
  405. }
  406. //发布项目
  407. func (c *BookController) Release() {
  408. c.Prepare()
  409. identify := c.GetString("identify")
  410. book ,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
  411. if err != nil {
  412. if err == models.ErrPermissionDenied {
  413. c.JsonResult(6001,"权限不足")
  414. }
  415. if err == orm.ErrNoRows {
  416. c.JsonResult(6002,"项目不存在")
  417. }
  418. beego.Error(err)
  419. c.JsonResult(6003,"未知错误")
  420. }
  421. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor{
  422. c.JsonResult(6003,"权限不足")
  423. }
  424. go models.NewDocument().ReleaseContent(book.BookId)
  425. c.JsonResult(0,"发布任务已推送到任务队列,稍后将在后台执行。")
  426. }
  427. func (c *BookController) SaveSort() {
  428. c.Prepare()
  429. identify := c.Ctx.Input.Param(":key")
  430. if identify == "" {
  431. c.Abort("404")
  432. }
  433. bookResult,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
  434. if err != nil {
  435. beego.Error("DocumentController.Edit => ",err)
  436. c.Abort("403")
  437. }
  438. if bookResult.RoleId == conf.BookObserver {
  439. c.JsonResult(6002,"项目不存在或权限不足")
  440. }
  441. content := c.Ctx.Input.RequestBody
  442. var docs []map[string]interface{}
  443. err = json.Unmarshal(content,&docs)
  444. if err != nil {
  445. beego.Error(err)
  446. c.JsonResult(6003,"数据错误")
  447. }
  448. fmt.Printf("%+v",docs)
  449. for _,item := range docs {
  450. if doc_id,ok := item["id"].(float64);ok {
  451. doc,err := models.NewDocument().Find(int(doc_id));
  452. if err != nil {
  453. beego.Error(err)
  454. continue;
  455. }
  456. if doc.BookId != bookResult.BookId {
  457. logs.Info("%s","权限错误")
  458. continue;
  459. }
  460. sort,ok := item["sort"].(float64);
  461. if !ok {
  462. beego.Info("排序数字转换失败 => ",item)
  463. continue
  464. }
  465. parent_id,ok := item["parent"].(float64)
  466. if !ok {
  467. beego.Info("父分类转换失败 => ",item)
  468. continue
  469. }
  470. if parent_id > 0 {
  471. if parent,err := models.NewDocument().Find(int(parent_id)); err != nil || parent.BookId != bookResult.BookId {
  472. continue
  473. }
  474. }
  475. doc.OrderSort = int(sort)
  476. doc.ParentId = int(parent_id)
  477. if err := doc.InsertOrUpdate(); err != nil {
  478. fmt.Printf("%s",err.Error())
  479. beego.Error(err)
  480. }
  481. }else{
  482. fmt.Printf("文档ID转换失败 => %+v",item)
  483. }
  484. }
  485. c.JsonResult(0,"ok")
  486. }
  487. func (c *BookController) IsPermission() (*models.BookResult,error) {
  488. identify := c.GetString("identify")
  489. book ,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
  490. if err != nil {
  491. if err == models.ErrPermissionDenied {
  492. return book,errors.New("权限不足")
  493. }
  494. if err == orm.ErrNoRows {
  495. return book,errors.New("项目不存在")
  496. }
  497. return book,err
  498. }
  499. if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  500. return book,errors.New("权限不足")
  501. }
  502. return book,nil
  503. }