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.
 
 
 
 
 

81 lines
2.2 KiB

  1. # -*- coding: utf-8 -*-
  2. """Emoticon models."""
  3. from flask import g, url_for
  4. import os
  5. import codecs
  6. import json
  7. import re
  8. import config
  9. import rophako.jsondb as JsonDB
  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.EMOTICON_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.EMOTICON_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.EMOTICON_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}" alt="{trigger}" title="{trigger}">""".format(
  56. url="/static/smileys/{}/{}".format(config.EMOTICON_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