Skip to content

Commit

Permalink
Update types and methods to latest layer as well.
Browse files Browse the repository at this point in the history
Signed-off-by: Aliwoto <[email protected]>
  • Loading branch information
ALiwoto committed Jan 9, 2024
1 parent 884f805 commit 009694f
Show file tree
Hide file tree
Showing 125 changed files with 4,863 additions and 1,215 deletions.
2 changes: 1 addition & 1 deletion pyrogram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>

__version__ = "2.0.136"
__version__ = "2.0.137"
__license__ = "GNU Lesser General Public License v3.0 (LGPL-3.0)"
__copyright__ = "Copyright (C) 2017-present Dan <https://github.com/delivrance>"

Expand Down
90 changes: 55 additions & 35 deletions pyrogram/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@
from pyrogram.errors import (
SessionPasswordNeeded,
VolumeLocNotFound, ChannelPrivate,
BadRequest
BadRequest, AuthBytesInvalid
)
from pyrogram.handlers.handler import Handler
from pyrogram.methods import Methods
from pyrogram.session import Auth, Session
from pyrogram.storage import FileStorage, MemoryStorage
from pyrogram.storage import Storage, FileStorage, MemoryStorage
from pyrogram.types import User, TermsOfService, ListenerStopped, ListenerTimeout, ListenerTypes
from pyrogram.utils import ainput, PyromodConfig
from .dispatcher import Dispatcher
Expand Down Expand Up @@ -177,6 +177,10 @@ class Client(Methods):
Set the maximum amount of concurrent transmissions (uploads & downloads).
A value that is too high may result in network related issues.
Defaults to 1.
storage_engine (:obj:`~pyrogram.storage.Storage`, *optional*):
Pass an instance of your own implementation of session storage engine.
Useful when you want to store your session in databases like Mongo, Redis, etc.
"""

APP_VERSION = f"Pyrogram {__version__}"
Expand Down Expand Up @@ -225,7 +229,8 @@ def __init__(
takeout: bool = None,
sleep_threshold: int = Session.SLEEP_THRESHOLD,
hide_password: bool = False,
max_concurrent_transmissions: int = MAX_CONCURRENT_TRANSMISSIONS
max_concurrent_transmissions: int = MAX_CONCURRENT_TRANSMISSIONS,
storage_engine: Storage = None
):
super().__init__()

Expand Down Expand Up @@ -261,6 +266,8 @@ def __init__(
self.storage = MemoryStorage(self.name, self.session_string)
elif self.in_memory:
self.storage = MemoryStorage(self.name)
elif isinstance(storage_engine, Storage):
self.storage = storage_engine
else:
self.storage = FileStorage(self.name, self.workdir)

Expand Down Expand Up @@ -625,15 +632,15 @@ async def fetch_peers(self, peers: List[Union[raw.types.User, raw.types.Chat, ra
is_min = True
continue

username = None
usernames = None
phone_number = None

if isinstance(peer, raw.types.User):
peer_id = peer.id
access_hash = peer.access_hash
username = (
peer.username.lower() if peer.username
else peer.usernames[0].username.lower() if peer.usernames
usernames = (
[peer.username.lower()] if peer.username
else [username.username.lower() for username in peer.usernames] if peer.usernames
else None
)
phone_number = peer.phone
Expand All @@ -645,9 +652,9 @@ async def fetch_peers(self, peers: List[Union[raw.types.User, raw.types.Chat, ra
elif isinstance(peer, raw.types.Channel):
peer_id = utils.get_channel_id(peer.id)
access_hash = peer.access_hash
username = (
peer.username.lower() if peer.username
else peer.usernames[0].username.lower() if peer.usernames
usernames = (
[peer.username.lower()] if peer.username
else [username.username.lower() for username in peer.usernames] if peer.usernames
else None
)
peer_type = "channel" if peer.broadcast else "supergroup"
Expand All @@ -658,7 +665,7 @@ async def fetch_peers(self, peers: List[Union[raw.types.User, raw.types.Chat, ra
else:
continue

parsed_peers.append((peer_id, access_hash, peer_type, username, phone_number))
parsed_peers.append((peer_id, access_hash, peer_type, usernames, phone_number))

await self.storage.update_peers(parsed_peers)

Expand Down Expand Up @@ -946,7 +953,7 @@ async def get_file(
offset: int = 0,
progress: Callable = None,
progress_args: tuple = ()
) -> Optional[AsyncGenerator[bytes, None]]:
) -> AsyncGenerator[bytes, None]:
async with self.get_file_semaphore:
file_type = file_id.file_type

Expand Down Expand Up @@ -994,31 +1001,40 @@ async def get_file(

dc_id = file_id.dc_id

session = Session(
self, dc_id,
await Auth(self, dc_id, await self.storage.test_mode()).create()
if dc_id != await self.storage.dc_id()
else await self.storage.auth_key(),
await self.storage.test_mode(),
is_media=True
)

try:
await session.start()

if dc_id != await self.storage.dc_id():
exported_auth = await self.invoke(
raw.functions.auth.ExportAuthorization(
dc_id=dc_id
)
session = self.media_sessions.get(dc_id)
if not session:
session = self.media_sessions[dc_id] = Session(
self, dc_id,
await Auth(self, dc_id, await self.storage.test_mode()).create()
if dc_id != await self.storage.dc_id()
else await self.storage.auth_key(),
await self.storage.test_mode(),
is_media=True
)
await session.start()

await session.invoke(
raw.functions.auth.ImportAuthorization(
id=exported_auth.id,
bytes=exported_auth.bytes
)
)
if dc_id != await self.storage.dc_id():
for _ in range(3):
exported_auth = await self.invoke(
raw.functions.auth.ExportAuthorization(
dc_id=dc_id
)
)

try:
await session.invoke(
raw.functions.auth.ImportAuthorization(
id=exported_auth.id,
bytes=exported_auth.bytes
)
)
except AuthBytesInvalid:
continue
else:
break
else:
raise AuthBytesInvalid

r = await session.invoke(
raw.functions.upload.GetFile(
Expand Down Expand Up @@ -1152,7 +1168,11 @@ async def get_file(
except Exception as e:
log.exception(e)
finally:
await session.stop()
if session:
try:
await session.stop()
self.media_sessions.pop(session.dc_id)
except: pass

def guess_mime_type(self, filename: str) -> Optional[str]:
return self.mimetypes.guess_type(filename)[0]
Expand Down
9 changes: 7 additions & 2 deletions pyrogram/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,13 @@ def __init__(self, client: "pyrogram.Client"):

async def message_parser(update, users, chats):
return (
await pyrogram.types.Message._parse(self.client, update.message, users, chats, None,
isinstance(update, UpdateNewScheduledMessage)),
await pyrogram.types.Message._parse(
self.client,
update.message,
users,
chats,
is_scheduled=isinstance(update, UpdateNewScheduledMessage)
),
MessageHandler
)

Expand Down
6 changes: 5 additions & 1 deletion pyrogram/enums/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
from .next_code_type import NextCodeType
from .parse_mode import ParseMode
from .poll_type import PollType
from .profile_color import ProfileColor
from .reply_color import ReplyColor
from .sent_code_type import SentCodeType
from .stories_privacy_rules import StoriesPrivacyRules
from .user_status import UserStatus
Expand All @@ -45,7 +47,9 @@
'NextCodeType',
'ParseMode',
'PollType',
'ProfileColor',
'ReplyColor',
'SentCodeType',
'StoriesPrivacyRules',
'UserStatus'
]
]
2 changes: 1 addition & 1 deletion pyrogram/enums/chat_event_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,4 @@ class ChatEventAction(AutoName):
"a forum topic has been deleted (see `deleted_forum_topic`)"

UNKNOWN = auto()
"Unknown chat event action"
"Unknown chat event action"
8 changes: 7 additions & 1 deletion pyrogram/enums/message_media_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,11 @@ class MessageMediaType(AutoName):
GAME = auto()
"Game media"

GIVEAWAY = auto()
"Giveaway media"

GIVEAWAY_RESULT = auto()
"Giveaway result media"

STORY = auto()
"Story media"
"Story media"
12 changes: 12 additions & 0 deletions pyrogram/enums/message_service_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
class MessageServiceType(AutoName):
"""Message service type enumeration used in :obj:`~pyrogram.types.Message`."""

CUSTOM_ACTION = auto()
"Custom action"

NEW_CHAT_MEMBERS = auto()
"New members join"

Expand Down Expand Up @@ -75,6 +78,12 @@ class MessageServiceType(AutoName):
GAME_HIGH_SCORE = auto()
"Game high score"

GIVEAWAY_LAUNCH = auto()
"Giveaway launch"

GIFT_CODE = auto()
"Gift code"

VIDEO_CHAT_STARTED = auto()
"Video chat started"

Expand All @@ -89,3 +98,6 @@ class MessageServiceType(AutoName):

WEB_APP_DATA = auto()
"Web app data"

REQUESTED_CHAT = auto()
"Requested chat"
71 changes: 71 additions & 0 deletions pyrogram/enums/profile_color.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.

from .auto_name import AutoName


class ProfileColor(AutoName):
"""Profile color enumeration used in :meth:`~pyrogram.Client.update_color` and :obj:`~pyrogram.types.ChatColor`."""

RED = 0
"Red color."

ORANGE = 1
"Orange color."

VIOLET = 2
"Violet color."

GREEN = 3
"Green color."

CYAN = 4
"Cyan color."

BLUE = 5
"Blue color."

PINK = 6
"Pink color."

GRAY = 7
"Gray color."

RED_LIGHT_RED = 8
"Red color with light red gradient."

ORANGE_LIGHT_ORANGE = 9
"Orange color with light red gradient."

VIOLET_LIGHT_VIOLET = 10
"Violet color with light violet gradient."

GREEN_LIGHT_GREEN = 11
"Green color with light green gradient."

CYAN_LIGHT_CYAN = 12
"Cyan color with light cyan gradient."

BLUE_LIGHT_BLUE = 13
"Blue color with light blue gradient."

PINK_LIGHT_PINK = 14
"Pink color with light pink gradient."

GRAY_LIGHT_GRAY = 15
"Gray color with light gray gradient."
Loading

0 comments on commit 009694f

Please sign in to comment.