A Python content management system designed for kirsle.net featuring a blog, comments and photo albums. https://rophako.kirsle.net/
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 

80 rader
2.1 KiB

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