aboutsummaryrefslogtreecommitdiff
path: root/apps
diff options
context:
space:
mode:
authorBobby <[email protected]>2024-12-12 15:40:19 -0500
committerBobby <[email protected]>2024-12-12 15:40:19 -0500
commitefb25b04c72b972c3eaf949d97ea81a38edacb21 (patch)
tree6a0c40d986d7a3eb05f6e42c17d473dc2f63a97f /apps
parent281b7301c8d97051e28608789ce07a5d505e476c (diff)
downloadthatcomputerscientist-efb25b04c72b972c3eaf949d97ea81a38edacb21.tar.xz
thatcomputerscientist-efb25b04c72b972c3eaf949d97ea81a38edacb21.zip
generic song impl: will switch to db possibly
Diffstat (limited to 'apps')
-rw-r--r--apps/stream/songs.py92
-rw-r--r--apps/stream/views.py185
2 files changed, 195 insertions, 82 deletions
diff --git a/apps/stream/songs.py b/apps/stream/songs.py
new file mode 100644
index 00000000..78fb79ca
--- /dev/null
+++ b/apps/stream/songs.py
@@ -0,0 +1,92 @@
+MUSIC_FILES = [
+ {
+ "id": "Bling-Bang-Bang-Born.mp3",
+ "title": "Bling Bang Bang Born",
+ "artist": "CREEPY NUTS",
+ "album": "Bling Bang Bang Born",
+ },
+ {
+ "id": "DADDY ! DADDY ! DO !.mp3",
+ "title": "DADDY ! DADDY ! DO !",
+ "artist": "Masayuki Suzuki",
+ "album": "Kaguya-sama: Love Is War",
+ },
+ {
+ "id": "Duvet.mp3",
+ "title": "Duvet",
+ "artist": "Boa",
+ "album": "Serial Experiments Lain",
+ },
+ {
+ "id": "Nandemonaiya - movie ver..mp3",
+ "title": "Nandemonaiya - movie ver.",
+ "artist": "RADWIMPS",
+ "album": "Your Name",
+ },
+ {
+ "id": "Shinunoga E-Wa.mp3",
+ "title": "Shinunoga E-Wa",
+ "artist": "Fujii Kaze",
+ "album": "HELP EVER HURT NEVER",
+ },
+ {
+ "id": "Sparkle - movie ver..mp3",
+ "title": "Sparkle - movie ver.",
+ "artist": "RADWIMPS",
+ "album": "Your Name",
+ },
+ {
+ "id": "Zenzenzense - movie ver..mp3",
+ "title": "Zenzenzense - movie ver.",
+ "artist": "RADWIMPS",
+ "album": "Your Name",
+ },
+ {
+ "id": "アイドル.mp3",
+ "title": "アイドル",
+ "artist": "YOASOBI",
+ "album": "アイドル",
+ },
+ {
+ "id": "ただ声一つ.mp3",
+ "title": "ただ声一つ",
+ "artist": "ロクデナシ",
+ "album": "ただ声一つ",
+ },
+ {
+ "id": "好きだから。.mp3",
+ "title": "好きだから。",
+ "artist": "『ユイカ』",
+ "album": "好きだから。",
+ },
+ {
+ "id": "忘れてください.mp3",
+ "title": "忘れてください",
+ "artist": "Yorushika",
+ "album": "忘れてください",
+ },
+ {
+ "id": "恋愛サーキュレーション.mp3",
+ "title": "恋愛サーキュレーション",
+ "artist": "物語シリーズ",
+ "album": "Utamonogatari Special Edition",
+ },
+ {
+ "id": "知らないままで.mp3",
+ "title": "知らないままで",
+ "artist": "ロクデナシ",
+ "album": "知らないままで",
+ },
+ {
+ "id": "言って。.mp3",
+ "title": "言って。",
+ "artist": "Yorushika",
+ "album": "夏草が邪魔をする",
+ },
+ {
+ "id": "青のすみか.mp3",
+ "title": "青のすみか",
+ "artist": "Tatsuya Kitani",
+ "album": "青のすみか",
+ },
+]
diff --git a/apps/stream/views.py b/apps/stream/views.py
index 820792c2..707a92af 100644
--- a/apps/stream/views.py
+++ b/apps/stream/views.py
@@ -2,100 +2,121 @@
import os
import random
from hashlib import md5
-from typing import Dict, Union
-
+from apps.stream.songs import MUSIC_FILES
import requests
from django.http import HttpResponse, JsonResponse
-from django.conf import settings
-from django.core.cache import cache
-
-# Constants from environment variables
-API_CONFIG = {
- "BASE_URL": os.getenv("MUSIC_API_BASE_URL", "http://music.shi.foo/rest"),
- "USERNAME": os.getenv("MUSIC_API_USERNAME"),
- "PASSWORD": os.getenv("MUSIC_API_PASSWORD"),
- "VERSION": os.getenv("MUSIC_API_VERSION", "1.16.1"),
- "CLIENT": os.getenv("MUSIC_API_CLIENT", "Shifoo"),
-}
-
-
-def get_auth_params() -> Dict[str, str]:
- """Generate authentication parameters for API requests."""
- salt = "".join(random.choices("abcdefghijklmnopqrstuvwxyz0123456789", k=6))
- token = md5((API_CONFIG["PASSWORD"] + salt).encode()).hexdigest()
-
- return {
- "u": API_CONFIG["USERNAME"],
- "t": token,
- "s": salt,
- "v": API_CONFIG["VERSION"],
- "c": API_CONFIG["CLIENT"],
- }
-
-
-def make_api_request(
- endpoint: str, params: Dict = None, stream: bool = False
-) -> Union[requests.Response, Dict]:
- """Make an API request with error handling."""
- auth_params = get_auth_params()
- if params:
- auth_params.update(params)
-
- url = f"{API_CONFIG['BASE_URL']}/{endpoint}"
-
- try:
- response = requests.get(url, params=auth_params, stream=stream)
- response.raise_for_status()
- return response if stream else response.json()
- except requests.RequestException as e:
- # Log error here if you have logging configured
- return {"error": str(e)}
-
-
-def random_song(request) -> JsonResponse:
- """Get a random song from the API."""
- # Try to get cached response first
- cache_key = "random_song_response"
- cached_response = cache.get(cache_key)
- if cached_response:
- return JsonResponse(cached_response)
-
- response = make_api_request("getRandomSongs", {"size": 1, "f": "json"})
- if "error" in response:
- return JsonResponse({"error": response["error"]}, status=500)
+CDN_URL = os.getenv("CDN_URL")
- try:
- subsonic_response = response.get("subsonic-response", {})
- song = subsonic_response.get("randomSongs", {}).get("song", [{}])[0]
- if not song:
- return JsonResponse({"error": "No song found"}, status=404)
+def get_stream_url(filename: str) -> str:
+ return f"{CDN_URL}/music/{filename}"
- # Construct response data
- response_data = {
- "song": song,
- "coverURL": f"{API_CONFIG['BASE_URL']}/getCoverArt",
- "coverParams": {"id": song.get("coverArt"), **get_auth_params()},
- }
- # Cache the response for a short period
- cache.set(cache_key, response_data, 30) # Cache for 30 seconds
-
- return JsonResponse(response_data)
- except Exception as e:
- # Log error here if you have logging configured
- return JsonResponse({"error": str(e)}, status=500)
+def random_song(request) -> JsonResponse:
+ """Get a random song from the API."""
+ song = random.choice(MUSIC_FILES)
+ return JsonResponse(song)
def stream_song(request, song_id: str) -> HttpResponse:
- """Stream a specific song by ID."""
- response = make_api_request("stream", {"id": song_id}, stream=True)
-
- if isinstance(response, dict) and "error" in response:
- return JsonResponse({"error": response["error"]}, status=500)
+ """Stream a specific song by filename."""
+ stream_url = get_stream_url(song_id)
+ response = requests.get(stream_url, stream=True)
return HttpResponse(
response.raw.read(),
content_type=response.headers.get("Content-Type", "audio/mpeg"),
)
+
+
+# Constants from environment variables
+# API_CONFIG = {
+# "BASE_URL": os.getenv("MUSIC_API_BASE_URL", "http://music.shi.foo/rest"),
+# "USERNAME": os.getenv("MUSIC_API_USERNAME"),
+# "PASSWORD": os.getenv("MUSIC_API_PASSWORD"),
+# "VERSION": os.getenv("MUSIC_API_VERSION", "1.16.1"),
+# "CLIENT": os.getenv("MUSIC_API_CLIENT", "Shifoo"),
+# }
+
+
+# def get_auth_params() -> Dict[str, str]:
+# """Generate authentication parameters for API requests."""
+# salt = "".join(random.choices("abcdefghijklmnopqrstuvwxyz0123456789", k=6))
+# token = md5((API_CONFIG["PASSWORD"] + salt).encode()).hexdigest()
+
+# return {
+# "u": API_CONFIG["USERNAME"],
+# "t": token,
+# "s": salt,
+# "v": API_CONFIG["VERSION"],
+# "c": API_CONFIG["CLIENT"],
+# }
+
+
+# def make_api_request(
+# endpoint: str, params: Dict = None, stream: bool = False
+# ) -> Union[requests.Response, Dict]:
+# """Make an API request with error handling."""
+# auth_params = get_auth_params()
+# if params:
+# auth_params.update(params)
+
+# url = f"{API_CONFIG['BASE_URL']}/{endpoint}"
+
+# try:
+# response = requests.get(url, params=auth_params, stream=stream)
+# response.raise_for_status()
+# return response if stream else response.json()
+# except requests.RequestException as e:
+# # Log error here if you have logging configured
+# return {"error": str(e)}
+
+
+# def random_song(request) -> JsonResponse:
+# """Get a random song from the API."""
+# # Try to get cached response first
+# cache_key = "random_song_response"
+# cached_response = cache.get(cache_key)
+# if cached_response:
+# return JsonResponse(cached_response)
+
+# response = make_api_request("getRandomSongs", {"size": 1, "f": "json"})
+
+# if "error" in response:
+# return JsonResponse({"error": response["error"]}, status=500)
+
+# try:
+# subsonic_response = response.get("subsonic-response", {})
+# song = subsonic_response.get("randomSongs", {}).get("song", [{}])[0]
+
+# if not song:
+# return JsonResponse({"error": "No song found"}, status=404)
+
+# # Construct response data
+# response_data = {
+# "song": song,
+# "coverURL": f"{API_CONFIG['BASE_URL']}/getCoverArt",
+# "coverParams": {"id": song.get("coverArt"), **get_auth_params()},
+# }
+
+# # Cache the response for a short period
+# cache.set(cache_key, response_data, 30) # Cache for 30 seconds
+
+# return JsonResponse(response_data)
+# except Exception as e:
+# # Log error here if you have logging configured
+# return JsonResponse({"error": str(e)}, status=500)
+
+
+# def stream_song(request, song_id: str) -> HttpResponse:
+# """Stream a specific song by ID."""
+# response = make_api_request("stream", {"id": song_id}, stream=True)
+
+# if isinstance(response, dict) and "error" in response:
+# return JsonResponse({"error": response["error"]}, status=500)
+
+# return HttpResponse(
+# response.raw.read(),
+# content_type=response.headers.get("Content-Type", "audio/mpeg"),
+# )