book_result.go 10 KB

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