document.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package models
  2. import (
  3. "time"
  4. "bytes"
  5. "fmt"
  6. "github.com/astaxie/beego"
  7. "github.com/astaxie/beego/orm"
  8. "github.com/lifei6671/mindoc/conf"
  9. "strings"
  10. "os"
  11. "path/filepath"
  12. "strconv"
  13. "github.com/PuerkitoBio/goquery"
  14. "github.com/lifei6671/mindoc/cache"
  15. "encoding/json"
  16. )
  17. // Document struct.
  18. type Document struct {
  19. DocumentId int `orm:"pk;auto;unique;column(document_id)" json:"doc_id"`
  20. DocumentName string `orm:"column(document_name);size(500)" json:"doc_name"`
  21. // Identify 文档唯一标识
  22. Identify string `orm:"column(identify);size(100);index;null;default(null)" json:"identify"`
  23. BookId int `orm:"column(book_id);type(int);index" json:"book_id"`
  24. ParentId int `orm:"column(parent_id);type(int);index;default(0)" json:"parent_id"`
  25. OrderSort int `orm:"column(order_sort);default(0);type(int);index" json:"order_sort"`
  26. // Markdown markdown格式文档.
  27. Markdown string `orm:"column(markdown);type(text);null" json:"markdown"`
  28. // Release 发布后的Html格式内容.
  29. Release string `orm:"column(release);type(text);null" json:"release"`
  30. // Content 未发布的 Html 格式内容.
  31. Content string `orm:"column(content);type(text);null" json:"content"`
  32. CreateTime time.Time `orm:"column(create_time);type(datetime);auto_now_add" json:"create_time"`
  33. MemberId int `orm:"column(member_id);type(int)" json:"member_id"`
  34. ModifyTime time.Time `orm:"column(modify_time);type(datetime)" json:"modify_time"`
  35. ModifyAt int `orm:"column(modify_at);type(int)" json:"-"`
  36. Version int64 `orm:"type(bigint);column(version)" json:"version"`
  37. AttachList []*Attachment `orm:"-" json:"attach"`
  38. }
  39. // TableName 获取对应数据库表名.
  40. func (m *Document) TableName() string {
  41. return "documents"
  42. }
  43. // TableEngine 获取数据使用的引擎.
  44. func (m *Document) TableEngine() string {
  45. return "INNODB"
  46. }
  47. func (m *Document) TableNameWithPrefix() string {
  48. return conf.GetDatabasePrefix() + m.TableName()
  49. }
  50. func NewDocument() *Document {
  51. return &Document{
  52. Version: time.Now().Unix(),
  53. }
  54. }
  55. //根据文档ID查询指定文档.
  56. func (m *Document) Find(id int) (*Document, error) {
  57. if id <= 0 {
  58. return m, ErrInvalidParameter
  59. }
  60. o := orm.NewOrm()
  61. err := o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", id).One(m)
  62. if err == orm.ErrNoRows {
  63. return m, ErrDataNotExist
  64. }
  65. return m, nil
  66. }
  67. //插入和更新文档.
  68. func (m *Document) InsertOrUpdate(cols ...string) error {
  69. o := orm.NewOrm()
  70. var err error
  71. if m.DocumentId > 0 {
  72. m.ModifyTime = time.Now().Local()
  73. _, err = o.Update(m)
  74. } else {
  75. _, err = o.Insert(m)
  76. NewBook().ResetDocumentNumber(m.BookId)
  77. }
  78. if err != nil {
  79. return err
  80. }
  81. return nil
  82. }
  83. //根据指定字段查询一条文档.
  84. func (m *Document) FindByFieldFirst(field string, v interface{}) (*Document, error) {
  85. o := orm.NewOrm()
  86. err := o.QueryTable(m.TableNameWithPrefix()).Filter(field, v).One(m)
  87. return m, err
  88. }
  89. //递归删除一个文档.
  90. func (m *Document) RecursiveDocument(docId int) error {
  91. o := orm.NewOrm()
  92. if doc, err := m.Find(docId); err == nil {
  93. o.Delete(doc)
  94. NewDocumentHistory().Clear(doc.DocumentId)
  95. }
  96. //
  97. //var docs []*Document
  98. //
  99. //_, err := o.QueryTable(m.TableNameWithPrefix()).Filter("parent_id", doc_id).All(&docs)
  100. var maps []orm.Params
  101. _, err := o.Raw("SELECT document_id FROM " + m.TableNameWithPrefix() + " WHERE parent_id=" + strconv.Itoa(docId)).Values(&maps)
  102. if err != nil {
  103. beego.Error("RecursiveDocument => ", err)
  104. return err
  105. }
  106. for _, item := range maps {
  107. if docId,ok := item["document_id"].(string); ok{
  108. id,_ := strconv.Atoi(docId)
  109. o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", id).Delete()
  110. m.RecursiveDocument(id)
  111. }
  112. }
  113. return nil
  114. }
  115. //发布文档
  116. func (m *Document) ReleaseContent(bookId int) {
  117. o := orm.NewOrm()
  118. var docs []*Document
  119. _, err := o.QueryTable(m.TableNameWithPrefix()).Filter("book_id", bookId).All(&docs, "document_id","identify", "content")
  120. if err != nil {
  121. beego.Error("发布失败 => ", err)
  122. return
  123. }
  124. for _, item := range docs {
  125. if item.Content != "" {
  126. item.Release = item.Content
  127. bufio := bytes.NewReader([]byte(item.Content))
  128. //解析文档中非本站的链接,并设置为新窗口打开
  129. if content, err := goquery.NewDocumentFromReader(bufio);err == nil {
  130. content.Find("a").Each(func(i int, contentSelection *goquery.Selection) {
  131. if src, ok := contentSelection.Attr("href"); ok{
  132. if strings.HasPrefix(src, "http://") || strings.HasPrefix(src,"https://") {
  133. //beego.Info(src,conf.BaseUrl,strings.HasPrefix(src,conf.BaseUrl))
  134. if conf.BaseUrl != "" && !strings.HasPrefix(src,conf.BaseUrl) {
  135. contentSelection.SetAttr("target", "_blank")
  136. if html, err := content.Html();err == nil {
  137. item.Release = html
  138. }
  139. }
  140. }
  141. }
  142. })
  143. }
  144. }
  145. attachList, err := NewAttachment().FindListByDocumentId(item.DocumentId)
  146. if err == nil && len(attachList) > 0 {
  147. content := bytes.NewBufferString("<div class=\"attach-list\"><strong>附件</strong><ul>")
  148. for _, attach := range attachList {
  149. if strings.HasPrefix(attach.HttpPath, "/") {
  150. attach.HttpPath = strings.TrimSuffix(conf.BaseUrl, "/") + attach.HttpPath
  151. }
  152. li := fmt.Sprintf("<li><a href=\"%s\" target=\"_blank\" title=\"%s\">%s</a></li>", attach.HttpPath, attach.FileName, attach.FileName)
  153. content.WriteString(li)
  154. }
  155. content.WriteString("</ul></div>")
  156. item.Release += content.String()
  157. }
  158. _, err = o.Update(item, "release")
  159. if err != nil {
  160. beego.Error(fmt.Sprintf("发布失败 => %+v", item), err)
  161. }else {
  162. //当文档发布后,需要清除已缓存的转换文档和文档缓存
  163. if doc,err := NewDocument().Find(item.DocumentId); err == nil {
  164. doc.PutToCache()
  165. }else{
  166. doc.RemoveCache()
  167. }
  168. os.RemoveAll(filepath.Join(conf.WorkingDirectory,"uploads","books",strconv.Itoa(bookId)))
  169. }
  170. }
  171. }
  172. //将文档写入缓存
  173. func (m *Document) PutToCache(){
  174. go func(m Document) {
  175. if v,err := json.Marshal(&m);err == nil {
  176. if m.Identify == "" {
  177. if err := cache.Put("Document.Id." + strconv.Itoa(m.DocumentId), v, time.Second*3600); err != nil {
  178. beego.Info("文档缓存失败:", m.DocumentId)
  179. }
  180. }else{
  181. if err := cache.Put("Document.Identify."+ m.Identify, v, time.Second*3600); err != nil {
  182. beego.Info("文档缓存失败:", m.DocumentId)
  183. }
  184. }
  185. }
  186. }(*m)
  187. }
  188. //清除缓存
  189. func (m *Document) RemoveCache() {
  190. go func(m Document) {
  191. cache.Put("Document.Id." + strconv.Itoa(m.DocumentId), m, time.Second*3600);
  192. if m.Identify != "" {
  193. cache.Put("Document.Identify."+ m.Identify, m, time.Second*3600);
  194. }
  195. }(*m)
  196. }
  197. //从缓存获取
  198. func (m *Document) FromCacheById(id int) (*Document,error) {
  199. b := cache.Get("Document.Id." + strconv.Itoa(id))
  200. if v,ok := b.([]byte); ok {
  201. if err := json.Unmarshal(v,m);err == nil{
  202. beego.Info("从缓存中获取文档信息成功",m.DocumentId)
  203. return m,nil
  204. }
  205. }
  206. defer func() {
  207. if m.DocumentId > 0 {
  208. m.PutToCache()
  209. }
  210. }()
  211. return m.Find(id)
  212. }
  213. //根据文档标识从缓存中查询文档
  214. func (m *Document) FromCacheByIdentify(identify string) (*Document,error) {
  215. b := cache.Get("Document.Identify." + identify)
  216. if v,ok := b.([]byte); ok {
  217. if err := json.Unmarshal(v,m);err == nil{
  218. beego.Info("从缓存中获取文档信息成功",m.DocumentId,identify)
  219. return m,nil
  220. }
  221. }
  222. defer func() {
  223. if m.DocumentId > 0 {
  224. m.PutToCache()
  225. }
  226. }()
  227. return m.FindByFieldFirst("identify",identify)
  228. }
  229. //根据项目ID查询文档列表.
  230. func (m *Document) FindListByBookId(bookId int) (docs []*Document, err error) {
  231. o := orm.NewOrm()
  232. _, err = o.QueryTable(m.TableNameWithPrefix()).Filter("book_id", bookId).OrderBy("order_sort").All(&docs)
  233. return
  234. }