<commit_before># NOTE: the .php filenames are kept so old URLs keep working

from flask import current_app, jsonify, render_template, redirect, request, \
        url_for, Response
import datetime
import dateutil.parser
import re
from werkzeug.contrib.atom import AtomFeed

from . import bp
from .view_utils import call_api, make_external, \
        tracklog_serialize, tracklog_full_serialize


def trackinfo():
    return call_api("/playlists/latest_track", 'GET')


#############################################################################
# Playlist Information
#############################################################################


@bp.route('/last15')
def last15():
    result = call_api("/playlists/last15", 'GET')

    if request.wants_json():
        return jsonify({
            'tracks': [tracklog_full_serialize(t) for t in result['tracks']],
        })

    return render_template('last15.html', tracklogs=result['tracks'],
                           feedlink=url_for('.last15_feed'))


@bp.route('/last15.atom')
def last15_feed():
    result = call_api("/playlists/last15", 'GET')
    tracks = result['tracks']
    feed = AtomFeed(
        "{0}: Last 15 Tracks".format(current_app.config['TRACKMAN_NAME']),
        feed_url=request.url,
        url=make_external(url_for('.last15')))

    for tracklog in tracks:
        feed.add(
            "{artist}: '{title}'".format(
                artist=tracklog['track']['artist'],
                title=tracklog['track']['title']),
            "'{title}' by {artist} on {album} spun by {dj}".format(
                album=tracklog['track']['album'],
                artist=tracklog['track']['artist'],
                title=tracklog['track']['title'],
                dj=tracklog['dj']['airname']),
            url=make_external(url_for('.playlist',
                                      set_id=tracklog['djset_id'],
                                      _anchor="t{}".format(tracklog['id']))),
            author=tracklog['dj']['airname'],
            updated=tracklog['played'],
            published=tracklog['played'])

    return feed.get_response()


@bp.route('/playlists/latest_track')
@bp.route('/playlists/latest_track.php')
def latest_track():
    if request.wants_json():
        return jsonify(trackinfo())

    return Response("{artist} - {title}".format(**trackinfo()),
                    mimetype="text/plain")


@bp.route('/playlists/latest_track_clean')
@bp.route('/playlists/latest_track_clean.php')
def latest_track_clean():
    naughty_word_re = re.compile(
        r'shit|piss|fuck|cunt|cocksucker|tits|twat|asshole',
        re.IGNORECASE)

    track = trackinfo()
    for k, v in list(track.items()):
        if type(v) == str or type(v) == str:
            track[k] = naughty_word_re.sub('****', v)

    if request.wants_json():
        return jsonify(track)

    output = "{artist} - {title} [DJ: {dj}]".format(**track)
    return Response(output, mimetype="text/plain")


@bp.route('/playlists/latest_track_slack')
def latest_track_slack():
    track = trackinfo()

    if track['dj_id'] > 0:
        dj_link = '<{url}|{dj}>'.format(
            dj=track['dj'],
            url=make_external(url_for('.playlists_dj_sets',
                                      dj_id=track['dj_id'])))
    else:
        dj_link = track['dj']

    return jsonify({
        "response_type": "in_channel",
        "text": "*{artist} - {title}*\nDJ: {dj_link}".format(
            dj_link=dj_link, **track),
    })


@bp.route('/playlists/latest_track_stream')
@bp.route('/playlists/latest_track_stream.php')
def latest_track_stream():
    return Response("""\
title={title}
artist={artist}
album={album}
description={description}
contact={contact}
""".format(**trackinfo()), mimetype="text/plain")


@bp.route('/playlists/live')
@bp.route('/live')
def live():
    url = "{0}/live".format(current_app.config['TRACKMAN_URL'])
    return redirect(url, 303)


# Playlist Archive (by date) {{{
@bp.route('/playlists/date')
def playlists_date():
    today = datetime.datetime.utcnow().replace(
        hour=0, minute=0, second=0, microsecond=0)
    return render_template('playlists_date_list.html', today=today)


@bp.route('/playlists/date/<int:year>/<int:month>/<int:day>')
def playlists_date_sets(year, month, day):
    results, status_code = call_api(
        "/playlists/date/{0}/{1}/{2}", 'GET', year, month, day)

    now = datetime.datetime.utcnow()

    next_date = results['dtstart'] + datetime.timedelta(hours=24)
    next_url = url_for('.playlists_date_sets', year=next_date.year,
                       month=next_date.month, day=next_date.day)
    if next_date > now:
        next_url = None

    if results['dtstart'] < now:
        prev_date = results['dtstart'] - datetime.timedelta(hours=24)
        prev_url = url_for('.playlists_date_sets', year=prev_date.year,
                           month=prev_date.month, day=prev_date.day)
    else:
        prev_url = None

    results.update({
        'prev_url': prev_url,
        'next_url': next_url,
    })

    if request.wants_json():
        return jsonify(results), status_code

    return render_template(
        'playlists_date_sets.html',
        date=results['dtstart'],
        sets=results['sets'],
        prev_url=results['prev_url'],
        next_url=results['next_url']), status_code


@bp.route('/playlists/date/jump', methods=['POST'])
def playlists_date_jump():
    jumpdate = datetime.datetime.strptime(request.form['date'], "%Y-%m-%d")<commit_msg>Fix a few date-parsing issues in Trackman client<commit_after># NOTE: the .php filenames are kept so old URLs keep working

from flask import current_app, jsonify, render_template, redirect, request, \
        url_for, Response
import datetime
import dateutil.parser
import re
from werkzeug.contrib.atom import AtomFeed

from . import bp
from .view_utils import call_api, make_external, \
        tracklog_serialize, tracklog_full_serialize


def trackinfo():
    return call_api("/playlists/latest_track", 'GET')


#############################################################################
# Playlist Information
#############################################################################


@bp.route('/last15')
def last15():
    result = call_api("/playlists/last15", 'GET')

    if request.wants_json():
        return jsonify({
            'tracks': [tracklog_full_serialize(t) for t in result['tracks']],
        })

    return render_template('last15.html', tracklogs=result['tracks'],
                           feedlink=url_for('.last15_feed'))


@bp.route('/last15.atom')
def last15_feed():
    result = call_api("/playlists/last15", 'GET')
    tracks = result['tracks']
    feed = AtomFeed(
        "{0}: Last 15 Tracks".format(current_app.config['STATION_SHORT_NAME']),
        feed_url=request.url,
        url=make_external(url_for('.last15')))

    for tracklog in tracks:
        feed.add(
            "{artist}: '{title}'".format(
                artist=tracklog['track']['artist'],
                title=tracklog['track']['title']),
            "'{title}' by {artist} on {album} spun by {dj}".format(
                album=tracklog['track']['album'],
                artist=tracklog['track']['artist'],
                title=tracklog['track']['title'],
                dj=tracklog['dj']['airname']),
            url=make_external(url_for('.playlist',
                                      set_id=tracklog['djset_id'],
                                      _anchor="t{}".format(tracklog['id']))),
            author=tracklog['dj']['airname'],
            updated=dateutil.parser.parse(tracklog['played']),
            published=dateutil.parser.parse(tracklog['played']))

    return feed.get_response()


@bp.route('/playlists/latest_track')
@bp.route('/playlists/latest_track.php')
def latest_track():
    if request.wants_json():
        return jsonify(trackinfo())

    return Response("{artist} - {title}".format(**trackinfo()),
                    mimetype="text/plain")


@bp.route('/playlists/latest_track_clean')
@bp.route('/playlists/latest_track_clean.php')
def latest_track_clean():
    naughty_word_re = re.compile(
        r'shit|piss|fuck|cunt|cocksucker|tits|twat|asshole',
        re.IGNORECASE)

    track = trackinfo()
    for k, v in list(track.items()):
        if type(v) == str or type(v) == str:
            track[k] = naughty_word_re.sub('****', v)

    if request.wants_json():
        return jsonify(track)

    output = "{artist} - {title} [DJ: {dj}]".format(**track)
    return Response(output, mimetype="text/plain")


@bp.route('/playlists/latest_track_slack')
def latest_track_slack():
    track = trackinfo()

    if track['dj_id'] > 0:
        dj_link = '<{url}|{dj}>'.format(
            dj=track['dj'],
            url=make_external(url_for('.playlists_dj_sets',
                                      dj_id=track['dj_id'])))
    else:
        dj_link = track['dj']

    return jsonify({
        "response_type": "in_channel",
        "text": "*{artist} - {title}*\nDJ: {dj_link}".format(
            dj_link=dj_link, **track),
    })


@bp.route('/playlists/latest_track_stream')
@bp.route('/playlists/latest_track_stream.php')
def latest_track_stream():
    return Response("""\
title={title}
artist={artist}
album={album}
description={description}
contact={contact}
""".format(**trackinfo()), mimetype="text/plain")


@bp.route('/playlists/live')
@bp.route('/live')
def live():
    url = "{0}/live".format(current_app.config['TRACKMAN_URL'])
    return redirect(url, 303)


# Playlist Archive (by date) {{{
@bp.route('/playlists/date')
def playlists_date():
    today = datetime.datetime.utcnow().replace(
        hour=0, minute=0, second=0, microsecond=0)
    return render_template('playlists_date_list.html', today=today)


@bp.route('/playlists/date/<int:year>/<int:month>/<int:day>')
def playlists_date_sets(year, month, day):
    results, status_code = call_api(
        "/playlists/date/{0}/{1}/{2}", 'GET', year, month, day)

    now = datetime.datetime.utcnow()
    start_date = dateutil.parser.parse(results['dtstart'])
    next_date = start_date + datetime.timedelta(hours=24)
    next_url = url_for('.playlists_date_sets', year=next_date.year,
                       month=next_date.month, day=next_date.day)
    if next_date > now:
        next_url = None

    if start_date < now:
        prev_date = start_date - datetime.timedelta(hours=24)
        prev_url = url_for('.playlists_date_sets', year=prev_date.year,
                           month=prev_date.month, day=prev_date.day)
    else:
        prev_url = None

    results.update({
        'prev_url': prev_url,
        'next_url': next_url,
    })

    if request.wants_json():
        return jsonify(results), status_code

    return render_template(
        'playlists_date_sets.html',
        date=results['dtstart'],
        sets=results['sets'],
        prev_url=results['prev_url'],
        next_url=results['next_url']), status_code


@bp.route('/playlists/date/jump', methods=['POST'])
def playlists_date_jump():
    jumpdate = datetime.datetime.strptime(request.form['date'], "%Y-%m-%d")
{'fraction_non_alphanumeric': 0.18268367163642896, 'fraction_numerical': 0.006646308604275193, 'mean_word_length': 3.101289134438306, 'pattern_counts': {'":': 4, '<': 13, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2815433', 'n_tokens_mistral': 3632, 'n_tokens_neox': 3435, 'n_words': 594}