mirror of
https://gitlab.science.ru.nl/technicie/MarietjeDjango.git
synced 2025-12-09 19:52:20 +01:00
73 lines
2.0 KiB
Python
73 lines
2.0 KiB
Python
import socket, struct, binascii
|
|
from django.conf import settings
|
|
from queues.models import Queue, Playlist
|
|
from django.http import StreamingHttpResponse
|
|
|
|
|
|
def song_to_dict(song, hash=False, user=False):
|
|
data = {
|
|
'id': song.id,
|
|
'artist': song.artist,
|
|
'title': song.title,
|
|
'duration': song.duration
|
|
}
|
|
|
|
if hash:
|
|
data['hash'] = song.hash
|
|
|
|
if user and song.user is not None and len(song.user.name) > 1:
|
|
data['uploader_name'] = song.user.name
|
|
return data
|
|
|
|
|
|
def playlist_song_to_dict(playlist_song, hash=False, user=None):
|
|
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, hash=hash),
|
|
'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)
|
|
hash = binascii.hexlify(sock.recv(64))
|
|
sock.close()
|
|
return 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(hash):
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
sock.connect(settings.BERTHA_HOST)
|
|
sock.sendall(struct.pack("<B", 2) + binascii.unhexlify(hash))
|
|
data = sock.recv(4096)
|
|
while data:
|
|
yield data
|
|
data = sock.recv(4096)
|
|
sock.close()
|
|
|
|
|
|
def get_from_bertha(hash):
|
|
response = StreamingHttpResponse(bertha_stream(hash))
|
|
response['Content-Disposition'] = 'attachment; filename="{}"'.format(hash)
|
|
return response
|