Example #1
0
    def get_videos(self, mbid, artist, url, check=False):
        token = 'lastfm:artist:videos:' + mbid + ':' + self.encode(artist)

        videos = cache.get(token)[token]
        if videos:
            return videos

        page, videos = 1, []

        while page:
            html = self.http_fetch(url + '/+videos?page=' + str(page))
            if html is None:
                break

            box = xbmcup.parser.re('restypeclass="externalvideo"(.+?)</ul>',
                                   html)
            if not box or not box[0]:
                break

            for row in xbmcup.parser.re.all('<li(.+?)</li>', box[0]):
                href = xbmcup.parser.re('<a href="[^"]+\-([^"]+)"', row[0])
                if href and href[0]:

                    img = xbmcup.parser.re('<img src="([^"]+)"', row[0])
                    if img and img[0]:
                        img = img[0].split('/')
                        img[-1] = '0.jpg'

                        title = xbmcup.parser.re('title="([^"]+)"', row[0])
                        if title and title[0]:
                            videos.append({
                                'id': href[0],
                                'image': '/'.join(img),
                                'title': title[0]
                            })
                        else:
                            videos.append({
                                'id': href[0],
                                'image': '/'.join(img),
                                'title': None
                            })

            if check:
                break

            pages = xbmcup.parser.re(
                '<a href="[^"]+page=([0-9]+)"[^>]+title="Next page"', html)
            if pages and pages[0]:
                page = int(pages[0])
            else:
                page = None

        else:
            if videos:
                cache.set(token, videos, 2592000)  # 1 month

        return videos
Example #2
0
def heartfelt_thanks():
    """The final stage when the user edits the given fortune."""

    # Updates the list with the user-given fortune
    if request.method == 'POST':
        old_fortune = cache.get("picked_fortune")
        new_fortune = request.form["new_fortune"]
        fortune_manager.update_fortune(old_fortune, new_fortune)

    return render_template('participatory_thanks.html')
Example #3
0
def process():
    payload = request.get_json()
    phrase = payload.get('text')
    string_key = cache_key(phrase)

    pairs = cache.get(string_key)
    if not pairs:
        pairs = pair_count(phrase)
        cache.set(string_key, pairs)

    return {'pairs': pairs}
Example #4
0
def city_weather(city_name):
    """Get the city wealth object by city name"""
    city_wealth = None

    if city_name in cache:
        city_wealth = cache.get(city_name)

    if city_wealth is None:
        response = weather_api.search_city(city_name)

        city_wealth = response.json()
        cache.set(city_name, city_wealth)

    return city_wealth
Example #5
0
    def get_videos(self, mbid, artist, url, check=False):
        token = 'lastfm:artist:videos:' + mbid + ':' + self.encode(artist)

        videos = cache.get(token)[token]
        if videos:
            return videos

        page, videos = 1, []

        while page:
            html = self.http_fetch(url + '/+videos?page=' + str(page))
            if html is None:
                break

            box = xbmcup.parser.re('restypeclass="externalvideo"(.+?)</ul>', html)
            if not box or not box[0]:
                break

            for row in xbmcup.parser.re.all('<li(.+?)</li>', box[0]):
                href = xbmcup.parser.re('<a href="[^"]+\-([^"]+)"', row[0])
                if href and href[0]:

                    img = xbmcup.parser.re('<img src="([^"]+)"', row[0])
                    if img and img[0]:
                        img = img[0].split('/')
                        img[-1] = '0.jpg'

                        title = xbmcup.parser.re('title="([^"]+)"', row[0])
                        if title and title[0]:
                            videos.append({'id': href[0], 'image': '/'.join(img), 'title': title[0]})
                        else:
                            videos.append({'id': href[0], 'image': '/'.join(img), 'title': None})

            if check:
                break

            pages = xbmcup.parser.re('<a href="[^"]+page=([0-9]+)"[^>]+title="Next page"', html)
            if pages and pages[0]:
                page = int(pages[0])
            else:
                page = None

        else:
            if videos:
                cache.set(token, videos, 2592000) # 1 month

        return videos
Example #6
0
def before():
    req_data = None
    try:
        req_data = json.loads(str(request.data))
        application.logger.info("XDBG REQUEST= `{}` {}: {}".format(
            request.method, request.path, req_data))
    except Exception as e:
        application.logger.info("XDBG REQUEST= {}".format(request.path))
    application.logger.info("XDBG REQUEST_HEADER= {}".format(request.headers))

    if request.path == '/lifecycle/installed':
        return jsonify({"message": "working"})

    if req_data and req_data.get('message'):
        last_message = cache.get('last_message')
        if last_message == req_data['message']['ts']:
            raise Exception('Same message')
        cache.set('last_message', req_data['message']['ts'])
def update_fortune(old_fortune, new_fortune):
    """Replaces a fortune with an updated fortune from the user.

    TODO: This algorithm has a lot of steps and I'm sure there's an
    updated algorithm somewhere that is faster than this.
    """
    # Get the list of fortunes in the cache
    fortunes = cache.get("fortunes")

    # Look and replace the fortune.
    # TODO: Dangerous assumption that text is clean from the request body
    # and front-end. A better way to do this is to usea better matching
    # algorithm.
    updated_fortunes = [
        new_fortune if f == old_fortune else f for f in fortunes
    ]

    # Save the updated list of fortunes in the cache.
    cache.update("fortunes", updated_fortunes)
    return new_fortune
Example #8
0
    def get_artist(self, mbid, artist):
        token = 'lastfm:artist:profile:' + mbid + ':' + self.encode(artist)

        data = cache.get(token)[token]
        if data:
            return data

        data = lastfm.artist.getInfo(mbid=mbid, artist=artist, lang=self.get_lang())
        if data:

            for tag in ('summary', 'content'):
                if data[tag]:
                    r = data[tag].rfind('<a href="')
                    if r != -1:
                        data[tag] = data[tag][:r]
                    text = xbmcup.parser.clear.text(data[tag])
                    data[tag] = text if text else None

            cache.set(token, data, 2592000) # 1 month

        return data
Example #9
0
    def get_artist(self, mbid, artist):
        token = 'lastfm:artist:profile:' + mbid + ':' + self.encode(artist)

        data = cache.get(token)[token]
        if data:
            return data

        data = lastfm.artist.getInfo(mbid=mbid,
                                     artist=artist,
                                     lang=self.get_lang())
        if data:

            for tag in ('summary', 'content'):
                if data[tag]:
                    r = data[tag].rfind('<a href="')
                    if r != -1:
                        data[tag] = data[tag][:r]
                    text = xbmcup.parser.clear.text(data[tag])
                    data[tag] = text if text else None

            cache.set(token, data, 2592000)  # 1 month

        return data
Example #10
0
def edit_fortune():
    """Allows the user to edit the picked fortune.
    """
    picked_fortune = cache.get("picked_fortune")
    return render_template('edit_cookie.html', fortune=picked_fortune)
Example #11
0
def get_all_fortunes():
    """A simple endpoint for gathering all fortunes."""
    return {'fortune': cache.get("fortunes")}
Example #12
0
def person(person_id):
    _person = cache.get(f'person_{person_id}')

    if _person is None:
        _person = Person.query.get(person_id)

    if request.method == 'GET':
        schema = PersonSchema()
        result = schema.dump(_person)
        cache.set(f'person_{person_id}', result, helper.get_hours_in_seconds(1))
        return make_response(jsonify(
            {
                'message': 'Success',
                'data': {'person': result}
            }), 200)

    if helper.is_empty_content_length(request):
        app.logger.error(f'Exception: {request.content_type}')
        return make_response(jsonify(
            {
                'message': 'Payload can not be empty'
            }), 411)

    if not helper.is_json_content(request):
        app.logger.error(f'Exception: {request.content_type}')
        return make_response(jsonify(
            {
                'message': 'Unsupported Media Type'
            }), 415)

    if request.method == 'PUT':
        try:
            _person.name = request.json['name']
            _person.email = request.json['email']
        except KeyError as err:
            app.logger.error(f'Exception: {err}')
            return make_response(jsonify(
                {
                    'message': 'Some parameter is missing on request'
                }), 400)

        try:
            db.session.commit()
            cache.delete(f'person_{person_id}')
            cache.delete('person_list')
            return make_response(jsonify(
                {
                    'message': 'Success',
                    'data': {'person_id': person_id}
                }), 200)
        except Exception as err:
            app.logger.error(f'Exception: {err}')
            return make_response(jsonify(
                {
                    'message': 'Error while updating person information',
                    'data': {'person_id': person_id}
                }), 500),

    if request.method == 'PATCH':
        _person.name = request.json.get('name') or _person.name
        _person.email = request.json.get('email') or _person.email

        try:
            db.session.commit()
            cache.delete(f'person_{person_id}')
            cache.delete('person_list')
            return make_response(jsonify(
                {
                    'message': 'Success',
                    'data': {'person_id', person_id}
                }), 200)
        except Exception as err:
            app.logger.error(f'Exception: {err}')
            return make_response(jsonify(
                {
                    'message': 'Error while updating person information',
                    'data': {'person_id': person_id}
                }), 500)

    if request.method == 'DELETE':
        if _person is None:
            return make_response(jsonify(
                {
                    'message': 'Person not found',
                    'data': {'person_id': person_id}
                }), 200)

        try:
            db.session.delete(_person)
            db.session.commit()
            cache.delete(f'person_{person_id}')
            cache.delete('person_list')
            return make_response(jsonify(
                {
                    'message': 'Success',
                    'data': {'person_id': person_id}
                }), 200)
        except Exception as err:
            app.logger.error(f'Exception: {err}')
            return make_response(jsonify(
                {
                    'message': 'Error while deleting person',
                    'data': {'person_id': person_id}
                }), 500)
Example #13
0
def person():
    if request.method == 'GET':
        person_list = cache.get('person_list')

        if person_list is not None:
            return make_response(jsonify(
                {
                    'message': 'Success',
                    'data': {'person_list': person_list}
                }), 200)

        person_list = Person.query.order_by(Person.create_date).all()
        schema = PersonSchema(many=True)
        result = schema.dump(person_list)
        cache.set('person_list', result, helper.get_hours_in_seconds(1))
        return make_response(jsonify(
            {
                'message': 'Success',
                'data': {'person_list': result}
            }), 200)

    if request.method == 'POST':
        if helper.is_empty_content_length(request):
            app.logger.error(f'Exception: {request.content_type}')
            return make_response(jsonify(
                {
                    'message': 'Payload can not be empty'
                }), 411)

        if not helper.is_json_content(request):
            app.logger.error(f'Exception: {request.content_type}')
            return make_response(jsonify(
                {
                    'message': 'Unsupported Media Type'
                }), 415)

        name = request.json['name']
        email = request.json['email']

        if name or email:
            _person = Person(name=name, email=email)

            try:
                db.session.add(_person)
                db.session.commit()
            except Exception as err:
                app.logger.error(f'Exception: {err}')
                return make_response(jsonify(
                    {
                        'message': 'Error while creating person! That email address is already in use.'
                    }), 500)
        else:
            return make_response(jsonify(
                {
                    'message': 'Name or email is missing.'
                }), 200)

        cache.delete('person_list')

        return make_response(jsonify(
            {
                'message': 'Success!',
                'data': {'person_id': _person.id}
            }), 200)
Example #14
0
def get_person_product_list(person_id):
    if request.method == 'GET':
        try:
            page = int(request.args.get('page')) or 1
        except ValueError as err:
            app.logger.error(f'Exception: {err}')
            return make_response(jsonify(
                {
                    'message': 'Some parameter is on incorrect format',
                    'data': {'person_id': person_id}
                }), 500)
        except Exception as err:
            app.logger.error(f'Exception: {err}')
            return make_response(jsonify(
                {
                    'message': 'Some parameter is missing on request',
                    'data': {'person_id': person_id}
                }), 400)

        app.logger.debug(f'page: {page}')

        product_list = cache.get(f'products_person_{person_id}_page_{page}')

        if product_list is not None:
            return make_response(jsonify(
                {
                    'message': 'Success',
                    'data': {'person_id': person_id, 'product_list': product_list}
                }), 200)

        product_count = ProductList.query.filter(ProductList.person_id == person_id).count()

        if product_count <= 0:
            return make_response(jsonify(
                {
                    'message': 'This product list is empty',
                    'data': {'person_id': person_id}
                }), 200)

        items_per_page = int(app.config['ITEMS_PER_PAGE'])
        max_page = math.ceil(product_count / items_per_page)

        if page > max_page:
            return make_response(jsonify(
                {
                    'message': f'Page number must be less than or equal to {max_page}',
                    'data': {'product_count': product_count}
                }), 404)

        products = ProductList.query.filter(ProductList.person_id == person_id).group_by(ProductList.insert_date).paginate(page, items_per_page, True).items

        if products:
            product_list = []
            product_api_endpoint = app.config['EXTERNAL_API']

            for product in products:
                response = requests.get(product_api_endpoint.replace('|PRODUCT_ID|', str(product.product_id)))

                if response.status_code == 200:
                    p = response.json()
                    title = p['title']
                    image = p['image']
                    price = p['price']
                    review_score = p['reviewScore'] if 'reviewScore' in p else None

                    product_list.append(
                        {
                            'id': product.product_id,
                            'title': title,
                            'image': image,
                            'price': price,
                            'review_score': review_score
                        }
                    )
                else:
                    app.logger.info(f'Product ({product.product_id}) not found')

            app.logger.debug(f'{len(product_list)} products on list')
            cache.set(f'products_person_{person_id}_page_{page}', product_list, helper.get_hours_in_seconds(1))
            return make_response(jsonify(
                {
                    'message': 'Success',
                    'data': {'person_id': person_id, 'product_list': product_list}
                }), 200)

        return make_response(jsonify(
            {
                'message': 'This product list is empty',
                'data': {'person_id': person_id}
            }), 200)

    if request.method == 'POST':
        product_id = request.json['product_id']
        app.logger.info(f'product_id: {product_id}')
        product_api_endpoint = app.config['EXTERNAL_API']
        response = requests.get(product_api_endpoint.replace('|PRODUCT_ID|', str(product_id)))

        if not response.status_code == 200:
            return make_response(jsonify(
                {
                    'message': 'This product does not exists',
                    'data': {'product_id': product_id}
                }), 404)

        _product = ProductList.query.filter(ProductList.person_id == person_id, ProductList.product_id == product_id).count()

        if _product:
            return make_response(jsonify(
                {
                    'message': 'Product already is this list',
                    'data': {'product_id': product_id}
                }), 200)

        _product = ProductList(person_id=person_id, product_id=product_id)

        try:
            db.session.add(_product)
            db.session.commit()
        except Exception as err:
            app.logger.error(f'Exception: {err}')
            return make_response(jsonify(
                {
                    'message': f'Error while adding product (\'{product_id}\') to person (\'{person_id}\'',
                    'data': {'person_id': person_id, 'product_id': product_id}
                }), 500)

        product_count = ProductList.query.filter(ProductList.person_id == person_id).count()
        items_per_page = int(app.config['ITEMS_PER_PAGE'])

        if items_per_page > 0:
            max_page = math.ceil(product_count / items_per_page)

            if max_page > 0:
                for page in range(1, max_page + 1):
                    app.logger.debug(f'Deleting cache key: products_person_{person_id}_page_{page}')
                    cache.delete(f'products_person_{person_id}_page_{page}')

        return make_response(jsonify(
            {
                'message': 'Product successfully added to list',
                'data': {'person_id': person_id, 'product_id': product_id}
            }), 200)
def get_fortune():
    """Picks a random fortune based on the list saved."""
    fortunes = cache.get("fortunes")
    return random.choice(fortunes)
Example #16
0
 def current(self):
     """ Selects the current hackathon. Will throw an error if no single current hackathons exist """
     return cache.get('HackathonManager.current_hackathon',
                      self.get,
                      current=True)