idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
59,300
def add_service ( self , zeroconf , service_type , name ) : self . lock . acquire ( ) try : self . _internal_add ( zeroconf , service_type , name ) finally : self . lock . release ( )
Handle callback from zeroconf when a service has been discovered .
59,301
def add_hs_service ( self , info , address ) : if self . protocol and self . protocol != PROTOCOL_DMAP : return name = info . properties [ b'Name' ] . decode ( 'utf-8' ) hsgid = info . properties [ b'hG' ] . decode ( 'utf-8' ) self . _handle_service ( address , name , conf . DmapService ( hsgid , port = info . port ) )
Add a new device to discovered list .
59,302
def add_non_hs_service ( self , info , address ) : if self . protocol and self . protocol != PROTOCOL_DMAP : return name = info . properties [ b'CtlN' ] . decode ( 'utf-8' ) self . _handle_service ( address , name , conf . DmapService ( None , port = info . port ) )
Add a new device without Home Sharing to discovered list .
59,303
def add_mrp_service ( self , info , address ) : if self . protocol and self . protocol != PROTOCOL_MRP : return name = info . properties [ b'Name' ] . decode ( 'utf-8' ) self . _handle_service ( address , name , conf . MrpService ( info . port ) )
Add a new MediaRemoteProtocol device to discovered list .
59,304
def add_airplay_service ( self , info , address ) : name = info . name . replace ( '._airplay._tcp.local.' , '' ) self . _handle_service ( address , name , conf . AirPlayService ( info . port ) )
Add a new AirPlay device to discovered list .
59,305
def usable_service ( self ) : services = self . _services for protocol in self . _supported_protocols : if protocol in services and services [ protocol ] . is_usable ( ) : return services [ protocol ] return None
Return a usable service or None if there is none .
59,306
def superseeded_by ( self , other_service ) : if not other_service or other_service . __class__ != self . __class__ or other_service . protocol != self . protocol or other_service . port != self . port : return False return not self . device_credentials and other_service . device_credentials
Return True if input service has login id and this has not .
59,307
async def print_what_is_playing ( loop ) : print ( 'Discovering devices on network...' ) atvs = await pyatv . scan_for_apple_tvs ( loop , timeout = 5 ) if not atvs : print ( 'no device found' , file = sys . stderr ) return print ( 'Connecting to {0}' . format ( atvs [ 0 ] . address ) ) atv = pyatv . connect_to_apple_tv ( atvs [ 0 ] , loop ) try : playing = await atv . metadata . playing ( ) print ( 'Currently playing:' ) print ( playing ) finally : await atv . logout ( )
Find a device and print what is playing .
59,308
async def start ( self , ** kwargs ) : zeroconf = kwargs [ 'zeroconf' ] self . _name = kwargs [ 'name' ] self . _pairing_guid = kwargs . get ( 'pairing_guid' , None ) or self . _generate_random_guid ( ) self . _web_server = web . Server ( self . handle_request , loop = self . _loop ) self . _server = await self . _loop . create_server ( self . _web_server , '0.0.0.0' ) allocated_port = self . _server . sockets [ 0 ] . getsockname ( ) [ 1 ] _LOGGER . debug ( 'Started pairing web server at port %d' , allocated_port ) self . _setup_zeroconf ( zeroconf , allocated_port )
Start the pairing server and publish service .
59,309
async def stop ( self , ** kwargs ) : _LOGGER . debug ( 'Shutting down pairing server' ) if self . _web_server is not None : await self . _web_server . shutdown ( ) self . _server . close ( ) if self . _server is not None : await self . _server . wait_closed ( )
Stop pairing server and unpublish service .
59,310
async def handle_request ( self , request ) : service_name = request . rel_url . query [ 'servicename' ] received_code = request . rel_url . query [ 'pairingcode' ] . lower ( ) _LOGGER . info ( 'Got pairing request from %s with code %s' , service_name , received_code ) if self . _verify_pin ( received_code ) : cmpg = tags . uint64_tag ( 'cmpg' , int ( self . _pairing_guid , 16 ) ) cmnm = tags . string_tag ( 'cmnm' , self . _name ) cmty = tags . string_tag ( 'cmty' , 'iPhone' ) response = tags . container_tag ( 'cmpa' , cmpg + cmnm + cmty ) self . _has_paired = True return web . Response ( body = response ) return web . Response ( status = 500 )
Respond to request if PIN is correct .
59,311
def log_binary ( logger , message , ** kwargs ) : if logger . isEnabledFor ( logging . DEBUG ) : output = ( '{0}={1}' . format ( k , binascii . hexlify ( bytearray ( v ) ) . decode ( ) ) for k , v in sorted ( kwargs . items ( ) ) ) logger . debug ( '%s (%s)' , message , ', ' . join ( output ) )
Log binary data if debug is enabled .
59,312
def _extract_command_with_args ( cmd ) : def _isint ( value ) : try : int ( value ) return True except ValueError : return False equal_sign = cmd . find ( '=' ) if equal_sign == - 1 : return cmd , [ ] command = cmd [ 0 : equal_sign ] args = cmd [ equal_sign + 1 : ] . split ( ',' ) converted = [ x if not _isint ( x ) else int ( x ) for x in args ] return command , converted
Parse input command with arguments .
59,313
def main ( ) : async def _run_application ( loop ) : try : return await cli_handler ( loop ) except KeyboardInterrupt : pass except SystemExit : pass except : import traceback traceback . print_exc ( file = sys . stderr ) sys . stderr . writelines ( '\n>>> An error occurred, full stack trace above\n' ) return 1 try : loop = asyncio . get_event_loop ( ) return loop . run_until_complete ( _run_application ( loop ) ) except KeyboardInterrupt : pass return 1
Start the asyncio event loop and runs the application .
59,314
async def commands ( self ) : _print_commands ( 'Remote control' , interface . RemoteControl ) _print_commands ( 'Metadata' , interface . Metadata ) _print_commands ( 'Playing' , interface . Playing ) _print_commands ( 'AirPlay' , interface . AirPlay ) _print_commands ( 'Device' , DeviceCommands ) _print_commands ( 'Global' , self . __class__ ) return 0
Print a list with available commands .
59,315
async def help ( self ) : if len ( self . args . command ) != 2 : print ( 'Which command do you want help with?' , file = sys . stderr ) return 1 iface = [ interface . RemoteControl , interface . Metadata , interface . Playing , interface . AirPlay , self . __class__ , DeviceCommands ] for cmd in iface : for key , value in cmd . __dict__ . items ( ) : if key . startswith ( '_' ) or key != self . args . command [ 1 ] : continue if inspect . isfunction ( value ) : signature = inspect . signature ( value ) else : signature = ' (property)' print ( 'COMMAND:\n>> {0}{1}\n\nHELP:\n{2}' . format ( key , signature , inspect . getdoc ( value ) ) ) return 0
Print help text for a command .
59,316
async def scan ( self ) : atvs = await pyatv . scan_for_apple_tvs ( self . loop , timeout = self . args . scan_timeout , only_usable = False ) _print_found_apple_tvs ( atvs ) return 0
Scan for Apple TVs on the network .
59,317
async def cli ( self ) : print ( 'Enter commands and press enter' ) print ( 'Type help for help and exit to quit' ) while True : command = await _read_input ( self . loop , 'pyatv> ' ) if command . lower ( ) == 'exit' : break elif command == 'cli' : print ( 'Command not availble here' ) continue await _handle_device_command ( self . args , command , self . atv , self . loop )
Enter commands in a simple CLI .
59,318
async def artwork_save ( self ) : artwork = await self . atv . metadata . artwork ( ) if artwork is not None : with open ( 'artwork.png' , 'wb' ) as file : file . write ( artwork ) else : print ( 'No artwork is currently available.' ) return 1 return 0
Download artwork and save it to artwork . png .
59,319
async def push_updates ( self ) : print ( 'Press ENTER to stop' ) self . atv . push_updater . start ( ) await self . atv . login ( ) await self . loop . run_in_executor ( None , sys . stdin . readline ) self . atv . push_updater . stop ( ) return 0
Listen for push updates .
59,320
async def auth ( self ) : credentials = await self . atv . airplay . generate_credentials ( ) await self . atv . airplay . load_credentials ( credentials ) try : await self . atv . airplay . start_authentication ( ) pin = await _read_input ( self . loop , 'Enter PIN on screen: ' ) await self . atv . airplay . finish_authentication ( pin ) print ( 'You may now use these credentials:' ) print ( credentials ) return 0 except exceptions . DeviceAuthenticationError : logging . exception ( 'Failed to authenticate - invalid PIN?' ) return 1
Perform AirPlay device authentication .
59,321
async def pair ( self ) : protocol = self . atv . service . protocol if protocol == const . PROTOCOL_DMAP : await self . atv . pairing . start ( zeroconf = Zeroconf ( ) , name = self . args . remote_name , pairing_guid = self . args . pairing_guid ) elif protocol == const . PROTOCOL_MRP : await self . atv . pairing . start ( ) if self . atv . pairing . device_provides_pin : pin = await _read_input ( self . loop , 'Enter PIN on screen: ' ) self . atv . pairing . pin ( pin ) else : self . atv . pairing . pin ( self . args . pin_code ) print ( 'Use {0} to pair with "{1}" (press ENTER to stop)' . format ( self . args . pin_code , self . args . remote_name ) ) if self . args . pin_code is None : print ( 'Use any pin to pair with "{}" (press ENTER to stop)' . format ( self . args . remote_name ) ) else : print ( 'Use pin {} to pair with "{}" (press ENTER to stop)' . format ( self . args . pin_code , self . args . remote_name ) ) await self . loop . run_in_executor ( None , sys . stdin . readline ) await self . atv . pairing . stop ( ) if self . atv . pairing . has_paired : print ( 'Pairing seems to have succeeded, yey!' ) print ( 'You may now use these credentials: {0}' . format ( self . atv . pairing . credentials ) ) else : print ( 'Pairing failed!' ) return 1 return 0
Pair pyatv as a remote control with an Apple TV .
59,322
def media_kind ( kind ) : if kind in [ 1 ] : return const . MEDIA_TYPE_UNKNOWN if kind in [ 3 , 7 , 11 , 12 , 13 , 18 , 32 ] : return const . MEDIA_TYPE_VIDEO if kind in [ 2 , 4 , 10 , 14 , 17 , 21 , 36 ] : return const . MEDIA_TYPE_MUSIC if kind in [ 8 , 64 ] : return const . MEDIA_TYPE_TV raise exceptions . UnknownMediaKind ( 'Unknown media kind: ' + str ( kind ) )
Convert iTunes media kind to API representation .
59,323
def media_type_str ( mediatype ) : if mediatype == const . MEDIA_TYPE_UNKNOWN : return 'Unknown' if mediatype == const . MEDIA_TYPE_VIDEO : return 'Video' if mediatype == const . MEDIA_TYPE_MUSIC : return 'Music' if mediatype == const . MEDIA_TYPE_TV : return 'TV' return 'Unsupported'
Convert internal API media type to string .
59,324
def playstate ( state ) : if state is None : return const . PLAY_STATE_NO_MEDIA if state == 0 : return const . PLAY_STATE_IDLE if state == 1 : return const . PLAY_STATE_LOADING if state == 3 : return const . PLAY_STATE_PAUSED if state == 4 : return const . PLAY_STATE_PLAYING if state == 5 : return const . PLAY_STATE_FAST_FORWARD if state == 6 : return const . PLAY_STATE_FAST_BACKWARD raise exceptions . UnknownPlayState ( 'Unknown playstate: ' + str ( state ) )
Convert iTunes playstate to API representation .
59,325
def playstate_str ( state ) : if state == const . PLAY_STATE_NO_MEDIA : return 'No media' if state == const . PLAY_STATE_IDLE : return 'Idle' if state == const . PLAY_STATE_LOADING : return 'Loading' if state == const . PLAY_STATE_PAUSED : return 'Paused' if state == const . PLAY_STATE_PLAYING : return 'Playing' if state == const . PLAY_STATE_FAST_FORWARD : return 'Fast forward' if state == const . PLAY_STATE_FAST_BACKWARD : return 'Fast backward' return 'Unsupported'
Convert internal API playstate to string .
59,326
def repeat_str ( state ) : if state == const . REPEAT_STATE_OFF : return 'Off' if state == const . REPEAT_STATE_TRACK : return 'Track' if state == const . REPEAT_STATE_ALL : return 'All' return 'Unsupported'
Convert internal API repeat state to string .
59,327
def protocol_str ( protocol ) : if protocol == const . PROTOCOL_MRP : return 'MRP' if protocol == const . PROTOCOL_DMAP : return 'DMAP' if protocol == const . PROTOCOL_AIRPLAY : return 'AirPlay' return 'Unknown'
Convert internal API protocol to string .
59,328
def first ( dmap_data , * path ) : if not ( path and isinstance ( dmap_data , list ) ) : return dmap_data for key in dmap_data : if path [ 0 ] in key : return first ( key [ path [ 0 ] ] , * path [ 1 : ] ) return None
Look up a value given a path in some parsed DMAP data .
59,329
def pprint ( data , tag_lookup , indent = 0 ) : output = '' if isinstance ( data , dict ) : for key , value in data . items ( ) : tag = tag_lookup ( key ) if isinstance ( value , ( dict , list ) ) and tag . type is not read_bplist : output += '{0}{1}: {2}\n' . format ( indent * ' ' , key , tag ) output += pprint ( value , tag_lookup , indent + 2 ) else : output += '{0}{1}: {2} {3}\n' . format ( indent * ' ' , key , str ( value ) , tag ) elif isinstance ( data , list ) : for elem in data : output += pprint ( elem , tag_lookup , indent ) else : raise exceptions . InvalidDmapDataError ( 'invalid dmap data: ' + str ( data ) ) return output
Return a pretty formatted string of parsed DMAP data .
59,330
def retrieve_commands ( obj ) : commands = { } for func in obj . __dict__ : if not inspect . isfunction ( obj . __dict__ [ func ] ) and not isinstance ( obj . __dict__ [ func ] , property ) : continue if func . startswith ( '_' ) : continue commands [ func ] = _get_first_sentence_in_pydoc ( obj . __dict__ [ func ] ) return commands
Retrieve all commands and help texts from an API object .
59,331
def hash ( self ) : base = '{0}{1}{2}{3}' . format ( self . title , self . artist , self . album , self . total_time ) return hashlib . sha256 ( base . encode ( 'utf-8' ) ) . hexdigest ( )
Create a unique hash for what is currently playing .
59,332
def extract_message_info ( ) : base_path = BASE_PACKAGE . replace ( '.' , '/' ) filename = os . path . join ( base_path , 'ProtocolMessage.proto' ) with open ( filename , 'r' ) as file : types_found = False for line in file : stripped = line . lstrip ( ) . rstrip ( ) if stripped == 'enum Type {' : types_found = True continue elif types_found and stripped == '}' : break elif not types_found : continue constant = stripped . split ( ' ' ) [ 0 ] title = constant . title ( ) . replace ( '_' , '' ) . replace ( 'Hid' , 'HID' ) accessor = title [ 0 ] . lower ( ) + title [ 1 : ] if not os . path . exists ( os . path . join ( base_path , title + '.proto' ) ) : continue yield MessageInfo ( title + '_pb2' , title , accessor , constant )
Get information about all messages of interest .
59,333
def main ( ) : message_names = set ( ) packages = [ ] messages = [ ] extensions = [ ] constants = [ ] for info in extract_message_info ( ) : message_names . add ( info . title ) packages . append ( 'from {0} import {1}' . format ( BASE_PACKAGE , info . module ) ) messages . append ( 'from {0}.{1} import {2}' . format ( BASE_PACKAGE , info . module , info . title ) ) extensions . append ( 'ProtocolMessage.{0}: {1}.{2},' . format ( info . const , info . module , info . accessor ) ) constants . append ( '{0} = ProtocolMessage.{0}' . format ( info . const ) ) for module_name , message_name in extract_unreferenced_messages ( ) : if message_name not in message_names : message_names . add ( message_name ) messages . append ( 'from {0}.{1} import {2}' . format ( BASE_PACKAGE , module_name , message_name ) ) print ( OUTPUT_TEMPLATE . format ( packages = '\n' . join ( sorted ( packages ) ) , messages = '\n' . join ( sorted ( messages ) ) , extensions = '\n ' . join ( sorted ( extensions ) ) , constants = '\n' . join ( sorted ( constants ) ) ) ) return 0
Script starts somewhere around here .
59,334
def hkdf_expand ( salt , info , shared_secret ) : from cryptography . hazmat . primitives import hashes from cryptography . hazmat . primitives . kdf . hkdf import HKDF from cryptography . hazmat . backends import default_backend hkdf = HKDF ( algorithm = hashes . SHA512 ( ) , length = 32 , salt = salt . encode ( ) , info = info . encode ( ) , backend = default_backend ( ) ) return hkdf . derive ( shared_secret )
Derive encryption keys from shared secret .
59,335
def parse ( cls , detail_string ) : split = detail_string . split ( ':' ) if len ( split ) != 4 : raise Exception ( 'invalid credentials' ) ltpk = binascii . unhexlify ( split [ 0 ] ) ltsk = binascii . unhexlify ( split [ 1 ] ) atv_id = binascii . unhexlify ( split [ 2 ] ) client_id = binascii . unhexlify ( split [ 3 ] ) return Credentials ( ltpk , ltsk , atv_id , client_id )
Parse a string represention of Credentials .
59,336
def initialize ( self ) : self . _signing_key = SigningKey ( os . urandom ( 32 ) ) self . _auth_private = self . _signing_key . to_seed ( ) self . _auth_public = self . _signing_key . get_verifying_key ( ) . to_bytes ( ) self . _verify_private = curve25519 . Private ( secret = os . urandom ( 32 ) ) self . _verify_public = self . _verify_private . get_public ( ) return self . _auth_public , self . _verify_public . serialize ( )
Initialize operation by generating new keys .
59,337
def verify1 ( self , credentials , session_pub_key , encrypted ) : self . _shared = self . _verify_private . get_shared_key ( curve25519 . Public ( session_pub_key ) , hashfunc = lambda x : x ) session_key = hkdf_expand ( 'Pair-Verify-Encrypt-Salt' , 'Pair-Verify-Encrypt-Info' , self . _shared ) chacha = chacha20 . Chacha20Cipher ( session_key , session_key ) decrypted_tlv = tlv8 . read_tlv ( chacha . decrypt ( encrypted , nounce = 'PV-Msg02' . encode ( ) ) ) identifier = decrypted_tlv [ tlv8 . TLV_IDENTIFIER ] signature = decrypted_tlv [ tlv8 . TLV_SIGNATURE ] if identifier != credentials . atv_id : raise Exception ( 'incorrect device response' ) info = session_pub_key + bytes ( identifier ) + self . _verify_public . serialize ( ) ltpk = VerifyingKey ( bytes ( credentials . ltpk ) ) ltpk . verify ( bytes ( signature ) , bytes ( info ) ) device_info = self . _verify_public . serialize ( ) + credentials . client_id + session_pub_key device_signature = SigningKey ( credentials . ltsk ) . sign ( device_info ) tlv = tlv8 . write_tlv ( { tlv8 . TLV_IDENTIFIER : credentials . client_id , tlv8 . TLV_SIGNATURE : device_signature } ) return chacha . encrypt ( tlv , nounce = 'PV-Msg03' . encode ( ) )
First verification step .
59,338
def verify2 ( self ) : output_key = hkdf_expand ( 'MediaRemote-Salt' , 'MediaRemote-Write-Encryption-Key' , self . _shared ) input_key = hkdf_expand ( 'MediaRemote-Salt' , 'MediaRemote-Read-Encryption-Key' , self . _shared ) log_binary ( _LOGGER , 'Keys' , Output = output_key , Input = input_key ) return output_key , input_key
Last verification step .
59,339
def step1 ( self , pin ) : context = SRPContext ( 'Pair-Setup' , str ( pin ) , prime = constants . PRIME_3072 , generator = constants . PRIME_3072_GEN , hash_func = hashlib . sha512 ) self . _session = SRPClientSession ( context , binascii . hexlify ( self . _auth_private ) . decode ( ) )
First pairing step .
59,340
def step2 ( self , atv_pub_key , atv_salt ) : pk_str = binascii . hexlify ( atv_pub_key ) . decode ( ) salt = binascii . hexlify ( atv_salt ) . decode ( ) self . _client_session_key , _ , _ = self . _session . process ( pk_str , salt ) if not self . _session . verify_proof ( self . _session . key_proof_hash ) : raise exceptions . AuthenticationError ( 'proofs do not match (mitm?)' ) pub_key = binascii . unhexlify ( self . _session . public ) proof = binascii . unhexlify ( self . _session . key_proof ) log_binary ( _LOGGER , 'Client' , Public = pub_key , Proof = proof ) return pub_key , proof
Second pairing step .
59,341
def step3 ( self ) : ios_device_x = hkdf_expand ( 'Pair-Setup-Controller-Sign-Salt' , 'Pair-Setup-Controller-Sign-Info' , binascii . unhexlify ( self . _client_session_key ) ) self . _session_key = hkdf_expand ( 'Pair-Setup-Encrypt-Salt' , 'Pair-Setup-Encrypt-Info' , binascii . unhexlify ( self . _client_session_key ) ) device_info = ios_device_x + self . pairing_id + self . _auth_public device_signature = self . _signing_key . sign ( device_info ) tlv = tlv8 . write_tlv ( { tlv8 . TLV_IDENTIFIER : self . pairing_id , tlv8 . TLV_PUBLIC_KEY : self . _auth_public , tlv8 . TLV_SIGNATURE : device_signature } ) chacha = chacha20 . Chacha20Cipher ( self . _session_key , self . _session_key ) encrypted_data = chacha . encrypt ( tlv , nounce = 'PS-Msg05' . encode ( ) ) log_binary ( _LOGGER , 'Data' , Encrypted = encrypted_data ) return encrypted_data
Third pairing step .
59,342
def step4 ( self , encrypted_data ) : chacha = chacha20 . Chacha20Cipher ( self . _session_key , self . _session_key ) decrypted_tlv_bytes = chacha . decrypt ( encrypted_data , nounce = 'PS-Msg06' . encode ( ) ) if not decrypted_tlv_bytes : raise Exception ( 'data decrypt failed' ) decrypted_tlv = tlv8 . read_tlv ( decrypted_tlv_bytes ) _LOGGER . debug ( 'PS-Msg06: %s' , decrypted_tlv ) atv_identifier = decrypted_tlv [ tlv8 . TLV_IDENTIFIER ] atv_signature = decrypted_tlv [ tlv8 . TLV_SIGNATURE ] atv_pub_key = decrypted_tlv [ tlv8 . TLV_PUBLIC_KEY ] log_binary ( _LOGGER , 'Device' , Identifier = atv_identifier , Signature = atv_signature , Public = atv_pub_key ) return Credentials ( atv_pub_key , self . _signing_key . to_seed ( ) , atv_identifier , self . pairing_id )
Last pairing step .
59,343
def hash_sha512 ( * indata ) : hasher = hashlib . sha512 ( ) for data in indata : if isinstance ( data , str ) : hasher . update ( data . encode ( 'utf-8' ) ) elif isinstance ( data , bytes ) : hasher . update ( data ) else : raise Exception ( 'invalid input data: ' + str ( data ) ) return hasher . digest ( )
Create SHA512 hash for input arguments .
59,344
def aes_encrypt ( mode , aes_key , aes_iv , * data ) : encryptor = Cipher ( algorithms . AES ( aes_key ) , mode ( aes_iv ) , backend = default_backend ( ) ) . encryptor ( ) result = None for value in data : result = encryptor . update ( value ) encryptor . finalize ( ) return result , None if not hasattr ( encryptor , 'tag' ) else encryptor . tag
Encrypt data with AES in specified mode .
59,345
def new_credentials ( ) : identifier = binascii . b2a_hex ( os . urandom ( 8 ) ) . decode ( ) . upper ( ) seed = binascii . b2a_hex ( os . urandom ( 32 ) ) return identifier , seed
Generate a new identifier and seed for authentication .
59,346
def initialize ( self , seed = None ) : self . seed = seed or os . urandom ( 32 ) signing_key = SigningKey ( self . seed ) verifying_key = signing_key . get_verifying_key ( ) self . _auth_private = signing_key . to_seed ( ) self . _auth_public = verifying_key . to_bytes ( ) log_binary ( _LOGGER , 'Authentication keys' , Private = self . _auth_private , Public = self . _auth_public )
Initialize handler operation .
59,347
def verify1 ( self ) : self . _check_initialized ( ) self . _verify_private = curve25519 . Private ( secret = self . seed ) self . _verify_public = self . _verify_private . get_public ( ) log_binary ( _LOGGER , 'Verification keys' , Private = self . _verify_private . serialize ( ) , Public = self . _verify_public . serialize ( ) ) verify_public = self . _verify_public . serialize ( ) return b'\x01\x00\x00\x00' + verify_public + self . _auth_public
First device verification step .
59,348
def verify2 ( self , atv_public_key , data ) : self . _check_initialized ( ) log_binary ( _LOGGER , 'Verify' , PublicSecret = atv_public_key , Data = data ) public = curve25519 . Public ( atv_public_key ) shared = self . _verify_private . get_shared_key ( public , hashfunc = lambda x : x ) log_binary ( _LOGGER , 'Shared secret' , Secret = shared ) aes_key = hash_sha512 ( 'Pair-Verify-AES-Key' , shared ) [ 0 : 16 ] aes_iv = hash_sha512 ( 'Pair-Verify-AES-IV' , shared ) [ 0 : 16 ] log_binary ( _LOGGER , 'Pair-Verify-AES' , Key = aes_key , IV = aes_iv ) signer = SigningKey ( self . _auth_private ) signed = signer . sign ( self . _verify_public . serialize ( ) + atv_public_key ) signature , _ = aes_encrypt ( modes . CTR , aes_key , aes_iv , data , signed ) log_binary ( _LOGGER , 'Signature' , Signature = signature ) return b'\x00\x00\x00\x00' + signature
Last device verification step .
59,349
def step1 ( self , username , password ) : self . _check_initialized ( ) context = AtvSRPContext ( str ( username ) , str ( password ) , prime = constants . PRIME_2048 , generator = constants . PRIME_2048_GEN ) self . session = SRPClientSession ( context , binascii . hexlify ( self . _auth_private ) . decode ( ) )
First authentication step .
59,350
def step2 ( self , pub_key , salt ) : self . _check_initialized ( ) pk_str = binascii . hexlify ( pub_key ) . decode ( ) salt = binascii . hexlify ( salt ) . decode ( ) self . client_session_key , _ , _ = self . session . process ( pk_str , salt ) _LOGGER . debug ( 'Client session key: %s' , self . client_session_key ) client_public = self . session . public client_session_key_proof = self . session . key_proof _LOGGER . debug ( 'Client public: %s, proof: %s' , client_public , client_session_key_proof ) if not self . session . verify_proof ( self . session . key_proof_hash ) : raise AuthenticationError ( 'proofs do not match (mitm?)' ) return client_public , client_session_key_proof
Second authentication step .
59,351
def step3 ( self ) : self . _check_initialized ( ) session_key = binascii . unhexlify ( self . client_session_key ) aes_key = hash_sha512 ( 'Pair-Setup-AES-Key' , session_key ) [ 0 : 16 ] tmp = bytearray ( hash_sha512 ( 'Pair-Setup-AES-IV' , session_key ) [ 0 : 16 ] ) tmp [ - 1 ] = tmp [ - 1 ] + 1 aes_iv = bytes ( tmp ) log_binary ( _LOGGER , 'Pair-Setup-AES' , Key = aes_key , IV = aes_iv ) epk , tag = aes_encrypt ( modes . GCM , aes_key , aes_iv , self . _auth_public ) log_binary ( _LOGGER , 'Pair-Setup EPK+Tag' , EPK = epk , Tag = tag ) return epk , tag
Last authentication step .
59,352
async def start_authentication ( self ) : _ , code = await self . http . post_data ( 'pair-pin-start' , headers = _AIRPLAY_HEADERS ) if code != 200 : raise DeviceAuthenticationError ( 'pair start failed' )
Start the authentication process .
59,353
async def finish_authentication ( self , username , password ) : self . srp . step1 ( username , password ) data = await self . _send_plist ( 'step1' , method = 'pin' , user = username ) resp = plistlib . loads ( data ) pub_key , key_proof = self . srp . step2 ( resp [ 'pk' ] , resp [ 'salt' ] ) await self . _send_plist ( 'step2' , pk = binascii . unhexlify ( pub_key ) , proof = binascii . unhexlify ( key_proof ) ) epk , tag = self . srp . step3 ( ) await self . _send_plist ( 'step3' , epk = epk , authTag = tag ) return True
Finish authentication process .
59,354
async def verify_authed ( self ) : resp = await self . _send ( self . srp . verify1 ( ) , 'verify1' ) atv_public_secret = resp [ 0 : 32 ] data = resp [ 32 : ] await self . _send ( self . srp . verify2 ( atv_public_secret , data ) , 'verify2' ) return True
Verify if device is allowed to use AirPlau .
59,355
async def generate_credentials ( self ) : identifier , seed = new_credentials ( ) return '{0}:{1}' . format ( identifier , seed . decode ( ) . upper ( ) )
Create new credentials for authentication .
59,356
async def load_credentials ( self , credentials ) : split = credentials . split ( ':' ) self . identifier = split [ 0 ] self . srp . initialize ( binascii . unhexlify ( split [ 1 ] ) ) _LOGGER . debug ( 'Loaded AirPlay credentials: %s' , credentials )
Load existing credentials .
59,357
def enable_encryption ( self , output_key , input_key ) : self . _chacha = chacha20 . Chacha20Cipher ( output_key , input_key )
Enable encryption with the specified keys .
59,358
def connect ( self ) : return self . loop . create_connection ( lambda : self , self . host , self . port )
Connect to device .
59,359
def close ( self ) : if self . _transport : self . _transport . close ( ) self . _transport = None self . _chacha = None
Close connection to device .
59,360
def send ( self , message ) : serialized = message . SerializeToString ( ) log_binary ( _LOGGER , '>> Send' , Data = serialized ) if self . _chacha : serialized = self . _chacha . encrypt ( serialized ) log_binary ( _LOGGER , '>> Send' , Encrypted = serialized ) data = write_variant ( len ( serialized ) ) + serialized self . _transport . write ( data ) _LOGGER . debug ( '>> Send: Protobuf=%s' , message )
Send message to device .
59,361
async def get_data ( self , path , headers = None , timeout = None ) : url = self . base_url + path _LOGGER . debug ( 'GET URL: %s' , url ) resp = None try : resp = await self . _session . get ( url , headers = headers , timeout = DEFAULT_TIMEOUT if timeout is None else timeout ) if resp . content_length is not None : resp_data = await resp . read ( ) else : resp_data = None return resp_data , resp . status except Exception as ex : if resp is not None : resp . close ( ) raise ex finally : if resp is not None : await resp . release ( )
Perform a GET request .
59,362
async def post_data ( self , path , data = None , headers = None , timeout = None ) : url = self . base_url + path _LOGGER . debug ( 'POST URL: %s' , url ) self . _log_data ( data , False ) resp = None try : resp = await self . _session . post ( url , headers = headers , data = data , timeout = DEFAULT_TIMEOUT if timeout is None else timeout ) if resp . content_length is not None : resp_data = await resp . read ( ) else : resp_data = None self . _log_data ( resp_data , True ) return resp_data , resp . status except Exception as ex : if resp is not None : resp . close ( ) raise ex finally : if resp is not None : await resp . release ( )
Perform a POST request .
59,363
def read_uint ( data , start , length ) : return int . from_bytes ( data [ start : start + length ] , byteorder = 'big' )
Extract a uint from a position in a sequence .
59,364
def read_bplist ( data , start , length ) : return plistlib . loads ( data [ start : start + length ] , fmt = plistlib . FMT_BINARY )
Extract a binary plist from a position in a sequence .
59,365
def raw_tag ( name , value ) : return name . encode ( 'utf-8' ) + len ( value ) . to_bytes ( 4 , byteorder = 'big' ) + value
Create a DMAP tag with raw data .
59,366
def string_tag ( name , value ) : return name . encode ( 'utf-8' ) + len ( value ) . to_bytes ( 4 , byteorder = 'big' ) + value . encode ( 'utf-8' )
Create a DMAP tag with string data .
59,367
def create ( message_type , priority = 0 ) : message = protobuf . ProtocolMessage ( ) message . type = message_type message . priority = priority return message
Create a ProtocolMessage .
59,368
def device_information ( name , identifier ) : message = create ( protobuf . DEVICE_INFO_MESSAGE ) info = message . inner ( ) info . uniqueIdentifier = identifier info . name = name info . localizedModelName = 'iPhone' info . systemBuildVersion = '14G60' info . applicationBundleIdentifier = 'com.apple.TVRemote' info . applicationBundleVersion = '273.12' info . protocolVersion = 1 info . lastSupportedMessageType = 58 info . supportsExtendedMotion = True return message
Create a new DEVICE_INFO_MESSAGE .
59,369
def set_connection_state ( ) : message = create ( protobuf . ProtocolMessage . SET_CONNECTION_STATE_MESSAGE ) message . inner ( ) . state = protobuf . SetConnectionStateMessage . Connected return message
Create a new SET_CONNECTION_STATE .
59,370
def crypto_pairing ( pairing_data ) : message = create ( protobuf . CRYPTO_PAIRING_MESSAGE ) crypto = message . inner ( ) crypto . status = 0 crypto . pairingData = tlv8 . write_tlv ( pairing_data ) return message
Create a new CRYPTO_PAIRING_MESSAGE .
59,371
def client_updates_config ( artwork = True , now_playing = True , volume = True , keyboard = True ) : message = create ( protobuf . CLIENT_UPDATES_CONFIG_MESSAGE ) config = message . inner ( ) config . artworkUpdates = artwork config . nowPlayingUpdates = now_playing config . volumeUpdates = volume config . keyboardUpdates = keyboard return message
Create a new CLIENT_UPDATES_CONFIG_MESSAGE .
59,372
def register_hid_device ( screen_width , screen_height , absolute = False , integrated_display = False ) : message = create ( protobuf . REGISTER_HID_DEVICE_MESSAGE ) descriptor = message . inner ( ) . deviceDescriptor descriptor . absolute = 1 if absolute else 0 descriptor . integratedDisplay = 1 if integrated_display else 0 descriptor . screenSizeWidth = screen_width descriptor . screenSizeHeight = screen_height return message
Create a new REGISTER_HID_DEVICE_MESSAGE .
59,373
def send_packed_virtual_touch_event ( xpos , ypos , phase , device_id , finger ) : message = create ( protobuf . SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE ) event = message . inner ( ) event . data = xpos . to_bytes ( 2 , byteorder = 'little' ) event . data += ypos . to_bytes ( 2 , byteorder = 'little' ) event . data += phase . to_bytes ( 2 , byteorder = 'little' ) event . data += device_id . to_bytes ( 2 , byteorder = 'little' ) event . data += finger . to_bytes ( 2 , byteorder = 'little' ) return message
Create a new WAKE_DEVICE_MESSAGE .
59,374
def send_hid_event ( use_page , usage , down ) : message = create ( protobuf . SEND_HID_EVENT_MESSAGE ) event = message . inner ( ) abstime = binascii . unhexlify ( b'438922cf08020000' ) data = use_page . to_bytes ( 2 , byteorder = 'big' ) data += usage . to_bytes ( 2 , byteorder = 'big' ) data += ( 1 if down else 0 ) . to_bytes ( 2 , byteorder = 'big' ) event . hidEventData = abstime + binascii . unhexlify ( b'00000000000000000100000000000000020' + b'00000200000000300000001000000000000' ) + data + binascii . unhexlify ( b'0000000000000001000000' ) return message
Create a new SEND_HID_EVENT_MESSAGE .
59,375
def command ( cmd ) : message = create ( protobuf . SEND_COMMAND_MESSAGE ) send_command = message . inner ( ) send_command . command = cmd return message
Playback command request .
59,376
def repeat ( mode ) : message = command ( protobuf . CommandInfo_pb2 . ChangeShuffleMode ) send_command = message . inner ( ) send_command . options . externalPlayerCommand = True send_command . options . repeatMode = mode return message
Change repeat mode of current player .
59,377
def shuffle ( enable ) : message = command ( protobuf . CommandInfo_pb2 . ChangeShuffleMode ) send_command = message . inner ( ) send_command . options . shuffleMode = 3 if enable else 1 return message
Change shuffle mode of current player .
59,378
def seek_to_position ( position ) : message = command ( protobuf . CommandInfo_pb2 . SeekToPlaybackPosition ) send_command = message . inner ( ) send_command . options . playbackPosition = position return message
Seek to an absolute position in stream .
59,379
async def pair_with_device ( loop ) : my_zeroconf = Zeroconf ( ) details = conf . AppleTV ( '127.0.0.1' , 'Apple TV' ) details . add_service ( conf . DmapService ( 'login_id' ) ) atv = pyatv . connect_to_apple_tv ( details , loop ) atv . pairing . pin ( PIN_CODE ) await atv . pairing . start ( zeroconf = my_zeroconf , name = REMOTE_NAME ) print ( 'You can now pair with pyatv' ) await asyncio . sleep ( 60 , loop = loop ) await atv . pairing . stop ( ) if atv . pairing . has_paired : print ( 'Paired with device!' ) print ( 'Credentials:' , atv . pairing . credentials ) else : print ( 'Did not pair with device!' ) my_zeroconf . close ( )
Make it possible to pair with device .
59,380
def read_variant ( variant ) : result = 0 cnt = 0 for data in variant : result |= ( data & 0x7f ) << ( 7 * cnt ) cnt += 1 if not data & 0x80 : return result , variant [ cnt : ] raise Exception ( 'invalid variant' )
Read and parse a binary protobuf variant value .
59,381
async def print_what_is_playing ( loop ) : details = conf . AppleTV ( ADDRESS , NAME ) details . add_service ( conf . DmapService ( HSGID ) ) print ( 'Connecting to {}' . format ( details . address ) ) atv = pyatv . connect_to_apple_tv ( details , loop ) try : print ( ( await atv . metadata . playing ( ) ) ) finally : await atv . logout ( )
Connect to device and print what is playing .
59,382
def add_listener ( self , listener , message_type , data = None , one_shot = False ) : lst = self . _one_shots if one_shot else self . _listeners if message_type not in lst : lst [ message_type ] = [ ] lst [ message_type ] . append ( Listener ( listener , data ) )
Add a listener that will receice incoming messages .
59,383
async def start ( self ) : if self . connection . connected : return await self . connection . connect ( ) if self . service . device_credentials : self . srp . pairing_id = Credentials . parse ( self . service . device_credentials ) . client_id msg = messages . device_information ( 'pyatv' , self . srp . pairing_id . decode ( ) ) await self . send_and_receive ( msg ) self . _initial_message_sent = True await self . send ( messages . set_ready_state ( ) ) async def _wait_for_updates ( _ , semaphore ) : semaphore . release ( ) semaphore = asyncio . Semaphore ( value = 0 , loop = self . loop ) self . add_listener ( _wait_for_updates , protobuf . SET_STATE_MESSAGE , data = semaphore , one_shot = True ) await self . send ( messages . client_updates_config ( ) ) await self . send ( messages . wake_device ( ) ) try : await asyncio . wait_for ( semaphore . acquire ( ) , 1 , loop = self . loop ) except asyncio . TimeoutError : pass
Connect to device and listen to incoming messages .
59,384
def stop ( self ) : if self . _outstanding : _LOGGER . warning ( 'There were %d outstanding requests' , len ( self . _outstanding ) ) self . _initial_message_sent = False self . _outstanding = { } self . _one_shots = { } self . connection . close ( )
Disconnect from device .
59,385
async def send_and_receive ( self , message , generate_identifier = True , timeout = 5 ) : await self . _connect_and_encrypt ( ) if generate_identifier : identifier = str ( uuid . uuid4 ( ) ) message . identifier = identifier else : identifier = 'type_' + str ( message . type ) self . connection . send ( message ) return await self . _receive ( identifier , timeout )
Send a message and wait for a response .
59,386
async def playstatus ( self , use_revision = False , timeout = None ) : cmd_url = _PSU_CMD . format ( self . playstatus_revision if use_revision else 0 ) resp = await self . daap . get ( cmd_url , timeout = timeout ) self . playstatus_revision = parser . first ( resp , 'cmst' , 'cmsr' ) return resp
Request raw data about what is currently playing .
59,387
def ctrl_int_cmd ( self , cmd ) : cmd_url = 'ctrl-int/1/{}?[AUTH]&prompt-id=0' . format ( cmd ) return self . daap . post ( cmd_url )
Perform a ctrl - int command .
59,388
def controlprompt_cmd ( self , cmd ) : data = tags . string_tag ( 'cmbe' , cmd ) + tags . uint8_tag ( 'cmcc' , 0 ) return self . daap . post ( _CTRL_PROMPT_CMD , data = data )
Perform a controlpromptentry command .
59,389
async def up ( self ) : await self . _send_commands ( self . _move ( 'Down' , 0 , 20 , 275 ) , self . _move ( 'Move' , 1 , 20 , 270 ) , self . _move ( 'Move' , 2 , 20 , 265 ) , self . _move ( 'Move' , 3 , 20 , 260 ) , self . _move ( 'Move' , 4 , 20 , 255 ) , self . _move ( 'Move' , 5 , 20 , 250 ) , self . _move ( 'Up' , 6 , 20 , 250 ) )
Press key up .
59,390
async def down ( self ) : await self . _send_commands ( self . _move ( 'Down' , 0 , 20 , 250 ) , self . _move ( 'Move' , 1 , 20 , 255 ) , self . _move ( 'Move' , 2 , 20 , 260 ) , self . _move ( 'Move' , 3 , 20 , 265 ) , self . _move ( 'Move' , 4 , 20 , 270 ) , self . _move ( 'Move' , 5 , 20 , 275 ) , self . _move ( 'Up' , 6 , 20 , 275 ) )
Press key down .
59,391
async def left ( self ) : await self . _send_commands ( self . _move ( 'Down' , 0 , 75 , 100 ) , self . _move ( 'Move' , 1 , 70 , 100 ) , self . _move ( 'Move' , 3 , 65 , 100 ) , self . _move ( 'Move' , 4 , 60 , 100 ) , self . _move ( 'Move' , 5 , 55 , 100 ) , self . _move ( 'Move' , 6 , 50 , 100 ) , self . _move ( 'Up' , 7 , 50 , 100 ) )
Press key left .
59,392
async def right ( self ) : await self . _send_commands ( self . _move ( 'Down' , 0 , 50 , 100 ) , self . _move ( 'Move' , 1 , 55 , 100 ) , self . _move ( 'Move' , 3 , 60 , 100 ) , self . _move ( 'Move' , 4 , 65 , 100 ) , self . _move ( 'Move' , 5 , 70 , 100 ) , self . _move ( 'Move' , 6 , 75 , 100 ) , self . _move ( 'Up' , 7 , 75 , 100 ) )
Press key right .
59,393
def set_position ( self , pos ) : time_in_ms = int ( pos ) * 1000 return self . apple_tv . set_property ( 'dacp.playingtime' , time_in_ms )
Seek in the current playing media .
59,394
async def authenticate_with_device ( atv ) : credentials = await atv . airplay . generate_credentials ( ) await atv . airplay . load_credentials ( credentials ) try : await atv . airplay . start_authentication ( ) pin = input ( 'PIN Code: ' ) await atv . airplay . finish_authentication ( pin ) print ( 'Credentials: {0}' . format ( credentials ) ) except exceptions . DeviceAuthenticationError : print ( 'Failed to authenticate' , file = sys . stderr )
Perform device authentication and print credentials .
59,395
def encrypt ( self , data , nounce = None ) : if nounce is None : nounce = self . _out_counter . to_bytes ( length = 8 , byteorder = 'little' ) self . _out_counter += 1 return self . _enc_out . seal ( b'\x00\x00\x00\x00' + nounce , data , bytes ( ) )
Encrypt data with counter or specified nounce .
59,396
def decrypt ( self , data , nounce = None ) : if nounce is None : nounce = self . _in_counter . to_bytes ( length = 8 , byteorder = 'little' ) self . _in_counter += 1 decrypted = self . _enc_in . open ( b'\x00\x00\x00\x00' + nounce , data , bytes ( ) ) if not decrypted : raise Exception ( 'data decrypt failed' ) return bytes ( decrypted )
Decrypt data with counter or specified nounce .
59,397
def auto_connect ( handler , timeout = 5 , not_found = None , event_loop = None ) : async def _handle ( loop ) : atvs = await pyatv . scan_for_apple_tvs ( loop , timeout = timeout , abort_on_found = True ) if atvs : atv = pyatv . connect_to_apple_tv ( atvs [ 0 ] , loop ) try : await handler ( atv ) finally : await atv . logout ( ) else : if not_found is not None : await not_found ( ) loop = event_loop if event_loop else asyncio . get_event_loop ( ) loop . run_until_complete ( _handle ( loop ) )
Short method for connecting to a device .
59,398
async def login ( self ) : def _login_request ( ) : return self . http . get_data ( self . _mkurl ( 'login?[AUTH]&hasFP=1' , session = False , login_id = True ) , headers = _DMAP_HEADERS ) resp = await self . _do ( _login_request , is_login = True ) self . _session_id = parser . first ( resp , 'mlog' , 'mlid' ) _LOGGER . info ( 'Logged in and got session id %s' , self . _session_id ) return self . _session_id
Login to Apple TV using specified login id .
59,399
async def get ( self , cmd , daap_data = True , timeout = None , ** args ) : def _get_request ( ) : return self . http . get_data ( self . _mkurl ( cmd , * args ) , headers = _DMAP_HEADERS , timeout = timeout ) await self . _assure_logged_in ( ) return await self . _do ( _get_request , is_daap = daap_data )
Perform a DAAP GET command .