Spaces:
Paused
Paused
File size: 11,907 Bytes
12e0ae2 a65da15 eda8225 3a9d14d 12e0ae2 a65da15 eda8225 cd171d0 12e0ae2 8d58bbb a65da15 8d58bbb 12e0ae2 a65da15 8d58bbb a65da15 8d58bbb a65da15 8d58bbb a65da15 eda8225 a65da15 8d58bbb a65da15 eda8225 8d58bbb a65da15 eda8225 8d58bbb a65da15 eda8225 8d58bbb a65da15 12e0ae2 8d58bbb a65da15 eda8225 a65da15 8d58bbb a65da15 eda8225 a65da15 eda8225 a65da15 eda8225 8d58bbb a65da15 eda8225 a65da15 8d58bbb eda8225 a65da15 eda8225 8d58bbb a65da15 12e0ae2 eda8225 12e0ae2 eda8225 a65da15 eda8225 a65da15 eda8225 12e0ae2 eda8225 12e0ae2 eda8225 12e0ae2 eda8225 12e0ae2 eda8225 12e0ae2 eda8225 12e0ae2 eda8225 12e0ae2 a65da15 12e0ae2 a65da15 12e0ae2 a65da15 12e0ae2 a65da15 12e0ae2 a65da15 12e0ae2 a65da15 12e0ae2 a65da15 12e0ae2 a65da15 12e0ae2 a65da15 |
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 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
import httpx
from youtubesearchpython.__future__ import VideosSearch
import asyncio
import os
import re
import json
from typing import Union
import requests
import yt_dlp
from pyrogram.enums import MessageEntityType
from pyrogram.types import Message
from youtubesearchpython.__future__ import VideosSearch
from DragMusic.utils.database import is_on_off
from DragMusic.utils.formatters import time_to_seconds
import os
import glob
import random
import logging
import aiohttp
def time_to_seconds(time):
stringt = str(time)
return sum(int(x) * 60**i for i, x in enumerate(reversed(stringt.split(":"))))
async def shell_cmd(cmd):
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
out, errorz = await proc.communicate()
if errorz:
if "unavailable videos are hidden" in (errorz.decode("utf-8")).lower():
return out.decode("utf-8")
else:
return errorz.decode("utf-8")
return out.decode("utf-8")
async def get_stream_url(query, video=False):
api_url = "http://46.250.243.87:1470/youtube"
api_key = "1a873582a7c83342f961cc0a177b2b26"
async with httpx.AsyncClient(timeout=60) as client:
params = {"query": query, "video": video, "api_key": api_key}
response = await client.get(api_url, params=params)
if response.status_code != 200:
return ""
info = response.json()
return info.get("stream_url")
class YouTubeAPI:
def __init__(self):
self.base = "https://www.youtube.com/watch?v="
self.regex = r"(?:youtube\.com|youtu\.be)"
self.status = "https://www.youtube.com/oembed?url="
self.listbase = "https://youtube.com/playlist?list="
self.reg = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
async def exists(self, link: str, videoid: Union[bool, str] = None):
if videoid:
link = self.base + link
if re.search(self.regex, link):
return True
else:
return False
async def url(self, message_1: Message) -> Union[str, None]:
messages = [message_1]
if message_1.reply_to_message:
messages.append(message_1.reply_to_message)
text = ""
offset = None
length = None
for message in messages:
if offset:
break
if message.entities:
for entity in message.entities:
if entity.type == MessageEntityType.URL:
text = message.text or message.caption
offset, length = entity.offset, entity.length
break
elif message.caption_entities:
for entity in message.caption_entities:
if entity.type == MessageEntityType.TEXT_LINK:
return entity.url
if offset in (None,):
return None
return text[offset : offset + length]
async def details(self, link: str, videoid: Union[bool, str] = None):
if videoid:
link = self.base + link
if "&" in link:
link = link.split("&")[0]
results = VideosSearch(link, limit=1)
for result in (await results.next())["result"]:
title = result["title"]
duration_min = result["duration"]
thumbnail = result["thumbnails"][0]["url"].split("?")[0]
vidid = result["id"]
if str(duration_min) == "None":
duration_sec = 0
else:
duration_sec = int(time_to_seconds(duration_min))
return title, duration_min, duration_sec, thumbnail, vidid
async def title(self, link: str, videoid: Union[bool, str] = None):
if videoid:
link = self.base + link
if "&" in link:
link = link.split("&")[0]
results = VideosSearch(link, limit=1)
for result in (await results.next())["result"]:
title = result["title"]
return title
async def duration(self, link: str, videoid: Union[bool, str] = None):
if videoid:
link = self.base + link
if "&" in link:
link = link.split("&")[0]
results = VideosSearch(link, limit=1)
for result in (await results.next())["result"]:
duration = result["duration"]
return duration
async def thumbnail(self, link: str, videoid: Union[bool, str] = None):
if videoid:
link = self.base + link
if "&" in link:
link = link.split("&")[0]
results = VideosSearch(link, limit=1)
for result in (await results.next())["result"]:
thumbnail = result["thumbnails"][0]["url"].split("?")[0]
return thumbnail
async def video(self, link: str, videoid: Union[bool, str] = None):
if videoid:
link = self.base + link
if "&" in link:
link = link.split("&")[0]
return await get_stream_url(link, True)
async def playlist(self, link, limit, user_id, videoid: Union[bool, str] = None):
if videoid:
link = self.listbase + link
if "&" in link:
link = link.split("&")[0]
playlist = await shell_cmd(
f"yt-dlp -i --get-id --flat-playlist --playlist-end {limit} --skip-download {link}"
)
try:
result = playlist.split("\n")
for key in result:
if key == "":
result.remove(key)
except:
result = []
return result
async def track(self, link: str, videoid: Union[bool, str] = None):
if videoid:
link = self.base + link
if "&" in link:
link = link.split("&")[0]
results = VideosSearch(link, limit=1)
for result in (await results.next())["result"]:
title = result["title"]
duration_min = result["duration"]
vidid = result["id"]
yturl = result["link"]
thumbnail = result["thumbnails"][0]["url"].split("?")[0]
track_details = {
"title": title,
"link": yturl,
"vidid": vidid,
"duration_min": duration_min,
"thumb": thumbnail,
}
return track_details, vidid
async def formats(self, link: str, videoid: Union[bool, str] = None):
if videoid:
link = self.base + link
if "&" in link:
link = link.split("&")[0]
ytdl_opts = {"quiet": True}
ydl = yt_dlp.YoutubeDL(ytdl_opts)
with ydl:
formats_available = []
r = ydl.extract_info(link, download=False)
for format in r["formats"]:
try:
str(format["format"])
except:
continue
if not "dash" in str(format["format"]).lower():
try:
format["format"]
format["filesize"]
format["format_id"]
format["ext"]
format["format_note"]
except:
continue
formats_available.append(
{
"format": format["format"],
"filesize": format["filesize"],
"format_id": format["format_id"],
"ext": format["ext"],
"format_note": format["format_note"],
"yturl": link,
}
)
return formats_available, link
async def slider(
self,
link: str,
query_type: int,
videoid: Union[bool, str] = None,
):
if videoid:
link = self.base + link
if "&" in link:
link = link.split("&")[0]
a = VideosSearch(link, limit=10)
result = (await a.next()).get("result")
title = result[query_type]["title"]
duration_min = result[query_type]["duration"]
vidid = result[query_type]["id"]
thumbnail = result[query_type]["thumbnails"][0]["url"].split("?")[0]
return title, duration_min, thumbnail, vidid
async def download(
self,
link: str,
mystic,
video: Union[bool, str] = None,
videoid: Union[bool, str] = None,
songaudio: Union[bool, str] = None,
songvideo: Union[bool, str] = None,
format_id: Union[bool, str] = None,
title: Union[bool, str] = None,
) -> str:
if videoid:
link = self.base + link
loop = asyncio.get_running_loop()
def audio_dl():
ydl_optssx = {
"format": "bestaudio/best",
"outtmpl": "downloads/%(id)s.%(ext)s",
"geo_bypass": True,
"nocheckcertificate": True,
"quiet": True,
"no_warnings": True,
}
x = yt_dlp.YoutubeDL(ydl_optssx)
info = x.extract_info(link, False)
xyz = os.path.join("downloads", f"{info['id']}.{info['ext']}")
if os.path.exists(xyz):
return xyz
x.download([link])
return xyz
def video_dl():
ydl_optssx = {
"format": "(bestvideo[height<=?720][width<=?1280][ext=mp4])+(bestaudio[ext=m4a])",
"outtmpl": "downloads/%(id)s.%(ext)s",
"geo_bypass": True,
"nocheckcertificate": True,
"quiet": True,
"no_warnings": True,
}
x = yt_dlp.YoutubeDL(ydl_optssx)
info = x.extract_info(link, False)
xyz = os.path.join("downloads", f"{info['id']}.{info['ext']}")
if os.path.exists(xyz):
return xyz
x.download([link])
return xyz
def song_video_dl():
formats = f"{format_id}+140"
fpath = f"downloads/{title}"
ydl_optssx = {
"format": formats,
"outtmpl": fpath,
"geo_bypass": True,
"nocheckcertificate": True,
"quiet": True,
"no_warnings": True,
"prefer_ffmpeg": True,
"merge_output_format": "mp4",
}
x = yt_dlp.YoutubeDL(ydl_optssx)
x.download([link])
def song_audio_dl():
fpath = f"downloads/{title}.%(ext)s"
ydl_optssx = {
"format": format_id,
"outtmpl": fpath,
"geo_bypass": True,
"nocheckcertificate": True,
"quiet": True,
"no_warnings": True,
"prefer_ffmpeg": True,
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "192",
}
],
}
x = yt_dlp.YoutubeDL(ydl_optssx)
x.download([link])
if songvideo:
await loop.run_in_executor(None, song_video_dl)
fpath = f"downloads/{title}.mp4"
return fpath
elif songaudio:
await loop.run_in_executor(None, song_audio_dl)
fpath = f"downloads/{title}.mp3"
return fpath
elif video:
downloaded_file = await get_stream_url(link, True)
direct = None
else:
direct = None
downloaded_file = await get_stream_url(link, False)
return downloaded_file, direct |