Example #1
0
    def __init__(self, schema, netloc, port, path, query, fragment, userinfo):
        self._strict = False

        if port:
            netloc += ':{}'.format(port)
        if userinfo:
            netloc = yarl.quote(
                userinfo, safe='@:',
                protected=':', strict=False) + '@' + netloc

        if path:
            path = yarl.quote(path, safe='@:', protected='/', strict=False)

        if query:
            query = yarl.quote(
                query, safe='=+&?/:@',
                protected=yarl.PROTECT_CHARS, qs=True, strict=False)

        if fragment:
            fragment = yarl.quote(fragment, safe='?/:@', strict=False)

        self._val = SplitResult(
            schema or '',  # scheme
            netloc=netloc, path=path, query=query, fragment=fragment)
        self._cache = {}
Example #2
0
    def __init__(self, schema, netloc, port, path, query, fragment, userinfo):
        self._strict = False

        if port:
            netloc += ':{}'.format(port)
        if userinfo:
            netloc = yarl.quote(
                userinfo, safe='@:', protected=':',
                strict=False) + '@' + netloc

        if path:
            path = yarl.quote(path, safe='@:', protected='/', strict=False)

        if query:
            query = yarl.quote(query,
                               safe='=+&?/:@',
                               protected=yarl.PROTECT_CHARS,
                               qs=True,
                               strict=False)

        if fragment:
            fragment = yarl.quote(fragment, safe='?/:@', strict=False)

        self._val = SplitResult(
            schema or '',  # scheme
            netloc=netloc,
            path=path,
            query=query,
            fragment=fragment)
        self._cache = {}
 def __init__(self, arg1051, arg1000, arg682, arg2280, arg192, arg1897,
              arg551):
     self.attribute1287 = False
     if arg682:
         arg1000 += ':{}'.format(arg682)
     if arg551:
         arg1000 = (
             (yarl.quote(arg551, safe='@:', protected=':', strict=False) +
              '@') + arg1000)
     if arg2280:
         arg2280 = yarl.quote(arg2280,
                              safe='@:',
                              protected='/',
                              strict=False)
     if arg192:
         arg192 = yarl.quote(arg192,
                             safe='=+&?/:@',
                             protected=yarl.PROTECT_CHARS,
                             qs=True,
                             strict=False)
     if arg1897:
         arg1897 = yarl.quote(arg1897, safe='?/:@', strict=False)
     self.attribute914 = SplitResult((schema or ''),
                                     netloc=arg1000,
                                     path=arg2280,
                                     query=arg192,
                                     fragment=arg1897)
     self.attribute233 = {}
Example #4
0
 def url_for(self, *, filename):
     if isinstance(filename, Path):
         filename = str(filename)
     while filename.startswith('/'):
         filename = filename[1:]
     url = self._prefix + quote(filename, safe='/')
     return URL(url)
Example #5
0
 def url(self, *, filename, query=None):
     if isinstance(filename, Path):
         filename = str(filename)
     while filename.startswith('/'):
         filename = filename[1:]
     url = self._prefix + quote(filename, safe='/')
     return self._append_query(url, query)
Example #6
0
 def url_for(self, *, filename):
     if isinstance(filename, Path):
         filename = str(filename)
     while filename.startswith('/'):
         filename = filename[1:]
     url = self._prefix + quote(filename, safe='/')
     return URL(url)
Example #7
0
    def record(self, record=True, tag=None):
        """Enable/disable recording.

        Return a coroutine.
        """
        path = '/startvideo?force=1' if record else '/stopvideo?force=1'
        if record and tag is not None:
            path = '/startvideo?force=1&tag={}'.format(yarl.quote(tag))

        return self._request(path)
Example #8
0
    def async_get_tts_audio(self, message, language=None):
        """Load TTS from google."""
        from gtts_token import gtts_token

        token = gtts_token.Token()
        websession = async_get_clientsession(self.hass)
        message_parts = self._split_message_to_parts(message)

        # If language is not specified or is not supported - use the language
        # from the config.
        if language not in SUPPORT_LANGUAGES:
            language = self.language

        data = b''
        for idx, part in enumerate(message_parts):
            part_token = yield from self.hass.loop.run_in_executor(
                None, token.calculate_token, part)

            url_param = {
                'ie': 'UTF-8',
                'tl': language,
                'q': yarl.quote(part),
                'tk': part_token,
                'total': len(message_parts),
                'idx': idx,
                'client': 'tw-ob',
                'textlen': len(part),
            }

            request = None
            try:
                with async_timeout.timeout(10, loop=self.hass.loop):
                    request = yield from websession.get(GOOGLE_SPEECH_URL,
                                                        params=url_param,
                                                        headers=self.headers)

                    if request.status != 200:
                        _LOGGER.error("Error %d on load url %s",
                                      request.status, request.url)
                        return (None, None)
                    data += yield from request.read()

            except (asyncio.TimeoutError, aiohttp.errors.ClientError):
                _LOGGER.error("Timeout for google speech.")
                return (None, None)

            finally:
                if request is not None:
                    yield from request.release()

        return ("mp3", data)
Example #9
0
    def add_resource(self, path, *, name=None):
        if path and not path.startswith('/'):
            raise ValueError("path should be started with / or be empty")
        if not ('{' in path or '}' in path or self.ROUTE_RE.search(path)):
            resource = PlainResource(quote(path, safe='/'), name=name)
            self._reg_resource(resource)
            return resource

        pattern = ''
        formatter = ''
        for part in self.ROUTE_RE.split(path):
            match = self.DYN.fullmatch(part)
            if match:
                pattern += '(?P<{}>{})'.format(match.group('var'), self.GOOD)
                formatter += '{' + match.group('var') + '}'
                continue

            match = self.DYN_WITH_RE.fullmatch(part)
            if match:
                pattern += '(?P<{var}>{re})'.format(**match.groupdict())
                formatter += '{' + match.group('var') + '}'
                continue

            if '{' in part or '}' in part:
                raise ValueError("Invalid path '{}'['{}']".format(path, part))

            part = quote(part, safe='/')
            formatter += part
            pattern += re.escape(part)

        try:
            compiled = re.compile(pattern)
        except re.error as exc:
            raise ValueError("Bad pattern '{}': {}".format(pattern,
                                                           exc)) from None
        resource = DynamicResource(compiled, formatter, name=name)
        self._reg_resource(resource)
        return resource
Example #10
0
    def add_resource(self, path, *, name=None):
        if not path.startswith('/'):
            raise ValueError("path should be started with /")
        if not ('{' in path or '}' in path or self.ROUTE_RE.search(path)):
            resource = PlainResource(quote(path, safe='/'), name=name)
            self._reg_resource(resource)
            return resource

        pattern = ''
        formatter = ''
        for part in self.ROUTE_RE.split(path):
            match = self.DYN.match(part)
            if match:
                pattern += '(?P<{}>{})'.format(match.group('var'), self.GOOD)
                formatter += '{' + match.group('var') + '}'
                continue

            match = self.DYN_WITH_RE.match(part)
            if match:
                pattern += '(?P<{var}>{re})'.format(**match.groupdict())
                formatter += '{' + match.group('var') + '}'
                continue

            if '{' in part or '}' in part:
                raise ValueError("Invalid path '{}'['{}']".format(path, part))

            part = quote(part, safe='/')
            formatter += part
            pattern += re.escape(part)

        try:
            compiled = re.compile('^' + pattern + '$')
        except re.error as exc:
            raise ValueError(
                "Bad pattern '{}': {}".format(pattern, exc)) from None
        resource = DynamicResource(compiled, formatter, name=name)
        self._reg_resource(resource)
        return resource
Example #11
0
    def async_get_tts_audio(self, message, language, options=None):
        """Load TTS from google."""
        from gtts_token import gtts_token

        token = gtts_token.Token()
        websession = async_get_clientsession(self.hass)
        message_parts = self._split_message_to_parts(message)

        data = b''
        for idx, part in enumerate(message_parts):
            part_token = yield from self.hass.loop.run_in_executor(
                None, token.calculate_token, part)

            url_param = {
                'ie': 'UTF-8',
                'tl': language,
                'q': yarl.quote(part),
                'tk': part_token,
                'total': len(message_parts),
                'idx': idx,
                'client': 'tw-ob',
                'textlen': len(part),
            }

            request = None
            try:
                with async_timeout.timeout(10, loop=self.hass.loop):
                    request = yield from websession.get(
                        GOOGLE_SPEECH_URL, params=url_param,
                        headers=self.headers
                    )

                    if request.status != 200:
                        _LOGGER.error("Error %d on load url %s",
                                      request.status, request.url)
                        return (None, None)
                    data += yield from request.read()

            except (asyncio.TimeoutError, aiohttp.errors.ClientError):
                _LOGGER.error("Timeout for google speech.")
                return (None, None)

            finally:
                if request is not None:
                    yield from request.release()

        return ("mp3", data)
Example #12
0
    def async_get_tts_audio(self, message, language, options=None):
        """Load TTS from google."""
        from gtts_token import gtts_token

        token = gtts_token.Token()
        websession = async_get_clientsession(self.hass)
        message_parts = self._split_message_to_parts(message)

        data = b''
        for idx, part in enumerate(message_parts):
            part_token = yield from self.hass.loop.run_in_executor(
                None, token.calculate_token, part)

            url_param = {
                'ie': 'UTF-8',
                'tl': language,
                'q': yarl.quote(part, strict=False),
                'tk': part_token,
                'total': len(message_parts),
                'idx': idx,
                'client': 'tw-ob',
                'textlen': len(part),
            }

            try:
                with async_timeout.timeout(10, loop=self.hass.loop):
                    request = yield from websession.get(
                        GOOGLE_SPEECH_URL, params=url_param,
                        headers=self.headers
                    )

                    if request.status != 200:
                        _LOGGER.error("Error %d on load url %s",
                                      request.status, request.url)
                        return (None, None)
                    data += yield from request.read()

            except (asyncio.TimeoutError, aiohttp.ClientError):
                _LOGGER.error("Timeout for google speech.")
                return (None, None)

        return ("mp3", data)
Example #13
0
    def add_static(self, prefix, path, *, name=None, expect_handler=None,
                   chunk_size=256*1024, response_factory=StreamResponse,
                   show_index=False):
        """Add static files view.

        prefix - url prefix
        path - folder with files

        """
        # TODO: implement via PrefixedResource, not ResourceAdapter
        assert prefix.startswith('/')
        if not prefix.endswith('/'):
            prefix += '/'
        prefix = quote(prefix, safe='/')
        route = StaticRoute(name, prefix, path,
                            expect_handler=expect_handler,
                            chunk_size=chunk_size,
                            response_factory=response_factory,
                            show_index=show_index)
        self.register_route(route)
        return route
Example #14
0
 def __init__(self, prefix, *, name=None):
     assert not prefix or prefix.startswith('/'), prefix
     assert prefix in ('', '/') or not prefix.endswith('/'), prefix
     super().__init__(name=name)
     self._prefix = quote(prefix, safe='/')
Example #15
0
 def __init__(self, prefix, *, name=None):
     assert not prefix or prefix.startswith('/'), prefix
     assert prefix in ('', '/') or not prefix.endswith('/'), prefix
     super().__init__(name=name)
     self._prefix = quote(prefix, safe='/')
Example #16
0
 def __init__(self, prefix, *, name=None):
     assert prefix.startswith('/'), prefix
     assert prefix.endswith('/'), prefix
     super().__init__(name=name)
     self._prefix = quote(prefix, safe='/')
     self._prefix_len = len(self._prefix)
Example #17
0
 def __init__(self, prefix, *, name=None):
     assert prefix.startswith('/'), prefix
     assert prefix.endswith('/'), prefix
     super().__init__(name=name)
     self._prefix = quote(prefix, safe='/')
     self._prefix_len = len(self._prefix)