comparison src/browser/sat_browser/strings.py @ 784:f3cd261ea12f

browser side: workaround for a pyjamas bug which freeze the browser in some case with addURLToText regex
author Goffi <goffi@goffi.org>
date Tue, 01 Dec 2015 13:55:01 +0100
parents
children f8a7a046ff9c
comparison
equal deleted inserted replaced
783:d24e56a5f2ef 784:f3cd261ea12f
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # SAT helpers methods for plugins
5 # Copyright (C) 2013, 2014, 2015 Adrien Cossa (souliane@mailoo.org)
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 import re
21 from __pyjamas__ import JS
22
23
24 def getURLParams(url):
25 """This comes from pyjamas.Location.makeUrlDict with a small change
26 to also parse full URLs, and parameters with no value specified
27 (in that case the default value "" is used).
28 @param url: any URL with or without parameters
29 @return: a dictionary of the parameters, if any was given, or {}
30 """
31 dict_ = {}
32 if "/" in url:
33 # keep the part after the last "/"
34 url = url[url.rindex("/") + 1:]
35 if url.startswith("?"):
36 # remove the first "?"
37 url = url[1:]
38 pairs = url.split("&")
39 for pair in pairs:
40 if len(pair) < 3:
41 continue
42 kv = pair.split("=", 1)
43 dict_[kv[0]] = kv[1] if len(kv) > 1 else ""
44 return dict_
45
46
47 def addURLToText(text):
48 """Workaround for a pyjamas bug with regex
49
50 In some case, Pyjamas' re module get crazy and freeze browsers (tested with Iceweasel and Chromium).
51 we use javascript as a workaround
52 This method is inspired from https://stackoverflow.com/questions/1500260/detect-urls-in-text-with-javascript
53 """
54 JS("""var urlRegex = /(https?:\/\/[^\s]+)/g;
55 return text.replace(urlRegex, function(url) {
56 return '<a href="' + url + '">' + url + '</a>';
57 })""")
58
59
60 def addURLToImage(string):
61 """Check a XHTML text for what looks like an imageURL and make it clickable"""
62 def repl(match):
63 url = match.group(1)
64 return '<a href="%s" target="_blank">%s</a>' % (url, match.group(0))
65 pattern = r"""<img[^>]* src="([^"]+)"[^>]*>"""
66 return re.sub(pattern, repl, string)