1
0

document.go 13 KB

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