dragonxd1 commited on
Commit
12e0ae2
·
verified ·
1 Parent(s): 29b4fb7

Update DragMusic/platforms/Youtube.py

Browse files
Files changed (1) hide show
  1. DragMusic/platforms/Youtube.py +57 -77
DragMusic/platforms/Youtube.py CHANGED
@@ -1,16 +1,27 @@
 
 
1
  import asyncio
2
  import os
3
  import re
4
  import json
5
- import httpx # Make sure to import httpx
6
  from typing import Union
 
7
  import yt_dlp
8
  from pyrogram.enums import MessageEntityType
9
  from pyrogram.types import Message
10
  from youtubesearchpython.__future__ import VideosSearch
11
- from DragMusic.utils.database import is_on_off
12
- from DragMusic.utils.formatters import time_to_seconds
13
- import tempfile
 
 
 
 
 
 
 
 
 
14
 
15
  async def shell_cmd(cmd):
16
  proc = await asyncio.create_subprocess_shell(
@@ -26,6 +37,22 @@ async def shell_cmd(cmd):
26
  return errorz.decode("utf-8")
27
  return out.decode("utf-8")
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  class YouTubeAPI:
30
  def __init__(self):
31
  self.base = "https://www.youtube.com/watch?v="
@@ -118,20 +145,9 @@ class YouTubeAPI:
118
  link = self.base + link
119
  if "&" in link:
120
  link = link.split("&")[0]
121
- proc = await asyncio.create_subprocess_exec(
122
- "yt-dlp",
123
- "-g",
124
- "-f",
125
- "best[height<=?720][width<=?1280]",
126
- f"{link}",
127
- stdout=asyncio.subprocess.PIPE,
128
- stderr=asyncio.subprocess.PIPE,
129
- )
130
- stdout, stderr = await proc.communicate()
131
- if stdout:
132
- return 1, stdout.decode().split("\n")[0]
133
- else:
134
- return 0, stderr.decode()
135
 
136
  async def playlist(self, link, limit, user_id, videoid: Union[bool, str] = None):
137
  if videoid:
@@ -225,22 +241,6 @@ class YouTubeAPI:
225
  thumbnail = result[query_type]["thumbnails"][0]["url"].split("?")[0]
226
  return title, duration_min, thumbnail, vidid
227
 
228
- async def get_video_info_from_bitflow(self, url: str, video: bool):
229
- api_url = "https://bitflow.in/api/youtube"
230
- params = {
231
- "query": url,
232
- "format": "video" if video else "audio",
233
- "download": True,
234
- "api_key": "1spiderkey2"
235
- }
236
-
237
- async with httpx.AsyncClient() as client:
238
- response = await client.get(api_url, params=params, timeout=150)
239
- if response.status_code == 200:
240
- return response.json()
241
- else:
242
- return {"status": "error", "message": "Failed to fetch data from Bitflow API."}
243
-
244
  async def download(
245
  self,
246
  link: str,
@@ -254,64 +254,45 @@ class YouTubeAPI:
254
  ) -> str:
255
  if videoid:
256
  link = self.base + link
257
- if "&" in link:
258
- link = link.split("&")[0]
259
  loop = asyncio.get_running_loop()
260
- bitflow_info = await self.get_video_info_from_bitflow(link, video)
261
- def audio_dl(bitflow_info):
262
- temp_dir = tempfile.gettempdir()
263
- xyz = os.path.join(temp_dir, f"{bitflow_info['videoid']}.{bitflow_info['ext']}")
264
- url = bitflow_info['url']
265
- # If the url is not a YouTube link, download directly
266
- if not (url.startswith('http') and ('youtube.com' in url or 'youtu.be' in url)):
267
- import httpx
268
- with httpx.Client() as client:
269
- r = client.get(url)
270
- with open(xyz, "wb") as f:
271
- f.write(r.content)
272
- return xyz
273
  ydl_optssx = {
274
  "format": "bestaudio/best",
275
- "outtmpl": xyz,
276
  "geo_bypass": True,
277
  "nocheckcertificate": True,
278
  "quiet": True,
279
  "no_warnings": True,
280
  }
281
  x = yt_dlp.YoutubeDL(ydl_optssx)
 
 
282
  if os.path.exists(xyz):
283
  return xyz
284
- x.download([url])
285
  return xyz
286
- def video_dl(bitflow_info):
287
- temp_dir = tempfile.gettempdir()
288
- xyz = os.path.join(temp_dir, f"{bitflow_info['videoid']}.{bitflow_info['ext']}")
289
- url = bitflow_info['url']
290
- # If the url is not a YouTube link, download directly
291
- if not (url.startswith('http') and ('youtube.com' in url or 'youtu.be' in url)):
292
- import httpx
293
- with httpx.Client() as client:
294
- r = client.get(url)
295
- with open(xyz, "wb") as f:
296
- f.write(r.content)
297
- return xyz
298
  ydl_optssx = {
299
  "format": "(bestvideo[height<=?720][width<=?1280][ext=mp4])+(bestaudio[ext=m4a])",
300
- "outtmpl": xyz,
301
  "geo_bypass": True,
302
  "nocheckcertificate": True,
303
  "quiet": True,
304
  "no_warnings": True,
305
  }
306
  x = yt_dlp.YoutubeDL(ydl_optssx)
 
 
307
  if os.path.exists(xyz):
308
  return xyz
309
- x.download([url])
310
  return xyz
 
311
  def song_video_dl():
312
- temp_dir = tempfile.gettempdir()
313
- fpath = os.path.join(temp_dir, f"{title}")
314
  formats = f"{format_id}+140"
 
315
  ydl_optssx = {
316
  "format": formats,
317
  "outtmpl": fpath,
@@ -324,9 +305,9 @@ class YouTubeAPI:
324
  }
325
  x = yt_dlp.YoutubeDL(ydl_optssx)
326
  x.download([link])
 
327
  def song_audio_dl():
328
- temp_dir = tempfile.gettempdir()
329
- fpath = os.path.join(temp_dir, f"{title}.%(ext)s")
330
  ydl_optssx = {
331
  "format": format_id,
332
  "outtmpl": fpath,
@@ -345,20 +326,19 @@ class YouTubeAPI:
345
  }
346
  x = yt_dlp.YoutubeDL(ydl_optssx)
347
  x.download([link])
 
348
  if songvideo:
349
  await loop.run_in_executor(None, song_video_dl)
350
- temp_dir = tempfile.gettempdir()
351
- fpath = os.path.join(temp_dir, f"{title}.mp4")
352
  return fpath
353
  elif songaudio:
354
  await loop.run_in_executor(None, song_audio_dl)
355
- temp_dir = tempfile.gettempdir()
356
- fpath = os.path.join(temp_dir, f"{title}.mp3")
357
  return fpath
358
  elif video:
359
- direct = True
360
- downloaded_file = await loop.run_in_executor(None, video_dl, bitflow_info)
361
  else:
362
- direct = True
363
- downloaded_file = await loop.run_in_executor(None, audio_dl, bitflow_info)
364
  return downloaded_file, direct
 
1
+ import httpx
2
+ from youtubesearchpython.__future__ import VideosSearch
3
  import asyncio
4
  import os
5
  import re
6
  import json
 
7
  from typing import Union
8
+ import requests
9
  import yt_dlp
10
  from pyrogram.enums import MessageEntityType
11
  from pyrogram.types import Message
12
  from youtubesearchpython.__future__ import VideosSearch
13
+ from AnonXMusic.utils.database import is_on_off
14
+ from AnonXMusic.utils.formatters import time_to_seconds
15
+ import os
16
+ import glob
17
+ import random
18
+ import logging
19
+ import aiohttp
20
+
21
+ def time_to_seconds(time):
22
+ stringt = str(time)
23
+ return sum(int(x) * 60**i for i, x in enumerate(reversed(stringt.split(":"))))
24
+
25
 
26
  async def shell_cmd(cmd):
27
  proc = await asyncio.create_subprocess_shell(
 
37
  return errorz.decode("utf-8")
38
  return out.decode("utf-8")
39
 
40
+
41
+
42
+ async def get_stream_url(query, video=False):
43
+ api_url = "http://46.250.243.87:1470/youtube"
44
+ api_key = "1a873582a7c83342f961cc0a177b2b26"
45
+
46
+ async with httpx.AsyncClient(timeout=60) as client:
47
+ params = {"query": query, "video": video, "api_key": api_key}
48
+ response = await client.get(api_url, params=params)
49
+ if response.status_code != 200:
50
+ return ""
51
+ info = response.json()
52
+ return info.get("stream_url")
53
+
54
+
55
+
56
  class YouTubeAPI:
57
  def __init__(self):
58
  self.base = "https://www.youtube.com/watch?v="
 
145
  link = self.base + link
146
  if "&" in link:
147
  link = link.split("&")[0]
148
+
149
+ return await get_stream_url(link, True)
150
+
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  async def playlist(self, link, limit, user_id, videoid: Union[bool, str] = None):
153
  if videoid:
 
241
  thumbnail = result[query_type]["thumbnails"][0]["url"].split("?")[0]
242
  return title, duration_min, thumbnail, vidid
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  async def download(
245
  self,
246
  link: str,
 
254
  ) -> str:
255
  if videoid:
256
  link = self.base + link
 
 
257
  loop = asyncio.get_running_loop()
258
+
259
+ def audio_dl():
 
 
 
 
 
 
 
 
 
 
 
260
  ydl_optssx = {
261
  "format": "bestaudio/best",
262
+ "outtmpl": "downloads/%(id)s.%(ext)s",
263
  "geo_bypass": True,
264
  "nocheckcertificate": True,
265
  "quiet": True,
266
  "no_warnings": True,
267
  }
268
  x = yt_dlp.YoutubeDL(ydl_optssx)
269
+ info = x.extract_info(link, False)
270
+ xyz = os.path.join("downloads", f"{info['id']}.{info['ext']}")
271
  if os.path.exists(xyz):
272
  return xyz
273
+ x.download([link])
274
  return xyz
275
+
276
+ def video_dl():
 
 
 
 
 
 
 
 
 
 
277
  ydl_optssx = {
278
  "format": "(bestvideo[height<=?720][width<=?1280][ext=mp4])+(bestaudio[ext=m4a])",
279
+ "outtmpl": "downloads/%(id)s.%(ext)s",
280
  "geo_bypass": True,
281
  "nocheckcertificate": True,
282
  "quiet": True,
283
  "no_warnings": True,
284
  }
285
  x = yt_dlp.YoutubeDL(ydl_optssx)
286
+ info = x.extract_info(link, False)
287
+ xyz = os.path.join("downloads", f"{info['id']}.{info['ext']}")
288
  if os.path.exists(xyz):
289
  return xyz
290
+ x.download([link])
291
  return xyz
292
+
293
  def song_video_dl():
 
 
294
  formats = f"{format_id}+140"
295
+ fpath = f"downloads/{title}"
296
  ydl_optssx = {
297
  "format": formats,
298
  "outtmpl": fpath,
 
305
  }
306
  x = yt_dlp.YoutubeDL(ydl_optssx)
307
  x.download([link])
308
+
309
  def song_audio_dl():
310
+ fpath = f"downloads/{title}.%(ext)s"
 
311
  ydl_optssx = {
312
  "format": format_id,
313
  "outtmpl": fpath,
 
326
  }
327
  x = yt_dlp.YoutubeDL(ydl_optssx)
328
  x.download([link])
329
+
330
  if songvideo:
331
  await loop.run_in_executor(None, song_video_dl)
332
+ fpath = f"downloads/{title}.mp4"
 
333
  return fpath
334
  elif songaudio:
335
  await loop.run_in_executor(None, song_audio_dl)
336
+ fpath = f"downloads/{title}.mp3"
 
337
  return fpath
338
  elif video:
339
+ downloaded_file = await get_stream_url(link, True)
340
+ direct = None
341
  else:
342
+ direct = None
343
+ downloaded_file = await get_stream_url(link, False)
344
  return downloaded_file, direct