Skip to content

Commit e226bdb

Browse files
committed
Create SQLiteStorage for better abstraction
1 parent 108fa08 commit e226bdb

1 file changed

Lines changed: 184 additions & 0 deletions

File tree

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
# Pyrogram - Telegram MTProto API Client Library for Python
2+
# Copyright (C) 2017-2019 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+
import inspect
20+
import sqlite3
21+
import time
22+
from pathlib import Path
23+
from threading import Lock
24+
from typing import List, Tuple, Any
25+
26+
from pyrogram.api import types
27+
from pyrogram.client.ext import utils
28+
from .storage import Storage
29+
30+
31+
def get_input_peer(peer_id: int, access_hash: int, peer_type: str):
32+
if peer_type in ["user", "bot"]:
33+
return types.InputPeerUser(
34+
user_id=peer_id,
35+
access_hash=access_hash
36+
)
37+
38+
if peer_type == "group":
39+
return types.InputPeerChat(
40+
chat_id=-peer_id
41+
)
42+
43+
if peer_type in ["channel", "supergroup"]:
44+
return types.InputPeerChannel(
45+
channel_id=utils.get_channel_id(peer_id),
46+
access_hash=access_hash
47+
)
48+
49+
raise ValueError("Invalid peer type: {}".format(peer_type))
50+
51+
52+
class SQLiteStorage(Storage):
53+
VERSION = 2
54+
USERNAME_TTL = 8 * 60 * 60
55+
56+
def __init__(self, name: str):
57+
super().__init__(name)
58+
59+
self.conn = None # type: sqlite3.Connection
60+
self.lock = Lock()
61+
62+
def create(self):
63+
with self.lock, self.conn:
64+
with open(str(Path(__file__).parent / "schema.sql"), "r") as schema:
65+
self.conn.executescript(schema.read())
66+
67+
self.conn.execute(
68+
"INSERT INTO version VALUES (?)",
69+
(self.VERSION,)
70+
)
71+
72+
self.conn.execute(
73+
"INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?)",
74+
(2, None, None, 0, None, None)
75+
)
76+
77+
def open(self):
78+
raise NotImplementedError
79+
80+
def save(self):
81+
self.date(int(time.time()))
82+
83+
with self.lock:
84+
self.conn.commit()
85+
86+
def close(self):
87+
with self.lock:
88+
self.conn.close()
89+
90+
def delete(self):
91+
raise NotImplementedError
92+
93+
def update_peers(self, peers: List[Tuple[int, int, str, str, str]]):
94+
with self.lock:
95+
self.conn.executemany(
96+
"REPLACE INTO peers (id, access_hash, type, username, phone_number)"
97+
"VALUES (?, ?, ?, ?, ?)",
98+
peers
99+
)
100+
101+
def get_peer_by_id(self, peer_id: int):
102+
r = self.conn.execute(
103+
"SELECT id, access_hash, type FROM peers WHERE id = ?",
104+
(peer_id,)
105+
).fetchone()
106+
107+
if r is None:
108+
raise KeyError("ID not found: {}".format(peer_id))
109+
110+
return get_input_peer(*r)
111+
112+
def get_peer_by_username(self, username: str):
113+
r = self.conn.execute(
114+
"SELECT id, access_hash, type, last_update_on FROM peers WHERE username = ?",
115+
(username,)
116+
).fetchone()
117+
118+
if r is None:
119+
raise KeyError("Username not found: {}".format(username))
120+
121+
if abs(time.time() - r[3]) > self.USERNAME_TTL:
122+
raise KeyError("Username expired: {}".format(username))
123+
124+
return get_input_peer(*r[:3])
125+
126+
def get_peer_by_phone_number(self, phone_number: str):
127+
r = self.conn.execute(
128+
"SELECT id, access_hash, type FROM peers WHERE phone_number = ?",
129+
(phone_number,)
130+
).fetchone()
131+
132+
if r is None:
133+
raise KeyError("Phone number not found: {}".format(phone_number))
134+
135+
return get_input_peer(*r)
136+
137+
def _get(self):
138+
attr = inspect.stack()[2].function
139+
140+
return self.conn.execute(
141+
"SELECT {} FROM sessions".format(attr)
142+
).fetchone()[0]
143+
144+
def _set(self, value: Any):
145+
attr = inspect.stack()[2].function
146+
147+
with self.lock, self.conn:
148+
self.conn.execute(
149+
"UPDATE sessions SET {} = ?".format(attr),
150+
(value,)
151+
)
152+
153+
def _accessor(self, value: Any = object):
154+
return self._get() if value == object else self._set(value)
155+
156+
def dc_id(self, value: int = object):
157+
return self._accessor(value)
158+
159+
def test_mode(self, value: bool = object):
160+
return self._accessor(value)
161+
162+
def auth_key(self, value: bytes = object):
163+
return self._accessor(value)
164+
165+
def date(self, value: int = object):
166+
return self._accessor(value)
167+
168+
def user_id(self, value: int = object):
169+
return self._accessor(value)
170+
171+
def is_bot(self, value: bool = object):
172+
return self._accessor(value)
173+
174+
def version(self, value: int = object):
175+
if value == object:
176+
return self.conn.execute(
177+
"SELECT number FROM version"
178+
).fetchone()[0]
179+
else:
180+
with self.lock, self.conn:
181+
self.conn.execute(
182+
"UPDATE version SET number = ?",
183+
(value,)
184+
)

0 commit comments

Comments
 (0)