import binascii import socket import struct from django.conf import settings from queues.models import PlaylistSong from songs.models import Song from django.db.models.functions import Coalesce from django.db.models import Sum, Value from django.db import transaction from mutagen import File class UploadException(Exception): pass def send_to_bertha(file): """Send a file to Berthad file storage.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(settings.BERTHA_HOST) sock.sendall(struct.pack(" float: try: stats = get_upload_stats(user) ratio = stats["queued_score"] / (2.0 * stats["upload_score"]) return ratio except ZeroDivisionError: return 99999.0 # high enough def check_upload_stats(user): # Allow upload if the user has a good reputation # Score function: # - U = duration * songs uploaded # - Q = duration * songs queued # - If 2*U < Q: allow upload (otherwise don't) if user.is_superuser: return True ratio = get_reputation(user) return ratio >= 1.0 def upload_file(file, artist, title, user): duration = File(file).info.length bertha_hash = send_to_bertha(file).decode("ascii") if not bertha_hash: raise UploadException("Files not uploaded correctly.") return Song.objects.create(user=user, artist=artist, title=title, hash=bertha_hash, duration=duration)