Repository: yt-dlp/yt-dlp

Issue:
[tvp] "Video requires payment and log-in, but log-in is not implemented"
### DO NOT REMOVE OR SKIP THE ISSUE TEMPLATE

- [X] I understand that I will be **blocked** if I *intentionally* remove or skip any mandatory\* field

### Checklist

- [X] I'm reporting that a **supported** site is broken
- [X] I've verified that I'm running yt-dlp version **2023.03.04** ([update instructions](https://github.com/yt-dlp/yt-dlp#update)) or later (specify commit)
- [X] I've checked that all provided URLs are playable in a browser with the same IP and same login details
- [X] I've checked that all URLs and arguments with special characters are [properly quoted or escaped](https://github.com/yt-dlp/yt-dlp/wiki/FAQ#video-url-contains-an-ampersand--and-im-getting-some-strange-output-1-2839-or-v-is-not-recognized-as-an-internal-or-external-command)
- [X] I've searched [known issues](https://github.com/yt-dlp/yt-dlp/issues/3766) and the [bugtracker](https://github.com/yt-dlp/yt-dlp/issues?q=) for similar issues **including closed ones**. DO NOT post duplicates
- [X] I've read the [guidelines for opening an issue](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#opening-an-issue)
- [X] I've read about [sharing account credentials](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#are-you-willing-to-share-account-details-if-needed) and I'm willing to share it if required

### Region

Canada

### Provide a description that is worded well enough to be understood

I've been downloading episodes from website: Vod.tvp.pl / https://vod.tvp.pl/seriale,18/polowanie-na-cmy-odcinki,390116

I've been able to get every episode with no issues what so ever, with the exception of Episode #7. https://vod.tvp.pl/seriale,18/polowanie-na-cmy-odcinki,390116/odcinek-7,S01E07,398869

[tvp:vod] Extracting URL: https://vod.tvp.pl/seriale,18/polowanie-na-cmy-odcinki,390116/odcinek-7,S01E07,398869
[tvp:vod] 398869: Downloading JSON metadata
[tvp:embed] Extracting URL: tvp:69230468
[tvp:embed] 69230468: Downloading webpage
ERROR: [tvp:embed] 69230468: Video requires payment and log-in, but log-in is not implemented; please report this issue on  https://github.com/yt-dlp/yt-dlp/issues?q= , filling out the appropriate issue template. Confirm you are on the latest version using  yt-dlp -U

(Same error with -vU)

The video works in browser, I've created an account and tried --cookies-from-browser chrome with no luck. 

I've updated twice hoping for a resolution - video has been available since April 30th, 2023. 

### Provide verbose output that clearly demonstrates the problem

- [X] Run **your** yt-dlp command with **-vU** flag added (`yt-dlp -vU <your command line>`)
- [X] If using API, add `'verbose': True` to `YoutubeDL` params instead
- [X] Copy the WHOLE output (starting with `[debug] Command-line config`) and insert it below

### Complete Verbose Output

```shell
[debug] Command-line config: ['-vU', 'https://vod.tvp.pl/seriale,18/polowanie-na-cmy-odcinki,390116/odcinek-7,S01E07,398869']
[debug] Encodings: locale cp1252, fs utf-8, pref cp1252, out utf-8, error utf-8, screen utf-8
[debug] yt-dlp version nightly@2023.05.03.204705 [2f07c4c1d] (win_exe)
[debug] Python 3.8.10 (CPython AMD64 64bit) - Windows-10-10.0.19044-SP0 (OpenSSL 1.1.1k  25 Mar 2021)
[debug] exe versions: none
[debug] Optional libraries: Cryptodome-3.17, brotli-1.0.9, certifi-2022.12.07, mutagen-1.46.0, sqlite3-2.6.0, websockets-11.0.2
[debug] Proxy map: {}
[debug] Loaded 1813 extractors
[debug] Fetching release info: https://api.github.com/repos/yt-dlp/yt-dlp-nightly-builds/releases/latest
Available version: nightly@2023.05.03.204705, Current version: nightly@2023.05.03.204705
Current Build Hash: b73b1cb4c64dcbd61a084ba9910dca9837cedb7b450c75605ec5d197cdc8ad01
yt-dlp is up to date (nightly@2023.05.03.204705)
[tvp:vod] Extracting URL: https://vod.tvp.pl/seriale,18/polowanie-na-cmy-odcinki,390116/odcinek-7,S01E07,398869
[tvp:vod] 398869: Downloading JSON metadata
[tvp:embed] Extracting URL: tvp:69230468
[tvp:embed] 69230468: Downloading webpage
ERROR: [tvp:embed] 69230468: Video requires payment and log-in, but log-in is not implemented; please report this issue on  https://github.com/yt-dlp/yt-dlp/issues?q= , filling out the appropriate issue template. Confirm you are on the latest version using  yt-dlp -U
  File "yt_dlp\extractor\common.py", line 694, in extract
  File "yt_dlp\extractor\tvp.py", line 392, in _real_extract
```



Discussion:
The extractor finds the TVP id `69230468` from a metadata API URL (the returned data includes a lot of other and tries this URL: https://www.tvp.pl/sess/TVPlayer2/api.php?id=69230468&@method=getTvpConfig&@callback=sasin70 (`callback` is picked randomly from a list). Fetching that URL returns a page with JSON like this
```py
[{'context': 'id',
  'data': None,
  'desc': 'Obiekt wymaga płatności',
  'type': 'Error'}]
```
The browser JS is using some different method<strike>, or passing additional headers, which might become apparent from a network trace using the browser's development tools</strike>.
Thank you for the reply! 

Could I ask for advice on how to run a network trace? 

I'm pretty new to all of this. 
Actually, the answer is this: https://vod.tvp.pl/api/products/398869/videos/playlist?platform=BROWSER&videoType=MOVIE
<details><summary>JSON playlist result</summary>

```py
{
  'sources': {
    'HLS': [
      {
        'src': 'https://rsdt-krk201-4.tvp.pl/token/video/vod/69230468/20230504/785384984/X2P8b7AC2hD-POBG5j1lWx35b4kPhUN76BrY8Sx2N6hXDVBtsw6o8GFB1VSqmw5aDiZutk97EpJd64s-0KV8ZM7s59QW7UQvuwJQVNIv84e9mTIiuLMsfDRW0bM3EigHpQLnSybEg7TeQPaG_-uSuPPlpVcGlC5o8r5cNu3lG_Q/video.ism/video-fmp4.m3u8'
      }
    ],
    'DASH': [
      {
        'src': 'https://rsdt-krk201-4.tvp.pl/token/video/vod/69230468/20230504/785384984/X2P8b7AC2hD-POBG5j1lWx35b4kPhUN76BrY8Sx2N6hXDVBtsw6o8GFB1VSqmw5aDiZutk97EpJd64s-0KV8ZM7s59QW7UQvuwJQVNIv84e9mTIiuLMsfDRW0bM3EigHpQLnSybEg7TeQPaG_-uSuPPlpVcGlC5o8r5cNu3lG_Q/video.ism/video.mpd'
      }
    ]
  },
  'stripe': {
    'id': 120545,
    'url': 'https://klatki.tvp.pl/rbig69230468/stripe_{index}.jpg',
    'interval': 2,
    'count': 8,
    'width': 640,
    'height': 360
  },
  'externalVideoSource': true
}
```
</details>

According to https://github.com/ytdl-org/youtube-dl/pull/32028, there is a new scheme at TVP; your problem show seems only to be accessible through that scheme. Instead of passing the external ID (`69230468`) it now uses the ID `398869` from the URL. The `videoType=MOVIE` is required: I have no idea if other values exist.

Once the yt-dl PR is merged (or ready), it'll come here.
I'm also surprised to see that it just plays for me in NL now, so I guess they've loosened the restrictions

Resolving patch:
diff --git a/yt_dlp/extractor/tvp.py b/yt_dlp/extractor/tvp.py
--- a/yt_dlp/extractor/tvp.py
+++ b/yt_dlp/extractor/tvp.py
@@ -482,21 +482,34 @@ def _real_extract(self, url):
 class TVPVODBaseIE(InfoExtractor):
     _API_BASE_URL = 'https://vod.tvp.pl/api/products'
 
-    def _call_api(self, resource, video_id, **kwargs):
-        return self._download_json(
+    def _call_api(self, resource, video_id, query={}, **kwargs):
+        is_valid = lambda x: 200 <= x < 300
+        document, urlh = self._download_json_handle(
             f'{self._API_BASE_URL}/{resource}', video_id,
-            query={'lang': 'pl', 'platform': 'BROWSER'}, **kwargs)
-
-    def _parse_video(self, video):
-        return {
-            '_type': 'url',
-            'url': 'tvp:' + video['externalUid'],
-            'ie_key': TVPEmbedIE.ie_key(),
-            'title': video.get('title'),
-            'description': traverse_obj(video, ('lead', 'description')),
-            'age_limit': int_or_none(video.get('rating')),
-            'duration': int_or_none(video.get('duration')),
-        }
+            query={'lang': 'pl', 'platform': 'BROWSER', **query},
+            expected_status=lambda x: is_valid(x) or 400 <= x < 500, **kwargs)
+        if is_valid(urlh.status):
+            return document
+        raise ExtractorError(f'Woronicza said: {document.get("code")} (HTTP {urlh.status})')
+
+    def _parse_video(self, video, with_url=True):
+        info_dict = traverse_obj(video, {
+            'id': ('id', {str_or_none}),
+            'title': 'title',
+            'age_limit': ('rating', {int_or_none}),
+            'duration': ('duration', {int_or_none}),
+            'episode_number': ('number', {int_or_none}),
+            'series': ('season', 'serial', 'title', {str_or_none}),
+            'thumbnails': ('images', ..., ..., {'url': ('url', {url_or_none})}),
+        })
+        info_dict['description'] = clean_html(dict_get(video, ('lead', 'description')))
+        if with_url:
+            info_dict.update({
+                '_type': 'url',
+                'url': video['webUrl'],
+                'ie_key': TVPVODVideoIE.ie_key(),
+            })
+        return info_dict
 
 
 class TVPVODVideoIE(TVPVODBaseIE):
@@ -506,37 +519,70 @@ class TVPVODVideoIE(TVPVODBaseIE):
     _TESTS = [{
         'url': 'https://vod.tvp.pl/dla-dzieci,24/laboratorium-alchemika-odcinki,309338/odcinek-24,S01E24,311357',
         'info_dict': {
-            'id': '60468609',
+            'id': '311357',
             'ext': 'mp4',
-            'title': 'Laboratorium alchemika, Tusze termiczne. Jak zobaczyć niewidoczne. Odcinek 24',
+            'title': 'Tusze termiczne. Jak zobaczyć niewidoczne. Odcinek 24',
             'description': 'md5:1d4098d3e537092ccbac1abf49b7cd4c',
             'duration': 300,
             'episode_number': 24,
             'episode': 'Episode 24',
             'age_limit': 0,
             'series': 'Laboratorium alchemika',
-            'thumbnail': 're:https://.+',
+            'thumbnail': 're:https?://.+',
         },
+        'params': {'skip_download': 'm3u8'},
     }, {
         'url': 'https://vod.tvp.pl/filmy-dokumentalne,163/ukrainski-sluga-narodu,339667',
         'info_dict': {
-            'id': '51640077',
+            'id': '339667',
             'ext': 'mp4',
-            'title': 'Ukraiński sługa narodu, Ukraiński sługa narodu',
-            'series': 'Ukraiński sługa narodu',
+            'title': 'Ukraiński sługa narodu',
             'description': 'md5:b7940c0a8e439b0c81653a986f544ef3',
             'age_limit': 12,
-            'episode': 'Episode 0',
-            'episode_number': 0,
             'duration': 3051,
-            'thumbnail': 're:https://.+',
+            'thumbnail': 're:https?://.+',
+            'subtitles': 'count:2',
         },
+        'params': {'skip_download': 'm3u8'},
+    }, {
+        'note': 'embed fails with "payment required"',
+        'url': 'https://vod.tvp.pl/seriale,18/polowanie-na-cmy-odcinki,390116/odcinek-7,S01E07,398869',
+        'info_dict': {
+            'id': '398869',
+            'ext': 'mp4',
+            'title': 'odc. 7',
+            'description': 'md5:dd2bb33f023dc5c2fbaddfbe4cb5dba0',
+            'duration': 2750,
+            'age_limit': 16,
+            'series': 'Polowanie na ćmy',
+            'episode_number': 7,
+            'episode': 'Episode 7',
+            'thumbnail': 're:https?://.+',
+        },
+        'params': {'skip_download': 'm3u8'},
     }]
 
     def _real_extract(self, url):
         video_id = self._match_id(url)
 
-        return self._parse_video(self._call_api(f'vods/{video_id}', video_id))
+        info_dict = self._parse_video(self._call_api(f'vods/{video_id}', video_id), with_url=False)
+
+        playlist = self._call_api(f'{video_id}/videos/playlist', video_id, query={'videoType': 'MOVIE'})
+
+        info_dict['formats'] = []
+        for manifest_url in traverse_obj(playlist, ('sources', 'HLS', ..., 'src')):
+            info_dict['formats'].extend(self._extract_m3u8_formats(manifest_url, video_id, fatal=False))
+        for manifest_url in traverse_obj(playlist, ('sources', 'DASH', ..., 'src')):
+            info_dict['formats'].extend(self._extract_mpd_formats(manifest_url, video_id, fatal=False))
+
+        info_dict['subtitles'] = {}
+        for sub in playlist.get('subtitles') or []:
+            info_dict['subtitles'].setdefault(sub.get('language') or 'und', []).append({
+                'url': sub['url'],
+                'ext': 'ttml',
+            })
+
+        return info_dict
 
 
 class TVPVODSeriesIE(TVPVODBaseIE):
@@ -551,7 +597,7 @@ class TVPVODSeriesIE(TVPVODBaseIE):
             'age_limit': 12,
             'categories': ['seriale'],
         },
-        'playlist_count': 129,
+        'playlist_count': 130,
     }, {
         'url': 'https://vod.tvp.pl/programy,88/rolnik-szuka-zony-odcinki,284514',
         'only_matching': True,


Test patch: