mentions.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import re
  2. from bs4 import BeautifulSoup, NavigableString
  3. from django.contrib.auth import get_user_model
  4. from django.utils import six
  5. SUPPORTED_TAGS = ('h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'p')
  6. USERNAME_RE = re.compile(r'@[0-9a-z]+', re.IGNORECASE)
  7. MENTIONS_LIMIT = 24
  8. def add_mentions(request, result):
  9. if '@' not in result['parsed_text']:
  10. return
  11. mentions_dict = {}
  12. soup = BeautifulSoup(result['parsed_text'], 'html5lib')
  13. elements = []
  14. for tagname in SUPPORTED_TAGS:
  15. if tagname in result['parsed_text']:
  16. elements += soup.find_all(tagname)
  17. for element in elements:
  18. add_mentions_to_element(request, element, mentions_dict)
  19. result['parsed_text'] = six.text_type(soup.body)[6:-7].strip()
  20. result['mentions'] = list(filter(bool, mentions_dict.values()))
  21. def add_mentions_to_element(request, element, mentions_dict):
  22. for item in element.contents:
  23. if item.name:
  24. if item.name != 'a':
  25. add_mentions_to_element(request, item, mentions_dict)
  26. elif '@' in item.string:
  27. parse_string(request, item, mentions_dict)
  28. def parse_string(request, element, mentions_dict):
  29. def replace_mentions(matchobj):
  30. if len(mentions_dict) >= MENTIONS_LIMIT:
  31. return matchobj.group(0)
  32. username = matchobj.group(0)[1:].strip().lower()
  33. if username not in mentions_dict:
  34. if username == request.user.slug:
  35. mentions_dict[username] = request.user
  36. else:
  37. User = get_user_model()
  38. try:
  39. mentions_dict[username] = User.objects.get(slug=username)
  40. except User.DoesNotExist:
  41. mentions_dict[username] = None
  42. if mentions_dict[username]:
  43. user = mentions_dict[username]
  44. return u'<a href="{}">@{}</a>'.format(user.get_absolute_url(), user.username)
  45. else:
  46. # we've failed to resolve user for username
  47. return matchobj.group(0)
  48. replaced_string = USERNAME_RE.sub(replace_mentions, element.string)
  49. element.replace_with(BeautifulSoup(replaced_string, 'html.parser'))