Repository navigation
Expand file tree
/
Copy pathTelegaKeeper.py
More file actions
201 lines (167 loc) · 5.49 KB
/
Copy pathTelegaKeeper.py
File metadata and controls
201 lines (167 loc) · 5.49 KB
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
# CopyLeft 2026 github.com/i-execute
# Author: I_execute.t.me
# Licensed under AGPLv3.
__version__ = (2, 0, 0)
# meta developer: Execute_forge.t.me
import atexit
import json
import logging
import os
import sys
import tempfile
from .. import loader
logger = logging.getLogger(__name__)
_TG_API_ID = 21882615
_TG_API_HASH = "a55678cc05c1aad2fb0aaccbf9663241"
_DB_ORIG_ID = "orig_api_id"
_DB_ORIG_HASH = "orig_api_hash"
_DB_CFG_PATH = "cfg_path"
def _candidate_dirs():
dirs = []
def add(d):
if d and d not in dirs:
dirs.append(d)
try:
cwd = os.getcwd()
add(cwd)
add(os.path.dirname(cwd))
except Exception:
pass
for name in ("heroku", "__main__"):
try:
mod = sys.modules.get(name)
f = getattr(mod, "__file__", None)
if f:
d = os.path.dirname(os.path.abspath(f))
add(d)
add(os.path.dirname(d))
except Exception:
pass
try:
if sys.argv and sys.argv[0]:
d = os.path.dirname(os.path.abspath(sys.argv[0]))
add(d)
add(os.path.dirname(d))
except Exception:
pass
try:
d = os.path.dirname(os.path.abspath(__file__))
for _ in range(4):
add(d)
d = os.path.dirname(d)
except Exception:
pass
return dirs
def _find_config():
for d in _candidate_dirs():
path = os.path.join(d, "config.json")
if not os.path.isfile(path):
continue
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict) and "api_id" in data and "api_hash" in data:
return path, data
except Exception:
continue
return None, None
def _atomic_write(path, data):
d = os.path.dirname(path)
fd, tmp = tempfile.mkstemp(dir=d, prefix=".config_", suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
f.flush()
os.fsync(f.fileno())
try:
os.chmod(tmp, os.stat(path).st_mode)
except Exception:
pass
os.replace(tmp, path)
finally:
if os.path.exists(tmp):
try:
os.remove(tmp)
except Exception:
pass
@loader.tds
class TelegaKeeper(loader.Module):
"""Make ur client unofficial"""
strings = {"name": "TelegaKeeper"}
async def client_ready(self, client, db):
self._client = client
self._db = db
self._swapped = False
try:
self._swap()
except Exception as e:
logger.error(f"[TelegaKeeper] swap error: {e}")
atexit.register(self._restore)
def _swap(self):
path, data = _find_config()
if not path:
logger.error("[TelegaKeeper] config.json not found")
return
cur_id, cur_hash = data.get("api_id"), data.get("api_hash")
already = str(cur_id) == str(_TG_API_ID) and str(cur_hash) == _TG_API_HASH
has_orig = self.get(_DB_ORIG_ID) is not None and self.get(_DB_ORIG_HASH)
if not already:
self.set(_DB_ORIG_ID, cur_id)
self.set(_DB_ORIG_HASH, cur_hash)
self.set(_DB_CFG_PATH, path)
try:
_atomic_write(
path + ".tk.bak",
{"api_id": cur_id, "api_hash": cur_hash},
)
except Exception as e:
logger.warning(f"[TelegaKeeper] bak write error: {e}")
data["api_id"] = _TG_API_ID
data["api_hash"] = _TG_API_HASH
_atomic_write(path, data)
logger.info(f"[TelegaKeeper] Keys swapped in {path}")
elif has_orig:
logger.info("[TelegaKeeper] Telega keys already set, originals kept")
else:
logger.warning("[TelegaKeeper] Telega keys set but originals unknown")
self._swapped = True
def _restore(self):
try:
orig_id = self.get(_DB_ORIG_ID)
orig_hash = self.get(_DB_ORIG_HASH)
path = self.get(_DB_CFG_PATH)
if (orig_id is None or not orig_hash) and path:
try:
with open(path + ".tk.bak", encoding="utf-8") as f:
bak = json.load(f)
orig_id, orig_hash = bak.get("api_id"), bak.get("api_hash")
except Exception:
pass
if orig_id is None or not orig_hash:
return
if not path or not os.path.isfile(path):
path, _ = _find_config()
if not path:
return
with open(path, encoding="utf-8") as f:
data = json.load(f)
data["api_id"] = orig_id
data["api_hash"] = orig_hash
_atomic_write(path, data)
self.set(_DB_ORIG_ID, None)
self.set(_DB_ORIG_HASH, None)
self.set(_DB_CFG_PATH, None)
try:
os.remove(path + ".tk.bak")
except Exception:
pass
self._swapped = False
logger.info("[TelegaKeeper] Original keys restored")
except Exception as e:
logger.error(f"[TelegaKeeper] restore error: {e}")
async def on_unload(self):
self._restore()
try:
atexit.unregister(self._restore)
except Exception:
pass