DocumentModel.go 8.4 KB

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