Ejemplo n.º 1
0
    def get(self, **kwargs):

        shortener = Shortener(self.context)

        # Get the url from the shortener and parse the values.
        url = yield gen.maybe_future(shortener.get(kwargs['key']))

        if not url:
            raise tornado.web.HTTPError(404)

        # Patch the request uri to allow normal thumbor operations
        self.request.uri = urlparse.urlparse(url).path

        options = RequestParser.path_to_parameters(self.request.uri)

        name = os.path.basename(options.get('image', None))
        if name:
            self.set_header(
                'Content-Disposition',
                'inline; filename="{name}"'.format(
                    name=name
                )
            )

        # Call the original ImageHandler.get method to serve the image.
        super(UrlShortenerHandler, self).get(**options)
Ejemplo n.º 2
0
    def post(self, **kwargs):
        self.should_return_image = False

        # URL can be passed as a URL argument or in the body
        url = kwargs['url'] if 'url' in kwargs else kwargs['key']

        if not url:
            logger.error("Couldn't find url param in body or key in URL...")
            raise tornado.web.HTTPError(404)

        options = RequestParser.path_to_parameters(url)

        yield self.check_image(options)

        # We check the status code, if != 200 the image is incorrect, and we shouldn't store the key
        if self.get_status() == 200:
            logger.debug("Image is checked, clearing the response before trying to store...")
            self.clear()
            try:
                shortener = Shortener(self.context)
                key = shortener.generate(url)
                shortener.put(key, url)

                self.write(json.dumps({'key': key}))
                self.set_header("Content-Type", "application/json")
            except Exception as e:
                logger.error("An error occurred while trying to store shortened URL: {error}.".format(error=e.message))
                self.set_status(500)
                self.write(json.dumps({'error': e.message}))
Ejemplo n.º 3
0
    def get(self, **kwargs):
        alias = kwargs['alias']
        img_url = kwargs['img_url']
        long_url = self.storage.get(alias)
        if not all([alias, img_url, long_url]):
            raise tornado.web.HTTPError(404)

        url = '{}/{}'.format(long_url, img_url)
        self.request.uri = urlparse(url).path
        options = RequestParser.path_to_parameters(self.request.uri)
        super(UrlAliasesHandler, self).get(**options)
Ejemplo n.º 4
0
    def get(self, **kwargs):
        # check if request is valid
        yield gen.maybe_future(self.check_pdf(kwargs.copy()))

        pdf = PDF(self.context)
        pdf_path = kwargs.pop('pdf')
        url_parts, pdf_url = pdf.url_parts(pdf_path)
        preview_path = pdf_path.replace('/pdf/', '').replace('.pdf', '.png')

        # Check if preview image already exists
        path = quote(preview_path.encode('utf-8'))
        exists = yield gen.maybe_future(pdf.get(path))
        if not exists:
            # create a new preview
            data = yield self.create_preview(pdf_url)
            if not data:
                raise tornado.web.HTTPError(400)
            # store it in storage
            yield gen.maybe_future(pdf.put(path, data))
        else:
            logger.debug('PDF preview already exists..')

        crypto = CryptoURL(key=self.context.server.security_key)
        options = {k: v for k, v in kwargs.items() if v and k != 'hash'}
        preview_url = crypto.generate(image_url=preview_path, **options)
        kwargs['hash'] = RequestParser.path_to_parameters(preview_url)['hash']

        # Patch the request uri to allow normal thumbor operations
        self.request.uri = preview_url
        self.request.path = preview_url

        kwargs['request'] = self.request
        kwargs['image'] = preview_path
        self.context.request = RequestParameters(**kwargs)

        # set valid file name in headers
        name = os.path.basename(kwargs.get('image', None))
        if name:
            self.set_header('Content-Disposition',
                            'inline; filename="{name}"'.format(name=name))

        # Call the original ImageHandler.get method to serve the image.
        super(PDFHandler, self).get(**kwargs)
Ejemplo n.º 5
0
    def post(self, **kwargs):

        # URL can be passed as a URL argument or in the body
        url = kwargs['url'] if 'url' in kwargs else kwargs['key']

        if not url:
            raise tornado.web.HTTPError(404)

        options = RequestParser.path_to_parameters(url)

        self.check_image(options)

        # We check the status code, if != 200 the image is incorrect, and we shouldn't store the key
        if self.get_status() == 200:
            self.clear()
            shortener = Shortener(self.context)
            key = yield gen.maybe_future(shortener.generate(url))
            shortener.put(key, url)

            self.write(json.dumps({'key': key}))
Ejemplo n.º 6
0
    def post(self, **kwargs):
        self.should_return_image = False

        content_type = self.request.headers.get("Content-Type", '')

        if 'key' in kwargs and kwargs['key']:
            url = kwargs['key']
        elif content_type.startswith("application/json"):
            data = json.loads(self.request.body)
            url = data['url'] if 'url' in data else None
        else:
            url = self.get_body_argument('url', None)

        if not url:
            logger.error("Couldn't find url param in body or key in URL...")
            raise tornado.web.HTTPError(400)

        options = RequestParser.path_to_parameters(url)

        yield self.check_image(options)

        # We check the status code, if != 200 the image is incorrect, and we shouldn't store the key
        if self.get_status() == 200:
            logger.debug(
                "Image is checked, clearing the response before trying to store..."
            )
            self.clear()
            try:
                shortener = Shortener(self.context)
                key = shortener.generate(url)
                shortener.put(key, url)

                self.write(json.dumps({'key': key}))
                self.set_header("Content-Type", "application/json")
            except Exception as e:
                logger.error(
                    "An error occurred while trying to store shortened URL: {error}."
                    .format(error=e.message))
                self.set_status(500)
                self.write(json.dumps({'error': e.message}))
Ejemplo n.º 7
0
    def get(self, **kwargs):

        shortener = Shortener(self.context)

        # Get the url from the shortener and parse the values.
        url = yield gen.maybe_future(shortener.get(kwargs['key']))

        if not url:
            raise tornado.web.HTTPError(404)

        # Patch the request uri to allow normal thumbor operations
        self.request.uri = urlparse.urlparse(url).path

        options = RequestParser.path_to_parameters(self.request.uri)

        name = os.path.basename(options.get('image', None))
        if name:
            self.set_header('Content-Disposition',
                            'inline; filename="{name}"'.format(name=name))

        # Call the original ImageHandler.get method to serve the image.
        super(UrlShortenerHandler, self).get(**options)
Ejemplo n.º 8
0
    def post(self, **kwargs):
        self.should_return_image = False

        content_type = self.request.headers.get("Content-Type", '')

        if 'key' in kwargs and kwargs['key']:
            url = kwargs['key']
        elif content_type.startswith("application/json"):
            data = json.loads(self.request.body)
            url = data['url'] if 'url' in data else None
        else:
            url = self.get_body_argument('url', None)

        if not url:
            logger.error("Couldn't find url param in body or key in URL...")
            raise tornado.web.HTTPError(400)

        options = RequestParser.path_to_parameters(url)

        yield self.check_image(options)

        # We check the status code, if != 200 the image is incorrect, and we shouldn't store the key
        if self.get_status() == 200:
            logger.debug("Image is checked, clearing the response before trying to store...")
            self.clear()
            try:
                shortener = Shortener(self.context)
                key = shortener.generate(url)
                shortener.put(key, url)

                self.write(json.dumps({'key': key}))
                self.set_header("Content-Type", "application/json")
            except Exception as e:
                logger.error("An error occurred while trying to store shortened URL: {error}.".format(error=e.message))
                self.set_status(500)
                self.write(json.dumps({'error': e.message}))
Ejemplo n.º 9
0
 def should_parse_parameters(self, topic):
     parameters = RequestParser.path_to_parameters(topic)
     expect(parameters).to_include('image')
     expect(parameters).to_include('width')
     expect(parameters).to_include('height')
Ejemplo n.º 10
0
 def should_parse_parameters(self, topic):
     parameters = RequestParser.path_to_parameters(topic)
     expect(parameters).to_include('image')
     expect(parameters).to_include('width')
     expect(parameters).to_include('height')