parser.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. from __future__ import unicode_literals
  2. import warnings
  3. import bleach
  4. import markdown
  5. from bs4 import BeautifulSoup
  6. from htmlmin.minify import html_minify
  7. from markdown.extensions.fenced_code import FencedCodeExtension
  8. from django.http import Http404
  9. from django.urls import resolve
  10. from django.utils import six
  11. from .bbcode import blocks, inline
  12. from .md.shortimgs import ShortImagesExtension
  13. from .md.striketrough import StriketroughExtension
  14. from .mentions import add_mentions
  15. from .pipeline import pipeline
  16. MISAGO_ATTACHMENT_VIEWS = ('misago:attachment', 'misago:attachment-thumbnail')
  17. def parse(
  18. text,
  19. request,
  20. poster,
  21. allow_mentions=True,
  22. allow_links=True,
  23. allow_images=True,
  24. allow_blocks=True,
  25. force_shva=False,
  26. minify=True
  27. ):
  28. """
  29. Message parser
  30. Utility for flavours to call
  31. Breaks text into paragraphs, supports code, spoiler and quote blocks,
  32. headers, lists, images, spoilers, text styles
  33. Returns dict object
  34. """
  35. md = md_factory(
  36. allow_links=allow_links,
  37. allow_images=allow_images,
  38. allow_blocks=allow_blocks,
  39. )
  40. parsing_result = {
  41. 'original_text': text,
  42. 'parsed_text': '',
  43. 'markdown': md,
  44. 'mentions': [],
  45. 'images': [],
  46. 'outgoing_links': [],
  47. 'inside_links': [],
  48. }
  49. # Parse text
  50. parsed_text = md.convert(text)
  51. # Clean and store parsed text
  52. parsing_result['parsed_text'] = parsed_text.strip()
  53. if allow_links:
  54. linkify_paragraphs(parsing_result)
  55. parsing_result = pipeline.process_result(parsing_result)
  56. if allow_mentions:
  57. add_mentions(request, parsing_result)
  58. if allow_links or allow_images:
  59. clean_links(request, parsing_result, force_shva)
  60. if minify:
  61. minify_result(parsing_result)
  62. return parsing_result
  63. def md_factory(allow_links=True, allow_images=True, allow_blocks=True):
  64. """
  65. Create and configure markdown object
  66. """
  67. md = markdown.Markdown(safe_mode='escape', extensions=['nl2br'])
  68. # Remove references
  69. del md.preprocessors['reference']
  70. del md.inlinePatterns['reference']
  71. del md.inlinePatterns['image_reference']
  72. del md.inlinePatterns['short_reference']
  73. # Add [b], [i], [u]
  74. md.inlinePatterns.add('bb_b', inline.bold, '<strong')
  75. md.inlinePatterns.add('bb_i', inline.italics, '<emphasis')
  76. md.inlinePatterns.add('bb_u', inline.underline, '<emphasis2')
  77. # Add ~~deleted~~
  78. striketrough_md = StriketroughExtension()
  79. striketrough_md.extendMarkdown(md)
  80. if not allow_links:
  81. # Remove links
  82. del md.inlinePatterns['link']
  83. del md.inlinePatterns['autolink']
  84. del md.inlinePatterns['automail']
  85. if allow_images:
  86. # Add [img]
  87. short_images_md = ShortImagesExtension()
  88. short_images_md.extendMarkdown(md)
  89. else:
  90. # Remove images
  91. del md.inlinePatterns['image_link']
  92. if allow_blocks:
  93. # Add [hr] and [quote] blocks
  94. md.parser.blockprocessors.add('bb_hr', blocks.BBCodeHRProcessor(md.parser), '>hr')
  95. fenced_code = FencedCodeExtension()
  96. fenced_code.extendMarkdown(md, None)
  97. code_bbcode = blocks.CodeBlockExtension()
  98. code_bbcode.extendMarkdown(md)
  99. quote_bbcode = blocks.QuoteExtension()
  100. quote_bbcode.extendMarkdown(md)
  101. else:
  102. # Remove blocks
  103. del md.parser.blockprocessors['hashheader']
  104. del md.parser.blockprocessors['setextheader']
  105. del md.parser.blockprocessors['code']
  106. del md.parser.blockprocessors['quote']
  107. del md.parser.blockprocessors['hr']
  108. del md.parser.blockprocessors['olist']
  109. del md.parser.blockprocessors['ulist']
  110. return pipeline.extend_markdown(md)
  111. def linkify_paragraphs(result):
  112. result['parsed_text'] = bleach.linkify(result['parsed_text'], skip_pre=True, parse_email=True)
  113. # dirty fix for
  114. if '<code>' in result['parsed_text'] and '<a' in result['parsed_text']:
  115. with warnings.catch_warnings():
  116. warnings.simplefilter("ignore")
  117. soup = BeautifulSoup(result['parsed_text'], 'html5lib')
  118. for link in soup.select('code > a'):
  119. link.replace_with(BeautifulSoup(link.string, 'html.parser'))
  120. # [6:-7] trims <body></body> wrap
  121. result['parsed_text'] = six.text_type(soup.body)[6:-7]
  122. def clean_links(request, result, force_shva=False):
  123. host = request.get_host()
  124. soup = BeautifulSoup(result['parsed_text'], 'html5lib')
  125. for link in soup.find_all('a'):
  126. if is_internal_link(link['href'], host):
  127. link['href'] = clean_internal_link(link['href'], host)
  128. result['inside_links'].append(link['href'])
  129. link['href'] = clean_attachment_link(link['href'], force_shva)
  130. else:
  131. result['outgoing_links'].append(link['href'])
  132. if link.string:
  133. link.string = clean_link_prefix(link.string)
  134. for img in soup.find_all('img'):
  135. img['alt'] = clean_link_prefix(img['alt'])
  136. if is_internal_link(img['src'], host):
  137. img['src'] = clean_internal_link(img['src'], host)
  138. result['images'].append(img['src'])
  139. img['src'] = clean_attachment_link(img['src'], force_shva)
  140. else:
  141. result['images'].append(img['src'])
  142. # [6:-7] trims <body></body> wrap
  143. result['parsed_text'] = six.text_type(soup.body)[6:-7]
  144. def is_internal_link(link, host):
  145. if link.startswith('/') and not link.startswith('//'):
  146. return True
  147. link = clean_link_prefix(link).lstrip('www.').lower()
  148. return link.lower().startswith(host.lstrip('www.'))
  149. def clean_link_prefix(link):
  150. if link.lower().startswith('https:'):
  151. link = link[6:]
  152. if link.lower().startswith('http:'):
  153. link = link[5:]
  154. if link.startswith('//'):
  155. link = link[2:]
  156. return link
  157. def clean_internal_link(link, host):
  158. link = clean_link_prefix(link)
  159. if link.lower().startswith('www.'):
  160. link = link[4:]
  161. if host.lower().startswith('www.'):
  162. host = host[4:]
  163. if link.lower().startswith(host):
  164. link = link[len(host):]
  165. return link or '/'
  166. def clean_attachment_link(link, force_shva=False):
  167. try:
  168. resolution = resolve(link)
  169. url_name = ':'.join(resolution.namespaces + [resolution.url_name])
  170. except (Http404, ValueError):
  171. return link
  172. if url_name in MISAGO_ATTACHMENT_VIEWS:
  173. if force_shva:
  174. link = '{}?shva=1'.format(link)
  175. elif link.endswith('?shva=1'):
  176. link = link[:-7]
  177. return link
  178. def minify_result(result):
  179. # [25:-14] trims <html><head></head><body> and </body></html>
  180. result['parsed_text'] = html_minify(result['parsed_text'].encode('utf-8'))
  181. result['parsed_text'] = result['parsed_text'][25:-14]