"""Tracks.""" from switchboard_consumer.constants import entity_type from switchboard_consumer.formatters.errors import \ format_create_track_errors from switchboard_consumer.formatters.track import ( format_result_id as format_track_result_id) from switchboard_consumer.logic.publisher import \ get_publisher_processing_results from switchboard_consumer.utils.message import (create_processing_result, create_track_identifiers) def create_tracks(logger, message, orchard_client, product_id, create_tracks_payload, track_mappings, unmapped_tracks_publishers): """Create tracks.""" processing_results = [] create_tracks_result = orchard_client.create_tracks( create_tracks_payload, product_id, message.correlation_id ) if (isinstance(create_tracks_result, dict) and # noqa: W504 create_tracks_result.get('errors')): # Create processing results for any successful tracks tracks = create_tracks_result.get('data', {}).get('saveTracks') or [] track_ids = map_identifiers_to_tracks(tracks, track_mappings) for track_id in track_ids: processing_results.append(create_processing_result( track_id, message, entity_type=entity_type.TRACK)) # Parse errors out of the bulk track results errors = create_tracks_result['errors'] results = format_create_track_errors(create_tracks_payload, message, errors, track_mappings, logger) logger.error('Problem inserting tracks. - {}'.format(errors)) processing_results.extend(results) return False, processing_results track_ids = map_identifiers_to_tracks(create_tracks_result, track_mappings) for track_id in track_ids: processing_results.append(create_processing_result( track_id, message, entity_type=entity_type.TRACK)) processing_results.extend(get_publisher_processing_results( logger, message, create_tracks_result, unmapped_tracks_publishers)) return True, processing_results def map_identifiers_to_tracks(tracks, mapping): """Construct tracks local ids from mapping.""" processed_track_identifiers = [] for track_item in list(filter(None, tracks)): track_identifiers = [] isrc = track_item['isrc'] track_identifer = format_track_result_id( track_item['tuid'], isrc) track_identifiers.extend(track_identifer) track_identifiers.append(mapping[isrc]) processed_track_identifiers.append( create_track_identifiers(track_identifiers, isrc) ) return processed_track_identifiers