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

Code before:
        'url': 'https://utexas.app.box.com/s/2x6vanv85fdl8j2eqlcxmv0gp1wvps6e',
        'info_dict': {
            'id': '787379022466',
            'ext': 'mp4',
            'title': 'Webinar recording: Take the Leap!.mp4',
            'uploader': 'Patricia Mosele',
            'timestamp': 1615824864,
            'upload_date': '20210315',
            'uploader_id': '239068974',
        },
        'params': {'skip_download': 'dash fragment too small'},
    }]

    def _real_extract(self, url):
        shared_name, file_id = self._match_valid_url(url).groups()
        webpage = self._download_webpage(url, file_id or shared_name)

        if file_id is None:
            post_stream_data = self._parse_json(self._search_regex(
                r'Box\.postStreamData\s*=\s*({.+?});', webpage, 'Box post-stream data'),
                file_id)
            shared_item = post_stream_data.get('/app-api/enduserapp/shared-item')
            if shared_item.get('itemType') != 'file':
                raise ExtractorError('Resource is not a file')

            file_id = str(shared_item.get('itemID'))

        request_token = self._parse_json(self._search_regex(
            r'Box\.config\s*=\s*({.+?});', webpage,
            'Box config'), file_id)['requestToken']
        access_token = self._download_json(
            'https://app.box.com/app-api/enduserapp/elements/tokens', file_id,
            'Downloading token JSON metadata',
            data=json.dumps({'fileIDs': [file_id]}).encode(), headers={
                'Content-Type': 'application/json',
                'X-Request-Token': request_token,
                'X-Box-EndUser-API': 'sharedName=' + shared_name,
            })[file_id]['read']
        shared_link = 'https://app.box.com/s/' + shared_name
        f = self._download_json(
            'https://api.box.com/2.0/files/' + file_id, file_id,
            'Downloading file JSON metadata', headers={
                'Authorization': 'Bearer ' + access_token,
                'BoxApi': 'shared_link=' + shared_link,
                'X-Rep-Hints': '[dash]',  # TODO: extract `hls` formats
            }, query={
                'fields': 'authenticated_download_url,created_at,created_by,description,extension,is_download_available,name,representations,size'
            })
        title = f['name']

        query = {

Review comment (refactor):
use `traverse_obj` so we don't throw during error handling (which should be `expected=True`, right?)

then let's intentionally KeyError if there's no `itemID`, since we need it for the next request
```suggestion
            shared_item = traverse_obj(post_stream_data, ('/app-api/enduserapp/shared-item', {dict}) or {}
            if shared_item.get('itemType') != 'file':
                raise ExtractorError('The requested resource is not a file', expected=True)

            file_id = str(shared_item['itemID'])
```

Code after:
        'url': 'https://utexas.app.box.com/s/2x6vanv85fdl8j2eqlcxmv0gp1wvps6e',
        'info_dict': {
            'id': '787379022466',
            'ext': 'mp4',
            'title': 'Webinar recording: Take the Leap!.mp4',
            'uploader': 'Patricia Mosele',
            'timestamp': 1615824864,
            'upload_date': '20210315',
            'uploader_id': '239068974',
        },
        'params': {'skip_download': 'dash fragment too small'},
    }]

    def _real_extract(self, url):
        shared_name, file_id = self._match_valid_url(url).groups()
        webpage = self._download_webpage(url, file_id or shared_name)

        if not file_id:
            post_stream_data = self._search_json(
                r'Box\.postStreamData\s*=', webpage, 'Box post-stream data', shared_name)
            shared_item = traverse_obj(
                post_stream_data, ('/app-api/enduserapp/shared-item', {dict})) or {}
            if shared_item.get('itemType') != 'file':
                raise ExtractorError('The requested resource is not a file', expected=True)

            file_id = str(shared_item['itemID'])

        request_token = self._search_json(
            r'Box\.config\s*=', webpage, 'Box config', file_id)['requestToken']
        access_token = self._download_json(
            'https://app.box.com/app-api/enduserapp/elements/tokens', file_id,
            'Downloading token JSON metadata',
            data=json.dumps({'fileIDs': [file_id]}).encode(), headers={
                'Content-Type': 'application/json',
                'X-Request-Token': request_token,
                'X-Box-EndUser-API': 'sharedName=' + shared_name,
            })[file_id]['read']
        shared_link = 'https://app.box.com/s/' + shared_name
        f = self._download_json(
            'https://api.box.com/2.0/files/' + file_id, file_id,
            'Downloading file JSON metadata', headers={
                'Authorization': 'Bearer ' + access_token,
                'BoxApi': 'shared_link=' + shared_link,
                'X-Rep-Hints': '[dash]',  # TODO: extract `hls` formats
            }, query={
                'fields': 'authenticated_download_url,created_at,created_by,description,extension,is_download_available,name,representations,size'
            })
        title = f['name']

        query = {
            'access_token': access_token,