forked from garyvalue/Media-Search-Bot-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
290 lines (246 loc) · 8.31 KB
/
utils.py
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python3
# Copyright (C) @ZauteKm
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import re
import base64
import logging
from struct import pack
from pyrogram.errors import UserNotParticipant
from pyrogram.file_id import FileId
from pymongo.errors import DuplicateKeyError
from umongo import Instance, Document, fields
from motor.motor_asyncio import AsyncIOMotorClient
from marshmallow.exceptions import ValidationError
import os
import PTN
import requests
import json
from info import DATABASE_URI, DATABASE_NAME, COLLECTION_NAME, USE_CAPTION_FILTER, AUTH_CHANNEL, API_KEY
DATABASE_URI_2=os.environ.get('DATABASE_URI_2', DATABASE_URI)
DATABASE_NAME_2=os.environ.get('DATABASE_NAME_2', DATABASE_NAME)
COLLECTION_NAME_2="Posters"
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
client = AsyncIOMotorClient(DATABASE_URI)
db = client[DATABASE_NAME]
instance = Instance.from_db(db)
IClient = AsyncIOMotorClient(DATABASE_URI_2)
imdbdb=client[DATABASE_NAME_2]
imdb=Instance.from_db(imdbdb)
@instance.register
class Media(Document):
file_id = fields.StrField(attribute='_id')
file_ref = fields.StrField(allow_none=True)
file_name = fields.StrField(required=True)
file_size = fields.IntField(required=True)
file_type = fields.StrField(allow_none=True)
mime_type = fields.StrField(allow_none=True)
caption = fields.StrField(allow_none=True)
class Meta:
collection_name = COLLECTION_NAME
@imdb.register
class Poster(Document):
imdb_id = fields.StrField(attribute='_id')
title = fields.StrField()
poster = fields.StrField()
year= fields.IntField(allow_none=True)
class Meta:
collection_name = COLLECTION_NAME_2
async def save_poster(imdb_id, title, year, url):
try:
data = Poster(
imdb_id=imdb_id,
title=title,
year=int(year),
poster=url
)
except ValidationError:
logger.exception('Error occurred while saving poster in database')
else:
try:
await data.commit()
except DuplicateKeyError:
logger.warning("already saved in database")
else:
logger.info("Poster is saved in database")
async def save_file(media):
"""Save file in database"""
# TODO: Find better way to get same file_id for same media to avoid duplicates
file_id, file_ref = unpack_new_file_id(media.file_id)
try:
file = Media(
file_id=file_id,
file_ref=file_ref,
file_name=media.file_name,
file_size=media.file_size,
file_type=media.file_type,
mime_type=media.mime_type,
caption=media.caption.html if media.caption else None,
)
except ValidationError:
logger.exception('Error occurred while saving file in database')
else:
try:
await file.commit()
except DuplicateKeyError:
logger.warning(media.file_name + " is already saved in database")
else:
logger.info(media.file_name + " is saved in database")
async def get_search_results(query, file_type=None, max_results=10, offset=0):
"""For given query return (results, next_offset)"""
query = query.strip()
if not query:
raw_pattern = '.'
elif ' ' not in query:
raw_pattern = r'(\b|[\.\+\-_])' + query + r'(\b|[\.\+\-_])'
else:
raw_pattern = query.replace(' ', r'.*[\s\.\+\-_]')
try:
regex = re.compile(raw_pattern, flags=re.IGNORECASE)
except:
return []
if USE_CAPTION_FILTER:
filter = {'$or': [{'file_name': regex}, {'caption': regex}]}
else:
filter = {'file_name': regex}
if file_type:
filter['file_type'] = file_type
total_results = await Media.count_documents(filter)
next_offset = offset + max_results
if next_offset > total_results:
next_offset = ''
cursor = Media.find(filter)
# Sort by recent
cursor.sort('$natural', -1)
# Slice files according to offset and max results
cursor.skip(offset).limit(max_results)
# Get list of files
files = await cursor.to_list(length=max_results)
return files, next_offset
async def get_filter_results(query):
query = query.strip()
if not query:
raw_pattern = '.'
elif ' ' not in query:
raw_pattern = r'(\b|[\.\+\-_])' + query + r'(\b|[\.\+\-_])'
else:
raw_pattern = query.replace(' ', r'.*[\s\.\+\-_]')
try:
regex = re.compile(raw_pattern, flags=re.IGNORECASE)
except:
return []
filter = {'file_name': regex}
total_results = await Media.count_documents(filter)
cursor = Media.find(filter)
cursor.sort('$natural', -1)
files = await cursor.to_list(length=int(total_results))
return files
async def get_file_details(query):
filter = {'file_id': query}
cursor = Media.find(filter)
filedetails = await cursor.to_list(length=1)
return filedetails
async def is_subscribed(bot, query):
try:
user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
except UserNotParticipant:
pass
except Exception as e:
logger.exception(e)
else:
if not user.status == 'kicked':
return True
return False
async def get_poster(movie):
extract = PTN.parse(movie)
try:
title=extract["title"]
except KeyError:
title=movie
try:
year=extract["year"]
year=int(year)
except KeyError:
year=None
if year:
filter = {'$and': [{'title': str(title).lower().strip()}, {'year': int(year)}]}
else:
filter = {'title': str(title).lower().strip()}
cursor = Poster.find(filter)
is_in_db = await cursor.to_list(length=1)
poster=None
if is_in_db:
for nyav in is_in_db:
poster=nyav.poster
else:
if year:
url=f'https://www.omdbapi.com/?s={title}&y={year}&apikey={API_KEY}'
else:
url=f'https://www.omdbapi.com/?s={title}&apikey={API_KEY}'
try:
n = requests.get(url)
a = json.loads(n.text)
if a["Response"] == 'True':
y = a.get("Search")[0]
v=y.get("Title").lower().strip()
poster = y.get("Poster")
year=y.get("Year")[:4]
id=y.get("imdbID")
await get_all(a.get("Search"))
except Exception as e:
logger.exception(e)
pass
return poster
async def get_all(list):
for y in list:
v=y.get("Title").lower().strip()
poster = y.get("Poster")
year=y.get("Year")[:4]
id=y.get("imdbID")
await save_poster(id, v, year, poster)
def encode_file_id(s: bytes) -> str:
r = b""
n = 0
for i in s + bytes([22]) + bytes([4]):
if i == 0:
n += 1
else:
if n:
r += b"\x00" + bytes([n])
n = 0
r += bytes([i])
return base64.urlsafe_b64encode(r).decode().rstrip("=")
def encode_file_ref(file_ref: bytes) -> str:
return base64.urlsafe_b64encode(file_ref).decode().rstrip("=")
def unpack_new_file_id(new_file_id):
"""Return file_id, file_ref"""
decoded = FileId.decode(new_file_id)
file_id = encode_file_id(
pack(
"<iiqq",
int(decoded.file_type),
decoded.dc_id,
decoded.media_id,
decoded.access_hash
)
)
file_ref = encode_file_ref(decoded.file_reference)
return file_id, file_ref
def get_size(size):
"""Get size in readable format"""
units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
size = float(size)
i = 0
while size >= 1024.0 and i < len(units):
i += 1
size /= 1024.0
return "%.2f %s" % (size, units[i])