Files
MarietjeDjango/marietje/marietje/utils.py

83 lines
2.3 KiB
Python

import binascii
import socket
import struct
from django.conf import settings
from django.http import StreamingHttpResponse
from queues.models import Queue, Playlist
def song_to_dict(song, include_hash=False, include_user=False, include_replaygain=False, **options):
data = {
"id": song.id,
"artist": song.artist,
"title": song.title,
"duration": song.duration,
}
if include_hash:
data["hash"] = song.hash
if include_user is not None and song.user is not None and song.user.name:
data["uploader_name"] = song.user.name
if include_replaygain:
data["rg_gain"] = song.rg_gain
data["rg_peak"] = song.rg_peak
return data
def playlist_song_to_dict(playlist_song, **options):
user = options.get("user")
return {
"id": playlist_song.id,
"requested_by": "Marietje" if playlist_song.user is None else playlist_song.user.name,
"song": song_to_dict(playlist_song.song, **options),
"can_move_down": playlist_song.user is not None and playlist_song.user == user,
}
# Send a file to bertha file storage.
def send_to_bertha(file):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(settings.BERTHA_HOST)
sock.sendall(struct.pack("<BQ", 4, file.size))
for chunk in file.chunks():
sock.sendall(chunk)
sock.shutdown(socket.SHUT_WR)
song_hash = binascii.hexlify(sock.recv(64))
sock.close()
return song_hash
def get_first_queue():
queue = Queue.objects.first()
if queue is None:
playlist = Playlist()
playlist.save()
random_playlist = Playlist()
random_playlist.save()
queue = Queue(name="Queue", playlist=playlist, random_playlist=random_playlist)
queue.save()
return queue
def bertha_stream(song_hash):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(settings.BERTHA_HOST)
sock.sendall(struct.pack("<B", 2) + binascii.unhexlify(song_hash))
data = sock.recv(4096)
while data:
yield data
data = sock.recv(4096)
sock.close()
def get_from_bertha(song_hash):
response = StreamingHttpResponse(bertha_stream(song_hash))
response["Content-Disposition"] = 'attachment; filename="{}"'.format(song_hash)
return response