export.go 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179
  1. // SiYuan - Refactor your thinking
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package model
  17. import (
  18. "bytes"
  19. "errors"
  20. "fmt"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "os/exec"
  25. "path"
  26. "path/filepath"
  27. "sort"
  28. "strconv"
  29. "strings"
  30. "time"
  31. "unicode/utf8"
  32. "github.com/88250/gulu"
  33. "github.com/88250/lute/ast"
  34. "github.com/88250/lute/editor"
  35. "github.com/88250/lute/html"
  36. "github.com/88250/lute/parse"
  37. "github.com/88250/lute/render"
  38. "github.com/88250/pdfcpu/pkg/api"
  39. "github.com/88250/pdfcpu/pkg/pdfcpu"
  40. "github.com/emirpasic/gods/sets/hashset"
  41. "github.com/emirpasic/gods/stacks/linkedliststack"
  42. "github.com/imroc/req/v3"
  43. "github.com/siyuan-note/filelock"
  44. "github.com/siyuan-note/httpclient"
  45. "github.com/siyuan-note/logging"
  46. "github.com/siyuan-note/siyuan/kernel/filesys"
  47. "github.com/siyuan-note/siyuan/kernel/sql"
  48. "github.com/siyuan-note/siyuan/kernel/treenode"
  49. "github.com/siyuan-note/siyuan/kernel/util"
  50. )
  51. func Export2Liandi(id string) (err error) {
  52. tree, err := loadTreeByBlockID(id)
  53. if nil != err {
  54. logging.LogErrorf("load tree by block id [%s] failed: %s", id, err)
  55. return
  56. }
  57. if IsUserGuide(tree.Box) {
  58. // Doc in the user guide no longer supports one-click sending to the community https://github.com/siyuan-note/siyuan/issues/8388
  59. return errors.New(Conf.Language(204))
  60. }
  61. sqlAssets := sql.QueryRootBlockAssets(id)
  62. err = uploadAssets2Cloud(sqlAssets, bizTypeExport2Liandi)
  63. if nil != err {
  64. return
  65. }
  66. msgId := util.PushMsg(Conf.Language(182), 15000)
  67. defer util.PushClearMsg(msgId)
  68. // 判断帖子是否已经存在,存在则使用更新接口
  69. const liandiArticleIdAttrName = "custom-liandi-articleId"
  70. foundArticle := false
  71. articleId := tree.Root.IALAttr(liandiArticleIdAttrName)
  72. if "" != articleId {
  73. result := gulu.Ret.NewResult()
  74. request := httpclient.NewCloudRequest30s()
  75. resp, getErr := request.
  76. SetSuccessResult(result).
  77. SetCookies(&http.Cookie{Name: "symphony", Value: Conf.User.UserToken}).
  78. Get(util.GetCloudAccountServer() + "/api/v2/article/update/" + articleId)
  79. if nil != getErr {
  80. logging.LogErrorf("get liandi article info failed: %s", getErr)
  81. return getErr
  82. }
  83. switch resp.StatusCode {
  84. case 200:
  85. if 0 == result.Code {
  86. foundArticle = true
  87. } else if 1 == result.Code {
  88. foundArticle = false
  89. }
  90. case 404:
  91. foundArticle = false
  92. default:
  93. msg := fmt.Sprintf("get liandi article info failed [sc=%d]", resp.StatusCode)
  94. err = errors.New(msg)
  95. return
  96. }
  97. }
  98. apiURL := util.GetCloudAccountServer() + "/api/v2/article"
  99. if foundArticle {
  100. apiURL += "/" + articleId
  101. }
  102. title := path.Base(tree.HPath)
  103. tags := tree.Root.IALAttr("tags")
  104. content := exportMarkdownContent0(tree, util.GetCloudForumAssetsServer()+time.Now().Format("2006/01")+"/siyuan/"+Conf.User.UserId+"/", true,
  105. 4, 1, 0,
  106. "#", "#",
  107. "", "",
  108. false)
  109. result := gulu.Ret.NewResult()
  110. request := httpclient.NewCloudRequest30s()
  111. request = request.
  112. SetSuccessResult(result).
  113. SetCookies(&http.Cookie{Name: "symphony", Value: Conf.User.UserToken}).
  114. SetBody(map[string]interface{}{
  115. "articleTitle": title,
  116. "articleTags": tags,
  117. "articleContent": content})
  118. var resp *req.Response
  119. var sendErr error
  120. if foundArticle {
  121. resp, sendErr = request.Put(apiURL)
  122. } else {
  123. resp, sendErr = request.Post(apiURL)
  124. }
  125. if nil != sendErr {
  126. logging.LogErrorf("send article to liandi failed: %s", err)
  127. return err
  128. }
  129. if 200 != resp.StatusCode {
  130. msg := fmt.Sprintf("send article to liandi failed [sc=%d]", resp.StatusCode)
  131. logging.LogErrorf(msg)
  132. return errors.New(msg)
  133. }
  134. if 0 != result.Code {
  135. msg := fmt.Sprintf("send article to liandi failed [code=%d, msg=%s]", result.Code, result.Msg)
  136. logging.LogErrorf(msg)
  137. util.PushClearMsg(msgId)
  138. return errors.New(result.Msg)
  139. }
  140. if !foundArticle {
  141. articleId = result.Data.(string)
  142. tree, _ = loadTreeByBlockID(id) // 这里必须重新加载,因为前面导出时已经修改了树结构
  143. tree.Root.SetIALAttr(liandiArticleIdAttrName, articleId)
  144. if err = writeJSONQueue(tree); nil != err {
  145. return
  146. }
  147. }
  148. msg := fmt.Sprintf(Conf.Language(181), util.GetCloudAccountServer()+"/article/"+articleId)
  149. util.PushMsg(msg, 7000)
  150. return
  151. }
  152. func ExportSystemLog() (zipPath string) {
  153. exportFolder := filepath.Join(util.TempDir, "export", "system-log")
  154. os.RemoveAll(exportFolder)
  155. if err := os.MkdirAll(exportFolder, 0755); nil != err {
  156. logging.LogErrorf("create export temp folder failed: %s", err)
  157. return
  158. }
  159. appLog := filepath.Join(util.HomeDir, ".config", "siyuan", "app.log")
  160. if gulu.File.IsExist(appLog) {
  161. to := filepath.Join(exportFolder, "app.log")
  162. if err := filelock.Copy(appLog, to); nil != err {
  163. logging.LogErrorf("copy app log from [%s] to [%s] failed: %s", err, appLog, to)
  164. }
  165. }
  166. kernelLog := filepath.Join(util.HomeDir, ".config", "siyuan", "kernel.log")
  167. if gulu.File.IsExist(kernelLog) {
  168. to := filepath.Join(exportFolder, "kernel.log")
  169. if err := filelock.Copy(kernelLog, to); nil != err {
  170. logging.LogErrorf("copy kernel log from [%s] to [%s] failed: %s", err, kernelLog, to)
  171. }
  172. }
  173. siyuanLog := filepath.Join(util.TempDir, "siyuan.log")
  174. if gulu.File.IsExist(siyuanLog) {
  175. to := filepath.Join(exportFolder, "siyuan.log")
  176. if err := filelock.Copy(siyuanLog, to); nil != err {
  177. logging.LogErrorf("copy kernel log from [%s] to [%s] failed: %s", err, siyuanLog, to)
  178. }
  179. }
  180. zipPath = exportFolder + ".zip"
  181. zip, err := gulu.Zip.Create(zipPath)
  182. if nil != err {
  183. logging.LogErrorf("create export log zip [%s] failed: %s", exportFolder, err)
  184. return ""
  185. }
  186. if err = zip.AddDirectory("log", exportFolder); nil != err {
  187. logging.LogErrorf("create export log zip [%s] failed: %s", exportFolder, err)
  188. return ""
  189. }
  190. if err = zip.Close(); nil != err {
  191. logging.LogErrorf("close export log zip failed: %s", err)
  192. }
  193. os.RemoveAll(exportFolder)
  194. zipPath = "/export/" + url.PathEscape(filepath.Base(zipPath))
  195. return
  196. }
  197. func ExportNotebookSY(id string) (zipPath string) {
  198. zipPath = exportBoxSYZip(id)
  199. return
  200. }
  201. func ExportSY(id string) (name, zipPath string) {
  202. block := treenode.GetBlockTree(id)
  203. if nil == block {
  204. logging.LogErrorf("not found block [%s]", id)
  205. return
  206. }
  207. boxID := block.BoxID
  208. box := Conf.Box(boxID)
  209. baseFolderName := path.Base(block.HPath)
  210. if "." == baseFolderName {
  211. baseFolderName = path.Base(block.Path)
  212. }
  213. rootPath := block.Path
  214. docPaths := []string{rootPath}
  215. docFiles := box.ListFiles(strings.TrimSuffix(block.Path, ".sy"))
  216. for _, docFile := range docFiles {
  217. docPaths = append(docPaths, docFile.path)
  218. }
  219. zipPath = exportSYZip(boxID, path.Dir(rootPath), baseFolderName, docPaths)
  220. name = strings.TrimSuffix(filepath.Base(block.Path), ".sy")
  221. return
  222. }
  223. func ExportDataInFolder(exportFolder string) (name string, err error) {
  224. util.PushEndlessProgress(Conf.Language(65))
  225. defer util.ClearPushProgress(100)
  226. zipPath, err := ExportData()
  227. if nil != err {
  228. return
  229. }
  230. name = filepath.Base(zipPath)
  231. name, err = url.PathUnescape(name)
  232. if nil != err {
  233. logging.LogErrorf("url unescape [%s] failed: %s", name, err)
  234. return
  235. }
  236. targetZipPath := filepath.Join(exportFolder, name)
  237. zipAbsPath := filepath.Join(util.TempDir, "export", name)
  238. err = filelock.Copy(zipAbsPath, targetZipPath)
  239. if nil != err {
  240. logging.LogErrorf("copy export zip from [%s] to [%s] failed: %s", zipAbsPath, targetZipPath, err)
  241. return
  242. }
  243. if removeErr := os.Remove(zipAbsPath); nil != removeErr {
  244. logging.LogErrorf("remove export zip failed: %s", removeErr)
  245. }
  246. return
  247. }
  248. func ExportData() (zipPath string, err error) {
  249. util.PushEndlessProgress(Conf.Language(65))
  250. defer util.ClearPushProgress(100)
  251. name := util.FilterFileName(filepath.Base(util.WorkspaceDir)) + "-" + util.CurrentTimeSecondsStr()
  252. exportFolder := filepath.Join(util.TempDir, "export", name)
  253. zipPath, err = exportData(exportFolder)
  254. if nil != err {
  255. return
  256. }
  257. zipPath = "/export/" + url.PathEscape(filepath.Base(zipPath))
  258. return
  259. }
  260. func exportData(exportFolder string) (zipPath string, err error) {
  261. WaitForWritingFiles()
  262. baseFolderName := "data-" + util.CurrentTimeSecondsStr()
  263. if err = os.MkdirAll(exportFolder, 0755); nil != err {
  264. logging.LogErrorf("create export temp folder failed: %s", err)
  265. return
  266. }
  267. data := filepath.Join(util.WorkspaceDir, "data")
  268. if err = filelock.Copy(data, exportFolder); nil != err {
  269. logging.LogErrorf("copy data dir from [%s] to [%s] failed: %s", data, baseFolderName, err)
  270. err = errors.New(fmt.Sprintf(Conf.Language(14), err.Error()))
  271. return
  272. }
  273. zipPath = exportFolder + ".zip"
  274. zip, err := gulu.Zip.Create(zipPath)
  275. if nil != err {
  276. logging.LogErrorf("create export data zip [%s] failed: %s", exportFolder, err)
  277. return
  278. }
  279. if err = zip.AddDirectory(baseFolderName, exportFolder); nil != err {
  280. logging.LogErrorf("create export data zip [%s] failed: %s", exportFolder, err)
  281. return
  282. }
  283. if err = zip.Close(); nil != err {
  284. logging.LogErrorf("close export data zip failed: %s", err)
  285. }
  286. os.RemoveAll(exportFolder)
  287. return
  288. }
  289. func ExportResources(resourcePaths []string, mainName string) (exportFilePath string, err error) {
  290. WaitForWritingFiles()
  291. // 用于导出的临时文件夹完整路径
  292. exportFolderPath := filepath.Join(util.TempDir, "export", mainName)
  293. if err = os.MkdirAll(exportFolderPath, 0755); nil != err {
  294. logging.LogErrorf("create export temp folder failed: %s", err)
  295. return
  296. }
  297. // 将需要导出的文件/文件夹复制到临时文件夹
  298. for _, resourcePath := range resourcePaths {
  299. resourceFullPath := filepath.Join(util.WorkspaceDir, resourcePath) // 资源完整路径
  300. resourceBaseName := filepath.Base(resourceFullPath) // 资源名称
  301. resourceCopyPath := filepath.Join(exportFolderPath, resourceBaseName) // 资源副本完整路径
  302. if err = filelock.Copy(resourceFullPath, resourceCopyPath); nil != err {
  303. logging.LogErrorf("copy resource will be exported from [%s] to [%s] failed: %s", resourcePath, resourceCopyPath, err)
  304. err = fmt.Errorf(Conf.Language(14), err.Error())
  305. return
  306. }
  307. }
  308. zipFilePath := exportFolderPath + ".zip" // 导出的 *.zip 文件完整路径
  309. zip, err := gulu.Zip.Create(zipFilePath)
  310. if nil != err {
  311. logging.LogErrorf("create export zip [%s] failed: %s", zipFilePath, err)
  312. return
  313. }
  314. if err = zip.AddDirectory(mainName, exportFolderPath); nil != err {
  315. logging.LogErrorf("create export zip [%s] failed: %s", exportFolderPath, err)
  316. return
  317. }
  318. if err = zip.Close(); nil != err {
  319. logging.LogErrorf("close export zip failed: %s", err)
  320. }
  321. os.RemoveAll(exportFolderPath)
  322. exportFilePath = path.Join("temp", "export", mainName+".zip") // 导出的 *.zip 文件相对于工作区目录的路径
  323. return
  324. }
  325. func Preview(id string) (retStdHTML string, retOutline []*Path) {
  326. tree, _ := loadTreeByBlockID(id)
  327. tree = exportTree(tree, false, false, false,
  328. Conf.Export.BlockRefMode, Conf.Export.BlockEmbedMode, Conf.Export.FileAnnotationRefMode,
  329. Conf.Export.TagOpenMarker, Conf.Export.TagCloseMarker,
  330. Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight,
  331. Conf.Export.AddTitle)
  332. luteEngine := NewLute()
  333. luteEngine.SetFootnotes(true)
  334. md := treenode.FormatNode(tree.Root, luteEngine)
  335. tree = parse.Parse("", []byte(md), luteEngine.ParseOptions)
  336. retStdHTML = luteEngine.ProtylePreview(tree, luteEngine.RenderOptions)
  337. if footnotesDefBlock := tree.Root.ChildByType(ast.NodeFootnotesDefBlock); nil != footnotesDefBlock {
  338. footnotesDefBlock.Unlink()
  339. }
  340. retOutline = outline(tree)
  341. return
  342. }
  343. func ExportDocx(id, savePath string, removeAssets, merge bool) (err error) {
  344. if !util.IsValidPandocBin(Conf.Export.PandocBin) {
  345. Conf.Export.PandocBin = util.PandocBinPath
  346. Conf.Save()
  347. if !util.IsValidPandocBin(Conf.Export.PandocBin) {
  348. return errors.New(Conf.Language(115))
  349. }
  350. }
  351. tmpDir := filepath.Join(util.TempDir, "export", gulu.Rand.String(7))
  352. if err = os.MkdirAll(tmpDir, 0755); nil != err {
  353. return
  354. }
  355. defer os.Remove(tmpDir)
  356. name, content := ExportMarkdownHTML(id, tmpDir, true, merge)
  357. tmpDocxPath := filepath.Join(tmpDir, name+".docx")
  358. args := []string{ // pandoc -f html --resource-path=请从这里开始 请从这里开始\index.html -o test.docx
  359. "-f", "html+tex_math_dollars",
  360. "--resource-path", tmpDir,
  361. "-o", tmpDocxPath,
  362. }
  363. pandoc := exec.Command(Conf.Export.PandocBin, args...)
  364. gulu.CmdAttr(pandoc)
  365. pandoc.Stdin = bytes.NewBufferString(content)
  366. output, err := pandoc.CombinedOutput()
  367. if nil != err {
  368. logging.LogErrorf("export docx failed: %s", gulu.Str.FromBytes(output))
  369. msg := fmt.Sprintf(Conf.Language(14), gulu.Str.FromBytes(output))
  370. return errors.New(msg)
  371. }
  372. targetPath := filepath.Join(savePath, name+".docx")
  373. if gulu.File.IsExist(targetPath) {
  374. // 先删除目标文件,以检查是否被占用 https://github.com/siyuan-note/siyuan/issues/8822
  375. if err := os.RemoveAll(targetPath); nil != err {
  376. logging.LogErrorf("export docx failed: %s", err)
  377. msg := fmt.Sprintf(Conf.language(215))
  378. return errors.New(msg)
  379. }
  380. }
  381. if err = filelock.Copy(tmpDocxPath, targetPath); nil != err {
  382. logging.LogErrorf("export docx failed: %s", err)
  383. return errors.New(fmt.Sprintf(Conf.Language(14), err))
  384. }
  385. if tmpAssets := filepath.Join(tmpDir, "assets"); !removeAssets && gulu.File.IsDir(tmpAssets) {
  386. if err = filelock.Copy(tmpAssets, filepath.Join(savePath, "assets")); nil != err {
  387. logging.LogErrorf("export docx failed: %s", err)
  388. return errors.New(fmt.Sprintf(Conf.Language(14), err))
  389. }
  390. }
  391. return
  392. }
  393. func ExportMarkdownHTML(id, savePath string, docx, merge bool) (name, dom string) {
  394. bt := treenode.GetBlockTree(id)
  395. if nil == bt {
  396. return
  397. }
  398. tree := prepareExportTree(bt)
  399. if merge {
  400. var mergeErr error
  401. tree, mergeErr = mergeSubDocs(tree)
  402. if nil != mergeErr {
  403. logging.LogErrorf("merge sub docs failed: %s", mergeErr)
  404. return
  405. }
  406. }
  407. tree = exportTree(tree, true, true, false,
  408. Conf.Export.BlockRefMode, Conf.Export.BlockEmbedMode, Conf.Export.FileAnnotationRefMode,
  409. Conf.Export.TagOpenMarker, Conf.Export.TagCloseMarker,
  410. Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight,
  411. Conf.Export.AddTitle)
  412. name = path.Base(tree.HPath)
  413. name = util.FilterFileName(name) // 导出 PDF、HTML 和 Word 时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/5614
  414. savePath = strings.TrimSpace(savePath)
  415. if err := os.MkdirAll(savePath, 0755); nil != err {
  416. logging.LogErrorf("mkdir [%s] failed: %s", savePath, err)
  417. return
  418. }
  419. assets := assetsLinkDestsInTree(tree)
  420. for _, asset := range assets {
  421. if strings.HasPrefix(asset, "assets/") {
  422. if strings.Contains(asset, "?") {
  423. asset = asset[:strings.LastIndex(asset, "?")]
  424. }
  425. srcAbsPath, err := GetAssetAbsPath(asset)
  426. if nil != err {
  427. logging.LogWarnf("resolve path of asset [%s] failed: %s", asset, err)
  428. continue
  429. }
  430. targetAbsPath := filepath.Join(savePath, asset)
  431. if err = filelock.Copy(srcAbsPath, targetAbsPath); nil != err {
  432. logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, err)
  433. }
  434. }
  435. }
  436. srcs := []string{"stage/build/export", "stage/build/fonts", "stage/protyle"}
  437. for _, src := range srcs {
  438. from := filepath.Join(util.WorkingDir, src)
  439. to := filepath.Join(savePath, src)
  440. if err := filelock.Copy(from, to); nil != err {
  441. logging.LogWarnf("copy stage from [%s] to [%s] failed: %s", from, savePath, err)
  442. return
  443. }
  444. }
  445. theme := Conf.Appearance.ThemeLight
  446. if 1 == Conf.Appearance.Mode {
  447. theme = Conf.Appearance.ThemeDark
  448. }
  449. srcs = []string{"icons", "themes/" + theme}
  450. for _, src := range srcs {
  451. from := filepath.Join(util.AppearancePath, src)
  452. to := filepath.Join(savePath, "appearance", src)
  453. if err := filelock.Copy(from, to); nil != err {
  454. logging.LogErrorf("copy appearance from [%s] to [%s] failed: %s", from, savePath, err)
  455. return
  456. }
  457. }
  458. // 复制自定义表情图片
  459. emojis := emojisInTree(tree)
  460. for _, emoji := range emojis {
  461. from := filepath.Join(util.DataDir, emoji)
  462. to := filepath.Join(savePath, emoji)
  463. if err := filelock.Copy(from, to); nil != err {
  464. logging.LogErrorf("copy emojis from [%s] to [%s] failed: %s", from, savePath, err)
  465. return
  466. }
  467. }
  468. luteEngine := NewLute()
  469. luteEngine.SetFootnotes(true)
  470. md := treenode.FormatNode(tree.Root, luteEngine)
  471. tree = parse.Parse("", []byte(md), luteEngine.ParseOptions)
  472. if docx {
  473. processIFrame(tree)
  474. }
  475. // 自定义表情图片地址去掉开头的 /
  476. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  477. if !entering {
  478. return ast.WalkContinue
  479. }
  480. if ast.NodeEmojiImg == n.Type {
  481. n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("src=\"/emojis"), []byte("src=\"emojis"))
  482. }
  483. return ast.WalkContinue
  484. })
  485. if docx {
  486. renderer := render.NewProtyleExportDocxRenderer(tree, luteEngine.RenderOptions)
  487. output := renderer.Render()
  488. dom = gulu.Str.FromBytes(output)
  489. } else {
  490. dom = luteEngine.ProtylePreview(tree, luteEngine.RenderOptions)
  491. }
  492. return
  493. }
  494. func ExportHTML(id, savePath string, pdf, image, keepFold, merge bool) (name, dom string) {
  495. savePath = strings.TrimSpace(savePath)
  496. bt := treenode.GetBlockTree(id)
  497. if nil == bt {
  498. return
  499. }
  500. tree := prepareExportTree(bt)
  501. if merge {
  502. var mergeErr error
  503. tree, mergeErr = mergeSubDocs(tree)
  504. if nil != mergeErr {
  505. logging.LogErrorf("merge sub docs failed: %s", mergeErr)
  506. return
  507. }
  508. }
  509. var headings []*ast.Node
  510. if pdf { // 导出 PDF 需要标记目录书签
  511. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  512. if entering && ast.NodeHeading == n.Type && !n.ParentIs(ast.NodeBlockquote) {
  513. headings = append(headings, n)
  514. return ast.WalkSkipChildren
  515. }
  516. return ast.WalkContinue
  517. })
  518. for _, h := range headings {
  519. link := &ast.Node{Type: ast.NodeLink}
  520. link.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  521. link.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(" ")})
  522. link.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  523. link.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  524. link.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte("pdf-outline://" + h.ID)})
  525. link.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  526. h.PrependChild(link)
  527. }
  528. }
  529. tree = exportTree(tree, true, true, keepFold,
  530. Conf.Export.BlockRefMode, Conf.Export.BlockEmbedMode, Conf.Export.FileAnnotationRefMode,
  531. Conf.Export.TagOpenMarker, Conf.Export.TagCloseMarker,
  532. Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight,
  533. Conf.Export.AddTitle)
  534. name = path.Base(tree.HPath)
  535. name = util.FilterFileName(name) // 导出 PDF、HTML 和 Word 时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/5614
  536. if "" != savePath {
  537. if err := os.MkdirAll(savePath, 0755); nil != err {
  538. logging.LogErrorf("mkdir [%s] failed: %s", savePath, err)
  539. return
  540. }
  541. assets := assetsLinkDestsInTree(tree)
  542. for _, asset := range assets {
  543. if strings.Contains(asset, "?") {
  544. asset = asset[:strings.LastIndex(asset, "?")]
  545. }
  546. srcAbsPath, err := GetAssetAbsPath(asset)
  547. if nil != err {
  548. logging.LogWarnf("resolve path of asset [%s] failed: %s", asset, err)
  549. continue
  550. }
  551. targetAbsPath := filepath.Join(savePath, asset)
  552. if err = filelock.Copy(srcAbsPath, targetAbsPath); nil != err {
  553. logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, err)
  554. }
  555. }
  556. }
  557. luteEngine := NewLute()
  558. if !pdf && "" != savePath { // 导出 HTML 需要复制静态资源
  559. srcs := []string{"stage/build/export", "stage/build/fonts", "stage/protyle"}
  560. for _, src := range srcs {
  561. from := filepath.Join(util.WorkingDir, src)
  562. to := filepath.Join(savePath, src)
  563. if err := filelock.Copy(from, to); nil != err {
  564. logging.LogErrorf("copy stage from [%s] to [%s] failed: %s", from, savePath, err)
  565. return
  566. }
  567. }
  568. theme := Conf.Appearance.ThemeLight
  569. if 1 == Conf.Appearance.Mode {
  570. theme = Conf.Appearance.ThemeDark
  571. }
  572. srcs = []string{"icons", "themes/" + theme}
  573. for _, src := range srcs {
  574. from := filepath.Join(util.AppearancePath, src)
  575. to := filepath.Join(savePath, "appearance", src)
  576. if err := filelock.Copy(from, to); nil != err {
  577. logging.LogErrorf("copy appearance from [%s] to [%s] failed: %s", from, savePath, err)
  578. return
  579. }
  580. }
  581. // 复制自定义表情图片
  582. emojis := emojisInTree(tree)
  583. for _, emoji := range emojis {
  584. from := filepath.Join(util.DataDir, emoji)
  585. to := filepath.Join(savePath, emoji)
  586. if err := filelock.Copy(from, to); nil != err {
  587. logging.LogErrorf("copy emojis from [%s] to [%s] failed: %s", from, savePath, err)
  588. return
  589. }
  590. }
  591. }
  592. if pdf {
  593. processIFrame(tree)
  594. }
  595. luteEngine.SetFootnotes(true)
  596. luteEngine.RenderOptions.ProtyleContenteditable = false
  597. luteEngine.SetProtyleMarkNetImg(false)
  598. // 不进行安全过滤,因为导出时需要保留所有的 HTML 标签
  599. // 使用属性 `data-export-html` 导出时 `<style></style>` 标签丢失 https://github.com/siyuan-note/siyuan/issues/6228
  600. luteEngine.SetSanitize(false)
  601. renderer := render.NewProtyleExportRenderer(tree, luteEngine.RenderOptions)
  602. dom = gulu.Str.FromBytes(renderer.Render())
  603. return
  604. }
  605. func prepareExportTree(bt *treenode.BlockTree) (ret *parse.Tree) {
  606. luteEngine := NewLute()
  607. ret, _ = filesys.LoadTree(bt.BoxID, bt.Path, luteEngine)
  608. if "d" != bt.Type {
  609. node := treenode.GetNodeInTree(ret, bt.ID)
  610. nodes := []*ast.Node{node}
  611. if "h" == bt.Type {
  612. children := treenode.HeadingChildren(node)
  613. for _, child := range children {
  614. nodes = append(nodes, child)
  615. }
  616. }
  617. ret = parse.Parse("", []byte(""), luteEngine.ParseOptions)
  618. first := ret.Root.FirstChild
  619. for _, node := range nodes {
  620. first.InsertBefore(node)
  621. }
  622. }
  623. ret.Path = bt.Path
  624. ret.HPath = bt.HPath
  625. ret.Box = bt.BoxID
  626. ret.ID = bt.RootID
  627. return
  628. }
  629. func processIFrame(tree *parse.Tree) {
  630. // 导出 PDF/Word 时 IFrame 块使用超链接 https://github.com/siyuan-note/siyuan/issues/4035
  631. var unlinks []*ast.Node
  632. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  633. if !entering {
  634. return ast.WalkContinue
  635. }
  636. if ast.NodeIFrame == n.Type {
  637. index := bytes.Index(n.Tokens, []byte("src=\""))
  638. if 0 > index {
  639. n.InsertBefore(&ast.Node{Type: ast.NodeText, Tokens: n.Tokens})
  640. } else {
  641. src := n.Tokens[index+len("src=\""):]
  642. src = src[:bytes.Index(src, []byte("\""))]
  643. src = html.UnescapeHTML(src)
  644. link := &ast.Node{Type: ast.NodeLink}
  645. link.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  646. link.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: src})
  647. link.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  648. link.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  649. link.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: src})
  650. link.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  651. n.InsertBefore(link)
  652. }
  653. unlinks = append(unlinks, n)
  654. }
  655. return ast.WalkContinue
  656. })
  657. for _, n := range unlinks {
  658. n.Unlink()
  659. }
  660. }
  661. func ProcessPDF(id, p string, merge, removeAssets bool) (err error) {
  662. tree, _ := loadTreeByBlockID(id)
  663. if nil == tree {
  664. return
  665. }
  666. if merge {
  667. var mergeErr error
  668. tree, mergeErr = mergeSubDocs(tree)
  669. if nil != mergeErr {
  670. logging.LogErrorf("merge sub docs failed: %s", mergeErr)
  671. return
  672. }
  673. }
  674. var headings []*ast.Node
  675. assetDests := assetsLinkDestsInTree(tree)
  676. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  677. if !entering {
  678. return ast.WalkContinue
  679. }
  680. if ast.NodeHeading == n.Type && !n.ParentIs(ast.NodeBlockquote) {
  681. headings = append(headings, n)
  682. return ast.WalkSkipChildren
  683. }
  684. return ast.WalkContinue
  685. })
  686. pdfCtx, ctxErr := api.ReadContextFile(p)
  687. if nil != ctxErr {
  688. logging.LogErrorf("read pdf context failed: %s", ctxErr)
  689. return
  690. }
  691. processPDFBookmarks(pdfCtx, headings)
  692. processPDFLinkEmbedAssets(pdfCtx, assetDests, removeAssets)
  693. pdfcpu.VersionStr = "SiYuan v" + util.Ver
  694. if writeErr := api.WriteContextFile(pdfCtx, p); nil != writeErr {
  695. logging.LogErrorf("write pdf context failed: %s", writeErr)
  696. return
  697. }
  698. return
  699. }
  700. func processPDFBookmarks(pdfCtx *pdfcpu.Context, headings []*ast.Node) {
  701. links, err := api.ListToCLinks(pdfCtx)
  702. if nil != err {
  703. return
  704. }
  705. sort.Slice(links, func(i, j int) bool {
  706. return links[i].Page < links[j].Page
  707. })
  708. bms := map[string]*pdfcpu.Bookmark{}
  709. for _, link := range links {
  710. linkID := link.URI[strings.LastIndex(link.URI, "/")+1:]
  711. b := sql.GetBlock(linkID)
  712. if nil == b {
  713. logging.LogWarnf("pdf outline block [%s] not found", linkID)
  714. continue
  715. }
  716. title := b.Content
  717. title, _ = url.QueryUnescape(title)
  718. bm := &pdfcpu.Bookmark{
  719. Title: title,
  720. PageFrom: link.Page,
  721. AbsPos: link.Rect.UR.Y,
  722. }
  723. bms[linkID] = bm
  724. }
  725. if 1 > len(bms) {
  726. return
  727. }
  728. var topBms []*pdfcpu.Bookmark
  729. stack := linkedliststack.New()
  730. for _, h := range headings {
  731. L:
  732. for ; ; stack.Pop() {
  733. cur, ok := stack.Peek()
  734. if !ok {
  735. bm := bms[h.ID]
  736. if nil == bm {
  737. break L
  738. }
  739. bm.Level = h.HeadingLevel
  740. stack.Push(bm)
  741. topBms = append(topBms, bm)
  742. break L
  743. }
  744. tip := cur.(*pdfcpu.Bookmark)
  745. if tip.Level < h.HeadingLevel {
  746. bm := bms[h.ID]
  747. bm.Level = h.HeadingLevel
  748. bm.Parent = tip
  749. tip.Children = append(tip.Children, bm)
  750. stack.Push(bm)
  751. break L
  752. }
  753. }
  754. }
  755. err = pdfCtx.AddBookmarks(topBms)
  756. if nil != err {
  757. logging.LogErrorf("add bookmark failed: %s", err)
  758. return
  759. }
  760. }
  761. // processPDFLinkEmbedAssets 处理资源文件超链接,根据 removeAssets 参数决定是否将资源文件嵌入到 PDF 中。
  762. // 导出 PDF 时支持将资源文件作为附件嵌入 https://github.com/siyuan-note/siyuan/issues/7414
  763. func processPDFLinkEmbedAssets(pdfCtx *pdfcpu.Context, assetDests []string, removeAssets bool) {
  764. var assetAbsPaths []string
  765. for _, dest := range assetDests {
  766. if absPath, _ := GetAssetAbsPath(dest); "" != absPath {
  767. assetAbsPaths = append(assetAbsPaths, absPath)
  768. }
  769. }
  770. if 1 > len(assetAbsPaths) {
  771. return
  772. }
  773. assetLinks, otherLinks, listErr := api.ListLinks(pdfCtx)
  774. if nil != listErr {
  775. logging.LogErrorf("list asset links failed: %s", listErr)
  776. return
  777. }
  778. if _, removeErr := pdfCtx.RemoveAnnotations(nil, nil, nil, false); nil != removeErr {
  779. logging.LogWarnf("remove annotations failed: %s", removeErr)
  780. }
  781. linkMap := map[int][]pdfcpu.AnnotationRenderer{}
  782. for _, link := range otherLinks {
  783. link.URI, _ = url.PathUnescape(link.URI)
  784. if 1 > len(linkMap[link.Page]) {
  785. linkMap[link.Page] = []pdfcpu.AnnotationRenderer{link}
  786. } else {
  787. linkMap[link.Page] = append(linkMap[link.Page], link)
  788. }
  789. }
  790. attachmentMap := map[int][]*pdfcpu.IndirectRef{}
  791. now := pdfcpu.StringLiteral(pdfcpu.DateString(time.Now()))
  792. for _, link := range assetLinks {
  793. link.URI = strings.ReplaceAll(link.URI, "http://"+util.LocalHost+":"+util.ServerPort+"/export/temp/", "")
  794. link.URI, _ = url.PathUnescape(link.URI)
  795. if idx := strings.Index(link.URI, "?"); 0 < idx {
  796. link.URI = link.URI[:idx]
  797. }
  798. if !removeAssets {
  799. // 不移除资源文件夹的话将超链接指向资源文件夹
  800. if 1 > len(linkMap[link.Page]) {
  801. linkMap[link.Page] = []pdfcpu.AnnotationRenderer{link}
  802. } else {
  803. linkMap[link.Page] = append(linkMap[link.Page], link)
  804. }
  805. continue
  806. }
  807. // 移除资源文件夹的话使用内嵌附件
  808. absPath, getErr := GetAssetAbsPath(link.URI)
  809. if nil != getErr {
  810. continue
  811. }
  812. ir, newErr := pdfCtx.XRefTable.NewEmbeddedFileStreamDict(absPath)
  813. if nil != newErr {
  814. logging.LogWarnf("new embedded file stream dict failed: %s", newErr)
  815. continue
  816. }
  817. fn := filepath.Base(absPath)
  818. fileSpecDict, newErr := pdfCtx.XRefTable.NewFileSpecDict(fn, pdfcpu.EncodeUTF16String(fn), "attached by SiYuan", *ir)
  819. if nil != newErr {
  820. logging.LogWarnf("new file spec dict failed: %s", newErr)
  821. continue
  822. }
  823. ir, indErr := pdfCtx.XRefTable.IndRefForNewObject(fileSpecDict)
  824. if nil != indErr {
  825. logging.LogWarnf("ind ref for new object failed: %s", indErr)
  826. continue
  827. }
  828. lx := link.Rect.LL.X + link.Rect.Width()
  829. ly := link.Rect.LL.Y + link.Rect.Height()/2
  830. ux := lx + link.Rect.Height()/2
  831. uy := ly + link.Rect.Height()/2
  832. d := pdfcpu.Dict(
  833. map[string]pdfcpu.Object{
  834. "Type": pdfcpu.Name("Annot"),
  835. "Subtype": pdfcpu.Name("FileAttachment"),
  836. "Contents": pdfcpu.StringLiteral(""),
  837. "Rect": pdfcpu.Rect(lx, ly, ux, uy).Array(),
  838. "P": link.P,
  839. "M": now,
  840. "F": pdfcpu.Integer(0),
  841. "Border": pdfcpu.NewIntegerArray(0, 0, 1),
  842. "C": pdfcpu.NewNumberArray(0.5, 0.0, 0.5),
  843. "CA": pdfcpu.Float(0.95),
  844. "CreationDate": now,
  845. "Name": pdfcpu.Name("FileAttachment"),
  846. "FS": *ir,
  847. "NM": pdfcpu.StringLiteral(""),
  848. },
  849. )
  850. ann, indErr := pdfCtx.XRefTable.IndRefForNewObject(d)
  851. if nil != indErr {
  852. logging.LogWarnf("ind ref for new object failed: %s", indErr)
  853. continue
  854. }
  855. pageDictIndRef, pageErr := pdfCtx.PageDictIndRef(link.Page)
  856. if nil != pageErr {
  857. logging.LogWarnf("page dict ind ref failed: %s", pageErr)
  858. continue
  859. }
  860. d, defErr := pdfCtx.DereferenceDict(*pageDictIndRef)
  861. if nil != defErr {
  862. logging.LogWarnf("dereference dict failed: %s", defErr)
  863. continue
  864. }
  865. if 1 > len(attachmentMap[link.Page]) {
  866. attachmentMap[link.Page] = []*pdfcpu.IndirectRef{ann}
  867. } else {
  868. attachmentMap[link.Page] = append(attachmentMap[link.Page], ann)
  869. }
  870. }
  871. if 0 < len(linkMap) {
  872. if _, addErr := pdfCtx.AddAnnotationsMap(linkMap, false); nil != addErr {
  873. logging.LogErrorf("add annotations map failed: %s", addErr)
  874. }
  875. }
  876. // 添加附件注解指向内嵌的附件
  877. for page, anns := range attachmentMap {
  878. pageDictIndRef, pageErr := pdfCtx.PageDictIndRef(page)
  879. if nil != pageErr {
  880. logging.LogWarnf("page dict ind ref failed: %s", pageErr)
  881. continue
  882. }
  883. pageDict, defErr := pdfCtx.DereferenceDict(*pageDictIndRef)
  884. if nil != defErr {
  885. logging.LogWarnf("dereference dict failed: %s", defErr)
  886. continue
  887. }
  888. array := pdfcpu.Array{}
  889. for _, ann := range anns {
  890. array = append(array, *ann)
  891. }
  892. obj, found := pageDict.Find("Annots")
  893. if !found {
  894. pageDict.Insert("Annots", array)
  895. pdfCtx.EnsureVersionForWriting()
  896. continue
  897. }
  898. ir, ok := obj.(pdfcpu.IndirectRef)
  899. if !ok {
  900. pageDict.Update("Annots", append(obj.(pdfcpu.Array), array...))
  901. pdfCtx.EnsureVersionForWriting()
  902. continue
  903. }
  904. // Annots array is an IndirectReference.
  905. o, err := pdfCtx.Dereference(ir)
  906. if err != nil || o == nil {
  907. continue
  908. }
  909. annots, _ := o.(pdfcpu.Array)
  910. entry, ok := pdfCtx.FindTableEntryForIndRef(&ir)
  911. if !ok {
  912. continue
  913. }
  914. entry.Object = append(annots, array...)
  915. pdfCtx.EnsureVersionForWriting()
  916. }
  917. }
  918. func ExportStdMarkdown(id string) string {
  919. tree, err := loadTreeByBlockID(id)
  920. if nil != err {
  921. logging.LogErrorf("load tree by block id [%s] failed: %s", id, err)
  922. return ""
  923. }
  924. cloudAssetsBase := ""
  925. if IsSubscriber() {
  926. cloudAssetsBase = util.GetCloudAssetsServer() + Conf.User.UserId + "/"
  927. }
  928. return exportMarkdownContent0(tree, cloudAssetsBase, false,
  929. Conf.Export.BlockRefMode, Conf.Export.BlockEmbedMode, Conf.Export.FileAnnotationRefMode,
  930. Conf.Export.TagOpenMarker, Conf.Export.TagCloseMarker,
  931. Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight,
  932. Conf.Export.AddTitle)
  933. }
  934. func ExportPandocConvertZip(id, pandocTo, ext string) (name, zipPath string) {
  935. block := treenode.GetBlockTree(id)
  936. if nil == block {
  937. logging.LogErrorf("not found block [%s]", id)
  938. return
  939. }
  940. boxID := block.BoxID
  941. box := Conf.Box(boxID)
  942. baseFolderName := path.Base(block.HPath)
  943. if "." == baseFolderName {
  944. baseFolderName = path.Base(block.Path)
  945. }
  946. docPaths := []string{block.Path}
  947. docFiles := box.ListFiles(strings.TrimSuffix(block.Path, ".sy"))
  948. for _, docFile := range docFiles {
  949. docPaths = append(docPaths, docFile.path)
  950. }
  951. zipPath = exportPandocConvertZip(boxID, baseFolderName, docPaths, "gfm+footnotes", pandocTo, ext)
  952. name = strings.TrimSuffix(filepath.Base(block.Path), ".sy")
  953. return
  954. }
  955. func BatchExportMarkdown(boxID, folderPath string) (zipPath string) {
  956. box := Conf.Box(boxID)
  957. var baseFolderName string
  958. if "/" == folderPath {
  959. baseFolderName = box.Name
  960. } else {
  961. block := treenode.GetBlockTreeRootByHPath(box.ID, folderPath)
  962. if nil == block {
  963. logging.LogErrorf("not found block")
  964. return
  965. }
  966. baseFolderName = path.Base(block.HPath)
  967. }
  968. if "" == baseFolderName {
  969. baseFolderName = "Untitled"
  970. }
  971. docFiles := box.ListFiles(folderPath)
  972. var docPaths []string
  973. for _, docFile := range docFiles {
  974. docPaths = append(docPaths, docFile.path)
  975. }
  976. zipPath = exportPandocConvertZip(boxID, baseFolderName, docPaths, "", "", ".md")
  977. return
  978. }
  979. func yfm(docIAL map[string]string) string {
  980. // 导出 Markdown 文件时开头附上一些元数据 https://github.com/siyuan-note/siyuan/issues/6880
  981. // 导出 Markdown 时在文档头添加 YFM 开关https://github.com/siyuan-note/siyuan/issues/7727
  982. if !Conf.Export.MarkdownYFM {
  983. return ""
  984. }
  985. buf := bytes.Buffer{}
  986. buf.WriteString("---\n")
  987. var title, created, updated, tags string
  988. for k, v := range docIAL {
  989. if "id" == k {
  990. createdTime, parseErr := time.Parse("20060102150405", util.TimeFromID(v))
  991. if nil == parseErr {
  992. created = createdTime.Format(time.RFC3339)
  993. }
  994. continue
  995. }
  996. if "title" == k {
  997. title = v
  998. continue
  999. }
  1000. if "updated" == k {
  1001. updatedTime, parseErr := time.Parse("20060102150405", v)
  1002. if nil == parseErr {
  1003. updated = updatedTime.Format(time.RFC3339)
  1004. }
  1005. continue
  1006. }
  1007. if "tags" == k {
  1008. tags = v
  1009. continue
  1010. }
  1011. }
  1012. if "" != title {
  1013. buf.WriteString("title: ")
  1014. buf.WriteString(title)
  1015. buf.WriteString("\n")
  1016. }
  1017. if "" == updated {
  1018. updated = time.Now().Format(time.RFC3339)
  1019. }
  1020. if "" == created {
  1021. created = updated
  1022. }
  1023. buf.WriteString("date: ")
  1024. buf.WriteString(created)
  1025. buf.WriteString("\n")
  1026. buf.WriteString("lastmod: ")
  1027. buf.WriteString(updated)
  1028. buf.WriteString("\n")
  1029. if "" != tags {
  1030. buf.WriteString("tags: [")
  1031. buf.WriteString(tags)
  1032. buf.WriteString("]\n")
  1033. }
  1034. buf.WriteString("---\n\n")
  1035. return buf.String()
  1036. }
  1037. func exportBoxSYZip(boxID string) (zipPath string) {
  1038. box := Conf.Box(boxID)
  1039. if nil == box {
  1040. logging.LogErrorf("not found box [%s]", boxID)
  1041. return
  1042. }
  1043. baseFolderName := box.Name
  1044. var docPaths []string
  1045. docFiles := box.ListFiles("/")
  1046. for _, docFile := range docFiles {
  1047. docPaths = append(docPaths, docFile.path)
  1048. }
  1049. zipPath = exportSYZip(boxID, "/", baseFolderName, docPaths)
  1050. return
  1051. }
  1052. func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (zipPath string) {
  1053. dir, name := path.Split(baseFolderName)
  1054. name = util.FilterFileName(name)
  1055. if strings.HasSuffix(name, "..") {
  1056. // 文档标题以 `..` 结尾时无法导出 Markdown https://github.com/siyuan-note/siyuan/issues/4698
  1057. // 似乎是 os.MkdirAll 的 bug,以 .. 结尾的路径无法创建,所以这里加上 _ 结尾
  1058. name += "_"
  1059. }
  1060. baseFolderName = path.Join(dir, name)
  1061. box := Conf.Box(boxID)
  1062. exportFolder := filepath.Join(util.TempDir, "export", baseFolderName)
  1063. if err := os.MkdirAll(exportFolder, 0755); nil != err {
  1064. logging.LogErrorf("create export temp folder failed: %s", err)
  1065. return
  1066. }
  1067. trees := map[string]*parse.Tree{}
  1068. refTrees := map[string]*parse.Tree{}
  1069. for _, p := range docPaths {
  1070. docIAL := box.docIAL(p)
  1071. if nil == docIAL {
  1072. continue
  1073. }
  1074. id := docIAL["id"]
  1075. tree, err := loadTreeByBlockID(id)
  1076. if nil != err {
  1077. continue
  1078. }
  1079. trees[tree.ID] = tree
  1080. }
  1081. for _, tree := range trees {
  1082. refs := exportRefTrees(tree)
  1083. for refTreeID, refTree := range refs {
  1084. if nil == trees[refTreeID] {
  1085. refTrees[refTreeID] = refTree
  1086. }
  1087. }
  1088. }
  1089. // 按文件夹结构复制选择的树
  1090. for _, tree := range trees {
  1091. readPath := filepath.Join(util.DataDir, tree.Box, tree.Path)
  1092. data, readErr := filelock.ReadFile(readPath)
  1093. if nil != readErr {
  1094. logging.LogErrorf("read file [%s] failed: %s", readPath, readErr)
  1095. continue
  1096. }
  1097. writePath := strings.TrimPrefix(tree.Path, rootDirPath)
  1098. writePath = filepath.Join(exportFolder, writePath)
  1099. writeFolder := filepath.Dir(writePath)
  1100. if mkdirErr := os.MkdirAll(writeFolder, 0755); nil != mkdirErr {
  1101. logging.LogErrorf("create export temp folder [%s] failed: %s", writeFolder, mkdirErr)
  1102. continue
  1103. }
  1104. if writeErr := os.WriteFile(writePath, data, 0644); nil != writeErr {
  1105. logging.LogErrorf("write export file [%s] failed: %s", writePath, writeErr)
  1106. continue
  1107. }
  1108. }
  1109. // 引用树放在导出文件夹根路径下
  1110. for treeID, tree := range refTrees {
  1111. readPath := filepath.Join(util.DataDir, tree.Box, tree.Path)
  1112. data, readErr := filelock.ReadFile(readPath)
  1113. if nil != readErr {
  1114. logging.LogErrorf("read file [%s] failed: %s", readPath, readErr)
  1115. continue
  1116. }
  1117. writePath := strings.TrimPrefix(tree.Path, rootDirPath)
  1118. writePath = filepath.Join(exportFolder, treeID+".sy")
  1119. if writeErr := os.WriteFile(writePath, data, 0644); nil != writeErr {
  1120. logging.LogErrorf("write export file [%s] failed: %s", writePath, writeErr)
  1121. continue
  1122. }
  1123. }
  1124. // 将引用树合并到选择树中,以便后面一次性导出资源文件
  1125. for treeID, tree := range refTrees {
  1126. trees[treeID] = tree
  1127. }
  1128. // 导出引用的资源文件
  1129. copiedAssets := hashset.New()
  1130. for _, tree := range trees {
  1131. var assets []string
  1132. assets = append(assets, assetsLinkDestsInTree(tree)...)
  1133. titleImgPath := treenode.GetDocTitleImgPath(tree.Root) // Export .sy.zip doc title image is not exported https://github.com/siyuan-note/siyuan/issues/8748
  1134. if "" != titleImgPath {
  1135. assets = append(assets, titleImgPath)
  1136. }
  1137. for _, asset := range assets {
  1138. asset = string(html.DecodeDestination([]byte(asset)))
  1139. if strings.Contains(asset, "?") {
  1140. asset = asset[:strings.LastIndex(asset, "?")]
  1141. }
  1142. if copiedAssets.Contains(asset) {
  1143. continue
  1144. }
  1145. srcPath, assetErr := GetAssetAbsPath(asset)
  1146. if nil != assetErr {
  1147. logging.LogWarnf("get asset [%s] abs path failed: %s", asset, assetErr)
  1148. continue
  1149. }
  1150. destPath := filepath.Join(exportFolder, asset)
  1151. assetErr = filelock.Copy(srcPath, destPath)
  1152. if nil != assetErr {
  1153. logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", srcPath, destPath, assetErr)
  1154. continue
  1155. }
  1156. if !gulu.File.IsDir(srcPath) && strings.HasSuffix(strings.ToLower(srcPath), ".pdf") {
  1157. sya := srcPath + ".sya"
  1158. if gulu.File.IsExist(sya) {
  1159. // Related PDF annotation information is not exported when exporting .sy.zip https://github.com/siyuan-note/siyuan/issues/7836
  1160. if syaErr := filelock.Copy(sya, destPath+".sya"); nil != syaErr {
  1161. logging.LogErrorf("copy sya from [%s] to [%s] failed: %s", sya, destPath+".sya", syaErr)
  1162. }
  1163. }
  1164. }
  1165. copiedAssets.Add(asset)
  1166. }
  1167. }
  1168. // 导出自定义排序
  1169. sortPath := filepath.Join(util.DataDir, box.ID, ".siyuan", "sort.json")
  1170. fullSortIDs := map[string]int{}
  1171. sortIDs := map[string]int{}
  1172. var sortData []byte
  1173. var sortErr error
  1174. if gulu.File.IsExist(sortPath) {
  1175. sortData, sortErr = filelock.ReadFile(sortPath)
  1176. if nil != sortErr {
  1177. logging.LogErrorf("read sort conf failed: %s", sortErr)
  1178. }
  1179. if sortErr = gulu.JSON.UnmarshalJSON(sortData, &fullSortIDs); nil != sortErr {
  1180. logging.LogErrorf("unmarshal sort conf failed: %s", sortErr)
  1181. }
  1182. if 0 < len(fullSortIDs) {
  1183. for _, tree := range trees {
  1184. if v, ok := fullSortIDs[tree.ID]; ok {
  1185. sortIDs[tree.ID] = v
  1186. }
  1187. }
  1188. }
  1189. if 0 < len(sortIDs) {
  1190. sortData, sortErr = gulu.JSON.MarshalJSON(sortIDs)
  1191. if nil != sortErr {
  1192. logging.LogErrorf("marshal sort conf failed: %s", sortErr)
  1193. }
  1194. if 0 < len(sortData) {
  1195. confDir := filepath.Join(exportFolder, ".siyuan")
  1196. if mkdirErr := os.MkdirAll(confDir, 0755); nil != mkdirErr {
  1197. logging.LogErrorf("create export conf folder [%s] failed: %s", confDir, mkdirErr)
  1198. } else {
  1199. sortPath = filepath.Join(confDir, "sort.json")
  1200. if writeErr := os.WriteFile(sortPath, sortData, 0644); nil != writeErr {
  1201. logging.LogErrorf("write sort conf failed: %s", writeErr)
  1202. }
  1203. }
  1204. }
  1205. }
  1206. }
  1207. zipPath = exportFolder + ".sy.zip"
  1208. zip, err := gulu.Zip.Create(zipPath)
  1209. if nil != err {
  1210. logging.LogErrorf("create export .sy.zip [%s] failed: %s", exportFolder, err)
  1211. return ""
  1212. }
  1213. if err = zip.AddDirectory(baseFolderName, exportFolder); nil != err {
  1214. logging.LogErrorf("create export .sy.zip [%s] failed: %s", exportFolder, err)
  1215. return ""
  1216. }
  1217. if err = zip.Close(); nil != err {
  1218. logging.LogErrorf("close export .sy.zip failed: %s", err)
  1219. }
  1220. os.RemoveAll(exportFolder)
  1221. zipPath = "/export/" + url.PathEscape(filepath.Base(zipPath))
  1222. return
  1223. }
  1224. func ExportMarkdownContent(id string) (hPath, exportedMd string) {
  1225. return exportMarkdownContent(id)
  1226. }
  1227. func exportMarkdownContent(id string) (hPath, exportedMd string) {
  1228. tree, err := loadTreeByBlockID(id)
  1229. if nil != err {
  1230. logging.LogErrorf("load tree by block id [%s] failed: %s", id, err)
  1231. return
  1232. }
  1233. hPath = tree.HPath
  1234. exportedMd = exportMarkdownContent0(tree, "", false,
  1235. Conf.Export.BlockRefMode, Conf.Export.BlockEmbedMode, Conf.Export.FileAnnotationRefMode,
  1236. Conf.Export.TagOpenMarker, Conf.Export.TagCloseMarker,
  1237. Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight,
  1238. Conf.Export.AddTitle)
  1239. docIAL := parse.IAL2Map(tree.Root.KramdownIAL)
  1240. exportedMd = yfm(docIAL) + exportedMd
  1241. return
  1242. }
  1243. func exportMarkdownContent0(tree *parse.Tree, cloudAssetsBase string, assetsDestSpace2Underscore bool,
  1244. blockRefMode, blockEmbedMode, fileAnnotationRefMode int,
  1245. tagOpenMarker, tagCloseMarker string,
  1246. blockRefTextLeft, blockRefTextRight string,
  1247. addTitle bool) (ret string) {
  1248. tree = exportTree(tree, false, true, false,
  1249. blockRefMode, blockEmbedMode, fileAnnotationRefMode,
  1250. tagOpenMarker, tagCloseMarker,
  1251. blockRefTextLeft, blockRefTextRight,
  1252. addTitle)
  1253. luteEngine := NewLute()
  1254. luteEngine.SetFootnotes(true)
  1255. luteEngine.SetKramdownIAL(false)
  1256. if "" != cloudAssetsBase {
  1257. luteEngine.RenderOptions.LinkBase = cloudAssetsBase
  1258. }
  1259. if assetsDestSpace2Underscore { // 上传到社区图床的资源文件会将空格转为下划线,所以这里也需要将文档内容做相应的转换
  1260. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  1261. if !entering {
  1262. return ast.WalkContinue
  1263. }
  1264. if ast.NodeLinkDest == n.Type {
  1265. if util.IsAssetLinkDest(n.Tokens) {
  1266. n.Tokens = bytes.ReplaceAll(n.Tokens, []byte(" "), []byte("_"))
  1267. }
  1268. } else if n.IsTextMarkType("a") {
  1269. href := n.TextMarkAHref
  1270. if util.IsAssetLinkDest([]byte(href)) {
  1271. n.TextMarkAHref = strings.ReplaceAll(href, " ", "_")
  1272. }
  1273. }
  1274. return ast.WalkContinue
  1275. })
  1276. }
  1277. renderer := render.NewProtyleExportMdRenderer(tree, luteEngine.RenderOptions)
  1278. ret = gulu.Str.FromBytes(renderer.Render())
  1279. return
  1280. }
  1281. func processKaTexMacros(n *ast.Node) {
  1282. if ast.NodeMathBlockContent != n.Type && ast.NodeTextMark != n.Type {
  1283. return
  1284. }
  1285. if ast.NodeTextMark == n.Type && !n.IsTextMarkType("inline-math") {
  1286. return
  1287. }
  1288. var mathContent string
  1289. if ast.NodeTextMark == n.Type {
  1290. mathContent = n.TextMarkInlineMathContent
  1291. } else {
  1292. mathContent = string(n.Tokens)
  1293. }
  1294. mathContent = strings.TrimSpace(mathContent)
  1295. if "" == mathContent {
  1296. return
  1297. }
  1298. macros := map[string]string{}
  1299. if err := gulu.JSON.UnmarshalJSON([]byte(Conf.Editor.KaTexMacros), &macros); nil != err {
  1300. logging.LogWarnf("parse katex macros failed: %s", err)
  1301. return
  1302. }
  1303. var keys []string
  1304. for k := range macros {
  1305. keys = append(keys, k)
  1306. }
  1307. useMacro := false
  1308. for k := range macros {
  1309. if strings.Contains(mathContent, k) {
  1310. useMacro = true
  1311. break
  1312. }
  1313. }
  1314. if !useMacro {
  1315. return
  1316. }
  1317. sort.Slice(keys, func(i, j int) bool { return len(keys[i]) > len(keys[j]) })
  1318. mathContent = escapeKaTexSupportedFunctions(mathContent)
  1319. usedMacros := extractUsedMacros(mathContent, &keys)
  1320. for _, usedMacro := range usedMacros {
  1321. expanded := resolveKaTexMacro(usedMacro, &macros, &keys)
  1322. expanded = unescapeKaTexSupportedFunctions(expanded)
  1323. mathContent = strings.ReplaceAll(mathContent, usedMacro, expanded)
  1324. }
  1325. mathContent = unescapeKaTexSupportedFunctions(mathContent)
  1326. if ast.NodeTextMark == n.Type {
  1327. n.TextMarkInlineMathContent = mathContent
  1328. } else {
  1329. n.Tokens = []byte(mathContent)
  1330. }
  1331. }
  1332. func exportTree(tree *parse.Tree, wysiwyg, expandKaTexMacros, keepFold bool,
  1333. blockRefMode, blockEmbedMode, fileAnnotationRefMode int,
  1334. tagOpenMarker, tagCloseMarker string,
  1335. blockRefTextLeft, blockRefTextRight string,
  1336. addTitle bool) (ret *parse.Tree) {
  1337. luteEngine := NewLute()
  1338. ret = tree
  1339. id := tree.Root.ID
  1340. var unlinks []*ast.Node
  1341. // 解析查询嵌入节点
  1342. ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  1343. if !entering || ast.NodeBlockQueryEmbed != n.Type {
  1344. return ast.WalkContinue
  1345. }
  1346. var defMd string
  1347. stmt := n.ChildByType(ast.NodeBlockQueryEmbedScript).TokensStr()
  1348. stmt = html.UnescapeString(stmt)
  1349. stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")
  1350. embedBlocks := searchEmbedBlock(n.ID, stmt, nil, 0, false)
  1351. if 1 > len(embedBlocks) {
  1352. return ast.WalkContinue
  1353. }
  1354. defMdBuf := bytes.Buffer{}
  1355. for _, def := range embedBlocks {
  1356. defMdBuf.WriteString(renderBlockMarkdownR(def.Block.ID))
  1357. defMdBuf.WriteString("\n\n")
  1358. }
  1359. defMd = defMdBuf.String()
  1360. buf := &bytes.Buffer{}
  1361. lines := strings.Split(defMd, "\n")
  1362. for i, line := range lines {
  1363. if 0 == blockEmbedMode { // 原始文本
  1364. buf.WriteString(line)
  1365. } else { // Blockquote
  1366. buf.WriteString("> " + line)
  1367. }
  1368. if i < len(lines)-1 {
  1369. buf.WriteString("\n")
  1370. }
  1371. }
  1372. buf.WriteString("\n\n")
  1373. refTree := parse.Parse("", buf.Bytes(), luteEngine.ParseOptions)
  1374. var children []*ast.Node
  1375. for c := refTree.Root.FirstChild; nil != c; c = c.Next {
  1376. children = append(children, c)
  1377. }
  1378. for _, c := range children {
  1379. if ast.NodeDocument == c.Type {
  1380. continue
  1381. }
  1382. n.InsertBefore(c)
  1383. }
  1384. unlinks = append(unlinks, n)
  1385. return ast.WalkSkipChildren
  1386. })
  1387. for _, n := range unlinks {
  1388. n.Unlink()
  1389. }
  1390. unlinks = nil
  1391. // 收集引用转脚注
  1392. var refFootnotes []*refAsFootnotes
  1393. if 4 == blockRefMode { // 块引转脚注
  1394. treeCache := map[string]*parse.Tree{}
  1395. treeCache[id] = ret
  1396. depth := 0
  1397. collectFootnotesDefs(ret.ID, &refFootnotes, &treeCache, &depth)
  1398. }
  1399. ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  1400. if !entering {
  1401. return ast.WalkContinue
  1402. }
  1403. switch n.Type {
  1404. case ast.NodeSuperBlockOpenMarker, ast.NodeSuperBlockLayoutMarker, ast.NodeSuperBlockCloseMarker:
  1405. if !wysiwyg {
  1406. unlinks = append(unlinks, n)
  1407. return ast.WalkContinue
  1408. }
  1409. case ast.NodeHeading:
  1410. n.HeadingNormalizedID = n.IALAttr("id")
  1411. n.ID = n.HeadingNormalizedID
  1412. case ast.NodeMathBlockContent:
  1413. n.Tokens = bytes.TrimSpace(n.Tokens) // 导出 Markdown 时去除公式内容中的首尾空格 https://github.com/siyuan-note/siyuan/issues/4666
  1414. return ast.WalkContinue
  1415. case ast.NodeTextMark:
  1416. if n.IsTextMarkType("inline-math") {
  1417. n.TextMarkInlineMathContent = strings.TrimSpace(n.TextMarkInlineMathContent)
  1418. return ast.WalkContinue
  1419. } else if treenode.IsFileAnnotationRef(n) {
  1420. refID := n.TextMarkFileAnnotationRefID
  1421. if !strings.Contains(refID, "/") {
  1422. return ast.WalkSkipChildren
  1423. }
  1424. status := processFileAnnotationRef(refID, n, fileAnnotationRefMode)
  1425. unlinks = append(unlinks, n)
  1426. return status
  1427. } else if n.IsTextMarkType("tag") {
  1428. if !wysiwyg {
  1429. n.Type = ast.NodeText
  1430. n.Tokens = []byte(tagOpenMarker + n.TextMarkTextContent + tagCloseMarker)
  1431. return ast.WalkContinue
  1432. }
  1433. }
  1434. }
  1435. if !treenode.IsBlockRef(n) {
  1436. return ast.WalkContinue
  1437. }
  1438. // 处理引用节点
  1439. defID, linkText, _ := treenode.GetBlockRef(n)
  1440. if "" == linkText {
  1441. linkText = sql.GetRefText(defID)
  1442. }
  1443. linkText = html.UnescapeHTMLStr(linkText) // 块引锚文本导出时 `&` 变为实体 `&amp;` https://github.com/siyuan-note/siyuan/issues/7659
  1444. if Conf.Editor.BlockRefDynamicAnchorTextMaxLen < utf8.RuneCountInString(linkText) {
  1445. linkText = gulu.Str.SubStr(linkText, Conf.Editor.BlockRefDynamicAnchorTextMaxLen) + "..."
  1446. }
  1447. linkText = blockRefTextLeft + linkText + blockRefTextRight
  1448. defTree, _ := loadTreeByBlockID(defID)
  1449. if nil == defTree {
  1450. return ast.WalkContinue
  1451. }
  1452. switch blockRefMode {
  1453. case 2: // 锚文本块链
  1454. var blockRefLink *ast.Node
  1455. blockRefLink = &ast.Node{Type: ast.NodeLink}
  1456. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  1457. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeLinkText, Tokens: []byte(linkText)})
  1458. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  1459. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  1460. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte("siyuan://blocks/" + defID)})
  1461. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  1462. n.InsertBefore(blockRefLink)
  1463. case 3: // 仅锚文本
  1464. n.InsertBefore(&ast.Node{Type: ast.NodeText, Tokens: []byte(linkText)})
  1465. case 4: // 脚注
  1466. refFoot := getRefAsFootnotes(defID, &refFootnotes)
  1467. n.InsertBefore(&ast.Node{Type: ast.NodeText, Tokens: []byte(linkText)})
  1468. n.InsertBefore(&ast.Node{Type: ast.NodeFootnotesRef, Tokens: []byte("^" + refFoot.refNum), FootnotesRefId: refFoot.refNum, FootnotesRefLabel: []byte("^" + refFoot.refNum)})
  1469. }
  1470. unlinks = append(unlinks, n)
  1471. if nil != n.Next && ast.NodeKramdownSpanIAL == n.Next.Type {
  1472. // 引用加排版标记(比如颜色)重叠时丢弃后面的排版属性节点
  1473. unlinks = append(unlinks, n.Next)
  1474. }
  1475. return ast.WalkSkipChildren
  1476. })
  1477. for _, n := range unlinks {
  1478. n.Unlink()
  1479. }
  1480. if 4 == blockRefMode { // 块引转脚注
  1481. if footnotesDefBlock := resolveFootnotesDefs(&refFootnotes, ret.Root.ID, blockRefTextLeft, blockRefTextRight); nil != footnotesDefBlock {
  1482. ret.Root.AppendChild(footnotesDefBlock)
  1483. }
  1484. }
  1485. if addTitle {
  1486. if root, _ := getBlock(id, tree); nil != root {
  1487. title := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 1, KramdownIAL: parse.Map2IAL(root.IAL)}
  1488. content := html.UnescapeString(root.Content)
  1489. title.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(content)})
  1490. ret.Root.PrependChild(title)
  1491. }
  1492. }
  1493. // 导出时支持导出题头图 https://github.com/siyuan-note/siyuan/issues/4372
  1494. titleImgPath := treenode.GetDocTitleImgPath(ret.Root)
  1495. if "" != titleImgPath {
  1496. p := &ast.Node{Type: ast.NodeParagraph}
  1497. titleImg := &ast.Node{Type: ast.NodeImage}
  1498. titleImg.AppendChild(&ast.Node{Type: ast.NodeBang})
  1499. titleImg.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  1500. titleImg.AppendChild(&ast.Node{Type: ast.NodeLinkText, Tokens: []byte("image")})
  1501. titleImg.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  1502. titleImg.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  1503. titleImg.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte(titleImgPath)})
  1504. titleImg.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  1505. p.AppendChild(titleImg)
  1506. ret.Root.PrependChild(p)
  1507. }
  1508. unlinks = nil
  1509. var emptyParagraphs []*ast.Node
  1510. ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  1511. if !entering {
  1512. return ast.WalkContinue
  1513. }
  1514. // 支持按照现有折叠状态导出 PDF https://github.com/siyuan-note/siyuan/issues/5941
  1515. if !keepFold {
  1516. // 块折叠以后导出 HTML/PDF 固定展开 https://github.com/siyuan-note/siyuan/issues/4064
  1517. n.RemoveIALAttr("fold")
  1518. n.RemoveIALAttr("heading-fold")
  1519. } else {
  1520. if "1" == n.IALAttr("heading-fold") {
  1521. unlinks = append(unlinks, n)
  1522. return ast.WalkContinue
  1523. }
  1524. }
  1525. // 导出时去掉内容块闪卡样式 https://github.com/siyuan-note/siyuan/issues/7374
  1526. if n.IsBlock() {
  1527. n.RemoveIALAttr("custom-riff-decks")
  1528. }
  1529. switch n.Type {
  1530. case ast.NodeParagraph:
  1531. if nil == n.FirstChild {
  1532. // 空的段落块需要补全文本展位,否则后续格式化后再解析树会语义不一致 https://github.com/siyuan-note/siyuan/issues/5806
  1533. emptyParagraphs = append(emptyParagraphs, n)
  1534. }
  1535. case ast.NodeMathBlockContent:
  1536. if expandKaTexMacros {
  1537. processKaTexMacros(n)
  1538. }
  1539. case ast.NodeTextMark:
  1540. if expandKaTexMacros && n.IsTextMarkType("inline-math") {
  1541. processKaTexMacros(n)
  1542. }
  1543. case ast.NodeWidget:
  1544. // 挂件块导出 https://github.com/siyuan-note/siyuan/issues/3834 https://github.com/siyuan-note/siyuan/issues/6188
  1545. if wysiwyg {
  1546. exportHtmlVal := n.IALAttr("data-export-html")
  1547. if "" != exportHtmlVal {
  1548. htmlBlock := &ast.Node{Type: ast.NodeHTMLBlock, Tokens: []byte(exportHtmlVal)}
  1549. n.InsertBefore(htmlBlock)
  1550. unlinks = append(unlinks, n)
  1551. return ast.WalkContinue
  1552. }
  1553. }
  1554. exportMdVal := n.IALAttr("data-export-md")
  1555. exportMdVal = html.UnescapeString(exportMdVal) // 导出 `data-export-md` 时未解析代码块与行内代码内的转义字符 https://github.com/siyuan-note/siyuan/issues/4180
  1556. if "" != exportMdVal {
  1557. luteEngine0 := util.NewLute()
  1558. luteEngine0.SetYamlFrontMatter(true) // 挂件导出属性 `data-export-md` 支持 YFM https://github.com/siyuan-note/siyuan/issues/7752
  1559. exportMdTree := parse.Parse("", []byte(exportMdVal), luteEngine0.ParseOptions)
  1560. var insertNodes []*ast.Node
  1561. for c := exportMdTree.Root.FirstChild; nil != c; c = c.Next {
  1562. if ast.NodeKramdownBlockIAL != c.Type {
  1563. insertNodes = append(insertNodes, c)
  1564. }
  1565. }
  1566. for _, insertNode := range insertNodes {
  1567. n.InsertBefore(insertNode)
  1568. }
  1569. unlinks = append(unlinks, n)
  1570. }
  1571. case ast.NodeSuperBlockOpenMarker, ast.NodeSuperBlockLayoutMarker, ast.NodeSuperBlockCloseMarker:
  1572. if !wysiwyg {
  1573. unlinks = append(unlinks, n)
  1574. }
  1575. }
  1576. if ast.NodeText != n.Type {
  1577. return ast.WalkContinue
  1578. }
  1579. // Shift+Enter 换行在导出为 Markdown 时使用硬换行 https://github.com/siyuan-note/siyuan/issues/3458
  1580. n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("\n"), []byte(" \n"))
  1581. return ast.WalkContinue
  1582. })
  1583. for _, n := range unlinks {
  1584. n.Unlink()
  1585. }
  1586. for _, emptyParagraph := range emptyParagraphs {
  1587. emptyParagraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(editor.Zwj)})
  1588. }
  1589. return ret
  1590. }
  1591. func resolveFootnotesDefs(refFootnotes *[]*refAsFootnotes, rootID string, blockRefTextLeft, blockRefTextRight string) (footnotesDefBlock *ast.Node) {
  1592. if 1 > len(*refFootnotes) {
  1593. return nil
  1594. }
  1595. footnotesDefBlock = &ast.Node{Type: ast.NodeFootnotesDefBlock}
  1596. var rendered []string
  1597. for _, foot := range *refFootnotes {
  1598. t, err := loadTreeByBlockID(foot.defID)
  1599. if nil != err {
  1600. continue
  1601. }
  1602. defNode := treenode.GetNodeInTree(t, foot.defID)
  1603. docID := strings.TrimSuffix(path.Base(defNode.Path), ".sy")
  1604. var nodes []*ast.Node
  1605. if ast.NodeHeading == defNode.Type {
  1606. nodes = append(nodes, defNode)
  1607. if rootID != docID {
  1608. // 同文档块引转脚注缩略定义考虑容器块和标题块 https://github.com/siyuan-note/siyuan/issues/5917
  1609. children := treenode.HeadingChildren(defNode)
  1610. nodes = append(nodes, children...)
  1611. }
  1612. } else if ast.NodeDocument == defNode.Type {
  1613. docTitle := &ast.Node{ID: defNode.ID, Type: ast.NodeHeading, HeadingLevel: 1}
  1614. docTitle.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(defNode.IALAttr("title"))})
  1615. nodes = append(nodes, docTitle)
  1616. for c := defNode.FirstChild; nil != c; c = c.Next {
  1617. nodes = append(nodes, c)
  1618. }
  1619. } else {
  1620. nodes = append(nodes, defNode)
  1621. }
  1622. var newNodes []*ast.Node
  1623. for _, node := range nodes {
  1624. var unlinks []*ast.Node
  1625. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  1626. if !entering {
  1627. return ast.WalkContinue
  1628. }
  1629. if treenode.IsBlockRef(n) {
  1630. defID, _, _ := treenode.GetBlockRef(n)
  1631. if f := getRefAsFootnotes(defID, refFootnotes); nil != f {
  1632. n.InsertBefore(&ast.Node{Type: ast.NodeText, Tokens: []byte(blockRefTextLeft + f.refAnchorText + blockRefTextRight)})
  1633. n.InsertBefore(&ast.Node{Type: ast.NodeFootnotesRef, Tokens: []byte("^" + f.refNum), FootnotesRefId: f.refNum, FootnotesRefLabel: []byte("^" + f.refNum)})
  1634. unlinks = append(unlinks, n)
  1635. }
  1636. return ast.WalkSkipChildren
  1637. } else if ast.NodeBlockQueryEmbed == n.Type {
  1638. stmt := n.ChildByType(ast.NodeBlockQueryEmbedScript).TokensStr()
  1639. stmt = html.UnescapeString(stmt)
  1640. stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")
  1641. sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)
  1642. for _, b := range sqlBlocks {
  1643. subNodes := renderBlockMarkdownR0(b.ID, &rendered)
  1644. for _, subNode := range subNodes {
  1645. if ast.NodeListItem == subNode.Type {
  1646. parentList := &ast.Node{Type: ast.NodeList, ListData: &ast.ListData{Typ: subNode.ListData.Typ}}
  1647. parentList.AppendChild(subNode)
  1648. newNodes = append(newNodes, parentList)
  1649. } else {
  1650. newNodes = append(newNodes, subNode)
  1651. }
  1652. }
  1653. }
  1654. unlinks = append(unlinks, n)
  1655. return ast.WalkSkipChildren
  1656. }
  1657. return ast.WalkContinue
  1658. })
  1659. for _, n := range unlinks {
  1660. n.Unlink()
  1661. }
  1662. if ast.NodeBlockQueryEmbed != node.Type {
  1663. if ast.NodeListItem == node.Type {
  1664. parentList := &ast.Node{Type: ast.NodeList, ListData: &ast.ListData{Typ: node.ListData.Typ}}
  1665. parentList.AppendChild(node)
  1666. newNodes = append(newNodes, parentList)
  1667. } else {
  1668. newNodes = append(newNodes, node)
  1669. }
  1670. }
  1671. }
  1672. footnotesDef := &ast.Node{Type: ast.NodeFootnotesDef, Tokens: []byte("^" + foot.refNum), FootnotesRefId: foot.refNum, FootnotesRefLabel: []byte("^" + foot.refNum)}
  1673. for _, node := range newNodes {
  1674. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  1675. if !entering {
  1676. return ast.WalkContinue
  1677. }
  1678. if ast.NodeParagraph != n.Type {
  1679. return ast.WalkContinue
  1680. }
  1681. docID := strings.TrimSuffix(path.Base(n.Path), ".sy")
  1682. if rootID == docID {
  1683. // 同文档块引转脚注缩略定义 https://github.com/siyuan-note/siyuan/issues/3299
  1684. if text := sql.GetRefText(n.ID); 64 < utf8.RuneCountInString(text) {
  1685. var unlinkChildren []*ast.Node
  1686. for c := n.FirstChild; nil != c; c = c.Next {
  1687. unlinkChildren = append(unlinkChildren, c)
  1688. }
  1689. for _, c := range unlinkChildren {
  1690. c.Unlink()
  1691. }
  1692. text = gulu.Str.SubStr(text, 64) + "..."
  1693. n.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(text)})
  1694. return ast.WalkSkipChildren
  1695. }
  1696. }
  1697. return ast.WalkContinue
  1698. })
  1699. footnotesDef.AppendChild(node)
  1700. }
  1701. footnotesDefBlock.AppendChild(footnotesDef)
  1702. }
  1703. return
  1704. }
  1705. func collectFootnotesDefs(id string, refFootnotes *[]*refAsFootnotes, treeCache *map[string]*parse.Tree, depth *int) {
  1706. *depth++
  1707. if 4096 < *depth {
  1708. return
  1709. }
  1710. b := treenode.GetBlockTree(id)
  1711. if nil == b {
  1712. return
  1713. }
  1714. t := (*treeCache)[b.RootID]
  1715. if nil == t {
  1716. var err error
  1717. if t, err = loadTreeByBlockID(b.ID); nil != err {
  1718. return
  1719. }
  1720. (*treeCache)[t.ID] = t
  1721. }
  1722. node := treenode.GetNodeInTree(t, b.ID)
  1723. if nil == node {
  1724. logging.LogErrorf("not found node [%s] in tree [%s]", b.ID, t.Root.ID)
  1725. return
  1726. }
  1727. collectFootnotesDefs0(node, refFootnotes, treeCache, depth)
  1728. if ast.NodeHeading == node.Type {
  1729. children := treenode.HeadingChildren(node)
  1730. for _, c := range children {
  1731. collectFootnotesDefs0(c, refFootnotes, treeCache, depth)
  1732. }
  1733. }
  1734. return
  1735. }
  1736. func collectFootnotesDefs0(node *ast.Node, refFootnotes *[]*refAsFootnotes, treeCache *map[string]*parse.Tree, depth *int) {
  1737. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  1738. if !entering {
  1739. return ast.WalkContinue
  1740. }
  1741. if treenode.IsBlockRef(n) {
  1742. defID, refText, _ := treenode.GetBlockRef(n)
  1743. if nil == getRefAsFootnotes(defID, refFootnotes) {
  1744. anchorText := refText
  1745. if Conf.Editor.BlockRefDynamicAnchorTextMaxLen < utf8.RuneCountInString(anchorText) {
  1746. anchorText = gulu.Str.SubStr(anchorText, Conf.Editor.BlockRefDynamicAnchorTextMaxLen) + "..."
  1747. }
  1748. *refFootnotes = append(*refFootnotes, &refAsFootnotes{
  1749. defID: defID,
  1750. refNum: strconv.Itoa(len(*refFootnotes) + 1),
  1751. refAnchorText: anchorText,
  1752. })
  1753. collectFootnotesDefs(defID, refFootnotes, treeCache, depth)
  1754. }
  1755. return ast.WalkSkipChildren
  1756. }
  1757. return ast.WalkContinue
  1758. })
  1759. }
  1760. func getRefAsFootnotes(defID string, slice *[]*refAsFootnotes) *refAsFootnotes {
  1761. for _, e := range *slice {
  1762. if e.defID == defID {
  1763. return e
  1764. }
  1765. }
  1766. return nil
  1767. }
  1768. type refAsFootnotes struct {
  1769. defID string
  1770. refNum string
  1771. refAnchorText string
  1772. }
  1773. func exportRefTrees(tree *parse.Tree) (ret map[string]*parse.Tree) {
  1774. ret = map[string]*parse.Tree{}
  1775. exportRefTrees0(tree, &ret)
  1776. return
  1777. }
  1778. func exportRefTrees0(tree *parse.Tree, retTrees *map[string]*parse.Tree) {
  1779. if nil != (*retTrees)[tree.ID] {
  1780. return
  1781. }
  1782. (*retTrees)[tree.ID] = tree
  1783. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  1784. if !entering {
  1785. return ast.WalkContinue
  1786. }
  1787. if treenode.IsBlockRef(n) {
  1788. defID, _, _ := treenode.GetBlockRef(n)
  1789. if "" == defID {
  1790. return ast.WalkContinue
  1791. }
  1792. defBlock := treenode.GetBlockTree(defID)
  1793. if nil == defBlock {
  1794. return ast.WalkSkipChildren
  1795. }
  1796. defTree, err := loadTreeByBlockID(defBlock.RootID)
  1797. if nil != err {
  1798. return ast.WalkSkipChildren
  1799. }
  1800. exportRefTrees0(defTree, retTrees)
  1801. }
  1802. return ast.WalkContinue
  1803. })
  1804. }
  1805. func processFileAnnotationRef(refID string, n *ast.Node, fileAnnotationRefMode int) ast.WalkStatus {
  1806. p := refID[:strings.LastIndex(refID, "/")]
  1807. absPath, err := GetAssetAbsPath(p)
  1808. if nil != err {
  1809. logging.LogWarnf("get assets abs path by rel path [%s] failed: %s", p, err)
  1810. return ast.WalkSkipChildren
  1811. }
  1812. sya := absPath + ".sya"
  1813. syaData, err := os.ReadFile(sya)
  1814. if nil != err {
  1815. logging.LogErrorf("read file [%s] failed: %s", sya, err)
  1816. return ast.WalkSkipChildren
  1817. }
  1818. syaJSON := map[string]interface{}{}
  1819. if err = gulu.JSON.UnmarshalJSON(syaData, &syaJSON); nil != err {
  1820. logging.LogErrorf("unmarshal file [%s] failed: %s", sya, err)
  1821. return ast.WalkSkipChildren
  1822. }
  1823. annotationID := refID[strings.LastIndex(refID, "/")+1:]
  1824. annotationData := syaJSON[annotationID]
  1825. if nil == annotationData {
  1826. logging.LogErrorf("not found annotation [%s] in .sya", annotationID)
  1827. return ast.WalkSkipChildren
  1828. }
  1829. pages := annotationData.(map[string]interface{})["pages"].([]interface{})
  1830. page := int(pages[0].(map[string]interface{})["index"].(float64)) + 1
  1831. pageStr := strconv.Itoa(page)
  1832. refText := n.TextMarkTextContent
  1833. ext := filepath.Ext(p)
  1834. file := p[7:len(p)-23-len(ext)] + ext
  1835. fileAnnotationRefLink := &ast.Node{Type: ast.NodeLink}
  1836. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  1837. if 0 == fileAnnotationRefMode {
  1838. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeLinkText, Tokens: []byte(file + " - p" + pageStr + " - " + refText)})
  1839. } else {
  1840. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeLinkText, Tokens: []byte(refText)})
  1841. }
  1842. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  1843. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  1844. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte(p + "?p=" + pageStr)})
  1845. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  1846. n.InsertBefore(fileAnnotationRefLink)
  1847. return ast.WalkSkipChildren
  1848. }
  1849. func exportPandocConvertZip(boxID, baseFolderName string, docPaths []string,
  1850. pandocFrom, pandocTo, ext string) (zipPath string) {
  1851. dir, name := path.Split(baseFolderName)
  1852. name = util.FilterFileName(name)
  1853. if strings.HasSuffix(name, "..") {
  1854. // 文档标题以 `..` 结尾时无法导出 Markdown https://github.com/siyuan-note/siyuan/issues/4698
  1855. // 似乎是 os.MkdirAll 的 bug,以 .. 结尾的路径无法创建,所以这里加上 _ 结尾
  1856. name += "_"
  1857. }
  1858. baseFolderName = path.Join(dir, name)
  1859. box := Conf.Box(boxID)
  1860. exportFolder := filepath.Join(util.TempDir, "export", baseFolderName+ext)
  1861. os.RemoveAll(exportFolder)
  1862. if err := os.MkdirAll(exportFolder, 0755); nil != err {
  1863. logging.LogErrorf("create export temp folder failed: %s", err)
  1864. return
  1865. }
  1866. luteEngine := util.NewLute()
  1867. for _, p := range docPaths {
  1868. docIAL := box.docIAL(p)
  1869. if nil == docIAL {
  1870. continue
  1871. }
  1872. id := docIAL["id"]
  1873. hPath, md := exportMarkdownContent(id)
  1874. dir, name = path.Split(hPath)
  1875. dir = util.FilterFilePath(dir) // 导出文档时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/4590
  1876. name = util.FilterFileName(name)
  1877. hPath = path.Join(dir, name)
  1878. p = hPath + ext
  1879. writePath := filepath.Join(exportFolder, p)
  1880. if gulu.File.IsExist(writePath) {
  1881. // 重名文档加 ID
  1882. p = hPath + "-" + id + ext
  1883. writePath = filepath.Join(exportFolder, p)
  1884. }
  1885. writeFolder := filepath.Dir(writePath)
  1886. if err := os.MkdirAll(writeFolder, 0755); nil != err {
  1887. logging.LogErrorf("create export temp folder [%s] failed: %s", writeFolder, err)
  1888. continue
  1889. }
  1890. // 解析导出后的标准 Markdown,汇总 assets
  1891. tree := parse.Parse("", gulu.Str.ToBytes(md), luteEngine.ParseOptions)
  1892. var assets []string
  1893. assets = append(assets, assetsLinkDestsInTree(tree)...)
  1894. for _, asset := range assets {
  1895. asset = string(html.DecodeDestination([]byte(asset)))
  1896. if strings.Contains(asset, "?") {
  1897. asset = asset[:strings.LastIndex(asset, "?")]
  1898. }
  1899. srcPath, err := GetAssetAbsPath(asset)
  1900. if nil != err {
  1901. logging.LogWarnf("get asset [%s] abs path failed: %s", asset, err)
  1902. continue
  1903. }
  1904. destPath := filepath.Join(writeFolder, asset)
  1905. err = filelock.Copy(srcPath, destPath)
  1906. if nil != err {
  1907. logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", srcPath, destPath, err)
  1908. continue
  1909. }
  1910. }
  1911. // 调用 Pandoc 进行格式转换
  1912. err := util.Pandoc(pandocFrom, pandocTo, writePath, md)
  1913. if nil != err {
  1914. logging.LogErrorf("pandoc failed: %s", err)
  1915. continue
  1916. }
  1917. }
  1918. zipPath = exportFolder + ".zip"
  1919. zip, err := gulu.Zip.Create(zipPath)
  1920. if nil != err {
  1921. logging.LogErrorf("create export markdown zip [%s] failed: %s", exportFolder, err)
  1922. return ""
  1923. }
  1924. // 导出 Markdown zip 包内不带文件夹 https://github.com/siyuan-note/siyuan/issues/6869
  1925. entries, err := os.ReadDir(exportFolder)
  1926. if nil != err {
  1927. logging.LogErrorf("read export markdown folder [%s] failed: %s", exportFolder, err)
  1928. return ""
  1929. }
  1930. for _, entry := range entries {
  1931. entryPath := filepath.Join(exportFolder, entry.Name())
  1932. if gulu.File.IsDir(entryPath) {
  1933. err = zip.AddDirectory(entry.Name(), entryPath)
  1934. } else {
  1935. err = zip.AddEntry(entry.Name(), entryPath)
  1936. }
  1937. if nil != err {
  1938. logging.LogErrorf("add entry [%s] to zip failed: %s", entry.Name(), err)
  1939. return ""
  1940. }
  1941. }
  1942. if err = zip.Close(); nil != err {
  1943. logging.LogErrorf("close export markdown zip failed: %s", err)
  1944. }
  1945. os.RemoveAll(exportFolder)
  1946. zipPath = "/export/" + url.PathEscape(filepath.Base(zipPath))
  1947. return
  1948. }