A Python content management system designed for kirsle.net featuring a blog, comments and photo albums. https://rophako.kirsle.net/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

emoticons.py 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. """Emoticon models."""
  4. from flask import request
  5. import os
  6. import codecs
  7. import json
  8. import re
  9. from rophako.settings import Config
  10. from rophako.log import logger
  11. _cache = {}
  12. def load_theme():
  13. """Pre-load and cache the emoticon theme. This happens on startup."""
  14. theme = Config.emoticons.theme
  15. global _cache
  16. # Cached?
  17. if _cache:
  18. return _cache
  19. # Only if the theme file exists.
  20. settings = os.path.join(Config.emoticons.root_private, theme, "emoticons.json")
  21. if not os.path.isfile(settings):
  22. logger.error("Failed to load smiley theme {}: not found!")
  23. # Try the default (tango).
  24. theme = "tango"
  25. settings = os.path.join(Config.emoticons.root_private, theme, "emoticons.json")
  26. if os.path.isfile(settings):
  27. logger.info("Falling back to default theme: tango")
  28. else:
  29. # Give up.
  30. return {}
  31. # Read it.
  32. fh = codecs.open(settings, "r", "utf-8")
  33. text = fh.read()
  34. fh.close()
  35. try:
  36. data = json.loads(text)
  37. except Exception as e:
  38. logger.error("Couldn't load JSON from emoticon file: {}".format(e))
  39. data = {}
  40. # Cache and return it.
  41. _cache = data
  42. return data
  43. def render(message):
  44. """Render the emoticons into a message.
  45. The message should already be stripped of HTML and otherwise be 'safe' to
  46. embed on a web page. The output of this function includes `<img>` tags and
  47. these won't work otherwise."""
  48. # Get the smileys config.
  49. smileys = load_theme()
  50. # Process all smileys.
  51. for img in sorted(smileys["map"]):
  52. for trigger in smileys["map"][img]:
  53. if trigger in message:
  54. # Substitute it.
  55. sub = """<img src="{url}" class="rophako-emoticon" alt="{trigger}" title="{trigger}">""".format(
  56. url="{}/static/smileys/{}/{}".format(request.url_root.strip("/"), Config.emoticons.theme, img),
  57. trigger=trigger,
  58. )
  59. pattern = r'([^A-Za-z0-9:\-]|^){}([^A-Za-z0-9:\-]|$)'.format(re.escape(trigger))
  60. result = r'\1{}\2'.format(sub)
  61. message = re.sub(pattern, result, message)
  62. return message