forked from linaspurinis/trakt.plex.scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrakt.py
More file actions
executable file
·171 lines (149 loc) · 5.69 KB
/
Copy pathtrakt.py
File metadata and controls
executable file
·171 lines (149 loc) · 5.69 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
#!/usr/bin/env python
# coding=utf-8
from __future__ import print_function
import json
import os
import re
import sys
import time
import requests
try:
import config
except ImportError:
print(('Please see config.py.example, update the '
'values and rename it to config.py'))
sys.exit(1)
APIURL = 'https://api.trakt.tv'
HERE = os.path.abspath(os.path.dirname(__file__))
CACHEFILE = os.path.join(HERE, '.local.db')
localdb = {}
if os.path.exists(CACHEFILE):
with open(CACHEFILE, 'r') as fp:
localdb = json.load(fp)
def get_oauth_headers():
headers = {
'Content-type': 'application/json',
'trakt-api-key': config.CLIENT_ID,
'trakt-api-version': '2',
}
access_token_expires = float(localdb.get('access_token_expires', 0))
access_token = localdb.get('access_token')
refresh_token = localdb.get('refresh_token')
if access_token_expires > time.time() and access_token:
headers['Authorization'] = 'Bearer %s' % access_token
else:
print('Acquiring access_token, refresh_token={0}...'.format(
refresh_token
))
if refresh_token:
req = requests.post(
'{0}/oauth/token'.format(APIURL),
headers=headers,
json={
'refresh_token': refresh_token,
'client_id': config.CLIENT_ID,
'client_secret': config.CLIENT_SECRET,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
'grant_type': 'refresh_token',
})
res = req.json()
db_set('access_token', res['access_token'])
db_set('refresh_token', res['refresh_token'])
db_set('access_token_expires', time.time() + res['expires_in'] - (14 * 24 * 3600))
print('New access_token acquired!')
else:
print('No refresh_token, manual action needed...')
req = requests.post(
'{0}/oauth/device/code'.format(APIURL),
json={
'client_id': config.CLIENT_ID,
}
)
assert req.ok, (req, req.content)
data = req.json()
start_time = time.time()
print('Go to {verification_url} and enter code {user_code}'.format(
verification_url=data['verification_url'],
user_code=data['user_code'],
))
interval = data['interval']
while 1:
if start_time + data['expires_in'] < time.time():
print('Too late, you need to start from beginning :(')
sys.exit(1)
time.sleep(interval)
req = requests.post(
'{0}/oauth/device/token'.format(APIURL),
json={
'client_id': config.CLIENT_ID,
'client_secret': config.CLIENT_SECRET,
'code': data['device_code'],
}
)
if req.status_code == 200:
res = req.json()
print('New tokens acquired!')
db_set('access_token', res['access_token'])
db_set('refresh_token', res['refresh_token'])
db_set('access_token_expires', time.time() + res['expires_in'] - (14 * 24 * 3600))
break
elif req.status_code == 400:
print('Pending - waiting for the user to authorize your app')
elif req.status_code == 404:
print('Not Found - invalid device_code')
return
elif req.status_code == 409:
print('Already Used - user already approved this code')
return
elif req.status_code == 410:
print('Expired - the tokens have expired, restart the process')
return
elif req.status_code == 418:
print('Denied - user explicitly denied this code')
return
elif req.status_code == 429:
print('Slow Down - your app is polling too quickly')
time.sleep(interval)
headers['Authorization'] = 'Bearer %s' % res['access_token']
return headers
def get_oauth_request(path, *args, **kwargs):
headers = get_oauth_headers()
if 'headers' in kwargs:
headers.update(kwargs.pop('headers'))
req = requests.get(
'{0}/{1}'.format(APIURL, path), headers=headers, **kwargs
)
assert req.ok, (req, req.content)
return req.json()
def post_oauth_request(path, data, *args, **kwargs):
req = requests.post(
'{0}/{1}'.format(APIURL, path),
json=data, headers=get_oauth_headers(), **kwargs
)
assert req.ok, (req, req.content)
return req
def put_oauth_request(path, data, *args, **kwargs):
req = requests.put(
'{0}/{1}'.format(APIURL, path),
json=data, headers=get_oauth_headers(), **kwargs
)
assert req.ok, (req, req.content)
return req
def get_list_id(name):
key = 'list-id:{0}'.format(name)
if key in localdb:
return localdb[key]
req = get_oauth_request('users/me/lists')
existing_lists = [x['name'] for x in req]
if name not in existing_lists:
post_oauth_request('users/me/lists', data={
'name': name,
})
time.sleep(0.5)
req = get_oauth_request('users/me/lists')
res = [x for x in req if x['name'] == name]
if not res:
raise Exception('Could not find the list "{0}" :('.format(name))
list_id = res[0]['ids']['trakt']
db_set(key, list_id)
return list_id