"""Publisher logic.""" import base64 import hashlib from switchboard_consumer.constants import entity_type, system from switchboard_consumer.utils.message import create_processing_result def _get_publisher_unid(name): """Generate publisher UNID.""" name_hash = base64.b64encode( hashlib.sha1(name.encode('utf-8')).digest()) return 'UNID:{}'.format(name_hash.decode('utf-8')) def get_publisher_processing_results( logger, message, tracks, unmapped_tracks_publishers): """Get publisher processing results from created tracks.""" processing_results = [] for track in tracks: track_created_publishers = (track.get('publishing', {}) or {}).get( 'publisherNames', []) or [] if not track_created_publishers: continue isrc = track['isrc'] unmapped_publishers = unmapped_tracks_publishers.get(isrc, []) for unmapped_publisher in unmapped_publishers: publisher_name = unmapped_publisher[0] unmapped_publisher_ingested = ( publisher_name in track_created_publishers) if unmapped_publisher_ingested: switchboard_local_id = unmapped_publisher[1] orchard_local_id = { 'system': system.ORCHARD, 'localId': _get_publisher_unid(publisher_name) } processing_results.append(create_processing_result( [switchboard_local_id, orchard_local_id], message, entity_type=entity_type.PUBLISHER)) else: logger.error( 'Failed to find unmapped publisher', custom_fields={'name': publisher_name, 'isrc': isrc}) return processing_results