<commit_before>"""
Browse your local movies with IMDB data and stream them to a Chromecast.
"""
from flask import Flask, flash, redirect, render_template, url_for
from media import Media
from werkzeug.urls import url_decode
import argparse
import mimetypes
import os
import partial_file
import pychromecast
import time

app = Flask(__name__)
app.config.update({
    'CHROMECAST_NAME': os.environ['CHROMECAST_NAME'],
    'MEDIA_FORMATS': ('.mp4', '.mkv'),
    'MEDIA_PATH': os.environ['MEDIA_PATH'],
    'SECRET_KEY': os.environ['SECRET_KEY'],
})

chromecast = None  # Global containing a connection to the Chromecast device


@app.route('/')
def index():
    """Returns all media within the directory."""
    media = os.listdir(app.config['MEDIA_PATH'])
    media = filter(lambda x: x.endswith(app.config['MEDIA_FORMATS']), media)
    media = [Media(x) for x in media]
    media = [x.to_dict() for x in media]

    global chromecast
    if not chromecast:
        chromecast = pychromecast.get_chromecast(
            friendly_name=app.config['CHROMECAST_NAME']
        )
        if not chromecast:
            flash('Chromecast not found.', 'error')

    now_playing = None
    is_paused = False

    if chromecast:
        if chromecast.is_idle:
            flash('Chromecast is idle.', 'info')

        chromecast.wait()
        media_controller = chromecast.media_controller

        if media_controller.is_paused or media_controller.is_playing:
            is_paused = media_controller.is_paused

            content_id = media_controller.status.content_id
            filename = url_decode(content_id).keys()[0].split('/')[-1]
            now_playing = Media(filename).to_dict()

    return render_template(
        'index.html',
        is_paused=is_paused,
        media=media,
        now_playing=now_playing,
    )


@app.route('/cast/<filename>')
def cast(filename):
    """Casts the filename to a chromecast."""
    global chromecast
    if not chromecast:
        chromecast = pychromecast.get_chromecast(
            friendly_name=app.config['CHROMECAST_NAME']
        )
        if not chromecast:
            flash('Chromecast not found.', 'error')
            return redirect(url_for('index'))

    media = Media(filename).to_dict()
    mimetype, _ = mimetypes.guess_type(filename)
    chromecast.media_controller.play_media(media['urls']['media'], mimetype)

    time.sleep(6)

    return redirect(url_for('index'))


@app.route('/play')
def play():
    """Resumes playback of the media on the Chromecast."""
    global chromecast
    if not chromecast:
        chromecast = pychromecast.get_chromecast(
            friendly_name=app.config['CHROMECAST_NAME']
        )
        if not chromecast:
            flash('Chromecast not found.', 'error')
            return redirect(url_for('index'))

    chromecast.media_controller.play()

    time.sleep(1)

    return redirect(url_for('index'))


@app.route('/pause')
def pause():
    """Pauses playback of the media on the Chromecast."""
    global chromecast
    if not chromecast:
        chromecast = pychromecast.get_chromecast(
            friendly_name=app.config['CHROMECAST_NAME']
        )
        if not chromecast:
            flash('Chromecast not found.', 'error')
            return redirect(url_for('index'))

    chromecast.media_controller.pause()

    time.sleep(1)

    return redirect(url_for('index'))


@app.route('/stop')
def stop():
    """Stops playback of the media on the Chromecast."""
    global chromecast
    if not chromecast:
        chromecast = pychromecast.get_chromecast(
            friendly_name=app.config['CHROMECAST_NAME']
        )
        if not chromecast:
            flash('Chromecast not found.', 'error')
            return redirect(url_for('index'))

    chromecast.media_controller.stop()

    time.sleep(1)

    return redirect(url_for('index'))


@app.route('/media/<filename>')
def media(filename):
    """Serves a media file via the 206 partial protocol."""
    path = '{}/{}'.format(app.config['MEDIA_PATH'], filename)
    return partial_file.send(path)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--debug', action='store_true', default=False)
    parser.add_argument('--host', default='127.0.0.1')
    parser.add_argument('--port', default='5000', type=int)
    args = parser.parse_args()
    app.run(
        host=args.host,
        port=args.port,
        debug=args.debug
    )<commit_msg>Clean up app.run<commit_after>"""
Browse your local movies with IMDB data and stream them to a Chromecast.
"""
from flask import Flask, flash, redirect, render_template, url_for
from media import Media
from werkzeug.urls import url_decode
import argparse
import mimetypes
import os
import partial_file
import pychromecast
import time

app = Flask(__name__)
app.config.update({
    'CHROMECAST_NAME': os.environ['CHROMECAST_NAME'],
    'MEDIA_FORMATS': ('.mp4', '.mkv'),
    'MEDIA_PATH': os.environ['MEDIA_PATH'],
    'SECRET_KEY': os.environ['SECRET_KEY'],
})

chromecast = None  # Global containing a connection to the Chromecast device


@app.route('/')
def index():
    """Returns all media within the directory."""
    media = os.listdir(app.config['MEDIA_PATH'])
    media = filter(lambda x: x.endswith(app.config['MEDIA_FORMATS']), media)
    media = [Media(x) for x in media]
    media = [x.to_dict() for x in media]

    global chromecast
    if not chromecast:
        chromecast = pychromecast.get_chromecast(
            friendly_name=app.config['CHROMECAST_NAME']
        )
        if not chromecast:
            flash('Chromecast not found.', 'error')

    now_playing = None
    is_paused = False

    if chromecast:
        if chromecast.is_idle:
            flash('Chromecast is idle.', 'info')

        chromecast.wait()
        media_controller = chromecast.media_controller

        if media_controller.is_paused or media_controller.is_playing:
            is_paused = media_controller.is_paused

            content_id = media_controller.status.content_id
            filename = url_decode(content_id).keys()[0].split('/')[-1]
            now_playing = Media(filename).to_dict()

    return render_template(
        'index.html',
        is_paused=is_paused,
        media=media,
        now_playing=now_playing,
    )


@app.route('/cast/<filename>')
def cast(filename):
    """Casts the filename to a chromecast."""
    global chromecast
    if not chromecast:
        chromecast = pychromecast.get_chromecast(
            friendly_name=app.config['CHROMECAST_NAME']
        )
        if not chromecast:
            flash('Chromecast not found.', 'error')
            return redirect(url_for('index'))

    media = Media(filename).to_dict()
    mimetype, _ = mimetypes.guess_type(filename)
    chromecast.media_controller.play_media(media['urls']['media'], mimetype)

    time.sleep(6)

    return redirect(url_for('index'))


@app.route('/play')
def play():
    """Resumes playback of the media on the Chromecast."""
    global chromecast
    if not chromecast:
        chromecast = pychromecast.get_chromecast(
            friendly_name=app.config['CHROMECAST_NAME']
        )
        if not chromecast:
            flash('Chromecast not found.', 'error')
            return redirect(url_for('index'))

    chromecast.media_controller.play()

    time.sleep(1)

    return redirect(url_for('index'))


@app.route('/pause')
def pause():
    """Pauses playback of the media on the Chromecast."""
    global chromecast
    if not chromecast:
        chromecast = pychromecast.get_chromecast(
            friendly_name=app.config['CHROMECAST_NAME']
        )
        if not chromecast:
            flash('Chromecast not found.', 'error')
            return redirect(url_for('index'))

    chromecast.media_controller.pause()

    time.sleep(1)

    return redirect(url_for('index'))


@app.route('/stop')
def stop():
    """Stops playback of the media on the Chromecast."""
    global chromecast
    if not chromecast:
        chromecast = pychromecast.get_chromecast(
            friendly_name=app.config['CHROMECAST_NAME']
        )
        if not chromecast:
            flash('Chromecast not found.', 'error')
            return redirect(url_for('index'))

    chromecast.media_controller.stop()

    time.sleep(1)

    return redirect(url_for('index'))


@app.route('/media/<filename>')
def media(filename):
    """Serves a media file via the 206 partial protocol."""
    path = '{}/{}'.format(app.config['MEDIA_PATH'], filename)
    return partial_file.send(path)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--debug', action='store_true', default=False)
    parser.add_argument('--host', default='127.0.0.1')
    parser.add_argument('--port', default='5000', type=int)
    args = parser.parse_args()
    app.run(host=args.host, port=args.port, debug=args.debug)
{'fraction_non_alphanumeric': 0.12294440093970242, 'fraction_numerical': 0.004474773464593355, 'mean_word_length': 3.0342960288808665, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2568795', 'n_tokens_mistral': 2903, 'n_tokens_neox': 2793, 'n_words': 615}