-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathmyplexaccount.py
309 lines (250 loc) · 10.9 KB
/
myplexaccount.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
from __future__ import absolute_import
import json
import time
import hashlib
from xml.etree import ElementTree
from . import plexapp
from . import myplexrequest
from . import locks
from . import callback
from . import asyncadapter
from . import util
ACCOUNT = None
class HomeUser(util.AttributeDict):
pass
class MyPlexAccount(object):
def __init__(self):
# Strings
self.ID = None
self.title = None
self.username = None
self.thumb = None
self.email = None
self.authToken = None
self.pin = None
self.thumb = None
# Booleans
self.isAuthenticated = util.INTERFACE.getPreference('auto_signin', False)
self.isSignedIn = False
self.isOffline = False
self.isExpired = False
self.isPlexPass = False
self.isManaged = False
self.isSecure = False
self.hasQueue = False
self.isAdmin = False
self.switchUser = False
self.adminHasPlexPass = False
self.lastHomeUserUpdate = None
self.homeUsers = []
def init(self):
self.loadState()
def saveState(self):
obj = {
'ID': self.ID,
'title': self.title,
'username': self.username,
'email': self.email,
'authToken': self.authToken,
'pin': self.pin,
'isPlexPass': self.isPlexPass,
'isManaged': self.isManaged,
'isAdmin': self.isAdmin,
'isSecure': self.isSecure,
'adminHasPlexPass': self.adminHasPlexPass
}
util.INTERFACE.setRegistry("MyPlexAccount", json.dumps(obj), "myplex")
def loadState(self):
# Look for the new JSON serialization. If it's not there, look for the
# old token and Plex Pass values.
util.APP.addInitializer("myplex")
jstring = util.INTERFACE.getRegistry("MyPlexAccount", None, "myplex")
if jstring:
try:
obj = json.loads(jstring)
except:
util.ERROR()
obj = None
if obj:
self.ID = obj.get('ID') or self.ID
self.title = obj.get('title') or self.title
self.username = obj.get('username') or self.username
self.email = obj.get('email') or self.email
self.authToken = obj.get('authToken') or self.authToken
self.pin = obj.get('pin') or self.pin
self.isPlexPass = obj.get('isPlexPass') or self.isPlexPass
self.isManaged = obj.get('isManaged') or self.isManaged
self.isAdmin = obj.get('isAdmin') or self.isAdmin
self.isSecure = obj.get('isSecure') or self.isSecure
self.isProtected = bool(obj.get('pin'))
self.adminHasPlexPass = obj.get('adminHasPlexPass') or self.adminHasPlexPass
if self.authToken:
request = myplexrequest.MyPlexRequest("/users/account")
context = request.createRequestContext("account", callback.Callable(self.onAccountResponse))
util.APP.startRequest(request, context)
else:
util.APP.clearInitializer("myplex")
def logState(self):
util.LOG("Authenticated as {0}:{1}".format(self.ID, repr(self.title)))
util.LOG("SignedIn: {0}".format(self.isSignedIn))
util.LOG("Offline: {0}".format(self.isOffline))
util.LOG("Authenticated: {0}".format(self.isAuthenticated))
util.LOG("PlexPass: {0}".format(self.isPlexPass))
util.LOG("Managed: {0}".format(self.isManaged))
util.LOG("Protected: {0}".format(self.isProtected))
util.LOG("Admin: {0}".format(self.isAdmin))
util.LOG("AdminPlexPass: {0}".format(self.adminHasPlexPass))
def onAccountResponse(self, request, response, context):
oldId = self.ID
if response.isSuccess():
data = response.getBodyXml()
# The user is signed in
self.isSignedIn = True
self.isOffline = False
self.ID = data.attrib.get('id')
self.title = data.attrib.get('title')
self.username = data.attrib.get('username')
self.email = data.attrib.get('email')
self.thumb = data.attrib.get('thumb')
self.authToken = data.attrib.get('authenticationToken')
self.isPlexPass = (data.find('subscription') is not None and data.find('subscription').attrib.get('active') == '1')
self.isManaged = data.attrib.get('restricted') == '1'
self.isSecure = data.attrib.get('secure') == '1'
self.hasQueue = bool(data.attrib.get('queueEmail'))
# PIN
if data.attrib.get('pin'):
self.pin = data.attrib.get('pin')
else:
self.pin = None
self.isProtected = bool(self.pin)
# update the list of users in the home
self.updateHomeUsers()
# set admin attribute for the user
self.isAdmin = False
if self.homeUsers:
for user in self.homeUsers:
if self.ID == user.id:
self.isAdmin = str(user.admin) == "1"
break
if self.isAdmin and self.isPlexPass:
self.adminHasPlexPass = True
# consider a single, unprotected user authenticated
if not self.isAuthenticated and not self.isProtected and len(self.homeUsers) <= 1:
self.isAuthenticated = True
self.logState()
self.saveState()
util.MANAGER.publish()
plexapp.refreshResources()
elif response.getStatus() >= 400 and response.getStatus() < 500:
# The user is specifically unauthorized, clear everything
util.WARN_LOG("Sign Out: User is unauthorized")
self.signOut(True)
else:
# Unexpected error, keep using whatever we read from the registry
util.WARN_LOG("Unexpected response from plex.tv ({0}), switching to OFFLINE mode".format(response.getStatus()))
self.logState()
self.isOffline = True
# consider a single, unprotected user authenticated
if not self.isAuthenticated and not self.isProtected:
self.isAuthenticated = True
util.APP.clearInitializer("myplex")
# Logger().UpdateSyslogHeader() # TODO: ------------------------------------------------------------------------------------------------------IMPLEMENT
if oldId != self.ID or self.switchUser:
self.switchUser = None
util.APP.trigger("change:user", account=self, reallyChanged=oldId != self.ID)
util.APP.trigger("account:response")
def signOut(self, expired=False):
# Strings
self.ID = None
self.title = None
self.username = None
self.email = None
self.authToken = None
self.pin = None
self.lastHomeUserUpdate = None
# Booleans
self.isSignedIn = False
self.isPlexPass = False
self.adminHasPlexPass = False
self.isManaged = False
self.isSecure = False
self.isExpired = expired
# Clear the saved resources
util.INTERFACE.clearRegistry("mpaResources", "xml_cache")
# Remove all saved servers
plexapp.SERVERMANAGER.clearServers()
# Enable the welcome screen again
util.INTERFACE.setPreference("show_welcome", True)
util.APP.trigger("change:user", account=self, reallyChanged=True)
self.saveState()
def hasPlexPass(self):
return self.isPlexPass or self.adminHasPlexPass
def validateToken(self, token, switchUser=False):
self.authToken = token
self.switchUser = switchUser
request = myplexrequest.MyPlexRequest("/users/sign_in.xml")
context = request.createRequestContext("sign_in", callback.Callable(self.onAccountResponse))
if self.isOffline:
context.timeout = self.isOffline and asyncadapter.AsyncTimeout(1).setConnectTimeout(1)
util.APP.startRequest(request, context, {})
def refreshAccount(self):
if not self.authToken:
return
self.validateToken(self.authToken, False)
def updateHomeUsers(self):
# Ignore request and clear any home users we are not signed in
if not self.isSignedIn:
self.homeUsers = []
if self.isOffline:
self.homeUsers.append(MyPlexAccount())
self.lastHomeUserUpdate = None
return
# Cache home users for 60 seconds, mainly to stop back to back tests
epoch = time.time()
if not self.lastHomeUserUpdate:
self.lastHomeUserUpdate = epoch
elif self.lastHomeUserUpdate + 60 > epoch:
util.DEBUG_LOG("Skipping home user update (updated {0} seconds ago)".format(epoch - self.lastHomeUserUpdate))
return
req = myplexrequest.MyPlexRequest("/api/home/users")
xml = req.getToStringWithTimeout()
data = ElementTree.fromstring(xml)
if data.attrib.get('size') and data.find('User') is not None:
self.homeUsers = []
for user in data.findall('User'):
homeUser = HomeUser(user.attrib)
homeUser.isAdmin = homeUser.admin == "1"
homeUser.isManaged = homeUser.restricted == "1"
homeUser.isProtected = homeUser.protected == "1"
self.homeUsers.append(homeUser)
self.lastHomeUserUpdate = epoch
util.LOG("home users: {0}".format(self.homeUsers))
def switchHomeUser(self, userId, pin=''):
if userId == self.ID and self.isAuthenticated:
return True
# Offline support
if self.isOffline:
hashed = 'NONE'
if pin and self.authToken:
hashed = hashlib.sha256(pin + self.authToken).digest()
if not self.isProtected or self.isAuthenticated or hashed == (self.pin or ""):
util.DEBUG_LOG("OFFLINE access granted")
self.isAuthenticated = True
self.validateToken(self.authToken, True)
return True
else:
# build path and post to myplex to swith the user
path = '/api/home/users/{0}/switch'.format(userId)
req = myplexrequest.MyPlexRequest(path)
xml = req.postToStringWithTimeout({'pin': pin})
data = ElementTree.fromstring(xml)
if data.attrib.get('authenticationToken'):
self.isAuthenticated = True
# validate the token (trigger change:user) on user change or channel startup
if userId != self.ID or not locks.LOCKS.isLocked("idleLock"):
self.validateToken(data.attrib.get('authenticationToken'), True)
return True
return False
def isActive(self):
return self.isSignedIn or self.isOffline
ACCOUNT = MyPlexAccount()