Skip to content

Instantly share code, notes, and snippets.

@fopina
Created June 23, 2015 16:35
Show Gist options
  • Save fopina/8f7f84a759f47a2cf0c3 to your computer and use it in GitHub Desktop.
Save fopina/8f7f84a759f47a2cf0c3 to your computer and use it in GitHub Desktop.
Trakt.tv Bulk AddToHistory
from urllib2 import Request, urlopen
import json
import sys
URL = 'https://api-v2launch.trakt.tv'
# create your own app
API_KEY = ''
SECRET = ''
PIN_URL = 'https://trakt.tv/pin/????'
def add_movies_to_history(token, imdb_list):
movies = []
for i in imdb_list:
movies.append(
{
# 'watched_at': '2014-09-01T09:10:11.000Z',
'ids': {
'imdb': i,
}
}
)
values = json.dumps({
'movies': movies
})
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer %s' % token,
'trakt-api-version': '2',
'trakt-api-key': API_KEY
}
request = Request('https://api-v2launch.trakt.tv/sync/history', data=values, headers=headers)
response_body = urlopen(request).read()
return json.loads(response_body)
def exchange_token(pin):
values = json.dumps({
'code': pin,
'client_id': API_KEY,
'client_secret': SECRET,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
'grant_type': 'authorization_code',
})
headers = {
'Content-Type': 'application/json'
}
request = Request('https://api-v2launch.trakt.tv/oauth/token', data=values, headers=headers)
response_body = json.loads(urlopen(request).read())
return response_body['access_token']
def main():
if len(sys.argv) < 2:
print 'Usage: %s [filename]' % sys.argv[0]
sys.exit(1)
token = raw_input('Access token (leave empty to generate new): ')
if not token:
pin = raw_input('Visit %s and enter your PIN: ' % PIN_URL)
token = exchange_token(pin)
print 'Access Token: %s\n' % token
list = map(str.strip, open(sys.argv[1]))
resp = add_movies_to_history(token, list)
print '''
Out of %d movies:
- %d added
- %d not found
''' % (len(list), resp['added']['movies'], len(resp['not_found']['movies']))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment