1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
|
# This file is part of Senator Sperma
# Licensed under the GPL-3.0 License
# Copyright (C) 2026 Salmonik @ salmonik@tuta.io
# https://codeberg.org/salmonik/senator-sperma
import logging
import os
import urllib.parse
import asyncio
from os import PathLike
from typing import Awaitable, Callable, List, Tuple
import re
from yt_dlp import YoutubeDL
import discord
from discord.commands import OptionChoice
from discord.ext import commands
from cogs.music import audio_playback, media_processing
from cogs.utils.file_search import UniversalSearcher
from cogs.utils.settings import get_uploadurl
logger = logging.getLogger(__name__)
EXTERNAL_URL_PATTERN = re.compile(
r"^https://(?=.*(?:youtube|youtu\.be|soundcloud|bandcamp))"
)
class PlayCommands(commands.Cog):
"""Discord slash commands for music playback."""
def __init__(self, bot):
from cogs.utils.temp import get_temp_dir
self.bot = bot
self.temp_dir = get_temp_dir()
self.path_mapping = {} # Maps display names to full paths
@staticmethod
async def _create_search_embed(
candidates: List[str],
) -> Tuple[discord.Embed, discord.ui.View]:
"""Create an embed and view for search results."""
embed = discord.Embed(
title="Wyniki wyszukiwania",
description="Wybierz plik do odtworzenia:",
color=discord.Color.blue(),
)
view = discord.ui.View(disable_on_timeout=True)
for i, candidate in enumerate(candidates, start=1):
filename = candidate.split("/")[-1].split("?")[0]
display_name = os.path.splitext(filename)[0]
embed.add_field(name=f"{i}. {display_name}", value="\u200b", inline=False)
return embed, view
async def _handle_search_results(
self,
ctx: discord.ApplicationContext,
candidates: List[str],
play_callback: Callable[[discord.Interaction, str], Awaitable[None]],
) -> None:
"""Handle the display of search results and button interactions."""
if not candidates:
await ctx.respond("Nie znaleziono pliku do odtworzenia", ephemeral=True)
return
embed, view = await self._create_search_embed(candidates)
# Add buttons for each candidate
for i, candidate in enumerate(candidates, start=1):
button = discord.ui.Button(label=f"Play {i}")
async def button_callback(
interaction: discord.Interaction, candidate_path=candidate
):
await interaction.response.defer(ephemeral=True)
await ctx.interaction.delete_original_response()
try:
await play_callback(interaction, candidate_path)
except Exception as e:
logger.error(f"Error in play callback: {str(e)}", exc_info=True)
await interaction.followup.send(
f"Wystąpił błąd podczas odtwarzania: {str(e)}", ephemeral=True
)
button.callback = button_callback
view.add_item(button)
await ctx.respond(embed=embed, view=view, ephemeral=True)
async def _search_autocomplete(
self, ctx: discord.AutocompleteContext
) -> List[OptionChoice]:
"""Autocomplete handler for search queries."""
if ctx.value.lower().startswith(("http://", "https://")):
return []
query = ctx.value.lower()
try:
results = await UniversalSearcher.search_copyparty_autocomplete_audio(
query, max_results=25
)
choices = []
self.path_mapping = {} # Reset the mapping for each new query
for url in results:
filename = url.split("/")[-1]
filename = filename.split("?")[0] # Remove query params if any
filename = urllib.parse.unquote(filename) # Decode URL encoding
display = os.path.splitext(filename)[0] # Remove extension
display = display.strip()
if len(display) > 100:
display = display[:99] + "…"
self.path_mapping[display] = url
choices.append(OptionChoice(display, display))
if len(choices) >= 25:
break
return choices
except Exception as e:
logger.error(f"Error in autocomplete: {str(e)}", exc_info=True)
return []
async def _handle_compressed_file_play(
self, ctx: discord.ApplicationContext, url: str
) -> None:
"""Download from copyparty, compress, then play locally."""
import aiohttp
local_path = None
compressed_path = None
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status != 200:
await ctx.respond("Nie udało się pobrać pliku.", ephemeral=True)
return
filename = url.split("/")[-1].split("?")[0]
filename = urllib.parse.unquote(filename)
local_path = os.path.join(self.temp_dir, filename)
os.makedirs(self.temp_dir, exist_ok=True)
loop = asyncio.get_event_loop()
with open(local_path, "wb") as f:
async for chunk in response.content.iter_chunked(8192):
await loop.run_in_executor(None, f.write, chunk)
compressed_path = await media_processing.AudioCompressor.compress(
ctx, local_path
)
if not compressed_path:
return
await audio_playback.AudioPlaybackManager.play(
ctx, compressed_path, delete_after_play=True
)
except Exception as e:
logger.error(f"Error in compressed playback: {str(e)}", exc_info=True)
await ctx.respond(f"Błąd: {str(e)}", ephemeral=True)
finally:
if local_path and os.path.exists(local_path):
try:
os.remove(local_path)
except Exception:
pass
async def _handle_external_url_play(
self, ctx: discord.ApplicationContext, url: str
) -> None:
"""Download from external URL, upload to copyparty, then play."""
local_path = None
try:
ytdl_opts = {
"outtmpl": os.path.join(self.temp_dir, "%(title)s.%(ext)s"),
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "192",
}
],
"force_ipv4": True,
}
loop = asyncio.get_event_loop()
with YoutubeDL(ytdl_opts) as ydl:
info_dict = await loop.run_in_executor(
None, lambda: ydl.extract_info(url, download=True)
)
title = info_dict.get("title", "nieznany")
base_filename = os.path.splitext(ydl.prepare_filename(info_dict))[0]
local_path = f"{base_filename}.mp3"
if not os.path.exists(local_path):
await ctx.respond("Nie udało się pobrać pliku.", ephemeral=True)
return
upload_task = asyncio.create_task(self._upload_to_copyparty_async(local_path))
await audio_playback.AudioPlaybackManager.play(
ctx, local_path, delete_after_play=True
)
try:
await asyncio.wait_for(upload_task, timeout=30.0)
except asyncio.TimeoutError:
logger.warning("Upload timed out")
except Exception as e:
logger.error(f"Error downloading external URL: {str(e)}", exc_info=True)
if local_path and os.path.exists(local_path):
try:
os.remove(local_path)
except Exception:
pass
await ctx.respond(f"Błąd pobierania: {str(e)}", ephemeral=True)
async def _upload_to_copyparty_async(self, file_path: str) -> None:
"""Upload file to copyparty asynchronously (fire and forget)."""
import aiohttp
try:
logger.info(f"Starting async upload: {file_path}")
baseurl = get_uploadurl()
password = os.getenv("COPYPARTY_PASSWORD", "")
logger.info(f"Upload - baseurl: {baseurl}, password set: {bool(password)}")
if baseurl == "http://localhost:3939":
logger.warning("COPYPARTY_URL_UPLOAD not set! Using default")
with open(file_path, "rb") as f:
content = f.read()
files = aiohttp.FormData()
files.add_field(
"f",
content,
filename=os.path.basename(file_path),
content_type="application/octet-stream",
)
headers = {"Cookie": f"cppwd={password}"}
params = {"j": "1", "ck": "b2"}
logger.info(f"Posting to {baseurl}")
async with aiohttp.ClientSession() as session:
async with session.post(baseurl, data=files, headers=headers, params=params) as response:
text = await response.text()
logger.info(f"Upload response: {response.status} - {text[:200] if text else 'empty'}")
if response.status in [200, 201]:
result = await response.json()
logger.info(f"Uploaded to copyparty: {result.get('fileurl')}")
except Exception as e:
logger.error(f"Async upload failed: {e}", exc_info=True)
async def _handle_local_file_play(
self, ctx: discord.ApplicationContext, file: str, compressed: bool
) -> None:
"""Handle file playback from copyparty URL."""
url = self.path_mapping.get(file, file) # Look up URL from display name
if compressed:
await self._handle_compressed_file_play(ctx, url)
else:
await audio_playback.AudioPlaybackManager.play(ctx, url)
@discord.slash_command(name="grajcuj", description="grajcujmy wszyscy!")
async def play(
self,
ctx: discord.ApplicationContext,
melodia: str = discord.Option(
str,
"odtwórz plik z serwera bądź strumienia",
autocomplete=_search_autocomplete,
required=False,
),
file: discord.Attachment = discord.Option(
discord.Attachment, "plik do zagrania", required=False
),
compressed: bool = discord.Option(
bool, "Czy skompresować dźwięk?", default=False
),
):
"""Odtwarza wybrany plik dźwiękowy lub stream internetowy."""
await ctx.defer()
if melodia and file:
await ctx.respond(
"Możesz podać plik z serwera LUB upload, nie oba naraz.", ephemeral=True
)
return
if not melodia and not file:
await ctx.respond("Musisz podać plik do odtworzenia.", ephemeral=True)
return
if file:
file_path: PathLike[str] | str = os.path.join(self.temp_dir, file.filename)
await file.save(file_path)
await audio_playback.AudioPlaybackManager.play(ctx, file_path)
else:
try:
if EXTERNAL_URL_PATTERN.match(melodia.lower()):
await self._handle_external_url_play(ctx, melodia)
else:
await self._handle_local_file_play(ctx, melodia, compressed)
except Exception as e:
logger.error(f"Error playing: {str(e)}", exc_info=True)
await ctx.respond(
f"Wystąpił błąd podczas odtworzenia: {str(e)}", ephemeral=True
)
def setup(bot):
bot.add_cog(PlayCommands(bot))
|