diff browser_side/tools.py @ 217:f7ec248192de

browser_side: display clickable URLs in chat text
author souliane <souliane@mailoo.org>
date Sun, 08 Sep 2013 12:34:00 +0200
parents c2639c9f86ea
children d7c41c84d062
line wrap: on
line diff
--- a/browser_side/tools.py	Sun Sep 08 13:40:01 2013 +0200
+++ b/browser_side/tools.py	Sun Sep 08 12:34:00 2013 +0200
@@ -20,18 +20,33 @@
 """
 
 from pyjamas.ui.DragWidget import DragWidget
+import re
 
 def html_sanitize(html):
     """Naive sanitization of HTML"""
     return html.replace('<','&lt;').replace('>','&gt;')
 
+
+def addURLToText(string):
+    """Check a text for what looks like an URL and make it clickable. Regexp
+    from http://daringfireball.net/2010/07/improved_regex_for_matching_urls"""
+
+    def repl(match):
+        url = match.group(0)
+        if not re.match(r"""[a-z]{3,}://|mailto:|xmpp:""", url):
+            url = "http://" + url
+        return '<a href="%s" target="_blank" class="url">%s</a>' % (url, match.group(0))
+    pattern = r"""(?i)\b((?:[a-z]{3,}://|(www|ftp)\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/|mailto:|xmpp:)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?]))"""
+    return re.sub(pattern, repl, string)
+
+
 class DragLabel(DragWidget):
 
     def __init__(self, text, _type):
         DragWidget.__init__(self)
         self._text = text
         self._type = _type
-    
+
     def onDragStart(self, event):
         dt = event.dataTransfer
         dt.setData('text/plain', "%s\n%s" % (self._text, self._type))