-
Notifications
You must be signed in to change notification settings - Fork 8
/
parse.py
195 lines (184 loc) · 8.48 KB
/
parse.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
#!/usr/bin/env python3
from html.parser import unescape
import socks
import requests
import socket
def get_cookie(params):
log = params['logger']
res = {}
for key in params:
if key != 'logger': # not serializable object
res[key] = params[key]
if params['proxy_port'] != -1:
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, params['proxy_ip'], params['proxy_port'])
socket.socket = socks.socksocket
try:
post_params = {
'login_username': params['username'].encode('cp1251'),
'login_password': params['password'].encode('cp1251'),
'login': b'\xe2\xf5\xee\xe4' # '%E2%F5%EE%E4'
}
r = requests.post('https://rutracker.org/forum/login.php',data=post_params,allow_redirects=False,timeout=20)
if 'bb_session' in r.cookies.keys():
cookie = 'bb_session=' + r.cookies['bb_session'] + '; bb_ssl=1'
res['cookie'] = cookie
log.debug('cookie: %s' % cookie)
return 'OK', res
else:
if 'неверный пароль'.encode('cp1251') in r.content:
error_text = 'wrong username/password'
elif 'введите код подтверждения'.encode('cp1251') in r.content:
error_text = 'site want captcha'
else:
error_text = 'no cookies returned'
log.debug(error_text)
res['text'] = error_text
return 'ERROR', res
except requests.exceptions.RequestException as e:
log.debug('request exception', repr(e))
res['text'] = 'request exception'
return 'ERROR', res
except socket.timeout as e:
log.debug('request timeout exception')
res['text'] = 'request timeout exception'
return 'ERROR', res
def get_page(params):
log = params['logger']
res = {}
for key in params:
if key != 'logger': # not serializable object
res[key] = params[key]
# log.debug('get_page start')
if params['proxy_port'] != -1:
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, params['proxy_ip'], params['proxy_port'])
socket.socket = socks.socksocket
def between(text, p_from, p_to):
return text.split(p_from)[1].split(p_to)[0]
try:
path = '/forum/viewtopic.php?t=%(id)i' % {'id': params['id']}
url = 'https://rutracker.org%(path)s' % {'path': path}
params['headers']['Cookie'] = params['cookie']
req = requests.get(url, headers=params['headers'], timeout=20)
html = req.text
if not (('<html' in html) or ('HTML' in html)):
res['text'] = 'not html in response'
return 'ERROR', res
if ('profile.php?mode=register">' in html) or ('action="https://rutracker.org/forum/login.php">' in html):
res['text'] = 'not logined'
return 'ERROR', res
if len(html) < 1000:
res['text'] = 'too short'
return 'ERROR', res
# f = open('html.txt', "w")
# f.write(html)
if not ('<a href="magnet:?xt=urn:btih:' in html):
return 'NO_HASH', res
else:
line = list()
line.append(str(params['id']))
title = between(html, '<title>', ' :: RuTracker.org')
title = unescape(title)
line.append(title)
size = between(html, '<span id="tor-size-humn" title="', '">') # '<span id="tor-size-humn"', '</span>')
if not size.isdigit():
error_text = 'parser, size, not only numbers, id: %i' % params['id']
log.warning(error_text)
res['text'] = error_text
return 'ERROR', res
line.append(size)
# seeds = '0'
if '<span class="seed">Сиды: <b>' in html:
seeds = between(html, 'seed">Сиды: <b>', '</b>')
else:
seeds = '0'
# error_text = 'parser, seeds, template not found, id: %i' % params['id']
# log.debug(error_text)
# res['text'] = error_text
# return 'ERROR', res
line.append(seeds)
# peers = '0'
if 'leech">Личи: <b>' in html:
peers = between(html, 'leech">Личи: <b>', '</b>')
else:
peers = '0'
# error_text = 'parser, peers, template not found, id: %i' % params['id']
# log.debug(error_text)
# res['text'] = error_text
# return 'ERROR', res
line.append(peers)
hash = between(html, '<a href="magnet:?xt=urn:btih:', '&')
line.append(hash)
if 'torrent скачан: <b>' in html:
downloads = between(html, 'torrent скачан: <b>', " раз").strip()
elif '<td>.torrent скачан:</td>\n\t\t<td>' in html:
downloads = between(html, '<td>.torrent скачан:</td>\n\t\t<td>', " раз").strip()
elif ('Скачан: ' in html) and ('раза\t\t</td>' in html):
downloads = between(html, 'Скачан: ', 'раза\t\t</td>').strip()
elif ('Скачан: ' in html) and ('раз\t\t</td>' in html):
downloads = between(html, 'Скачан: ', 'раз\t\t</td>').strip()
else:
error_text = 'parser, downloads, template not found, id: %i' % params['id']
log.warning(error_text)
res['text'] = error_text
return 'ERROR', res
downloads = downloads.replace(',', '')
if not downloads.isdigit():
error_text = 'parser, downloads, bad template, id: %i' % params['id']
log.warning(error_text)
res['text'] = error_text
return 'ERROR', res
line.append(downloads)
if '>Зарегистрирован:</td>' in html:
date = between(html, '>Зарегистрирован:</td>', '</td>')
date = between(date, '<li>', '</li>')
else:
error_text = 'parser, date, template not found, id: %i' % params['id']
log.warning(error_text)
res['text'] = error_text
return 'ERROR', res
months = ("Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек")
for i in range(len(months)):
date = date.replace(months[i], "%02d" % (i+1))
line.append(date)
category_htmlpart = between(html, '<td class="nav w100"', '</td>')
category_temp = category_htmlpart.replace('">', "</a>").split('</a>')
category_list = list((i for i in category_temp if
('<em>' not in i) and ('\t' not in i) and ('style="' not in i) and (
'Список форумов ' not in i)))
category_string = ''
for one_category in category_list:
category_string += one_category + ' | '
category_string = category_string[:-3]
line.append(category_string)
line = '\t'.join(line)
descr = between(html, '<div class="post_body" id="', '<div class="clear"')
descr = descr.split('>', 1)[1]
descr = descr.strip()
if descr.endswith('</div><!--/post_body-->'):
descr = descr[:-23].strip()
elif descr.endswith('</div>'):
descr = descr[:-6].strip()
descr = unescape(descr)
res['line'] = line
res['description'] = descr
return 'OK', res
except requests.exceptions.RequestException as e:
error_text = 'request exception, id: %i' % params['id']
log.debug(error_text, exc_info=True)
res['text'] = error_text
return 'ERROR', res
except socket.timeout as e:
error_text = 'request timeout exception, id: %i' % params['id']
log.debug(error_text, exc_info=True)
res['text'] = error_text
return 'ERROR', res
except socks.Socks5Error as e:
error_text = 'request exception (socket error), id: %i' % params['id']
log.debug(error_text, exc_info=True)
res['text'] = error_text
return 'ERROR', res
except Exception as e:
error_text = 'unknown error, id: %i' % params['id']
log.exception(error_text)
res['text'] = error_text
return 'ERROR', res