b64.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. """
  2. B64.
  3. An extension for Python Markdown.
  4. Given an absolute base path, this extension searches for image tags,
  5. and if the images are local, will embed the images in base64.
  6. MIT license.
  7. Copyright (c) 2014 - 2017 Isaac Muse <isaacmuse@gmail.com>
  8. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  9. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  10. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  11. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in all copies or substantial portions
  13. of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  15. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  16. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  17. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  18. DEALINGS IN THE SOFTWARE.
  19. """
  20. from markdown import Extension
  21. from markdown.postprocessors import Postprocessor
  22. from . import util
  23. import os
  24. import base64
  25. import re
  26. RE_SLASH_WIN_DRIVE = re.compile(r"^/[A-Za-z]{1}:/.*")
  27. file_types = {
  28. (".png",): "image/png",
  29. (".jpg", ".jpeg"): "image/jpeg",
  30. (".gif",): "image/gif"
  31. }
  32. RE_TAG_HTML = re.compile(
  33. r'''(?xus)
  34. (?:
  35. (?P<comments>(\r?\n?\s*)<!--[\s\S]*?-->(\s*)(?=\r?\n)|<!--[\s\S]*?-->)|
  36. (?P<open><(?P<tag>img))
  37. (?P<attr>(?:\s+[\w\-:]+(?:\s*=\s*(?:"[^"]*"|'[^']*'))?)*)
  38. (?P<close>\s*(?:\/?)>)
  39. )
  40. '''
  41. )
  42. RE_TAG_LINK_ATTR = re.compile(
  43. r'''(?xus)
  44. (?P<attr>
  45. (?:
  46. (?P<name>\s+src\s*=\s*)
  47. (?P<path>"[^"]*"|'[^']*')
  48. )
  49. )
  50. '''
  51. )
  52. def repl_path(m, base_path):
  53. """Replace path with b64 encoded data."""
  54. link = m.group(0)
  55. try:
  56. scheme, netloc, path, params, query, fragment, is_url, is_absolute = util.parse_url(m.group('path')[1:-1])
  57. if not is_url:
  58. path = util.url2path(path)
  59. if is_absolute:
  60. file_name = os.path.normpath(path)
  61. else:
  62. file_name = os.path.normpath(os.path.join(base_path, path))
  63. if os.path.exists(file_name):
  64. ext = os.path.splitext(file_name)[1].lower()
  65. for b64_ext in file_types:
  66. if ext in b64_ext:
  67. with open(file_name, "rb") as f:
  68. link = " src=\"data:%s;base64,%s\"" % (
  69. file_types[b64_ext],
  70. base64.b64encode(f.read()).decode('ascii')
  71. )
  72. break
  73. except Exception: # pragma: no cover
  74. # Parsing crashed and burned; no need to continue.
  75. pass
  76. return link
  77. def repl(m, base_path):
  78. """Replace."""
  79. if m.group('comments'):
  80. tag = m.group('comments')
  81. else:
  82. tag = m.group('open')
  83. tag += RE_TAG_LINK_ATTR.sub(lambda m2: repl_path(m2, base_path), m.group('attr'))
  84. tag += m.group('close')
  85. return tag
  86. class B64Postprocessor(Postprocessor):
  87. """Post processor for B64."""
  88. def run(self, text):
  89. """Find and replace paths with base64 encoded file."""
  90. basepath = self.config['base_path']
  91. text = RE_TAG_HTML.sub(lambda m: repl(m, basepath), text)
  92. return text
  93. class B64Extension(Extension):
  94. """B64 extension."""
  95. def __init__(self, *args, **kwargs):
  96. """Initialize."""
  97. self.config = {
  98. 'base_path': [".", "Base path for b64 to use to resolve paths - Default: \".\""]
  99. }
  100. super(B64Extension, self).__init__(*args, **kwargs)
  101. def extendMarkdown(self, md):
  102. """Add base 64 tree processor to Markdown instance."""
  103. b64 = B64Postprocessor(md)
  104. b64.config = self.getConfigs()
  105. md.postprocessors.register(b64, "b64", 2)
  106. md.registerExtension(self)
  107. def makeExtension(*args, **kwargs):
  108. """Return extension."""
  109. return B64Extension(*args, **kwargs)