book_result.go 20 KB

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