<commit_before>import os
import json

from flask import request, render_template, jsonify, session

from flask import send_from_directory
from flask import make_response, abort
from flask.ext.socketio import emit, join_room, leave_room

from flask.ext.bcrypt import Bcrypt

from angular_flask import app, socketio

# routing for API endpoints, generated from the models designated as API_MODELS
from angular_flask.core import api_manager
from angular_flask.models import *

#Add logger to print to console
import logging
logger = logging.basicConfig()

#Create hashing functionality
bcrypt = Bcrypt(app)

# models for which we want to create API endpoints
for model_name in app.config['API_MODELS']:
    model_class = app.config['API_MODELS'][model_name]
    api_manager.create_api(model_class, methods=['GET', 'POST', 'PUT', 'PATCH'])

#Db session for making
db_session = api_manager.session

@socketio.on('join', namespace='/client')
def on_join(data):
    if data["queue"]:
        queue = data['queue']
        join_room(queue)

@socketio.on('leave', namespace='/client')
def on_leave(data):
    if data["queue"]:
        queue = data['queue']
        leave_room(queue)

@socketio.on('vote', namespace='/client')
def handle_voting(data):
    if data["vote_for"]:
        song = Song.query.filter(Song.id == int(data['vote_for'])).first()
        if song :
            song.votes = song.votes + 1
            db_session.commit()
            emit('vote', {'updated': [{'id': song.id, 'votes': song.votes}]}, room=song.queue_id)
        else:
            #TODO: Add Error Handling
            print("song doesnt exist")


@socketio.on('player-control', namespace='/client')
def handle_player_change(data):
    if "new" in data:
        songs = Song.query.filter(Song.queue_id == int(data["queue"])).order_by(Song.votes).all()
        print(songs)
        dictionary = dict()
        for song in songs:
            dictionary[song.votes] = song

        maxVotes = 0
        for votes in dictionary:
            if votes > maxVotes:
                maxVotes = votes
        emit('player-change', {'action': 'new','url': song.url}, room=song.queue_id)
        print(song, song.title, song.votes, song.queue_id)
        song.votes = 0
        db_session.commit()
        emit('vote', {'updated': [{'id': song.id, 'votes': song.votes}]}, room=song.queue_id)
        return
    elif "stop" in data:
        emit('player-change', {'action': 'stop'}, room=data['queue'])
        return
    elif "start" in data:
        emit('player-change', {'action': 'start'}, room=data['queue'])
        return
    elif "seek" in data:
        return

#TODO: Rewrite video_client handler using socketio
def handle_websocket(ws, url="xjB7J9dOtSM", queueID = 1):
    while True:
        f = open('ws.log', 'w')
        message = ws.receive()
        if message is None:
            break
        else:
            message = json.loads(message)

        songs = db_session.query(Song).all()
        dictionary = dict()
        for song in songs:
            dictionary[song.votes] = song

        maxVotes = 0
        for votes in dictionary:
            if votes > maxVotes:
                maxVotes = votes
        url = dictionary[maxVotes].url.partition('v=')[2][:11]
        f.write(url)
        f.write('\n')
        ws.send(json.dumps({'output':url}))

        toDelete = dictionary[maxVotes]
        toDelete.votes = 0

        db_session.add(toDelete)
        db_session.flush()

        f.close()

@app.route('/client', methods=['GET', 'POST'])
def client():
    return render_template('client.html')<commit_msg>Comments - explaining how websockets are handled<commit_after>import os
import json

from flask import request, render_template, jsonify, session

from flask import send_from_directory
from flask import make_response, abort
from flask.ext.socketio import emit, join_room, leave_room

from flask.ext.bcrypt import Bcrypt

from angular_flask import app, socketio

# routing for API endpoints, generated from the models designated as API_MODELS
from angular_flask.core import api_manager
from angular_flask.models import *

#Add logger to print to console
import logging
logger = logging.basicConfig()

#Create hashing functionality
bcrypt = Bcrypt(app)

# models for which we want to create API endpoints
for model_name in app.config['API_MODELS']:
    model_class = app.config['API_MODELS'][model_name]
    api_manager.create_api(model_class, methods=['GET', 'POST', 'PUT', 'PATCH'])

#Db session for making
db_session = api_manager.session

@socketio.on('join', namespace='/client')
def on_join(data):
    if data["queue"]:
        queue = data['queue']
        join_room(queue)

@socketio.on('leave', namespace='/client')
def on_leave(data):
    if data["queue"]:
        queue = data['queue']
        leave_room(queue)

@socketio.on('vote', namespace='/client')
def handle_voting(data):
    if data["vote_for"]:
        song = Song.query.filter(Song.id == int(data['vote_for'])).first()
        if song :
            song.votes = song.votes + 1
            db_session.commit()
            emit('vote', {'updated': [{'id': song.id, 'votes': song.votes}]}, room=song.queue_id)
        else:
            #TODO: Add Error Handling
            print("song doesnt exist")


@socketio.on('player-control', namespace='/client')
def handle_player_change(data):
    if "new" in data:
        songs = Song.query.filter(Song.queue_id == int(data["queue"])).order_by(Song.votes).all()
        print(songs)
        dictionary = dict()
        for song in songs:
            dictionary[song.votes] = song

        maxVotes = 0
        for votes in dictionary:
            if votes > maxVotes:
                maxVotes = votes
        emit('player-change', {'action': 'new','url': song.url}, room=song.queue_id)
        print(song, song.title, song.votes, song.queue_id)
        song.votes = 0
        db_session.commit()
        emit('vote', {'updated': [{'id': song.id, 'votes': song.votes}]}, room=song.queue_id)
        return
    elif "stop" in data:
        emit('player-change', {'action': 'stop'}, room=data['queue'])
        return
    elif "start" in data:
        emit('player-change', {'action': 'start'}, room=data['queue'])
        return
    elif "seek" in data:
        return

#TODO: Rewrite video_client handler using socketio
def handle_websocket(ws, url="xjB7J9dOtSM", queueID = 1):
    while True:
        f = open('ws.log', 'w')
        
	# The following action blocks
	message = ws.receive()
        if message is None:
            break
        else:
            message = json.loads(message)

	# Fetch the list of songs in the database
        songs = db_session.query(Song).all()

	# Map out the most popular songs
	# Number of votes	->	Song object
	# Tie breaking favors the latest song observed
        dictionary = dict()
        for song in songs:
            dictionary[song.votes] = song

	# Figure out which song is most popular
        maxVotes = 0
        for votes in dictionary:
            if votes > maxVotes:
                maxVotes = votes

	# Parse out the video ID
        url = dictionary[maxVotes].url.partition('v=')[2][:11]
        f.write(url)
        f.write('\n')

	# Send the video ID of the most popular song to clients
        ws.send(json.dumps({'output':url}))

	# Delete most popular song now that it's been pushed out to clients
        toDelete = dictionary[maxVotes]
        toDelete.votes = 0
        db_session.add(toDelete)
        db_session.flush()

        f.close()

@app.route('/client', methods=['GET', 'POST'])
def client():
    return render_template('client.html')
{'fraction_non_alphanumeric': 0.12713198635528733, 'fraction_numerical': 0.0028863815271582263, 'mean_word_length': 2.8095952023988007, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, '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': '4110703', 'n_tokens_mistral': 2392, 'n_tokens_neox': 2307, 'n_words': 633}