annotate smiley/utils.py @ 1022:82f1f6f905eb

Perform image_check on private messages.
author Brian Neal <bgneal@gmail.com>
date Wed, 09 Dec 2015 21:16:04 -0600
parents 98d2388b6bb2
children
rev   line source
bgneal@124 1 """
bgneal@211 2 Smiley classes and functions.
bgneal@613 3
bgneal@124 4 """
bgneal@124 5 from django.utils.safestring import SafeData
bgneal@124 6 from django.utils.html import conditional_escape
bgneal@124 7
bgneal@925 8 from models import Smiley
bgneal@124 9
bgneal@124 10
bgneal@211 11 class SmilifyHtml(object):
bgneal@124 12 """
bgneal@211 13 A class to "smilify" text by replacing text with HTML img tags for smiley
bgneal@211 14 images.
bgneal@124 15 """
bgneal@124 16 def __init__(self):
bgneal@124 17 self.map = Smiley.objects.get_smiley_map()
bgneal@124 18
bgneal@211 19 def convert(self, value, autoescape=False):
bgneal@128 20 """
bgneal@211 21 Converts and returns the supplied text with the HTML version of the
bgneal@211 22 smileys.
bgneal@128 23 """
bgneal@286 24 if not value:
bgneal@286 25 return u''
bgneal@286 26
bgneal@124 27 if not autoescape or isinstance(value, SafeData):
bgneal@124 28 esc = lambda x: x
bgneal@124 29 else:
bgneal@124 30 esc = conditional_escape
bgneal@124 31
bgneal@124 32 words = value.split()
bgneal@124 33 for i, word in enumerate(words):
bgneal@124 34 if word in self.map:
bgneal@211 35 words[i] = self.map[word]
bgneal@124 36 else:
bgneal@124 37 words[i] = esc(words[i])
bgneal@124 38 return u' '.join(words)
bgneal@128 39
bgneal@211 40
bgneal@211 41 class SmilifyMarkdown(object):
bgneal@211 42 """
bgneal@211 43 A class to "smilify" text by replacing text with Markdown image syntax for
bgneal@211 44 smiley images.
bgneal@211 45 """
bgneal@792 46 def __init__(self, relative_urls=True):
bgneal@792 47 self.regexes = Smiley.objects.get_smiley_regexes(
bgneal@792 48 relative_urls=relative_urls)
bgneal@211 49
bgneal@211 50 def convert(self, s):
bgneal@128 51 """
bgneal@211 52 Returns a string copy of the input s that has the smiley codes replaced
bgneal@211 53 with Markdown for smiley images.
bgneal@128 54 """
bgneal@286 55 if not s:
bgneal@286 56 return u''
bgneal@286 57
bgneal@211 58 for regex, repl in self.regexes:
bgneal@211 59 s = regex.sub(repl, s)
bgneal@211 60 return s
bgneal@128 61
bgneal@124 62
bgneal@128 63 def smilify_html(value, autoescape=False):
bgneal@124 64 """
bgneal@124 65 A convenience function to "smilify" text by replacing text with HTML
bgneal@124 66 img tags of smilies.
bgneal@124 67 """
bgneal@211 68 s = SmilifyHtml()
bgneal@211 69 return s.convert(value, autoescape=autoescape)