forked from xbmc/repo-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthorizers.py
More file actions
158 lines (120 loc) · 5.18 KB
/
authorizers.py
File metadata and controls
158 lines (120 loc) · 5.18 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
import xbmcgui
import xbmcvfs
import json
import pyqrcode
import time
import resources.lib.tinyurl as tinyurl
import resources.lib.utils as utils
import datetime
# don't die on import error yet, these might not even get used
try:
from dropbox import dropbox
from dropbox import oauth
except ImportError:
pass
# fix for datetime.strptime bug https://kodi.wiki/view/Python_Problems#datetime.strptime
def patch_strptime(date_string, format):
return datetime.datetime(*(time.strptime(date_string, format)[:6]))
class QRCode(xbmcgui.WindowXMLDialog):
def __init__(self, *args, **kwargs):
self.image = kwargs["image"]
self.text = kwargs["text"]
self.url = kwargs['url']
def onInit(self):
self.imagecontrol = 501
self.textbox1 = 502
self.textbox2 = 504
self.okbutton = 503
self.showdialog()
def showdialog(self):
self.getControl(self.imagecontrol).setImage(self.image)
self.getControl(self.textbox1).setText(self.text)
self.getControl(self.textbox2).setText(self.url)
self.setFocus(self.getControl(self.okbutton))
def onClick(self, controlId):
if (controlId == self.okbutton):
self.close()
class DropboxAuthorizer:
TOKEN_FILE = "tokens.json"
APP_KEY = ""
APP_SECRET = ""
def __init__(self):
self.APP_KEY = utils.getSettingStringStripped('dropbox_key')
self.APP_SECRET = utils.getSettingStringStripped('dropbox_secret')
def setup(self):
result = True
if(self.APP_KEY == '' and self.APP_SECRET == ''):
# we can't go any farther, need these for sure
xbmcgui.Dialog().ok(utils.getString(30010), '%s %s\n%s' % (utils.getString(30027), utils.getString(30058), utils.getString(30059)))
result = False
return result
def isAuthorized(self):
user_token = self._getToken()
return 'access_token' in user_token
def authorize(self):
result = True
if(not self.setup()):
return False
if(self.isAuthorized()):
# delete the token to start over
self._deleteToken()
# copied flow from http://dropbox-sdk-python.readthedocs.io/en/latest/moduledoc.html#dropbox.oauth.DropboxOAuth2FlowNoRedirect
flow = oauth.DropboxOAuth2FlowNoRedirect(consumer_key=self.APP_KEY, consumer_secret=self.APP_SECRET, token_access_type="offline")
url = flow.start()
# print url in log
utils.log("Authorize URL: " + url)
# create a QR Code
shortUrl = str(tinyurl.shorten(url), 'utf-8')
imageFile = xbmcvfs.translatePath(utils.data_dir() + '/qrcode.png')
qrIMG = pyqrcode.create(shortUrl)
qrIMG.png(imageFile, scale=10)
# show the dialog prompt to authorize
qr = QRCode("script-backup-qrcode.xml", utils.addon_dir(), "default", image=imageFile, text=utils.getString(30056), url=shortUrl)
qr.doModal()
# cleanup
del qr
xbmcvfs.delete(imageFile)
# get the auth code
code = xbmcgui.Dialog().input(utils.getString(30027) + ' ' + utils.getString(30103))
# if user authorized this will work
try:
user_token = flow.finish(code)
self._setToken(user_token)
except Exception as e:
utils.log("Error: %s" % (e,))
result = False
return result
# return the DropboxClient, or None if can't be created
def getClient(self):
result = None
user_token = self._getToken()
if(user_token != ''):
# create the client
result = dropbox.Dropbox(oauth2_access_token=user_token['access_token'], oauth2_refresh_token=user_token['refresh_token'],
oauth2_access_token_expiration=user_token['expiration'], app_key=self.APP_KEY, app_secret=self.APP_SECRET)
try:
result.users_get_current_account()
except:
# this didn't work, delete the token file
self._deleteToken()
result = None
return result
def _setToken(self, token):
# write the token files
with open(xbmcvfs.translatePath(utils.data_dir() + self.TOKEN_FILE), 'w') as token_file:
token_file.write(json.dumps({"access_token": token.access_token, "refresh_token": token.refresh_token, "expiration": str(token.expires_at)}))
def _getToken(self):
result = {}
# get token, if it exists
if(xbmcvfs.exists(xbmcvfs.translatePath(utils.data_dir() + self.TOKEN_FILE))):
token = ""
with open(xbmcvfs.translatePath(utils.data_dir() + self.TOKEN_FILE), 'r') as token_file:
token = token_file.read()
if(token.strip() != ""):
result = json.loads(token)
# convert expiration back to a datetime object
result['expiration'] = patch_strptime(result['expiration'], "%Y-%m-%d %H:%M:%S.%f")
return result
def _deleteToken(self):
if(xbmcvfs.exists(xbmcvfs.translatePath(utils.data_dir() + self.TOKEN_FILE))):
xbmcvfs.delete(xbmcvfs.translatePath(utils.data_dir() + self.TOKEN_FILE))