BookResult.go 23 KB

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