#NEWLINE# def _create_api( self ) : #NEWLINE# #INDENT# "Creates a new CrunchyrollAPI object, initiates it's session and\n        tries to authenticate it either by using saved credentials or the\n        user's username and password.\n        " #NEWLINE# if self . options . get ( 'purge_credentials' ) : #NEWLINE# #INDENT# self . cache . set ( 'session_id' , None , 0 ) #NEWLINE# self . cache . set ( 'auth' , None , 0 ) #NEWLINE# #UNINDENT# current_time = datetime . datetime . utcnow ( ) #NEWLINE# device_id = self . _get_device_id ( ) #NEWLINE# locale = self . options . get ( 'locale' ) #NEWLINE# api = CrunchyrollAPI ( self . cache . get ( 'session_id' ) , self . cache . get ( 'auth' ) , locale ) #NEWLINE# self . logger . debug ( 'Creating session' ) #NEWLINE# try : #NEWLINE# #INDENT# api . session_id = api . start_session ( device_id , schema = _session_schema ) #NEWLINE# #UNINDENT# except CrunchyrollAPIError as err : #NEWLINE# #INDENT# if ( err . code == 'bad_session' ) : #NEWLINE# #INDENT# self . logger . debug ( 'Current session has expired, creating a new one' ) #NEWLINE# api = CrunchyrollAPI ( locale = locale ) #NEWLINE# api . session_id = api . start_session ( expires , schema = _session_schema ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# raise err #NEWLINE# #UNINDENT# #UNINDENT# self . cache . set ( 'session_id' , api . session_id , ( ( 4 * 60 ) * 60 ) ) #NEWLINE# self . logger . debug ( 'Session created' ) #NEWLINE# if api . auth : #NEWLINE# #INDENT# self . logger . debug ( 'Using saved credentials' ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if self . options . get ( 'username' ) : #NEWLINE# #INDENT# try : #NEWLINE# #INDENT# self . logger . info ( 'Attempting to login using username and password' ) #NEWLINE# login = api . login ( self . options . get ( 'username' ) , self . options . get ( 'password' ) , schema = _login_schema ) #NEWLINE# api . auth = login [ 'auth' ] #NEWLINE# self . logger . info ( "Successfully logged in as '{0}'" , login [ 'user' ] [ 'username' ] ) #NEWLINE# expires = ( login [ 'expires' ] - current_time ) . total_seconds ( ) #NEWLINE# self . cache . set ( 'auth' , login [ 'auth' ] , expires ) #NEWLINE# #UNINDENT# except CrunchyrollAPIError as err : #NEWLINE# #INDENT# raise PluginError ( 'Authentication error: {0}' . format ( err . msg ) ) #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# self . logger . warning ( "No authentication provided, you won't be able to access premium restricted content" ) #NEWLINE# #UNINDENT# #UNINDENT# return api