Repository navigation
Expand file tree
/
Copy pathAccount.py
More file actions
309 lines (230 loc) · 9.53 KB
/
Copy pathAccount.py
File metadata and controls
309 lines (230 loc) · 9.53 KB
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
# -*- coding: utf-8 -*-
import random
import threading
import time
import traceback
from pyload.plugin.Plugin import Base
from pyload.utils import compare_time, parseFileSize, lock
class WrongPassword(Exception):
pass
class Account(Base):
"""
Base class for every Account plugin.
Just overwrite `login` and cookies will be stored and account becomes accessible in\
associated hoster plugin. Plugin should also provide `loadAccountInfo`
"""
__name = "Account"
__type = "account"
__version = "0.03"
__description = """Base account plugin"""
__license = "GPLv3"
__authors = [("mkaay", "mkaay@mkaay.de")]
#: after that time (in minutes) pyload will relogin the account
login_timeout = 10 * 60
#: after that time (in minutes) account data will be reloaded
info_threshold = 10 * 60
def __init__(self, manager, accounts):
Base.__init__(self, manager.core)
self.manager = manager
self.accounts = {}
self.infos = {} #: cache for account information
self.lock = threading.RLock()
self.timestamps = {}
self.init()
self.setAccounts(accounts)
def init(self):
pass
def login(self, user, data, req):
"""login into account, the cookies will be saved so user can be recognized
:param user: loginname
:param data: data dictionary
:param req: `Request` instance
"""
pass
@lock
def _login(self, user, data):
# set timestamp for login
self.timestamps[user] = time.time()
req = self.getAccountRequest(user)
try:
self.login(user, data, req)
except WrongPassword:
self.logWarning(
_("Could not login with account %(user)s | %(msg)s") % {"user": user,
"msg": _("Wrong Password")})
success = data['valid'] = False
except Exception, e:
self.logWarning(
_("Could not login with account %(user)s | %(msg)s") % {"user": user,
"msg": e})
success = data['valid'] = False
if self.core.debug:
traceback.print_exc()
else:
success = True
finally:
if req:
req.close()
return success
def relogin(self, user):
req = self.getAccountRequest(user)
if req:
req.cj.clear()
req.close()
if user in self.infos:
del self.infos[user] #: delete old information
return self._login(user, self.accounts[user])
def setAccounts(self, accounts):
self.accounts = accounts
for user, data in self.accounts.iteritems():
self._login(user, data)
self.infos[user] = {}
def updateAccounts(self, user, password=None, options={}):
""" updates account and return true if anything changed """
if user in self.accounts:
self.accounts[user]['valid'] = True #: do not remove or accounts will not login
if password:
self.accounts[user]['password'] = password
self.relogin(user)
return True
if options:
before = self.accounts[user]['options']
self.accounts[user]['options'].update(options)
return self.accounts[user]['options'] != before
else:
self.accounts[user] = {"password": password, "options": options, "valid": True}
self._login(user, self.accounts[user])
return True
def removeAccount(self, user):
if user in self.accounts:
del self.accounts[user]
if user in self.infos:
del self.infos[user]
if user in self.timestamps:
del self.timestamps[user]
@lock
def getAccountInfo(self, name, force=False):
"""retrieve account infos for an user, do **not** overwrite this method!\\
just use it to retrieve infos in hoster plugins. see `loadAccountInfo`
:param name: username
:param force: reloads cached account information
:return: dictionary with information
"""
data = Account.loadAccountInfo(self, name)
if force or name not in self.infos:
self.logDebug("Get Account Info for %s" % name)
req = self.getAccountRequest(name)
try:
infos = self.loadAccountInfo(name, req)
if not type(infos) == dict:
raise Exception("Wrong return format")
except Exception, e:
infos = {"error": str(e)}
traceback.print_exc()
if req:
req.close()
self.logDebug("Account Info: %s" % infos)
infos['timestamp'] = time.time()
self.infos[name] = infos
elif "timestamp" in self.infos[name] and self.infos[name]['timestamp'] + self.info_threshold * 60 < time.time():
self.logDebug("Reached timeout for account data")
self.scheduleRefresh(name)
data.update(self.infos[name])
return data
def isPremium(self, user):
info = self.getAccountInfo(user)
return info['premium']
def loadAccountInfo(self, name, req=None):
"""this should be overwritten in account plugin,\
and retrieving account information for user
:param name:
:param req: `Request` instance
:return:
"""
return {"validuntil" : None, #: -1 for unlimited
"login" : name,
# "password" : self.accounts[name]['password'], #: commented due security reason
"options" : self.accounts[name]['options'],
"valid" : self.accounts[name]['valid'],
"trafficleft": None, #: in bytes, -1 for unlimited
"maxtraffic" : None,
"premium" : None,
"timestamp" : 0, #: time this info was retrieved
"type" : self.getClassName()}
def getAllAccounts(self, force=False):
return [self.getAccountInfo(user, force) for user, data in self.accounts.iteritems()]
def getAccountRequest(self, user=None):
if not user:
user, data = self.selectAccount()
if not user:
return None
req = self.core.requestFactory.getRequest(self.getClassName(), user)
return req
def getAccountCookies(self, user=None):
if not user:
user, data = self.selectAccount()
if not user:
return None
cj = self.core.requestFactory.getCookieJar(self.getClassName(), user)
return cj
def getAccountData(self, user):
return self.accounts[user]
def selectAccount(self):
""" returns an valid account name and data"""
usable = []
for user, data in self.accounts.iteritems():
if not data['valid']:
continue
if "time" in data['options'] and data['options']['time']:
time_data = ""
try:
time_data = data['options']['time'][0]
start, end = time_data.split("-")
if not compare_time.time(start.split(":"), end.split(":")):
continue
except Exception:
self.logWarning(_("Your Time %s has wrong format, use: 1:22-3:44") % time_data)
if user in self.infos:
if "validuntil" in self.infos[user]:
if self.infos[user]['validuntil'] > 0 and time.time() > self.infos[user]['validuntil']:
continue
if "trafficleft" in self.infos[user]:
if self.infos[user]['trafficleft'] == 0:
continue
usable.append((user, data))
if not usable:
return None, None
return random.choice(usable)
def canUse(self):
return self.selectAccount() != (None, None)
def parseTraffic(self, value, unit=None): #: return bytes
if not unit and not isinstance(value, basestring):
unit = "KB"
return parseFileSize(value, unit)
def wrongPassword(self):
raise WrongPassword
def empty(self, user):
if user in self.infos:
self.logWarning(_("Account %s has not enough traffic, checking again in 30min") % user)
self.infos[user].update({"trafficleft": 0})
self.scheduleRefresh(user, 30 * 60)
def expired(self, user):
if user in self.infos:
self.logWarning(_("Account %s is expired, checking again in 1h") % user)
self.infos[user].update({"validuntil": time.time() - 1})
self.scheduleRefresh(user, 60 * 60)
def scheduleRefresh(self, user, time=0, force=True):
""" add task to refresh account info to sheduler """
self.logDebug("Scheduled Account refresh for %s in %s seconds." % (user, time))
self.core.scheduler.addJob(time, self.getAccountInfo, [user, force])
@lock
def checkLogin(self, user):
""" checks if user is still logged in """
if user in self.timestamps:
if self.login_timeout > 0 and self.timestamps[user] + self.login_timeout * 60 < time.time():
self.logDebug("Reached login timeout for %s" % user)
return self.relogin(user)
else:
return True
else:
return False