|
| 1 | +# Pyrogram - Telegram MTProto API Client Library for Python |
| 2 | +# Copyright (C) 2017 Dan Tès <https://github.com/delivrance> |
| 3 | +# |
| 4 | +# This file is part of Pyrogram. |
| 5 | +# |
| 6 | +# Pyrogram is free software: you can redistribute it and/or modify |
| 7 | +# it under the terms of the GNU Lesser General Public License as published |
| 8 | +# by the Free Software Foundation, either version 3 of the License, or |
| 9 | +# (at your option) any later version. |
| 10 | +# |
| 11 | +# Pyrogram is distributed in the hope that it will be useful, |
| 12 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | +# GNU Lesser General Public License for more details. |
| 15 | +# |
| 16 | +# You should have received a copy of the GNU Lesser General Public License |
| 17 | +# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. |
| 18 | + |
| 19 | +from collections import OrderedDict |
| 20 | +from datetime import datetime |
| 21 | +from importlib import import_module |
| 22 | +from io import BytesIO |
| 23 | +from json import JSONEncoder, dumps |
| 24 | + |
| 25 | +from ..all import objects |
| 26 | + |
| 27 | + |
| 28 | +class Object: |
| 29 | + @staticmethod |
| 30 | + def read(b: BytesIO, *args): |
| 31 | + id = int.from_bytes(b.read(4), "little") |
| 32 | + name = objects.get(id) |
| 33 | + path, name = name.rsplit(".", 1) |
| 34 | + |
| 35 | + return getattr( |
| 36 | + import_module("pyrogram.api." + path), |
| 37 | + name |
| 38 | + ).read(b, *args) |
| 39 | + |
| 40 | + def write(self, *args) -> bytes: |
| 41 | + pass |
| 42 | + |
| 43 | + def __str__(self) -> str: |
| 44 | + return dumps(self, cls=Encoder, indent=4) |
| 45 | + |
| 46 | + def __eq__(self, other) -> bool: |
| 47 | + return self.__dict__ == other.__dict__ |
| 48 | + |
| 49 | + def __len__(self) -> int: |
| 50 | + return len(self.write()) |
| 51 | + |
| 52 | + def __call__(self): |
| 53 | + pass |
| 54 | + |
| 55 | + |
| 56 | +class Encoder(JSONEncoder): |
| 57 | + def default(self, o: Object): |
| 58 | + try: |
| 59 | + content = o.__dict__ |
| 60 | + except AttributeError: |
| 61 | + if isinstance(o, datetime): |
| 62 | + return o.strftime("%d-%b-%Y %H:%M:%S") |
| 63 | + else: |
| 64 | + return repr(o) |
| 65 | + |
| 66 | + return OrderedDict( |
| 67 | + [("_", objects.get(getattr(o, "ID", None), None))] |
| 68 | + + [i for i in content.items()] |
| 69 | + ) |
0 commit comments