Exemplo n.º 1
0
    def __get_post_data(self, method):
        raw = method._to_raw()
        if self._debug:
            log.debug('CMD: %s', raw)

        use_multipart = False
        for k in list(raw.keys()):
            if issubclass(raw[k].__class__, io.IOBase):
                use_multipart = True
                break

        if not use_multipart:
            return raw

        data = FormData()
        for k in list(raw.keys()):
            if issubclass(raw[k].__class__, io.IOBase):
                try:
                    filename = os.path.basename(raw[k].name)
                except AttributeError:
                    filename = None
                data.add_field(k, raw[k], filename=filename)
            else:
                data.add_field(k, str(raw[k]))
        return data
Exemplo n.º 2
0
    def _sendfile(self, inputfile, filetype, params):
        method = {'photo':    'sendPhoto',
                  'audio':    'sendAudio',
                  'document': 'sendDocument',
                  'sticker':  'sendSticker',
                  'video':    'sendVideo',
                  'voice':    'sendVoice',}[filetype]

        if _isstring(inputfile):
            params[filetype] = inputfile
            return (yield from _post(self._methodurl(method), self._http_timeout,
                                     data=_rectify(params)))
        else:
            if isinstance(inputfile, tuple):
                if len(inputfile) == 2:
                    filename, fileobj = inputfile
                else:
                    raise ValueError('Tuple must have exactly 2 elements: filename, fileobj')
            else:
                filename, fileobj = guess_filename(inputfile) or filetype, inputfile

            data = FormData()
            for key,value in _rectify(params).items():
                data.add_field(key, str(value))
            data.add_field(filetype, fileobj, filename=filename)

            return (yield from _post(self._methodurl(method), None,
                                     data=data))
    def __get_post_data(self, method):
        raw = method._to_raw()
        if self._debug:
            log.debug("CMD: %s", raw)

        use_multipart = False
        for k in list(raw.keys()):
            if issubclass(raw[k].__class__, io.IOBase):
                use_multipart = True
                break

        if not use_multipart:
            return raw

        data = FormData()
        for k in list(raw.keys()):
            if issubclass(raw[k].__class__, io.IOBase):
                try:
                    filename = os.path.basename(raw[k].name)
                except AttributeError:
                    filename = None
                data.add_field(k, raw[k], filename=filename)
            else:
                data.add_field(k, str(raw[k]))
        return data
Exemplo n.º 4
0
def test_allows_post_with_url_encoding(app):
    data = FormData()
    data.add_field('query', '{test}')
    _, response = app.client.post(
        uri=url_string(),
        data=data(),
        headers={'content-type': 'application/x-www-form-urlencoded'})

    assert response.status == 200
    assert response_json(response) == {'data': {'test': "Hello World"}}
Exemplo n.º 5
0
async def test_allows_post_with_url_encoding(client, base_url):
    data = FormData()
    data.add_field('query', '{test}')
    response = await client.post(
        base_url,
        data=data(),
        headers={'content-type': 'application/x-www-form-urlencoded'},
    )

    assert await response.json() == {'data': {'test': "Hello World"}}
    assert response.status == 200
Exemplo n.º 6
0
    def remote_post(self, request):
        url = 'http://httpbin.org/post'
        data = FormData()
        data.add_field('file',
                       open('/Users/levi/needle/crispy-sniffle/test.json', 'rb'),
                       filename='test.json',
                       content_type='application/text')

        response = yield from aiohttp.request('POST', url=url, data=data)
        text = yield from response.text()
        return aiohttp.web.Response(text=text, content_type='text/html')
Exemplo n.º 7
0
def convert_online_mp4_to_gif(source_url, fallback_url=False):
    """experimental utility function to convert telegram mp4s back into gifs"""

    config = _telesync_config(tg_bot.ho_bot)

    if "convert-with-gifscom" in config and not config["convert-with-gifscom"]:
        # must be explicitly disabled
        return fallback_url or source_url

    if "convert-with-gifscom" in config and config[
            "convert-with-gifscom"] is not True:
        # api key can be explicitly defined
        api_key = config["convert-with-gifscom"]
    else:
        # an api key isn't required, but...
        # XXX: demo api key from https://gifs.com/
        api_key = "gifs56d63999f0f34"

    # retrieve the source image
    api_request = yield from aiohttp.request('get', source_url)
    raw_image = yield from api_request.read()

    # upload it to gifs.com for conversion

    url = "https://api.gifs.com/media/upload"

    headers = {"Gifs-Api-Key": api_key}
    data = FormData()
    data.add_field('file', raw_image)
    data.add_field('title', 'example.mp4')

    response = yield from aiohttp.post(url, data=data, headers=headers)
    if response.status != 200:
        return fallback_url or source_url

    results = yield from response.json()
    if "success" not in results:
        return fallback_url or source_url

    # return the link to the converted file

    return results["success"]["files"]["gif"]
Exemplo n.º 8
0
def convert_online_mp4_to_gif(source_url, fallback_url=False):
    """experimental utility function to convert telegram mp4s back into gifs"""

    config = _telesync_config(tg_bot.ho_bot)

    if "convert-with-gifscom" in config and not config["convert-with-gifscom"]:
        # must be explicitly disabled
        return fallback_url or source_url

    if "convert-with-gifscom" in config and config["convert-with-gifscom"] is not True:
        # api key can be explicitly defined
        api_key = config["convert-with-gifscom"]
    else:
        # an api key isn't required, but...
        # XXX: demo api key from https://gifs.com/
        api_key = "gifs56d63999f0f34"

    # retrieve the source image
    api_request = yield from aiohttp.request('get', source_url)
    raw_image = yield from api_request.read()

    # upload it to gifs.com for conversion

    url = "https://api.gifs.com/media/upload"

    headers = { "Gifs-Api-Key": api_key }
    data = FormData()
    data.add_field('file', raw_image)
    data.add_field('title', 'example.mp4')

    response = yield from aiohttp.post(url, data=data, headers=headers)
    if response.status != 200:
        return fallback_url or source_url

    results = yield from response.json()
    if "success" not in results:
        return fallback_url or source_url

    # return the link to the converted file

    return results["success"]["files"]["gif"]
Exemplo n.º 9
0
    def __get_post_data(self, method):
        raw = method._to_raw()
        if self._debug:
            log.debug('CMD: %s', raw)

        use_multipart = False
        for k in list(raw.keys()):
            if isinstance(raw[k], BufferedReader):
                use_multipart = True
                break

        if not use_multipart:
            return raw

        data = FormData()
        for k in list(raw.keys()):
            if isinstance(raw[k], BufferedReader):
                filename = os.path.split(raw[k].name)[1]
                data.add_field(k, raw[k].read(), filename=filename)
            else:
                data.add_field(k, str(raw[k]))
        return data
Exemplo n.º 10
0
Arquivo: api.py Projeto: pingiun/tlask
    async def _api_call_upload(self, method, **kwargs):
        if not hasattr(self, 'token'):
            raise RuntimeError("Telegram token not set")
        data = FormData()
        for k, v in kwargs.items():
            if v is not None:
                # Ints and bools need to be converted to strings, but files not
                if type(v) == dict or type(v) == list:
                    v = json.dumps(v)
                if type(v) != str and not hasattr(v, 'read'):
                    v = str(v)
                data.add_field(k, v)

        baseurl = 'https://api.telegram.org/bot' + self.token + '/'

        async with aiohttp.ClientSession() as session:
            async with session.post(baseurl + method, data=data) as response:
                if not response.status == 200:
                    responsetext = await response.text()
                    raise RuntimeError(
                        "Got a {} return status. Telegram error: {}".format(
                            response.status, responsetext))
                jsondata = await response.json()
                return jsondata['result']