/
i.py
459 lines (405 loc) · 17.6 KB
/
i.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
from PyQt5.QtWidgets import QWidget, QLineEdit, QApplication, QLabel, \
QPushButton
from PyQt5.QtCore import QSize, QByteArray, QUrl
from PyQt5.QtGui import QIcon, QPixmap, QFontMetrics, QDesktopServices
from PyQt5.QtCore import Qt as Fl
from PyQt5.Qt import pyqtSignal
import instaloader
import sys
import requests
class MainWindow(QWidget):
def __init__(self, *args, **kwars):
super().__init__(*args, **kwars)
# Характеристики окна
self.resize(200, 200)
self.setMaximumSize(QSize(3272, 3402))
self.setMinimumSize(326, 339)
self.setWindowTitle("Inst")
# Главное
self.search_line = QLineEdit(self)
self.search_line.editingFinished.connect(self.search_acc)
self.mess_label = QLabel(self)
self.mess_label.hide()
self.mess_label.resize(120, 40)
self.mess_label.setAlignment(Fl.AlignHCenter | Fl.AlignTop)
# 9 фото
self.tables = 0
self.right = QPushButton(self)
self.right.setText("->")
self.right.clicked.connect(self.next_table)
self.right.hide()
self.left = QPushButton(self)
self.left.setText("<-")
self.left.clicked.connect(self.prev_table)
self.left.hide()
self.pixmaps = []
self.labels_px = []
for i in range(3):
mat = []
mat2 = []
for j in range(3):
mat.append("")
mat2.append(MLabel(self))
mat2[j].clicked.connect(self.open_link)
mat2[j].hide()
self.pixmaps.append(mat)
self.labels_px.append(mat2)
flags = Fl.CustomizeWindowHint | Fl.WindowMinimizeButtonHint
flags = flags | Fl.WindowFullScreen | Fl.WindowCloseButtonHint
flags = flags | Fl.WindowMaximizeButtonHint
self.setWindowFlags(flags)
# Остальное
self.instloader_instance = instaloader.Instaloader()
self.sh_profile = None
self.show_profile = False
self.search_lines = []
self.loaded = 0
for i in range(3):
self.search_lines.append(SearchLine(self))
self.init_ui()
def resizeEvent(self, resize_event):
self.init_ui()
def init_ui(self): # Корректировка интерфейса под окно
x_y = self.size()
x = self.size().width()
y = self.size().height()
del x_y
# Размеры поисковой строки и отступы для неё
search_w = int(0.81595 * x)
search_h = int(y * 0.0442)
search_x = int(x * 0.0613)
search_y = int(y * 0.00613)
self.search_line.resize(search_w, search_h)
b_suze = int(x * 0.09203) - 4
# Кнопки лево и право
self.right.resize(b_suze, search_h)
self.right.move(x - b_suze - 2, search_y)
self.left.resize(b_suze, search_h)
self.left.move(2, search_y)
search_x = 4 + b_suze
self.search_line.move(search_x, search_y)
for i in range(0, 3):
# Задание аднных, необходимых для правильного отображения
# поисковой выдачи
self.search_lines[i].x = search_x
self.search_lines[i].y = search_y + (i + 1) * search_h
self.search_lines[i].width = search_w
self.search_lines[i].height = search_h
if self.search_lines[i].see:
self.search_lines[i].generate()
if self.show_profile:
# Если профиль открыт
if self.sh_profile.inst_profile.is_private:
self.mess_label.show()
elif self.loaded == 0:
self.mess_label.show()
pic_size = int(0.3129 * min(x, y))
b_x = int(x / 2 - 1.5 * pic_size)
b_y = search_h + search_y + int(0.0184 * y)
self.mess_label.move(int(x / 2) - 60, b_y + 5)
# Задаём описание профиля при наведении
tt = str(
"Username: " + self.sh_profile.inst_profile.username)
tt += "; ID: " + str(self.sh_profile.inst_profile.userid) + "; "
tt += (
" private " if self.sh_profile.inst_profile.is_private else "")
tt += (
" verified" if self.sh_profile.inst_profile.is_verified else "")
tool_tip = tt + "\n" + "Подписчиков: " + str(
self.sh_profile.inst_profile.followers) + "\nПодписок: "
tool_tip += str(self.sh_profile.inst_profile.followees) + \
"\nБиография:\n" + self.sh_profile.inst_profile.biography
if self.sh_profile.inst_profile.biography == "":
tool_tip = tool_tip[: -1]
self.setToolTip(tool_tip)
# Отображение картинок:
# - фокусировка в центре и сжатие до нужного размера
# - перемещение соответствующего Label на экране
# - задание подсказки о посте при наведении
for i in range(3):
for j in range(3):
if i * 3 + j >= self.loaded:
self.labels_px[i][j].hide()
continue
mn = min(self.pixmaps[i][j].size().width(),
self.pixmaps[i][j].size().height())
self.labels_px[i][j].resize(pic_size, pic_size)
self.labels_px[i][j].setPixmap(self.pixmaps[i][j].copy(
int(self.pixmaps[i][j].size().width() / 2) - int(
mn / 2),
int(self.pixmaps[i][j].size().height() / 2) - int(
mn / 2), mn, mn).scaled(pic_size, pic_size))
self.labels_px[i][j].move(b_x + pic_size * j,
b_y + pic_size * i)
ind = i * 3 + j + self.tables * 9
sp = self.sh_profile.posts[ind].caption.split(".")
text = ""
opened = 0
for ii in sp:
if ii != "":
if opened > 0 and ii.count("”") > 0:
text = text[: -1]
opened -= 1
if ii.count("“") > 0:
if opened == 0:
opened += ii.count("“") % 2
text += ii + ".\n"
else:
text += "."
if text[-1] == "\n":
text = text[: -1]
ur = self.labels_px[i][j].url.split()[1]
ur = ur[: len(ur) - 1]
text_tip = "Нравится: " + str(self.sh_profile.posts[
ind].likes) + \
"; Комментарии: " + str(
self.sh_profile.posts[
ind].comments) + "\nДата публикации: " + str(
self.sh_profile.posts[ind].date_local) \
+ "\nНажмите, чтобы открыть в браузере /p/" + \
ur + "\nТекст публикации:\n" + text
self.labels_px[i][j].setToolTip(
text_tip[:len(text_tip) - 1])
self.labels_px[i][j].show()
# Изменение кегля поисковой строки
font = self.search_line.font()
font.setPointSize(int(0.567 * int(y * 0.0442)))
self.search_line.setFont(font)
def open_link(self): # Универсальное открытие ссылки
ur = "https://instagram.com/p/" + self.sender().url.split()[1]
ur = ur[:len(ur) - 1]
print(ur)
QDesktopServices.openUrl(QUrl(ur))
def search_acc(
self): # Поиск аккаунта и отображение соответсвующей информации
t = self.search_line.text()
if t == "":
for i in range(3):
self.search_lines[i].message = False
self.search_lines[i].hide()
return
to_show = self.__search_acc__(t)
for i in range(3):
self.search_lines[i].message = False
self.search_lines[i].hide()
if len(to_show) == 0:
self.search_lines[0].message = True
self.search_lines[0].text = "Не найдено"
self.search_lines[0].generate()
self.search_lines[0].show()
elif len(to_show) > 0:
self.search_lines[0].new_profile(to_show[0])
self.search_lines[0].generate()
self.search_lines[0].show()
if len(to_show) > 1:
self.search_lines[1].new_profile(to_show[1])
self.search_lines[1].generate()
self.search_lines[1].show()
def __search_acc__(self, text: str): # Именно поиск аккаунта
result = []
try:
res = MProfile(instaloader.Profile.from_username(
self.instloader_instance.context, text))
if isinstance(res, MProfile):
result.append(res)
except instaloader.ProfileNotExistsException:
pass
except Exception as ex:
pass
try:
res = MProfile(instaloader.Profile.from_id(
self.instloader_instance.context, int(text)))
if isinstance(res, MProfile):
result.append(res)
except instaloader.ProfileNotExistsException:
pass
except ValueError:
pass
except Exception as ex:
pass
return result
def show_profile_f(self): # Первое отображение профиля
self.mess_label.hide()
self.right.hide()
self.left.hide()
for i in range(3):
self.search_lines[i].message = False
self.search_lines[i].hide()
sender = self.sender()
for i in range(3):
if self.search_lines[i].label_for_text == sender or \
self.search_lines[i].label_for_pic == sender:
self.sh_profile = self.search_lines[i].profile
self.show_profile = True
self.search_line.setText(self.sh_profile.inst_profile.username)
break
self.setWindowTitle(self.sh_profile.inst_profile.username)
ico = QPixmap()
ico.loadFromData(QByteArray(self.sh_profile.profile_pic))
self.setWindowIcon(QIcon(ico))
self.search_line.setText("")
self.loaded = 0
# Загрузка фото
for i in self.sh_profile.inst_profile.get_posts():
self.sh_profile.add_image(requests.get(i.url).content)
self.sh_profile.add_post(i)
self.loaded += 1
if self.loaded == 10:
break
# Проверка на исключительные случаи
# 0 фото или приватный профиль
if self.loaded == 0:
self.mess_label.setText("Публикаций пока нет")
self.mess_label.show()
if self.sh_profile.inst_profile.is_private:
self.mess_label.setText("Это приватный аккаунт")
self.mess_label.show()
if self.loaded != 0 and not self.sh_profile.inst_profile.is_private:
self.mess_label.hide()
self.tables = 0
if self.loaded > 9:
self.right.show()
self.set_table(0)
self.init_ui()
def set_table(self, ind): # Задание соответствующей страницы 3*3
self.clear_table()
ind *= 9
for i in range(3):
for j in range(3):
if i * 3 + j + ind >= self.loaded:
return
else:
self.pixmaps[i][j].loadFromData(
QByteArray(self.sh_profile.images[i * 3 + j + ind]))
self.labels_px[i][j].url = str(
self.sh_profile.posts[i * 3 + j + ind])
def clear_table(self): # Очистка от предыдущей страницы
for i in range(3):
for j in range(3):
self.pixmaps[i][j] = QPixmap()
self.labels_px[i][j].setPixmap(QPixmap())
self.labels_px[i][j].url = ""
def next_table(self): # Отображение следующей страницы 3*3
self.tables += 1
if self.tables >= 1:
self.left.show()
end = self.tables * 9 + 9
ind = 0
if self.loaded < end:
for i in self.sh_profile.inst_profile.get_posts():
if ind > self.loaded:
self.sh_profile.add_image(requests.get(i.url).content)
self.sh_profile.add_post(i)
if ind >= end:
break
ind += 1
else:
self.right.hide()
self.loaded = end
self.set_table(self.tables)
self.init_ui()
def prev_table(self): # Отображение предыдущей страницы 3*3
self.tables -= 1
if self.tables == 0:
self.left.hide()
self.right.show()
self.set_table(self.tables)
self.init_ui()
class MProfile: # Класс с сохранением уже полученной информации
def __init__(self, profile: instaloader.Profile):
self.images = []
self.inst_profile = profile
self.posts = []
if profile.profile_pic_url:
self.profile_pic = requests.get(profile.profile_pic_url).content
self.hasPic = True
else:
self.hasPic = False
self.profile_pic = None
def add_image(self, image):
self.images.append(image)
def add_post(self, post):
self.posts.append(post)
def __getitem__(self, item):
return self.post[item]
class SearchLine: # Поисковой результат
def __init__(self, parent):
self.profile = None
self.x = 0
self.y = 0
self.width = 0
self.height = 0
self.label_for_text = ClickedLabel(parent)
self.label_for_text.clicked.connect(parent.show_profile_f)
self.label_for_text.setAlignment(Fl.AlignLeft | Fl.AlignVCenter)
self.label_for_pic = ClickedLabel(parent)
self.label_for_pic.clicked.connect(parent.show_profile_f)
self.see = False
self.message = False
self.text = None
self.hide()
def new_profile(self, profile: MProfile): # Новый профиль для отображения
self.profile = profile
def generate(self): # Отображение в соответствие с размерами
size_pic = min(self.height, self.width)
self.label_for_pic.resize(size_pic, size_pic)
if not self.message:
pxmap = QPixmap()
if self.profile.hasPic:
pxmap.loadFromData(QByteArray(self.profile.profile_pic))
else:
pxmap.loadFromData(no_photo)
pxmap = pxmap.scaled(size_pic, size_pic)
self.label_for_pic.setPixmap(pxmap)
self.label_for_pic.move(self.x, self.y)
else:
self.label_for_pic.setPixmap(QPixmap())
font = self.label_for_text.font()
limit = int(self.height * 0.9)
min_size_font = 0
max_size_font = 200
while max_size_font - min_size_font > 1:
d = int((min_size_font + max_size_font) / 2)
font.setPointSize(d)
if QFontMetrics(font).height() > limit:
max_size_font = d
else:
min_size_font = d
font.setPointSize(min_size_font)
self.label_for_text.setFont(font)
self.label_for_text.resize(self.width - size_pic, self.height)
if not self.message:
self.label_for_text.move(self.x + size_pic + 10, self.y)
text = self.profile.inst_profile.username
if self.profile.inst_profile.is_private:
text += " (private) "
self.label_for_text.setText(text)
else:
self.label_for_text.move(self.x + 4, self.y)
self.label_for_text.setText(self.text)
def show(self): # Показать элементы данного блока
self.see = True
self.label_for_text.show()
self.label_for_pic.show()
def hide(self): # Скрыть элементы данного блока
self.see = False
self.label_for_pic.hide()
self.label_for_text.hide()
class ClickedLabel(QLabel): # QLabel с возможность connect к clicked
clicked = pyqtSignal()
def mouseReleaseEvent(self, e):
super().mouseReleaseEvent(e)
self.clicked.emit()
class MLabel(QLabel): # Qlabel с ссылкой
clicked = pyqtSignal()
def __init__(self, *args, **kwars):
super().__init__(*args, **kwars)
self.url = None
def mouseReleaseEvent(self, e):
super().mouseReleaseEvent(e)
self.clicked.emit()
if __name__ == "__main__":
app = QApplication(sys.argv)
m = MainWindow()
m.show()
sys.exit(app.exec())