forked from DiMartinoXBMC/plugin.video.torrenter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearcherABC.py
256 lines (221 loc) · 8.44 KB
/
SearcherABC.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
# -*- coding: utf-8 -*-
'''
Torrenter v2 plugin for XBMC/Kodi
Copyright (C) 2012-2015 Vadim Skorba v1 - DiMartino v2
https://forums.tvaddons.ag/addon-releases/29224-torrenter-v2.html
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import urllib
import urllib2
import cookielib
import re
import tempfile
import hashlib
import os
from StringIO import StringIO
import zlib
import socket
import sys
import xbmcgui
import xbmc
import Localization
from functions import log, debug, showMessage
class SearcherABC:
searchIcon = '/icons/video.png'
sourceWeight = 1
cookieJar = None
timeout_multi=int(sys.modules["__main__"].__settings__.getSetting("timeout"))
proxy=int(sys.modules["__main__"].__settings__.getSetting("proxy"))
__plugin__='Empty v 0 0 0'
baseurl = 'site.com'
socket.setdefaulttimeout(10+(10*int(timeout_multi)))
def search(self, keyword):
'''
Retrieve keyword from the input and return a list of tuples:
filesList.append((
int(weight),
int(seeds),
str(title),
str(link),
str(image),
))
'''
return
def isMagnetLinkSource(self):
return 'Should never see this'
def getTorrentFile(self, url):
return url
def sizeConvert(self, sizeBytes):
if long(sizeBytes) >= 1024 * 1024 * 1024:
size = str(long(sizeBytes) / (1024 * 1024 * 1024)) + 'GB'
elif long(sizeBytes) >= 1024 * 1024:
size = str(long(sizeBytes) / (1024 * 1024)) + 'MB'
elif sizeBytes >= 1024:
size = str(long(sizeBytes) / 1024) + 'KB'
else:
size = str(long(sizeBytes)) + 'B'
return size
def check_login(self, response=None):
return True
def login(self):
return True
def load_cookie(self):
cookie=os.path.join(self.tempdir(), self.__class__.__name__+'.txt')
self.cookieJar = cookielib.MozillaCookieJar(cookie)
try:
if os.path.exists(cookie): self.cookieJar.load(ignore_discard=True)
except:
self.log('[load_cookie]: os.remove(cookie)')
os.remove(cookie)
self.cookieJar = cookielib.MozillaCookieJar(cookie)
def clear_cookie(self, domain):
cookie=os.path.join(self.tempdir(),self.__class__.__name__+'.txt')
self.cookieJar = cookielib.MozillaCookieJar(cookie)
if os.path.exists(cookie):
os.remove(cookie)
self.log('[clear_cookie]: cookie cleared')
def makeRequest(self, url, data={}, headers={}):
self.load_cookie()
opener = None
if self.proxy == 1:
try:
from resources.proxy import antizapret
opener = urllib2.build_opener(antizapret.AntizapretProxyHandler(), urllib2.HTTPCookieProcessor(self.cookieJar))
config = antizapret.config()
self.debug('[antizapret]: '+str(config["domains"]))
self.debug('[antizapret]: '+str(config["server"]))
except:
showMessage('AntiZapret', Localization.localize('Error'))
self.debug('[antizapret]: OFF!')
if not opener:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookieJar))
opener.addheaders = headers
if 0 < len(data):
encodedData = urllib.urlencode(data)
else:
encodedData = None
try:
response = opener.open(url, encodedData)
except urllib2.HTTPError as e:
if e.code == 404:
self.log('[makeRequest]: Not Found! HTTP Error, e.code=' + str(e.code))
return
elif e.code in [503]:
self.log('[makeRequest]: Denied, HTTP Error, e.code=' + str(e.code))
return
else:
self.log('[makeRequest]: HTTP Error, e.code=' + str(e.code))
return
#self.cookieJar.extract_cookies(response, urllib2)
if response.info().get('Content-Encoding') == 'gzip':
buf = StringIO(response.read())
decomp = zlib.decompressobj(16 + zlib.MAX_WBITS)
response = decomp.decompress(buf.getvalue())
else:
response = response.read()
return response
def askCaptcha(self, url):
temp_dir = self.tempdir()
if isinstance(temp_dir, list): temp_dir = temp_dir[0]
urllib.URLopener().retrieve(url, temp_dir + '/captcha.png')
window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
if isinstance(temp_dir, list): temp_dir = temp_dir[0]
image = xbmcgui.ControlImage(460, 20, 360, 160, temp_dir + '/captcha.png')
window.addControl(image)
keyboardCaptcha = xbmc.Keyboard('', '[%s] %s' % (self.__plugin__, Localization.localize('Input symbols from CAPTCHA image:')))
keyboardCaptcha.doModal()
captchaText = keyboardCaptcha.getText()
window.removeControl(image)
if not captchaText:
return False
else:
return captchaText
htmlCodes = (
('&', '&'),
('<', '<'),
('>', '>'),
('"', '"'),
('"', '"'),
("'", '''),
("&", '&'),
("'", '''),
("&", '&'),)
stripPairs = (
('<p>', '\n'),
('<li>', '\n'),
('<br>', '\n'),
('<.+?>', ' '),
('</.+?>', ' '),
(' ', ' '),
('«', '"'),
('»', '"'),
)
def unescape(self, string):
for (symbol, code) in self.htmlCodes:
string = re.sub(code, symbol, string)
return string
def stripHtml(self, string):
for (html, replacement) in self.stripPairs:
string = re.sub(html, replacement, string)
return string
def md5(self, string):
hasher = hashlib.md5()
hasher.update(string)
return hasher.hexdigest()
def tempdir(self):
dirname = xbmc.translatePath('special://temp')
for subdir in ('xbmcup', 'plugin.video.torrenter'):
dirname = os.path.join(dirname, subdir)
if not os.path.exists(dirname):
os.mkdir(dirname)
return dirname
def timeout(self, add_seconds=0):
seconds=10+(10*int(self.timeout_multi))+int(add_seconds)
socket.setdefaulttimeout(int(seconds))
def clean(self, string):
specials = ['/', '\\', '-', '[', ']', '(', ')', ',']
for symbol in specials:
string = string.replace(symbol, ' ')
if len(string) > 120:
string = string[:120]
last_piece = string.split(' ')[-1]
string = string[:120 - len(last_piece)].strip()
return string
def saveTorrentFile(self, url, content):
try:
temp_dir = tempfile.gettempdir()
except:
temp_dir = self.tempdir()
localFileName = temp_dir + os.path.sep + self.md5(url) + ".torrent"
localFile = open(localFileName, 'wb+')
localFile.write(content)
localFile.close()
return localFileName
def logout(self):
pass
def log(self, msg):
log('[%s] ' % self.__plugin__ +msg)
def debug(self, msg):
debug('[%s] ' % self.__plugin__ +msg)
def open2(self, url=''):
import httplib
conn = httplib.HTTPConnection(self.baseurl)
conn.request("GET", str(url))
r1 = conn.getresponse()
status = str(r1.status) + " " + r1.reason
content = r1.read()
self.debug('[open2] status:'+str(status))
return content
def showMessage(self, heading, message, times=10000):
xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")' % (
heading.replace('"', "'"), message.replace('"', "'"), times, self.searchIcon))
self.log(str((heading.replace('"', "'"), message.replace('"', "'"), times, self.searchIcon)))