-
Notifications
You must be signed in to change notification settings - Fork 0
/
nyaa.py
374 lines (357 loc) · 14.7 KB
/
nyaa.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
'''Simple parsing script to obtain magnet link of a torrent'''
from bs4 import BeautifulSoup
import json
import os
import signal
import subprocess
import sys
import re
import requests
class NyaaSiDownloader():
'''Torrent magnet link'''
# text format
workflow: bool
bold_text = "\033[1m"
underscore = "\x1b[4m"
reset_clr = "\x1b[0m"
red = "\x1b[31m"
green = "\x1b[32m"
yellow = "\x1b[33m"
blue = "\x1b[34m"
magenta = "\x1b[35m"
cyan = "\x1b[36m"
white = "\x1b[37m"
categories = ["0_0", "1_0", "1_1", "1_2", "1_3", "1_4", "2_0", "2_1", "2_2", "3_0", "3_1",
"3_2", "3_3", "4_0", "4_1", "4_2", "4_3", "4_4", "5_0", "5_1", "5_2", "6_0", "6_1", "6_2"]
search_type = categories[0]
# config
autoadd = False
# end config
json_torrent = '''
{
"Torrent": [
]
}
'''
@staticmethod
def verify_magnet_link(magnet_link: str) -> bool:
'''verify a magnet link using regex'''
result = re.fullmatch(
"^magnet:\?xt=urn:btih:[0-9a-fA-F]{40,}.*$", magnet_link)
if result is not None:
return True
else:
return False
@staticmethod
def searchnyaasi(req: requests.models.Response) -> None:
'''Parsing function'''
# extracting data in json format
for parsed in BeautifulSoup(req.text, "html.parser").findAll('tr'):
size = ""
seed = ""
leech = ""
date_t = ""
title = ""
magnet = ""
type_torr = ""
x = 0
for elem in parsed.findAll('img', alt=True):
type_torr = elem['alt']
for elem in parsed.findAll('td', attrs={'colspan': '2'}):
for k in elem:
if k.string is not None:
if len(k.string) > 5:
title = k.string
for elem in parsed.findAll('td', attrs={'class': 'text-center'}):
for k in elem:
if x == 3:
# sometimes there is no download link
try:
magnet = k.get('href')
except AttributeError:
title = ""
if x == 5:
size = k.string
if x == 6:
date_t = k.string
if x == 7:
seed = k.string
if x == 8:
leech = k.string
x += 1
leech = (elem.text)
# create a json with torrent info
if len(title) > 1:
temp = {
'name': title,
'size': float(size.split(" ")[0]),
'type': size.split(" ")[1],
'seed': seed,
'leech': leech,
'movie_type': type_torr,
'date': date_t,
'magnet': magnet
}
data = json.loads(NyaaSiDownloader.json_torrent)
data['Torrent'].append(temp)
NyaaSiDownloader.json_torrent = json.dumps(data, indent=4)
sorted_obj = dict(data)
sorted_obj['Torrent'] = sorted(
data['Torrent'], key=lambda pos: pos['size'], reverse=True)
NyaaSiDownloader.json_torrent = json.dumps(
sorted_obj, indent=4)
@staticmethod
def print_elem_gui(elem: dict, torrent: int) -> None:
'''Print torrent element'''
from PySide2.QtWidgets import QTableWidgetItem
title_t = elem['name']
min_pos = 0
max_pos = 95
NyaaSiDownloader.tabella.setItem(
torrent, 0, QTableWidgetItem(title_t[min_pos:max_pos]))
NyaaSiDownloader.tabella.setItem(
torrent, 1, QTableWidgetItem(f"{str(elem['size'])} {elem['type']}"))
NyaaSiDownloader.tabella.setItem(
torrent, 2, QTableWidgetItem(f"{elem['seed']}"))
NyaaSiDownloader.tabella.setItem(
torrent, 3, QTableWidgetItem(f"{elem['leech']}"))
NyaaSiDownloader.tabella.setItem(
torrent, 4, QTableWidgetItem(f"{elem['movie_type']}"))
NyaaSiDownloader.tabella.setItem(
torrent, 5, QTableWidgetItem(f"{elem['date']}"))
NyaaSiDownloader.tabella.resizeColumnsToContents()
@staticmethod
def print_elem(elem: dict) -> None:
'''Print torrent element'''
title_t = elem['name']
min_pos = 0
max_pos = 95
print(
f" {NyaaSiDownloader.cyan}TITLE: {title_t[min_pos:max_pos]}{NyaaSiDownloader.reset_clr}")
while max_pos < len(title_t):
min_pos += 95
max_pos += 95
print(
f" {NyaaSiDownloader.cyan} {title_t[min_pos:max_pos]}{NyaaSiDownloader.reset_clr}")
print(
f" {NyaaSiDownloader.red}DATE: {elem['date']}{NyaaSiDownloader.reset_clr}")
print(
f" {NyaaSiDownloader.green}DIM: {str(elem['size'])} {elem['type']} {NyaaSiDownloader.reset_clr}")
print(
f" {NyaaSiDownloader.yellow}SEED: {elem['seed']}{NyaaSiDownloader.reset_clr}")
print(
f" {NyaaSiDownloader.white}LEECH: {elem['leech']}{NyaaSiDownloader.reset_clr}")
print(
f" {NyaaSiDownloader.magenta}TYPE: {elem['movie_type']}{NyaaSiDownloader.reset_clr}")
@staticmethod
def searchnyaasi_request(name_s: str) -> None:
'''Request to the torrent site'''
# sending get request and saving the response as response object
url = f"https://nyaa.si/?f=0&c={NyaaSiDownloader.search_type}&q=/{name_s}"
req = requests.get(url=url, params={}, allow_redirects=False)
NyaaSiDownloader.searchnyaasi(req)
def avvia_ricerca(self) -> None:
'''avvio ricerca GUI'''
from PySide2.QtWidgets import QTableWidget, QPushButton, QApplication, QComboBox
# reset to allow multiple search
NyaaSiDownloader.json_torrent = '''
{
"Torrent": [
]
}
'''
NyaaSiDownloader.category = NyaaSiDownloader.window.findChild(
QComboBox, "category")
NyaaSiDownloader.search_type = NyaaSiDownloader.categories[NyaaSiDownloader.category.currentIndex(
)]
name_input = NyaaSiDownloader.titolo.text()
NyaaSiDownloader.searchnyaasi_request(str(name_input))
# populate tabel
torrent = 1
data = json.loads(NyaaSiDownloader.json_torrent)
NyaaSiDownloader.tabella = NyaaSiDownloader.window.findChild(
QTableWidget, "tableWidget")
NyaaSiDownloader.seleziona = NyaaSiDownloader.window.findChild(
QPushButton, "select")
NyaaSiDownloader.seleziona.clicked.connect(self.get_selected_element)
NyaaSiDownloader.tabella.clearContents()
NyaaSiDownloader.tabella.setRowCount(0)
QApplication.processEvents()
for elem in data['Torrent']:
pos = torrent - 1
NyaaSiDownloader.tabella.insertRow(pos)
NyaaSiDownloader.print_elem_gui(elem, pos)
torrent += 1
def get_selected_element(self) -> None:
# GUI (first time only)
NyaaSiDownloader.autoadd = NyaaSiDownloader.add.isChecked()
# get multiple selection
items = NyaaSiDownloader.tabella.selectedItems()
item_dict = json.loads(NyaaSiDownloader.json_torrent)['Torrent']
for item in items:
# only 1 item in a row
if item.column() == 1:
# start download with each selected row
magnet = item_dict[item.row()]['magnet']
self.start(magnet)
return
def choose(self) -> None:
'''Select torrent'''
# write _____________
print(f'{NyaaSiDownloader.underscore}'+' ' *
120+f'{NyaaSiDownloader.reset_clr}\n')
found = 0
while found == 0:
item_dict = json.loads(NyaaSiDownloader.json_torrent)
if item_dict['Torrent'] == []:
print(
f"{NyaaSiDownloader.red}No Torrent Found{NyaaSiDownloader.reset_clr}")
sys.exit(0)
if (NyaaSiDownloader.workflow):
number = 1
else:
try:
number = int(input('Choose torrent: '))
except ValueError:
print(
f"\n{NyaaSiDownloader.red}Not Valid!!{NyaaSiDownloader.reset_clr}\n")
self.choose()
found = 1
item_dict = json.loads(NyaaSiDownloader.json_torrent)[
'Torrent'][number-1]
NyaaSiDownloader.print_elem(item_dict)
conf = ""
if (NyaaSiDownloader.workflow):
conf = 'y'
while conf.lower() not in ['y', 'n']:
conf = input("\ny to confirm, n to repeat: ")
if conf.lower() == 'n':
found = 0
elif (conf.lower() == 'y'):
number -= 1 # indice di un array
# controllo che number sia una scelta valida:
item_dict = json.loads(NyaaSiDownloader.json_torrent)
if number < len(item_dict['Torrent']) and number >= 0:
magnet = item_dict['Torrent'][number]['magnet']
self.start(magnet)
else:
print(
f"{NyaaSiDownloader.red}Not Valid{NyaaSiDownloader.reset_clr}")
def get_magnet(self, position: int) -> None:
'''function to get magnet link'''
item_dict = json.loads(NyaaSiDownloader.json_torrent)[
'Torrent'][position]
magnet_link = item_dict['magnet']
self.start(magnet_link)
def start(self, magnet_link: str) -> None:
'''start gui search'''
# check magnet validity
if (not NyaaSiDownloader.verify_magnet_link(magnet_link)):
print(
f"{NyaaSiDownloader.red}Not a valid Magnet{NyaaSiDownloader.reset_clr}")
sys.exit(0)
if (NyaaSiDownloader.autoadd):
done = True
# avvio il magnet
if sys.platform.startswith('linux'):
try:
subprocess.Popen(['xdg-open', magnet_link])
except subprocess.CalledProcessError:
done = False
elif sys.platform.startswith('win32'):
done = os.startfile(magnet_link) # check false
elif sys.platform.startswith('cygwin'):
done = os.startfile(magnet_link) # check false
elif sys.platform.startswith('darwin'):
try:
subprocess.Popen(['open', magnet_link])
except subprocess.CalledProcessError:
done = False
else:
try:
subprocess.Popen(['xdg-open', magnet_link])
except subprocess.CalledProcessError:
done = False
if done:
print(
f'\n{NyaaSiDownloader.green}Success{NyaaSiDownloader.reset_clr}')
else: # ho incontrato un errore
if (self.gui):
from PySide2.QtWidgets import QTextEdit
text = NyaaSiDownloader.magnet_window.findChild(
QTextEdit, "magnet_link")
text.insertPlainText(magnet_link)
text.insertPlainText("\n")
text.insertPlainText("\n")
NyaaSiDownloader.magnet_window.show()
else:
print(
f"\nMagnet:{NyaaSiDownloader.red}{magnet_link}{NyaaSiDownloader.reset_clr}\n")
else:
if (self.gui):
from PySide2.QtWidgets import QTextEdit
text: QTextEdit = NyaaSiDownloader.magnet_window.findChild(
QTextEdit, "magnet_link")
# text.clear()
text.insertPlainText(magnet_link)
text.insertPlainText("\n")
text.insertPlainText("\n")
NyaaSiDownloader.magnet_window.show()
else:
print(
f"\nMagnet:{NyaaSiDownloader.red}{magnet_link}{NyaaSiDownloader.reset_clr}\n")
def __init__(self, gui: bool, wf: bool = False) -> None:
NyaaSiDownloader.workflow = wf
self.gui = gui
self_wrapp = self
signal.signal(signal.SIGTERM, NyaaSiDownloader.sig_handler)
signal.signal(signal.SIGINT, NyaaSiDownloader.sig_handler)
if (self.gui):
# GUI import
from PySide2.QtWidgets import QCheckBox, QPushButton, QLineEdit
from PySide2.QtCore import QObject
from PySide2.QtGui import QKeyEvent
class KeyPressEater(QObject):
'''event filter '''
def eventFilter(self, widget, event: QKeyEvent):
from PySide2.QtCore import QEvent, Qt
if (event.type() == QEvent.KeyPress):
key = event.key()
if key == Qt.Key_Return:
self_wrapp.avvia_ricerca()
return False
NyaaSiDownloader.filtro = KeyPressEater()
NyaaSiDownloader.titolo = NyaaSiDownloader.window.findChild(
QLineEdit, "titolo")
NyaaSiDownloader.cerca = NyaaSiDownloader.window.findChild(
QPushButton, "cerca")
NyaaSiDownloader.add = NyaaSiDownloader.window.findChild(
QCheckBox, "add")
NyaaSiDownloader.cerca.clicked.connect(self.avvia_ricerca)
NyaaSiDownloader.titolo.installEventFilter(
NyaaSiDownloader.filtro)
else:
if len(sys.argv) == 1:
name_input = input('Nome Film da cercare: ').strip()
else:
name_input = sys.argv[1]
for elem in sys.argv[2:]:
name_input += '+' + elem
NyaaSiDownloader.searchnyaasi_request(str(name_input))
# print list
torrent = 1
data = json.loads(NyaaSiDownloader.json_torrent)
for elem in data['Torrent']:
# write _____________
print(f'{NyaaSiDownloader.underscore}' + ' ' *
120 + f'{NyaaSiDownloader.reset_clr}\n')
print(
f" {NyaaSiDownloader.bold_text}Torrent {torrent} :{NyaaSiDownloader.reset_clr}")
NyaaSiDownloader.print_elem(elem)
torrent += 1
self.choose()
@classmethod
def sig_handler(cls, _signo, _stack_frame):
'''Catch ctr+c signal'''
print("\n")
sys.exit(0)