Esempio n. 1
0
    def create(self):

        if 'url' not in self.request.params:
            raise HTTPBadRequest('The parameter url is required')

        url = self.request.params['url']

        # Check that it is an internal URL...
        hostname = urlparse(url).hostname
        if hostname != self.request.host:
            raise HTTPBadRequest("The requested host '%s' shound be '%s'" %
                                 (hostname, self.request.host))

        tries = 0
        while True:
            ref = ''.join(
                random.choice(string.ascii_letters + string.digits)
                for i in range(self.settings.get('length', 4)))
            test_url = DBSession.query(Shorturl).filter(
                Shorturl.ref == ref).all()
            if len(test_url) == 0:
                break
            if tries > 20:  # pragma: no cover
                message = "No free ref found, considere to incrase the length"
                logging.error(message)
                raise HTTPInternalServerError(message)

        user_email = self.request.user.email \
            if self.request.user is not None else None
        email = self.request.params.get('email') or user_email
        short_url = Shorturl()
        short_url.url = url
        short_url.ref = ref
        short_url.creator_email = email
        short_url.creation = datetime.now()
        short_url.nb_hits = 0

        DBSession.add(short_url)

        s_url = self.request.route_url('shortener_get', ref=ref)

        if \
                email is not None and \
                'email_from' in self.settings and \
                'email_subject' in self.settings and \
                'email_body' in self.settings and \
                'smtp_server' in self.settings:  # pragma: no cover
            text = self.settings['email_body'] % {
                'full_url': url,
                'short_url': s_url,
            }
            send_email(
                self.settings['email_from'],
                [email],
                text.encode('utf-8'),
                self.settings['email_subject'],
                self.settings['smtp_server'],
            )

        return {'short_url': s_url}
Esempio n. 2
0
    def create(self):

        if "url" not in self.request.params:
            raise HTTPBadRequest("The parameter url is required")

        url = self.request.params["url"]

        # Check that it is an internal URL...
        uri_parts = urlparse(url)
        hostname = uri_parts.hostname
        paths = uri_parts.path.split("/")
        if hostname != self.request.server_name:
            raise HTTPBadRequest("The requested host '%s' should be '%s'" % (
                hostname, self.request.host
            ))

        shortened = False
        if (len(paths) > 1 and paths[-2] == "short"):
            ref = paths[-1]
            shortened = True

        tries = 0
        while not shortened:
            ref = "".join(
                random.choice(string.ascii_letters + string.digits)
                for i in range(self.settings.get("length", 4))
            )
            test_url = DBSession.query(Shorturl).filter(Shorturl.ref == ref).all()
            if len(test_url) == 0:
                break
            tries += 1  # pragma: no cover
            if tries > 20:  # pragma: no cover
                message = "No free ref found, considere to increase the length"
                logging.error(message)
                raise HTTPInternalServerError(message)

        user_email = self.request.user.email \
            if self.request.user is not None else None
        email = self.request.params.get("email")
        if not shortened:
            short_url = Shorturl()
            short_url.url = url
            short_url.ref = ref
            short_url.creator_email = user_email
            short_url.creation = datetime.now()
            short_url.nb_hits = 0

            DBSession.add(short_url)

        if "base_url" in self.settings:
            s_url = self.settings["base_url"] + ref
        else:
            s_url = self.request.route_url("shortener_get", ref=ref)

        email = email or user_email

        if \
                email is not None and \
                "email_from" in self.settings and \
                "email_subject" in self.settings and \
                "email_body" in self.settings and \
                "smtp_server" in self.settings:  # pragma: no cover
            text = self.settings["email_body"] % {
                "full_url": url,
                "short_url": s_url,
            }
            send_email(
                self.settings["email_from"],
                [email],
                text.encode("utf-8"),
                self.settings["email_subject"],
                self.settings["smtp_server"],
            )

        set_common_headers(
            self.request, "shortner", NO_CACHE
        )
        return {"short_url": s_url}
Esempio n. 3
0
    def create(self):

        if 'url' not in self.request.params:
            raise HTTPBadRequest('The parameter url is required')

        url = self.request.params['url']

        # Check that it is an internal URL...
        uri_parts = urlparse(url)
        hostname = uri_parts.hostname
        paths = uri_parts.path.split('/')
        if hostname != self.request.server_name:
            raise HTTPBadRequest("The requested host '%s' should be '%s'" % (
                hostname, self.request.host
            ))

        shortened = False
        if (len(paths) > 1 and paths[-2] == 'short'):
            ref = paths[-1]
            shortened = True

        tries = 0
        while not shortened:
            ref = ''.join(
                random.choice(string.ascii_letters + string.digits)
                for i in range(self.settings.get('length', 4))
            )
            test_url = DBSession.query(Shorturl).filter(Shorturl.ref == ref).all()
            if len(test_url) == 0:
                break
            tries += 1  # pragma: no cover
            if tries > 20:  # pragma: no cover
                message = "No free ref found, considere to increase the length"
                logging.error(message)
                raise HTTPInternalServerError(message)

        user_email = self.request.user.email \
            if self.request.user is not None else None
        email = self.request.params.get('email')
        if not shortened:
            short_url = Shorturl()
            short_url.url = url
            short_url.ref = ref
            short_url.creator_email = user_email
            short_url.creation = datetime.now()
            short_url.nb_hits = 0

            DBSession.add(short_url)

        s_url = self.request.route_url('shortener_get', ref=ref)

        email = email or user_email

        if \
                email is not None and \
                'email_from' in self.settings and \
                'email_subject' in self.settings and \
                'email_body' in self.settings and \
                'smtp_server' in self.settings:  # pragma: no cover
            text = self.settings['email_body'] % {
                'full_url': url,
                'short_url': s_url,
            }
            send_email(
                self.settings['email_from'],
                [email],
                text.encode('utf-8'),
                self.settings['email_subject'],
                self.settings['smtp_server'],
            )

        return {'short_url': s_url}
Esempio n. 4
0
    def create(self):

        if "url" not in self.request.params:
            raise HTTPBadRequest("The parameter url is required")

        url = self.request.params["url"]

        # see: http://httpd.apache.org/docs/2.2/mod/core.html#limitrequestline
        if len(url) > 8190:  # pragma: no cover
            raise HTTPBadRequest("The parameter url is too long ({} > {})".format(len(url), 8190))

        # Check that it is an internal URL...
        uri_parts = urlparse(url)
        hostname = uri_parts.hostname
        if "allowed_hosts" in self.settings:
            if hostname not in self.settings["allowed_hosts"]:  # pragma: no cover
                raise HTTPBadRequest("The requested host is not allowed.")
        else:
            if hostname != self.request.server_name:
                raise HTTPBadRequest("The requested host '{0!s}' should be '{1!s}'".format(
                    hostname, self.request.server_name
                ))

        shortened = False

        for base in self.short_bases:
            base_parts = urlparse(base)
            if uri_parts.path.startswith(base_parts.path):
                shortened = True
                ref = uri_parts.path.split("/")[-1]

        tries = 0
        while not shortened:
            ref = "".join(
                random.choice(string.ascii_letters + string.digits)
                for i in range(self.settings.get("length", 4))
            )
            test_url = DBSession.query(Shorturl).filter(Shorturl.ref == ref).all()
            if len(test_url) == 0:
                break
            tries += 1  # pragma: no cover
            if tries > 20:  # pragma: no cover
                message = "No free ref found, considere to increase the length"
                logging.error(message)
                raise HTTPInternalServerError(message)

        user_email = self.request.user.email \
            if self.request.user is not None else None
        email = self.request.params.get("email")
        if not shortened:
            short_url = Shorturl()
            short_url.url = url
            short_url.ref = ref
            short_url.creator_email = user_email
            short_url.creation = datetime.now()
            short_url.nb_hits = 0

            DBSession.add(short_url)

        if "base_url" in self.settings:
            s_url = self.settings["base_url"] + ref
        else:
            s_url = self.request.route_url("shortener_get", ref=ref)

        if \
                email is not None and \
                "email_from" in self.settings and \
                "email_subject" in self.settings and \
                "email_body" in self.settings and \
                "smtp_server" in self.settings:  # pragma: no cover
            text = self.settings["email_body"] % {
                "full_url": url,
                "short_url": s_url,
                "message": self.request.params.get("message", ""),
            }
            send_email(
                self.settings["email_from"],
                [email],
                text.encode("utf-8"),
                self.settings["email_subject"],
                self.settings["smtp_server"],
            )

        set_common_headers(
            self.request, "shortner", NO_CACHE
        )
        return {"short_url": s_url}
Esempio n. 5
0
    def create(self):

        if "url" not in self.request.params:
            raise HTTPBadRequest("The parameter url is required")

        url = self.request.params["url"]

        # Check that it is an internal URL...
        uri_parts = urlparse(url)
        hostname = uri_parts.hostname
        if "allowed_hosts" in self.settings:
            if hostname not in self.settings[
                    "allowed_hosts"]:  # pragma: no cover
                raise HTTPBadRequest("The requested host is not allowed.")
        else:
            if hostname != self.request.server_name:
                raise HTTPBadRequest("The requested host '%s' should be '%s'" %
                                     (hostname, self.request.server_name))

        shortened = False

        for base in self.short_bases:
            base_parts = urlparse(base)
            if uri_parts.path.startswith(base_parts.path):
                shortened = True
                ref = uri_parts.path.split("/")[-1]

        tries = 0
        while not shortened:
            ref = "".join(
                random.choice(string.ascii_letters + string.digits)
                for i in range(self.settings.get("length", 4)))
            test_url = DBSession.query(Shorturl).filter(
                Shorturl.ref == ref).all()
            if len(test_url) == 0:
                break
            tries += 1  # pragma: no cover
            if tries > 20:  # pragma: no cover
                message = "No free ref found, considere to increase the length"
                logging.error(message)
                raise HTTPInternalServerError(message)

        user_email = self.request.user.email \
            if self.request.user is not None else None
        email = self.request.params.get("email")
        if not shortened:
            short_url = Shorturl()
            short_url.url = url
            short_url.ref = ref
            short_url.creator_email = user_email
            short_url.creation = datetime.now()
            short_url.nb_hits = 0

            DBSession.add(short_url)

        if "base_url" in self.settings:
            s_url = self.settings["base_url"] + ref
        else:
            s_url = self.request.route_url("shortener_get", ref=ref)

        if \
                email is not None and \
                "email_from" in self.settings and \
                "email_subject" in self.settings and \
                "email_body" in self.settings and \
                "smtp_server" in self.settings:  # pragma: no cover
            text = self.settings["email_body"] % {
                "full_url": url,
                "short_url": s_url,
                "message": self.request.params.get("message", ""),
            }
            send_email(
                self.settings["email_from"],
                [email],
                text.encode("utf-8"),
                self.settings["email_subject"],
                self.settings["smtp_server"],
            )

        set_common_headers(self.request, "shortner", NO_CACHE)
        return {"short_url": s_url}