document.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. package controllers
  2. import (
  3. "os"
  4. "time"
  5. "regexp"
  6. "strconv"
  7. "strings"
  8. "net/http"
  9. "path/filepath"
  10. "encoding/json"
  11. "html/template"
  12. "github.com/lifei6671/godoc/models"
  13. "github.com/lifei6671/godoc/conf"
  14. "github.com/astaxie/beego"
  15. "github.com/astaxie/beego/orm"
  16. )
  17. type DocumentController struct {
  18. BaseController
  19. }
  20. //判断用户是否可以阅读文档
  21. func isReadable (identify,token string,c *DocumentController) *models.BookResult {
  22. book, err := models.NewBook().FindByFieldFirst("identify", identify)
  23. if err != nil {
  24. beego.Error(err)
  25. c.Abort("500")
  26. }
  27. //如果文档是私有的
  28. if book.PrivatelyOwned == 1 {
  29. is_ok := false
  30. if c.Member != nil {
  31. _, err := models.NewRelationship().FindForRoleId(book.BookId, c.Member.MemberId)
  32. if err == nil {
  33. is_ok = true
  34. }
  35. }
  36. if book.PrivateToken != "" && !is_ok {
  37. //如果有访问的Token,并且该项目设置了访问Token,并且和用户提供的相匹配,则记录到Session中.
  38. //如果用户未提供Token且用户登录了,则判断用户是否参与了该项目.
  39. //如果用户未登录,则从Session中读取Token.
  40. if token != "" && strings.EqualFold(token, book.PrivateToken) {
  41. c.SetSession(identify, token)
  42. } else if token, ok := c.GetSession(identify).(string); !ok || !strings.EqualFold(token, book.PrivateToken) {
  43. c.Abort("403")
  44. }
  45. } else {
  46. c.Abort("403")
  47. }
  48. }
  49. bookResult := book.ToBookResult()
  50. if c.Member != nil {
  51. rel, err := models.NewRelationship().FindByBookIdAndMemberId(bookResult.BookId, c.Member.MemberId)
  52. if err == nil {
  53. bookResult.MemberId = rel.MemberId
  54. bookResult.RoleId = rel.RoleId
  55. bookResult.RelationshipId = rel.RelationshipId
  56. }
  57. }
  58. //判断是否需要显示评论框
  59. if bookResult.CommentStatus == "closed" {
  60. bookResult.IsDisplayComment = false
  61. } else if bookResult.CommentStatus == "open" {
  62. bookResult.IsDisplayComment = true
  63. } else if bookResult.CommentStatus == "group_only" {
  64. bookResult.IsDisplayComment = bookResult.RelationshipId > 0
  65. } else if bookResult.CommentStatus == "registered_only" {
  66. bookResult.IsDisplayComment = true
  67. }
  68. return bookResult
  69. }
  70. func (c *DocumentController) Index() {
  71. c.Prepare()
  72. identify := c.Ctx.Input.Param(":key")
  73. token := c.GetString("token")
  74. if identify == "" {
  75. c.Abort("404")
  76. }
  77. bookResult := isReadable(identify,token,c)
  78. c.TplName = "document/" + bookResult.Theme + "_read.tpl"
  79. tree,err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId,0)
  80. if err != nil {
  81. beego.Error(err)
  82. c.Abort("500")
  83. }
  84. c.Data["Model"] = bookResult
  85. c.Data["Result"] = template.HTML(tree)
  86. c.Data["Title"] = "概要"
  87. c.Data["Content"] = bookResult.Description
  88. }
  89. func (c *DocumentController) Read() {
  90. c.Prepare()
  91. identify := c.Ctx.Input.Param(":key")
  92. token := c.GetString("token")
  93. id := c.GetString(":id")
  94. if identify == "" || id == ""{
  95. c.Abort("404")
  96. }
  97. bookResult := isReadable(identify,token,c)
  98. c.TplName = "document/" + bookResult.Theme + "_read.tpl"
  99. doc := models.NewDocument()
  100. if doc_id,err := strconv.Atoi(id);err == nil {
  101. doc,err = doc.Find(doc_id)
  102. if err != nil {
  103. beego.Error(err)
  104. c.Abort("500")
  105. }
  106. }else{
  107. doc,err = doc.FindByFieldFirst("identify",id)
  108. if err != nil {
  109. beego.Error(err)
  110. c.Abort("500")
  111. }
  112. }
  113. if doc.BookId != bookResult.BookId {
  114. c.Abort("403")
  115. }
  116. if c.IsAjax() {
  117. var data struct{
  118. DocTitle string `json:"doc_title"`
  119. Body string `json:"body"`
  120. Title string `json:"title"`
  121. }
  122. data.DocTitle = doc.DocumentName
  123. data.Body = doc.Release
  124. data.Title = doc.DocumentName + " - Powered by MinDoc"
  125. c.JsonResult(0,"ok",data)
  126. }
  127. tree,err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId,doc.DocumentId)
  128. if err != nil {
  129. beego.Error(err)
  130. c.Abort("500")
  131. }
  132. c.Data["Model"] = bookResult
  133. c.Data["Result"] = template.HTML(tree)
  134. c.Data["Title"] = doc.DocumentName
  135. c.Data["Content"] = template.HTML(doc.Release)
  136. }
  137. func (c *DocumentController) Edit() {
  138. c.Prepare()
  139. identify := c.Ctx.Input.Param(":key")
  140. if identify == "" {
  141. c.Abort("404")
  142. }
  143. bookResult,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
  144. if err != nil {
  145. beego.Error("DocumentController.Edit => ",err)
  146. c.Abort("403")
  147. }
  148. if bookResult.RoleId == conf.BookObserver {
  149. c.JsonResult(6002,"项目不存在或权限不足")
  150. }
  151. //根据不同编辑器类型加载编辑器
  152. if bookResult.Editor == "markdown" {
  153. c.TplName = "document/markdown_edit_template.tpl"
  154. }else if bookResult.Editor == "html"{
  155. c.TplName = "document/html_edit_template.tpl"
  156. }else{
  157. c.TplName = "document/" + bookResult.Editor + "_edit_template.tpl"
  158. }
  159. c.Data["Model"] = bookResult
  160. r,_ := json.Marshal(bookResult)
  161. c.Data["ModelResult"] = template.JS(string(r))
  162. c.Data["Result"] = template.JS("[]")
  163. trees ,err := models.NewDocument().FindDocumentTree(bookResult.BookId)
  164. if err != nil {
  165. beego.Error("FindDocumentTree => ", err)
  166. }else{
  167. if len(trees) > 0 {
  168. if jtree, err := json.Marshal(trees); err == nil {
  169. c.Data["Result"] = template.JS(string(jtree))
  170. }
  171. }else{
  172. c.Data["Result"] = template.JS("[]")
  173. }
  174. }
  175. }
  176. //创建一个文档.
  177. func (c *DocumentController) Create() {
  178. identify := c.GetString("identify")
  179. doc_identify := c.GetString("doc_identify")
  180. doc_name := c.GetString("doc_name")
  181. parent_id,_ := c.GetInt("parent_id",0)
  182. doc_id,_ := c.GetInt("doc_id",0)
  183. if identify == "" {
  184. c.JsonResult(6001,"参数错误")
  185. }
  186. if doc_name == "" {
  187. c.JsonResult(6004,"文档名称不能为空")
  188. }
  189. if doc_identify != "" {
  190. if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, doc_identify); !ok || err != nil {
  191. c.JsonResult(6003, "文档标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
  192. }
  193. d,_ := models.NewDocument().FindByFieldFirst("identify",doc_identify);
  194. if d.DocumentId > 0 && d.DocumentId != doc_id{
  195. c.JsonResult(6006,"文档标识已被使用")
  196. }
  197. }
  198. bookResult,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
  199. if err != nil || bookResult.RoleId == conf.BookObserver {
  200. beego.Error("FindByIdentify => ",err)
  201. c.JsonResult(6002,"项目不存在或权限不足")
  202. }
  203. if parent_id > 0 {
  204. doc,err := models.NewDocument().Find(parent_id)
  205. if err != nil || doc.BookId != bookResult.BookId{
  206. c.JsonResult(6003,"父分类不存在")
  207. }
  208. }
  209. document,_ := models.NewDocument().Find(doc_id)
  210. document.MemberId = c.Member.MemberId
  211. document.BookId = bookResult.BookId
  212. if doc_identify != ""{
  213. document.Identify = doc_identify
  214. }
  215. document.Version = time.Now().Unix()
  216. document.DocumentName = doc_name
  217. document.ParentId = parent_id
  218. if err := document.InsertOrUpdate();err != nil {
  219. beego.Error("InsertOrUpdate => ",err)
  220. c.JsonResult(6005,"保存失败")
  221. }else{
  222. beego.Info("",document)
  223. c.JsonResult(0,"ok",document)
  224. }
  225. }
  226. //上传附件或图片.
  227. func (c *DocumentController) Upload() {
  228. identify := c.GetString("identify")
  229. doc_id,_ := c.GetInt("doc_id")
  230. if identify == "" {
  231. c.JsonResult(6001,"参数错误")
  232. }
  233. name := "editormd-file-file"
  234. file,moreFile,err := c.GetFile(name)
  235. if err == http.ErrMissingFile {
  236. name = "editormd-image-file"
  237. file,moreFile,err = c.GetFile(name);
  238. if err == http.ErrMissingFile {
  239. c.JsonResult(6003,"没有发现需要上传的文件")
  240. }
  241. }
  242. if err != nil {
  243. c.JsonResult(6002,err.Error())
  244. }
  245. defer file.Close()
  246. ext := filepath.Ext(moreFile.Filename)
  247. if ext == "" {
  248. c.JsonResult(6003,"无法解析文件的格式")
  249. }
  250. if !conf.IsAllowUploadFileExt(ext) {
  251. c.JsonResult(6004,"不允许的文件类型")
  252. }
  253. book,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
  254. if err != nil {
  255. beego.Error("DocumentController.Edit => ",err)
  256. if err == orm.ErrNoRows {
  257. c.JsonResult(6006,"权限不足")
  258. }
  259. c.JsonResult(6001,err.Error())
  260. }
  261. //如果没有编辑权限
  262. if book.RoleId != conf.BookEditor && book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
  263. c.JsonResult(6006,"权限不足")
  264. }
  265. if doc_id > 0 {
  266. doc,err := models.NewDocument().Find(doc_id);
  267. if err != nil {
  268. c.JsonResult(6007,"文档不存在")
  269. }
  270. if doc.BookId != book.BookId {
  271. c.JsonResult(6008,"文档不属于指定的项目")
  272. }
  273. }
  274. fileName := "attachment_" + strconv.FormatInt(time.Now().UnixNano(), 16)
  275. filePath := "uploads/" + time.Now().Format("200601") + "/" + fileName + ext
  276. path := filepath.Dir(filePath)
  277. os.MkdirAll(path, os.ModePerm)
  278. err = c.SaveToFile(name,filePath)
  279. if err != nil {
  280. beego.Error("SaveToFile => ",err)
  281. c.JsonResult(6005,"保存文件失败")
  282. }
  283. attachment := models.NewAttachment()
  284. attachment.BookId = book.BookId
  285. attachment.FileName = moreFile.Filename
  286. attachment.CreateAt = c.Member.MemberId
  287. attachment.FileExt = ext
  288. attachment.FilePath = filePath
  289. if doc_id > 0{
  290. attachment.DocumentId = doc_id
  291. }
  292. if strings.EqualFold(ext,".jpg") || strings.EqualFold(ext,".jpeg") || strings.EqualFold(ext,"png") || strings.EqualFold(ext,"gif") {
  293. attachment.HttpPath = c.BaseUrl() + "/" + filePath
  294. }
  295. err = attachment.Insert();
  296. if err != nil {
  297. os.Remove(filePath)
  298. beego.Error("Attachment Insert => ",err)
  299. c.JsonResult(6006,"文件保存失败")
  300. }
  301. if attachment.HttpPath == "" {
  302. attachment.HttpPath = c.BaseUrl() + beego.URLFor("DocumentController.DownloadAttachment",":key", identify, ":attach_id", attachment.AttachmentId)
  303. if err := attachment.Update();err != nil {
  304. beego.Error("SaveToFile => ",err)
  305. c.JsonResult(6005,"保存文件失败")
  306. }
  307. }
  308. result := map[string]interface{}{
  309. "errcode" : 0,
  310. "success" : 1,
  311. "message" :"ok",
  312. "url" : attachment.HttpPath,
  313. "alt" : attachment.FileName,
  314. }
  315. c.Data["json"] = result
  316. c.ServeJSON(true)
  317. c.StopRun()
  318. }
  319. //DownloadAttachment 下载附件.
  320. func (c *DocumentController) DownloadAttachment() {
  321. c.Prepare()
  322. identify := c.Ctx.Input.Param(":key")
  323. attach_id,_ := strconv.Atoi(c.Ctx.Input.Param(":attach_id"))
  324. token := c.GetString("token")
  325. member_id := 0
  326. if c.Member != nil {
  327. member_id = c.Member.MemberId
  328. }
  329. book_id := 0
  330. //判断用户是否参与了项目
  331. bookResult,err := models.NewBookResult().FindByIdentify(identify,member_id)
  332. if err != nil {
  333. //判断项目公开状态
  334. book,err := models.NewBook().FindByFieldFirst("identify",identify)
  335. if err != nil {
  336. c.Abort("404")
  337. }
  338. //如果项目是私有的,并且token不正确
  339. if (book.PrivatelyOwned == 1 && token == "" ) || ( book.PrivatelyOwned == 1 && book.PrivateToken != token ){
  340. c.Abort("403")
  341. }
  342. book_id = book.BookId
  343. }else{
  344. book_id = bookResult.BookId
  345. }
  346. attachment,err := models.NewAttachment().Find(attach_id)
  347. if err != nil {
  348. beego.Error("DownloadAttachment => ", err)
  349. if err == orm.ErrNoRows {
  350. c.Abort("404")
  351. } else {
  352. c.Abort("500")
  353. }
  354. }
  355. if attachment.BookId != book_id {
  356. c.Abort("404")
  357. }
  358. c.Ctx.Output.Download(attachment.FilePath,attachment.FileName)
  359. c.StopRun()
  360. }
  361. func (c *DocumentController) Delete() {
  362. c.Prepare()
  363. identify := c.GetString("identify")
  364. doc_id,err := c.GetInt("doc_id",0)
  365. bookResult,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
  366. if err != nil || bookResult.RoleId == conf.BookObserver {
  367. beego.Error("FindByIdentify => ",err)
  368. c.JsonResult(6002,"项目不存在或权限不足")
  369. }
  370. if doc_id <= 0 {
  371. c.JsonResult(6001,"参数错误")
  372. }
  373. doc,err := models.NewDocument().Find(doc_id)
  374. if err != nil {
  375. beego.Error("Delete => ",err)
  376. c.JsonResult(6003,"删除失败")
  377. }
  378. if doc.BookId != bookResult.BookId {
  379. c.JsonResult(6004,"参数错误")
  380. }
  381. err = doc.RecursiveDocument(doc.DocumentId)
  382. if err != nil {
  383. c.JsonResult(6005,"删除失败")
  384. }
  385. c.JsonResult(0,"ok")
  386. }
  387. func (c *DocumentController) Content() {
  388. c.Prepare()
  389. identify := c.Ctx.Input.Param(":key")
  390. doc_id,err := c.GetInt("doc_id")
  391. if err != nil {
  392. doc_id,_ = strconv.Atoi(c.Ctx.Input.Param(":id"))
  393. }
  394. bookResult,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
  395. if err != nil || bookResult.RoleId == conf.BookObserver {
  396. beego.Error("FindByIdentify => ",err)
  397. c.JsonResult(6002,"项目不存在或权限不足")
  398. }
  399. if doc_id <= 0 {
  400. c.JsonResult(6001,"参数错误")
  401. }
  402. if c.Ctx.Input.IsPost() {
  403. markdown := strings.TrimSpace(c.GetString("markdown",""))
  404. content := c.GetString("html")
  405. version,_ := c.GetInt64("version",0)
  406. is_cover := c.GetString("cover")
  407. doc ,err := models.NewDocument().Find(doc_id);
  408. if err != nil {
  409. c.JsonResult(6003,"读取文档错误")
  410. }
  411. if doc.BookId != bookResult.BookId {
  412. c.JsonResult(6004,"保存的文档不属于指定项目")
  413. }
  414. if doc.Version != version && !strings.EqualFold(is_cover,"yes"){
  415. beego.Info("%d|",version,doc.Version)
  416. c.JsonResult(6005,"文档已被修改确定要覆盖吗?")
  417. }
  418. if markdown == "" && content != ""{
  419. doc.Markdown = content
  420. }else{
  421. doc.Markdown = markdown
  422. }
  423. doc.Version = time.Now().Unix()
  424. doc.Content = content
  425. if err := doc.InsertOrUpdate();err != nil {
  426. beego.Error("InsertOrUpdate => ",err)
  427. c.JsonResult(6006,"保存失败")
  428. }
  429. c.JsonResult(0,"ok",doc)
  430. }
  431. doc,err := models.NewDocument().Find(doc_id)
  432. if err != nil {
  433. c.JsonResult(6003,"文档不存在")
  434. }
  435. c.JsonResult(0,"ok",doc)
  436. }