BookResult.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. package models
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/PuerkitoBio/goquery"
  11. "github.com/astaxie/beego"
  12. "github.com/astaxie/beego/logs"
  13. "github.com/astaxie/beego/orm"
  14. "github.com/lifei6671/mindoc/conf"
  15. "github.com/lifei6671/mindoc/converter"
  16. "github.com/lifei6671/mindoc/utils/filetil"
  17. "github.com/lifei6671/mindoc/utils/ziptil"
  18. "gopkg.in/russross/blackfriday.v2"
  19. "regexp"
  20. "github.com/lifei6671/mindoc/utils/cryptil"
  21. "github.com/lifei6671/mindoc/utils/requests"
  22. "github.com/lifei6671/mindoc/utils/gopool"
  23. "net/http"
  24. )
  25. var(
  26. exportLimitWorkerChannel = gopool.NewChannelPool(conf.GetExportLimitNum(),conf.GetExportQueueLimitNum())
  27. )
  28. type BookResult struct {
  29. BookId int `json:"book_id"`
  30. BookName string `json:"book_name"`
  31. Identify string `json:"identify"`
  32. OrderIndex int `json:"order_index"`
  33. Description string `json:"description"`
  34. Publisher string `json:"publisher"`
  35. PrivatelyOwned int `json:"privately_owned"`
  36. PrivateToken string `json:"private_token"`
  37. DocCount int `json:"doc_count"`
  38. CommentStatus string `json:"comment_status"`
  39. CommentCount int `json:"comment_count"`
  40. CreateTime time.Time `json:"create_time"`
  41. CreateName string `json:"create_name"`
  42. RealName string `json:"real_name"`
  43. ModifyTime time.Time `json:"modify_time"`
  44. Cover string `json:"cover"`
  45. Theme string `json:"theme"`
  46. Label string `json:"label"`
  47. MemberId int `json:"member_id"`
  48. Editor string `json:"editor"`
  49. AutoRelease bool `json:"auto_release"`
  50. HistoryCount int `json:"history_count"`
  51. RelationshipId int `json:"relationship_id"`
  52. RoleId int `json:"role_id"`
  53. RoleName string `json:"role_name"`
  54. Status int `json:"status"`
  55. IsEnableShare bool `json:"is_enable_share"`
  56. IsUseFirstDocument bool `json:"is_use_first_document"`
  57. LastModifyText string `json:"last_modify_text"`
  58. IsDisplayComment bool `json:"is_display_comment"`
  59. IsDownload bool `json:"is_download"`
  60. }
  61. func NewBookResult() *BookResult {
  62. return &BookResult{}
  63. }
  64. // 根据项目标识查询项目以及指定用户权限的信息.
  65. func (m *BookResult) FindByIdentify(identify string, memberId int) (*BookResult, error) {
  66. if identify == "" || memberId <= 0 {
  67. return m, ErrInvalidParameter
  68. }
  69. o := orm.NewOrm()
  70. book := NewBook()
  71. err := o.QueryTable(book.TableNameWithPrefix()).Filter("identify", identify).One(book)
  72. if err != nil {
  73. return m, err
  74. }
  75. relationship := NewRelationship()
  76. err = o.QueryTable(relationship.TableNameWithPrefix()).Filter("book_id", book.BookId).Filter("member_id", memberId).One(relationship)
  77. if err != nil {
  78. return m, err
  79. }
  80. var relationship2 Relationship
  81. err = o.QueryTable(relationship.TableNameWithPrefix()).Filter("book_id", book.BookId).Filter("role_id", 0).One(&relationship2)
  82. if err != nil {
  83. logs.Error("根据项目标识查询项目以及指定用户权限的信息 => ", err)
  84. return m, ErrPermissionDenied
  85. }
  86. member, err := NewMember().Find(relationship2.MemberId)
  87. if err != nil {
  88. return m, err
  89. }
  90. m = NewBookResult().ToBookResult(*book)
  91. m.CreateName = member.Account
  92. if member.RealName != "" {
  93. m.RealName = member.RealName
  94. }
  95. m.MemberId = relationship.MemberId
  96. m.RoleId = relationship.RoleId
  97. m.RelationshipId = relationship.RelationshipId
  98. if m.RoleId == conf.BookFounder {
  99. m.RoleName = "创始人"
  100. } else if m.RoleId == conf.BookAdmin {
  101. m.RoleName = "管理员"
  102. } else if m.RoleId == conf.BookEditor {
  103. m.RoleName = "编辑者"
  104. } else if m.RoleId == conf.BookObserver {
  105. m.RoleName = "观察者"
  106. }
  107. doc := NewDocument()
  108. err = o.QueryTable(doc.TableNameWithPrefix()).Filter("book_id", book.BookId).OrderBy("modify_time").One(doc)
  109. if err == nil {
  110. member2 := NewMember()
  111. member2.Find(doc.ModifyAt)
  112. m.LastModifyText = member2.Account + " 于 " + doc.ModifyTime.Local().Format("2006-01-02 15:04:05")
  113. }
  114. return m, nil
  115. }
  116. func (m *BookResult) FindToPager(pageIndex, pageSize int) (books []*BookResult, totalCount int, err error) {
  117. o := orm.NewOrm()
  118. count, err := o.QueryTable(NewBook().TableNameWithPrefix()).Count()
  119. if err != nil {
  120. return
  121. }
  122. totalCount = int(count)
  123. sql := `SELECT
  124. book.*,rel.relationship_id,rel.role_id,m.account AS create_name,m.real_name
  125. FROM md_books AS book
  126. LEFT JOIN md_relationship AS rel ON rel.book_id = book.book_id AND rel.role_id = 0
  127. LEFT JOIN md_members AS m ON rel.member_id = m.member_id
  128. ORDER BY book.order_index DESC ,book.book_id DESC LIMIT ?,?`
  129. offset := (pageIndex - 1) * pageSize
  130. _, err = o.Raw(sql, offset, pageSize).QueryRows(&books)
  131. return
  132. }
  133. //实体转换
  134. func (m *BookResult) ToBookResult(book Book) *BookResult {
  135. m.BookId = book.BookId
  136. m.BookName = book.BookName
  137. m.Identify = book.Identify
  138. m.OrderIndex = book.OrderIndex
  139. m.Description = strings.Replace(book.Description, "\r\n", "<br/>", -1)
  140. m.PrivatelyOwned = book.PrivatelyOwned
  141. m.PrivateToken = book.PrivateToken
  142. m.DocCount = book.DocCount
  143. m.CommentStatus = book.CommentStatus
  144. m.CommentCount = book.CommentCount
  145. m.CreateTime = book.CreateTime
  146. m.ModifyTime = book.ModifyTime
  147. m.Cover = book.Cover
  148. m.Label = book.Label
  149. m.Status = book.Status
  150. m.Editor = book.Editor
  151. m.Theme = book.Theme
  152. m.AutoRelease = book.AutoRelease == 1
  153. m.IsEnableShare = book.IsEnableShare == 0
  154. m.IsUseFirstDocument = book.IsUseFirstDocument == 1
  155. m.Publisher = book.Publisher
  156. m.HistoryCount = book.HistoryCount
  157. m.IsDownload = book.IsDownload == 0
  158. if book.Theme == "" {
  159. m.Theme = "default"
  160. }
  161. if book.Editor == "" {
  162. m.Editor = "markdown"
  163. }
  164. doc := NewDocument()
  165. o := orm.NewOrm()
  166. err := o.QueryTable(doc.TableNameWithPrefix()).Filter("book_id", book.BookId).OrderBy("modify_time").One(doc)
  167. if err == nil {
  168. member2 := NewMember()
  169. member2.Find(doc.ModifyAt)
  170. m.LastModifyText = member2.Account + " 于 " + doc.ModifyTime.Local().Format("2006-01-02 15:04:05")
  171. }
  172. return m
  173. }
  174. //后台转换
  175. func BackgroupConvert(sessionId string,bookResult *BookResult) error {
  176. if err := converter.CheckConvertCommand(); err != nil {
  177. beego.Error("检查转换程序失败 -> ",err)
  178. return err
  179. }
  180. err := exportLimitWorkerChannel.LoadOrStore(bookResult.Identify, func() {
  181. bookResult.Converter(sessionId)
  182. })
  183. if err != nil {
  184. beego.Error("将导出任务加入任务队列失败 -> ",err)
  185. return err
  186. }
  187. exportLimitWorkerChannel.Start()
  188. return nil
  189. }
  190. //导出PDF、word等格式
  191. func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) {
  192. convertBookResult := ConvertBookResult{}
  193. outputPath := filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(m.BookId))
  194. viewPath := beego.BConfig.WebConfig.ViewsPath
  195. pdfpath := filepath.Join(outputPath, "book.pdf")
  196. epubpath := filepath.Join(outputPath, "book.epub")
  197. mobipath := filepath.Join(outputPath, "book.mobi")
  198. docxpath := filepath.Join(outputPath, "book.docx")
  199. //先将转换的文件储存到临时目录
  200. tempOutputPath := filepath.Join(os.TempDir(), sessionId, m.Identify,"source") //filepath.Abs(filepath.Join("cache", sessionId))
  201. sourceDir := strings.TrimSuffix(tempOutputPath,"source");
  202. if filetil.FileExists(sourceDir) {
  203. if err := os.RemoveAll(sourceDir); err != nil {
  204. beego.Error("删除临时目录失败 ->", sourceDir , err)
  205. }
  206. }
  207. if err := os.MkdirAll(outputPath, 0766); err != nil {
  208. beego.Error("创建目录失败 => ",outputPath,err)
  209. }
  210. if err := os.MkdirAll(tempOutputPath, 0766);err != nil {
  211. beego.Error("创建目录失败 => ",tempOutputPath,err)
  212. }
  213. os.MkdirAll(filepath.Join(tempOutputPath,"Images"),0755)
  214. //defer os.RemoveAll(strings.TrimSuffix(tempOutputPath,"source"))
  215. if filetil.FileExists(pdfpath) && filetil.FileExists(epubpath) && filetil.FileExists(mobipath) && filetil.FileExists(docxpath) {
  216. convertBookResult.EpubPath = epubpath
  217. convertBookResult.MobiPath = mobipath
  218. convertBookResult.PDFPath = pdfpath
  219. convertBookResult.WordPath = docxpath
  220. return convertBookResult, nil
  221. }
  222. docs, err := NewDocument().FindListByBookId(m.BookId)
  223. if err != nil {
  224. return convertBookResult, err
  225. }
  226. tocList := make([]converter.Toc, 0)
  227. for _, item := range docs {
  228. if item.ParentId == 0 {
  229. toc := converter.Toc{
  230. Id: item.DocumentId,
  231. Link: strconv.Itoa(item.DocumentId) + ".html",
  232. Pid: item.ParentId,
  233. Title: item.DocumentName,
  234. }
  235. tocList = append(tocList, toc)
  236. }
  237. }
  238. for _, item := range docs {
  239. if item.ParentId != 0 {
  240. toc := converter.Toc{
  241. Id: item.DocumentId,
  242. Link: strconv.Itoa(item.DocumentId) + ".html",
  243. Pid: item.ParentId,
  244. Title: item.DocumentName,
  245. }
  246. tocList = append(tocList, toc)
  247. }
  248. }
  249. ebookConfig := converter.Config{
  250. Charset: "utf-8",
  251. Cover: m.Cover,
  252. Timestamp: time.Now().Format("2006-01-02 15:04:05"),
  253. Description: string(blackfriday.Run([]byte(m.Description))),
  254. 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>",
  255. Header: "<p style='color:#8E8E8E;font-size:12px;'>_SECTION_</p>",
  256. Identifier: "",
  257. Language: "zh-CN",
  258. Creator: m.CreateName,
  259. Publisher: m.Publisher,
  260. Contributor: m.Publisher,
  261. Title: m.BookName,
  262. Format: []string{"epub", "mobi", "pdf", "docx"},
  263. FontSize: "14",
  264. PaperSize: "a4",
  265. MarginLeft: "72",
  266. MarginRight: "72",
  267. MarginTop: "72",
  268. MarginBottom: "72",
  269. Toc: tocList,
  270. More: []string{},
  271. }
  272. if m.Publisher != "" {
  273. 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>"
  274. }
  275. if m.RealName != "" {
  276. ebookConfig.Creator = m.RealName
  277. }
  278. if tempOutputPath, err = filepath.Abs(tempOutputPath); err != nil {
  279. beego.Error("导出目录配置错误:" + err.Error())
  280. return convertBookResult, err
  281. }
  282. for _, item := range docs {
  283. name := strconv.Itoa(item.DocumentId)
  284. fpath := filepath.Join(tempOutputPath, name+".html")
  285. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0777)
  286. if err != nil {
  287. return convertBookResult, err
  288. }
  289. var buf bytes.Buffer
  290. if err := beego.ExecuteViewPathTemplate(&buf, "document/export.tpl", viewPath, map[string]interface{}{"Model": m, "Lists": item, "BaseUrl": conf.BaseUrl}); err != nil {
  291. return convertBookResult, err
  292. }
  293. html := buf.String()
  294. if err != nil {
  295. f.Close()
  296. return convertBookResult, err
  297. }
  298. bufio := bytes.NewReader(buf.Bytes())
  299. doc, err := goquery.NewDocumentFromReader(bufio)
  300. doc.Find("img").Each(func(i int, contentSelection *goquery.Selection) {
  301. if src, ok := contentSelection.Attr("src"); ok {
  302. //var encodeString string
  303. dstSrcString := "Images/" + filepath.Base(src)
  304. //如果是本地路径则直接读取文件内容
  305. if strings.HasPrefix(src, "/") {
  306. spath := filepath.Join(conf.WorkingDirectory, src)
  307. if filetil.CopyFile(spath,filepath.Join(tempOutputPath,dstSrcString));err != nil {
  308. beego.Error("复制图片失败 -> ",err,src)
  309. return
  310. }
  311. //if ff, e := ioutil.ReadFile(spath); e == nil {
  312. // encodeString = base64.StdEncoding.EncodeToString(ff)
  313. //}
  314. }else{
  315. client := &http.Client{}
  316. if req,err := http.NewRequest("GET",src,nil); err == nil {
  317. req.Header.Set("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36")
  318. req.Header.Set("Referer",src)
  319. //10秒连接超时时间
  320. client.Timeout = time.Second * 100
  321. if resp ,err := client.Do(req);err == nil {
  322. defer resp.Body.Close()
  323. if body, err := ioutil.ReadAll(resp.Body);err == nil {
  324. //encodeString = base64.StdEncoding.EncodeToString(body)
  325. if err := ioutil.WriteFile(filepath.Join(tempOutputPath,dstSrcString),body,0755);err != nil {
  326. beego.Error("下载图片失败 -> ",err,src)
  327. return
  328. }
  329. }else{
  330. beego.Error("下载图片失败 -> ",err,src)
  331. return
  332. }
  333. }else{
  334. beego.Error("下载图片失败 -> ",err,src)
  335. return
  336. }
  337. }
  338. }
  339. //if encodeString != "" {
  340. // src = "data:image/" + strings.TrimPrefix(filepath.Ext(src),".") + ";base64," + encodeString
  341. //
  342. // contentSelection.SetAttr("src", src)
  343. //}
  344. contentSelection.SetAttr("src", dstSrcString)
  345. }
  346. })
  347. html, err = doc.Html()
  348. if err != nil {
  349. f.Close()
  350. return convertBookResult, err
  351. }
  352. f.WriteString(html)
  353. f.Close()
  354. }
  355. if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "css", "kancloud.css"), filepath.Join(tempOutputPath, "styles", "css", "kancloud.css")); err != nil {
  356. beego.Error("复制CSS样式出错 => static/css/kancloud.css",err)
  357. }
  358. if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "css", "export.css"), filepath.Join(tempOutputPath, "styles", "css", "export.css"));err != nil {
  359. beego.Error("复制CSS样式出错 => static/css/export.css",err)
  360. }
  361. if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "editor.md", "css", "editormd.preview.css"), filepath.Join(tempOutputPath, "styles", "editor.md", "css", "editormd.preview.css"));err != nil {
  362. beego.Error("复制CSS样式出错 => static/editor.md/css/editormd.preview.css",err)
  363. }
  364. if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "prettify", "themes", "prettify.css"), filepath.Join(tempOutputPath, "styles", "prettify", "themes", "prettify.css")); err != nil {
  365. beego.Error("复制CSS样式出错 => static/prettify/themes/prettify.css",err)
  366. }
  367. if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "css", "markdown.preview.css"), filepath.Join(tempOutputPath, "styles", "css", "markdown.preview.css"));err != nil {
  368. beego.Error("复制CSS样式出错 => static/css/markdown.preview.css",err)
  369. }
  370. if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "highlight", "styles", "vs.css"), filepath.Join(tempOutputPath, "styles", "highlight", "styles", "vs.css")); err != nil {
  371. beego.Error("复制CSS样式出错 => static/highlight/styles/vs.css",err)
  372. }
  373. if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "katex", "katex.min.css"), filepath.Join(tempOutputPath, "styles", "katex", "katex.min.css")); err != nil {
  374. beego.Error("复制CSS样式出错 => static/katex/katex.min.css",err)
  375. }
  376. eBookConverter := &converter.Converter{
  377. BasePath: tempOutputPath,
  378. OutputPath: filepath.Join(strings.TrimSuffix(tempOutputPath, "source"),"output"),
  379. Config: ebookConfig,
  380. Debug: true,
  381. ProcessNum: conf.GetExportProcessNum(),
  382. }
  383. os.MkdirAll(eBookConverter.OutputPath,0766)
  384. if err := eBookConverter.Convert(); err != nil {
  385. beego.Error("转换文件错误:" + m.BookName + " => " + err.Error())
  386. return convertBookResult, err
  387. }
  388. beego.Info("文档转换完成:" + m.BookName)
  389. if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath,"output", "book.mobi"),mobipath,);err != nil {
  390. beego.Error("复制文档失败 => ",filepath.Join(eBookConverter.OutputPath,"output", "book.mobi"),err)
  391. }
  392. if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath,"output", "book.pdf"),pdfpath);err != nil {
  393. beego.Error("复制文档失败 => ",filepath.Join(eBookConverter.OutputPath,"output", "book.pdf"),err)
  394. }
  395. if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath,"output", "book.epub"),epubpath); err != nil{
  396. beego.Error("复制文档失败 => ",filepath.Join(eBookConverter.OutputPath,"output", "book.epub"),err)
  397. }
  398. if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath,"output", "book.docx"),docxpath); err != nil {
  399. beego.Error("复制文档失败 => ",filepath.Join(eBookConverter.OutputPath,"output", "book.docx"),err)
  400. }
  401. convertBookResult.MobiPath = mobipath
  402. convertBookResult.PDFPath = pdfpath
  403. convertBookResult.EpubPath = epubpath
  404. convertBookResult.WordPath = docxpath
  405. return convertBookResult, nil
  406. }
  407. //导出Markdown原始文件
  408. func (m *BookResult) ExportMarkdown(sessionId string) (string, error) {
  409. outputPath := filepath.Join(conf.WorkingDirectory, "uploads", "books", strconv.Itoa(m.BookId), "book.zip")
  410. os.MkdirAll(filepath.Dir(outputPath), 0644)
  411. tempOutputPath := filepath.Join(os.TempDir(), sessionId, "markdown")
  412. defer os.RemoveAll(tempOutputPath)
  413. bookUrl := conf.URLFor("DocumentController.Index",":key" , m.Identify) + "/"
  414. err := exportMarkdown(tempOutputPath, 0, m.BookId,tempOutputPath,bookUrl)
  415. if err != nil {
  416. return "", err
  417. }
  418. if err := ziptil.Compress(outputPath, tempOutputPath); err != nil {
  419. beego.Error("导出Markdown失败=>", err)
  420. return "", err
  421. }
  422. return outputPath, nil
  423. }
  424. //递归导出Markdown文档
  425. func exportMarkdown(p string, parentId int, bookId int,baseDir string,bookUrl string) error {
  426. o := orm.NewOrm()
  427. var docs []*Document
  428. _, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).Filter("parent_id", parentId).All(&docs)
  429. if err != nil {
  430. beego.Error("导出Markdown失败=>", err)
  431. return err
  432. }
  433. for _, doc := range docs {
  434. //获取当前文档的子文档数量,如果数量不为0,则将当前文档命名为READMD.md并设置成目录。
  435. subDocCount, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("parent_id", doc.DocumentId).Count()
  436. if err != nil {
  437. beego.Error("导出Markdown失败=>", err)
  438. return err
  439. }
  440. var docPath string
  441. if subDocCount > 0 {
  442. if doc.Identify != "" {
  443. docPath = filepath.Join(p, doc.Identify, "README.md")
  444. } else {
  445. docPath = filepath.Join(p, strconv.Itoa(doc.DocumentId), "README.md")
  446. }
  447. } else {
  448. if doc.Identify != "" {
  449. if strings.HasSuffix(doc.Identify,".md") || strings.HasSuffix(doc.Identify,".markdown") {
  450. docPath = filepath.Join(p, doc.Identify)
  451. }else {
  452. docPath = filepath.Join(p, doc.Identify+".md")
  453. }
  454. } else {
  455. docPath = filepath.Join(p, strings.TrimSpace(doc.DocumentName)+".md")
  456. }
  457. }
  458. dirPath := filepath.Dir(docPath)
  459. os.MkdirAll(dirPath, 0766)
  460. markdown := doc.Markdown
  461. //如果当前文档不为空
  462. if strings.TrimSpace(doc.Markdown) != "" {
  463. re := regexp.MustCompile(`!\[(.*?)\]\((.*?)\)`)
  464. //处理文档中图片
  465. markdown = re.ReplaceAllStringFunc(doc.Markdown, func(image string) string {
  466. images := re.FindAllSubmatch([]byte(image), -1)
  467. if len(images) <= 0 || len(images[0]) < 3 {
  468. return image
  469. }
  470. originalImageUrl := string(images[0][2])
  471. imageUrl := strings.Replace(string(originalImageUrl), "\\", "/", -1)
  472. //如果是本地路径,则需要将图片复制到项目目录
  473. if strings.HasPrefix(imageUrl, "http://") || strings.HasPrefix(imageUrl, "https://") {
  474. imageExt := cryptil.Md5Crypt(imageUrl) + filepath.Ext(imageUrl)
  475. dstFile := filepath.Join(baseDir, "uploads", time.Now().Format("200601"), imageExt)
  476. if err := requests.DownloadAndSaveFile(imageUrl, dstFile); err == nil {
  477. imageUrl = strings.TrimPrefix(strings.Replace(dstFile, "\\", "/", -1), strings.Replace(baseDir, "\\", "/", -1))
  478. if !strings.HasPrefix(imageUrl, "/") && !strings.HasPrefix(imageUrl, "\\") {
  479. imageUrl = "/" + imageUrl
  480. }
  481. }
  482. } else if strings.HasPrefix(imageUrl, "/") {
  483. filetil.CopyFile(filepath.Join(conf.WorkingDirectory, imageUrl), filepath.Join(baseDir, imageUrl))
  484. }
  485. imageUrl = strings.Replace(strings.TrimSuffix(image, originalImageUrl+")")+imageUrl+")", "\\", "/", -1)
  486. return imageUrl
  487. })
  488. linkRe := regexp.MustCompile(`\[(.*?)\]\((.*?)\)`)
  489. markdown = linkRe.ReplaceAllStringFunc(markdown, func(link string) string {
  490. links := linkRe.FindAllStringSubmatch(link, -1)
  491. if len(links) > 0 && len(links[0]) >= 3 {
  492. originalLink := links[0][2]
  493. //如果当前链接位于当前项目内
  494. if strings.HasPrefix(originalLink,bookUrl) {
  495. docIdentify := strings.TrimSpace(strings.TrimPrefix(originalLink, bookUrl))
  496. tempDoc := NewDocument()
  497. if id,err := strconv.Atoi(docIdentify);err == nil && id > 0 {
  498. err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("document_id",id).One(tempDoc,"identify","parent_id","document_id")
  499. if err != nil {
  500. beego.Error(err)
  501. return link
  502. }
  503. }else{
  504. err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("identify",docIdentify).One(tempDoc,"identify","parent_id","document_id")
  505. if err != nil {
  506. beego.Error(err)
  507. return link
  508. }
  509. }
  510. tempLink := recursiveJoinDocumentIdentify(tempDoc.ParentId,"") + strings.TrimPrefix(originalLink, bookUrl)
  511. if !strings.HasSuffix(tempLink,".md") && !strings.HasSuffix(doc.Identify,".markdown") {
  512. tempLink = tempLink + ".md"
  513. }
  514. relative := strings.TrimPrefix(strings.Replace(p,"\\","/",-1),strings.Replace(baseDir,"\\","/",-1))
  515. repeat := 0
  516. if relative != "" {
  517. relative = strings.TrimSuffix(strings.TrimPrefix(relative,"/"),"/")
  518. repeat = strings.Count(relative,"/") + 1
  519. }
  520. beego.Info(repeat,"|",relative,"|",p,"|",baseDir)
  521. tempLink = strings.Repeat("../",repeat) + tempLink
  522. link = strings.TrimSuffix(link, originalLink+")") + tempLink + ")"
  523. }
  524. }
  525. return link
  526. })
  527. }else{
  528. markdown = "# " + doc.DocumentName + "\n"
  529. }
  530. if err := ioutil.WriteFile(docPath, []byte(markdown), 0644); err != nil {
  531. beego.Error("导出Markdown失败=>", err)
  532. return err
  533. }
  534. if subDocCount > 0 {
  535. if err = exportMarkdown(dirPath, doc.DocumentId, bookId,baseDir,bookUrl); err != nil {
  536. return err
  537. }
  538. }
  539. }
  540. return nil
  541. }
  542. func recursiveJoinDocumentIdentify(parentDocId int,identify string) string {
  543. o := orm.NewOrm()
  544. doc := NewDocument()
  545. err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("document_id",parentDocId).One(doc,"identify","parent_id","document_id")
  546. if err != nil {
  547. beego.Error(err)
  548. return identify
  549. }
  550. if doc.Identify == "" {
  551. identify = strconv.Itoa(doc.DocumentId) + "/" + identify
  552. }else{
  553. identify = doc.Identify + "/" + identify
  554. }
  555. if doc.ParentId > 0 {
  556. identify = recursiveJoinDocumentIdentify(doc.ParentId,identify)
  557. }
  558. return identify
  559. }
  560. //查询项目的第一篇文档
  561. func (m *BookResult) FindFirstDocumentByBookId(bookId int) (*Document, error) {
  562. o := orm.NewOrm()
  563. doc := NewDocument()
  564. err := o.QueryTable(doc.TableNameWithPrefix()).Filter("book_id", bookId).Filter("parent_id", 0).OrderBy("order_sort").One(doc)
  565. return doc, err
  566. }