book_result.go 20 KB

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