Created
February 20, 2016 17:03
-
-
Save anonymous/f1d60543741aa56892c2 to your computer and use it in GitHub Desktop.
Movie Diary.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import requests | |
import json | |
import appex | |
import dialogs | |
import re | |
import datetime | |
import keychain | |
import console | |
class NoResultsError (Exception): pass | |
class NoMoviePickError (Exception): pass | |
class NoRatingError (Exception): pass | |
class ConnectionError (Exception): pass | |
class MissingApiKeyError (Exception): pass | |
def journal(data): | |
airtable_api = keychain.get_password('Airtable', 'API') | |
if airtable_api == None: | |
airtable_api = console.input_alert('Insert your Airtable API key') | |
if airtable_api == None: | |
raise MissingApiKeyError() | |
else: | |
keychain.set_password('Airtable', 'API', airtable_api) | |
airtable_db = keychain.get_password('Airtable', 'Movie Diary') | |
if airtable_db == None: | |
airtable_db = console.input_alert('Insert your Airtable database ID') | |
if airtable_db == None: | |
raise MissingApiKeyError() | |
else: | |
keychain.set_password('Airtable', 'Movie Diary', airtable_db) | |
headers = { | |
'Authorization': 'Bearer ' + airtable_api, | |
'Content-type': 'application/json' | |
} | |
r = requests.post('https://api.airtable.com/v0/{0}/Entries'.format(airtable_db), headers=headers, data=json.dumps({'fields': data})) | |
if r.status_code == 200: | |
console.hud_alert('Added movie', 'success') | |
else: | |
raise ConnectionError() | |
def getyear(d, raw=False): | |
if d is None or d == '': | |
return '' | |
elif raw: | |
return str(d[:4]) | |
else: | |
return ' ({0})'.format(d[:4]) | |
def getdirectors(url, params): | |
r = requests.get(url + '/credits', params=params) | |
if r.status_code == 200: | |
j = json.loads(r.text) | |
return ', '.join([c['name'] for c in j['crew'] if c['job'] == 'Director']) | |
else: | |
raise ConnectionError() | |
def getmovie(url, params): | |
r = requests.get(url, params=params) | |
if r.status_code == 200: | |
j = json.loads(r.text) | |
fields = { | |
'Overview': j['overview'], | |
'Title': j['title'], | |
'Year': getyear(j['release_date'], True), | |
#'Date': dialogs.date_dialog().isoformat(), | |
'Date': datetime.datetime.now().date().isoformat(), | |
'Directors': getdirectors(url, params), | |
'Rating': dialogs.list_dialog("Rate '{0}'".format(j['title']), ['★★★★★','★★★★½','★★★★','★★★½','★★★','★★½','★★','★½','★','½']) | |
} | |
if j['poster_path'] is not None: | |
fields['Poster'] = [{'url': 'https://image.tmdb.org/t/p/original' + j['poster_path']}] | |
if fields['Rating'] is not None: | |
return journal(fields) | |
else: | |
raise NoRatingError() | |
else: | |
raise ConnectionError() | |
def main(): | |
moviedb_api = keychain.get_password('MovieDB', 'API') | |
if moviedb_api == None: | |
moviedb_api = console.input_alert('Insert your TMDB API key', '', '84cef43ccf02b1ba6093c9694ed671c9') | |
if moviedb_api == None: | |
raise MissingApiKeyError() | |
else: | |
keychain.set_password('MovieDB', 'API', moviedb_api) | |
try: | |
url_match = re.match(r'^https?://(?:www\.)?imdb\.com/title/(tt\d+)/?', appex.get_url()) | |
params = { | |
'api_key': moviedb_api, | |
'external_source': 'imdb_id' | |
} | |
return getmovie('https://api.themoviedb.org/3/movie/' + url_match.group(1), params) | |
except TypeError: | |
params = { | |
'api_key': moviedb_api, | |
'query': console.input_alert('Search for movie') | |
} | |
r = requests.post('https://api.themoviedb.org/3/search/movie', params=params) | |
try: | |
if r.status_code == 200: | |
j = json.loads(r.text) | |
if j['total_results'] > 1: | |
results_map = {e['title'] + getyear(e['release_date']) : e for e in j['results']} | |
movie_pick = dialogs.list_dialog('Pick a movie', [e['title'] + getyear(e['release_date']) for e in j['results']]) | |
if movie_pick is not None: | |
return getmovie('https://api.themoviedb.org/3/movie/' + str(results_map[movie_pick]['id']), {'api_key': moviedb_api}) | |
else: | |
raise NoMoviePickError() | |
elif j['total_results'] == 1: | |
return getmovie('https://api.themoviedb.org/3/movie/' + str(j['results'][0]['id']), {'api_key': moviedb_api}) | |
else: | |
raise NoResultsError() | |
else: | |
raise ConnectionError() | |
except NoResultsError: | |
console.alert('No Results', 'Couldn\'t find any movie matching your query. Try again with different terms.') | |
except ConnectionError: | |
console.alert('Failed to connect', 'Something went wrong in the request. Try again in a couple of minutes.') | |
except NoMoviePickError: | |
console.alert('No movie selected', 'You gotta pick a movie for the script to work.') | |
except NoRatingError: | |
console.alert('No rating', 'You gotta rate the movie for the script to work.') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment