def _list_replicas(dataset_clause, file_clause, state_clause, show_pfns, schemes, files_wo_replica, rse_clause, client_location, domain, sign_urls, signature_lifetime, constituent_clause, resolve_parents, updated_after, filters, ignore_availability, session):
    replicas = heapq.merge(_list_replicas_for_datasets(dataset_clause, state_clause, rse_clause, ignore_availability, updated_after, session), _list_replicas_for_files(file_clause, state_clause, files_wo_replica, rse_clause, ignore_availability, updated_after, session), _list_replicas_for_constituents(constituent_clause, state_clause, files_wo_replica, rse_clause, ignore_availability, updated_after, session), key=(lambda t: (t[0], t[1])))
    original_domain = deepcopy(domain)
    local_rses = []
    if (domain is None):
        if (client_location and ('site' in client_location) and client_location['site']):
            try:
                local_rses = [rse['id'] for rse in parse_expression(('site=%s' % client_location['site']), filter=filters, session=session)]
            except Exception:
                pass
    (file, tmp_protocols, rse_info, pfns_cache) = ({}, {}, {}, {})
    for (scope, name, archive_scope, archive_name, bytes, md5, adler32, path, state, rse_id, rse, rse_type, volatile) in replicas:
        pfns = []
        domain = deepcopy(original_domain)
        if (show_pfns and rse_id):
            if (rse_id not in rse_info):
                rse_info[rse_id] = rsemgr.get_rse_info(rse_id=rse_id, session=session)
            rse_info[rse_id]['priority_wan'] = {p['scheme']: p['domains']['wan']['read'] for p in rse_info[rse_id]['protocols'] if (p['domains']['wan']['read'] > 0)}
            rse_info[rse_id]['priority_lan'] = {p['scheme']: p['domains']['lan']['read'] for p in rse_info[rse_id]['protocols'] if (p['domains']['lan']['read'] > 0)}
            if (domain is None):
                domain = 'wan'
                if (local_rses and (rse_id in local_rses)):
                    domain = 'lan'
            if (rse_id not in tmp_protocols):
                rse_schemes = (schemes or [])
                if (not rse_schemes):
                    try:
                        if (domain == 'all'):
                            rse_schemes.append(rsemgr.select_protocol(rse_settings=rse_info[rse_id], operation='read', domain='wan')['scheme'])
                            rse_schemes.append(rsemgr.select_protocol(rse_settings=rse_info[rse_id], operation='read', domain='lan')['scheme'])
                        else:
                            rse_schemes.append(rsemgr.select_protocol(rse_settings=rse_info[rse_id], operation='read', domain=domain)['scheme'])
                    except exception.RSEProtocolNotSupported:
                        pass
                    except Exception:
                        print(format_exc())
                if (archive_scope and archive_name and ('root' not in rse_schemes)):
                    rse_schemes.append('root')
                protocols = []
                for s in rse_schemes:
                    try:
                        if (domain == 'all'):
                            protocols.append(('lan', rsemgr.create_protocol(rse_settings=rse_info[rse_id], operation='read', scheme=s, domain='lan'), rse_info[rse_id]['priority_lan'][s]))
                            protocols.append(('wan', rsemgr.create_protocol(rse_settings=rse_info[rse_id], operation='read', scheme=s, domain='wan'), rse_info[rse_id]['priority_wan'][s]))
                        else:
                            protocols.append((domain, rsemgr.create_protocol(rse_settings=rse_info[rse_id], operation='read', scheme=s, domain=domain), rse_info[rse_id][('priority_%s' % domain)][s]))
                    except exception.RSEProtocolNotSupported:
                        pass
                    except Exception:
                        print(format_exc())
                tmp_protocols[rse_id] = protocols
            for tmp_protocol in tmp_protocols[rse_id]:
                if (archive_scope and archive_name):
                    t_scope = archive_scope
                    t_name = archive_name
                else:
                    t_scope = scope
                    t_name = name
                protocol = tmp_protocol[1]
                if ('determinism_type' in protocol.attributes):
                    try:
                        path = pfns_cache[('%s:%s:%s' % (protocol.attributes['determinism_type'], t_scope.internal, t_name))]
                    except KeyError:
                        path = protocol._get_path(t_scope, t_name)
                        pfns_cache[('%s:%s:%s' % (protocol.attributes['determinism_type'], t_scope.internal, t_name))] = path
                try:
                    pfn = list(protocol.lfns2pfns(lfns={'scope': t_scope.external, 'name': t_name, 'path': path}).values())[0]
                    if (sign_urls and (protocol.attributes['scheme'] == 'https')):
                        service = get_rse_attribute('sign_url', rse_id=rse_id, session=session)
                        if (service and isinstance(service, list)):
                            pfn = get_signed_url(rse_id=rse_id, service=service[0], operation='read', url=pfn, lifetime=signature_lifetime)
                    if ((domain == 'wan') and (protocol.attributes['scheme'] in ['root', 'http', 'https']) and client_location):
                        if (('site' in client_location) and client_location['site']):
                            rse_site_attr = get_rse_attribute('site', rse_id, session=session)
                            replica_site = ['']
                            if (isinstance(rse_site_attr, list) and rse_site_attr):
                                replica_site = rse_site_attr[0]
                            if (client_location['site'] != replica_site):
                                cache_site = config_get('clientcachemap', client_location['site'], default='', session=session)
                                if (cache_site != ''):
                                    selected_prefix = get_multi_cache_prefix(cache_site, t_name)
                                    if selected_prefix:
                                        pfn = ((('root://' + selected_prefix) + '//') + pfn.replace('davs://', 'root://'))
                                else:
                                    root_proxy_internal = config_get('root-proxy-internal', client_location['site'], default='', session=session)
                                    if root_proxy_internal:
                                        if (('storage.googleapis.com' in pfn) or ('atlas-google-cloud.cern.ch' in pfn) or ('amazonaws.com' in pfn)):
                                            pass
                                        else:
                                            pfn = ((('root://' + root_proxy_internal) + '//') + pfn.replace('davs://', 'https://'))
                    t_domain = tmp_protocol[0]
                    t_priority = tmp_protocol[2]
                    t_client_extract = False
                    if (archive_scope and archive_name):
                        t_domain = 'zip'
                        pfn = add_url_query(pfn, {'xrdcl.unzip': name})
                        if (protocol.attributes['scheme'] == 'root'):
                            t_client_extract = False
                            t_priority = (- 1)
                        else:
                            t_client_extract = True
                    pfns.append((pfn, t_domain, t_priority, t_client_extract))
                except Exception:
                    print(format_exc())
                if (protocol.attributes['scheme'] == 'srm'):
                    try:
                        file['space_token'] = protocol.attributes['extended_attributes']['space_token']
                    except KeyError:
                        file['space_token'] = None
        if (('scope' in file) and ('name' in file)):
            if ((file['scope'] == scope) and (file['name'] == name)):
                file['rses'][rse_id] += list(set([tmp_pfn[0] for tmp_pfn in pfns]))
                file['states'][rse_id] = str((state.name if state else state))
                if resolve_parents:
                    file['parents'] = [('%s:%s' % (parent['scope'].internal, parent['name'])) for parent in rucio.core.did.list_all_parent_dids(scope, name, session=session)]
                for tmp_pfn in pfns:
                    file['pfns'][tmp_pfn[0]] = {'rse_id': rse_id, 'rse': rse, 'type': str(rse_type.name), 'volatile': volatile, 'domain': tmp_pfn[1], 'priority': tmp_pfn[2], 'client_extract': tmp_pfn[3]}
            else:
                if resolve_parents:
                    file['parents'] = [('%s:%s' % (parent['scope'].internal, parent['name'])) for parent in rucio.core.did.list_all_parent_dids(file['scope'], file['name'], session=session)]
                tmp = sorted([(file['pfns'][p]['domain'], file['pfns'][p]['priority'], p) for p in file['pfns']])
                for i in range(0, len(tmp)):
                    file['pfns'][tmp[i][2]]['priority'] = (i + 1)
                    file['rses'] = {}
                    rse_pfns = []
                    for (t_rse, t_priority, t_pfn) in [(file['pfns'][t_pfn]['rse_id'], file['pfns'][t_pfn]['priority'], t_pfn) for t_pfn in file['pfns']]:
                        rse_pfns.append((t_rse, t_priority, t_pfn))
                    rse_pfns = sorted(rse_pfns)
                    for (t_rse, t_priority, t_pfn) in rse_pfns:
                        if (t_rse in file['rses']):
                            file['rses'][t_rse].append(t_pfn)
                        else:
                            file['rses'][t_rse] = [t_pfn]
                (yield file)
                file = {}
        if (not (('scope' in file) and ('name' in file))):
            (file['scope'], file['name']) = (scope, name)
            (file['bytes'], file['md5'], file['adler32']) = (bytes, md5, adler32)
            (file['pfns'], file['rses']) = ({}, defaultdict(list))
            file['states'] = {rse_id: str((state.name if state else state))}
            if resolve_parents:
                file['parents'] = [('%s:%s' % (parent['scope'].internal, parent['name'])) for parent in rucio.core.did.list_all_parent_dids(scope, name, session=session)]
            if rse_id:
                file['rses'][rse_id] = list(set([tmp_pfn[0] for tmp_pfn in pfns]))
                for tmp_pfn in pfns:
                    file['pfns'][tmp_pfn[0]] = {'rse_id': rse_id, 'rse': rse, 'type': str(rse_type.name), 'volatile': volatile, 'domain': tmp_pfn[1], 'priority': tmp_pfn[2], 'client_extract': tmp_pfn[3]}
    if ('pfns' in file):
        tmp = sorted([(file['pfns'][p]['domain'], file['pfns'][p]['priority'], p) for p in file['pfns']])
        for i in range(0, len(tmp)):
            file['pfns'][tmp[i][2]]['priority'] = (i + 1)
    if (('scope' in file) and ('name' in file)):
        file['rses'] = {}
        if resolve_parents:
            file['parents'] = [('%s:%s' % (parent['scope'].internal, parent['name'])) for parent in rucio.core.did.list_all_parent_dids(file['scope'], file['name'], session=session)]
        rse_pfns = []
        for (t_rse, t_priority, t_pfn) in [(file['pfns'][t_pfn]['rse_id'], file['pfns'][t_pfn]['priority'], t_pfn) for t_pfn in file['pfns']]:
            rse_pfns.append((t_rse, t_priority, t_pfn))
        rse_pfns = sorted(rse_pfns)
        for (t_rse, t_priority, t_pfn) in rse_pfns:
            if (t_rse in file['rses']):
                file['rses'][t_rse].append(t_pfn)
            else:
                file['rses'][t_rse] = [t_pfn]
        (yield file)
        file = {}
    for (scope, name, bytes, md5, adler32) in _list_files_wo_replicas(files_wo_replica, session):
        (yield {'scope': scope, 'name': name, 'bytes': bytes, 'md5': md5, 'adler32': adler32, 'pfns': {}, 'rses': defaultdict(list)})
def _list_replicas(dataset_clause, file_clause, state_clause, show_pfns, schemes, files_wo_replica, rse_clause, client_location, domain, sign_urls, signature_lifetime, constituent_clause, resolve_parents, updated_after, filters, ignore_availability, session):
    replicas = heapq.merge(_list_replicas_for_datasets(dataset_clause, state_clause, rse_clause, ignore_availability, updated_after, session), _list_replicas_for_files(file_clause, state_clause, files_wo_replica, rse_clause, ignore_availability, updated_after, session), _list_replicas_for_constituents(constituent_clause, state_clause, files_wo_replica, rse_clause, ignore_availability, updated_after, session), key=(lambda t: (t[0], t[1])))
    original_domain = deepcopy(domain)
    local_rses = []
    if (domain is None):
        if (client_location and ('site' in client_location) and client_location['site']):
            try:
                local_rses = [rse['id'] for rse in parse_expression(('site=%s' % client_location['site']), filter=filters, session=session)]
            except Exception:
                pass
    (file, tmp_protocols, rse_info, pfns_cache) = ({}, {}, {}, {})
    for (scope, name, archive_scope, archive_name, bytes, md5, adler32, path, state, rse_id, rse, rse_type, volatile) in replicas:
        pfns = []
        domain = deepcopy(original_domain)
        if (show_pfns and rse_id):
            if (rse_id not in rse_info):
                rse_info[rse_id] = rsemgr.get_rse_info(rse_id=rse_id, session=session)
            rse_info[rse_id]['priority_wan'] = {p['scheme']: p['domains']['wan']['read'] for p in rse_info[rse_id]['protocols'] if (p['domains']['wan']['read'] > 0)}
            rse_info[rse_id]['priority_lan'] = {p['scheme']: p['domains']['lan']['read'] for p in rse_info[rse_id]['protocols'] if (p['domains']['lan']['read'] > 0)}
            if (domain is None):
                domain = 'wan'
                if (local_rses and (rse_id in local_rses)):
                    domain = 'lan'
            if (rse_id not in tmp_protocols):
                rse_schemes = (schemes or [])
                if (not rse_schemes):
                    try:
                        if (domain == 'all'):
                            rse_schemes.append(rsemgr.select_protocol(rse_settings=rse_info[rse_id], operation='read', domain='wan')['scheme'])
                            rse_schemes.append(rsemgr.select_protocol(rse_settings=rse_info[rse_id], operation='read', domain='lan')['scheme'])
                        else:
                            rse_schemes.append(rsemgr.select_protocol(rse_settings=rse_info[rse_id], operation='read', domain=domain)['scheme'])
                    except exception.RSEProtocolNotSupported:
                        pass
                    except Exception:
                        print(format_exc())
                if (archive_scope and archive_name and ('root' not in rse_schemes)):
                    rse_schemes.append('root')
                protocols = []
                for s in rse_schemes:
                    try:
                        if (domain == 'all'):
                            protocols.append(('lan', rsemgr.create_protocol(rse_settings=rse_info[rse_id], operation='read', scheme=s, domain='lan'), rse_info[rse_id]['priority_lan'][s]))
                            protocols.append(('wan', rsemgr.create_protocol(rse_settings=rse_info[rse_id], operation='read', scheme=s, domain='wan'), rse_info[rse_id]['priority_wan'][s]))
                        else:
                            protocols.append((domain, rsemgr.create_protocol(rse_settings=rse_info[rse_id], operation='read', scheme=s, domain=domain), rse_info[rse_id][('priority_%s' % domain)][s]))
                    except exception.RSEProtocolNotSupported:
                        pass
                    except Exception:
                        print(format_exc())
                tmp_protocols[rse_id] = protocols
            for tmp_protocol in tmp_protocols[rse_id]:
                if (archive_scope and archive_name):
                    t_scope = archive_scope
                    t_name = archive_name
                else:
                    t_scope = scope
                    t_name = name
                protocol = tmp_protocol[1]
                if ('determinism_type' in protocol.attributes):
                    try:
                        path = pfns_cache[('%s:%s:%s' % (protocol.attributes['determinism_type'], t_scope.internal, t_name))]
                    except KeyError:
                        path = protocol._get_path(t_scope, t_name)
                        pfns_cache[('%s:%s:%s' % (protocol.attributes['determinism_type'], t_scope.internal, t_name))] = path
                try:
                    pfn = list(protocol.lfns2pfns(lfns={'scope': t_scope.external, 'name': t_name, 'path': path}).values())[0]
                    if (sign_urls and (protocol.attributes['scheme'] == 'https')):
                        service = get_rse_attribute('sign_url', rse_id=rse_id, session=session)
                        if (service and isinstance(service, list)):
                            pfn = get_signed_url(rse_id=rse_id, service=service[0], operation='read', url=pfn, lifetime=signature_lifetime)
                    if ((domain == 'wan') and (protocol.attributes['scheme'] in ['root', 'http', 'https']) and client_location):
                        if (('site' in client_location) and client_location['site']):
                            rse_site_attr = get_rse_attribute('site', rse_id, session=session)
                            replica_site = []
                            if (isinstance(rse_site_attr, list) and rse_site_attr):
                                replica_site = rse_site_attr[0]
                            if (client_location['site'] != replica_site):
                                cache_site = config_get('clientcachemap', client_location['site'], default=, session=session)
                                if (cache_site != ):
                                    selected_prefix = get_multi_cache_prefix(cache_site, t_name)
                                    if selected_prefix:
                                        pfn = ((('root://' + selected_prefix) + '//') + pfn.replace('davs://', 'root://'))
                                else:
                                    root_proxy_internal = config_get('root-proxy-internal', client_location['site'], default=, session=session)
                                    if root_proxy_internal:
                                        if (('storage.googleapis.com' in pfn) or ('atlas-google-cloud.cern.ch' in pfn) or ('amazonaws.com' in pfn)):
                                            pass
                                        else:
                                            pfn = ((('root://' + root_proxy_internal) + '//') + pfn.replace('davs://', 'https://'))
                    t_domain = tmp_protocol[0]
                    t_priority = tmp_protocol[2]
                    t_client_extract = False
                    if (archive_scope and archive_name):
                        t_domain = 'zip'
                        pfn = add_url_query(pfn, {'xrdcl.unzip': name})
                        if (protocol.attributes['scheme'] == 'root'):
                            t_client_extract = False
                            t_priority = (- 1)
                        else:
                            t_client_extract = True
                    pfns.append((pfn, t_domain, t_priority, t_client_extract))
                except Exception:
                    print(format_exc())
                if (protocol.attributes['scheme'] == 'srm'):
                    try:
                        file['space_token'] = protocol.attributes['extended_attributes']['space_token']
                    except KeyError:
                        file['space_token'] = None
        if (('scope' in file) and ('name' in file)):
            if ((file['scope'] == scope) and (file['name'] == name)):
                file['rses'][rse_id] += list(set([tmp_pfn[0] for tmp_pfn in pfns]))
                file['states'][rse_id] = str((state.name if state else state))
                if resolve_parents:
                    file['parents'] = [('%s:%s' % (parent['scope'].internal, parent['name'])) for parent in rucio.core.did.list_all_parent_dids(scope, name, session=session)]
                for tmp_pfn in pfns:
                    file['pfns'][tmp_pfn[0]] = {'rse_id': rse_id, 'rse': rse, 'type': str(rse_type.name), 'volatile': volatile, 'domain': tmp_pfn[1], 'priority': tmp_pfn[2], 'client_extract': tmp_pfn[3]}
            else:
                if resolve_parents:
                    file['parents'] = [('%s:%s' % (parent['scope'].internal, parent['name'])) for parent in rucio.core.did.list_all_parent_dids(file['scope'], file['name'], session=session)]
                tmp = sorted([(file['pfns'][p]['domain'], file['pfns'][p]['priority'], p) for p in file['pfns']])
                for i in range(0, len(tmp)):
                    file['pfns'][tmp[i][2]]['priority'] = (i + 1)
                    file['rses'] = {}
                    rse_pfns = []
                    for (t_rse, t_priority, t_pfn) in [(file['pfns'][t_pfn]['rse_id'], file['pfns'][t_pfn]['priority'], t_pfn) for t_pfn in file['pfns']]:
                        rse_pfns.append((t_rse, t_priority, t_pfn))
                    rse_pfns = sorted(rse_pfns)
                    for (t_rse, t_priority, t_pfn) in rse_pfns:
                        if (t_rse in file['rses']):
                            file['rses'][t_rse].append(t_pfn)
                        else:
                            file['rses'][t_rse] = [t_pfn]
                (yield file)
                file = {}
        if (not (('scope' in file) and ('name' in file))):
            (file['scope'], file['name']) = (scope, name)
            (file['bytes'], file['md5'], file['adler32']) = (bytes, md5, adler32)
            (file['pfns'], file['rses']) = ({}, defaultdict(list))
            file['states'] = {rse_id: str((state.name if state else state))}
            if resolve_parents:
                file['parents'] = [('%s:%s' % (parent['scope'].internal, parent['name'])) for parent in rucio.core.did.list_all_parent_dids(scope, name, session=session)]
            if rse_id:
                file['rses'][rse_id] = list(set([tmp_pfn[0] for tmp_pfn in pfns]))
                for tmp_pfn in pfns:
                    file['pfns'][tmp_pfn[0]] = {'rse_id': rse_id, 'rse': rse, 'type': str(rse_type.name), 'volatile': volatile, 'domain': tmp_pfn[1], 'priority': tmp_pfn[2], 'client_extract': tmp_pfn[3]}
    if ('pfns' in file):
        tmp = sorted([(file['pfns'][p]['domain'], file['pfns'][p]['priority'], p) for p in file['pfns']])
        for i in range(0, len(tmp)):
            file['pfns'][tmp[i][2]]['priority'] = (i + 1)
    if (('scope' in file) and ('name' in file)):
        file['rses'] = {}
        if resolve_parents:
            file['parents'] = [('%s:%s' % (parent['scope'].internal, parent['name'])) for parent in rucio.core.did.list_all_parent_dids(file['scope'], file['name'], session=session)]
        rse_pfns = []
        for (t_rse, t_priority, t_pfn) in [(file['pfns'][t_pfn]['rse_id'], file['pfns'][t_pfn]['priority'], t_pfn) for t_pfn in file['pfns']]:
            rse_pfns.append((t_rse, t_priority, t_pfn))
        rse_pfns = sorted(rse_pfns)
        for (t_rse, t_priority, t_pfn) in rse_pfns:
            if (t_rse in file['rses']):
                file['rses'][t_rse].append(t_pfn)
            else:
                file['rses'][t_rse] = [t_pfn]
        (yield file)
        file = {}
    for (scope, name, bytes, md5, adler32) in _list_files_wo_replicas(files_wo_replica, session):
        (yield {'scope': scope, 'name': name, 'bytes': bytes, 'md5': md5, 'adler32': adler32, 'pfns': {}, 'rses': defaultdict(list)})