code:
import hashlib
import itertools
import json
import re
import time
import urllib.error

from .common import InfoExtractor
from ..utils import (
    ExtractorError,
    decode_base_n,
    encode_base_n,
    float_or_none,
    format_field,
    get_element_by_attribute,
    int_or_none,
    lowercase_escape,
    str_or_none,
    str_to_int,
    traverse_obj,
    url_or_none,
    urlencode_postdata,
)

_ENCODING_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'

def _pk_to_id(id):
    """Source: https://stackoverflow.com/questions/24437823/getting-instagram-post-url-from-media-id"""
    return encode_base_n(int(id.split('_')[0]), table=_ENCODING_CHARS)

def _id_to_pk(shortcode):
    """Covert a shortcode to a numeric value"""
    return decode_base_n(shortcode[:11], table=_ENCODING_CHARS)

class InstagramBaseIE(InfoExtractor):
    _NETRC_MACHINE = 'instagram'
    _IS_LOGGED_IN = False

    _API_BASE_URL = 'https://i.instagram.com/api/v1'
    _LOGIN_URL = 'https://www.instagram.com/accounts/login'
    _API_HEADERS = {
        'X-IG-App-ID': '936619743392459',
        'X-ASBD-ID': '198387',
        'X-IG-WWW-Claim': '0',
        'Origin': 'https://www.instagram.com',
        'Accept': '*/*',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
    }

    def _perform_login(self, username, password):
        if self._IS_LOGGED_IN:
            return

        login_webpage = self._download_webpage(
            self._LOGIN_URL, None, note='Downloading login webpage', errnote='Failed to download login webpage')

        shared_data = self._parse_json(self._search_regex(
            r'window\._sharedData\s*=\s*({.+?});', login_webpage, 'shared data', default='{}'), None)

        login = self._download_json(
            f'{self._LOGIN_URL}/ajax/', None, note='Logging in', headers={
                **self._API_HEADERS,
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': shared_data['config']['csrf_token'],
                'X-Instagram-AJAX': shared_data['rollout_hash'],
                'Referer': 'https://www.instagram.com/',
            }, data=urlencode_postdata({
                'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{int(time.time())}:{password}',
                'username': username,
                'queryParams': '{}',
                'optIntoOneTap': 'false',
                'stopDeletionNonce': '',
                'trustedDeviceRecords': '{}',
            }))

        if not login.get('authenticated'):
            if login.get('message'):
                raise ExtractorError(f'Unable to login: {login["message"]}')
            elif login.get('user'):
                raise ExtractorError('Unable to login: Sorry, your password was incorrect. Please double-check your password.', expected=True)
            elif login.get('user') is False:
                raise ExtractorError('Unable to login: The username you entered doesn\'t belong to an account. Please check your username and try again.', expected=True)
            raise ExtractorError('Unable to login')
        InstagramBaseIE._IS_LOGGED_IN = True

    def _get_count(self, media, kind, *keys):
        return traverse_obj(
            media, (kind, 'count'), *((f'edge_media_{key}', 'count') for key in keys),
            expected_type=int_or_none)

    def _get_dimension(self, name, media, webpage=None):
        return (
            traverse_obj(media, ('dimensions', name), expected_type=int_or_none)
            or int_or_none(self._html_search_meta(
                (f'og:video:{name}', f'video:{name}'), webpage or '', default=None)))

    def _extract_nodes(self, nodes, is_direct=False):
        for idx, node in enumerate(nodes, start=1):
            if node.get('__typename') != 'GraphVideo' and node.get('is_video') is not True:
                continue

            video_id = node.get('shortcode')

            if is_direct:
                info = {
                    'id': video_id or node['id'],
                    'url': node.get('video_url'),
                    'width': self._get_dimension('width', node),
                    'height': self._get_dimension('height', node),
                    'http_headers': {
                        'Referer': 'https://www.instagram.com/',
                    }
                }
            elif not video_id:
                continue
            else:
                info = {
                    '_type': 'url',
                    'ie_key': 'Instagram',
                    'id': video_id,
                    'url': f'https://instagram.com/p/{video_id}',
                }

            yield {
                **info,
                'title': node.get('title') or (f'Video {idx}' if is_direct else None),
                'description': traverse_obj(
                    node, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type=str),
                'thumbnail': traverse_obj(
                    node, 'display_url', 'thumbnail_src', 'display_src', expected_type=url_or_none),
                'duration': float_or_none(node.get('video_duration')),
                'timestamp': int_or_none(node.get('taken_at_timestamp')),
                'view_count': int_or_none(node.get('video_view_count')),
                'comment_count': self._get_count(node, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
                'like_count': self._get_count(node, 'likes', 'preview_like'),
            }

    def _extract_product_media(self, product_media):
        media_id = product_media.get('code') or _pk_to_id(product_media.get('pk'))
        vcodec = product_media.get('video_codec')
        dash_manifest_raw = product_media.get('video_dash_manifest')
        videos_list = product_media.get('video_versions')
        if not (dash_manifest_raw or videos_list):
            return {}

        formats = [{
            'format_id': format.get('id'),
            'url': format.get('url'),
            'width': format.get('width'),
            'height': format.get('height'),
            'vcodec': vcodec,
        } for format in videos_list or []]
        if dash_manifest_raw:
            formats.extend(self._parse_mpd_formats(self._parse_xml(dash_manifest_raw, media_id), mpd_id='dash'))
        self._sort_formats(formats)

        thumbnails = [{
            'url': thumbnail.get('url'),
            'width': thumbnail.get('width'),
            'height': thumbnail.get('height')
        } for thumbnail in traverse_obj(product_media, ('image_versions2', 'candidates')) or []]
        return {
            'id': media_id,
            'duration': float_or_none(product_media.get('video_duration')),
            'formats': formats,
            'thumbnails': thumbnails
        }

    def _extract_product(self, product_info):
        if isinstance(product_info, list):
            product_info = product_info[0]

        user_info = product_info.get('user') or {}
        info_dict = {
            'id': _pk_to_id(traverse_obj(product_info, 'pk', 'id', expected_type=str_or_none)[:19]),
            'title': product_info.get('title') or f'Video by {user_info.get("username")}',
            'description': traverse_obj(product_info, ('caption', 'text'), expected_type=str_or_none),
            'timestamp': int_or_none(product_info.get('taken_at')),
            'channel': user_info.get('username'),
            'uploader': user_info.get('full_name'),
            'uploader_id': str_or_none(user_info.get('pk')),
            'view_count': int_or_none(product_info.get('view_count')),
            'like_count': int_or_none(product_info.get('like_count')),
            'comment_count': int_or_none(product_info.get('comment_count')),
            '__post_extractor': self.extract_comments(_pk_to_id(product_info.get('pk'))),
            'http_headers': {
                'Referer': 'https://www.instagram.com/',
            }
        }
        carousel_media = product_info.get('carousel_media')
        if carousel_media:
            return {
                '_type': 'playlist',
                **info_dict,
                'title': f'Post by {user_info.get("username")}',
                'entries': [{
                    **info_dict,
                    **self._extract_product_media(product_media),
                } for product_media in carousel_media],
            }

        return {
            **info_dict,
            **self._extract_product_media(product_info)
        }

    def _get_comments(self, video_id):
        comments_info = self._download_json(
            f'{self._API_BASE_URL}/media/{_id_to_pk(video_id)}/comments/?can_support_threading=true&permalink_enabled=false', video_id,
            fatal=False, errnote='Comments extraction failed', note='Downloading comments info', headers=self._API_HEADERS) or {}

        comment_data = traverse_obj(comments_info, ('edge_media_to_parent_comment', 'edges'), 'comments')
        for comment_dict in comment_data or []:
            yield {
                'author': traverse_obj(comment_dict, ('node', 'owner', 'username'), ('user', 'username')),
                'author_id': traverse_obj(comment_dict, ('node', 'owner', 'id'), ('user', 'pk')),
                'author_thumbnail': traverse_obj(comment_dict, ('node', 'owner', 'profile_pic_url'), ('user', 'profile_pic_url'), expected_type=url_or_none),
                'id': traverse_obj(comment_dict, ('node', 'id'), 'pk'),
                'text': traverse_obj(comment_dict, ('node', 'text'), 'text'),
                'like_count': traverse_obj(comment_dict, ('node', 'edge_liked_by', 'count'), 'comment_like_count', expected_type=int_or_none),
                'timestamp': traverse_obj(comment_dict, ('node', 'created_at'), 'created_at', expected_type=int_or_none),
            }

class InstagramIOSIE(InfoExtractor):
    IE_DESC = 'IOS instagram:// URL'
    _VALID_URL = r'instagram://media\?id=(?P<id>[\d_]+)'
    _TESTS = [{
        'url': 'instagram://media?id=482584233761418119',
        'md5': '0d2da106a9d2631273e192b372806516',
        'info_dict': {
            'id': 'aye83DjauH',
            'ext': 'mp4',
            'title': 'Video by naomipq',
            'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
            'thumbnail': r're:^https?://.*\.jpg',
            'duration': 0,
            'timestamp': 1371748545,
            'upload_date': '20130620',
            'uploader_id': 'naomipq',
            'uploader': 'B E A U T Y  F O R  A S H E S',
            'like_count': int,
            'comment_count': int,
            'comments': list,
        },
        'add_ie': ['Instagram']
    }]

    def _real_extract(self, url):
        video_id = _pk_to_id(self._match_id(url))
        return self.url_result(f'http://instagram.com/tv/{video_id}', InstagramIE, video_id)

class InstagramIE(InstagramBaseIE):
    _VALID_URL = r'(?P<url>https?://(?:www\.)?instagram\.com(?:/[^/]+)?/(?:p|tv|reel)/(?P<id>[^/?#&]+))'
    _EMBED_REGEX = [r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?instagram\.com/p/[^/]+/embed.*?)\1']
    _TESTS = [{
        'url': 'https://instagram.com/p/aye83DjauH/?foo=bar#abc',
        'md5': '0d2da106a9d2631273e192b372806516',
        'info_dict': {
            'id': 'aye83DjauH',
            'ext': 'mp4',
            'title': 'Video by naomipq',
            'description': 'md5:1f17f0ab29bd6fe2bfad705f58de3cb8',
            'thumbnail': r're:^https?://.*\.jpg',
            'duration': 8.747,
            'timestamp': 1371748545,
            'upload_date': '20130620',
            'uploader_id': '2815873',
            'uploader': 'B E A U T Y  F O R  A S H E S',
            'channel': 'naomipq',
            'like_count': int,
            'comment_count': int,
            'comments': list,
        },
        'expected_warnings': [
            'General metadata extraction failed',
            'Main webpage is locked behind the login page',
        ],
    }, {
        # reel
        'url': 'https://www.instagram.com/reel/Chunk8-jurw/',
        'md5': 'f6d8277f74515fa3ff9f5791426e42b1',
        'info_dict': {
            'id': 'Chunk8-jurw',
            'ext': 'mp4',
            'title': 'Video by instagram',
            'description': 'md5:c9cde483606ed6f80fbe9283a6a2b290',
            'thumbnail': r're:^https?://.*\.jpg',
            'duration': 5.016,
            'timestamp': 1661529231,
            'upload_date': '20220826',
            'uploader_id': '25025320',
            'uploader': 'Instagram',
            'channel': 'instagram',
            'like_count': int,
            'comment_count': int,
            'comments': list,
        },
        'expected_warnings': [
            'General metadata extraction failed',
            'Main webpage is locked behind the login page',
        ],
    }, {
        # multi video post
        'url': 'https://www.instagram.com/p/BQ0eAlwhDrw/',
        'playlist': [{
            'info_dict': {
                'id': 'BQ0dSaohpPW',
                'ext': 'mp4',
                'title': 'Video 1',
                'thumbnail': r're:^https?://.*\.jpg',
                'view_count': int,
            },
        }, {
            'info_dict': {
                'id': 'BQ0dTpOhuHT',
                'ext': 'mp4',
                'title': 'Video 2',
                'thumbnail': r're:^https?://.*\.jpg',
                'view_count': int,
            },
        }, {
            'info_dict': {
                'id': 'BQ0dT7RBFeF',
                'ext': 'mp4',
                'title': 'Video 3',
                'thumbnail': r're:^https?://.*\.jpg',
                'view_count': int,
            },
        }],
        'info_dict': {
            'id': 'BQ0eAlwhDrw',
            'title': 'Post by instagram',
            'description': 'md5:0f9203fc6a2ce4d228da5754bcf54957',
        },
        'expected_warnings': [
            'General metadata extraction failed',
            'Main webpage is locked behind the login page',
        ],
    }, {
        # IGTV
        'url': 'https://www.instagram.com/tv/BkfuX9UB-eK/',
        'info_dict': {
            'id': 'BkfuX9UB-eK',
            'ext': 'mp4',
            'title': 'Fingerboarding Tricks with @cass.fb',
            'thumbnail': r're:^https?://.*\.jpg',
            'duration': 53.83,
            'timestamp': 1530032919,
            'upload_date': '20180626',
            'uploader_id': '25025320',
            'uploader': 'Instagram',
            'channel': 'instagram',
            'like_count': int,
            'comment_count': int,
            'comments': list,
            'description': 'Meet Cass Hirst (@cass.fb), a fingerboarding pro who can perform tiny ollies and kickflips while blindfolded.',
        },
        'expected_warnings': [
            'General metadata extraction failed',
            'Main webpage is locked behind the login page',
        ],
    }, {
        'url': 'https://instagram.com/p/-Cmh1cukG2/',
        'only_matching': True,
    }, {
        'url': 'http://instagram.com/p/9o6LshA7zy/embed/',
        'only_matching': True,
    }, {
        'url': 'https://www.instagram.com/tv/aye83DjauH/',
        'only_matching': True,
    }, {
        'url': 'https://www.instagram.com/reel/CDUMkliABpa/',
        'only_matching': True,
    }, {
        'url': 'https://www.instagram.com/marvelskies.fc/reel/CWqAgUZgCku/',
        'only_matching': True,
    }]

    @classmethod
    def _extract_embed_urls(cls, url, webpage):
        res = tuple(super()._extract_embed_urls(url, webpage))
        if res:
            return res

        mobj = re.search(r'<a[^>]+href=([\'"])(?P<link>[^\'"]+)\1',
                         get_element_by_attribute('class', 'instagram-media', webpage) or '')
        if mobj:
            return [mobj.group('link')]

    def _real_extract(self, url):
        video_id, url = self._match_valid_url(url).group('id', 'url')
        media, webpage = {}, ''

        if self._get_cookies(url).get('sessionid'):
            info = traverse_obj(self._download_json(
                f'{self._API_BASE_URL}/media/{_id_to_pk(video_id)}/info/', video_id,
                fatal=False, errnote='Video info extraction failed',
                note='Downloading video info', headers=self._API_HEADERS), ('items', 0))
            if info:
                media.update(info)
                return self._extract_product(media)

        api_check = self._download_json(
            f'{self._API_BASE_URL}/web/get_ruling_for_content/?content_type=MEDIA&target_id={_id_to_pk(video_id)}',
            video_id, headers=self._API_HEADERS, fatal=False, note='Setting up session', errnote=False) or {}
        csrf_token = self._get_cookies('https://www.instagram.com').get('csrftoken')

        if not csrf_token:
            self.report_warning('No csrf token set by Instagram API', video_id)
        else:
            csrf_token = csrf_token.value if api_check.get('status') == 'ok' else None
            if not csrf_token:
                self.report_warning('Instagram API is not granting access', video_id)

        variables = {
            'shortcode': video_id,
            'child_comment_count': 3,
            'fetch_comment_count': 40,
            'parent_comment_count': 24,
            'has_threaded_comments': True,
        }
        general_info = self._download_json(
            'https://www.instagram.com/graphql/query/', video_id, fatal=False, errnote=False,
            headers={
                **self._API_HEADERS,
                'X-CSRFToken': csrf_token or '',
                'X-Requested-With': 'XMLHttpRequest',
                'Referer': url,
            }, query={
                'query_hash': '9f8827793ef34641b2fb195d4d41151c',
                'variables': json.dumps(variables, separators=(',', ':')),
            })
        media.update(traverse_obj(general_info, ('data', 'shortcode_media')) or {})

        if not general_info:
            self.report_warning('General metadata extraction failed (some metadata might be missing).', video_id)
            webpage, urlh = self._download_webpage_handle(url, video_id)
            shared_data = self._search_json(
                r'window\._sharedData\s*=', webpage, 'shared data', video_id, fatal=False) or {}

            if shared_data and self._LOGIN_URL not in urlh.geturl():
                media.update(traverse_obj(
                    shared_data, ('entry_data', 'PostPage', 0, 'graphql', 'shortcode_media'),
                    ('entry_data', 'PostPage', 0, 'media'), expected_type=dict) or {})
            else:
                self.report_warning('Main webpage is locked behind the login page. Retrying with embed webpage (some metadata might be missing).')
                webpage = self._download_webpage(
                    f'{url}/embed/', video_id, note='Downloading embed webpage', fatal=False)
                additional_data = self._search_json(
                    r'window\.__additionalDataLoaded\s*\(\s*[^,]+,\s*', webpage, 'additional data', video_id, fatal=False)
                if not additional_data and not media:
                    self.raise_login_required('Requested content is not available, rate-limit reached or login required')

                product_item = traverse_obj(additional_data, ('items', 0), expected_type=dict)
                if product_item:
                    media.update(product_item)
                    return self._extract_product(media)

                media.update(traverse_obj(
                    additional_data, ('graphql', 'shortcode_media'), 'shortcode_media', expected_type=dict) or {})

        username = traverse_obj(media, ('owner', 'username')) or self._search_regex(
            r'"owner"\s*:\s*{\s*"username"\s*:\s*"(.+?)"', webpage, 'username', fatal=False)

        description = (
            traverse_obj(media, ('edge_media_to_caption', 'edges', 0, 'node', 'text'), expected_type=str)
            or media.get('caption'))
        if not description:
            description = self._search_regex(
                r'"caption"\s*:\s*"(.+?)"', webpage, 'description', default=None)
            if description is not None:
                description = lowercase_escape(description)

        video_url = media.get('video_url')
        if not video_url:
            nodes = traverse_obj(media, ('edge_sidecar_to_children', 'edges', ..., 'node'), expected_type=dict) or []
            if nodes:
                return self.playlist_result(
                    self._extract_nodes(nodes, True), video_id,
                    format_field(username, None, 'Post by %s'), description)

            video_url = self._og_search_video_url(webpage, secure=False)

        formats = [{
            'url': video_url,
            'width': self._get_dimension('width', media, webpage),
            'height': self._get_dimension('height', media, webpage),
        }]
        dash = traverse_obj(media, ('dash_info', 'video_dash_manifest'))
        if dash:
            formats.extend(self._parse_mpd_formats(self._parse_xml(dash, video_id), mpd_id='dash'))
        self._sort_formats(formats)

        comment_data = traverse_obj(media, ('edge_media_to_parent_comment', 'edges'))
        comments = [{
            'author': traverse_obj(comment_dict, ('node', 'owner', 'username')),
            'author_id': traverse_obj(comment_dict, ('node', 'owner', 'id')),
            'id': traverse_obj(comment_dict, ('node', 'id')),
            'text': traverse_obj(comment_dict, ('node', 'text')),
            'timestamp': traverse_obj(comment_dict, ('node', 'created_at'), expected_type=int_or_none),
        } for comment_dict in comment_data] if comment_data else None

        display_resources = (
            media.get('display_resources')
            or [{'src': media.get(key)} for key in ('display_src', 'display_url')]
            or [{'src': self._og_search_thumbnail(webpage)}])
        thumbnails = [{
            'url': thumbnail['src'],
            'width': thumbnail.get('config_width'),
            'height': thumbnail.get('config_height'),
        } for thumbnail in display_resources if thumbnail.get('src')]

        return {
            'id': video_id,
            'formats': formats,
            'title': media.get('title') or 'Video by %s' % username,
            'description': description,
            'duration': float_or_none(media.get('video_duration')),
            'timestamp': traverse_obj(media, 'taken_at_timestamp', 'date', expected_type=int_or_none),
            'uploader_id': traverse_obj(media, ('owner', 'id')),
            'uploader': traverse_obj(media, ('owner', 'full_name')),
            'channel': username,
            'like_count': self._get_count(media, 'likes', 'preview_like') or str_to_int(self._search_regex(
                r'data-log-event="likeCountClick"[^>]*>[^\d]*([\d,\.]+)', webpage, 'like count', fatal=False)),
            'comment_count': self._get_count(media, 'comments', 'preview_comment', 'to_comment', 'to_parent_comment'),
            'comments': comments,
            'thumbnails': thumbnails,
            'http_headers': {
                'Referer': 'https://www.instagram.com/',
            }
        }

class InstagramPlaylistBaseIE(InstagramBaseIE):
    _gis_tmpl = None  # used to cache GIS request type

    def _parse_graphql(self, webpage, item_id):
        # Reads a webpage and returns its GraphQL data.
        return self._parse_json(
            self._search_regex(
                r'sharedData\s*=\s*({.+?})\s*;\s*[<\n]', webpage, 'data'),
            item_id)

    def _extract_graphql(self, data, url):
        # Parses GraphQL queries containing videos and generates a playlist.
        uploader_id = self._match_id(url)
        csrf_token = data['config']['csrf_token']
        rhx_gis = data.get('rhx_gis') or '3c7ca9dcefcf966d11dacf1f151335e8'

        cursor = ''
        for page_num in itertools.count(1):
            variables = {
                'first': 12,
                'after': cursor,
            }
            variables.update(self._query_vars_for(data))
            variables = json.dumps(variables)

            if self._gis_tmpl:
                gis_tmpls = [self._gis_tmpl]
            else:
                gis_tmpls = [
                    '%s' % rhx_gis,
                    '',
                    '%s:%s' % (rhx_gis, csrf_token),
                    '%s:%s:%s' % (rhx_gis, csrf_token, self.get_param('http_headers')['User-Agent']),
                ]

            # try all of the ways to generate a GIS query, and not only use the
            # first one that works, but cache it for future requests
            for gis_tmpl in gis_tmpls:
                try:
                    json_data = self._download_json(
                        'https://www.instagram.com/graphql/query/', uploader_id,
                        'Downloading JSON page %d' % page_num, headers={
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-Instagram-GIS': hashlib.md5(
                                ('%s:%s' % (gis_tmpl, variables)).encode('utf-8')).hexdigest(),
                        }, query={
                            'query_hash': self._QUERY_HASH,
                            'variables': variables,
                        })
                    media = self._parse_timeline_from(json_data)
                    self._gis_tmpl = gis_tmpl
                    break
                except ExtractorError as e:
                    # if it's an error caused by a bad query, and there are
                    # more GIS templates to try, ignore it and keep trying
                    if isinstance(e.cause, urllib.error.HTTPError) and e.cause.code == 403:
                        if gis_tmpl != gis_tmpls[-1]:
                            continue
                    raise

            nodes = traverse_obj(media, ('edges', ..., 'node'), expected_type=dict) or []
            if not nodes:
                break
            yield from self._extract_nodes(nodes)

            has_next_page = traverse_obj(media, ('page_info', 'has_next_page'))
            cursor = traverse_obj(media, ('page_info', 'end_cursor'), expected_type=str)
            if not has_next_page or not cursor:
                break

    def _real_extract(self, url):
        user_or_tag = self._match_id(url)
        webpage = self._download_webpage(url, user_or_tag)
        data = self._parse_graphql(webpage, user_or_tag)

        self._set_cookie('instagram.com', 'ig_pr', '1')

        return self.playlist_result(
            self._extract_graphql(data, url), user_or_tag, user_or_tag)

class InstagramUserIE(InstagramPlaylistBaseIE):
    _VALID_URL = r'https?://(?:www\.)?instagram\.com/(?P<id>[^/]{2,})/?(?:$|[?#])'
    IE_DESC = 'Instagram user profile'
    IE_NAME = 'instagram:user'
    _TESTS = [{
        'url': 'https://instagram.com/porsche',
        'info_dict': {
            'id': 'porsche',
            'title': 'porsche',
        },
        'playlist_count': 5,
        'params': {
            'extract_flat': True,
            'skip_download': True,
            'playlistend': 5,
        }
    }]

    _QUERY_HASH = '42323d64886122307be10013ad2dcc44',

    @staticmethod
    def _parse_timeline_from(data):
        # extracts the media timeline data from a GraphQL result
        return data['data']['user']['edge_owner_to_timeline_media']

    @staticmethod
    def _query_vars_for(data):
        # returns a dictionary of variables to add to the timeline query based
        # on the GraphQL of the original page
        return {
            'id': data['entry_data']['ProfilePage'][0]['graphql']['user']['id']
        }

class InstagramTagIE(InstagramPlaylistBaseIE):
    _VALID_URL = r'https?://(?:www\.)?instagram\.com/explore/tags/(?P<id>[^/]+)'
    IE_DESC = 'Instagram hashtag search URLs'
    IE_NAME = 'instagram:tag'
    _TESTS = [{
        'url': 'https://instagram.com/explore/tags/lolcats',
        'info_dict': {
            'id': 'lolcats',
            'title': 'lolcats',
        },
        'playlist_count': 50,
        'params': {
            'extract_flat': True,
            'skip_download': True,
            'playlistend': 50,
        }
    }]

    _QUERY_HASH = 'f92f56d47dc7a55b606908374b43a314',

    @staticmethod
    def _parse_timeline_from(data):
        # extracts the media timeline data from a GraphQL result
        return data['data']['hashtag']['edge_hashtag_to_media']

    @staticmethod
    def _query_vars_for(data):
        # returns a dictionary of variables to add to the timeline query based
        # on the GraphQL of the original page
        return {
            'tag_name':
                data['entry_data']['TagPage'][0]['graphql']['hashtag']['name']
        }

class InstagramStoryIE(InstagramBaseIE):
    _VALID_URL = r'https?://(?:www\.)?instagram\.com/stories/(?P<user>[^/]+)/(?P<id>\d+)'
    IE_NAME = 'instagram:story'

    _TESTS = [{
        'url': 'https://www.instagram.com/stories/highlights/18090946048123978/',
        'info_dict': {
            'id': '18090946048123978',
            'title': 'Rare',
        },
        'playlist_mincount': 50
    }]

    def _real_extract(self, url):
        username, story_id = self._match_valid_url(url).groups()
        story_info = self._download_webpage(url, story_id)
        user_info = self._search_json(r'"user":', story_info, 'user info', story_id, fatal=False)
        if not user_info:
            self.raise_login_required('This content is unreachable')
        user_id = user_info.get('id')

        story_info_url = user_id if username != 'highlights' else f'highlight:{story_id}'
        videos = traverse_obj(self._download_json(
            f'{self._API_BASE_URL}/feed/reels_media/?reel_ids={story_info_url}',
            story_id, errnote=False, fatal=False, headers=self._API_HEADERS), 'reels')
        if not videos:
            self.raise_login_required('You need to log in to access this content')

        full_name = traverse_obj(videos, (f'highlight:{story_id}', 'user', 'full_name'), (str(user_id), 'user', 'full_name'))
        story_title = traverse_obj(videos, (f'highlight:{story_id}', 'title'))
        if not story_title:
            story_title = f'Story by {username}'

        highlights = traverse_obj(videos, (f'highlight:{story_id}', 'items'), (str(user_id), 'items'))
        info_data = []
        for highlight in highlights:
            highlight_data = self._extract_product(highlight)
            if highlight_data.get('formats'):
                info_data.append({
                    **highlight_data,
                    'uploader': full_name,
                    'uploader_id': user_id,
                })
        return self.playlist_result(info_data, playlist_id=story_id, playlist_title=story_title)


code:
from .common import InfoExtractor
from ..utils import unified_timestamp

class InternazionaleIE(InfoExtractor):
    _VALID_URL = r'https?://(?:www\.)?internazionale\.it/video/(?:[^/]+/)*(?P<id>[^/?#&]+)'
    _TESTS = [{
        'url': 'https://www.internazionale.it/video/2015/02/19/richard-linklater-racconta-una-scena-di-boyhood',
        'md5': '3e39d32b66882c1218e305acbf8348ca',
        'info_dict': {
            'id': '265968',
            'display_id': 'richard-linklater-racconta-una-scena-di-boyhood',
            'ext': 'mp4',
            'title': 'Richard Linklater racconta una scena di Boyhood',
            'description': 'md5:efb7e5bbfb1a54ae2ed5a4a015f0e665',
            'timestamp': 1424354635,
            'upload_date': '20150219',
            'thumbnail': r're:^https?://.*\.jpg$',
        },
    }, {
        'url': 'https://www.internazionale.it/video/2018/08/29/telefono-stare-con-noi-stessi',
        'md5': '9db8663704cab73eb972d1cee0082c79',
        'info_dict': {
            'id': '761344',
            'display_id': 'telefono-stare-con-noi-stessi',
            'ext': 'mp4',
            'title': 'Usiamo il telefono per evitare di stare con noi stessi',
            'description': 'md5:75ccfb0d6bcefc6e7428c68b4aa1fe44',
            'timestamp': 1535528954,
            'upload_date': '20180829',
            'thumbnail': r're:^https?://.*\.jpg$',
        },
    }]

    def _real_extract(self, url):
        display_id = self._match_id(url)

        webpage = self._download_webpage(url, display_id)

        DATA_RE = r'data-%s=(["\'])(?P<value>(?:(?!\1).)+)\1'

        title = self._search_regex(
            DATA_RE % 'video-title', webpage, 'title', default=None,
            group='value') or self._og_search_title(webpage)

        video_id = self._search_regex(
            DATA_RE % 'job-id', webpage, 'video id', group='value')
        video_path = self._search_regex(
            DATA_RE % 'video-path', webpage, 'video path', group='value')
        video_available_abroad = self._search_regex(
            DATA_RE % 'video-available_abroad', webpage,
            'video available aboard', default='1', group='value')
        video_available_abroad = video_available_abroad == '1'

        video_base = 'https://video%s.internazionale.it/%s/%s.' % \
            ('' if video_available_abroad else '-ita', video_path, video_id)

        formats = self._extract_m3u8_formats(
            video_base + 'm3u8', display_id, 'mp4',
            entry_protocol='m3u8_native', m3u8_id='hls', fatal=False)
        formats.extend(self._extract_mpd_formats(
            video_base + 'mpd', display_id, mpd_id='dash', fatal=False))
        self._sort_formats(formats)

        timestamp = unified_timestamp(self._html_search_meta(
            'article:published_time', webpage, 'timestamp'))

        return {
            'id': video_id,
            'display_id': display_id,
            'title': title,
            'thumbnail': self._og_search_thumbnail(webpage),
            'description': self._og_search_description(webpage),
            'timestamp': timestamp,
            'formats': formats,
        }

repo_name: Lesmiscore/ytdl


code:
import json
import re

from .common import InfoExtractor
from ..utils import parse_qs

class InternetVideoArchiveIE(InfoExtractor):
    _VALID_URL = r'https?://video\.internetvideoarchive\.net/(?:player|flash/players)/.*?\?.*?publishedid.*?'

    _TEST = {
        'url': 'http://video.internetvideoarchive.net/player/6/configuration.ashx?customerid=69249&publishedid=194487&reporttag=vdbetatitle&playerid=641&autolist=0&domain=www.videodetective.com&maxrate=high&minrate=low&socialplayer=false',
        'info_dict': {
            'id': '194487',
            'ext': 'mp4',
            'title': 'Kick-Ass 2',
            'description': 'md5:c189d5b7280400630a1d3dd17eaa8d8a',
        },
        'params': {
            # m3u8 download
            'skip_download': True,
        },
    }

    @staticmethod
    def _build_json_url(query):
        return 'http://video.internetvideoarchive.net/player/6/configuration.ashx?' + query

    def _real_extract(self, url):
        query = parse_qs(url)
        video_id = query['publishedid'][0]
        data = self._download_json(
            'https://video.internetvideoarchive.net/videojs7/videojs7.ivasettings.ashx',
            video_id, data=json.dumps({
                'customerid': query['customerid'][0],
                'publishedid': video_id,
            }).encode())
        title = data['Title']
        formats = self._extract_m3u8_formats(
            data['VideoUrl'], video_id, 'mp4',
            'm3u8_native', m3u8_id='hls', fatal=False)
        file_url = formats[0]['url']
        if '.ism/' in file_url:
            replace_url = lambda x: re.sub(r'\.ism/[^?]+', '.ism/' + x, file_url)
            formats.extend(self._extract_f4m_formats(
                replace_url('.f4m'), video_id, f4m_id='hds', fatal=False))
            formats.extend(self._extract_mpd_formats(
                replace_url('.mpd'), video_id, mpd_id='dash', fatal=False))
            formats.extend(self._extract_ism_formats(
                replace_url('Manifest'), video_id, ism_id='mss', fatal=False))
        self._sort_formats(formats)

        return {
            'id': video_id,
            'title': title,
            'formats': formats,
            'thumbnail': data.get('PosterUrl'),
            'description': data.get('Description'),
        }


code:
import re
import time

from .common import InfoExtractor
from ..utils import (
    determine_ext,
    js_to_json,
    urlencode_postdata,
    ExtractorError,
    parse_qs
)

class IPrimaIE(InfoExtractor):
    _VALID_URL = r'https?://(?!cnn)(?:[^/]+)\.iprima\.cz/(?:[^/]+/)*(?P<id>[^/?#&]+)'
    _GEO_BYPASS = False
    _NETRC_MACHINE = 'iprima'
    _LOGIN_URL = 'https://auth.iprima.cz/oauth2/login'
    _TOKEN_URL = 'https://auth.iprima.cz/oauth2/token'
    access_token = None

    _TESTS = [{
        'url': 'https://prima.iprima.cz/particka/92-epizoda',
        'info_dict': {
            'id': 'p51388',
            'ext': 'mp4',
            'title': 'Partička (92)',
            'description': 'md5:859d53beae4609e6dd7796413f1b6cac',
            'upload_date': '20201103',
            'timestamp': 1604437480,
        },
        'params': {
            'skip_download': True,  # m3u8 download
        },
    }, {
        'url': 'http://play.iprima.cz/particka/particka-92',
        'only_matching': True,
    }, {
        # geo restricted
        'url': 'http://play.iprima.cz/closer-nove-pripady/closer-nove-pripady-iv-1',
        'only_matching': True,
    }, {
        'url': 'https://prima.iprima.cz/my-little-pony/mapa-znameni-2-2',
        'only_matching': True,
    }, {
        'url': 'https://prima.iprima.cz/porady/jak-se-stavi-sen/rodina-rathousova-praha',
        'only_matching': True,
    }, {
        'url': 'http://www.iprima.cz/filmy/desne-rande',
        'only_matching': True,
    }, {
        'url': 'https://zoom.iprima.cz/10-nejvetsich-tajemstvi-zahad/posvatna-mista-a-stavby',
        'only_matching': True,
    }, {
        'url': 'https://krimi.iprima.cz/mraz-0/sebevrazdy',
        'only_matching': True,
    }, {
        'url': 'https://cool.iprima.cz/derava-silnice-nevadi',
        'only_matching': True,
    }, {
        'url': 'https://love.iprima.cz/laska-az-za-hrob/slib-dany-bratrovi',
        'only_matching': True,
    }]

    def _perform_login(self, username, password):
        if self.access_token:
            return

        login_page = self._download_webpage(
            self._LOGIN_URL, None, note='Downloading login page',
            errnote='Downloading login page failed')

        login_form = self._hidden_inputs(login_page)

        login_form.update({
            '_email': username,
            '_password': password})

        _, login_handle = self._download_webpage_handle(
            self._LOGIN_URL, None, data=urlencode_postdata(login_form),
            note='Logging in')

        code = parse_qs(login_handle.geturl()).get('code')[0]
        if not code:
            raise ExtractorError('Login failed', expected=True)

        token_request_data = {
            'scope': 'openid+email+profile+phone+address+offline_access',
            'client_id': 'prima_sso',
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': 'https://auth.iprima.cz/sso/auth-check'}

        token_data = self._download_json(
            self._TOKEN_URL, None,
            note='Downloading token', errnote='Downloading token failed',
            data=urlencode_postdata(token_request_data))

        self.access_token = token_data.get('access_token')
        if self.access_token is None:
            raise ExtractorError('Getting token failed', expected=True)

    def _real_initialize(self):
        if not self.access_token:
            self.raise_login_required('Login is required to access any iPrima content', method='password')

    def _raise_access_error(self, error_code):
        if error_code == 'PLAY_GEOIP_DENIED':
            self.raise_geo_restricted(countries=['CZ'], metadata_available=True)
        elif error_code is not None:
            self.raise_no_formats('Access to stream infos forbidden', expected=True)

    def _real_extract(self, url):
        video_id = self._match_id(url)

        webpage = self._download_webpage(url, video_id)

        title = self._html_search_meta(
            ['og:title', 'twitter:title'],
            webpage, 'title', default=None)

        video_id = self._search_regex((
            r'productId\s*=\s*([\'"])(?P<id>p\d+)\1',
            r'pproduct_id\s*=\s*([\'"])(?P<id>p\d+)\1'),
            webpage, 'real id', group='id')

        metadata = self._download_json(
            f'https://api.play-backend.iprima.cz/api/v1//products/id-{video_id}/play',
            video_id, note='Getting manifest URLs', errnote='Failed to get manifest URLs',
            headers={'X-OTT-Access-Token': self.access_token},
            expected_status=403)

        self._raise_access_error(metadata.get('errorCode'))

        stream_infos = metadata.get('streamInfos')
        formats = []
        if stream_infos is None:
            self.raise_no_formats('Reading stream infos failed', expected=True)
        else:
            for manifest in stream_infos:
                manifest_type = manifest.get('type')
                manifest_url = manifest.get('url')
                ext = determine_ext(manifest_url)
                if manifest_type == 'HLS' or ext == 'm3u8':
                    formats += self._extract_m3u8_formats(
                        manifest_url, video_id, 'mp4', entry_protocol='m3u8_native',
                        m3u8_id='hls', fatal=False)
                elif manifest_type == 'DASH' or ext == 'mpd':
                    formats += self._extract_mpd_formats(
                        manifest_url, video_id, mpd_id='dash', fatal=False)
            self._sort_formats(formats)

        final_result = self._search_json_ld(webpage, video_id) or {}
        final_result.update({
            'id': video_id,
            'title': title,
            'thumbnail': self._html_search_meta(
                ['thumbnail', 'og:image', 'twitter:image'],
                webpage, 'thumbnail', default=None),
            'formats': formats,
            'description': self._html_search_meta(
                ['description', 'og:description', 'twitter:description'],
                webpage, 'description', default=None)})

        return final_result

class IPrimaCNNIE(InfoExtractor):
    _VALID_URL = r'https?://cnn\.iprima\.cz/(?:[^/]+/)*(?P<id>[^/?#&]+)'
    _GEO_BYPASS = False

    _TESTS = [{
        'url': 'https://cnn.iprima.cz/porady/strunc/24072020-koronaviru-mam-plne-zuby-strasit-druhou-vlnou-je-absurdni-rika-senatorka-dernerova',
        'info_dict': {
            'id': 'p716177',
            'ext': 'mp4',
            'title': 'md5:277c6b1ed0577e51b40ddd35602ff43e',
        },
        'params': {
            'skip_download': 'm3u8'
        }
    }]

    def _real_extract(self, url):
        video_id = self._match_id(url)

        self._set_cookie('play.iprima.cz', 'ott_adult_confirmed', '1')

        webpage = self._download_webpage(url, video_id)

        title = self._og_search_title(
            webpage, default=None) or self._search_regex(
            r'<h1>([^<]+)', webpage, 'title')

        video_id = self._search_regex(
            (r'<iframe[^>]+\bsrc=["\'](?:https?:)?//(?:api\.play-backend\.iprima\.cz/prehravac/embedded|prima\.iprima\.cz/[^/]+/[^/]+)\?.*?\bid=(p\d+)',
             r'data-product="([^"]+)">',
             r'id=["\']player-(p\d+)"',
             r'playerId\s*:\s*["\']player-(p\d+)',
             r'\bvideos\s*=\s*["\'](p\d+)'),
            webpage, 'real id')

        playerpage = self._download_webpage(
            'http://play.iprima.cz/prehravac/init',
            video_id, note='Downloading player', query={
                '_infuse': 1,
                '_ts': round(time.time()),
                'productId': video_id,
            }, headers={'Referer': url})

        formats = []

        def extract_formats(format_url, format_key=None, lang=None):
            ext = determine_ext(format_url)
            new_formats = []
            if format_key == 'hls' or ext == 'm3u8':
                new_formats = self._extract_m3u8_formats(
                    format_url, video_id, 'mp4', entry_protocol='m3u8_native',
                    m3u8_id='hls', fatal=False)
            elif format_key == 'dash' or ext == 'mpd':
                return
                new_formats = self._extract_mpd_formats(
                    format_url, video_id, mpd_id='dash', fatal=False)
            if lang:
                for f in new_formats:
                    if not f.get('language'):
                        f['language'] = lang
            formats.extend(new_formats)

        options = self._parse_json(
            self._search_regex(
                r'(?s)(?:TDIPlayerOptions|playerOptions)\s*=\s*({.+?});\s*\]\]',
                playerpage, 'player options', default='{}'),
            video_id, transform_source=js_to_json, fatal=False)
        if options:
            for key, tracks in options.get('tracks', {}).items():
                if not isinstance(tracks, list):
                    continue
                for track in tracks:
                    src = track.get('src')
                    if src:
                        extract_formats(src, key.lower(), track.get('lang'))

        if not formats:
            for _, src in re.findall(r'src["\']\s*:\s*(["\'])(.+?)\1', playerpage):
                extract_formats(src)

        if not formats and '>GEO_IP_NOT_ALLOWED<' in playerpage:
            self.raise_geo_restricted(countries=['CZ'], metadata_available=True)

        self._sort_formats(formats)

        return {
            'id': video_id,
            'title': title,
            'thumbnail': self._og_search_thumbnail(webpage, default=None),
            'formats': formats,
            'description': self._og_search_description(webpage, default=None),
        }


code:
import hashlib
import itertools
import re
import time

from .common import InfoExtractor
from ..compat import (
    compat_str,
    compat_urllib_parse_urlencode,
    compat_urllib_parse_unquote
)
from .openload import PhantomJSwrapper
from ..utils import (
    clean_html,
    decode_packed_codes,
    ExtractorError,
    float_or_none,
    format_field,
    get_element_by_id,
    get_element_by_attribute,
    int_or_none,
    js_to_json,
    ohdave_rsa_encrypt,
    parse_age_limit,
    parse_duration,
    parse_iso8601,
    parse_resolution,
    qualities,
    remove_start,
    str_or_none,
    traverse_obj,
    urljoin,
)

def md5_text(text):
    return hashlib.md5(text.encode('utf-8')).hexdigest()

class IqiyiSDK:
    def __init__(self, target, ip, timestamp):
        self.target = target
        self.ip = ip
        self.timestamp = timestamp

    @staticmethod
    def split_sum(data):
        return compat_str(sum(map(lambda p: int(p, 16), list(data))))

    @staticmethod
    def digit_sum(num):
        if isinstance(num, int):
            num = compat_str(num)
        return compat_str(sum(map(int, num)))

    def even_odd(self):
        even = self.digit_sum(compat_str(self.timestamp)[::2])
        odd = self.digit_sum(compat_str(self.timestamp)[1::2])
        return even, odd

    def preprocess(self, chunksize):
        self.target = md5_text(self.target)
        chunks = []
        for i in range(32 // chunksize):
            chunks.append(self.target[chunksize * i:chunksize * (i + 1)])
        if 32 % chunksize:
            chunks.append(self.target[32 - 32 % chunksize:])
        return chunks, list(map(int, self.ip.split('.')))

    def mod(self, modulus):
        chunks, ip = self.preprocess(32)
        self.target = chunks[0] + ''.join(map(lambda p: compat_str(p % modulus), ip))

    def split(self, chunksize):
        modulus_map = {
            4: 256,
            5: 10,
            8: 100,
        }

        chunks, ip = self.preprocess(chunksize)
        ret = ''
        for i in range(len(chunks)):
            ip_part = compat_str(ip[i] % modulus_map[chunksize]) if i < 4 else ''
            if chunksize == 8:
                ret += ip_part + chunks[i]
            else:
                ret += chunks[i] + ip_part
        self.target = ret

    def handle_input16(self):
        self.target = md5_text(self.target)
        self.target = self.split_sum(self.target[:16]) + self.target + self.split_sum(self.target[16:])

    def handle_input8(self):
        self.target = md5_text(self.target)
        ret = ''
        for i in range(4):
            part = self.target[8 * i:8 * (i + 1)]
            ret += self.split_sum(part) + part
        self.target = ret

    def handleSum(self):
        self.target = md5_text(self.target)
        self.target = self.split_sum(self.target) + self.target

    def date(self, scheme):
        self.target = md5_text(self.target)
        d = time.localtime(self.timestamp)
        strings = {
            'y': compat_str(d.tm_year),
            'm': '%02d' % d.tm_mon,
            'd': '%02d' % d.tm_mday,
        }
        self.target += ''.join(map(lambda c: strings[c], list(scheme)))

    def split_time_even_odd(self):
        even, odd = self.even_odd()
        self.target = odd + md5_text(self.target) + even

    def split_time_odd_even(self):
        even, odd = self.even_odd()
        self.target = even + md5_text(self.target) + odd

    def split_ip_time_sum(self):
        chunks, ip = self.preprocess(32)
        self.target = compat_str(sum(ip)) + chunks[0] + self.digit_sum(self.timestamp)

    def split_time_ip_sum(self):
        chunks, ip = self.preprocess(32)
        self.target = self.digit_sum(self.timestamp) + chunks[0] + compat_str(sum(ip))

class IqiyiSDKInterpreter:
    def __init__(self, sdk_code):
        self.sdk_code = sdk_code

    def run(self, target, ip, timestamp):
        self.sdk_code = decode_packed_codes(self.sdk_code)

        functions = re.findall(r'input=([a-zA-Z0-9]+)\(input', self.sdk_code)

        sdk = IqiyiSDK(target, ip, timestamp)

        other_functions = {
            'handleSum': sdk.handleSum,
            'handleInput8': sdk.handle_input8,
            'handleInput16': sdk.handle_input16,
            'splitTimeEvenOdd': sdk.split_time_even_odd,
            'splitTimeOddEven': sdk.split_time_odd_even,
            'splitIpTimeSum': sdk.split_ip_time_sum,
            'splitTimeIpSum': sdk.split_time_ip_sum,
        }
        for function in functions:
            if re.match(r'mod\d+', function):
                sdk.mod(int(function[3:]))
            elif re.match(r'date[ymd]{3}', function):
                sdk.date(function[4:])
            elif re.match(r'split\d+', function):
                sdk.split(int(function[5:]))
            elif function in other_functions:
                other_functions[function]()
            else:
                raise ExtractorError('Unknown function %s' % function)

        return sdk.target

class IqiyiIE(InfoExtractor):
    IE_NAME = 'iqiyi'
    IE_DESC = '爱奇艺'

    _VALID_URL = r'https?://(?:(?:[^.]+\.)?iqiyi\.com|www\.pps\.tv)/.+\.html'

    _NETRC_MACHINE = 'iqiyi'

    _TESTS = [{
        'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
        # MD5 checksum differs on my machine and Travis CI
        'info_dict': {
            'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
            'ext': 'mp4',
            'title': '美国德州空中惊现奇异云团 酷似UFO',
        }
    }, {
        'url': 'http://www.iqiyi.com/v_19rrhnnclk.html',
        'md5': 'b7dc800a4004b1b57749d9abae0472da',
        'info_dict': {
            'id': 'e3f585b550a280af23c98b6cb2be19fb',
            'ext': 'mp4',
            # This can be either Simplified Chinese or Traditional Chinese
            'title': r're:^(?:名侦探柯南 国语版：第752集 迫近灰原秘密的黑影 下篇|名偵探柯南 國語版：第752集 迫近灰原秘密的黑影 下篇)$',
        },
        'skip': 'Geo-restricted to China',
    }, {
        'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html',
        'only_matching': True,
    }, {
        'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html',
        'only_matching': True,
    }, {
        'url': 'http://yule.iqiyi.com/pcb.html',
        'info_dict': {
            'id': '4a0af228fddb55ec96398a364248ed7f',
            'ext': 'mp4',
            'title': '第2017-04-21期 女艺人频遭极端粉丝骚扰',
        },
    }, {
        # VIP-only video. The first 2 parts (6 minutes) are available without login
        # MD5 sums omitted as values are different on Travis CI and my machine
        'url': 'http://www.iqiyi.com/v_19rrny4w8w.html',
        'info_dict': {
            'id': 'f3cf468b39dddb30d676f89a91200dc1',
            'ext': 'mp4',
            'title': '泰坦尼克号',
        },
        'skip': 'Geo-restricted to China',
    }, {
        'url': 'http://www.iqiyi.com/a_19rrhb8ce1.html',
        'info_dict': {
            'id': '202918101',
            'title': '灌篮高手 国语版',
        },
        'playlist_count': 101,
    }, {
        'url': 'http://www.pps.tv/w_19rrbav0ph.html',
        'only_matching': True,
    }]

    _FORMATS_MAP = {
        '96': 1,    # 216p, 240p
        '1': 2,     # 336p, 360p
        '2': 3,     # 480p, 504p
        '21': 4,    # 504p
        '4': 5,     # 720p
        '17': 5,    # 720p
        '5': 6,     # 1072p, 1080p
        '18': 7,    # 1080p
    }

    @staticmethod
    def _rsa_fun(data):
        # public key extracted from http://static.iqiyi.com/js/qiyiV2/20160129180840/jobs/i18n/i18nIndex.js
        N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
        e = 65537

        return ohdave_rsa_encrypt(data, e, N)

    def _perform_login(self, username, password):

        data = self._download_json(
            'http://kylin.iqiyi.com/get_token', None,
            note='Get token for logging', errnote='Unable to get token for logging')
        sdk = data['sdk']
        timestamp = int(time.time())
        target = '/apis/reglogin/login.action?lang=zh_TW&area_code=null&email=%s&passwd=%s&agenttype=1&from=undefined&keeplogin=0&piccode=&fromurl=&_pos=1' % (
            username, self._rsa_fun(password.encode('utf-8')))

        interp = IqiyiSDKInterpreter(sdk)
        sign = interp.run(target, data['ip'], timestamp)

        validation_params = {
            'target': target,
            'server': 'BEA3AA1908656AABCCFF76582C4C6660',
            'token': data['token'],
            'bird_src': 'f8d91d57af224da7893dd397d52d811a',
            'sign': sign,
            'bird_t': timestamp,
        }
        validation_result = self._download_json(
            'http://kylin.iqiyi.com/validate?' + compat_urllib_parse_urlencode(validation_params), None,
            note='Validate credentials', errnote='Unable to validate credentials')

        MSG_MAP = {
            'P00107': 'please login via the web interface and enter the CAPTCHA code',
            'P00117': 'bad username or password',
        }

        code = validation_result['code']
        if code != 'A00000':
            msg = MSG_MAP.get(code)
            if not msg:
                msg = 'error %s' % code
                if validation_result.get('msg'):
                    msg += ': ' + validation_result['msg']
            self.report_warning('unable to log in: ' + msg)
            return False

        return True

    def get_raw_data(self, tvid, video_id):
        tm = int(time.time() * 1000)

        key = 'd5fb4bd9d50c4be6948c97edd7254b0e'
        sc = md5_text(compat_str(tm) + key + tvid)
        params = {
            'tvid': tvid,
            'vid': video_id,
            'src': '76f90cbd92f94a2e925d83e8ccd22cb7',
            'sc': sc,
            't': tm,
        }

        return self._download_json(
            'http://cache.m.iqiyi.com/jp/tmts/%s/%s/' % (tvid, video_id),
            video_id, transform_source=lambda s: remove_start(s, 'var tvInfoJs='),
            query=params, headers=self.geo_verification_headers())

    def _extract_playlist(self, webpage):
        PAGE_SIZE = 50

        links = re.findall(
            r'<a[^>]+class="site-piclist_pic_link"[^>]+href="(http://www\.iqiyi\.com/.+\.html)"',
            webpage)
        if not links:
            return

        album_id = self._search_regex(
            r'albumId\s*:\s*(\d+),', webpage, 'album ID')
        album_title = self._search_regex(
            r'data-share-title="([^"]+)"', webpage, 'album title', fatal=False)

        entries = list(map(self.url_result, links))

        # Start from 2 because links in the first page are already on webpage
        for page_num in itertools.count(2):
            pagelist_page = self._download_webpage(
                'http://cache.video.qiyi.com/jp/avlist/%s/%d/%d/' % (album_id, page_num, PAGE_SIZE),
                album_id,
                note='Download playlist page %d' % page_num,
                errnote='Failed to download playlist page %d' % page_num)
            pagelist = self._parse_json(
                remove_start(pagelist_page, 'var tvInfoJs='), album_id)
            vlist = pagelist['data']['vlist']
            for item in vlist:
                entries.append(self.url_result(item['vurl']))
            if len(vlist) < PAGE_SIZE:
                break

        return self.playlist_result(entries, album_id, album_title)

    def _real_extract(self, url):
        webpage = self._download_webpage(
            url, 'temp_id', note='download video page')

        # There's no simple way to determine whether an URL is a playlist or not
        # Sometimes there are playlist links in individual videos, so treat it
        # as a single video first
        tvid = self._search_regex(
            r'data-(?:player|shareplattrigger)-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid', default=None)
        if tvid is None:
            playlist_result = self._extract_playlist(webpage)
            if playlist_result:
                return playlist_result
            raise ExtractorError('Can\'t find any video')

        video_id = self._search_regex(
            r'data-(?:player|shareplattrigger)-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')

        formats = []
        for _ in range(5):
            raw_data = self.get_raw_data(tvid, video_id)

            if raw_data['code'] != 'A00000':
                if raw_data['code'] == 'A00111':
                    self.raise_geo_restricted()
                raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])

            data = raw_data['data']

            for stream in data['vidl']:
                if 'm3utx' not in stream:
                    continue
                vd = compat_str(stream['vd'])
                formats.append({
                    'url': stream['m3utx'],
                    'format_id': vd,
                    'ext': 'mp4',
                    'quality': self._FORMATS_MAP.get(vd, -1),
                    'protocol': 'm3u8_native',
                })

            if formats:
                break

            self._sleep(5, video_id)

        self._sort_formats(formats)
        title = (get_element_by_id('widget-videotitle', webpage)
                 or clean_html(get_element_by_attribute('class', 'mod-play-tit', webpage))
                 or self._html_search_regex(r'<span[^>]+data-videochanged-title="word"[^>]*>([^<]+)</span>', webpage, 'title'))

        return {
            'id': video_id,
            'title': title,
            'formats': formats,
        }

class IqIE(InfoExtractor):
    IE_NAME = 'iq.com'
    IE_DESC = 'International version of iQiyi'
    _VALID_URL = r'https?://(?:www\.)?iq\.com/play/(?:[\w%-]*-)?(?P<id>\w+)'
    _TESTS = [{
        'url': 'https://www.iq.com/play/one-piece-episode-1000-1ma1i6ferf4',
        'md5': '2d7caf6eeca8a32b407094b33b757d39',
        'info_dict': {
            'ext': 'mp4',
            'id': '1ma1i6ferf4',
            'title': '航海王 第1000集',
            'description': 'Subtitle available on Sunday 4PM（GMT+8）.',
            'duration': 1430,
            'timestamp': 1637488203,
            'upload_date': '20211121',
            'episode_number': 1000,
            'episode': 'Episode 1000',
            'series': 'One Piece',
            'age_limit': 13,
            'average_rating': float,
        },
        'params': {
            'format': '500',
        },
        'expected_warnings': ['format is restricted']
    }, {
        # VIP-restricted video
        'url': 'https://www.iq.com/play/mermaid-in-the-fog-2021-gbdpx13bs4',
        'only_matching': True
    }]
    _BID_TAGS = {
        '100': '240P',
        '200': '360P',
        '300': '480P',
        '500': '720P',
        '600': '1080P',
        '610': '1080P50',
        '700': '2K',
        '800': '4K',
    }
    _LID_TAGS = {
        '1': 'zh_CN',
        '2': 'zh_TW',
        '3': 'en',
        '4': 'kor',
        '18': 'th',
        '21': 'my',
        '23': 'vi',
        '24': 'id',
        '26': 'es',
        '28': 'ar',
    }

    _DASH_JS = '''
        console.log(page.evaluate(function() {
            var tvid = "%(tvid)s"; var vid = "%(vid)s"; var src = "%(src)s";
            var uid = "%(uid)s"; var dfp = "%(dfp)s"; var mode = "%(mode)s"; var lang = "%(lang)s";
            var bid_list = %(bid_list)s; var ut_list = %(ut_list)s; var tm = new Date().getTime();
            var cmd5x_func = %(cmd5x_func)s; var cmd5x_exporter = {}; cmd5x_func({}, cmd5x_exporter, {}); var cmd5x = cmd5x_exporter.cmd5x;
            var authKey = cmd5x(cmd5x('') + tm + '' + tvid);
            var k_uid = Array.apply(null, Array(32)).map(function() {return Math.floor(Math.random() * 15).toString(16)}).join('');
            var dash_paths = {};
            bid_list.forEach(function(bid) {
                var query = {
                    'tvid': tvid,
                    'bid': bid,
                    'ds': 1,
                    'vid': vid,
                    'src': src,
                    'vt': 0,
                    'rs': 1,
                    'uid': uid,
                    'ori': 'pcw',
                    'ps': 1,
                    'k_uid': k_uid,
                    'pt': 0,
                    'd': 0,
                    's': '',
                    'lid': '',
                    'slid': 0,
                    'cf': '',
                    'ct': '',
                    'authKey': authKey,
                    'k_tag': 1,
                    'ost': 0,
                    'ppt': 0,
                    'dfp': dfp,
                    'prio': JSON.stringify({
                        'ff': 'f4v',
                        'code': 2
                    }),
                    'k_err_retries': 0,
                    'up': '',
                    'su': 2,
                    'applang': lang,
                    'sver': 2,
                    'X-USER-MODE': mode,
                    'qd_v': 2,
                    'tm': tm,
                    'qdy': 'a',
                    'qds': 0,
                    'k_ft1': 141287244169348,
                    'k_ft4': 34359746564,
                    'k_ft5': 1,
                    'bop': JSON.stringify({
                        'version': '10.0',
                        'dfp': dfp
                    }),
                };
                var enc_params = [];
                for (var prop in query) {
                    enc_params.push(encodeURIComponent(prop) + '=' + encodeURIComponent(query[prop]));
                }
                ut_list.forEach(function(ut) {
                    enc_params.push('ut=' + ut);
                })
                var dash_path = '/dash?' + enc_params.join('&'); dash_path += '&vf=' + cmd5x(dash_path);
                dash_paths[bid] = dash_path;
            });
            return JSON.stringify(dash_paths);
        }));
        saveAndExit();
    '''

    def _extract_vms_player_js(self, webpage, video_id):
        player_js_cache = self.cache.load('iq', 'player_js')
        if player_js_cache:
            return player_js_cache
        webpack_js_url = self._proto_relative_url(self._search_regex(
            r'<script src="((?:https?)?//stc.iqiyipic.com/_next/static/chunks/webpack-\w+\.js)"', webpage, 'webpack URL'))
        webpack_js = self._download_webpage(webpack_js_url, video_id, note='Downloading webpack JS', errnote='Unable to download webpack JS')
        webpack_map1, webpack_map2 = [self._parse_json(js_map, video_id, transform_source=js_to_json) for js_map in self._search_regex(
            r'\(({[^}]*})\[\w+\][^\)]*\)\s*\+\s*["\']\.["\']\s*\+\s*({[^}]*})\[\w+\]\+["\']\.js', webpack_js, 'JS locations', group=(1, 2))]
        for module_index in reversed(list(webpack_map2.keys())):
            module_js = self._download_webpage(
                f'https://stc.iqiyipic.com/_next/static/chunks/{webpack_map1.get(module_index, module_index)}.{webpack_map2[module_index]}.js',
                video_id, note=f'Downloading #{module_index} module JS', errnote='Unable to download module JS', fatal=False) or ''
            if 'vms request' in module_js:
                self.cache.store('iq', 'player_js', module_js)
                return module_js
        raise ExtractorError('Unable to extract player JS')

    def _extract_cmd5x_function(self, webpage, video_id):
        return self._search_regex(r',\s*(function\s*\([^\)]*\)\s*{\s*var _qda.+_qdc\(\)\s*})\s*,',
                                  self._extract_vms_player_js(webpage, video_id), 'signature function')

    def _update_bid_tags(self, webpage, video_id):
        extracted_bid_tags = self._parse_json(
            self._search_regex(
                r'arguments\[1\][^,]*,\s*function\s*\([^\)]*\)\s*{\s*"use strict";?\s*var \w=({.+}})\s*,\s*\w\s*=\s*{\s*getNewVd',
                self._extract_vms_player_js(webpage, video_id), 'video tags', default=''),
            video_id, transform_source=js_to_json, fatal=False)
        if not extracted_bid_tags:
            return
        self._BID_TAGS = {
            bid: traverse_obj(extracted_bid_tags, (bid, 'value'), expected_type=str, default=self._BID_TAGS.get(bid))
            for bid in extracted_bid_tags.keys()
        }

    def _get_cookie(self, name, default=None):
        cookie = self._get_cookies('https://iq.com/').get(name)
        return cookie.value if cookie else default

    def _real_extract(self, url):
        video_id = self._match_id(url)
        webpage = self._download_webpage(url, video_id)
        self._update_bid_tags(webpage, video_id)

        next_props = self._search_nextjs_data(webpage, video_id)['props']
        page_data = next_props['initialState']['play']
        video_info = page_data['curVideoInfo']

        uid = traverse_obj(
            self._parse_json(
                self._get_cookie('I00002', '{}'), video_id, transform_source=compat_urllib_parse_unquote, fatal=False),
            ('data', 'uid'), default=0)

        if uid:
            vip_data = self._download_json(
                'https://pcw-api.iq.com/api/vtype', video_id, note='Downloading VIP data', errnote='Unable to download VIP data', query={
                    'batch': 1,
                    'platformId': 3,
                    'modeCode': self._get_cookie('mod', 'intl'),
                    'langCode': self._get_cookie('lang', 'en_us'),
                    'deviceId': self._get_cookie('QC005', '')
                }, fatal=False)
            ut_list = traverse_obj(vip_data, ('data', 'all_vip', ..., 'vipType'), expected_type=str_or_none, default=[])
        else:
            ut_list = ['0']

        # bid 0 as an initial format checker
        dash_paths = self._parse_json(PhantomJSwrapper(self).get(
            url, html='<!DOCTYPE html>', video_id=video_id, note2='Executing signature code', jscode=self._DASH_JS % {
                'tvid': video_info['tvId'],
                'vid': video_info['vid'],
                'src': traverse_obj(next_props, ('initialProps', 'pageProps', 'ptid'),
                                    expected_type=str, default='04022001010011000000'),
                'uid': uid,
                'dfp': self._get_cookie('dfp', ''),
                'mode': self._get_cookie('mod', 'intl'),
                'lang': self._get_cookie('lang', 'en_us'),
                'bid_list': '[' + ','.join(['0', *self._BID_TAGS.keys()]) + ']',
                'ut_list': '[' + ','.join(ut_list) + ']',
                'cmd5x_func': self._extract_cmd5x_function(webpage, video_id),
            })[1].strip(), video_id)

        formats, subtitles = [], {}
        initial_format_data = self._download_json(
            urljoin('https://cache-video.iq.com', dash_paths['0']), video_id,
            note='Downloading initial video format info', errnote='Unable to download initial video format info')['data']

        preview_time = traverse_obj(
            initial_format_data, ('boss_ts', (None, 'data'), ('previewTime', 'rtime')), expected_type=float_or_none, get_all=False)
        if traverse_obj(initial_format_data, ('boss_ts', 'data', 'prv'), expected_type=int_or_none):
            self.report_warning('This preview video is limited%s' % format_field(preview_time, None, ' to %s seconds'))

        # TODO: Extract audio-only formats
        for bid in set(traverse_obj(initial_format_data, ('program', 'video', ..., 'bid'), expected_type=str_or_none, default=[])):
            dash_path = dash_paths.get(bid)
            if not dash_path:
                self.report_warning(f'Unknown format id: {bid}. It is currently not being extracted')
                continue
            format_data = traverse_obj(self._download_json(
                urljoin('https://cache-video.iq.com', dash_path), video_id,
                note=f'Downloading format data for {self._BID_TAGS[bid]}', errnote='Unable to download format data',
                fatal=False), 'data', expected_type=dict)

            video_format = traverse_obj(format_data, ('program', 'video', lambda _, v: str(v['bid']) == bid),
                                        expected_type=dict, default=[], get_all=False) or {}
            extracted_formats = []
            if video_format.get('m3u8Url'):
                extracted_formats.extend(self._extract_m3u8_formats(
                    urljoin(format_data.get('dm3u8', 'https://cache-m.iq.com/dc/dt/'), video_format['m3u8Url']),
                    'mp4', m3u8_id=bid, fatal=False))
            if video_format.get('mpdUrl'):
                # TODO: Properly extract mpd hostname
                extracted_formats.extend(self._extract_mpd_formats(
                    urljoin(format_data.get('dm3u8', 'https://cache-m.iq.com/dc/dt/'), video_format['mpdUrl']),
                    mpd_id=bid, fatal=False))
            if video_format.get('m3u8'):
                ff = video_format.get('ff', 'ts')
                if ff == 'ts':
                    m3u8_formats, _ = self._parse_m3u8_formats_and_subtitles(
                        video_format['m3u8'], ext='mp4', m3u8_id=bid, fatal=False)
                    extracted_formats.extend(m3u8_formats)
                elif ff == 'm4s':
                    mpd_data = traverse_obj(
                        self._parse_json(video_format['m3u8'], video_id, fatal=False), ('payload', ..., 'data'), expected_type=str)
                    if not mpd_data:
                        continue
                    mpd_formats, _ = self._parse_mpd_formats_and_subtitles(
                        mpd_data, bid, format_data.get('dm3u8', 'https://cache-m.iq.com/dc/dt/'))
                    extracted_formats.extend(mpd_formats)
                else:
                    self.report_warning(f'{ff} formats are currently not supported')

            if not extracted_formats:
                if video_format.get('s'):
                    self.report_warning(f'{self._BID_TAGS[bid]} format is restricted')
                else:
                    self.report_warning(f'Unable to extract {self._BID_TAGS[bid]} format')
            for f in extracted_formats:
                f.update({
                    'quality': qualities(list(self._BID_TAGS.keys()))(bid),
                    'format_note': self._BID_TAGS[bid],
                    **parse_resolution(video_format.get('scrsz'))
                })
            formats.extend(extracted_formats)

        self._sort_formats(formats)

        for sub_format in traverse_obj(initial_format_data, ('program', 'stl', ...), expected_type=dict, default=[]):
            lang = self._LID_TAGS.get(str_or_none(sub_format.get('lid')), sub_format.get('_name'))
            subtitles.setdefault(lang, []).extend([{
                'ext': format_ext,
                'url': urljoin(initial_format_data.get('dstl', 'http://meta.video.iqiyi.com'), sub_format[format_key])
            } for format_key, format_ext in [('srt', 'srt'), ('webvtt', 'vtt')] if sub_format.get(format_key)])

        extra_metadata = page_data.get('albumInfo') if video_info.get('albumId') and page_data.get('albumInfo') else video_info
        return {
            'id': video_id,
            'title': video_info['name'],
            'formats': formats,
            'subtitles': subtitles,
            'description': video_info.get('mergeDesc'),
            'duration': parse_duration(video_info.get('len')),
            'age_limit': parse_age_limit(video_info.get('rating')),
            'average_rating': traverse_obj(page_data, ('playScoreInfo', 'score'), expected_type=float_or_none),
            'timestamp': parse_iso8601(video_info.get('isoUploadDate')),
            'categories': traverse_obj(extra_metadata, ('videoTagMap', ..., ..., 'name'), expected_type=str),
            'cast': traverse_obj(extra_metadata, ('actorArr', ..., 'name'), expected_type=str),
            'episode_number': int_or_none(video_info.get('order')) or None,
            'series': video_info.get('albumName'),
        }

class IqAlbumIE(InfoExtractor):
    IE_NAME = 'iq.com:album'
    _VALID_URL = r'https?://(?:www\.)?iq\.com/album/(?:[\w%-]*-)?(?P<id>\w+)'
    _TESTS = [{
        'url': 'https://www.iq.com/album/one-piece-1999-1bk9icvr331',
        'info_dict': {
            'id': '1bk9icvr331',
            'title': 'One Piece',
            'description': 'Subtitle available on Sunday 4PM（GMT+8）.'
        },
        'playlist_mincount': 238
    }, {
        # Movie/single video
        'url': 'https://www.iq.com/album/九龙城寨-2021-22yjnij099k',
        'info_dict': {
            'ext': 'mp4',
            'id': '22yjnij099k',
            'title': '九龙城寨',
            'description': 'md5:8a09f50b8ba0db4dc69bc7c844228044',
            'duration': 5000,
            'timestamp': 1641911371,
            'upload_date': '20220111',
            'series': '九龙城寨',
            'cast': ['Shi Yan Neng', 'Yu Lang', 'Peter  lv', 'Sun Zi Jun', 'Yang Xiao Bo'],
            'age_limit': 13,
            'average_rating': float,
        },
        'expected_warnings': ['format is restricted']
    }]

    def _entries(self, album_id_num, page_ranges, album_id=None, mode_code='intl', lang_code='en_us'):
        for page_range in page_ranges:
            page = self._download_json(
                f'https://pcw-api.iq.com/api/episodeListSource/{album_id_num}', album_id,
                note=f'Downloading video list episodes {page_range.get("msg", "")}',
                errnote='Unable to download video list', query={
                    'platformId': 3,
                    'modeCode': mode_code,
                    'langCode': lang_code,
                    'endOrder': page_range['to'],
                    'startOrder': page_range['from']
                })
            for video in page['data']['epg']:
                yield self.url_result('https://www.iq.com/play/%s' % (video.get('playLocSuffix') or video['qipuIdStr']),
                                      IqIE.ie_key(), video.get('qipuIdStr'), video.get('name'))

    def _real_extract(self, url):
        album_id = self._match_id(url)
        webpage = self._download_webpage(url, album_id)
        next_data = self._search_nextjs_data(webpage, album_id)
        album_data = next_data['props']['initialState']['album']['videoAlbumInfo']

        if album_data.get('videoType') == 'singleVideo':
            return self.url_result('https://www.iq.com/play/%s' % album_id, IqIE.ie_key())
        return self.playlist_result(
            self._entries(album_data['albumId'], album_data['totalPageRange'], album_id,
                          traverse_obj(next_data, ('props', 'initialProps', 'pageProps', 'modeCode')),
                          traverse_obj(next_data, ('props', 'initialProps', 'pageProps', 'langCode'))),
            album_id, album_data.get('name'), album_data.get('desc'))


code:
import re

from .common import InfoExtractor
from ..utils import traverse_obj, urljoin

class IslamChannelIE(InfoExtractor):
    _VALID_URL = r'https?://watch\.islamchannel\.tv/watch/(?P<id>\d+)'
    _TESTS = [{
        'url': 'https://watch.islamchannel.tv/watch/38604310',
        'info_dict': {
            'id': '38604310',
            'title': 'Omar - Young Omar',
            'description': 'md5:5cc7ddecef064ea7afe52eb5e0e33b55',
            'thumbnail': r're:https?://.+',
            'ext': 'mp4',
        }
    }]

    def _real_extract(self, url):
        video_id = self._match_id(url)
        webpage = self._download_webpage(url, video_id)

        thumbnail = self._search_regex(
            r'data-poster="([^"]+)"', webpage, 'data poster', fatal=False) or \
            self._html_search_meta(('og:image', 'twitter:image'), webpage)

        headers = {
            'Token': self._search_regex(r'data-token="([^"]+)"', webpage, 'data token'),
            'Token-Expiry': self._search_regex(r'data-expiry="([^"]+)"', webpage, 'data expiry'),
            'Uvid': video_id,
        }
        show_stream = self._download_json(
            f'https://v2-streams-elb.simplestreamcdn.com/api/show/stream/{video_id}', video_id,
            query={
                'key': self._search_regex(r'data-key="([^"]+)"', webpage, 'data key'),
                'platform': 'chrome',
            }, headers=headers)
        # TODO: show_stream['stream'] and show_stream['drm'] may contain something interesting
        streams = self._download_json(
            traverse_obj(show_stream, ('response', 'tokenization', 'url')), video_id,
            headers=headers)
        formats, subs = self._extract_m3u8_formats_and_subtitles(traverse_obj(streams, ('Streams', 'Adaptive')), video_id, 'mp4')
        self._sort_formats(formats)

        return {
            'id': video_id,
            'title': self._html_search_meta(('og:title', 'twitter:title'), webpage),
            'description': self._html_search_meta(('og:description', 'twitter:description', 'description'), webpage),
            'formats': formats,
            'subtitles': subs,
            'thumbnails': [{
                'id': 'unscaled',
                'url': thumbnail.split('?')[0],
                'ext': 'jpg',
                'preference': 2,
            }, {
                'id': 'orig',
                'url': thumbnail,
                'ext': 'jpg',
                'preference': 1,
            }] if thumbnail else None,
        }

class IslamChannelSeriesIE(InfoExtractor):
    _VALID_URL = r'https?://watch\.islamchannel\.tv/series/(?P<id>[a-f\d-]+)'
    _TESTS = [{
        'url': 'https://watch.islamchannel.tv/series/a6cccef3-3ef1-11eb-bc19-06b69c2357cd',
        'info_dict': {
            'id': 'a6cccef3-3ef1-11eb-bc19-06b69c2357cd',
        },
        'playlist_mincount': 31,
    }]

    def _real_extract(self, url):
        pl_id = self._match_id(url)
        webpage = self._download_webpage(url, pl_id)

        return self.playlist_from_matches(
            re.finditer(r'<a\s+href="(/watch/\d+)"[^>]+?data-video-type="show">', webpage),
            pl_id, getter=lambda x: urljoin(url, x.group(1)), ie=IslamChannelIE)


code:
import re

from .common import InfoExtractor

from ..utils import (
    int_or_none,
    str_or_none,
    traverse_obj,
    urljoin
)

class ITProTVBaseIE(InfoExtractor):
    _ENDPOINTS = {
        'course': 'course?url={}&brand=00002560-0000-3fa9-0000-1d61000035f3',
        'episode': 'brand/00002560-0000-3fa9-0000-1d61000035f3/episode?url={}'
    }

    def _call_api(self, ep, item_id, webpage):
        return self._download_json(
            f'https://api.itpro.tv/api/urza/v3/consumer-web/{self._ENDPOINTS[ep].format(item_id)}',
            item_id, note=f'Fetching {ep} data API',
            headers={'Authorization': f'Bearer {self._fetch_jwt(webpage)}'})[ep]

    def _fetch_jwt(self, webpage):
        return self._search_regex(r'{"passedToken":"([\w-]+\.[\w-]+\.[\w-]+)",', webpage, 'jwt')

    def _check_if_logged_in(self, webpage):
        if re.match(r'{\s*member\s*:\s*null', webpage):
            self.raise_login_required()

class ITProTVIE(ITProTVBaseIE):
    _VALID_URL = r'https://app.itpro.tv/course/(?P<course>[\w-]+)/(?P<id>[\w-]+)'
    _TESTS = [{
        'url': 'https://app.itpro.tv/course/guided-tour/introductionitprotv',
        'md5': 'bca4a28c2667fd1a63052e71a94bb88c',
        'info_dict': {
            'id': 'introductionitprotv',
            'ext': 'mp4',
            'title': 'An Introduction to ITProTV 101',
            'thumbnail': 'https://itprotv-image-bucket.s3.amazonaws.com/getting-started/itprotv-101-introduction-PGM.11_39_56_02.Still001.png',
            'description': 'md5:b175c2c3061ce35a4dd33865b2c1da4e',
            'duration': 269,
            'series': 'ITProTV 101',
            'series_id': 'guided-tour',
            'availability': 'needs_auth',
            'chapter': 'ITProTV 101',
            'chapter_number': 1,
            'chapter_id': '5dbb3de426b46c0010b5d1b6'
        },
    },
        {
        'url': 'https://app.itpro.tv/course/beyond-tech/job-interview-tips',
        'md5': '101a299b98c47ccf4c67f9f0951defa8',
        'info_dict': {
            'id': 'job-interview-tips',
            'ext': 'mp4',
            'title': 'Job Interview Tips',
            'thumbnail': 'https://s3.amazonaws.com:443/production-itprotv-thumbnails/2f370bf5-294d-4bbe-ab80-c0b5781630ea.png',
            'description': 'md5:30d8ba483febdf89ec85623aad3c3cb6',
            'duration': 267,
            'series': 'Beyond Tech',
            'series_id': 'beyond-tech',
            'availability': 'needs_auth',
            'chapter': 'Job Development',
            'chapter_number': 2,
            'chapter_id': '5f7c78d424330c000edf04d9'
        },
    }]

    def _real_extract(self, url):
        episode_id, course_name = self._match_valid_url(url).group('id', 'course')
        webpage = self._download_webpage(url, episode_id)
        self._check_if_logged_in(webpage)
        course = self._call_api('course', course_name, webpage)
        episode = self._call_api('episode', episode_id, webpage)

        chapter_number, chapter = next((
            (i, topic) for i, topic in enumerate(course.get('topics') or [], 1)
            if traverse_obj(topic, 'id') == episode.get('topic')), {})

        return {
            'id': episode_id,
            'title': episode.get('title'),
            'description': episode.get('description'),
            'thumbnail': episode.get('thumbnail'),
            'formats': [
                {'url': episode[f'jwVideo{h}Embed'], 'height': h}
                for h in (320, 480, 720, 1080) if episode.get(f'jwVideo{h}Embed')
            ],
            'duration': int_or_none(episode.get('length')),
            'series': course.get('name'),
            'series_id': course.get('url'),
            'chapter': str_or_none(chapter.get('title')),
            'chapter_number': chapter_number,
            'chapter_id': str_or_none(chapter.get('id')),
            'subtitles': {
                'en': [{'ext': 'vtt', 'data': episode['enCaptionData']}]
            } if episode.get('enCaptionData') else None,
        }

class ITProTVCourseIE(ITProTVBaseIE):
    _VALID_URL = r'https?://app.itpro.tv/course/(?P<id>[\w-]+)/?(?:$|[#?])'
    _TESTS = [
        {
            'url': 'https://app.itpro.tv/course/guided-tour',
            'info_dict': {
                'id': 'guided-tour',
                'description': 'md5:b175c2c3061ce35a4dd33865b2c1da4e',
                'title': 'ITProTV 101',
            },
            'playlist_count': 6
        },
        {
            'url': 'https://app.itpro.tv/course/beyond-tech',
            'info_dict': {
                'id': 'beyond-tech',
                'description': 'md5:44cd99855e7f81a15ce1269bd0621fed',
                'title': 'Beyond Tech'
            },
            'playlist_count': 15
        },
    ]

    def _real_extract(self, url):
        course_id = self._match_id(url)
        webpage = self._download_webpage(url, course_id)
        self._check_if_logged_in(webpage)
        course = self._call_api('course', course_id, webpage)

        entries = [self.url_result(
            urljoin(url, f'{course_id}/{episode["url"]}'), ITProTVIE,
            episode['url'], episode.get('title'), url_transparent=True)
            for episode in course['episodes']]

        return self.playlist_result(
            entries, course_id, course.get('name'), course.get('description'))


code:
import json

from .common import InfoExtractor
from .brightcove import BrightcoveNewIE

from ..compat import compat_str
from ..utils import (
    base_url,
    clean_html,
    determine_ext,
    extract_attributes,
    ExtractorError,
    get_element_by_class,
    JSON_LD_RE,
    merge_dicts,
    parse_duration,
    smuggle_url,
    try_get,
    url_or_none,
    url_basename,
    urljoin,
)

class ITVIE(InfoExtractor):
    _VALID_URL = r'https?://(?:www\.)?itv\.com/hub/[^/]+/(?P<id>[0-9a-zA-Z]+)'
    _GEO_COUNTRIES = ['GB']
    _TESTS = [{
        'url': 'https://www.itv.com/hub/plebs/2a1873a0002',
        'info_dict': {
            'id': '2a1873a0002',
            'ext': 'mp4',
            'title': 'Plebs - The Orgy',
            'description': 'md5:4d7159af53ebd5b36e8b3ec82a41fdb4',
            'series': 'Plebs',
            'season_number': 1,
            'episode_number': 1,
            'thumbnail': r're:https?://hubimages\.itv\.com/episode/2_1873_0002'
        },
        'params': {
            # m3u8 download
            'skip_download': True,
        },
    }, {
        'url': 'https://www.itv.com/hub/the-jonathan-ross-show/2a1166a0209',
        'info_dict': {
            'id': '2a1166a0209',
            'ext': 'mp4',
            'title': 'The Jonathan Ross Show - Series 17 - Episode 8',
            'description': 'md5:3023dcdd375db1bc9967186cdb3f1399',
            'series': 'The Jonathan Ross Show',
            'episode_number': 8,
            'season_number': 17,
            'thumbnail': r're:https?://hubimages\.itv\.com/episode/2_1873_0002'
        },
        'params': {
            # m3u8 download
            'skip_download': True,
        },
    }, {
        # unavailable via data-playlist-url
        'url': 'https://www.itv.com/hub/through-the-keyhole/2a2271a0033',
        'only_matching': True,
    }, {
        # InvalidVodcrid
        'url': 'https://www.itv.com/hub/james-martins-saturday-morning/2a5159a0034',
        'only_matching': True,
    }, {
        # ContentUnavailable
        'url': 'https://www.itv.com/hub/whos-doing-the-dishes/2a2898a0024',
        'only_matching': True,
    }]

    def _generate_api_headers(self, hmac):
        return merge_dicts({
            'Accept': 'application/vnd.itv.vod.playlist.v2+json',
            'Content-Type': 'application/json',
            'hmac': hmac.upper(),
        }, self.geo_verification_headers())

    def _call_api(self, video_id, playlist_url, headers, platform_tag, featureset, fatal=True):
        return self._download_json(
            playlist_url, video_id, data=json.dumps({
                'user': {
                    'itvUserId': '',
                    'entitlements': [],
                    'token': ''
                },
                'device': {
                    'manufacturer': 'Safari',
                    'model': '5',
                    'os': {
                        'name': 'Windows NT',
                        'version': '6.1',
                        'type': 'desktop'
                    }
                },
                'client': {
                    'version': '4.1',
                    'id': 'browser'
                },
                'variantAvailability': {
                    'featureset': {
                        'min': featureset,
                        'max': featureset
                    },
                    'platformTag': platform_tag
                }
            }).encode(), headers=headers, fatal=fatal)

    def _get_subtitles(self, video_id, variants, ios_playlist_url, headers, *args, **kwargs):
        subtitles = {}
        # Prefer last matching featureset
        # See: https://github.com/yt-dlp/yt-dlp/issues/986
        platform_tag_subs, featureset_subs = next(
            ((platform_tag, featureset)
             for platform_tag, featuresets in reversed(list(variants.items())) for featureset in featuresets
             if try_get(featureset, lambda x: x[2]) == 'outband-webvtt'),
            (None, None))

        if platform_tag_subs and featureset_subs:
            subs_playlist = self._call_api(
                video_id, ios_playlist_url, headers, platform_tag_subs, featureset_subs, fatal=False)
            subs = try_get(subs_playlist, lambda x: x['Playlist']['Video']['Subtitles'], list) or []
            for sub in subs:
                if not isinstance(sub, dict):
                    continue
                href = url_or_none(sub.get('Href'))
                if not href:
                    continue
                subtitles.setdefault('en', []).append({'url': href})
        return subtitles

    def _real_extract(self, url):
        video_id = self._match_id(url)
        webpage = self._download_webpage(url, video_id)
        params = extract_attributes(self._search_regex(
            r'(?s)(<[^>]+id="video"[^>]*>)', webpage, 'params'))
        variants = self._parse_json(
            try_get(params, lambda x: x['data-video-variants'], compat_str) or '{}',
            video_id, fatal=False)
        # Prefer last matching featureset
        # See: https://github.com/yt-dlp/yt-dlp/issues/986
        platform_tag_video, featureset_video = next(
            ((platform_tag, featureset)
             for platform_tag, featuresets in reversed(list(variants.items())) for featureset in featuresets
             if set(try_get(featureset, lambda x: x[:2]) or []) == {'aes', 'hls'}),
            (None, None))
        if not platform_tag_video or not featureset_video:
            raise ExtractorError('No downloads available', expected=True, video_id=video_id)

        ios_playlist_url = params.get('data-video-playlist') or params['data-video-id']
        headers = self._generate_api_headers(params['data-video-hmac'])
        ios_playlist = self._call_api(
            video_id, ios_playlist_url, headers, platform_tag_video, featureset_video)

        video_data = try_get(ios_playlist, lambda x: x['Playlist']['Video'], dict) or {}
        ios_base_url = video_data.get('Base')
        formats = []
        for media_file in (video_data.get('MediaFiles') or []):
            href = media_file.get('Href')
            if not href:
                continue
            if ios_base_url:
                href = ios_base_url + href
            ext = determine_ext(href)
            if ext == 'm3u8':
                formats.extend(self._extract_m3u8_formats(
                    href, video_id, 'mp4', entry_protocol='m3u8_native',
                    m3u8_id='hls', fatal=False))
            else:
                formats.append({
                    'url': href,
                })
        self._sort_formats(formats)
        info = self._search_json_ld(webpage, video_id, default={})
        if not info:
            json_ld = self._parse_json(self._search_regex(
                JSON_LD_RE, webpage, 'JSON-LD', '{}',
                group='json_ld'), video_id, fatal=False)
            if json_ld and json_ld.get('@type') == 'BreadcrumbList':
                for ile in (json_ld.get('itemListElement:') or []):
                    item = ile.get('item:') or {}
                    if item.get('@type') == 'TVEpisode':
                        item['@context'] = 'http://schema.org'
                        info = self._json_ld(item, video_id, fatal=False) or {}
                        break

        thumbnails = []
        thumbnail_url = try_get(params, lambda x: x['data-video-posterframe'], compat_str)
        if thumbnail_url:
            thumbnails.extend([{
                'url': thumbnail_url.format(width=1920, height=1080, quality=100, blur=0, bg='false'),
                'width': 1920,
                'height': 1080,
            }, {
                'url': urljoin(base_url(thumbnail_url), url_basename(thumbnail_url)),
                'preference': -2
            }])

        thumbnail_url = self._html_search_meta(['og:image', 'twitter:image'], webpage, default=None)
        if thumbnail_url:
            thumbnails.append({
                'url': thumbnail_url,
            })
        self._remove_duplicate_formats(thumbnails)

        return merge_dicts({
            'id': video_id,
            'title': self._html_search_meta(['og:title', 'twitter:title'], webpage),
            'formats': formats,
            'subtitles': self.extract_subtitles(video_id, variants, ios_playlist_url, headers),
            'duration': parse_duration(video_data.get('Duration')),
            'description': clean_html(get_element_by_class('episode-info__synopsis', webpage)),
            'thumbnails': thumbnails
        }, info)

class ITVBTCCIE(InfoExtractor):
    _VALID_URL = r'https?://(?:www\.)?itv\.com/(?:news|btcc)/(?:[^/]+/)*(?P<id>[^/?#&]+)'
    _TESTS = [{
        'url': 'https://www.itv.com/btcc/articles/btcc-2019-brands-hatch-gp-race-action',
        'info_dict': {
            'id': 'btcc-2019-brands-hatch-gp-race-action',
            'title': 'BTCC 2019: Brands Hatch GP race action',
        },
        'playlist_count': 12,
    }, {
        'url': 'https://www.itv.com/news/2021-10-27/i-have-to-protect-the-country-says-rishi-sunak-as-uk-faces-interest-rate-hike',
        'info_dict': {
            'id': 'i-have-to-protect-the-country-says-rishi-sunak-as-uk-faces-interest-rate-hike',
            'title': 'md5:6ef054dd9f069330db3dcc66cb772d32'
        },
        'playlist_count': 4
    }]
    BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/%s/%s_default/index.html?videoId=%s'

    def _real_extract(self, url):
        playlist_id = self._match_id(url)

        webpage = self._download_webpage(url, playlist_id)

        json_map = try_get(
            self._search_nextjs_data(webpage, playlist_id),
            lambda x: x['props']['pageProps']['article']['body']['content']) or []

        entries = []
        for video in json_map:
            if not any(video['data'].get(attr) == 'Brightcove' for attr in ('name', 'type')):
                continue
            video_id = video['data']['id']
            account_id = video['data']['accountId']
            player_id = video['data']['playerId']
            entries.append(self.url_result(
                smuggle_url(self.BRIGHTCOVE_URL_TEMPLATE % (account_id, player_id, video_id), {
                    # ITV does not like some GB IP ranges, so here are some
                    # IP blocks it accepts
                    'geo_ip_blocks': [
                        '193.113.0.0/16', '54.36.162.0/23', '159.65.16.0/21'
                    ],
                    'referrer': url,
                }),
                ie=BrightcoveNewIE.ie_key(), video_id=video_id))

        title = self._og_search_title(webpage, fatal=False)

        return self.playlist_result(entries, playlist_id, title)