Esempio n. 1
0
def reset_latest_import_timestamp():
    if request.method == "POST":
        token = request.form.get("token")
        if token != current_user.auth_token:
            raise BadRequest(
                "Can only reset latest import timestamp of currently logged in user"
            )
        reset = request.form.get("reset")
        if reset == "yes":
            try:
                db_user.reset_latest_import(current_user.musicbrainz_id)
                flash.info(
                    "Latest import time reset, we'll now import all your data instead of stopping at your last imported listen."
                )
            except DatabaseException:
                flash.error(
                    "Something went wrong! Unable to reset latest import timestamp right now."
                )
        return redirect(url_for("profile.info"))
    else:
        token = current_user.auth_token
        return render_template(
            "profile/resetlatestimportts.html",
            token=token,
        )
Esempio n. 2
0
def delete_listens():
    """ Delete all the listens for the currently logged-in user from ListenBrainz.

    If POST request, this view checks for the correct authorization token and
    deletes the listens. If deletion is successful, redirects to user's profile page,
    else flashes an error and redirects to user's info page.

    If GET request, this view renders a page asking the user to confirm that they
    wish to delete their listens.
    """
    if request.method == 'POST':
        if request.form.get('token') and (request.form.get('token') == current_user.auth_token):
            try:
                delete_listens_history(current_user.musicbrainz_id)
            except Exception as e:
                current_app.logger.error('Error while deleting listens for %s: %s', current_user.musicbrainz_id, str(e))
                flash.error('Error while deleting listens for %s, please try again later.' % current_user.musicbrainz_id)
                return redirect(url_for('profile.info'))
            flash.info('Successfully deleted listens for %s.' % current_user.musicbrainz_id)
            return redirect(url_for('user.profile', user_name=current_user.musicbrainz_id))
        else:
            raise Unauthorized("Auth token invalid or missing.")
    else:
        return render_template(
            'profile/delete_listens.html',
            user=current_user,
        )
Esempio n. 3
0
def reset_latest_import_timestamp():
    form = FlaskForm()
    if form.validate_on_submit():
        try:
            listens_importer.update_latest_listened_at(
                current_user.id, ExternalServiceType.LASTFM, 0)
            flash.info(
                "Latest import time reset, we'll now import all your data instead of stopping at your last imported listen."
            )
        except DatabaseException:
            flash.error(
                "Something went wrong! Unable to reset latest import timestamp right now."
            )
        return redirect(url_for("profile.info"))

    if form.csrf_token.errors:
        flash.error(
            'Cannot reset import time due to error during authentication, please try again later.'
        )
        return redirect(url_for('profile.info'))

    return render_template(
        "profile/resetlatestimportts.html",
        form=form,
    )
Esempio n. 4
0
def delete_listens():
    """ Delete all the listens for the currently logged-in user from ListenBrainz.

    If POST request, this view checks for the correct authorization token and
    deletes the listens. If deletion is successful, redirects to user's profile page,
    else flashes an error and redirects to user's info page.

    If GET request, this view renders a page asking the user to confirm that they
    wish to delete their listens.
    """
    form = FlaskForm()
    if form.validate_on_submit():
        try:
            delete_listens_history(current_user.musicbrainz_id)
            flash.info('Successfully deleted listens for %s.' %
                       current_user.musicbrainz_id)
            return redirect(
                url_for('user.profile', user_name=current_user.musicbrainz_id))
        except Exception as e:
            current_app.logger.error('Error while deleting listens for %s: %s',
                                     current_user.musicbrainz_id, str(e))
            flash.error(
                'Error while deleting listens for %s, please try again later.'
                % current_user.musicbrainz_id)
            return redirect(url_for('profile.info'))

    if form.csrf_token.errors:
        flash.error(
            'Cannot delete listens due to error during authentication, please try again later.'
        )
        return redirect(url_for('profile.info'))

    return render_template('profile/delete_listens.html',
                           user=current_user,
                           form=form)
def upload():
    if request.method == 'POST':
        try:
            f = request.files['file']
            if f.filename == '':
                flash.warning('No file selected.')
                return redirect(request.url)
        except RequestEntityTooLarge:
            raise RequestEntityTooLarge('Maximum filesize upload limit exceeded. File must be <=' +
                                        sizeof_readable(current_app.config['MAX_CONTENT_LENGTH']))
        except:
            raise InternalServerError("Something went wrong. Could not upload the file")

        # Check upload folder
        if 'UPLOAD_FOLDER' not in current_app.config:
            raise InternalServerError("Could not upload the file. Upload folder not specified")
        upload_path = path.join(path.abspath(current_app.config['UPLOAD_FOLDER']), current_user.musicbrainz_id)
        if not path.isdir(upload_path):
            makedirs(upload_path)

        # Write to a file
        filename = path.join(upload_path, secure_filename(f.filename))
        f.save(filename)

        if not zipfile.is_zipfile(filename):
            raise BadRequest('Not a valid zip file.')

        success = failure = 0
        regex = re.compile('json/scrobbles/scrobbles-*')
        try:
            zf = zipfile.ZipFile(filename, 'r')
            files = zf.namelist()
            # Iterate over file that match the regex
            for f in [f for f in files if regex.match(f)]:
                try:
                    # Load listens file
                    jsonlist = ujson.loads(zf.read(f))
                    if not isinstance(jsonlist, list):
                        raise ValueError
                except ValueError:
                    failure += 1
                    continue

                payload = convert_backup_to_native_format(jsonlist)
                for listen in payload:
                    validate_listen(listen, LISTEN_TYPE_IMPORT)
                insert_payload(payload, current_user)
                success += 1
        except Exception:
            raise BadRequest('Not a valid lastfm-backup-file.')
        finally:
            os.remove(filename)

        # reset listen count for user
        db_connection = webserver.influx_connection._influx
        db_connection.reset_listen_count(current_user.musicbrainz_id)

        flash.info('Congratulations! Your listens from %d files have been uploaded successfully.' % success)
    return redirect(url_for("profile.import_data"))
Esempio n. 6
0
def reset_latest_import_timestamp():
    if request.method == "POST":
        token = request.form.get("token")
        if token != current_user.auth_token:
            raise BadRequest("Can only reset latest import timestamp of currently logged in user")
        reset = request.form.get("reset")
        if reset == "yes":
            try:
                db_user.reset_latest_import(current_user.musicbrainz_id)
                flash.info("Latest import time reset, we'll now import all your data instead of stopping at your last imported listen.")
            except DatabaseException:
                flash.error("Something went wrong! Unable to reset latest import timestamp right now.")
        return redirect(url_for("profile.info"))
    else:
        token = current_user.auth_token
        return render_template(
            "profile/resetlatestimportts.html",
            token=token,
        )
Esempio n. 7
0
def reset_token():
    if request.method == "POST":
        token = request.form.get("token")
        if token != current_user.auth_token:
            raise BadRequest("Can only reset token of currently logged in user")
        reset = request.form.get("reset")
        if reset == "yes":
            try:
                db_user.update_token(current_user.id)
                flash.info("Access token reset")
            except DatabaseException:
                flash.error("Something went wrong! Unable to reset token right now.")
        return redirect(url_for("profile.info"))
    else:
        token = current_user.auth_token
        return render_template(
            "user/resettoken.html",
            token=token,
        )
Esempio n. 8
0
def reset_token():
    if request.method == "POST":
        token = request.form.get("token")
        if token != current_user.auth_token:
            raise BadRequest("Can only reset token of currently logged in user")
        reset = request.form.get("reset")
        if reset == "yes":
            try:
                db_user.update_token(current_user.id)
                flash.info("Access token reset")
            except DatabaseException:
                flash.error("Something went wrong! Unable to reset token right now.")
        return redirect(url_for("profile.info"))
    else:
        token = current_user.auth_token
        return render_template(
            "user/resettoken.html",
            token=token,
        )
Esempio n. 9
0
def reset_token():
    form = FlaskForm()
    if form.validate_on_submit():
        try:
            db_user.update_token(current_user.id)
            flash.info("Access token reset")
        except DatabaseException:
            flash.error(
                "Something went wrong! Unable to reset token right now.")
        return redirect(url_for("profile.info"))

    if form.csrf_token.errors:
        flash.error(
            'Cannot reset token due to error during authentication, please try again later.'
        )
        return redirect(url_for('profile.info'))

    return render_template(
        "user/resettoken.html",
        form=form,
    )
Esempio n. 10
0
def request_stats():
    """ Check if the current user's statistics have been calculated and if not,
        put them in the stats queue for stats_calculator.
    """
    status = _redis.redis.get(construct_stats_queue_key(current_user.musicbrainz_id)) == 'queued'
    if status == 'queued':
        flash.info('You have already been added to the stats calculation queue! Please check back later.')
    elif db_stats.valid_stats_exist(current_user.id):
        flash.info('Your stats were calculated in the most recent stats calculation interval,'
            ' please wait until the next interval! We calculate new statistics every Monday at 00:00 UTC.')
    else:
        # publish to rabbitmq queue that the stats-calculator consumes
        data = {
            'type': 'user',
            'id': current_user.id,
            'musicbrainz_id': current_user.musicbrainz_id,
        }
        publish_data_to_queue(
            data=data,
            exchange=current_app.config['BIGQUERY_EXCHANGE'],
            queue=current_app.config['BIGQUERY_QUEUE'],
            error_msg='Could not put user %s into statistics calculation queue, please try again later',
        )
        _redis.redis.set(construct_stats_queue_key(current_user.musicbrainz_id), 'queued')
        flash.info('You have been added to the stats calculation queue! Please check back later.')
    return redirect(url_for('profile.info'))
Esempio n. 11
0
def request_stats():
    """ Check if the current user's statistics have been calculated and if not,
        put them in the stats queue for stats_calculator.
    """
    status = _redis.redis.get(
        construct_stats_queue_key(current_user.musicbrainz_id)) == 'queued'
    if status == 'queued':
        flash.info(
            'You have already been added to the stats calculation queue! Please check back later.'
        )
    elif db_stats.valid_stats_exist(current_user.id):
        flash.info(
            'Your stats were calculated in the most recent stats calculation interval,'
            ' please wait until the next interval! We calculate new statistics every Monday at 00:00 UTC.'
        )
    else:
        # publish to rabbitmq queue that the stats-calculator consumes
        data = {
            'type': 'user',
            'id': current_user.id,
            'musicbrainz_id': current_user.musicbrainz_id,
        }
        publish_data_to_queue(
            data=data,
            exchange=current_app.config['BIGQUERY_EXCHANGE'],
            queue=current_app.config['BIGQUERY_QUEUE'],
            error_msg=
            'Could not put user %s into statistics calculation queue, please try again later',
        )
        _redis.redis.set(
            construct_stats_queue_key(current_user.musicbrainz_id), 'queued')
        flash.info(
            'You have been added to the stats calculation queue! Please check back later.'
        )
    return redirect(url_for('profile.info'))