book_result.go 9.8 KB

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