Repository: yt-dlp/yt-dlp
File: yt_dlp/extractor/redgifs.py (Python)

Code before:
        if 'error' in data:
            raise ExtractorError(f'RedGifs said: {data["error"]}', expected=True, video_id=video_id)
        return data

    def _fetch_page(self, ep, video_id, query, page):
        query['page'] = page + 1
        data = self._call_api(
            ep, video_id, query=query, note=f'Downloading JSON metadata page {page + 1}')

        for entry in data['gifs']:
            yield self._parse_gif_data(entry)

    def _prepare_api_query(self, query, fields):
        api_query = [
            (field_name, query.get(field_name, (default,))[0])
            for field_name, default in fields.items()]

        return {key: val for key, val in api_query if val is not None}

    def _paged_entries(self, ep, item_id, query, fields):
        page = int_or_none(query.get('page', (None,))[0])
        page_fetcher = functools.partial(
            self._fetch_page, ep, item_id, self._prepare_api_query(query, fields))
        return page_fetcher(page) if page else OnDemandPagedList(page_fetcher, self._PAGE_SIZE)


class RedGifsIE(RedGifsBaseInfoExtractor):
    _VALID_URL = r'https?://(?:(?:www\.)?redgifs\.com/watch/|thumbs2\.redgifs\.com/)(?P<id>[^-/?#\.]+)'
    _TESTS = [{
        'url': 'https://www.redgifs.com/watch/squeakyhelplesswisent',
        'info_dict': {
            'id': 'squeakyhelplesswisent',
            'ext': 'mp4',
            'title': 'Hotwife Legs Thick',
            'timestamp': 1636287915,
            'upload_date': '20211107',
            'uploader': 'ignored52',
            'duration': 16,
            'view_count': int,
            'like_count': int,
            'categories': list,
            'age_limit': 18,
        }
    }, {
        'url': 'https://thumbs2.redgifs.com/SqueakyHelplessWisent-mobile.mp4#t=0',
        'info_dict': {
            'id': 'squeakyhelplesswisent',
            'ext': 'mp4',
            'title': 'Hotwife Legs Thick',
            'timestamp': 1636287915,
            'upload_date': '20211107',

Review comment (security):
* You sure all of these are needed?
* I think this should be a class var.

* Also follow code guidelines:
```suggestion
        headers = {
            'authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIxODIzYzMxZjdkMy03NDVhLTY1ODktMDAwNS1kOGU4ZmUwYTQ0YzIiLCJleHAiOjE2NjM2NzczMjEsInN1YiI6ImNsaWVudFwvMTgyM2MzMWY3ZDMtNzQ1YS02NTg5LTAwMDUtZDhlOGZlMGE0NGMyIiwic2NvcGVzIjoicmVhZCIsInJhdGUiOi0xfQ.uod5xbnhPbdlOb5UTdHPFls3ZtwxKOjkHtN2rpU8h6Y',
            'x-customheader': f'https://www.redgifs.com/watch/{video_id}',
            'referer': 'https://www.redgifs.com/',
            'origin': 'https://www.redgifs.com',
            'content-type': 'application/json'
        }
```

Code after:
            'formats': formats,
        }

    def _fetch_oauth_token(self, video_id):
        # These pages contain the OAuth token that is necessary to make API calls.
        index_page = self._download_webpage(f'https://www.redgifs.com/watch/{video_id}', video_id)
        index_js_uri = self._html_search_regex(
            r'href="?(/assets/js/index[.a-z0-9]*.js)"?\W', index_page, 'index_js_uri')
        index_js = self._download_webpage(f'https://www.redgifs.com/{index_js_uri}', video_id)
        # It turns out that a { followed by any valid JSON punctuation will always result in the
        # first two characters of the base64 encoding being "ey".
        # Use this fact to find any such string constant of a reasonable length with the correct
        # punctuation for an oauth token
        oauth_token = self._html_search_regex(
            r'\w+\s*[=:]\s*"(ey[^"]+\.[^"]*\.[^"]{43,45})"', index_js, 'oauth token')
        self._API_HEADERS['authorization'] = f'Bearer {oauth_token}'

    def _call_api(self, ep, video_id, *args, **kwargs):
        if 'authorization' not in self._API_HEADERS:
            self._fetch_oauth_token(video_id)
        assert 'authorization' in self._API_HEADERS

        headers = dict(self._API_HEADERS)
        headers['x-customheader'] = f'https://www.redgifs.com/watch/{video_id}'
        data = self._download_json(
            f'https://api.redgifs.com/v2/{ep}', video_id, headers=headers, *args, **kwargs)
        if 'error' in data:
            raise ExtractorError(f'RedGifs said: {data["error"]}', expected=True, video_id=video_id)
        return data

    def _fetch_page(self, ep, video_id, query, page):
        query['page'] = page + 1
        data = self._call_api(
            ep, video_id, query=query, note=f'Downloading JSON metadata page {page + 1}')

        for entry in data['gifs']:
            yield self._parse_gif_data(entry)

    def _prepare_api_query(self, query, fields):
        api_query = [
            (field_name, query.get(field_name, (default,))[0])
            for field_name, default in fields.items()]

        return {key: val for key, val in api_query if val is not None}

    def _paged_entries(self, ep, item_id, query, fields):
        page = int_or_none(query.get('page', (None,))[0])
        page_fetcher = functools.partial(
            self._fetch_page, ep, item_id, self._prepare_api_query(query, fields))
        return page_fetcher(page) if page else OnDemandPagedList(page_fetcher, self._PAGE_SIZE)