document.go 13 KB

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