A Python content management system designed for kirsle.net featuring a blog, comments and photo albums. https://rophako.kirsle.net/
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

81 linhas
2.2 KiB

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