BookResult.go 23 KB

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