def dispatch(self, request, *args, slug=None, **kwargs):
     self.slug = slug
     try:
         self.cookie_data = json.loads(url_unquote(request.COOKIES.get(self.cookie_name, '')))
     except (TypeError, ValueError):
         pass
     return super().dispatch(request, *args, **kwargs)
Example #2
0
    def player_update(self, obj, player):
        # player name
        obj.part_text_set('player_name', player.label or player.name)

        # play/pause button
        if player.playback_status == 'Playing':
            obj.signal_emit('state,set,playing', '')
        else:
            obj.signal_emit('state,set,paused', '')

        # metadata
        txt = ''
        if 'xesam:title' in player.metadata:
            txt += '<title>%s</><br>' % player.metadata['xesam:title']
        if 'xesam:artist' in player.metadata:
            txt += '<tag>by</> %s<br>' % player.metadata['xesam:artist'][0]
        if 'xesam:album' in player.metadata:
            txt += '<tag>from</> %s<br>' % player.metadata['xesam:album']
        obj.part_text_set('metadata', txt)

        # cover image
        img = obj.content_unset('cover.swallow')
        if img: img.delete()

        if 'mpris:artUrl' in player.metadata:
            fname = url_unquote(player.metadata['mpris:artUrl'])
            fname = fname.replace('file://', '')
            try:
                img = evas.FilledImage(obj.evas, file=fname)
                obj.content_set('cover.swallow', img)
            except:
                pass
Example #3
0
def unquote(text):
    """Replace all percent-encoded entities in text."""
    while '%' in text:
        newtext = url_unquote(text)
        if newtext == text:
            break
        text = newtext
    return text
Example #4
0
 def path(self):
     """
     Requested path. This works a bit like the regular path info in
     the WSGI environment, but always include a leading slash, even if
     the URL root is accessed.
     :return:
     """
     return url_unquote(self.environ.get('PATH_INFO', ''))
Example #5
0
def brushinfo_unquote(quoted):
    """Unquote a serialised string value from a brush field.

    >>> brushinfo_unquote(b"foo") == u'foo'
    True
    >>> brushinfo_unquote(b"foo%2fbar%20blah") == u'foo/bar blah'
    True
    >>> expected = u'Have a nice day \u263A'
    >>> brushinfo_unquote(b'Have%20a%20nice%20day%20%E2%98%BA') == expected
    True

    """
    if not isinstance(quoted, bytes):
        raise ValueError("Cann")
    u8bytes = url_unquote(quoted)
    return unicode(u8bytes.decode("utf-8"))
def show_outbound_msg(request, verification_code):
    '''Show the outbound message with the verification code.'''

    try:
        template = 'mail/verified_encrypted.html'
        result_headers = []
        results = []
        error_message = None

        email = request.user.email
        records = history.get_outbound_messages(email)
        if records:
            # narrow the messages to those matching the verification_code
            records = records.filter(verification_code=url_unquote(verification_code))
        if not records:
            try:
                # use the verification_code without unquoting it in case they pasted it into a url field
                records = records.filter(verification_code=verification_code)
            except:
                pass

        if records:
            results, private, private_signed, clear_signed, dkim_signed = summarize_outbound_messages(
                records)
            main_headline, subheadline = get_verify_msg_headlines(
                'sent', private, private_signed, clear_signed, dkim_signed)
        else:
            main_headline = i18n('<font color="red">Not</font> Verified')
            subheadline = i18n('Message not sent privately from {}'.format(email))
            error1 = NOT_SENT_PRIVATELY.format(email=email, verification_code=verification_code)
            error2 = TAMPERED_SENT_WARNING.format(email=email)
            error_message = '{} {}'.format(error1, error2)
            log_message(error_message)

        params = {'email': email,
                  'main_headline': main_headline,
                  'subheadline': subheadline,
                  'results': results,
                  'error_message': error_message}
        response = render_to_response(
            template, params, context_instance=RequestContext(request))
    except Exception:
        record_exception()
        log_message('EXCEPTION - see syr.exception.log for details')
        response = HttpResponseRedirect('/mail/show_encrypted_history/')

    return response
Example #7
0
    def make_environ(self):
        request_url = url_parse(self.path)

        def shutdown_server():
            self.server.shutdown_signal = True

        url_scheme = self.server.ssl_context is None and 'http' or 'https'
        path_info = url_unquote(request_url.path)

        environ = {
            'wsgi.version':         (1, 0),
            'wsgi.url_scheme':      url_scheme,
            'wsgi.input':           self.rfile,
            'wsgi.errors':          sys.stderr,
            'wsgi.multithread':     self.server.multithread,
            'wsgi.multiprocess':    self.server.multiprocess,
            'wsgi.run_once':        False,
            'werkzeug.server.shutdown':
                                    shutdown_server,
            'SERVER_SOFTWARE':      self.server_version,
            'REQUEST_METHOD':       self.command,
            'SCRIPT_NAME':          '',
            'PATH_INFO':            wsgi_encoding_dance(path_info),
            'QUERY_STRING':         wsgi_encoding_dance(request_url.query),
            'CONTENT_TYPE':         self.headers.get('Content-Type', ''),
            'CONTENT_LENGTH':       self.headers.get('Content-Length', ''),
            'REMOTE_ADDR':          self.client_address[0],
            'REMOTE_PORT':          self.client_address[1],
            'SERVER_NAME':          self.server.server_address[0],
            'SERVER_PORT':          str(self.server.server_address[1]),
            'SERVER_PROTOCOL':      self.request_version
        }

        for key, value in self.headers.items():
            key = 'HTTP_' + key.upper().replace('-', '_')
            if key not in ('HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH'):
                environ[key] = value

        if request_url.netloc:
            environ['HTTP_HOST'] = request_url.netloc

        return environ
Example #8
0
def parse_ticket(secret, ticket, ip, digest_algo=DEFAULT_DIGEST):
    """
    Parse the ticket, returning (timestamp, userid, tokens, user_data).

    If the ticket cannot be parsed, ``BadTicket`` will be raised with
    an explanation.
    """
    if isinstance(digest_algo, str):
        # correct specification of digest from hashlib or fail
        digest_algo = getattr(hashlib, digest_algo)
    digest_hexa_size = digest_algo().digest_size * 2
    ticket = ticket.strip('"')
    digest = ticket[:digest_hexa_size]
    try:
        timestamp = int(ticket[digest_hexa_size:digest_hexa_size + 8], 16)
    except ValueError as e:
        raise BadTicket('Timestamp is not a hex integer: %s' % e)
    try:
        userid, data = ticket[digest_hexa_size + 8:].split('!', 1)
    except ValueError:
        raise BadTicket('userid is not followed by !')
    userid = url_unquote(userid)
    if '!' in data:
        tokens, user_data = data.split('!', 1)
    else:
        # @@: Is this the right order?
        tokens = ''
        user_data = data

    expected = calculate_digest(ip, timestamp, secret,
                                userid, tokens, user_data,
                                digest_algo)

    if expected != digest:
        raise BadTicket('Digest signature is not correct',
                        expected=(expected, digest))

    tokens = tokens.split(',')

    return (timestamp, userid, tokens, user_data)
Example #9
0
    def __init__(self, request, panel_classes, global_panel_classes):
        self.panels = []
        self.global_panels = []
        self.request = request
        self.status = 200

        # Panels can be be activated (more features) (e.g. Performace panel)
        pdtb_active = url_unquote(request.cookies.get('pdtb_active', ''))

        activated = pdtb_active.split(';')
        # XXX
        for panel_class in panel_classes:
            panel_inst = panel_class(request)
            if panel_inst.dom_id in activated and panel_inst.has_content:
                panel_inst.is_active = True
            self.panels.append(panel_inst)

        for panel_class in global_panel_classes:
            panel_inst = panel_class(request)
            if panel_inst.dom_id in activated and panel_inst.has_content:
                panel_inst.is_active = True
            self.global_panels.append(panel_inst)
Example #10
0
 def url_unquote_text(v, encoding='utf-8', errors='replace'): # pragma: no cover
     v = url_unquote(v)
     return v.decode(encoding, errors)
Example #11
0
def make_environ(inp, host, port, script_name):
    """
    Take 'inp' as if it were HTTP-speak being received on host:port,
    and parse it into a WSGI-ok environment dictionary.  Return the
    dictionary.

    Set 'SCRIPT_NAME' from the 'script_name' input, and, if present,
    remove it from the beginning of the PATH_INFO variable.
    """
    #
    # parse the input up to the first blank line (or its end).
    #

    environ = {}

    method_line = inp.readline()
    if six.PY3:
        method_line = method_line.decode('ISO-8859-1')

    content_type = None
    content_length = None
    cookies = []

    for line in inp:
        if not line.strip():
            break

        k, v = line.strip().split(b':', 1)
        v = v.lstrip()
        # Make header value a "native" string. PEP 3333 requires that
        # string-like things in headers be of type `str`. Much of the
        # time this isn't a problem but the SimpleCookie library does
        # type checking against `type("")`.
        v = str(v.decode('ISO-8859-1'))

        #
        # take care of special headers, and for the rest, put them
        # into the environ with HTTP_ in front.
        #

        if k.lower() == b'content-type':
            content_type = v
        elif k.lower() == b'content-length':
            content_length = v
        elif k.lower() == b'cookie' or k.lower() == b'cookie2':
            cookies.append(v)
        else:
            h = k.upper()
            h = h.replace(b'-', b'_')
            environ['HTTP_' + h.decode('ISO-8859-1')] = v

        if debuglevel >= 2:
            print('HEADER:', k, v)

    #
    # decode the method line
    #

    if debuglevel >= 2:
        print('METHOD LINE:', method_line)

    method, url, protocol = method_line.split(' ')

    # Store the URI as requested by the user, without modification
    # so that PATH_INFO munging can be corrected.
    environ['REQUEST_URI'] = url
    environ['RAW_URI'] = url

    # clean the script_name off of the url, if it's there.
    if not url.startswith(script_name):
        script_name = ''                # @CTB what to do -- bad URL.  scrap?
    else:
        url = url[len(script_name):]

    url = url.split('?', 1)
    path_info = url_unquote(url[0])
    query_string = ""
    if len(url) == 2:
        query_string = url[1]

    if debuglevel:
        print("method: %s; script_name: %s; path_info: %s; query_string: %s" %
                (method, script_name, path_info, query_string))

    r = inp.read()
    inp = BytesIO(r)

    #
    # fill out our dictionary.
    #

    # In Python3 turn the bytes of the path info into a string of
    # latin-1 code points, because that's what the spec says we must
    # do to be like a server. Later various libraries will be forced
    # to decode and then reencode to get the UTF-8 that everyone
    # wants.
    if six.PY3:
        path_info = path_info.decode('latin-1')

    environ.update({
        "wsgi.version": (1, 0),
        "wsgi.url_scheme": "http",
        "wsgi.input": inp,  # to read for POSTs
        "wsgi.errors": sys.stderr,
        "wsgi.multithread": 0,
        "wsgi.multiprocess": 0,
        "wsgi.run_once": 0,

        "PATH_INFO": path_info,
        "REMOTE_ADDR": '127.0.0.1',
        "REQUEST_METHOD": method,
        "SCRIPT_NAME": script_name,
        "SERVER_NAME": host,
        "SERVER_PORT": port,
        "SERVER_PROTOCOL": protocol,
    })

    #
    # query_string, content_type & length are optional.
    #

    if query_string:
        environ['QUERY_STRING'] = query_string

    if content_type:
        environ['CONTENT_TYPE'] = content_type
        if debuglevel >= 2:
            print('CONTENT-TYPE:', content_type)
    if content_length:
        environ['CONTENT_LENGTH'] = content_length
        if debuglevel >= 2:
            print('CONTENT-LENGTH:', content_length)

    #
    # handle cookies.
    #
    if cookies:
        environ['HTTP_COOKIE'] = "; ".join(cookies)

    if debuglevel:
        print('WSGI environ dictionary:', environ)

    return environ
Example #12
0
 def url_unquote_text(v, encoding="utf-8", errors="replace"):
     v = url_unquote(v)
     return v.decode(encoding, errors)