Python 3 port:
/!\ this is a huge commit /!\ starting from this commit, SàT is needs Python 3.6+ /!\ SàT maybe be instable or some feature may not work anymore, this will improve with time This patch port backend, bridge and frontends to Python 3. Roughly this has been done this way: - 2to3 tools has been applied (with python 3.7) - all references to python2 have been replaced with python3 (notably shebangs) - fixed files not handled by 2to3 (notably the shell script) - several manual fixes - fixed issues reported by Python 3 that where not handled in Python 2 - replaced "async" with "async_" when needed (it's a reserved word from Python 3.7) - replaced zope's "implements" with @implementer decorator - temporary hack to handle data pickled in database, as str or bytes may be returned, to be checked later - fixed hash comparison for password - removed some code which is not needed anymore with Python 3 - deactivated some code which needs to be checked (notably certificate validation) - tested with jp, fixed reported issues until some basic commands worked - ported Primitivus (after porting dependencies like urwid satext) - more manual fixes
This commit is contained in:
parent
d21a6a660f
commit
fbfe96c505
12 changed files with 6336 additions and 6398 deletions
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SàT: a XMPP client
|
||||
|
|
@ -26,7 +26,7 @@ class ANSI(object):
|
|||
RESET = "\033[0m"
|
||||
NORMAL_WEIGHT = "\033[22m"
|
||||
FG_BLACK, FG_RED, FG_GREEN, FG_YELLOW, FG_BLUE, FG_MAGENTA, FG_CYAN, FG_WHITE = (
|
||||
"\033[3%dm" % nb for nb in xrange(8)
|
||||
"\033[3%dm" % nb for nb in range(8)
|
||||
)
|
||||
BOLD = "\033[1m"
|
||||
BLINK = "\033[5m"
|
||||
|
|
@ -42,7 +42,7 @@ class ANSI(object):
|
|||
if args[-1] != cls.RESET:
|
||||
args = list(args)
|
||||
args.append(cls.RESET)
|
||||
return u"".join(args)
|
||||
return "".join(args)
|
||||
|
||||
|
||||
try:
|
||||
|
|
@ -55,6 +55,6 @@ except (
|
|||
if not tty:
|
||||
# we don't want ANSI escape codes if we are not outputing to a tty!
|
||||
for attr in dir(ANSI):
|
||||
if isinstance(getattr(ANSI, attr), basestring):
|
||||
setattr(ANSI, attr, u"")
|
||||
if isinstance(getattr(ANSI, attr), str):
|
||||
setattr(ANSI, attr, "")
|
||||
del tty
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SAT: a jabber client
|
||||
|
|
@ -56,7 +56,7 @@ class CommandProtocol(protocol.ProcessProtocol):
|
|||
return os.path.splitext(os.path.basename(self.command))[0].decode('utf-8',
|
||||
'ignore')
|
||||
else:
|
||||
return u''
|
||||
return ''
|
||||
|
||||
def connectionMade(self):
|
||||
if self._stdin is not None:
|
||||
|
|
@ -74,22 +74,22 @@ class CommandProtocol(protocol.ProcessProtocol):
|
|||
self.err_data.append(data)
|
||||
|
||||
def processEnded(self, reason):
|
||||
data = ''.join(self.data)
|
||||
data = b''.join(self.data)
|
||||
if (reason.value.exitCode == 0):
|
||||
log.debug(_(u'{name} command succeed').format(name=self.command_name))
|
||||
log.debug(_('{name} command succeed').format(name=self.command_name))
|
||||
# we don't use "replace" on purpose, we want an exception if decoding
|
||||
# is not working properly
|
||||
self._deferred.callback(data.encode('utf-8'))
|
||||
self._deferred.callback(data)
|
||||
else:
|
||||
err_data = u''.join(self.err_data)
|
||||
err_data = b''.join(self.err_data)
|
||||
|
||||
msg = (_(u"Can't complete {name} command (error code: {code}):\n"
|
||||
u"stderr:\n{stderr}\n{stdout}\n")
|
||||
msg = (_("Can't complete {name} command (error code: {code}):\n"
|
||||
"stderr:\n{stderr}\n{stdout}\n")
|
||||
.format(name = self.command_name,
|
||||
code = reason.value.exitCode,
|
||||
stderr= err_data.encode('utf-8', 'replace'),
|
||||
stdout = "stdout: " + data.encode('utf-8', 'replace')
|
||||
if data else u'',
|
||||
stdout = "stdout: " + data.decode('utf-8', 'replace')
|
||||
if data else '',
|
||||
))
|
||||
self._deferred.errback(Failure(exceptions.CommandException(
|
||||
msg, data, err_data)))
|
||||
|
|
@ -114,10 +114,10 @@ class CommandProtocol(protocol.ProcessProtocol):
|
|||
if stdin is not None:
|
||||
stdin = stdin.encode('utf-8')
|
||||
verbose = kwargs.pop('verbose', False)
|
||||
if u'path' in kwargs:
|
||||
kwargs[u'path'] = kwargs[u'path'].encode('utf-8')
|
||||
if 'path' in kwargs:
|
||||
kwargs['path'] = kwargs['path'].encode('utf-8')
|
||||
args = [a.encode('utf-8') for a in args]
|
||||
kwargs = {k:v.encode('utf-8') for k,v in kwargs.items()}
|
||||
kwargs = {k:v.encode('utf-8') for k,v in list(kwargs.items())}
|
||||
d = defer.Deferred()
|
||||
prot = cls(d, stdin=stdin)
|
||||
if verbose:
|
||||
|
|
@ -125,12 +125,12 @@ class CommandProtocol(protocol.ProcessProtocol):
|
|||
if cls.command is None:
|
||||
if not args:
|
||||
raise ValueError(
|
||||
u"You must either specify cls.command or use a full path to command "
|
||||
u"to execute as first argument")
|
||||
"You must either specify cls.command or use a full path to command "
|
||||
"to execute as first argument")
|
||||
command = args.pop(0)
|
||||
if prot.name is None:
|
||||
name = os.path.splitext(os.path.basename(command))[0]
|
||||
prot.name = name.encode(u'utf-8', u'ignore')
|
||||
prot.name = name
|
||||
else:
|
||||
command = cls.command
|
||||
cmd_args = [os.path.basename(command)] + args
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SAT: a jabber client
|
||||
|
|
@ -50,7 +50,7 @@ def dict2iter(name, dict_, pop=False):
|
|||
idx = 1
|
||||
while True:
|
||||
try:
|
||||
yield get(dict_, u"{}#{}".format(name, idx))
|
||||
yield get(dict_, "{}#{}".format(name, idx))
|
||||
except KeyError:
|
||||
return
|
||||
else:
|
||||
|
|
@ -73,7 +73,7 @@ def dict2iterdict(name, dict_, extra_keys, pop=False):
|
|||
ret = {name: main_value}
|
||||
for k in extra_keys:
|
||||
ret[k] = get(
|
||||
dict_, u"{}{}_{}".format(name, (u"#" + unicode(idx)) if idx else u"", k)
|
||||
dict_, "{}{}_{}".format(name, ("#" + str(idx)) if idx else "", k)
|
||||
)
|
||||
yield ret
|
||||
|
||||
|
|
@ -98,14 +98,14 @@ def iter2dict(name, iter_, dict_=None, check_conflict=True):
|
|||
if idx == 0:
|
||||
key = name
|
||||
else:
|
||||
key = u"{}#{}".format(name, idx)
|
||||
key = "{}#{}".format(name, idx)
|
||||
if check_conflict and key in dict_:
|
||||
raise exceptions.ConflictError
|
||||
dict_[key] = value
|
||||
return dict
|
||||
|
||||
|
||||
def getSubDict(name, dict_, sep=u"_"):
|
||||
def getSubDict(name, dict_, sep="_"):
|
||||
"""get a sub dictionary from a serialised dictionary
|
||||
|
||||
look for keys starting with name, and create a dict with it
|
||||
|
|
@ -116,7 +116,7 @@ def getSubDict(name, dict_, sep=u"_"):
|
|||
@param sep(unicode): separator used between name and subkey
|
||||
@return iter: iterate through the deserialised items
|
||||
"""
|
||||
for k, v in dict_.iteritems():
|
||||
for k, v in dict_.items():
|
||||
if k.startswith(name):
|
||||
if k == name:
|
||||
yield None, v
|
||||
|
|
@ -131,7 +131,7 @@ def serialise(data):
|
|||
|
||||
@return(unicode): serialised data, can be transmitted as string to the bridge
|
||||
"""
|
||||
return json.dumps(data, ensure_ascii=False, default=unicode)
|
||||
return json.dumps(data, ensure_ascii=False, default=str)
|
||||
|
||||
def deserialise(serialised_data, default=None, type_check=dict):
|
||||
"""Deserialize data from bridge
|
||||
|
|
@ -142,10 +142,10 @@ def deserialise(serialised_data, default=None, type_check=dict):
|
|||
@return(object): deserialised data
|
||||
@raise ValueError: serialised_data is of wrong type
|
||||
"""
|
||||
if serialised_data == u"":
|
||||
if serialised_data == "":
|
||||
return default
|
||||
ret = json.loads(serialised_data)
|
||||
if type_check is not None and not isinstance(ret, type_check):
|
||||
raise ValueError(u"Bad data type, was expecting {type_check}, got {real_type}"
|
||||
raise ValueError("Bad data type, was expecting {type_check}, got {real_type}"
|
||||
.format(type_check=type_check, real_type=type(ret)))
|
||||
return ret
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SAT: a jabber client
|
||||
|
|
@ -25,12 +25,12 @@ from sat.tools.common import data_format
|
|||
try:
|
||||
from jinja2 import Markup as safe
|
||||
except ImportError:
|
||||
safe = unicode
|
||||
safe = str
|
||||
|
||||
from sat.tools.common import uri as xmpp_uri
|
||||
import urllib
|
||||
import urllib.request, urllib.parse, urllib.error
|
||||
|
||||
q = lambda value: urllib.quote(value.encode("utf-8"), safe="@")
|
||||
q = lambda value: urllib.parse.quote(value.encode("utf-8"), safe="@")
|
||||
|
||||
|
||||
def parsePubSubMetadata(metadata, items):
|
||||
|
|
@ -49,25 +49,25 @@ def parsePubSubMetadata(metadata, items):
|
|||
data = {}
|
||||
assert "complete" not in metadata
|
||||
|
||||
for key, value in metadata.iteritems():
|
||||
if key in (u"rsm_index", u"rsm_count"):
|
||||
for key, value in metadata.items():
|
||||
if key in ("rsm_index", "rsm_count"):
|
||||
value = int(value)
|
||||
elif key == u"mam_stable":
|
||||
elif key == "mam_stable":
|
||||
value = C.bool(value)
|
||||
elif key == u"mam_complete":
|
||||
key = u"complete"
|
||||
elif key == "mam_complete":
|
||||
key = "complete"
|
||||
value = C.bool(value)
|
||||
data[key] = value
|
||||
if u"complete" not in data:
|
||||
index = data.get(u"rsm_index")
|
||||
count = data.get(u"rsm_count")
|
||||
if "complete" not in data:
|
||||
index = data.get("rsm_index")
|
||||
count = data.get("rsm_count")
|
||||
if index is None or count is None:
|
||||
# we don't have enough information to know if the data is complete or not
|
||||
data[u"complete"] = None
|
||||
data["complete"] = None
|
||||
else:
|
||||
# normally we have a strict equality here but XEP-0059 states
|
||||
# that index MAY be approximative, so just in case…
|
||||
data[u"complete"] = index + len(items) >= count
|
||||
data["complete"] = index + len(items) >= count
|
||||
return data
|
||||
|
||||
|
||||
|
|
@ -88,75 +88,75 @@ class BlogItem(object):
|
|||
|
||||
@property
|
||||
def id(self):
|
||||
return self.mb_data.get(u"id")
|
||||
return self.mb_data.get("id")
|
||||
|
||||
@property
|
||||
def atom_id(self):
|
||||
return self.mb_data.get(u"atom_id")
|
||||
return self.mb_data.get("atom_id")
|
||||
|
||||
@property
|
||||
def uri(self):
|
||||
node = self.parent.node
|
||||
service = self.parent.service
|
||||
return xmpp_uri.buildXMPPUri(
|
||||
u"pubsub", subtype=u"microblog", path=service, node=node, item=self.id
|
||||
"pubsub", subtype="microblog", path=service, node=node, item=self.id
|
||||
)
|
||||
|
||||
@property
|
||||
def published(self):
|
||||
return self.mb_data.get(u"published")
|
||||
return self.mb_data.get("published")
|
||||
|
||||
@property
|
||||
def updated(self):
|
||||
return self.mb_data.get(u"updated")
|
||||
return self.mb_data.get("updated")
|
||||
|
||||
@property
|
||||
def language(self):
|
||||
return self.mb_data.get(u"language")
|
||||
return self.mb_data.get("language")
|
||||
|
||||
@property
|
||||
def author(self):
|
||||
return self.mb_data.get(u"author")
|
||||
return self.mb_data.get("author")
|
||||
|
||||
@property
|
||||
def author_jid(self):
|
||||
return self.mb_data.get(u"author_jid")
|
||||
return self.mb_data.get("author_jid")
|
||||
|
||||
@property
|
||||
def author_jid_verified(self):
|
||||
return self.mb_data.get(u"author_jid_verified")
|
||||
return self.mb_data.get("author_jid_verified")
|
||||
|
||||
@property
|
||||
def author_email(self):
|
||||
return self.mb_data.get(u"author_email")
|
||||
return self.mb_data.get("author_email")
|
||||
|
||||
@property
|
||||
def tags(self):
|
||||
return self.mb_data.get(u'tags', [])
|
||||
return self.mb_data.get('tags', [])
|
||||
|
||||
@property
|
||||
def groups(self):
|
||||
return self.mb_data.get(u'groups', [])
|
||||
return self.mb_data.get('groups', [])
|
||||
|
||||
@property
|
||||
def title(self):
|
||||
return self.mb_data.get(u"title")
|
||||
return self.mb_data.get("title")
|
||||
|
||||
@property
|
||||
def title_xhtml(self):
|
||||
try:
|
||||
return safe(self.mb_data[u"title_xhtml"])
|
||||
return safe(self.mb_data["title_xhtml"])
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
@property
|
||||
def content(self):
|
||||
return self.mb_data.get(u"content")
|
||||
return self.mb_data.get("content")
|
||||
|
||||
@property
|
||||
def content_xhtml(self):
|
||||
try:
|
||||
return safe(self.mb_data[u"content_xhtml"])
|
||||
return safe(self.mb_data["content_xhtml"])
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
|
|
@ -164,17 +164,17 @@ class BlogItem(object):
|
|||
def comments(self):
|
||||
if self._comments is None:
|
||||
self._comments = data_format.dict2iterdict(
|
||||
u"comments", self.mb_data, (u"node", u"service")
|
||||
"comments", self.mb_data, ("node", "service")
|
||||
)
|
||||
return self._comments
|
||||
|
||||
@property
|
||||
def comments_service(self):
|
||||
return self.mb_data.get(u"comments_service")
|
||||
return self.mb_data.get("comments_service")
|
||||
|
||||
@property
|
||||
def comments_node(self):
|
||||
return self.mb_data.get(u"comments_node")
|
||||
return self.mb_data.get("comments_node")
|
||||
|
||||
@property
|
||||
def comments_items_list(self):
|
||||
|
|
@ -199,40 +199,40 @@ class BlogItems(object):
|
|||
|
||||
@property
|
||||
def service(self):
|
||||
return self.metadata[u"service"]
|
||||
return self.metadata["service"]
|
||||
|
||||
@property
|
||||
def node(self):
|
||||
return self.metadata[u"node"]
|
||||
return self.metadata["node"]
|
||||
|
||||
@property
|
||||
def uri(self):
|
||||
return self.metadata[u"uri"]
|
||||
return self.metadata["uri"]
|
||||
|
||||
@property
|
||||
def with_rsm(self):
|
||||
"""Return True if RSM is activated on this request"""
|
||||
return u"rsm_first" in self.metadata
|
||||
return "rsm_first" in self.metadata
|
||||
|
||||
@property
|
||||
def rsm_first(self):
|
||||
return self.metadata[u"rsm_first"]
|
||||
return self.metadata["rsm_first"]
|
||||
|
||||
@property
|
||||
def rsm_last(self):
|
||||
return self.metadata[u"rsm_last"]
|
||||
return self.metadata["rsm_last"]
|
||||
|
||||
@property
|
||||
def rsm_index(self):
|
||||
return self.metadata[u"rsm_index"]
|
||||
return self.metadata["rsm_index"]
|
||||
|
||||
@property
|
||||
def rsm_count(self):
|
||||
return self.metadata[u"rsm_count"]
|
||||
return self.metadata["rsm_count"]
|
||||
|
||||
@property
|
||||
def complete(self):
|
||||
return self.metadata[u"complete"]
|
||||
return self.metadata["complete"]
|
||||
|
||||
def __len__(self):
|
||||
return self.items.__len__()
|
||||
|
|
@ -282,14 +282,14 @@ class Message(object):
|
|||
try:
|
||||
return self._message_data[""]
|
||||
except KeyError:
|
||||
return next(self._message_data.itervalues())
|
||||
return next(iter(self._message_data.values()))
|
||||
|
||||
@property
|
||||
def subject(self):
|
||||
try:
|
||||
return self._subject_data[""]
|
||||
except KeyError:
|
||||
return next(self._subject_data.itervalues())
|
||||
return next(iter(self._subject_data.values()))
|
||||
|
||||
@property
|
||||
def type(self):
|
||||
|
|
@ -322,7 +322,7 @@ class Message(object):
|
|||
try:
|
||||
return safe(self._html[""])
|
||||
except KeyError:
|
||||
return safe(next(self._html.itervalues()))
|
||||
return safe(next(iter(self._html.values())))
|
||||
|
||||
|
||||
class Messages(object):
|
||||
|
|
@ -419,5 +419,5 @@ class OnClick(object):
|
|||
values will be quoted before being used
|
||||
"""
|
||||
return self.url.format(
|
||||
*[q(a) for a in args], **{k: ObjectQuoter(v) for k, v in kwargs.iteritems()}
|
||||
*[q(a) for a in args], **{k: ObjectQuoter(v) for k, v in kwargs.items()}
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SAT: a jabber client
|
||||
|
|
@ -30,14 +30,14 @@ import calendar
|
|||
import time
|
||||
import re
|
||||
|
||||
RELATIVE_RE = re.compile(ur"(?P<date>.*?)(?P<direction>[-+]?) *(?P<quantity>\d+) *"
|
||||
ur"(?P<unit>(second|minute|hour|day|week|month|year))s?"
|
||||
ur"(?P<ago> +ago)?", re.I)
|
||||
YEAR_FIRST_RE = re.compile(ur"\d{4}[^\d]+")
|
||||
RELATIVE_RE = re.compile(r"(?P<date>.*?)(?P<direction>[-+]?) *(?P<quantity>\d+) *"
|
||||
r"(?P<unit>(second|minute|hour|day|week|month|year))s?"
|
||||
r"(?P<ago> +ago)?", re.I)
|
||||
YEAR_FIRST_RE = re.compile(r"\d{4}[^\d]+")
|
||||
TZ_UTC = tz.tzutc()
|
||||
TZ_LOCAL = tz.gettz()
|
||||
# used to replace values when something is missing
|
||||
DEFAULT_DATETIME = datetime.datetime(2000, 01, 01)
|
||||
DEFAULT_DATETIME = datetime.datetime(2000, 0o1, 0o1)
|
||||
|
||||
|
||||
def date_parse(value, default_tz=TZ_UTC):
|
||||
|
|
@ -47,7 +47,7 @@ def date_parse(value, default_tz=TZ_UTC):
|
|||
@param default_tz(datetime.tzinfo): default timezone
|
||||
@return (int): timestamp
|
||||
"""
|
||||
value = unicode(value).strip()
|
||||
value = str(value).strip()
|
||||
dayfirst = False if YEAR_FIRST_RE.match(value) else True
|
||||
|
||||
dt = default_tzinfo(
|
||||
|
|
@ -71,23 +71,23 @@ def date_parse_ext(value, default_tz=TZ_UTC):
|
|||
if m is None:
|
||||
return date_parse(value, default_tz=default_tz)
|
||||
|
||||
if m.group(u"direction") and m.group(u"ago"):
|
||||
if m.group("direction") and m.group("ago"):
|
||||
raise ValueError(
|
||||
_(u"You can't use a direction (+ or -) and \"ago\" at the same time"))
|
||||
_("You can't use a direction (+ or -) and \"ago\" at the same time"))
|
||||
|
||||
if m.group(u"direction") == u'-' or m.group(u"ago"):
|
||||
if m.group("direction") == '-' or m.group("ago"):
|
||||
direction = -1
|
||||
else:
|
||||
direction = 1
|
||||
|
||||
date = m.group(u"date").strip().lower()
|
||||
if not date or date == u"now":
|
||||
date = m.group("date").strip().lower()
|
||||
if not date or date == "now":
|
||||
dt = datetime.datetime.now(tz.tzutc())
|
||||
else:
|
||||
dt = default_tzinfo(parser.parse(date, dayfirst=True))
|
||||
|
||||
quantity = int(m.group(u"quantity"))
|
||||
key = m.group(u"unit").lower() + u"s"
|
||||
quantity = int(m.group("quantity"))
|
||||
key = m.group("unit").lower() + "s"
|
||||
delta_kw = {key: direction * quantity}
|
||||
dt = dt + relativedelta(**delta_kw)
|
||||
return calendar.timegm(dt.utctimetuple())
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SàT: a XMPP
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SàT: a jabber client
|
||||
|
|
@ -19,14 +19,14 @@
|
|||
|
||||
"""email sending facilities"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
from email.mime.text import MIMEText
|
||||
from twisted.mail import smtp
|
||||
from sat.core.constants import Const as C
|
||||
from sat.tools import config as tools_config
|
||||
|
||||
|
||||
def sendEmail(config, to_emails, subject=u"", body=u"", from_email=None):
|
||||
def sendEmail(config, to_emails, subject="", body="", from_email=None):
|
||||
"""Send an email using SàT configuration
|
||||
|
||||
@param config (SafeConfigParser): the configuration instance
|
||||
|
|
@ -37,26 +37,26 @@ def sendEmail(config, to_emails, subject=u"", body=u"", from_email=None):
|
|||
@param from_email(unicode): address of the sender
|
||||
@return (D): same as smtp.sendmail
|
||||
"""
|
||||
if isinstance(to_emails, basestring):
|
||||
if isinstance(to_emails, str):
|
||||
to_emails = to_emails.split()
|
||||
email_host = tools_config.getConfig(config, None, u"email_server") or u"localhost"
|
||||
email_from = tools_config.getConfig(config, None, u"email_from")
|
||||
email_host = tools_config.getConfig(config, None, "email_server") or "localhost"
|
||||
email_from = tools_config.getConfig(config, None, "email_from")
|
||||
if email_from is None:
|
||||
# we suppose that email domain and XMPP domain are identical
|
||||
domain = tools_config.getConfig(config, None, u"xmpp_domain", u"example.net")
|
||||
email_from = u"no_reply@" + domain
|
||||
email_sender_domain = tools_config.getConfig(config, None, u"email_sender_domain")
|
||||
email_port = int(tools_config.getConfig(config, None, u"email_port", 25))
|
||||
email_username = tools_config.getConfig(config, None, u"email_username")
|
||||
email_password = tools_config.getConfig(config, None, u"email_password")
|
||||
domain = tools_config.getConfig(config, None, "xmpp_domain", "example.net")
|
||||
email_from = "no_reply@" + domain
|
||||
email_sender_domain = tools_config.getConfig(config, None, "email_sender_domain")
|
||||
email_port = int(tools_config.getConfig(config, None, "email_port", 25))
|
||||
email_username = tools_config.getConfig(config, None, "email_username")
|
||||
email_password = tools_config.getConfig(config, None, "email_password")
|
||||
email_auth = C.bool(tools_config.getConfig(config, None, "email_auth", C.BOOL_FALSE))
|
||||
email_starttls = C.bool(tools_config.getConfig(config, None, "email_starttls",
|
||||
C.BOOL_FALSE))
|
||||
|
||||
msg = MIMEText(body, "plain", "UTF-8")
|
||||
msg[u"Subject"] = subject
|
||||
msg[u"From"] = email_from
|
||||
msg[u"To"] = u", ".join(to_emails)
|
||||
msg["Subject"] = subject
|
||||
msg["From"] = email_from
|
||||
msg["To"] = ", ".join(to_emails)
|
||||
|
||||
return smtp.sendmail(
|
||||
email_host.encode("utf-8"),
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SAT: a jabber client
|
||||
|
|
@ -30,6 +30,6 @@ def get_unique_name(path):
|
|||
ori_path = path
|
||||
idx = 1
|
||||
while os.path.exists(path):
|
||||
path = ori_path + u"_" + unicode(idx)
|
||||
path = ori_path + "_" + str(idx)
|
||||
idx += 1
|
||||
return path
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Salut à Toi: an XMPP client
|
||||
|
|
@ -22,8 +22,8 @@
|
|||
import re
|
||||
|
||||
path_escape = {"%": "%25", "/": "%2F", "\\": "%5c"}
|
||||
path_escape_rev = {re.escape(v): k for k, v in path_escape.iteritems()}
|
||||
path_escape = {re.escape(k): v for k, v in path_escape.iteritems()}
|
||||
path_escape_rev = {re.escape(v): k for k, v in path_escape.items()}
|
||||
path_escape = {re.escape(k): v for k, v in path_escape.items()}
|
||||
# thanks to Martijn Pieters (https://stackoverflow.com/a/14693789)
|
||||
RE_ANSI_REMOVE = re.compile(r"\x1b[^m]*m")
|
||||
|
||||
|
|
@ -44,8 +44,8 @@ def reSubDict(pattern, repl_dict, string):
|
|||
return pattern.sub(lambda m: repl_dict[re.escape(m.group(0))], string)
|
||||
|
||||
|
||||
path_escape_re = reJoin(path_escape.keys())
|
||||
path_escape_rev_re = reJoin(path_escape_rev.keys())
|
||||
path_escape_re = reJoin(list(path_escape.keys()))
|
||||
path_escape_rev_re = reJoin(list(path_escape_rev.keys()))
|
||||
|
||||
|
||||
def pathEscape(string):
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SAT: a jabber client
|
||||
|
|
@ -41,8 +41,8 @@ try:
|
|||
import sat_templates
|
||||
except ImportError:
|
||||
raise exceptions.MissingModule(
|
||||
u"sat_templates module is not available, please install it or check your path to "
|
||||
u"use template engine"
|
||||
"sat_templates module is not available, please install it or check your path to "
|
||||
"use template engine"
|
||||
)
|
||||
else:
|
||||
sat_templates # to avoid pyflakes warning
|
||||
|
|
@ -51,8 +51,8 @@ try:
|
|||
import jinja2
|
||||
except:
|
||||
raise exceptions.MissingModule(
|
||||
u"Missing module jinja2, please install it from http://jinja.pocoo.org or with "
|
||||
u"pip install jinja2"
|
||||
"Missing module jinja2, please install it from http://jinja.pocoo.org or with "
|
||||
"pip install jinja2"
|
||||
)
|
||||
|
||||
from jinja2 import Markup as safe
|
||||
|
|
@ -67,9 +67,9 @@ log = getLogger(__name__)
|
|||
|
||||
HTML_EXT = ("html", "xhtml")
|
||||
RE_ATTR_ESCAPE = re.compile(r"[^a-z_-]")
|
||||
SITE_RESERVED_NAMES = (u"sat",)
|
||||
TPL_RESERVED_CHARS = ur"()/."
|
||||
RE_TPL_RESERVED_CHARS = re.compile(u"[" + TPL_RESERVED_CHARS + u"]")
|
||||
SITE_RESERVED_NAMES = ("sat",)
|
||||
TPL_RESERVED_CHARS = r"()/."
|
||||
RE_TPL_RESERVED_CHARS = re.compile("[" + TPL_RESERVED_CHARS + "]")
|
||||
|
||||
TemplateData = namedtuple("TemplateData", ['site', 'theme', 'path'])
|
||||
|
||||
|
|
@ -85,8 +85,8 @@ class TemplateLoader(jinja2.BaseLoader):
|
|||
as this allow the template to open any file on the system that the
|
||||
launching user can access.
|
||||
"""
|
||||
if not sites_paths or not u"" in sites_paths:
|
||||
raise exceptions.InternalError(u"Invalid sites_paths")
|
||||
if not sites_paths or not "" in sites_paths:
|
||||
raise exceptions.InternalError("Invalid sites_paths")
|
||||
super(jinja2.BaseLoader, self).__init__()
|
||||
self.sites_paths = sites_paths
|
||||
self.trusted = trusted
|
||||
|
|
@ -108,49 +108,49 @@ class TemplateLoader(jinja2.BaseLoader):
|
|||
site and theme can be both None if absolute path is used
|
||||
Relative path is the path from theme root dir e.g. blog/articles.html
|
||||
"""
|
||||
if template.startswith(u"("):
|
||||
if template.startswith("("):
|
||||
# site and/or theme are specified
|
||||
try:
|
||||
theme_end = template.index(u")")
|
||||
theme_end = template.index(")")
|
||||
except IndexError:
|
||||
raise ValueError(u"incorrect site/theme in template")
|
||||
raise ValueError("incorrect site/theme in template")
|
||||
theme_data = template[1:theme_end]
|
||||
theme_splitted = theme_data.split(u'/')
|
||||
theme_splitted = theme_data.split('/')
|
||||
if len(theme_splitted) == 1:
|
||||
site, theme = u"", theme_splitted[0]
|
||||
site, theme = "", theme_splitted[0]
|
||||
elif len(theme_splitted) == 2:
|
||||
site, theme = theme_splitted
|
||||
else:
|
||||
raise ValueError(u"incorrect site/theme in template")
|
||||
raise ValueError("incorrect site/theme in template")
|
||||
template_path = template[theme_end+1:]
|
||||
if not template_path or template_path.startswith(u"/"):
|
||||
raise ValueError(u"incorrect template path")
|
||||
elif template.startswith(u"/"):
|
||||
if not template_path or template_path.startswith("/"):
|
||||
raise ValueError("incorrect template path")
|
||||
elif template.startswith("/"):
|
||||
# this is an absolute path, so we have no site and no theme
|
||||
site = None
|
||||
theme = None
|
||||
template_path = template
|
||||
else:
|
||||
# a default template
|
||||
site = u""
|
||||
site = ""
|
||||
theme = C.TEMPLATE_THEME_DEFAULT
|
||||
template_path = template
|
||||
|
||||
if site is not None:
|
||||
site = site.strip()
|
||||
if not site:
|
||||
site = u""
|
||||
site = ""
|
||||
elif site in SITE_RESERVED_NAMES:
|
||||
raise ValueError(_(u"{site} can't be used as site name, "
|
||||
u"it's reserved.").format(site=site))
|
||||
raise ValueError(_("{site} can't be used as site name, "
|
||||
"it's reserved.").format(site=site))
|
||||
|
||||
if theme is not None:
|
||||
theme = theme.strip()
|
||||
if not theme:
|
||||
theme = C.TEMPLATE_THEME_DEFAULT
|
||||
if RE_TPL_RESERVED_CHARS.search(theme):
|
||||
raise ValueError(_(u"{theme} contain forbidden char. Following chars "
|
||||
u"are forbidden: {reserved}").format(
|
||||
raise ValueError(_("{theme} contain forbidden char. Following chars "
|
||||
"are forbidden: {reserved}").format(
|
||||
theme=theme, reserved=TPL_RESERVED_CHARS))
|
||||
|
||||
return TemplateData(site, theme, template_path)
|
||||
|
|
@ -169,7 +169,7 @@ class TemplateLoader(jinja2.BaseLoader):
|
|||
sites_and_themes.append([site, C.TEMPLATE_THEME_DEFAULT])
|
||||
if site:
|
||||
# the site is not the default one, so we add default at the end
|
||||
sites_and_themes.append([u'', C.TEMPLATE_THEME_DEFAULT])
|
||||
sites_and_themes.append(['', C.TEMPLATE_THEME_DEFAULT])
|
||||
return sites_and_themes
|
||||
|
||||
def _get_template_f(self, site, theme, path_elts):
|
||||
|
|
@ -185,15 +185,15 @@ class TemplateLoader(jinja2.BaseLoader):
|
|||
"""
|
||||
if site is None:
|
||||
raise exceptions.InternalError(
|
||||
u"_get_template_f must not be used with absolute path")
|
||||
"_get_template_f must not be used with absolute path")
|
||||
for site, theme in self.getSitesAndThemes(site, theme):
|
||||
try:
|
||||
base_path = self.sites_paths[site]
|
||||
except KeyError:
|
||||
log.warning(_(u"Unregistered site requested: {site}").format(
|
||||
log.warning(_("Unregistered site requested: {site}").format(
|
||||
site=site))
|
||||
filepath = os.path.join(base_path, C.TEMPLATE_TPL_DIR, theme, *path_elts)
|
||||
f = utils.open_if_exists(filepath)
|
||||
f = utils.open_if_exists(filepath, 'r')
|
||||
if f is not None:
|
||||
return f, filepath
|
||||
return None, None
|
||||
|
|
@ -211,14 +211,14 @@ class TemplateLoader(jinja2.BaseLoader):
|
|||
if site is None:
|
||||
# we have an abolute template
|
||||
if theme is not None:
|
||||
raise exceptions.InternalError(u"We can't have a theme with absolute "
|
||||
u"template.")
|
||||
raise exceptions.InternalError("We can't have a theme with absolute "
|
||||
"template.")
|
||||
if not self.trusted:
|
||||
log.error(_(u"Absolute template used while unsecure is disabled, hack "
|
||||
u"attempt? Template: {template}").format(template=template))
|
||||
raise exceptions.PermissionError(u"absolute template is not allowed")
|
||||
log.error(_("Absolute template used while unsecure is disabled, hack "
|
||||
"attempt? Template: {template}").format(template=template))
|
||||
raise exceptions.PermissionError("absolute template is not allowed")
|
||||
filepath = template_path
|
||||
f = utils.open_if_exists(filepath)
|
||||
f = utils.open_if_exists(filepath, 'r')
|
||||
else:
|
||||
# relative path, we have to deal with site and theme
|
||||
assert theme and template_path
|
||||
|
|
@ -227,19 +227,19 @@ class TemplateLoader(jinja2.BaseLoader):
|
|||
f, filepath = self._get_template_f(site, theme, path_elts)
|
||||
|
||||
if f is None:
|
||||
if (site is not None and path_elts[0] == u"error"
|
||||
if (site is not None and path_elts[0] == "error"
|
||||
and os.path.splitext(template_path)[1][1:] in HTML_EXT):
|
||||
# if an HTML error is requested but doesn't exist, we try again
|
||||
# with base error.
|
||||
f, filepath = self._get_template_f(
|
||||
site, theme, ("error", "base.html"))
|
||||
if f is None:
|
||||
raise exceptions.InternalError(u"error/base.html should exist")
|
||||
raise exceptions.InternalError("error/base.html should exist")
|
||||
else:
|
||||
raise TemplateNotFound(template)
|
||||
|
||||
try:
|
||||
contents = f.read().decode('utf-8')
|
||||
contents = f.read()
|
||||
finally:
|
||||
f.close()
|
||||
|
||||
|
|
@ -285,15 +285,15 @@ class ScriptsHandler(object):
|
|||
@param library_name(unicode): name of the library to import
|
||||
@param loading:
|
||||
"""
|
||||
if attribute not in (u"defer", u"async", u""):
|
||||
if attribute not in ("defer", "async", ""):
|
||||
raise exceptions.DataError(
|
||||
_(u'Invalid attribute, please use one of "defer", "async" or ""')
|
||||
_('Invalid attribute, please use one of "defer", "async" or ""')
|
||||
)
|
||||
if not library_name.endswith(u".js"):
|
||||
library_name = library_name + u".js"
|
||||
if not library_name.endswith(".js"):
|
||||
library_name = library_name + ".js"
|
||||
if (library_name, attribute) not in self.scripts:
|
||||
self.scripts.append((library_name, attribute))
|
||||
return u""
|
||||
return ""
|
||||
|
||||
def generate_scripts(self):
|
||||
"""Generate the <script> elements
|
||||
|
|
@ -301,28 +301,28 @@ class ScriptsHandler(object):
|
|||
@return (unicode): <scripts> HTML tags
|
||||
"""
|
||||
scripts = []
|
||||
tpl = u"<script src={src} {attribute}></script>"
|
||||
tpl = "<script src={src} {attribute}></script>"
|
||||
for library, attribute in self.scripts:
|
||||
library_path = self.renderer.getStaticPath(self.template_data, library)
|
||||
if library_path is None:
|
||||
log.warning(_(u"Can't find {libary} javascript library").format(
|
||||
log.warning(_("Can't find {libary} javascript library").format(
|
||||
library=library))
|
||||
continue
|
||||
path = self.renderer.getFrontURL(library_path)
|
||||
scripts.append(tpl.format(src=quoteattr(path), attribute=attribute))
|
||||
return safe(u"\n".join(scripts))
|
||||
return safe("\n".join(scripts))
|
||||
|
||||
|
||||
class Environment(jinja2.Environment):
|
||||
|
||||
def get_template(self, name, parent=None, globals=None):
|
||||
if name[0] not in (u'/', u'('):
|
||||
if name[0] not in ('/', '('):
|
||||
# if name is not an absolute path or a full template name (this happen on
|
||||
# extend or import during rendering), we convert it to a full template name.
|
||||
# This is needed to handle cache correctly when a base template is overriden.
|
||||
# Without that, we could not distinguish something like base/base.html if
|
||||
# it's launched from some_site/some_theme or from [default]/default
|
||||
name = u"({site}/{theme}){template}".format(
|
||||
name = "({site}/{theme}){template}".format(
|
||||
site=self._template_data.site,
|
||||
theme=self._template_data.theme,
|
||||
template=name)
|
||||
|
|
@ -348,26 +348,26 @@ class Renderer(object):
|
|||
self.host = host
|
||||
self.trusted = trusted
|
||||
self.sites_paths = {
|
||||
u"": os.path.dirname(sat_templates.__file__),
|
||||
"": os.path.dirname(sat_templates.__file__),
|
||||
}
|
||||
conf = config.parseMainConf()
|
||||
public_sites = config.getConfig(conf, None, u"sites_path_public_dict", {})
|
||||
public_sites = config.getConfig(conf, None, "sites_path_public_dict", {})
|
||||
sites_data = [public_sites]
|
||||
if private:
|
||||
private_sites = config.getConfig(conf, None, u"sites_path_private_dict", {})
|
||||
private_sites = config.getConfig(conf, None, "sites_path_private_dict", {})
|
||||
sites_data.append(private_sites)
|
||||
for sites in sites_data:
|
||||
normalised = {}
|
||||
for name, path in sites.iteritems():
|
||||
for name, path in sites.items():
|
||||
if RE_TPL_RESERVED_CHARS.search(name):
|
||||
log.warning(_(u"Can't add \"{name}\" site, it contains forbidden "
|
||||
u"characters. Forbidden characters are {forbidden}.")
|
||||
log.warning(_("Can't add \"{name}\" site, it contains forbidden "
|
||||
"characters. Forbidden characters are {forbidden}.")
|
||||
.format(name=name, forbidden=TPL_RESERVED_CHARS))
|
||||
continue
|
||||
path = os.path.expanduser(os.path.normpath(path))
|
||||
if not path or not path.startswith(u"/"):
|
||||
log.warning(_(u"Can't add \"{name}\" site, it should map to an "
|
||||
u"absolute path").format(name=name))
|
||||
if not path or not path.startswith("/"):
|
||||
log.warning(_("Can't add \"{name}\" site, it should map to an "
|
||||
"absolute path").format(name=name))
|
||||
continue
|
||||
normalised[name] = path
|
||||
self.sites_paths.update(normalised)
|
||||
|
|
@ -385,26 +385,26 @@ class Renderer(object):
|
|||
self.installTranslations()
|
||||
|
||||
# we want to have access to SàT constants in templates
|
||||
self.env.globals[u"C"] = C
|
||||
self.env.globals["C"] = C
|
||||
|
||||
# custom filters
|
||||
self.env.filters[u"next_gidx"] = self._next_gidx
|
||||
self.env.filters[u"cur_gidx"] = self._cur_gidx
|
||||
self.env.filters[u"date_fmt"] = self._date_fmt
|
||||
self.env.filters[u"xmlui_class"] = self._xmlui_class
|
||||
self.env.filters[u"attr_escape"] = self.attr_escape
|
||||
self.env.filters[u"item_filter"] = self._item_filter
|
||||
self.env.filters[u"adv_format"] = self._adv_format
|
||||
self.env.filters[u"dict_ext"] = self._dict_ext
|
||||
self.env.filters[u"highlight"] = self.highlight
|
||||
self.env.filters[u"front_url"] = (self._front_url if front_url_filter is None
|
||||
self.env.filters["next_gidx"] = self._next_gidx
|
||||
self.env.filters["cur_gidx"] = self._cur_gidx
|
||||
self.env.filters["date_fmt"] = self._date_fmt
|
||||
self.env.filters["xmlui_class"] = self._xmlui_class
|
||||
self.env.filters["attr_escape"] = self.attr_escape
|
||||
self.env.filters["item_filter"] = self._item_filter
|
||||
self.env.filters["adv_format"] = self._adv_format
|
||||
self.env.filters["dict_ext"] = self._dict_ext
|
||||
self.env.filters["highlight"] = self.highlight
|
||||
self.env.filters["front_url"] = (self._front_url if front_url_filter is None
|
||||
else front_url_filter)
|
||||
# custom tests
|
||||
self.env.tests[u"in_the_past"] = self._in_the_past
|
||||
self.icons_path = os.path.join(host.media_dir, u"fonts/fontello/svg")
|
||||
self.env.tests["in_the_past"] = self._in_the_past
|
||||
self.icons_path = os.path.join(host.media_dir, "fonts/fontello/svg")
|
||||
|
||||
# policies
|
||||
self.env.policies[u"ext.i18n.trimmed"] = True
|
||||
self.env.policies["ext.i18n.trimmed"] = True
|
||||
|
||||
def getFrontURL(self, template_data, path=None):
|
||||
"""Give front URL (i.e. URL seen by end-user) of a path
|
||||
|
|
@ -413,15 +413,15 @@ class Renderer(object):
|
|||
@param path(unicode, None): relative path of file to get,
|
||||
if set, will remplate template_data.path
|
||||
"""
|
||||
return self.env.filters[u"front_url"]({u"template_data": template_data},
|
||||
return self.env.filters["front_url"]({"template_data": template_data},
|
||||
path or template_data.path)
|
||||
|
||||
def installTranslations(self):
|
||||
# TODO: support multi translation
|
||||
# for now, only translations in sat_templates are handled
|
||||
self.translations = {}
|
||||
for site_key, site_path in self.sites_paths.iteritems():
|
||||
site_prefix = u"[{}] ".format(site_key) if site_key else u''
|
||||
for site_key, site_path in self.sites_paths.items():
|
||||
site_prefix = "[{}] ".format(site_key) if site_key else ''
|
||||
i18n_dir = os.path.join(site_path, "i18n")
|
||||
for lang_dir in os.listdir(i18n_dir):
|
||||
lang_path = os.path.join(i18n_dir, lang_dir)
|
||||
|
|
@ -439,13 +439,13 @@ class Renderer(object):
|
|||
translations.merge(support.Translations(f, "sat"))
|
||||
except EnvironmentError:
|
||||
log.error(
|
||||
_(u"Can't find template translation at {path}").format(
|
||||
_("Can't find template translation at {path}").format(
|
||||
path=po_path))
|
||||
except UnknownLocaleError as e:
|
||||
log.error(_(u"{site}Invalid locale name: {msg}").format(
|
||||
log.error(_("{site}Invalid locale name: {msg}").format(
|
||||
site=site_prefix, msg=e))
|
||||
else:
|
||||
log.info(_(u"{site}loaded {lang} templates translations").format(
|
||||
log.info(_("{site}loaded {lang} templates translations").format(
|
||||
site = site_prefix,
|
||||
lang=lang_dir))
|
||||
|
||||
|
|
@ -458,7 +458,7 @@ class Renderer(object):
|
|||
self.env.install_null_translations(True)
|
||||
# we generate a tuple of locales ordered by display name that templates can access
|
||||
# through the "locales" variable
|
||||
self.locales = tuple(sorted(self.translations.keys(),
|
||||
self.locales = tuple(sorted(list(self.translations.keys()),
|
||||
key=lambda l: l.language_name.lower()))
|
||||
|
||||
|
||||
|
|
@ -476,21 +476,21 @@ class Renderer(object):
|
|||
try:
|
||||
locale = Locale.parse(locale_str)
|
||||
except ValueError as e:
|
||||
log.warning(_(u"invalid locale value: {msg}").format(msg=e))
|
||||
log.warning(_("invalid locale value: {msg}").format(msg=e))
|
||||
locale_str = self._locale_str = C.DEFAULT_LOCALE
|
||||
locale = Locale.parse(locale_str)
|
||||
|
||||
locale_str = unicode(locale)
|
||||
locale_str = str(locale)
|
||||
if locale_str != C.DEFAULT_LOCALE:
|
||||
try:
|
||||
translations = self.translations[locale]
|
||||
except KeyError:
|
||||
log.warning(_(u"Can't find locale {locale}".format(locale=locale)))
|
||||
log.warning(_("Can't find locale {locale}".format(locale=locale)))
|
||||
locale_str = C.DEFAULT_LOCALE
|
||||
locale = Locale.parse(self._locale_str)
|
||||
else:
|
||||
self.env.install_gettext_translations(translations, True)
|
||||
log.debug(_(u"Switched to {lang}").format(lang=locale.english_name))
|
||||
log.debug(_("Switched to {lang}").format(lang=locale.english_name))
|
||||
|
||||
if locale_str == C.DEFAULT_LOCALE:
|
||||
self.env.install_null_translations(True)
|
||||
|
|
@ -509,7 +509,7 @@ class Renderer(object):
|
|||
site, theme, __ = self.env.loader.parse_template(template)
|
||||
if site is None:
|
||||
# absolute template
|
||||
return u"", os.path.dirname(template)
|
||||
return "", os.path.dirname(template)
|
||||
try:
|
||||
site_root_dir = self.sites_paths[site]
|
||||
except KeyError:
|
||||
|
|
@ -533,9 +533,9 @@ class Renderer(object):
|
|||
if template_data.site is None:
|
||||
# we have and absolue path
|
||||
if (not template_data.theme is None
|
||||
or not template_data.path.startswith(u'/')):
|
||||
or not template_data.path.startswith('/')):
|
||||
raise exceptions.InternalError(
|
||||
u"invalid template data, was expecting absolute URL")
|
||||
"invalid template data, was expecting absolute URL")
|
||||
static_dir = os.path.dirname(template_data.path)
|
||||
file_path = os.path.join(static_dir, filename)
|
||||
if os.path.exists(file_path):
|
||||
|
|
@ -562,11 +562,11 @@ class Renderer(object):
|
|||
@param css_files_noscript(list): list to fill of relative path to found css file
|
||||
with "_noscript" suffix
|
||||
"""
|
||||
name = name_root + u".css"
|
||||
name = name_root + ".css"
|
||||
css_path = self.getStaticPath(template_data, name)
|
||||
if css_path is not None:
|
||||
css_files.append(self.getFrontURL(css_path))
|
||||
noscript_name = name_root + u"_noscript.css"
|
||||
noscript_name = name_root + "_noscript.css"
|
||||
noscript_path = self.getStaticPath(template_data, noscript_name)
|
||||
if noscript_path is not None:
|
||||
css_files_noscript.append(self.getFrontURL(noscript_path))
|
||||
|
|
@ -600,18 +600,18 @@ class Renderer(object):
|
|||
# TODO: some caching would be nice
|
||||
css_files = []
|
||||
css_files_noscript = []
|
||||
path_elems = template_data.path.split(u'/')
|
||||
path_elems = template_data.path.split('/')
|
||||
path_elems[-1] = os.path.splitext(path_elems[-1])[0]
|
||||
|
||||
css_path = self.getStaticPath(template_data, u'fonts.css')
|
||||
css_path = self.getStaticPath(template_data, 'fonts.css')
|
||||
if css_path is not None:
|
||||
css_files.append(self.getFrontURL(css_path))
|
||||
|
||||
for name_root in (u'styles', u'styles_extra', u'highlight'):
|
||||
for name_root in ('styles', 'styles_extra', 'highlight'):
|
||||
self._appendCSSPaths(template_data, css_files, css_files_noscript, name_root)
|
||||
|
||||
for idx in xrange(len(path_elems)):
|
||||
name_root = u"_".join(path_elems[:idx+1])
|
||||
for idx in range(len(path_elems)):
|
||||
name_root = "_".join(path_elems[:idx+1])
|
||||
self._appendCSSPaths(template_data, css_files, css_files_noscript, name_root)
|
||||
|
||||
return css_files, css_files_noscript
|
||||
|
|
@ -624,10 +624,10 @@ class Renderer(object):
|
|||
|
||||
This default method return absolute full path
|
||||
"""
|
||||
template_data = ctx[u'template_data']
|
||||
template_data = ctx['template_data']
|
||||
if template_data.site is None:
|
||||
assert template_data.theme is None
|
||||
assert template_data.path.startswith(u"/")
|
||||
assert template_data.path.startswith("/")
|
||||
return os.path.join(os.path.dirname(template_data.path, relative_url))
|
||||
|
||||
site_root_dir = self.sites_paths[template_data.site]
|
||||
|
|
@ -638,25 +638,25 @@ class Renderer(object):
|
|||
def _next_gidx(self, ctx, value):
|
||||
"""Use next current global index as suffix"""
|
||||
next_ = ctx["gidx"].next(value)
|
||||
return value if next_ == 0 else u"{}_{}".format(value, next_)
|
||||
return value if next_ == 0 else "{}_{}".format(value, next_)
|
||||
|
||||
@contextfilter
|
||||
def _cur_gidx(self, ctx, value):
|
||||
"""Use current current global index as suffix"""
|
||||
current = ctx["gidx"].current(value)
|
||||
return value if not current else u"{}_{}".format(value, current)
|
||||
return value if not current else "{}_{}".format(value, current)
|
||||
|
||||
def _date_fmt(self, timestamp, fmt="short", date_only=False, auto_limit=None,
|
||||
auto_old_fmt=None):
|
||||
if is_undefined(fmt):
|
||||
fmt = u"short"
|
||||
fmt = "short"
|
||||
try:
|
||||
return date_utils.date_fmt(
|
||||
timestamp, fmt, date_only, auto_limit, auto_old_fmt,
|
||||
locale_str = self._locale_str
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning(_(u"Can't parse date: {msg}").format(msg=e))
|
||||
log.warning(_("Can't parse date: {msg}").format(msg=e))
|
||||
return timestamp
|
||||
|
||||
def attr_escape(self, text):
|
||||
|
|
@ -664,7 +664,7 @@ class Renderer(object):
|
|||
|
||||
remove spaces, and put in lower case
|
||||
"""
|
||||
return RE_ATTR_ESCAPE.sub(u"_", text.strip().lower())[:50]
|
||||
return RE_ATTR_ESCAPE.sub("_", text.strip().lower())[:50]
|
||||
|
||||
def _xmlui_class(self, xmlui_item, fields):
|
||||
"""return classes computed from XMLUI fields name
|
||||
|
|
@ -683,10 +683,10 @@ class Renderer(object):
|
|||
classes.append(escaped_name + "_" + self.attr_escape(value))
|
||||
except KeyError:
|
||||
log.debug(
|
||||
_(u'ignoring field "{name}": it doesn\'t exists').format(name=name)
|
||||
_('ignoring field "{name}": it doesn\'t exists').format(name=name)
|
||||
)
|
||||
continue
|
||||
return u" ".join(classes) or None
|
||||
return " ".join(classes) or None
|
||||
|
||||
@contextfilter
|
||||
def _item_filter(self, ctx, item, filters):
|
||||
|
|
@ -709,8 +709,8 @@ class Renderer(object):
|
|||
if filter_ is None:
|
||||
return value
|
||||
elif isinstance(filter_, dict):
|
||||
filters_args = filter_.get(u"filters_args")
|
||||
for idx, f_name in enumerate(filter_.get(u"filters", [])):
|
||||
filters_args = filter_.get("filters_args")
|
||||
for idx, f_name in enumerate(filter_.get("filters", [])):
|
||||
kwargs = filters_args[idx] if filters_args is not None else {}
|
||||
filter_func = self.env.filters[f_name]
|
||||
try:
|
||||
|
|
@ -722,7 +722,7 @@ class Renderer(object):
|
|||
value = filter_func(ctx.eval_ctx, value, **kwargs)
|
||||
else:
|
||||
value = filter_func(value, **kwargs)
|
||||
template = filter_.get(u"template")
|
||||
template = filter_.get("template")
|
||||
if template:
|
||||
# format will return a string, so we need to check first
|
||||
# if the value is safe or not, and re-mark it after formatting
|
||||
|
|
@ -745,7 +745,7 @@ class Renderer(object):
|
|||
if template is None:
|
||||
return value
|
||||
# jinja use string when no special char is used, so we have to convert to unicode
|
||||
return unicode(template).format(value=value, **kwargs)
|
||||
return str(template).format(value=value, **kwargs)
|
||||
|
||||
def _dict_ext(self, source_dict, extra_dict, key=None):
|
||||
"""extend source_dict with extra dict and return the result
|
||||
|
|
@ -813,23 +813,23 @@ class Renderer(object):
|
|||
)
|
||||
defs_elt = etree.SubElement(svg_elt, "defs")
|
||||
for name in names:
|
||||
path = os.path.join(self.icons_path, name + u".svg")
|
||||
path = os.path.join(self.icons_path, name + ".svg")
|
||||
icon_svg_elt = etree.parse(path).getroot()
|
||||
# we use icon name as id, so we can retrieve them easily
|
||||
icon_svg_elt.set("id", name)
|
||||
if not icon_svg_elt.tag == "{http://www.w3.org/2000/svg}svg":
|
||||
raise exceptions.DataError(u"invalid SVG element")
|
||||
raise exceptions.DataError("invalid SVG element")
|
||||
defs_elt.append(icon_svg_elt)
|
||||
return safe(etree.tostring(svg_elt, encoding="unicode"))
|
||||
|
||||
def _icon_use(self, name, cls=""):
|
||||
return safe(u'<svg class="svg-icon{cls}" xmlns="http://www.w3.org/2000/svg" '
|
||||
u'viewBox="0 0 100 100">\n'
|
||||
u' <use href="#{name}"/>'
|
||||
u'</svg>\n'.format(name=name, cls=(" " + cls) if cls else ""))
|
||||
return safe('<svg class="svg-icon{cls}" xmlns="http://www.w3.org/2000/svg" '
|
||||
'viewBox="0 0 100 100">\n'
|
||||
' <use href="#{name}"/>'
|
||||
'</svg>\n'.format(name=name, cls=(" " + cls) if cls else ""))
|
||||
|
||||
def render(self, template, site=None, theme=None, locale=C.DEFAULT_LOCALE,
|
||||
media_path=u"", css_files=None, css_inline=False, **kwargs):
|
||||
media_path="", css_files=None, css_inline=False, **kwargs):
|
||||
"""Render a template
|
||||
|
||||
@param template(unicode): template to render (e.g. blog/articles.html)
|
||||
|
|
@ -847,21 +847,21 @@ class Renderer(object):
|
|||
@param **kwargs: variable to transmit to the template
|
||||
"""
|
||||
if not template:
|
||||
raise ValueError(u"template can't be empty")
|
||||
raise ValueError("template can't be empty")
|
||||
if site is not None or theme is not None:
|
||||
# user wants to set site and/or theme, so we add it to the template path
|
||||
if site is None:
|
||||
site = u''
|
||||
site = ''
|
||||
if theme is None:
|
||||
theme = C.TEMPLATE_THEME_DEFAULT
|
||||
if template[0] == u"(":
|
||||
if template[0] == "(":
|
||||
raise ValueError(
|
||||
u"you can't specify site or theme in template path and in argument "
|
||||
u"at the same time"
|
||||
"you can't specify site or theme in template path and in argument "
|
||||
"at the same time"
|
||||
)
|
||||
|
||||
template_data = TemplateData(site, theme, template)
|
||||
template = u"({site}/{theme}){template}".format(
|
||||
template = "({site}/{theme}){template}".format(
|
||||
site=site, theme=theme, template=template)
|
||||
else:
|
||||
template_data = self.env.loader.parse_template(template)
|
||||
|
|
@ -883,15 +883,15 @@ class Renderer(object):
|
|||
|
||||
if css_inline:
|
||||
css_contents = []
|
||||
for files, suffix in ((css_files, u""),
|
||||
(css_files_noscript, u"_noscript")):
|
||||
for files, suffix in ((css_files, ""),
|
||||
(css_files_noscript, "_noscript")):
|
||||
site_root_dir = self.sites_paths[template_data.site]
|
||||
for css_file in files:
|
||||
css_file_path = os.path.join(site_root_dir, css_file)
|
||||
with open(css_file_path) as f:
|
||||
css_contents.append(f.read())
|
||||
if css_contents:
|
||||
kwargs[u"css_content" + suffix] = u"\n".join(css_contents)
|
||||
kwargs["css_content" + suffix] = "\n".join(css_contents)
|
||||
|
||||
scripts_handler = ScriptsHandler(self, template_data)
|
||||
self.setLocale(locale)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SAT: a jabber client
|
||||
|
|
@ -39,7 +39,7 @@ except ImportError:
|
|||
|
||||
|
||||
class Widget(object):
|
||||
category = u"widget"
|
||||
category = "widget"
|
||||
type = None
|
||||
enabled = True
|
||||
read_only = True
|
||||
|
|
@ -103,11 +103,11 @@ class OptionsWidget(Widget):
|
|||
|
||||
@property
|
||||
def inline(self):
|
||||
return u"inline" in self.style
|
||||
return "inline" in self.style
|
||||
|
||||
@property
|
||||
def no_select(self):
|
||||
return u"noselect" in self.style
|
||||
return "noselect" in self.style
|
||||
|
||||
|
||||
class EmptyWidget(xmlui.EmptyWidget, Widget):
|
||||
|
|
@ -116,11 +116,11 @@ class EmptyWidget(xmlui.EmptyWidget, Widget):
|
|||
|
||||
|
||||
class TextWidget(xmlui.TextWidget, ValueWidget):
|
||||
type = u"text"
|
||||
type = "text"
|
||||
|
||||
|
||||
class LabelWidget(xmlui.LabelWidget, ValueWidget):
|
||||
type = u"label"
|
||||
type = "label"
|
||||
|
||||
@property
|
||||
def for_name(self):
|
||||
|
|
@ -131,19 +131,19 @@ class LabelWidget(xmlui.LabelWidget, ValueWidget):
|
|||
|
||||
|
||||
class StringWidget(xmlui.StringWidget, InputWidget):
|
||||
type = u"string"
|
||||
type = "string"
|
||||
|
||||
|
||||
class JidInputWidget(xmlui.JidInputWidget, StringWidget):
|
||||
type = u"jid"
|
||||
type = "jid"
|
||||
|
||||
|
||||
class TextBoxWidget(xmlui.TextWidget, InputWidget):
|
||||
type = u"textbox"
|
||||
type = "textbox"
|
||||
|
||||
|
||||
class XHTMLBoxWidget(xmlui.XHTMLBoxWidget, InputWidget):
|
||||
type = u"xhtmlbox"
|
||||
type = "xhtmlbox"
|
||||
|
||||
def __init__(self, xmlui_parent, value, read_only=False):
|
||||
# XXX: XHTMLBoxWidget value must be cleaned (harmful XHTML must be removed)
|
||||
|
|
@ -154,14 +154,14 @@ class XHTMLBoxWidget(xmlui.XHTMLBoxWidget, InputWidget):
|
|||
|
||||
|
||||
class ListWidget(xmlui.ListWidget, OptionsWidget):
|
||||
type = u"list"
|
||||
type = "list"
|
||||
|
||||
|
||||
## Containers ##
|
||||
|
||||
|
||||
class Container(object):
|
||||
category = u"container"
|
||||
category = "container"
|
||||
type = None
|
||||
|
||||
def __init__(self, xmlui_parent):
|
||||
|
|
@ -179,15 +179,15 @@ class Container(object):
|
|||
|
||||
|
||||
class VerticalContainer(xmlui.VerticalContainer, Container):
|
||||
type = u"vertical"
|
||||
type = "vertical"
|
||||
|
||||
|
||||
class PairsContainer(xmlui.PairsContainer, Container):
|
||||
type = u"pairs"
|
||||
type = "pairs"
|
||||
|
||||
|
||||
class LabelContainer(xmlui.PairsContainer, Container):
|
||||
type = u"label"
|
||||
type = "label"
|
||||
|
||||
|
||||
## Factory ##
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/env python2
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SAT: a jabber client
|
||||
|
|
@ -19,8 +19,8 @@
|
|||
|
||||
""" XMPP uri parsing tools """
|
||||
|
||||
import urlparse
|
||||
import urllib
|
||||
import urllib.parse
|
||||
import urllib.request, urllib.parse, urllib.error
|
||||
|
||||
# FIXME: basic implementation, need to follow RFC 5122
|
||||
|
||||
|
|
@ -40,64 +40,64 @@ def parseXMPPUri(uri):
|
|||
id: id of the element (item for pubsub)
|
||||
@raise ValueError: the scheme is not xmpp
|
||||
"""
|
||||
uri_split = urlparse.urlsplit(uri.encode("utf-8"))
|
||||
uri_split = urllib.parse.urlsplit(uri)
|
||||
if uri_split.scheme != "xmpp":
|
||||
raise ValueError(u"this is not a XMPP URI")
|
||||
raise ValueError("this is not a XMPP URI")
|
||||
|
||||
# XXX: we don't use jid.JID for path as it can be used both in backend and frontend
|
||||
# which may use different JID classes
|
||||
data = {u"path": urllib.unquote(uri_split.path).decode("utf-8")}
|
||||
data = {"path": urllib.parse.unquote(uri_split.path)}
|
||||
|
||||
query_end = uri_split.query.find(";")
|
||||
query_type = uri_split.query[:query_end]
|
||||
if query_end == -1 or "=" in query_type:
|
||||
raise ValueError("no query type, invalid XMPP URI")
|
||||
|
||||
pairs = urlparse.parse_qs(uri_split.geturl())
|
||||
for k, v in pairs.items():
|
||||
pairs = urllib.parse.parse_qs(uri_split.geturl())
|
||||
for k, v in list(pairs.items()):
|
||||
if len(v) != 1:
|
||||
raise NotImplementedError(u"multiple values not managed")
|
||||
raise NotImplementedError("multiple values not managed")
|
||||
if k in ("path", "type", "sub_type"):
|
||||
raise NotImplementedError(u"reserved key used in URI, this is not supported")
|
||||
data[k.decode("utf-8")] = urllib.unquote(v[0]).decode("utf-8")
|
||||
raise NotImplementedError("reserved key used in URI, this is not supported")
|
||||
data[k] = urllib.parse.unquote(v[0])
|
||||
|
||||
if query_type:
|
||||
data[u"type"] = query_type.decode("utf-8")
|
||||
elif u"node" in data:
|
||||
data[u"type"] = u"pubsub"
|
||||
data["type"] = query_type
|
||||
elif "node" in data:
|
||||
data["type"] = "pubsub"
|
||||
else:
|
||||
data[u"type"] = ""
|
||||
data["type"] = ""
|
||||
|
||||
if u"node" in data:
|
||||
if data[u"node"].startswith(u"urn:xmpp:microblog:"):
|
||||
data[u"sub_type"] = "microblog"
|
||||
if "node" in data:
|
||||
if data["node"].startswith("urn:xmpp:microblog:"):
|
||||
data["sub_type"] = "microblog"
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def addPairs(uri, pairs):
|
||||
for k, v in pairs.iteritems():
|
||||
for k, v in pairs.items():
|
||||
uri.append(
|
||||
u";"
|
||||
+ urllib.quote_plus(k.encode("utf-8"))
|
||||
+ u"="
|
||||
+ urllib.quote_plus(v.encode("utf-8"))
|
||||
";"
|
||||
+ urllib.parse.quote_plus(k.encode("utf-8"))
|
||||
+ "="
|
||||
+ urllib.parse.quote_plus(v.encode("utf-8"))
|
||||
)
|
||||
|
||||
|
||||
def buildXMPPUri(type_, **kwargs):
|
||||
uri = [u"xmpp:"]
|
||||
uri = ["xmpp:"]
|
||||
subtype = kwargs.pop("subtype", None)
|
||||
path = kwargs.pop("path")
|
||||
uri.append(urllib.quote_plus(path.encode("utf-8")).replace(u"%40", "@"))
|
||||
uri.append(urllib.parse.quote_plus(path.encode("utf-8")).replace("%40", "@"))
|
||||
|
||||
if type_ == u"pubsub":
|
||||
if type_ == "pubsub":
|
||||
if subtype == "microblog" and not kwargs.get("node"):
|
||||
kwargs[u"node"] = "urn:xmpp:microblog:0"
|
||||
kwargs["node"] = "urn:xmpp:microblog:0"
|
||||
if kwargs:
|
||||
uri.append(u"?")
|
||||
uri.append("?")
|
||||
addPairs(uri, kwargs)
|
||||
else:
|
||||
raise NotImplementedError(u"{type_} URI are not handled yet".format(type_=type_))
|
||||
raise NotImplementedError("{type_} URI are not handled yet".format(type_=type_))
|
||||
|
||||
return u"".join(uri)
|
||||
return "".join(uri)
|
||||
|
|
|
|||
Loading…
Reference in a new issue