Skip to content

Commit

Permalink
NEW VC PLAYER (#3)
Browse files Browse the repository at this point in the history
* Update requirements.txt

* v1.4.4

* v1.4.4

* Revert "v1.4.4"

This reverts commit 53e3e3e.

---------

Co-authored-by: Jisan <[email protected]>
  • Loading branch information
ZAR0X and Jisan09 authored Apr 9, 2023
1 parent 9182aca commit 9838f8b
Show file tree
Hide file tree
Showing 5 changed files with 557 additions and 147 deletions.
34 changes: 21 additions & 13 deletions helper/tg_downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from telethon.tl import types
from telethon.utils import get_extension
from userbot import catub
from userbot.Config import Config
from userbot.core.managers import edit_or_reply
from userbot.helpers import progress
Expand All @@ -20,14 +21,14 @@ async def _get_file_name(path: pathlib.Path, full: bool = True) -> str:
return str(path.absolute()) if full else path.stem + path.suffix


async def tg_dl(event):
async def tg_dl(event, reply, tgbot=False):
"To download the replied telegram file"
mone = await edit_or_reply(event, "`Downloading....`")
name = NAME
path = None
if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
reply = await event.get_reply_message()
# reply = await event.get_reply_message()
if reply:
start = datetime.now()
for attr in getattr(reply.document, "attributes", []):
Expand All @@ -54,6 +55,10 @@ async def tg_dl(event):
file_name = downloads / name
file_name.parent.mkdir(parents=True, exist_ok=True)
c_time = time.time()
if tgbot: progress_callback = None
else : progress_callback = lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, mone, c_time, "trying to download")
)
if (
not reply.document
and reply.photo
Expand All @@ -64,33 +69,36 @@ async def tg_dl(event):
):
await reply.download_media(
file=file_name.absolute(),
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, mone, c_time, "trying to download")
),
progress_callback=progress_callback
)
elif not reply.document:
file_name = await reply.download_media(
file=downloads,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, mone, c_time, "trying to download")
),
progress_callback=progress_callback
)
else:
dl = io.FileIO(file_name.absolute(), "a")
await event.client.fast_download_file(
await catub.fast_download_file(
location=reply.document,
out=dl,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, mone, c_time, "trying to download")
),
progress_callback=progress_callback,
)
dl.close()
end = datetime.now()
ms = (end - start).seconds
await mone.edit(
f"**• Downloaded in {ms} seconds.**\n**• Downloaded to :- ** `{os.path.relpath(file_name,os.getcwd())}`\n"
)
return os.path.relpath(file_name, os.getcwd())
try:
thumb = await reply.download_media(thumb=-1)
except TypeError as error:
try:
nail_ = await event.client.get_profile_photos(catub.me.id)
thumb = await event.client.download_media(nail_[0], file=downloads)
except:
thumb = "catvc/resources/404.png"

return [os.path.relpath(file_name, os.getcwd()), thumb]
else:
await mone.edit("`Reply to a message to download and stream.`")
return False
118 changes: 98 additions & 20 deletions helper/vcp_helper.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import asyncio
from pathlib import Path

Expand All @@ -16,9 +17,13 @@
from telethon.errors import ChatAdminRequiredError
from yt_dlp import YoutubeDL

from userbot import Config, catub
from userbot.helpers.functions import yt_search, get_ytthumb
from userbot.core.managers import edit_or_reply
from .stream_helper import Stream, check_url, video_dl, yt_regex



class CatVC:
def __init__(self, client) -> None:
self.app = PyTgCalls(client, overload_quiet_mode=True)
Expand All @@ -29,6 +34,11 @@ def __init__(self, client) -> None:
self.PAUSED = False
self.MUTED = False
self.PLAYLIST = []
self.EVENTS = []
self.SILENT = True
self.PUBLICMODE = False
self.BOTMODE = False
self.CLEANMODE = False

async def start(self):
await self.app.start()
Expand All @@ -42,6 +52,7 @@ def clear_vars(self):
self.PLAYLIST = []

async def join_vc(self, chat, join_as=None):
self.SILENT = True
if self.CHAT_ID:
return f"Already in a group call on {self.CHAT_NAME}"
if join_as:
Expand Down Expand Up @@ -86,20 +97,48 @@ async def leave_vc(self):
await self.app.leave_group_call(self.CHAT_ID)
except (NotInGroupCallError, NoActiveGroupCall):
pass
for event in self.EVENTS:
try:
await event.delete()
except:
pass
self.CHAT_NAME = None
self.CHAT_ID = None
self.PLAYING = False
self.PLAYLIST = []
self.EVENTS = []

async def play_song(self, input, stream=Stream.audio, force=False):
if yt_regex.match(input):
with YoutubeDL({}) as ytdl:
ytdl_data = ytdl.extract_info(input, download=False)
title = ytdl_data.get("title", None)
if title:
playable = await video_dl(input, title)
async def duration(self, name):
int_ = int(name)
ute = int_//60
ond_ = int_%60
if int(ond_) in list(range(0, 10)):
ond = f"0{ond_}"
else:
ond = ond_
duration = f"{ute}:{ond}"
return duration

async def play_song(self, event, input, stream=Stream.audio, force=False, reply=False, **kwargs):
yt_url = False
img = False
if not input: return
if reply:
path = Path(input[0])
if path.exists():
if not path.name.endswith(
(".mkv", ".mp4", ".webm", ".m4v", ".mp3", ".flac", ".wav", ".m4a")
):
return "`File is invalid for Streaming`"
playable = str(path.absolute())
title = path.name
duration = await self.duration(reply.file.duration)
img = input[1]
url = f"https://t.me/c/{abs(reply.chat_id) if not str(abs(reply.chat_id)).startswith('100') else str(abs(reply.chat_id))[3:]}/{reply.id}"
else:
return "Error Fetching URL"
return "`File Path is invalid`"
elif yt_regex.match(input):
yt_url = input
elif check_url(input):
try:
res = requests.get(input, allow_redirects=True, stream=True)
Expand All @@ -112,6 +151,9 @@ async def play_song(self, input, stream=Stream.audio, force=False):
else:
title = input
playable = input
url = input
img = "catvc/resources/404.png"
duration = "UNKNOWN"
except Exception as e:
return f"**INVALID URL**\n\n{e}"
else:
Expand All @@ -123,39 +165,69 @@ async def play_song(self, input, stream=Stream.audio, force=False):
return "`File is invalid for Streaming`"
playable = str(path.absolute())
title = path.name
if kwargs:
duration = kwargs['duration']
url = kwargs['url']
img = kwargs['img']
else:
duration = "UNKNOWN"
url = ""
else:
return "`File Path is invalid`"
yt_url = await yt_search(input)


if yt_url:
with YoutubeDL({}) as ytdl:
ytdl_data = ytdl.extract_info(yt_url, download=False)

title = ytdl_data.get("title", None)
if title:
await event.edit("`Downloading...`")
playable = await video_dl(yt_url, title)
else:
return "Error Fetching URL"

img = await get_ytthumb(ytdl_data['id'])
duration = await self.duration(ytdl_data['duration'])
url = yt_url



msg = f"**🎧 Playing:** [{title}]({url})\n"
msg += f"**⏳ Duration:** `{duration}`\n"
msg += f"**💭 Chat:** `{self.CHAT_NAME}`"
print(playable)
if self.PLAYING and not force:
self.PLAYLIST.append({"title": title, "path": playable, "stream": stream})
return f"Added to playlist.\n Position: {len(self.PLAYLIST)+1}"
self.PLAYLIST.append({"title": title, "path": playable, "stream": stream, "img": img, "duration": duration, "url": url})
return [img, f"**🎧 Added to playlist:** {msg[15:]}\n\n👾 Position: {len(self.PLAYLIST)+1}"] if img else f"**🎧 Added to playlist:** {msg[15:]}\n\n👾 Position: {len(self.PLAYLIST)+1}"
if not self.PLAYING:
self.PLAYLIST.append({"title": title, "path": playable, "stream": stream})
self.PLAYLIST.append({"title": title, "path": playable, "stream": stream, "img": img, "duration": duration, "url": url})
await self.skip()
return f"Playing {title}"
return [img, msg] if img else msg
if force and self.PLAYING:
self.PLAYLIST.insert(
0, {"title": title, "path": playable, "stream": stream}
0, {"title": title, "path": playable, "stream": stream, "img": img, "duration": duration, "url": url}
)
await self.skip()
return f"Playing {title}"
return [img, msg] if img else msg

async def handle_next(self, update):
if isinstance(update, StreamAudioEnded):
await self.skip()
return await self.skip()

async def skip(self, clear=False):
self.SILENT = False
if clear:
self.PLAYLIST = []

#log chat name
if not self.PLAYLIST:
if self.PLAYING:
await self.app.change_stream(
self.CHAT_ID,
AudioPiped("catvc/resources/Silence01s.mp3"),
)
self.PLAYING = False
return "Skipped Stream\nEmpty Playlist"
return "**Skipped Stream\nEmpty Playlist**"

next = self.PLAYLIST.pop(0)
if next["stream"] == Stream.audio:
Expand All @@ -167,7 +239,11 @@ async def skip(self, clear=False):
except Exception:
await self.skip()
self.PLAYING = next
return f"Skipped Stream\nPlaying : `{next['title']}`"
msg = f"**🌬 Skipped Stream**\n\n"
msg += f"**🎧 Playing:** [{next['title']}]({next['url']})\n"
msg += f"**⏳ Duration:** `{next['duration']}`\n"
msg += f"**💭 Chat:** `{self.CHAT_NAME}`"
return [next['img'], msg] if next['img'] else msg

async def pause(self):
if not self.PLAYING:
Expand All @@ -190,7 +266,7 @@ async def resume(self):
# return "Nothing is playing to Mute"
# if not self.MUTED:
# await self.app.mute_stream(self.CHAT_ID)
# self.PAUSED = True
# self.MUTED = True
# return f"Muted Stream on {self.CHAT_NAME}"

# async def unmute(self):
Expand All @@ -200,3 +276,5 @@ async def resume(self):
# await self.app.unmute_stream(self.CHAT_ID)
# self.MUTED = False
# return f"Unmuted Stream on {self.CHAT_NAME}"


2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
py-tgcalls==0.9.1
py-tgcalls==0.9.1
Binary file added resources/404.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 9838f8b

Please sign in to comment.