book_result.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package models
  2. import (
  3. "bytes"
  4. "time"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "encoding/base64"
  11. "github.com/PuerkitoBio/goquery"
  12. "github.com/astaxie/beego"
  13. "github.com/astaxie/beego/logs"
  14. "github.com/astaxie/beego/orm"
  15. "github.com/lifei6671/mindoc/conf"
  16. "github.com/lifei6671/mindoc/converter"
  17. "github.com/lifei6671/mindoc/utils"
  18. "gopkg.in/russross/blackfriday.v2"
  19. )
  20. type BookResult struct {
  21. BookId int `json:"book_id"`
  22. BookName string `json:"book_name"`
  23. Identify string `json:"identify"`
  24. OrderIndex int `json:"order_index"`
  25. Description string `json:"description"`
  26. Publisher string `json:"publisher"`
  27. PrivatelyOwned int `json:"privately_owned"`
  28. PrivateToken string `json:"private_token"`
  29. DocCount int `json:"doc_count"`
  30. CommentStatus string `json:"comment_status"`
  31. CommentCount int `json:"comment_count"`
  32. CreateTime time.Time `json:"create_time"`
  33. CreateName string `json:"create_name"`
  34. RealName string `json:"real_name"`
  35. ModifyTime time.Time `json:"modify_time"`
  36. Cover string `json:"cover"`
  37. Theme string `json:"theme"`
  38. Label string `json:"label"`
  39. MemberId int `json:"member_id"`
  40. Editor string `json:"editor"`
  41. AutoRelease bool `json:"auto_release"`
  42. HistoryCount int `json:"history_count"`
  43. RelationshipId int `json:"relationship_id"`
  44. RoleId int `json:"role_id"`
  45. RoleName string `json:"role_name"`
  46. Status int
  47. LastModifyText string `json:"last_modify_text"`
  48. IsDisplayComment bool `json:"is_display_comment"`
  49. IsDownload bool `json:"is_download"`
  50. }
  51. func NewBookResult() *BookResult {
  52. return &BookResult{}
  53. }
  54. // 根据项目标识查询项目以及指定用户权限的信息.
  55. func (m *BookResult) FindByIdentify(identify string, member_id int) (*BookResult, error) {
  56. if identify == "" || member_id <= 0 {
  57. return m, ErrInvalidParameter
  58. }
  59. o := orm.NewOrm()
  60. book := NewBook()
  61. err := o.QueryTable(book.TableNameWithPrefix()).Filter("identify", identify).One(book)
  62. if err != nil {
  63. return m, err
  64. }
  65. relationship := NewRelationship()
  66. err = o.QueryTable(relationship.TableNameWithPrefix()).Filter("book_id", book.BookId).Filter("member_id", member_id).One(relationship)
  67. if err != nil {
  68. return m, err
  69. }
  70. var relationship2 Relationship
  71. err = o.QueryTable(relationship.TableNameWithPrefix()).Filter("book_id", book.BookId).Filter("role_id", 0).One(&relationship2)
  72. if err != nil {
  73. logs.Error("根据项目标识查询项目以及指定用户权限的信息 => ", err)
  74. return m, ErrPermissionDenied
  75. }
  76. member, err := NewMember().Find(relationship2.MemberId)
  77. if err != nil {
  78. return m, err
  79. }
  80. m = NewBookResult().ToBookResult(*book)
  81. m.CreateName = member.Account
  82. if member.RealName != "" {
  83. m.RealName = member.RealName
  84. }
  85. m.MemberId = relationship.MemberId
  86. m.RoleId = relationship.RoleId
  87. m.RelationshipId = relationship.RelationshipId
  88. if m.RoleId == conf.BookFounder {
  89. m.RoleName = "创始人"
  90. } else if m.RoleId == conf.BookAdmin {
  91. m.RoleName = "管理员"
  92. } else if m.RoleId == conf.BookEditor {
  93. m.RoleName = "编辑者"
  94. } else if m.RoleId == conf.BookObserver {
  95. m.RoleName = "观察者"
  96. }
  97. doc := NewDocument()
  98. err = o.QueryTable(doc.TableNameWithPrefix()).Filter("book_id", book.BookId).OrderBy("modify_time").One(doc)
  99. if err == nil {
  100. member2 := NewMember()
  101. member2.Find(doc.ModifyAt)
  102. m.LastModifyText = member2.Account + " 于 " + doc.ModifyTime.Format("2006-01-02 15:04:05")
  103. }
  104. return m, nil
  105. }
  106. func (m *BookResult) FindToPager(pageIndex, pageSize int) (books []*BookResult, totalCount int, err error) {
  107. o := orm.NewOrm()
  108. count, err := o.QueryTable(NewBook().TableNameWithPrefix()).Count()
  109. if err != nil {
  110. return
  111. }
  112. totalCount = int(count)
  113. sql := `SELECT
  114. book.*,rel.relationship_id,rel.role_id,m.account AS create_name,m.real_name
  115. FROM md_books AS book
  116. LEFT JOIN md_relationship AS rel ON rel.book_id = book.book_id AND rel.role_id = 0
  117. LEFT JOIN md_members AS m ON rel.member_id = m.member_id
  118. ORDER BY book.order_index DESC ,book.book_id DESC LIMIT ?,?`
  119. offset := (pageIndex - 1) * pageSize
  120. _, err = o.Raw(sql, offset, pageSize).QueryRows(&books)
  121. return
  122. }
  123. //实体转换
  124. func (m *BookResult) ToBookResult(book Book) *BookResult {
  125. m.BookId = book.BookId
  126. m.BookName = book.BookName
  127. m.Identify = book.Identify
  128. m.OrderIndex = book.OrderIndex
  129. m.Description = strings.Replace(book.Description, "\r\n", "<br/>", -1)
  130. m.PrivatelyOwned = book.PrivatelyOwned
  131. m.PrivateToken = book.PrivateToken
  132. m.DocCount = book.DocCount
  133. m.CommentStatus = book.CommentStatus
  134. m.CommentCount = book.CommentCount
  135. m.CreateTime = book.CreateTime
  136. m.ModifyTime = book.ModifyTime
  137. m.Cover = book.Cover
  138. m.Label = book.Label
  139. m.Status = book.Status
  140. m.Editor = book.Editor
  141. m.Theme = book.Theme
  142. m.AutoRelease = book.AutoRelease == 1
  143. m.Publisher = book.Publisher
  144. m.HistoryCount = book.HistoryCount
  145. m.IsDownload = book.IsDownload == 0
  146. if book.Theme == "" {
  147. m.Theme = "default"
  148. }
  149. if book.Editor == "" {
  150. m.Editor = "markdown"
  151. }
  152. return m
  153. }
  154. func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) {
  155. convertBookResult := ConvertBookResult{}
  156. outputPath := filepath.Join(conf.WorkingDirectory,"uploads","books", strconv.Itoa(m.BookId))
  157. viewPath := beego.BConfig.WebConfig.ViewsPath
  158. pdfpath := filepath.Join(outputPath, "book.pdf")
  159. epubpath := filepath.Join(outputPath, "book.epub")
  160. mobipath := filepath.Join(outputPath, "book.mobi")
  161. docxpath := filepath.Join(outputPath, "book.docx")
  162. //先将转换的文件储存到临时目录
  163. tempOutputPath := filepath.Join(os.TempDir(),sessionId) //filepath.Abs(filepath.Join("cache", sessionId))
  164. os.MkdirAll(outputPath, 0766)
  165. os.MkdirAll(tempOutputPath, 0766)
  166. defer func(p string) {
  167. os.RemoveAll(p)
  168. }(tempOutputPath)
  169. if utils.FileExists(pdfpath) && utils.FileExists(epubpath) && utils.FileExists(mobipath) && utils.FileExists(docxpath) {
  170. convertBookResult.EpubPath = epubpath
  171. convertBookResult.MobiPath = mobipath
  172. convertBookResult.PDFPath = pdfpath
  173. convertBookResult.WordPath = docxpath
  174. return convertBookResult, nil
  175. }
  176. docs, err := NewDocument().FindListByBookId(m.BookId)
  177. if err != nil {
  178. return convertBookResult, err
  179. }
  180. tocList := make([]converter.Toc, 0)
  181. for _, item := range docs {
  182. if item.ParentId == 0 {
  183. toc := converter.Toc{
  184. Id: item.DocumentId,
  185. Link: strconv.Itoa(item.DocumentId) + ".html",
  186. Pid: item.ParentId,
  187. Title: item.DocumentName,
  188. }
  189. tocList = append(tocList, toc)
  190. }
  191. }
  192. for _, item := range docs {
  193. if item.ParentId != 0 {
  194. toc := converter.Toc{
  195. Id: item.DocumentId,
  196. Link: strconv.Itoa(item.DocumentId) + ".html",
  197. Pid: item.ParentId,
  198. Title: item.DocumentName,
  199. }
  200. tocList = append(tocList, toc)
  201. }
  202. }
  203. ebookConfig := converter.Config{
  204. Charset: "utf-8",
  205. Cover: m.Cover,
  206. Timestamp: time.Now().Format("2006-01-02 15:04:05"),
  207. Description: string(blackfriday.Run([]byte(m.Description))),
  208. Footer: "<p style='color:#8E8E8E;font-size:12px;'>本文档使用 <a href='https://www.iminho.me' style='text-decoration:none;color:#1abc9c;font-weight:bold;'>MinDoc</a> 构建 <span style='float:right'>- _PAGENUM_ -</span></p>",
  209. Header: "<p style='color:#8E8E8E;font-size:12px;'>_SECTION_</p>",
  210. Identifier: "",
  211. Language: "zh-CN",
  212. Creator: m.CreateName,
  213. Publisher: m.Publisher,
  214. Contributor: m.Publisher,
  215. Title: m.BookName,
  216. Format: []string{"epub", "mobi", "pdf", "docx"},
  217. FontSize: "14",
  218. PaperSize: "a4",
  219. MarginLeft: "72",
  220. MarginRight: "72",
  221. MarginTop: "72",
  222. MarginBottom: "72",
  223. Toc: tocList,
  224. More: []string{},
  225. }
  226. if m.Publisher != "" {
  227. ebookConfig.Footer = "<p style='color:#8E8E8E;font-size:12px;'>本文档由 <span style='text-decoration:none;color:#1abc9c;font-weight:bold;'>"+ m.Publisher +"</span> 生成<span style='float:right'>- _PAGENUM_ -</span></p>"
  228. }
  229. if m.RealName != "" {
  230. ebookConfig.Creator = m.RealName
  231. }
  232. if tempOutputPath, err = filepath.Abs(tempOutputPath); err != nil {
  233. beego.Error("导出目录配置错误:" + err.Error())
  234. return convertBookResult, err
  235. }
  236. for _, item := range docs {
  237. name := strconv.Itoa(item.DocumentId)
  238. fpath := filepath.Join(tempOutputPath, name+".html")
  239. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0777)
  240. if err != nil {
  241. return convertBookResult, err
  242. }
  243. var buf bytes.Buffer
  244. if err := beego.ExecuteViewPathTemplate(&buf, "document/export.tpl", viewPath, map[string]interface{}{"Model": m, "Lists": item, "BaseUrl": conf.BaseUrl}); err != nil {
  245. return convertBookResult, err
  246. }
  247. html := buf.String()
  248. if err != nil {
  249. f.Close()
  250. return convertBookResult, err
  251. }
  252. bufio := bytes.NewReader(buf.Bytes())
  253. doc, err := goquery.NewDocumentFromReader(bufio)
  254. doc.Find("img").Each(func(i int, contentSelection *goquery.Selection) {
  255. if src, ok := contentSelection.Attr("src"); ok && strings.HasPrefix(src, "/") {
  256. //contentSelection.SetAttr("src", baseUrl + src)
  257. spath := filepath.Join(conf.WorkingDirectory, src)
  258. if ff, e := ioutil.ReadFile(spath); e == nil {
  259. encodeString := base64.StdEncoding.EncodeToString(ff)
  260. src = "data:image/" + filepath.Ext(src) + ";base64," + encodeString
  261. contentSelection.SetAttr("src", src)
  262. }
  263. }
  264. })
  265. html, err = doc.Html()
  266. if err != nil {
  267. f.Close()
  268. return convertBookResult, err
  269. }
  270. // html = strings.Replace(html, "<img src=\"/uploads", "<img src=\"" + c.BaseUrl() + "/uploads", -1)
  271. f.WriteString(html)
  272. f.Close()
  273. }
  274. eBookConverter := &converter.Converter{
  275. BasePath: tempOutputPath,
  276. Config: ebookConfig,
  277. Debug: true,
  278. }
  279. if err := eBookConverter.Convert(); err != nil {
  280. beego.Error("转换文件错误:" + m.BookName + " => " + err.Error())
  281. return convertBookResult, err
  282. }
  283. beego.Info("文档转换完成:" + m.BookName)
  284. utils.CopyFile(mobipath, filepath.Join(tempOutputPath, "output", "book.mobi"))
  285. utils.CopyFile(pdfpath, filepath.Join(tempOutputPath, "output", "book.pdf"))
  286. utils.CopyFile(epubpath, filepath.Join(tempOutputPath, "output", "book.epub"))
  287. utils.CopyFile(docxpath, filepath.Join(tempOutputPath, "output", "book.docx"))
  288. convertBookResult.MobiPath = mobipath
  289. convertBookResult.PDFPath = pdfpath
  290. convertBookResult.EpubPath = epubpath
  291. convertBookResult.WordPath = docxpath
  292. return convertBookResult, nil
  293. }