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

Code before:
    def _perform_login(self, username, password):
        sign_in = self._download_json(
            f'{self._BASE_URL}/web_api/signin', None, 'Logging in', headers={
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }, data=json.dumps({
                'session': {
                    'email': username,
                    'password': password,
                },
            }).encode(), expected_status=401)

        if sign_in.get('error'):
            raise ExtractorError('Invalid username or password', expected=True)

    def _real_extract(self, url):
        program_id = self._match_id(url)
        try:
            programs = self._download_json(
                f'{self._BASE_URL}/web_api/programs/{program_id}', program_id)
        except ExtractorError as e:
            if isinstance(e.cause, HTTPError) and e.cause.status == 404:
                raise ExtractorError('Invalid URL', expected=True)
            raise

        enc_id = lambda p: base64.b64encode(str(p['id']).encode()).decode()
        query = {k: v[0] for k, v in parse_qs(url).items() if v}
        if 'c' not in query:
            entries = [self.url_result(
                f'{url}?c={enc_id(program)}', OnsenIE,
            ) for program in traverse_obj(programs, ('contents', lambda _, v: v['id']))]

            return self.playlist_result(
                entries, program_id, programs['program_info']['title'])

        raw_id = base64.b64decode(query['c'] + '=' * (-len(query['c']) & 3)).decode()
        p_keys = ('contents', lambda _, v: v['id'] == int(raw_id))

        program = traverse_obj(programs, (*p_keys, any))
        if not program:
            raise ExtractorError(
                'This program is no longer available', expected=True)
        m3u8_url = traverse_obj(program, ('streaming_url', {url_or_none}))
        if not m3u8_url:
            self.raise_login_required(
                'This program is only available for premium supporters')

        display_id = enc_id(program)
        date_str = self._search_regex(
            rf'{program_id}0?(\d{{6}})', m3u8_url, 'date string', default=None)


Review comment (suggestion):
I would just pull this out to a method. Lambdas and nested funcs can end up creating more work later on down the maintenance timeline

also, are we sure this should be `b64encode` and not `urlsafe_b64encode`?
```py
    @staticmethod
    def _get_encoded_id(program):
        return base64.b64encode(str(program['id']).encode()).decode()
```

Code after:

    @staticmethod
    def _get_encoded_id(program):
        return base64.urlsafe_b64encode(str(program['id']).encode()).decode()

    def _perform_login(self, username, password):
        sign_in = self._download_json(
            f'{self._BASE_URL}/web_api/signin', None, 'Logging in', headers={
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }, data=json.dumps({
                'session': {
                    'email': username,
                    'password': password,
                },
            }).encode(), expected_status=401)

        if sign_in.get('error'):
            raise ExtractorError('Invalid username or password', expected=True)

    def _real_extract(self, url):
        program_id = self._match_id(url)
        try:
            programs = self._download_json(
                f'{self._BASE_URL}/web_api/programs/{program_id}', program_id)
        except ExtractorError as e:
            if isinstance(e.cause, HTTPError) and e.cause.status == 404:
                raise ExtractorError('Invalid URL', expected=True)
            raise

        query = {k: v[-1] for k, v in parse_qs(url).items() if v}
        if 'c' not in query:
            entries = [
                self.url_result(update_url_query(url, {'c': self._get_encoded_id(program)}), OnsenIE)
                for program in traverse_obj(programs, ('contents', lambda _, v: v['id']))
            ]

            return self.playlist_result(
                entries, program_id, traverse_obj(programs, ('program_info', 'title', {clean_html})))

        raw_id = base64.urlsafe_b64decode(f'{query["c"]}===').decode()
        p_keys = ('contents', lambda _, v: v['id'] == int(raw_id))

        program = traverse_obj(programs, (*p_keys, any))
        if not program:
            raise ExtractorError(
                'This program is no longer available', expected=True)
        m3u8_url = traverse_obj(program, ('streaming_url', {url_or_none}))
        if not m3u8_url:
            self.raise_login_required(
                'This program is only available for premium supporters')