Compare commits

..
25 Commits
Author SHA1 Message Date
pukkandan c69911e4c1 Release 2021.01.20 2021-01-21 02:51:45 +05:30
pukkandan e7ff505132 [pokemon] Add /#/player URLs (Closes #24) 2021-01-21 02:26:24 +05:30
pukkandan fbced7341d [sponskrub] Better debug output and error message 2021-01-21 01:41:05 +05:30
pukkandan 43820c0370 Improved passing of multiple postprocessor-args
* Added `PP+exe:args` syntax
    If `PP+exe:args` is specifically given, only it used.
    Otherwise, `PP:args` and `exe:args` are combined.
    If none of the `PP`, `exe` or `PP+exe` args are given, `default` is used
    `Default` is purposely left undocumented since it exists only for backward compatibility

* Also added proper handling of args in `EmbedThumbnail`

Related: https://github.com/ytdl-org/youtube-dl/pull/27723
2021-01-21 01:36:10 +05:30
pukkandan 5c610515c9 [TrovoLive] Add extractor (partially fix #20)
Only VOD extractor has been implemented

Related: https://github.com/ytdl-org/youtube-dl/issues/26125
Related: https://github.com/blackjack4494/yt-dlc/issues/220
2021-01-20 00:42:39 +05:30
pukkandan 8a51f56439 [readme] Cleanup options
(Closes #23) :skip ci
2021-01-19 00:56:07 +05:30
pukkandan 67002a5ad8 [EmbedThumbnail] Simplify embedding in mkv (Closes #22) 2021-01-18 19:36:50 +05:30
pukkandan 477cf32f37 [sponskrub] Encode filenames correctly 2021-01-18 19:23:08 +05:30
pukkandan f57adf0e59 [version] update
:skip ci all
2021-01-17 00:36:23 +05:30
pukkandan 298f597b4f Release 2021.01.16 2021-01-17 00:24:52 +05:30
pukkandan e2e43aea21 Portable Configuration file (closes #19)
Inspired by https://github.com/ytdl-org/youtube-dl/pull/27592
2021-01-17 00:05:46 +05:30
pukkandan 30a074c2b6 Update to ytdl-2021.01.16 2021-01-16 18:50:48 +05:30
pukkandan 7bc877a20d Add PyPI release 2021-01-16 01:05:53 +05:30
pukkandan ff0bc1aa4c [version] update
:skip ci all
2021-01-14 22:02:53 +05:30
pukkandan bf5a997e24 Release 2021.01.14 2021-01-14 21:54:03 +05:30
pukkandan 17fa3ee25f Documentation fixes
* Change all links to point to new fork URL
* Changed sponskrub links to my fork of the same
* Other typos
2021-01-14 21:51:14 +05:30
pukkandan 2e8d2629f3 [tiktok] Fix for when share_info is empty
(Related: https://github.com/blackjack4494/yt-dlc/pull/20)
2021-01-14 20:15:36 +05:30
Felix Stuppandpukkandan b4d1044095 [roosterteeth] Changed API endpoint (Closes #16)
New endpoint allows to request metadata for bonus episodes

Authored by Zocker1999NET
2021-01-14 18:56:05 +05:30
pukkandan fd51377c95 [issuetemplates] Change all links to point to new fork URL 2021-01-14 14:29:19 +05:30
pukkandan 44af9751a7 Print full error in verbose for sponskrub 2021-01-14 14:04:33 +05:30
pukkandan 806b05cf7a Fix write_debug in EmbedThumbnail
Closes #17
2021-01-14 14:03:05 +05:30
pukkandan d83cb5312c Fix archive bug introduced in 8b0d7497d5 2021-01-13 21:03:50 +05:30
pukkandan 8b0d7497d5 Added option --break-on-reject
and modified `--break-on-existing`
2021-01-13 06:44:35 +05:30
pukkandan 90505ff153 [readme] Change all links to point to new fork URL 2021-01-13 05:17:31 +05:30
pukkandan 8c1fead3ce [version] update 2021-01-13 03:59:14 +05:30
52 changed files with 1309 additions and 876 deletions
+5 -5
View File
@@ -21,15 +21,15 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is 2021.01.10. If it's not, see https://github.com/pukkandan/yt-dlc on how to update. Issues with outdated version will be REJECTED. - First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is 2021.01.16. If it's not, see https://github.com/pukkandan/yt-dlp on how to update. Issues with outdated version will be REJECTED.
- Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser. - Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser.
- Make sure that all URLs and arguments with special characters are properly quoted or escaped as explained in https://github.com/pukkandan/yt-dlc. - Make sure that all URLs and arguments with special characters are properly quoted or escaped as explained in https://github.com/pukkandan/yt-dlp.
- Search the bugtracker for similar issues: https://github.com/pukkandan/yt-dlc. DO NOT post duplicates. - Search the bugtracker for similar issues: https://github.com/pukkandan/yt-dlp. DO NOT post duplicates.
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
- [ ] I'm reporting a broken site support - [ ] I'm reporting a broken site support
- [ ] I've verified that I'm running yt-dlp version **2021.01.10** - [ ] I've verified that I'm running yt-dlp version **2021.01.16**
- [ ] I've checked that all provided URLs are alive and playable in a browser - [ ] I've checked that all provided URLs are alive and playable in a browser
- [ ] I've checked that all URLs and arguments with special characters are properly quoted or escaped - [ ] I've checked that all URLs and arguments with special characters are properly quoted or escaped
- [ ] I've searched the bugtracker for similar issues including closed ones - [ ] I've searched the bugtracker for similar issues including closed ones
@@ -44,7 +44,7 @@ Add the `-v` flag to your command line you run youtube-dlc with (`youtube-dlc -v
[debug] User config: [] [debug] User config: []
[debug] Command-line args: [u'-v', u'http://www.youtube.com/watch?v=BaW_jenozKcj'] [debug] Command-line args: [u'-v', u'http://www.youtube.com/watch?v=BaW_jenozKcj']
[debug] Encodings: locale cp1251, fs mbcs, out cp866, pref cp1251 [debug] Encodings: locale cp1251, fs mbcs, out cp866, pref cp1251
[debug] yt-dlp version 2021.01.10 [debug] yt-dlp version 2021.01.16
[debug] Python version 2.7.11 - Windows-2003Server-5.2.3790-SP2 [debug] Python version 2.7.11 - Windows-2003Server-5.2.3790-SP2
[debug] exe versions: ffmpeg N-75573-g1d0487f, ffprobe N-75573-g1d0487f, rtmpdump 2.4 [debug] exe versions: ffmpeg N-75573-g1d0487f, ffprobe N-75573-g1d0487f, rtmpdump 2.4
[debug] Proxy map: {} [debug] Proxy map: {}
@@ -21,15 +21,15 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is 2021.01.10. If it's not, see https://github.com/pukkandan/yt-dlc on how to update. Issues with outdated version will be REJECTED. - First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is 2021.01.16. If it's not, see https://github.com/pukkandan/yt-dlp on how to update. Issues with outdated version will be REJECTED.
- Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser. - Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser.
- Make sure that site you are requesting is not dedicated to copyright infringement, see https://github.com/pukkandan/yt-dlc. yt-dlp does not support such sites. In order for site support request to be accepted all provided example URLs should not violate any copyrights. - Make sure that site you are requesting is not dedicated to copyright infringement, see https://github.com/pukkandan/yt-dlp. yt-dlp does not support such sites. In order for site support request to be accepted all provided example URLs should not violate any copyrights.
- Search the bugtracker for similar site support requests: https://github.com/pukkandan/yt-dlc. DO NOT post duplicates. - Search the bugtracker for similar site support requests: https://github.com/pukkandan/yt-dlp. DO NOT post duplicates.
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
- [ ] I'm reporting a new site support request - [ ] I'm reporting a new site support request
- [ ] I've verified that I'm running yt-dlp version **2021.01.10** - [ ] I've verified that I'm running yt-dlp version **2021.01.16**
- [ ] I've checked that all provided URLs are alive and playable in a browser - [ ] I've checked that all provided URLs are alive and playable in a browser
- [ ] I've checked that none of provided URLs violate any copyrights - [ ] I've checked that none of provided URLs violate any copyrights
- [ ] I've searched the bugtracker for similar site support requests including closed ones - [ ] I've searched the bugtracker for similar site support requests including closed ones
@@ -21,13 +21,13 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is 2021.01.10. If it's not, see https://github.com/pukkandan/yt-dlc on how to update. Issues with outdated version will be REJECTED. - First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is 2021.01.16. If it's not, see https://github.com/pukkandan/yt-dlp on how to update. Issues with outdated version will be REJECTED.
- Search the bugtracker for similar site feature requests: https://github.com/pukkandan/yt-dlc. DO NOT post duplicates. - Search the bugtracker for similar site feature requests: https://github.com/pukkandan/yt-dlp. DO NOT post duplicates.
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
- [ ] I'm reporting a site feature request - [ ] I'm reporting a site feature request
- [ ] I've verified that I'm running yt-dlp version **2021.01.10** - [ ] I've verified that I'm running yt-dlp version **2021.01.16**
- [ ] I've searched the bugtracker for similar site feature requests including closed ones - [ ] I've searched the bugtracker for similar site feature requests including closed ones
+6 -6
View File
@@ -21,16 +21,16 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is 2021.01.10. If it's not, see https://github.com/pukkandan/yt-dlc on how to update. Issues with outdated version will be REJECTED. - First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is 2021.01.16. If it's not, see https://github.com/pukkandan/yt-dlp on how to update. Issues with outdated version will be REJECTED.
- Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser. - Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser.
- Make sure that all URLs and arguments with special characters are properly quoted or escaped as explained in https://github.com/pukkandan/yt-dlc. - Make sure that all URLs and arguments with special characters are properly quoted or escaped as explained in https://github.com/pukkandan/yt-dlp.
- Search the bugtracker for similar issues: https://github.com/pukkandan/yt-dlc. DO NOT post duplicates. - Search the bugtracker for similar issues: https://github.com/pukkandan/yt-dlp. DO NOT post duplicates.
- Read bugs section in FAQ: https://github.com/pukkandan/yt-dlc - Read bugs section in FAQ: https://github.com/pukkandan/yt-dlp
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
- [ ] I'm reporting a broken site support issue - [ ] I'm reporting a broken site support issue
- [ ] I've verified that I'm running yt-dlp version **2021.01.10** - [ ] I've verified that I'm running yt-dlp version **2021.01.16**
- [ ] I've checked that all provided URLs are alive and playable in a browser - [ ] I've checked that all provided URLs are alive and playable in a browser
- [ ] I've checked that all URLs and arguments with special characters are properly quoted or escaped - [ ] I've checked that all URLs and arguments with special characters are properly quoted or escaped
- [ ] I've searched the bugtracker for similar bug reports including closed ones - [ ] I've searched the bugtracker for similar bug reports including closed ones
@@ -46,7 +46,7 @@ Add the `-v` flag to your command line you run youtube-dlc with (`youtube-dlc -v
[debug] User config: [] [debug] User config: []
[debug] Command-line args: [u'-v', u'http://www.youtube.com/watch?v=BaW_jenozKcj'] [debug] Command-line args: [u'-v', u'http://www.youtube.com/watch?v=BaW_jenozKcj']
[debug] Encodings: locale cp1251, fs mbcs, out cp866, pref cp1251 [debug] Encodings: locale cp1251, fs mbcs, out cp866, pref cp1251
[debug] yt-dlp version 2021.01.10 [debug] yt-dlp version 2021.01.16
[debug] Python version 2.7.11 - Windows-2003Server-5.2.3790-SP2 [debug] Python version 2.7.11 - Windows-2003Server-5.2.3790-SP2
[debug] exe versions: ffmpeg N-75573-g1d0487f, ffprobe N-75573-g1d0487f, rtmpdump 2.4 [debug] exe versions: ffmpeg N-75573-g1d0487f, ffprobe N-75573-g1d0487f, rtmpdump 2.4
[debug] Proxy map: {} [debug] Proxy map: {}
+3 -3
View File
@@ -21,13 +21,13 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is 2021.01.10. If it's not, see https://github.com/pukkandan/yt-dlc on how to update. Issues with outdated version will be REJECTED. - First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is 2021.01.16. If it's not, see https://github.com/pukkandan/yt-dlp on how to update. Issues with outdated version will be REJECTED.
- Search the bugtracker for similar feature requests: https://github.com/pukkandan/yt-dlc. DO NOT post duplicates. - Search the bugtracker for similar feature requests: https://github.com/pukkandan/yt-dlp. DO NOT post duplicates.
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
- [ ] I'm reporting a feature request - [ ] I'm reporting a feature request
- [ ] I've verified that I'm running yt-dlp version **2021.01.10** - [ ] I've verified that I'm running yt-dlp version **2021.01.16**
- [ ] I've searched the bugtracker for similar feature requests including closed ones - [ ] I've searched the bugtracker for similar feature requests including closed ones
+1 -1
View File
@@ -21,7 +21,7 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- Look through the README (https://github.com/pukkandan/yt-dlc) and FAQ (https://github.com/pukkandan/yt-dlc) for similar questions - Look through the README (https://github.com/pukkandan/yt-dlp) and FAQ (https://github.com/pukkandan/yt-dlp) for similar questions
- Search the bugtracker for similar questions: https://github.com/blackjack4494/yt-dlc - Search the bugtracker for similar questions: https://github.com/blackjack4494/yt-dlc
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
+3 -3
View File
@@ -21,10 +21,10 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is %(version)s. If it's not, see https://github.com/pukkandan/yt-dlc on how to update. Issues with outdated version will be REJECTED. - First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is %(version)s. If it's not, see https://github.com/pukkandan/yt-dlp on how to update. Issues with outdated version will be REJECTED.
- Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser. - Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser.
- Make sure that all URLs and arguments with special characters are properly quoted or escaped as explained in https://github.com/pukkandan/yt-dlc. - Make sure that all URLs and arguments with special characters are properly quoted or escaped as explained in https://github.com/pukkandan/yt-dlp.
- Search the bugtracker for similar issues: https://github.com/pukkandan/yt-dlc. DO NOT post duplicates. - Search the bugtracker for similar issues: https://github.com/pukkandan/yt-dlp. DO NOT post duplicates.
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
@@ -21,10 +21,10 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is %(version)s. If it's not, see https://github.com/pukkandan/yt-dlc on how to update. Issues with outdated version will be REJECTED. - First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is %(version)s. If it's not, see https://github.com/pukkandan/yt-dlp on how to update. Issues with outdated version will be REJECTED.
- Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser. - Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser.
- Make sure that site you are requesting is not dedicated to copyright infringement, see https://github.com/pukkandan/yt-dlc. yt-dlp does not support such sites. In order for site support request to be accepted all provided example URLs should not violate any copyrights. - Make sure that site you are requesting is not dedicated to copyright infringement, see https://github.com/pukkandan/yt-dlp. yt-dlp does not support such sites. In order for site support request to be accepted all provided example URLs should not violate any copyrights.
- Search the bugtracker for similar site support requests: https://github.com/pukkandan/yt-dlc. DO NOT post duplicates. - Search the bugtracker for similar site support requests: https://github.com/pukkandan/yt-dlp. DO NOT post duplicates.
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
@@ -21,8 +21,8 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is %(version)s. If it's not, see https://github.com/pukkandan/yt-dlc on how to update. Issues with outdated version will be REJECTED. - First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is %(version)s. If it's not, see https://github.com/pukkandan/yt-dlp on how to update. Issues with outdated version will be REJECTED.
- Search the bugtracker for similar site feature requests: https://github.com/pukkandan/yt-dlc. DO NOT post duplicates. - Search the bugtracker for similar site feature requests: https://github.com/pukkandan/yt-dlp. DO NOT post duplicates.
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
+4 -4
View File
@@ -21,11 +21,11 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is %(version)s. If it's not, see https://github.com/pukkandan/yt-dlc on how to update. Issues with outdated version will be REJECTED. - First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is %(version)s. If it's not, see https://github.com/pukkandan/yt-dlp on how to update. Issues with outdated version will be REJECTED.
- Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser. - Make sure that all provided video/audio/playlist URLs (if any) are alive and playable in a browser.
- Make sure that all URLs and arguments with special characters are properly quoted or escaped as explained in https://github.com/pukkandan/yt-dlc. - Make sure that all URLs and arguments with special characters are properly quoted or escaped as explained in https://github.com/pukkandan/yt-dlp.
- Search the bugtracker for similar issues: https://github.com/pukkandan/yt-dlc. DO NOT post duplicates. - Search the bugtracker for similar issues: https://github.com/pukkandan/yt-dlp. DO NOT post duplicates.
- Read bugs section in FAQ: https://github.com/pukkandan/yt-dlc - Read bugs section in FAQ: https://github.com/pukkandan/yt-dlp
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
@@ -21,8 +21,8 @@ assignees: ''
<!-- <!--
Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc: Carefully read and work through this check list in order to prevent the most common mistakes and misuse of youtube-dlc:
- First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is %(version)s. If it's not, see https://github.com/pukkandan/yt-dlc on how to update. Issues with outdated version will be REJECTED. - First of, make sure you are using the latest version of yt-dlp. Run `youtube-dlc --version` and ensure your version is %(version)s. If it's not, see https://github.com/pukkandan/yt-dlp on how to update. Issues with outdated version will be REJECTED.
- Search the bugtracker for similar feature requests: https://github.com/pukkandan/yt-dlc. DO NOT post duplicates. - Search the bugtracker for similar feature requests: https://github.com/pukkandan/yt-dlp. DO NOT post duplicates.
- Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space) - Finally, put x into all relevant boxes like this [x] (Dont forget to delete the empty space)
--> -->
+1 -1
View File
@@ -8,7 +8,7 @@
### Before submitting a *pull request* make sure you have: ### Before submitting a *pull request* make sure you have:
- [ ] At least skimmed through [adding new extractor tutorial](https://github.com/ytdl-org/youtube-dl#adding-support-for-a-new-site) and [youtube-dl coding conventions](https://github.com/ytdl-org/youtube-dl#youtube-dl-coding-conventions) sections - [ ] At least skimmed through [adding new extractor tutorial](https://github.com/ytdl-org/youtube-dl#adding-support-for-a-new-site) and [youtube-dl coding conventions](https://github.com/ytdl-org/youtube-dl#youtube-dl-coding-conventions) sections
- [ ] [Searched](https://github.com/pukkandan/yt-dlc/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [ ] [Searched](https://github.com/pukkandan/yt-dlp/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests
- [ ] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) - [ ] Checked the code with [flake8](https://pypi.python.org/pypi/flake8)
### In order to be accepted and merged into youtube-dl each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: ### In order to be accepted and merged into youtube-dl each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options:
+13 -13
View File
@@ -37,7 +37,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
tag_name: ${{ steps.bump_version.outputs.ytdlc_version }} tag_name: ${{ steps.bump_version.outputs.ytdlc_version }}
release_name: youtube-dlc ${{ steps.bump_version.outputs.ytdlc_version }} release_name: yt-dlp ${{ steps.bump_version.outputs.ytdlc_version }}
body: | body: |
Changelog: Changelog:
PLACEHOLDER PLACEHOLDER
@@ -58,18 +58,18 @@ jobs:
env: env:
SHA2: ${{ hashFiles('youtube-dlc') }} SHA2: ${{ hashFiles('youtube-dlc') }}
run: echo "::set-output name=sha2_unix::$SHA2" run: echo "::set-output name=sha2_unix::$SHA2"
# - name: Install dependencies for pypi - name: Install dependencies for pypi
# run: | run: |
# python -m pip install --upgrade pip python -m pip install --upgrade pip
# pip install setuptools wheel twine pip install setuptools wheel twine
# - name: Build and publish - name: Build and publish on pypi
# env: env:
# TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} TWINE_USERNAME: __token__
# TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
# run: | run: |
# rm -rf dist/* rm -rf dist/*
# python setup.py sdist bdist_wheel python setup.py sdist bdist_wheel
# twine upload dist/* twine upload dist/*
build_windows: build_windows:
+1 -1
View File
@@ -1,5 +1,5 @@
name: Full Test name: Full Test
on: [push] on: [push, pull_request]
jobs: jobs:
tests: tests:
name: Tests name: Tests
@@ -1,33 +0,0 @@
# This workflows will upload a Python Package using Twine when a release is created
# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
name: Upload Python Package
on:
push:
branches:
- release
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
- name: Build and publish
env:
TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
run: |
rm -rf dist/*
python setup.py sdist bdist_wheel
twine upload dist/*
+1 -1
View File
@@ -1,5 +1,5 @@
name: Core Test name: Core Test
on: [push] on: [push, pull_request]
jobs: jobs:
tests: tests:
name: Core Tests name: Core Tests
+2
View File
@@ -46,8 +46,10 @@ updates_key.pem
*.swf *.swf
*.part *.part
*.ytdl *.ytdl
*.conf
*.swp *.swp
*.spec *.spec
*.exe
test/local_parameters.json test/local_parameters.json
.tox .tox
youtube-dl.zsh youtube-dl.zsh
+2 -1
View File
@@ -14,4 +14,5 @@ mariuszskon
ohnonot ohnonot
samiksome samiksome
alxnull alxnull
FelixFrog FelixFrog
Zocker1999NET
+29 -3
View File
@@ -15,9 +15,35 @@
--> -->
### 2021.01.20
* [TrovoLive] Add extractor (only VODs)
* [pokemon] Add `/#/player` URLs (Closes #24)
* Improved parsing of multiple postprocessor-args, add `--ppa` as alias
* [EmbedThumbnail] Simplify embedding in mkv
* [sponskrub] Encode filenames correctly, better debug output and error message
* [readme] Cleanup options
### 2021.01.16
* **Merge youtube-dl:** Upto [2021.01.16](https://github.com/ytdl-org/youtube-dl/releases/tag/2021.01.16)
* **Configuration files:**
* Portable configuration file: `./yt-dlp.conf`
* Allow the configuration files to be named `yt-dlp` instead of `youtube-dlc`. See [this](https://github.com/pukkandan/yt-dlp#configuration) for details
* Add PyPI release
### 2021.01.14
* Added option `--break-on-reject`
* [roosterteeth.com] Fix for bonus episodes by @Zocker1999NET
* [tiktok] Fix for when share_info is empty
* [EmbedThumbnail] Fix bug due to incorrect function name
* [documentation] Changed sponskrub links to point to [pukkandan/sponskrub](https://github.com/pukkandan/SponSkrub) since I am now providing both linux and windows releases
* [documentation] Change all links to correctly point to new fork URL
* [documentation] Fixes typos
### 2021.01.12 ### 2021.01.12
* [roosterteeth.com] Add subtitle support by @samiksome * [roosterteeth.com] Add subtitle support by @samiksome
* Added `--force-overwrites` by @alxnull * Added `--force-overwrites`, `--no-force-overwrites` by @alxnull
* Changed fork name to `yt-dlp` * Changed fork name to `yt-dlp`
* Fix typos by @FelixFrog * Fix typos by @FelixFrog
* [ci] Option to skip * [ci] Option to skip
@@ -44,7 +70,7 @@
### 2021.01.08 ### 2021.01.08
* **Merge youtube-dl:** Upto [2021.01.08](https://github.com/ytdl-org/youtube-dl/commit/bf6a74c620bd4d5726503c5302906bb36b009026) * **Merge youtube-dl:** Upto [2021.01.08](https://github.com/ytdl-org/youtube-dl/releases/tag/2021.01.08)
* Extractor stitcher ([1](https://github.com/ytdl-org/youtube-dl/commit/bb38a1215718cdf36d73ff0a7830a64cd9fa37cc), [2](https://github.com/ytdl-org/youtube-dl/commit/a563c97c5cddf55f8989ed7ea8314ef78e30107f)) have not been merged * Extractor stitcher ([1](https://github.com/ytdl-org/youtube-dl/commit/bb38a1215718cdf36d73ff0a7830a64cd9fa37cc), [2](https://github.com/ytdl-org/youtube-dl/commit/a563c97c5cddf55f8989ed7ea8314ef78e30107f)) have not been merged
* Moved changelog to seperate file * Moved changelog to seperate file
@@ -86,7 +112,7 @@
* Added `b`,`w`,`v`,`a` as alias for `best`, `worst`, `video` and `audio` respectively * Added `b`,`w`,`v`,`a` as alias for `best`, `worst`, `video` and `audio` respectively
* **Shortcut Options:** Added `--write-link`, `--write-url-link`, `--write-webloc-link`, `--write-desktop-link` by @h-h-h-h - See [Internet Shortcut Options]README.md(#internet-shortcut-options) for details * **Shortcut Options:** Added `--write-link`, `--write-url-link`, `--write-webloc-link`, `--write-desktop-link` by @h-h-h-h - See [Internet Shortcut Options]README.md(#internet-shortcut-options) for details
* **Sponskrub integration:** Added `--sponskrub`, `--sponskrub-cut`, `--sponskrub-force`, `--sponskrub-location`, `--sponskrub-args` - See [SponSkrub Options](README.md#sponskrub-options-sponsorblock) for details * **Sponskrub integration:** Added `--sponskrub`, `--sponskrub-cut`, `--sponskrub-force`, `--sponskrub-location`, `--sponskrub-args` - See [SponSkrub Options](README.md#sponskrub-options-sponsorblock) for details
* Added `--force-download-archive` (`--force-write-archive`) by by h-h-h-h * Added `--force-download-archive` (`--force-write-archive`) by @h-h-h-h
* Added `--list-formats-as-table`, `--list-formats-old` * Added `--list-formats-as-table`, `--list-formats-old`
* **Negative Options:** Makes it possible to negate most boolean options by adding a `no-` to the switch. Usefull when you want to reverse an option that is defined in a config file * **Negative Options:** Makes it possible to negate most boolean options by adding a `no-` to the switch. Usefull when you want to reverse an option that is defined in a config file
* Added `--no-ignore-dynamic-mpd`, `--no-allow-dynamic-mpd`, `--allow-dynamic-mpd`, `--youtube-include-hls-manifest`, `--no-youtube-include-hls-manifest`, `--no-youtube-skip-hls-manifest`, `--no-download`, `--no-download-archive`, `--resize-buffer`, `--part`, `--mtime`, `--no-keep-fragments`, `--no-cookies`, `--no-write-annotations`, `--no-write-info-json`, `--no-write-description`, `--no-write-thumbnail`, `--youtube-include-dash-manifest`, `--post-overwrites`, `--no-keep-video`, `--no-embed-subs`, `--no-embed-thumbnail`, `--no-add-metadata`, `--no-include-ads`, `--no-write-sub`, `--no-write-auto-sub`, `--no-playlist-reverse`, `--no-restrict-filenames`, `--youtube-include-dash-manifest`, `--no-format-sort-force`, `--flat-videos`, `--no-list-formats-as-table`, `--no-sponskrub`, `--no-sponskrub-cut`, `--no-sponskrub-force` * Added `--no-ignore-dynamic-mpd`, `--no-allow-dynamic-mpd`, `--allow-dynamic-mpd`, `--youtube-include-hls-manifest`, `--no-youtube-include-hls-manifest`, `--no-youtube-skip-hls-manifest`, `--no-download`, `--no-download-archive`, `--resize-buffer`, `--part`, `--mtime`, `--no-keep-fragments`, `--no-cookies`, `--no-write-annotations`, `--no-write-info-json`, `--no-write-description`, `--no-write-thumbnail`, `--youtube-include-dash-manifest`, `--post-overwrites`, `--no-keep-video`, `--no-embed-subs`, `--no-embed-thumbnail`, `--no-add-metadata`, `--no-include-ads`, `--no-write-sub`, `--no-write-auto-sub`, `--no-playlist-reverse`, `--no-restrict-filenames`, `--youtube-include-dash-manifest`, `--no-format-sort-force`, `--flat-videos`, `--no-list-formats-as-table`, `--no-sponskrub`, `--no-sponskrub-cut`, `--no-sponskrub-force`
+4 -2
View File
@@ -1,8 +1,10 @@
all: youtube-dlc README.md CONTRIBUTING.md README.txt issuetemplates youtube-dlc.1 youtube-dlc.bash-completion youtube-dlc.zsh youtube-dlc.fish supportedsites all: youtube-dlc doc man
doc: README.md CONTRIBUTING.md issuetemplates supportedsites doc: README.md CONTRIBUTING.md issuetemplates supportedsites
man: README.txt youtube-dlc.1 youtube-dlc.bash-completion youtube-dlc.zsh youtube-dlc.fish
clean: clean:
rm -rf youtube-dlc.1.temp.md youtube-dlc.1 youtube-dlc.bash-completion README.txt MANIFEST build/ dist/ .coverage cover/ youtube-dlc.tar.gz youtube-dlc.zsh youtube-dlc.fish youtube_dlc/extractor/lazy_extractors.py *.dump *.part* *.ytdl *.info.json *.mp4 *.m4a *.flv *.mp3 *.avi *.mkv *.webm *.3gp *.wav *.ape *.swf *.jpg *.png CONTRIBUTING.md.tmp youtube-dlc youtube-dlc.exe rm -rf youtube-dlc.1.temp.md youtube-dlc.1 youtube-dlc.bash-completion README.txt MANIFEST build/ dist/ .coverage cover/ youtube-dlc.tar.gz youtube-dlc.zsh youtube-dlc.fish youtube_dlc/extractor/lazy_extractors.py *.dump *.part* *.ytdl *.info.json *.mp4 *.m4a *.flv *.mp3 *.avi *.mkv *.webm *.3gp *.wav *.ape *.swf *.jpg *.png *.spec CONTRIBUTING.md.tmp youtube-dlc youtube-dlc.exe
find . -name "*.pyc" -delete find . -name "*.pyc" -delete
find . -name "*.class" -delete find . -name "*.class" -delete
+149 -123
View File
@@ -1,10 +1,10 @@
# YT-DLP # YT-DLP
<!-- See: https://github.com/marketplace/actions/dynamic-badges --> <!-- See: https://github.com/marketplace/actions/dynamic-badges -->
[![Release Version](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/pukkandan/c69cb23c3c5b3316248e52022790aa57/raw/version.json&color=brightgreen)](https://github.com/pukkandan/yt-dlc/releases/latest) [![Release Version](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/pukkandan/c69cb23c3c5b3316248e52022790aa57/raw/version.json&color=brightgreen)](https://github.com/pukkandan/yt-dlp/releases/latest)
[![License: Unlicense](https://img.shields.io/badge/License-Unlicense-blue.svg)](https://github.com/pukkandan/yt-dlc/blob/master/LICENSE) [![License: Unlicense](https://img.shields.io/badge/License-Unlicense-blue.svg)](https://github.com/pukkandan/yt-dlp/blob/master/LICENSE)
[![Core Status](https://github.com/pukkandan/yt-dlc/workflows/Core%20Test/badge.svg?branch=master)](https://github.com/pukkandan/yt-dlc/actions?query=workflow%3ACore) [![Core Status](https://github.com/pukkandan/yt-dlp/workflows/Core%20Test/badge.svg?branch=master)](https://github.com/pukkandan/yt-dlp/actions?query=workflow%3ACore)
[![CI Status](https://github.com/pukkandan/yt-dlc/workflows/Full%20Test/badge.svg?branch=master)](https://github.com/pukkandan/yt-dlc/actions?query=workflow%3AFull) [![CI Status](https://github.com/pukkandan/yt-dlp/workflows/Full%20Test/badge.svg?branch=master)](https://github.com/pukkandan/yt-dlp/actions?query=workflow%3AFull)
A command-line program to download videos from youtube.com and many other [video platforms](docs/supportedsites.md) A command-line program to download videos from youtube.com and many other [video platforms](docs/supportedsites.md)
@@ -12,8 +12,8 @@ This is a fork of [youtube-dlc](https://github.com/blackjack4494/yt-dlc) which i
* [NEW FEATURES](#new-features) * [NEW FEATURES](#new-features)
* [INSTALLATION](#installation) * [INSTALLATION](#installation)
* [UPDATE](#update) * [Update](#update)
* [COMPILE](#compile) * [Compile](#compile)
* [DESCRIPTION](#description) * [DESCRIPTION](#description)
* [OPTIONS](#options) * [OPTIONS](#options)
* [Network Options](#network-options) * [Network Options](#network-options)
@@ -30,7 +30,7 @@ This is a fork of [youtube-dlc](https://github.com/blackjack4494/yt-dlc) which i
* [Authentication Options](#authentication-options) * [Authentication Options](#authentication-options)
* [Adobe Pass Options](#adobe-pass-options) * [Adobe Pass Options](#adobe-pass-options)
* [Post-processing Options](#post-processing-options) * [Post-processing Options](#post-processing-options)
* [SponSkrub Options (SponsorBlock)](#sponSkrub-options-sponsorblock) * [SponSkrub (SponsorBlock) Options](#sponskrub-sponsorblock-options)
* [Extractor Options](#extractor-options) * [Extractor Options](#extractor-options)
* [CONFIGURATION](#configuration) * [CONFIGURATION](#configuration)
* [Authentication with .netrc file](#authentication-with-netrc-file) * [Authentication with .netrc file](#authentication-with-netrc-file)
@@ -41,49 +41,49 @@ This is a fork of [youtube-dlc](https://github.com/blackjack4494/yt-dlc) which i
* [Filtering Formats](#filtering-formats) * [Filtering Formats](#filtering-formats)
* [Sorting Formats](#sorting-formats) * [Sorting Formats](#sorting-formats)
* [Format Selection examples](#format-selection-examples) * [Format Selection examples](#format-selection-examples)
* [VIDEO SELECTION](#video-selection-1)
* [MORE](#more) * [MORE](#more)
# NEW FEATURES # NEW FEATURES
The major new features from the latest release of [blackjack4494/yt-dlc](https://github.com/blackjack4494/yt-dlc) are: The major new features from the latest release of [blackjack4494/yt-dlc](https://github.com/blackjack4494/yt-dlc) are:
* **[SponSkrub Integration](#sponSkrub-options-sponsorblock)**: You can use [SponSkrub](https://github.com/faissaloo/SponSkrub) to mark/remove sponsor sections in youtube videos by utilizing the [SponsorBlock](https://sponsor.ajay.app) API * **[SponSkrub Integration](#sponskrub-sponsorblock-options)**: You can use [SponSkrub](https://github.com/pukkandan/SponSkrub) to mark/remove sponsor sections in youtube videos by utilizing the [SponsorBlock](https://sponsor.ajay.app) API
* **[Format Sorting](#sorting-formats)**: The default format sorting options have been changed so that higher resolution and better codecs will be now prefered instead of simply using larger bitrate. Furthermore, you can now specify the sort order using `-S`. This allows for much easier format selection that what is possible by simply using `--format` ([examples](#format-selection-examples)) * **[Format Sorting](#sorting-formats)**: The default format sorting options have been changed so that higher resolution and better codecs will be now preferred instead of simply using larger bitrate. Furthermore, you can now specify the sort order using `-S`. This allows for much easier format selection that what is possible by simply using `--format` ([examples](#format-selection-examples))
* Merged with youtube-dl **v2020.01.08**: You get all the latest features and patches of [youtube-dl](https://github.com/ytdl-org/youtube-dl) in addition to all the features of [youtube-dlc](https://github.com/blackjack4494) * **Merged with youtube-dl v2021.01.16**: You get all the latest features and patches of [youtube-dl](https://github.com/ytdl-org/youtube-dl) in addition to all the features of [youtube-dlc](https://github.com/blackjack4494/yt-dlc)
* **Youtube improvements**: * **Youtube improvements**:
* All Youtube Feeds (`:ytfav`, `:ytwatchlater`, `:ytsubs`, `:ythistory`, `:ytrec`) works correctly and support downloading multiple pages of content * All Youtube Feeds (`:ytfav`, `:ytwatchlater`, `:ytsubs`, `:ythistory`, `:ytrec`) works correctly and support downloading multiple pages of content
* Youtube search works correctly (`ytsearch:`, `ytsearchdate:`) along with Search URLs * Youtube search works correctly (`ytsearch:`, `ytsearchdate:`) along with Search URLs
* Redirect channel's home URL automatically to `/video` to preserve the old behaviour * Redirect channel's home URL automatically to `/video` to preserve the old behaviour
* **New extractors**: AnimeLab, Philo MSO, Rcs, Gedi, bitwave.tv * **New extractors**: Trovo.live, AnimeLab, Philo MSO, Rcs, Gedi, bitwave.tv
* **Fixed extractors**: archive.org, roosterteeth.com, skyit, instagram, itv, SouthparkDe, spreaker, Vlive, tiktok, akamai, ina * **Fixed extractors**: archive.org, roosterteeth.com, skyit, instagram, itv, SouthparkDe, spreaker, Vlive, tiktok, akamai, ina
* **New options**: `--list-formats-as-table`, `--write-link`, `--force-download-archive` etc * **New options**: `--list-formats-as-table`, `--write-link`, `--force-download-archive`, `--force-overwrites`, `--break-on-reject` etc
and many other features and patches. See [changelog](Changelog.md) or [commits](https://github.com/pukkandan/yt-dlc/commits) for the full list of changes * **Improvements**: Multiple `--postprocessor-args`, `%(duration_string)s` in `-o`, faster archive checking, more [format selection options](#format-selection) etc
See [changelog](Changelog.md) or [commits](https://github.com/pukkandan/yt-dlp/commits) for the full list of changes
**PS**: Some of these changes are already in youtube-dlc, but are still unreleased. See [this](changelog.md#unreleased-changes-in-blackjack4494yt-dlc) for details **PS**: Some of these changes are already in youtube-dlc, but are still unreleased. See [this](Changelog.md#unreleased-changes-in-blackjack4494yt-dlc) for details
If you are coming from [youtube-dl](https://github.com/ytdl-org/youtube-dl), the amount of changes are very large. Compare [options](#options) and [supported sites](docs/supportedsites.md) with youtube-dl's to get an idea of the massive number of features/patches [youtube-dlc](https://github.com/blackjack4494/yt-dlc) has accumulated. If you are coming from [youtube-dl](https://github.com/ytdl-org/youtube-dl), the amount of changes are very large. Compare [options](#options) and [supported sites](docs/supportedsites.md) with youtube-dl's to get an idea of the massive number of features/patches [youtube-dlc](https://github.com/blackjack4494/yt-dlc) has accumulated.
# INSTALLATION # INSTALLATION
To use the latest version, simply download and run the [latest release](https://github.com/pukkandan/yt-dlc/releases/latest). You can install yt-dlp using one of the following methods:
Currently, there is no support for any package managers. * Use [PyPI package](https://pypi.org/project/yt-dlp/): `python -m pip install --upgrade yt-dlp`
* Download the binary from the [latest release](https://github.com/pukkandan/yt-dlp/releases/latest)
If you want to install the current master branch * Use pip+git: `python -m pip install --upgrade git+https://github.com/pukkandan/yt-dlp.git@release`
* Install master branch: `python -m pip install --upgrade git+https://github.com/pukkandan/yt-dlp`
python -m pip install git+https://github.com/pukkandan/yt-dlc
### UPDATE ### UPDATE
**DO NOT UPDATE using `-U` !** instead download binaries again `-U` does not work. Simply repeat the install process to update.
### COMPILE ### COMPILE
@@ -125,9 +125,9 @@ Then simply type this
permissions (run with sudo if needed) permissions (run with sudo if needed)
-i, --ignore-errors Continue on download errors, for example to -i, --ignore-errors Continue on download errors, for example to
skip unavailable videos in a playlist skip unavailable videos in a playlist
(default) (Same as --no-abort-on-error) (default) (Alias: --no-abort-on-error)
--abort-on-error Abort downloading of further videos if an --abort-on-error Abort downloading of further videos if an
error occurs (Same as --no-ignore-errors) error occurs (Alias: --no-ignore-errors)
--dump-user-agent Display the current browser identification --dump-user-agent Display the current browser identification
--list-extractors List all supported extractors --list-extractors List all supported extractors
--extractor-descriptions Output descriptions of all supported --extractor-descriptions Output descriptions of all supported
@@ -142,23 +142,25 @@ Then simply type this
warning when guessing). "error" just throws warning when guessing). "error" just throws
an error. The default value "fixup_error" an error. The default value "fixup_error"
repairs broken URLs, but emits an error if repairs broken URLs, but emits an error if
this is not possible instead of searching. this is not possible instead of searching
--ignore-config, --no-config Do not read configuration files. When given --ignore-config, --no-config Disable loading any configuration files
in the global configuration file except the one provided by --config-location.
/etc/youtube-dl.conf: Do not read the user When given inside a configuration
configuration in ~/.config/youtube- file, no further configuration files are
dl/config (%APPDATA%/youtube-dl/config.txt loaded. Additionally, (for backward
on Windows) compatibility) if this option is found
inside the system configuration file, the
user configuration is not loaded
--config-location PATH Location of the configuration file; either --config-location PATH Location of the configuration file; either
the path to the config or its containing the path to the config or its containing
directory. directory
--flat-playlist Do not extract the videos of a playlist, --flat-playlist Do not extract the videos of a playlist,
only list them. only list them
--flat-videos Do not resolve the video urls --flat-videos Do not resolve the video urls
--no-flat-playlist Extract the videos of a playlist --no-flat-playlist Extract the videos of a playlist
--mark-watched Mark videos watched (YouTube only) --mark-watched Mark videos watched (YouTube only)
--no-mark-watched Do not mark videos watched --no-mark-watched Do not mark videos watched
--no-color Do not emit color codes in output --no-colors Do not emit color codes in output
## Network Options: ## Network Options:
--proxy URL Use the specified HTTP/HTTPS/SOCKS proxy. --proxy URL Use the specified HTTP/HTTPS/SOCKS proxy.
@@ -176,7 +178,7 @@ Then simply type this
some geo-restricted sites. The default some geo-restricted sites. The default
proxy specified by --proxy (or none, if the proxy specified by --proxy (or none, if the
option is not present) is used for the option is not present) is used for the
actual downloading. actual downloading
--geo-bypass Bypass geographic restriction via faking --geo-bypass Bypass geographic restriction via faking
X-Forwarded-For HTTP header X-Forwarded-For HTTP header
--no-geo-bypass Do not bypass geographic restriction via --no-geo-bypass Do not bypass geographic restriction via
@@ -198,7 +200,7 @@ Then simply type this
indexed 1, 2, 5, 8 in the playlist. You can indexed 1, 2, 5, 8 in the playlist. You can
specify range: "--playlist-items specify range: "--playlist-items
1-3,7,10-13", it will download the videos 1-3,7,10-13", it will download the videos
at index 1, 2, 3, 7, 10, 11, 12 and 13. at index 1, 2, 3, 7, 10, 11, 12 and 13
--match-title REGEX Download only matching titles (regex or --match-title REGEX Download only matching titles (regex or
caseless sub-string) caseless sub-string)
--reject-title REGEX Skip download for matching titles (regex or --reject-title REGEX Skip download for matching titles (regex or
@@ -222,36 +224,38 @@ Then simply type this
--max-views COUNT Do not download any videos with more than --max-views COUNT Do not download any videos with more than
COUNT views COUNT views
--match-filter FILTER Generic video filter. Specify any key (see --match-filter FILTER Generic video filter. Specify any key (see
the "OUTPUT TEMPLATE" for a list of "OUTPUT TEMPLATE" for a list of available
available keys) to match if the key is keys) to match if the key is present, !key
present, !key to check if the key is not to check if the key is not present,
present, key > NUMBER (like "comment_count key>NUMBER (like "comment_count > 12", also
> 12", also works with >=, <, <=, !=, =) to works with >=, <, <=, !=, =) to compare
compare against a number, key = 'LITERAL' against a number, key = 'LITERAL' (like
(like "uploader = 'Mike Smith'", also works "uploader = 'Mike Smith'", also works with
with !=) to match against a string literal !=) to match against a string literal and &
and & to require multiple matches. Values to require multiple matches. Values which
which are not known are excluded unless you are not known are excluded unless you put a
put a question mark (?) after the operator. question mark (?) after the operator. For
For example, to only match videos that have example, to only match videos that have
been liked more than 100 times and disliked been liked more than 100 times and disliked
less than 50 times (or the dislike less than 50 times (or the dislike
functionality is not available at the given functionality is not available at the given
service), but who also have a description, service), but who also have a description,
use --match-filter "like_count > 100 & use --match-filter "like_count > 100 &
dislike_count <? 50 & description" . dislike_count <? 50 & description"
--no-match-filter Do not use generic video filter (default) --no-match-filter Do not use generic video filter (default)
--no-playlist Download only the video, if the URL refers --no-playlist Download only the video, if the URL refers
to a video and a playlist. to a video and a playlist
--yes-playlist Download the playlist, if the URL refers to --yes-playlist Download the playlist, if the URL refers to
a video and a playlist. a video and a playlist
--age-limit YEARS Download only videos suitable for the given --age-limit YEARS Download only videos suitable for the given
age age
--download-archive FILE Download only videos not listed in the --download-archive FILE Download only videos not listed in the
archive file. Record the IDs of all archive file. Record the IDs of all
downloaded videos in it. downloaded videos in it
--break-on-existing Stop the download process after attempting --break-on-existing Stop the download process when encountering
to download a file that's in the archive. a file that is in the archive
--break-on-reject Stop the download process when encountering
a file that has been filtered out
--no-download-archive Do not use archive file (default) --no-download-archive Do not use archive file (default)
--include-ads Download advertisements as well --include-ads Download advertisements as well
(experimental) (experimental)
@@ -261,15 +265,15 @@ Then simply type this
-r, --limit-rate RATE Maximum download rate in bytes per second -r, --limit-rate RATE Maximum download rate in bytes per second
(e.g. 50K or 4.2M) (e.g. 50K or 4.2M)
-R, --retries RETRIES Number of retries (default is 10), or -R, --retries RETRIES Number of retries (default is 10), or
"infinite". "infinite"
--fragment-retries RETRIES Number of retries for a fragment (default --fragment-retries RETRIES Number of retries for a fragment (default
is 10), or "infinite" (DASH, hlsnative and is 10), or "infinite" (DASH, hlsnative and
ISM) ISM)
--skip-unavailable-fragments Skip unavailable fragments for DASH, --skip-unavailable-fragments Skip unavailable fragments for DASH,
hlsnative and ISM (default) hlsnative and ISM (default)
(Same as --no-abort-on-unavailable-fragment) (Alias: --no-abort-on-unavailable-fragment)
--abort-on-unavailable-fragment Abort downloading if a fragment is unavailable --abort-on-unavailable-fragment Abort downloading if a fragment is unavailable
(Same as --no-skip-unavailable-fragments) (Alias: --no-skip-unavailable-fragments)
--keep-fragments Keep downloaded fragments on disk after --keep-fragments Keep downloaded fragments on disk after
downloading is finished downloading is finished
--no-keep-fragments Delete downloaded fragments after --no-keep-fragments Delete downloaded fragments after
@@ -309,8 +313,8 @@ Then simply type this
-a, --batch-file FILE File containing URLs to download ('-' for -a, --batch-file FILE File containing URLs to download ('-' for
stdin), one URL per line. Lines starting stdin), one URL per line. Lines starting
with '#', ';' or ']' are considered as with '#', ';' or ']' are considered as
comments and ignored. comments and ignored
-o, --output TEMPLATE Output filename template, see the "OUTPUT -o, --output TEMPLATE Output filename template, see "OUTPUT
TEMPLATE" for details TEMPLATE" for details
--autonumber-start NUMBER Specify the start value for %(autonumber)s --autonumber-start NUMBER Specify the start value for %(autonumber)s
(default is 1) (default is 1)
@@ -356,7 +360,7 @@ Then simply type this
~/.cache/youtube-dl . At the moment, only ~/.cache/youtube-dl . At the moment, only
YouTube player files (for videos with YouTube player files (for videos with
obfuscated signatures) are cached, but that obfuscated signatures) are cached, but that
may change. may change
--no-cache-dir Disable filesystem caching --no-cache-dir Disable filesystem caching
--rm-cache-dir Delete all filesystem cache files --rm-cache-dir Delete all filesystem cache files
--trim-file-name LENGTH Limit the filename length (extension --trim-file-name LENGTH Limit the filename length (extension
@@ -371,13 +375,13 @@ Then simply type this
formats formats
## Internet Shortcut Options: ## Internet Shortcut Options:
--write-link Write an internet shortcut file, depending on --write-link Write an internet shortcut file, depending
the current platform (.url/.webloc/.desktop). on the current platform (.url, .webloc or
The URL may be cached by the OS. .desktop). The URL may be cached by the OS
--write-url-link Write a Windows .url internet shortcut file. --write-url-link Write a .url Windows internet shortcut. The
(The OS caches the URL based on the file path) OS caches the URL based on the file path
--write-webloc-link Write a .webloc macOS internet shortcut file --write-webloc-link Write a .webloc macOS internet shortcut
--write-desktop-link Write a .desktop Linux internet shortcut file --write-desktop-link Write a .desktop Linux internet shortcut
## Verbosity / Simulation Options: ## Verbosity / Simulation Options:
-q, --quiet Activate quiet mode -q, --quiet Activate quiet mode
@@ -394,18 +398,18 @@ Then simply type this
--get-filename Simulate, quiet but print output filename --get-filename Simulate, quiet but print output filename
--get-format Simulate, quiet but print output format --get-format Simulate, quiet but print output format
-j, --dump-json Simulate, quiet but print JSON information. -j, --dump-json Simulate, quiet but print JSON information.
See the "OUTPUT TEMPLATE" for a description See "OUTPUT TEMPLATE" for a description of
of available keys. available keys
-J, --dump-single-json Simulate, quiet but print JSON information -J, --dump-single-json Simulate, quiet but print JSON information
for each command-line argument. If the URL for each command-line argument. If the URL
refers to a playlist, dump the whole refers to a playlist, dump the whole
playlist information in a single line. playlist information in a single line
--print-json Be quiet and print the video information as --print-json Be quiet and print the video information as
JSON (video is still being downloaded). JSON (video is still being downloaded)
--force-write-archive Force download archive entries to be written --force-write-archive Force download archive entries to be
as far as no errors occur, even if -s or written as far as no errors occur,even if
another simulation switch is used. -s or another simulation switch is used
(Same as --force-download-archive) (Alias: --force-download-archive)
--newline Output progress bar as new lines --newline Output progress bar as new lines
--no-progress Do not print progress bar --no-progress Do not print progress bar
--console-title Display progress in console titlebar --console-title Display progress in console titlebar
@@ -441,11 +445,11 @@ Then simply type this
of a range for randomized sleep before each of a range for randomized sleep before each
download (minimum possible number of download (minimum possible number of
seconds to sleep) when used along with seconds to sleep) when used along with
--max-sleep-interval. --max-sleep-interval
--max-sleep-interval SECONDS Upper bound of a range for randomized sleep --max-sleep-interval SECONDS Upper bound of a range for randomized sleep
before each download (maximum possible before each download (maximum possible
number of seconds to sleep). Must only be number of seconds to sleep). Must only be
used along with --min-sleep-interval. used along with --min-sleep-interval
--sleep-subtitles SECONDS Enforce sleep interval on subtitles as well --sleep-subtitles SECONDS Enforce sleep interval on subtitles as well
## Video Format Options: ## Video Format Options:
@@ -453,8 +457,8 @@ Then simply type this
for more details for more details
-S, --format-sort SORTORDER Sort the formats by the fields given, see -S, --format-sort SORTORDER Sort the formats by the fields given, see
"Sorting Formats" for more details "Sorting Formats" for more details
--S-force, --format-sort-force Force user specified sort order to have --S-force, --format-sort-force Force user specified sort order to have
precedence over all fields, see "Sorting precedence over all fields, see "Sorting
Formats" for more details Formats" for more details
--no-format-sort-force Some fields have precedence over the user --no-format-sort-force Some fields have precedence over the user
specified sort order (default), see specified sort order (default), see
@@ -472,22 +476,22 @@ Then simply type this
formats of same quality formats of same quality
-F, --list-formats List all available formats of requested -F, --list-formats List all available formats of requested
videos videos
--list-formats-as-table Present the output of -F in a more tabular --list-formats-as-table Present the output of -F in tabular form
form (default) (default)
(Same as --no-list-formats-as-table)
--list-formats-old Present the output of -F in the old form --list-formats-old Present the output of -F in the old form
--youtube-include-dash-manifest Download the DASH manifests and related data (Alias: --no-list-formats-as-table)
on YouTube videos (default) --youtube-include-dash-manifest Download the DASH manifests and related
(Same as --no-youtube-skip-dash-manifest) data on YouTube videos (default) (Alias:
--no-youtube-skip-dash-manifest)
--youtube-skip-dash-manifest Do not download the DASH manifests and --youtube-skip-dash-manifest Do not download the DASH manifests and
related data on YouTube videos related data on YouTube videos (Alias:
(Same as --no-youtube-include-dash-manifest) --no-youtube-include-dash-manifest)
--youtube-include-hls-manifest Download the HLS manifests and related data --youtube-include-hls-manifest Download the HLS manifests and related data
on YouTube videos (default) on YouTube videos (default) (Alias:
(Same as --no-youtube-skip-hls-manifest) --no-youtube-skip-hls-manifest)
--youtube-skip-hls-manifest Do not download the HLS manifests and --youtube-skip-hls-manifest Do not download the HLS manifests and
related data on YouTube videos related data on YouTube videos (Alias:
(Same as --no-youtube-include-hls-manifest) --no-youtube-include-hls-manifest)
--merge-output-format FORMAT If a merge is required (e.g. --merge-output-format FORMAT If a merge is required (e.g.
bestvideo+bestaudio), output to given bestvideo+bestaudio), output to given
container format. One of mkv, mp4, ogg, container format. One of mkv, mp4, ogg,
@@ -513,7 +517,7 @@ Then simply type this
## Authentication Options: ## Authentication Options:
-u, --username USERNAME Login with this account ID -u, --username USERNAME Login with this account ID
-p, --password PASSWORD Account password. If this option is left -p, --password PASSWORD Account password. If this option is left
out, youtube-dlc will ask interactively. out, youtube-dlc will ask interactively
-2, --twofactor TWOFACTOR Two-factor authentication code -2, --twofactor TWOFACTOR Two-factor authentication code
-n, --netrc Use .netrc authentication data -n, --netrc Use .netrc authentication data
--video-password PASSWORD Video password (vimeo, youku) --video-password PASSWORD Video password (vimeo, youku)
@@ -525,7 +529,7 @@ Then simply type this
--ap-username USERNAME Multiple-system operator account login --ap-username USERNAME Multiple-system operator account login
--ap-password PASSWORD Multiple-system operator account password. --ap-password PASSWORD Multiple-system operator account password.
If this option is left out, youtube-dlc If this option is left out, youtube-dlc
will ask interactively. will ask interactively
--ap-list-mso List all supported multiple-system --ap-list-mso List all supported multiple-system
operators operators
@@ -549,17 +553,24 @@ Then simply type this
re-encoding is necessary (currently re-encoding is necessary (currently
supported: mp4|flv|ogg|webm|mkv|avi) supported: mp4|flv|ogg|webm|mkv|avi)
--postprocessor-args NAME:ARGS Give these arguments to the postprocessors. --postprocessor-args NAME:ARGS Give these arguments to the postprocessors.
Specify the postprocessor name and the Specify the postprocessor/executable name
arguments separated by a colon ':' to give and the arguments separated by a colon ':'
the argument to only the specified to give the argument to only the specified
postprocessor. Supported names are postprocessor/executable. Supported
postprocessors are: SponSkrub,
ExtractAudio, VideoRemuxer, VideoConvertor, ExtractAudio, VideoRemuxer, VideoConvertor,
EmbedSubtitle, Metadata, Merger, EmbedSubtitle, Metadata, Merger,
FixupStretched, FixupM4a, FixupM3u8, FixupStretched, FixupM4a, FixupM3u8,
SubtitlesConvertor, SponSkrub and Default. SubtitlesConvertor and EmbedThumbnail. The
You can use this option multiple times to supported executables are: SponSkrub,
give different arguments to different FFmpeg, FFprobe, avconf, avprobe and
postprocessors AtomicParsley. You can use this option
multiple times to give different arguments
to different postprocessors. You can also
specify "PP+EXE:ARGS" to give the arguments
to the specified executable only when being
used by the specified postprocessor (Alias:
--ppa)
-k, --keep-video Keep the intermediate video file on disk -k, --keep-video Keep the intermediate video file on disk
after post-processing after post-processing
--no-keep-video Delete the intermediate video file after --no-keep-video Delete the intermediate video file after
@@ -591,13 +602,14 @@ Then simply type this
default; fix file if we can, warn default; fix file if we can, warn
otherwise) otherwise)
--prefer-avconv Prefer avconv over ffmpeg for running the --prefer-avconv Prefer avconv over ffmpeg for running the
postprocessors (Same as --no-prefer-ffmpeg) postprocessors (Alias: --no-prefer-ffmpeg)
--prefer-ffmpeg Prefer ffmpeg over avconv for running the --prefer-ffmpeg Prefer ffmpeg over avconv for running the
postprocessors (default) postprocessors (default)
(Same as --no-prefer-avconv) (Alias: --no-prefer-avconv)
--ffmpeg-location PATH Location of the ffmpeg/avconv binary; --ffmpeg-location PATH Location of the ffmpeg/avconv binary;
either the path to the binary or its either the path to the binary or its
containing directory. containing directory
(Alias: --avconv-location)
--exec CMD Execute a command on the file after --exec CMD Execute a command on the file after
downloading and post-processing, similar to downloading and post-processing, similar to
find's -exec syntax. Example: --exec 'adb find's -exec syntax. Example: --exec 'adb
@@ -605,11 +617,14 @@ Then simply type this
--convert-subs FORMAT Convert the subtitles to other format --convert-subs FORMAT Convert the subtitles to other format
(currently supported: srt|ass|vtt|lrc) (currently supported: srt|ass|vtt|lrc)
## [SponSkrub](https://github.com/faissaloo/SponSkrub) Options ([SponsorBlock](https://sponsor.ajay.app)): ## SponSkrub (SponsorBlock) Options:
--sponskrub Use sponskrub to mark sponsored sections [SponSkrub](https://github.com/pukkandan/SponSkrub) is a utility to
with the data available in SponsorBlock mark/remove sponsor segments from downloaded YouTube videos using
API. This is enabled by default if the [SponsorBlock API](https://sponsor.ajay.app)
sponskrub binary exists (Youtube only)
--sponskrub Use sponskrub to mark sponsored sections.
This is enabled by default if the sponskrub
binary exists (Youtube only)
--no-sponskrub Do not use sponskrub --no-sponskrub Do not use sponskrub
--sponskrub-cut Cut out the sponsor sections instead of --sponskrub-cut Cut out the sponsor sections instead of
simply marking them simply marking them
@@ -621,19 +636,32 @@ Then simply type this
video was already downloaded (default) video was already downloaded (default)
--sponskrub-location PATH Location of the sponskrub binary; either --sponskrub-location PATH Location of the sponskrub binary; either
the path to the binary or its containing the path to the binary or its containing
directory. directory
## Extractor Options: ## Extractor Options:
--ignore-dynamic-mpd Do not process dynamic DASH manifests
(Same as --no-allow-dynamic-mpd)
--allow-dynamic-mpd Process dynamic DASH manifests (default) --allow-dynamic-mpd Process dynamic DASH manifests (default)
(Same as --no-ignore-dynamic-mpd) (Alias: --no-ignore-dynamic-mpd)
--ignore-dynamic-mpd Do not process dynamic DASH manifests
(Alias: --no-allow-dynamic-mpd)
# CONFIGURATION # CONFIGURATION
You can configure youtube-dlc by placing any supported command line option to a configuration file. On Linux and macOS, the system wide configuration file is located at `/etc/youtube-dlc.conf` and the user wide configuration file at `~/.config/youtube-dlc/config`. On Windows, the user wide configuration file locations are `%APPDATA%\youtube-dlc\config.txt` or `C:\Users\<user name>\youtube-dlc.conf`. Note that by default configuration file may not exist so you may need to create it yourself. You can configure youtube-dlc by placing any supported command line option to a configuration file. The configuration is loaded from the following locations:
For example, with the following configuration file youtube-dlc will always extract the audio, not copy the mtime, use a proxy and save all videos under `Movies` directory in your home directory: 1. The file given by `--config-location`
1. **Portable Configuration**: `yt-dlp.conf` or `youtube-dlc.conf` in the same directory as the bundled binary. If you are running from source-code (`<root dir>/youtube_dlc/__main__.py`), the root directory is used instead.
1. **User Configuration**:
* `%XDG_CONFIG_HOME%/yt-dlp/config` (recommended on Linux/macOS)
* `%XDG_CONFIG_HOME%/yt-dlp.conf`
* `%APPDATA%/yt-dlp/config` (recommended on Windows)
* `%APPDATA%/yt-dlp/config.txt`
* `~/yt-dlp.conf`
* `~/yt-dlp.conf.txt`
If none of these files are found, the search is performed again by replacing `yt-dlp` with `youtube-dlc`. Note that `~` points to `C:\Users\<user name>` on windows. Also, `%XDG_CONFIG_HOME%` defaults to `~/.config` if undefined
1. **System Configuration**: `/etc/yt-dlp.conf` or `/etc/youtube-dlc.conf`
For example, with the following configuration file youtube-dlc will always extract the audio, not copy the mtime, use a proxy and save all videos under `YouTube` directory in your home directory:
``` ```
# Lines starting with # are comments # Lines starting with # are comments
@@ -646,15 +674,13 @@ For example, with the following configuration file youtube-dlc will always extra
# Use this proxy # Use this proxy
--proxy 127.0.0.1:3128 --proxy 127.0.0.1:3128
# Save all videos under Movies directory in your home directory # Save all videos under YouTube directory in your home directory
-o ~/Movies/%(title)s.%(ext)s -o ~/YouTube/%(title)s.%(ext)s
``` ```
Note that options in configuration file are just the same options aka switches used in regular command line calls thus there **must be no whitespace** after `-` or `--`, e.g. `-o` or `--proxy` but not `- o` or `-- proxy`. Note that options in configuration file are just the same options aka switches used in regular command line calls; thus there **must be no whitespace** after `-` or `--`, e.g. `-o` or `--proxy` but not `- o` or `-- proxy`.
You can use `--ignore-config` if you want to disable the configuration file for a particular youtube-dlc run. You can use `--ignore-config` if you want to disable all configuration files for a particular youtube-dlc run. If `--ignore-config` is found inside any configuration file, no further configuration will be loaded. For example, having the option in the portable configuration file prevents loading of user and system configurations. Additionally, (for backward compatibility) if `--ignore-config` is found inside the system configuration file, the user configuration is not loaded.
You can also use `--config-location` if you want to use custom configuration file for a particular youtube-dlc run.
### Authentication with `.netrc` file ### Authentication with `.netrc` file
+3 -1
View File
@@ -431,7 +431,8 @@
- **Katsomo** - **Katsomo**
- **KeezMovies** - **KeezMovies**
- **Ketnet** - **Ketnet**
- **KhanAcademy** - **khanacademy**
- **khanacademy:unit**
- **KickStarter** - **KickStarter**
- **KinjaEmbed** - **KinjaEmbed**
- **KinoPoisk** - **KinoPoisk**
@@ -967,6 +968,7 @@
- **ToypicsUser**: Toypics user profile - **ToypicsUser**: Toypics user profile
- **TrailerAddict** (Currently broken) - **TrailerAddict** (Currently broken)
- **Trilulilu** - **Trilulilu**
- **TrovoLive**
- **TruNews** - **TruNews**
- **TruTV** - **TruTV**
- **Tube8** - **Tube8**
+17 -11
View File
@@ -11,8 +11,12 @@ from distutils.spawn import spawn
exec(compile(open('youtube_dlc/version.py').read(), exec(compile(open('youtube_dlc/version.py').read(),
'youtube_dlc/version.py', 'exec')) 'youtube_dlc/version.py', 'exec'))
DESCRIPTION = 'Media downloader supporting various sites such as youtube' DESCRIPTION = 'Command-line program to download videos from YouTube.com and many other other video platforms.'
LONG_DESCRIPTION = 'Command-line program to download videos from YouTube.com and other video sites. Based on a more active community fork.'
LONG_DESCRIPTION = '\n\n'.join((
'Official repository: <https://github.com/pukkandan/yt-dlp>',
'**PS**: Many links in this document will not work since this is a copy of the README.md from Github',
open("README.md", "r", encoding="utf-8").read()))
if len(sys.argv) >= 2 and sys.argv[1] == 'py2exe': if len(sys.argv) >= 2 and sys.argv[1] == 'py2exe':
print("inv") print("inv")
@@ -59,19 +63,21 @@ class build_lazy_extractors(Command):
) )
setup( setup(
name="youtube_dlc", name="yt-dlp",
version=__version__, version=__version__,
maintainer="Tom-Oliver Heidel", maintainer="pukkandan",
maintainer_email="theidel@uni-bremen.de", maintainer_email="pukkandan@gmail.com",
description=DESCRIPTION, description=DESCRIPTION,
long_description=LONG_DESCRIPTION, long_description=LONG_DESCRIPTION,
# long_description_content_type="text/markdown", long_description_content_type="text/markdown",
url="https://github.com/pukkandan/yt-dlc", url="https://github.com/pukkandan/yt-dlp",
packages=find_packages(exclude=("youtube_dl","test",)), packages=find_packages(exclude=("youtube_dl","test",)),
#packages=[ project_urls={
# 'youtube_dlc', 'Documentation': 'https://github.com/pukkandan/yt-dlp#yt-dlp',
# 'youtube_dlc.extractor', 'youtube_dlc.downloader', 'Source': 'https://github.com/pukkandan/yt-dlp',
# 'youtube_dlc.postprocessor'], 'Tracker': 'https://github.com/pukkandan/yt-dlp/issues',
#'Funding': 'https://donate.pypi.org',
},
classifiers=[ classifiers=[
"Topic :: Multimedia :: Video", "Topic :: Multimedia :: Video",
"Development Status :: 5 - Production/Stable", "Development Status :: 5 - Production/Stable",
+1 -1
View File
@@ -1 +1 @@
py "%~dp0youtube_dl\__main__.py" @py "%~dp0youtube_dlc\__main__.py" %*
+192 -159
View File
@@ -58,6 +58,7 @@ from .utils import (
encode_compat_str, encode_compat_str,
encodeFilename, encodeFilename,
error_to_compat_str, error_to_compat_str,
ExistingVideoReached,
expand_path, expand_path,
ExtractorError, ExtractorError,
format_bytes, format_bytes,
@@ -81,6 +82,7 @@ from .utils import (
register_socks_protocols, register_socks_protocols,
render_table, render_table,
replace_extension, replace_extension,
RejectedVideoReached,
SameFileError, SameFileError,
sanitize_filename, sanitize_filename,
sanitize_path, sanitize_path,
@@ -230,9 +232,11 @@ class YoutubeDL(object):
download_archive: File name of a file where all downloads are recorded. download_archive: File name of a file where all downloads are recorded.
Videos already present in the file are not downloaded Videos already present in the file are not downloaded
again. again.
break_on_existing: Stop the download process after attempting to download a file that's break_on_existing: Stop the download process after attempting to download a
in the archive. file that is in the archive.
cookiefile: File name where cookies should be read from and dumped to. break_on_reject: Stop the download process when encountering a video that
has been filtered out.
cookiefile: File name where cookies should be read from and dumped to
nocheckcertificate:Do not verify SSL certificates nocheckcertificate:Do not verify SSL certificates
prefer_insecure: Use HTTP instead of HTTPS to retrieve information. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
At the moment, this is only supported by YouTube. At the moment, this is only supported by YouTube.
@@ -339,10 +343,11 @@ class YoutubeDL(object):
otherwise prefer ffmpeg. otherwise prefer ffmpeg.
ffmpeg_location: Location of the ffmpeg/avconv binary; either the path ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
to the binary or its containing directory. to the binary or its containing directory.
postprocessor_args: A dictionary of postprocessor names (in lower case) and a list postprocessor_args: A dictionary of postprocessor/executable keys (in lower case)
of additional command-line arguments for the postprocessor. and a list of additional command-line arguments for the
Use 'default' as the name for arguments to passed to all PP. postprocessor/executable. The dict can also have "PP+EXE" keys
which are used when the given exe is used by the given PP.
Use 'default' as the name for arguments to passed to all PP
The following options are used by the Youtube extractor: The following options are used by the Youtube extractor:
youtube_include_dash_manifest: If True (default), DASH manifests and related youtube_include_dash_manifest: If True (default), DASH manifests and related
data will be downloaded and processed by extractor. data will be downloaded and processed by extractor.
@@ -366,6 +371,8 @@ class YoutubeDL(object):
_pps = [] _pps = []
_download_retcode = None _download_retcode = None
_num_downloads = None _num_downloads = None
_playlist_level = 0
_playlist_urls = set()
_screen_file = None _screen_file = None
def __init__(self, params=None, auto_init=True): def __init__(self, params=None, auto_init=True):
@@ -797,44 +804,53 @@ class YoutubeDL(object):
def _match_entry(self, info_dict, incomplete): def _match_entry(self, info_dict, incomplete):
""" Returns None if the file should be downloaded """ """ Returns None if the file should be downloaded """
video_title = info_dict.get('title', info_dict.get('id', 'video')) def check_filter():
if 'title' in info_dict: video_title = info_dict.get('title', info_dict.get('id', 'video'))
# This can happen when we're just evaluating the playlist if 'title' in info_dict:
title = info_dict['title'] # This can happen when we're just evaluating the playlist
matchtitle = self.params.get('matchtitle', False) title = info_dict['title']
if matchtitle: matchtitle = self.params.get('matchtitle', False)
if not re.search(matchtitle, title, re.IGNORECASE): if matchtitle:
return '"' + title + '" title did not match pattern "' + matchtitle + '"' if not re.search(matchtitle, title, re.IGNORECASE):
rejecttitle = self.params.get('rejecttitle', False) return '"' + title + '" title did not match pattern "' + matchtitle + '"'
if rejecttitle: rejecttitle = self.params.get('rejecttitle', False)
if re.search(rejecttitle, title, re.IGNORECASE): if rejecttitle:
return '"' + title + '" title matched reject pattern "' + rejecttitle + '"' if re.search(rejecttitle, title, re.IGNORECASE):
date = info_dict.get('upload_date') return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
if date is not None: date = info_dict.get('upload_date')
dateRange = self.params.get('daterange', DateRange()) if date is not None:
if date not in dateRange: dateRange = self.params.get('daterange', DateRange())
return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange) if date not in dateRange:
view_count = info_dict.get('view_count') return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
if view_count is not None: view_count = info_dict.get('view_count')
min_views = self.params.get('min_views') if view_count is not None:
if min_views is not None and view_count < min_views: min_views = self.params.get('min_views')
return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views) if min_views is not None and view_count < min_views:
max_views = self.params.get('max_views') return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
if max_views is not None and view_count > max_views: max_views = self.params.get('max_views')
return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views) if max_views is not None and view_count > max_views:
if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')): return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
return 'Skipping "%s" because it is age restricted' % video_title if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
if self.in_download_archive(info_dict): return 'Skipping "%s" because it is age restricted' % video_title
return '%s has already been recorded in archive' % video_title if self.in_download_archive(info_dict):
return '%s has already been recorded in archive' % video_title
if not incomplete: if not incomplete:
match_filter = self.params.get('match_filter') match_filter = self.params.get('match_filter')
if match_filter is not None: if match_filter is not None:
ret = match_filter(info_dict) ret = match_filter(info_dict)
if ret is not None: if ret is not None:
return ret return ret
return None
return None reason = check_filter()
if reason is not None:
self.to_screen('[download] ' + reason)
if reason.endswith('has already been recorded in the archive') and self.params.get('break_on_existing', False):
raise ExistingVideoReached()
elif self.params.get('break_on_reject', False):
raise RejectedVideoReached()
return reason
@staticmethod @staticmethod
def add_extra_info(info_dict, extra_info): def add_extra_info(info_dict, extra_info):
@@ -895,7 +911,7 @@ class YoutubeDL(object):
self.report_error(msg) self.report_error(msg)
except ExtractorError as e: # An error we somewhat expected except ExtractorError as e: # An error we somewhat expected
self.report_error(compat_str(e), e.format_traceback()) self.report_error(compat_str(e), e.format_traceback())
except MaxDownloadsReached: except (MaxDownloadsReached, ExistingVideoReached, RejectedVideoReached):
raise raise
except Exception as e: except Exception as e:
if self.params.get('ignoreerrors', False): if self.params.get('ignoreerrors', False):
@@ -1000,119 +1016,23 @@ class YoutubeDL(object):
return self.process_ie_result( return self.process_ie_result(
new_result, download=download, extra_info=extra_info) new_result, download=download, extra_info=extra_info)
elif result_type in ('playlist', 'multi_video'): elif result_type in ('playlist', 'multi_video'):
# We process each entry in the playlist # Protect from infinite recursion due to recursively nested playlists
playlist = ie_result.get('title') or ie_result.get('id') # (see https://github.com/ytdl-org/youtube-dl/issues/27833)
self.to_screen('[download] Downloading playlist: %s' % playlist) webpage_url = ie_result['webpage_url']
if webpage_url in self._playlist_urls:
playlist_results = []
playliststart = self.params.get('playliststart', 1) - 1
playlistend = self.params.get('playlistend')
# For backwards compatibility, interpret -1 as whole list
if playlistend == -1:
playlistend = None
playlistitems_str = self.params.get('playlist_items')
playlistitems = None
if playlistitems_str is not None:
def iter_playlistitems(format):
for string_segment in format.split(','):
if '-' in string_segment:
start, end = string_segment.split('-')
for item in range(int(start), int(end) + 1):
yield int(item)
else:
yield int(string_segment)
playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
ie_entries = ie_result['entries']
def make_playlistitems_entries(list_ie_entries):
num_entries = len(list_ie_entries)
return [
list_ie_entries[i - 1] for i in playlistitems
if -num_entries <= i - 1 < num_entries]
def report_download(num_entries):
self.to_screen( self.to_screen(
'[%s] playlist %s: Downloading %d videos' % '[download] Skipping already downloaded playlist: %s'
(ie_result['extractor'], playlist, num_entries)) % ie_result.get('title') or ie_result.get('id'))
return
if isinstance(ie_entries, list): self._playlist_level += 1
n_all_entries = len(ie_entries) self._playlist_urls.add(webpage_url)
if playlistitems: try:
entries = make_playlistitems_entries(ie_entries) return self.__process_playlist(ie_result, download)
else: finally:
entries = ie_entries[playliststart:playlistend] self._playlist_level -= 1
n_entries = len(entries) if not self._playlist_level:
self.to_screen( self._playlist_urls.clear()
'[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
(ie_result['extractor'], playlist, n_all_entries, n_entries))
elif isinstance(ie_entries, PagedList):
if playlistitems:
entries = []
for item in playlistitems:
entries.extend(ie_entries.getslice(
item - 1, item
))
else:
entries = ie_entries.getslice(
playliststart, playlistend)
n_entries = len(entries)
report_download(n_entries)
else: # iterable
if playlistitems:
entries = make_playlistitems_entries(list(itertools.islice(
ie_entries, 0, max(playlistitems))))
else:
entries = list(itertools.islice(
ie_entries, playliststart, playlistend))
n_entries = len(entries)
report_download(n_entries)
if self.params.get('playlistreverse', False):
entries = entries[::-1]
if self.params.get('playlistrandom', False):
random.shuffle(entries)
x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
for i, entry in enumerate(entries, 1):
self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
# This __x_forwarded_for_ip thing is a bit ugly but requires
# minimal changes
if x_forwarded_for:
entry['__x_forwarded_for_ip'] = x_forwarded_for
extra = {
'n_entries': n_entries,
'playlist': playlist,
'playlist_id': ie_result.get('id'),
'playlist_title': ie_result.get('title'),
'playlist_uploader': ie_result.get('uploader'),
'playlist_uploader_id': ie_result.get('uploader_id'),
'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart,
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
reason = self._match_entry(entry, incomplete=True)
if reason is not None:
if reason.endswith('has already been recorded in the archive') and self.params.get('break_on_existing'):
print('[download] tried downloading a file that\'s already in the archive, stopping since --break-on-existing is set.')
break
else:
self.to_screen('[download] ' + reason)
continue
entry_result = self.__process_iterable_entry(entry, download, extra)
# TODO: skip failed (empty) entries?
playlist_results.append(entry_result)
ie_result['entries'] = playlist_results
self.to_screen('[download] Finished downloading playlist: %s' % playlist)
return ie_result
elif result_type == 'compat_list': elif result_type == 'compat_list':
self.report_warning( self.report_warning(
'Extractor %s returned a compat_list result. ' 'Extractor %s returned a compat_list result. '
@@ -1137,6 +1057,115 @@ class YoutubeDL(object):
else: else:
raise Exception('Invalid result type: %s' % result_type) raise Exception('Invalid result type: %s' % result_type)
def __process_playlist(self, ie_result, download):
# We process each entry in the playlist
playlist = ie_result.get('title') or ie_result.get('id')
self.to_screen('[download] Downloading playlist: %s' % playlist)
playlist_results = []
playliststart = self.params.get('playliststart', 1) - 1
playlistend = self.params.get('playlistend')
# For backwards compatibility, interpret -1 as whole list
if playlistend == -1:
playlistend = None
playlistitems_str = self.params.get('playlist_items')
playlistitems = None
if playlistitems_str is not None:
def iter_playlistitems(format):
for string_segment in format.split(','):
if '-' in string_segment:
start, end = string_segment.split('-')
for item in range(int(start), int(end) + 1):
yield int(item)
else:
yield int(string_segment)
playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
ie_entries = ie_result['entries']
def make_playlistitems_entries(list_ie_entries):
num_entries = len(list_ie_entries)
return [
list_ie_entries[i - 1] for i in playlistitems
if -num_entries <= i - 1 < num_entries]
def report_download(num_entries):
self.to_screen(
'[%s] playlist %s: Downloading %d videos' %
(ie_result['extractor'], playlist, num_entries))
if isinstance(ie_entries, list):
n_all_entries = len(ie_entries)
if playlistitems:
entries = make_playlistitems_entries(ie_entries)
else:
entries = ie_entries[playliststart:playlistend]
n_entries = len(entries)
self.to_screen(
'[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
(ie_result['extractor'], playlist, n_all_entries, n_entries))
elif isinstance(ie_entries, PagedList):
if playlistitems:
entries = []
for item in playlistitems:
entries.extend(ie_entries.getslice(
item - 1, item
))
else:
entries = ie_entries.getslice(
playliststart, playlistend)
n_entries = len(entries)
report_download(n_entries)
else: # iterable
if playlistitems:
entries = make_playlistitems_entries(list(itertools.islice(
ie_entries, 0, max(playlistitems))))
else:
entries = list(itertools.islice(
ie_entries, playliststart, playlistend))
n_entries = len(entries)
report_download(n_entries)
if self.params.get('playlistreverse', False):
entries = entries[::-1]
if self.params.get('playlistrandom', False):
random.shuffle(entries)
x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
for i, entry in enumerate(entries, 1):
self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
# This __x_forwarded_for_ip thing is a bit ugly but requires
# minimal changes
if x_forwarded_for:
entry['__x_forwarded_for_ip'] = x_forwarded_for
extra = {
'n_entries': n_entries,
'playlist': playlist,
'playlist_id': ie_result.get('id'),
'playlist_title': ie_result.get('title'),
'playlist_uploader': ie_result.get('uploader'),
'playlist_uploader_id': ie_result.get('uploader_id'),
'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart,
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
if self._match_entry(entry, incomplete=True) is not None:
continue
entry_result = self.__process_iterable_entry(entry, download, extra)
# TODO: skip failed (empty) entries?
playlist_results.append(entry_result)
ie_result['entries'] = playlist_results
self.to_screen('[download] Finished downloading playlist: %s' % playlist)
return ie_result
@__handle_extraction_exceptions @__handle_extraction_exceptions
def __process_iterable_entry(self, entry, download, extra_info): def __process_iterable_entry(self, entry, download, extra_info):
return self.process_ie_result( return self.process_ie_result(
@@ -1870,9 +1899,7 @@ class YoutubeDL(object):
if 'format' not in info_dict: if 'format' not in info_dict:
info_dict['format'] = info_dict['ext'] info_dict['format'] = info_dict['ext']
reason = self._match_entry(info_dict, incomplete=False) if self._match_entry(info_dict, incomplete=False) is not None:
if reason is not None:
self.to_screen('[download] ' + reason)
return return
self._num_downloads += 1 self._num_downloads += 1
@@ -2260,7 +2287,13 @@ class YoutubeDL(object):
except UnavailableVideoError: except UnavailableVideoError:
self.report_error('unable to download video') self.report_error('unable to download video')
except MaxDownloadsReached: except MaxDownloadsReached:
self.to_screen('[info] Maximum number of downloaded files reached.') self.to_screen('[info] Maximum number of downloaded files reached')
raise
except ExistingVideoReached:
self.to_screen('[info] Encountered a file that is already in the archive, stopping due to --break-on-existing')
raise
except RejectedVideoReached:
self.to_screen('[info] Encountered a file that did not match filter, stopping due to --break-on-reject')
raise raise
else: else:
if self.params.get('dump_single_json', False): if self.params.get('dump_single_json', False):
+12 -9
View File
@@ -8,8 +8,8 @@ __license__ = 'Public Domain'
import codecs import codecs
import io import io
import os import os
import re
import random import random
import re
import sys import sys
@@ -26,11 +26,13 @@ from .utils import (
decodeOption, decodeOption,
DEFAULT_OUTTMPL, DEFAULT_OUTTMPL,
DownloadError, DownloadError,
ExistingVideoReached,
expand_path, expand_path,
match_filter_func, match_filter_func,
MaxDownloadsReached, MaxDownloadsReached,
preferredencoding, preferredencoding,
read_batch_urls, read_batch_urls,
RejectedVideoReached,
SameFileError, SameFileError,
setproctitle, setproctitle,
std_headers, std_headers,
@@ -338,18 +340,18 @@ def _real_main(argv=None):
postprocessor_args = {} postprocessor_args = {}
if opts.postprocessor_args is not None: if opts.postprocessor_args is not None:
for string in opts.postprocessor_args: for string in opts.postprocessor_args:
mobj = re.match(r'(?P<pp>\w+):(?P<args>.*)$', string) mobj = re.match(r'(?P<pp>\w+(?:\+\w+)?):(?P<args>.*)$', string)
if mobj is None: if mobj is None:
if 'sponskrub' not in postprocessor_args: # for backward compatibility if 'sponskrub' not in postprocessor_args: # for backward compatibility
postprocessor_args['sponskrub'] = [] postprocessor_args['sponskrub'] = []
if opts.verbose: if opts.verbose:
write_string('[debug] Adding postprocessor args from command line option sponskrub:\n') write_string('[debug] Adding postprocessor args from command line option sponskrub: \n')
pp_name, pp_args = 'default', string pp_key, pp_args = 'default', string
else: else:
pp_name, pp_args = mobj.group('pp').lower(), mobj.group('args') pp_key, pp_args = mobj.group('pp').lower(), mobj.group('args')
if opts.verbose: if opts.verbose:
write_string('[debug] Adding postprocessor args from command line option %s:%s\n' % (pp_name, pp_args)) write_string('[debug] Adding postprocessor args from command line option %s: %s\n' % (pp_key, pp_args))
postprocessor_args[pp_name] = compat_shlex_split(pp_args) postprocessor_args[pp_key] = compat_shlex_split(pp_args)
match_filter = ( match_filter = (
None if opts.match_filter is None None if opts.match_filter is None
@@ -449,6 +451,7 @@ def _real_main(argv=None):
'age_limit': opts.age_limit, 'age_limit': opts.age_limit,
'download_archive': download_archive_fn, 'download_archive': download_archive_fn,
'break_on_existing': opts.break_on_existing, 'break_on_existing': opts.break_on_existing,
'break_on_reject': opts.break_on_reject,
'cookiefile': opts.cookiefile, 'cookiefile': opts.cookiefile,
'nocheckcertificate': opts.no_check_certificate, 'nocheckcertificate': opts.no_check_certificate,
'prefer_insecure': opts.prefer_insecure, 'prefer_insecure': opts.prefer_insecure,
@@ -519,8 +522,8 @@ def _real_main(argv=None):
retcode = ydl.download_with_info_file(expand_path(opts.load_info_filename)) retcode = ydl.download_with_info_file(expand_path(opts.load_info_filename))
else: else:
retcode = ydl.download(all_urls) retcode = ydl.download(all_urls)
except MaxDownloadsReached: except (MaxDownloadsReached, ExistingVideoReached, RejectedVideoReached):
ydl.to_screen('--max-download limit reached, aborting.') ydl.to_screen('Aborting remaining downloads')
retcode = 101 retcode = 101
sys.exit(retcode) sys.exit(retcode)
+102 -66
View File
@@ -10,6 +10,7 @@ import random
from .common import InfoExtractor from .common import InfoExtractor
from ..aes import aes_cbc_decrypt from ..aes import aes_cbc_decrypt
from ..compat import ( from ..compat import (
compat_HTTPError,
compat_b64decode, compat_b64decode,
compat_ord, compat_ord,
) )
@@ -18,11 +19,13 @@ from ..utils import (
bytes_to_long, bytes_to_long,
ExtractorError, ExtractorError,
float_or_none, float_or_none,
int_or_none,
intlist_to_bytes, intlist_to_bytes,
long_to_bytes, long_to_bytes,
pkcs1pad, pkcs1pad,
strip_or_none, strip_or_none,
urljoin, try_get,
unified_strdate,
) )
@@ -31,16 +34,27 @@ class ADNIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?animedigitalnetwork\.fr/video/[^/]+/(?P<id>\d+)' _VALID_URL = r'https?://(?:www\.)?animedigitalnetwork\.fr/video/[^/]+/(?P<id>\d+)'
_TEST = { _TEST = {
'url': 'http://animedigitalnetwork.fr/video/blue-exorcist-kyoto-saga/7778-episode-1-debut-des-hostilites', 'url': 'http://animedigitalnetwork.fr/video/blue-exorcist-kyoto-saga/7778-episode-1-debut-des-hostilites',
'md5': 'e497370d847fd79d9d4c74be55575c7a', 'md5': '0319c99885ff5547565cacb4f3f9348d',
'info_dict': { 'info_dict': {
'id': '7778', 'id': '7778',
'ext': 'mp4', 'ext': 'mp4',
'title': 'Blue Exorcist - Kyôto Saga - Épisode 1', 'title': 'Blue Exorcist - Kyôto Saga - Episode 1',
'description': 'md5:2f7b5aa76edbc1a7a92cedcda8a528d5', 'description': 'md5:2f7b5aa76edbc1a7a92cedcda8a528d5',
'series': 'Blue Exorcist - Kyôto Saga',
'duration': 1467,
'release_date': '20170106',
'comment_count': int,
'average_rating': float,
'season_number': 2,
'episode': 'Début des hostilités',
'episode_number': 1,
} }
} }
_BASE_URL = 'http://animedigitalnetwork.fr' _BASE_URL = 'http://animedigitalnetwork.fr'
_RSA_KEY = (0xc35ae1e4356b65a73b551493da94b8cb443491c0aa092a357a5aee57ffc14dda85326f42d716e539a34542a0d3f363adf16c5ec222d713d5997194030ee2e4f0d1fb328c01a81cf6868c090d50de8e169c6b13d1675b9eeed1cbc51e1fffca9b38af07f37abd790924cd3bee59d0257cfda4fe5f3f0534877e21ce5821447d1b, 65537) _API_BASE_URL = 'https://gw.api.animedigitalnetwork.fr/'
_PLAYER_BASE_URL = _API_BASE_URL + 'player/'
_RSA_KEY = (0x9B42B08905199A5CCE2026274399CA560ECB209EE9878A708B1C0812E1BB8CB5D1FB7441861147C1A1F2F3A0476DD63A9CAC20D3E983613346850AA6CB38F16DC7D720FD7D86FC6E5B3D5BBC72E14CD0BF9E869F2CEA2CCAD648F1DCE38F1FF916CEFB2D339B64AA0264372344BC775E265E8A852F88144AB0BD9AA06C1A4ABB, 65537)
_POS_ALIGN_MAP = { _POS_ALIGN_MAP = {
'start': 1, 'start': 1,
'end': 3, 'end': 3,
@@ -54,26 +68,24 @@ class ADNIE(InfoExtractor):
def _ass_subtitles_timecode(seconds): def _ass_subtitles_timecode(seconds):
return '%01d:%02d:%02d.%02d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 100) return '%01d:%02d:%02d.%02d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 100)
def _get_subtitles(self, sub_path, video_id): def _get_subtitles(self, sub_url, video_id):
if not sub_path: if not sub_url:
return None return None
enc_subtitles = self._download_webpage( enc_subtitles = self._download_webpage(
urljoin(self._BASE_URL, sub_path), sub_url, video_id, 'Downloading subtitles location', fatal=False) or '{}'
video_id, 'Downloading subtitles location', fatal=False) or '{}'
subtitle_location = (self._parse_json(enc_subtitles, video_id, fatal=False) or {}).get('location') subtitle_location = (self._parse_json(enc_subtitles, video_id, fatal=False) or {}).get('location')
if subtitle_location: if subtitle_location:
enc_subtitles = self._download_webpage( enc_subtitles = self._download_webpage(
urljoin(self._BASE_URL, subtitle_location), subtitle_location, video_id, 'Downloading subtitles data',
video_id, 'Downloading subtitles data', fatal=False, fatal=False, headers={'Origin': 'https://animedigitalnetwork.fr'})
headers={'Origin': 'https://animedigitalnetwork.fr'})
if not enc_subtitles: if not enc_subtitles:
return None return None
# http://animedigitalnetwork.fr/components/com_vodvideo/videojs/adn-vjs.min.js # http://animedigitalnetwork.fr/components/com_vodvideo/videojs/adn-vjs.min.js
dec_subtitles = intlist_to_bytes(aes_cbc_decrypt( dec_subtitles = intlist_to_bytes(aes_cbc_decrypt(
bytes_to_intlist(compat_b64decode(enc_subtitles[24:])), bytes_to_intlist(compat_b64decode(enc_subtitles[24:])),
bytes_to_intlist(binascii.unhexlify(self._K + '4b8ef13ec1872730')), bytes_to_intlist(binascii.unhexlify(self._K + 'ab9f52f5baae7c72')),
bytes_to_intlist(compat_b64decode(enc_subtitles[:24])) bytes_to_intlist(compat_b64decode(enc_subtitles[:24]))
)) ))
subtitles_json = self._parse_json( subtitles_json = self._parse_json(
@@ -119,59 +131,76 @@ Format: Marked,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text'''
def _real_extract(self, url): def _real_extract(self, url):
video_id = self._match_id(url) video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id) video_base_url = self._PLAYER_BASE_URL + 'video/%s/' % video_id
player_config = self._parse_json(self._search_regex( player = self._download_json(
r'playerConfig\s*=\s*({.+});', webpage, video_base_url + 'configuration', video_id,
'player config', default='{}'), video_id, fatal=False) 'Downloading player config JSON metadata')['player']
if not player_config: options = player['options']
config_url = urljoin(self._BASE_URL, self._search_regex(
r'(?:id="player"|class="[^"]*adn-player-container[^"]*")[^>]+data-url="([^"]+)"',
webpage, 'config url'))
player_config = self._download_json(
config_url, video_id,
'Downloading player config JSON metadata')['player']
video_info = {} user = options['user']
video_info_str = self._search_regex( if not user.get('hasAccess'):
r'videoInfo\s*=\s*({.+});', webpage, raise ExtractorError(
'video info', fatal=False) 'This video is only available for paying users', expected=True)
if video_info_str: # self.raise_login_required() # FIXME: Login is not implemented
video_info = self._parse_json(
video_info_str, video_id, fatal=False) or {}
options = player_config.get('options') or {} token = self._download_json(
metas = options.get('metas') or {} user.get('refreshTokenUrl') or (self._PLAYER_BASE_URL + 'refresh/token'),
links = player_config.get('links') or {} video_id, 'Downloading access token', headers={
sub_path = player_config.get('subtitles') 'x-player-refresh-token': user['refreshToken']
error = None }, data=b'')['token']
if not links:
links_url = player_config.get('linksurl') or options['videoUrl'] links_url = try_get(options, lambda x: x['video']['url']) or (video_base_url + 'link')
token = options['token'] self._K = ''.join([random.choice('0123456789abcdef') for _ in range(16)])
self._K = ''.join([random.choice('0123456789abcdef') for _ in range(16)]) message = bytes_to_intlist(json.dumps({
message = bytes_to_intlist(json.dumps({ 'k': self._K,
'k': self._K, 't': token,
'e': 60, }))
't': token,
})) # Sometimes authentication fails for no good reason, retry with
# a different random padding
links_data = None
for _ in range(3):
padded_message = intlist_to_bytes(pkcs1pad(message, 128)) padded_message = intlist_to_bytes(pkcs1pad(message, 128))
n, e = self._RSA_KEY n, e = self._RSA_KEY
encrypted_message = long_to_bytes(pow(bytes_to_long(padded_message), e, n)) encrypted_message = long_to_bytes(pow(bytes_to_long(padded_message), e, n))
authorization = base64.b64encode(encrypted_message).decode() authorization = base64.b64encode(encrypted_message).decode()
links_data = self._download_json(
urljoin(self._BASE_URL, links_url), video_id, try:
'Downloading links JSON metadata', headers={ links_data = self._download_json(
'Authorization': 'Bearer ' + authorization, links_url, video_id, 'Downloading links JSON metadata', headers={
}) 'X-Player-Token': authorization
links = links_data.get('links') or {} }, query={
metas = metas or links_data.get('meta') or {} 'freeWithAds': 'true',
sub_path = sub_path or links_data.get('subtitles') or \ 'adaptive': 'false',
'index.php?option=com_vodapi&task=subtitles.getJSON&format=json&id=' + video_id 'withMetadata': 'true',
sub_path += '&token=' + token 'source': 'Web'
error = links_data.get('error') })
title = metas.get('title') or video_info['title'] break
except ExtractorError as e:
if not isinstance(e.cause, compat_HTTPError):
raise e
if e.cause.code == 401:
# This usually goes away with a different random pkcs1pad, so retry
continue
error = self._parse_json(e.cause.read(), video_id)
message = error.get('message')
if e.cause.code == 403 and error.get('code') == 'player-bad-geolocation-country':
self.raise_geo_restricted(msg=message)
else:
raise ExtractorError(message)
else:
raise ExtractorError('Giving up retrying')
links = links_data.get('links') or {}
metas = links_data.get('metadata') or {}
sub_url = (links.get('subtitles') or {}).get('all')
video_info = links_data.get('video') or {}
title = metas['title']
formats = [] formats = []
for format_id, qualities in links.items(): for format_id, qualities in (links.get('streaming') or {}).items():
if not isinstance(qualities, dict): if not isinstance(qualities, dict):
continue continue
for quality, load_balancer_url in qualities.items(): for quality, load_balancer_url in qualities.items():
@@ -189,19 +218,26 @@ Format: Marked,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text'''
for f in m3u8_formats: for f in m3u8_formats:
f['language'] = 'fr' f['language'] = 'fr'
formats.extend(m3u8_formats) formats.extend(m3u8_formats)
if not error:
error = options.get('error')
if not formats and error:
raise ExtractorError('%s said: %s' % (self.IE_NAME, error), expected=True)
self._sort_formats(formats) self._sort_formats(formats)
video = (self._download_json(
self._API_BASE_URL + 'video/%s' % video_id, video_id,
'Downloading additional video metadata', fatal=False) or {}).get('video') or {}
show = video.get('show') or {}
return { return {
'id': video_id, 'id': video_id,
'title': title, 'title': title,
'description': strip_or_none(metas.get('summary') or video_info.get('resume')), 'description': strip_or_none(metas.get('summary') or video.get('summary')),
'thumbnail': video_info.get('image'), 'thumbnail': video_info.get('image') or player.get('image'),
'formats': formats, 'formats': formats,
'subtitles': self.extract_subtitles(sub_path, video_id), 'subtitles': self.extract_subtitles(sub_url, video_id),
'episode': metas.get('subtitle') or video_info.get('videoTitle'), 'episode': metas.get('subtitle') or video.get('name'),
'series': video_info.get('playlistTitle'), 'episode_number': int_or_none(video.get('shortNumber')),
'series': show.get('title'),
'season_number': int_or_none(video.get('season')),
'duration': int_or_none(video_info.get('duration') or video.get('duration')),
'release_date': unified_strdate(video.get('releaseDate')),
'average_rating': float_or_none(video.get('rating') or metas.get('rating')),
'comment_count': int_or_none(video.get('commentsCount')),
} }
+16 -10
View File
@@ -116,8 +116,6 @@ class AnimeOnDemandIE(InfoExtractor):
r'(?s)<div[^>]+itemprop="description"[^>]*>(.+?)</div>', r'(?s)<div[^>]+itemprop="description"[^>]*>(.+?)</div>',
webpage, 'anime description', default=None) webpage, 'anime description', default=None)
entries = []
def extract_info(html, video_id, num=None): def extract_info(html, video_id, num=None):
title, description = [None] * 2 title, description = [None] * 2
formats = [] formats = []
@@ -233,7 +231,7 @@ class AnimeOnDemandIE(InfoExtractor):
self._sort_formats(info['formats']) self._sort_formats(info['formats'])
f = common_info.copy() f = common_info.copy()
f.update(info) f.update(info)
entries.append(f) yield f
# Extract teaser/trailer only when full episode is not available # Extract teaser/trailer only when full episode is not available
if not info['formats']: if not info['formats']:
@@ -247,7 +245,7 @@ class AnimeOnDemandIE(InfoExtractor):
'title': m.group('title'), 'title': m.group('title'),
'url': urljoin(url, m.group('href')), 'url': urljoin(url, m.group('href')),
}) })
entries.append(f) yield f
def extract_episodes(html): def extract_episodes(html):
for num, episode_html in enumerate(re.findall( for num, episode_html in enumerate(re.findall(
@@ -275,7 +273,8 @@ class AnimeOnDemandIE(InfoExtractor):
'episode_number': episode_number, 'episode_number': episode_number,
} }
extract_entries(episode_html, video_id, common_info) for e in extract_entries(episode_html, video_id, common_info):
yield e
def extract_film(html, video_id): def extract_film(html, video_id):
common_info = { common_info = {
@@ -283,11 +282,18 @@ class AnimeOnDemandIE(InfoExtractor):
'title': anime_title, 'title': anime_title,
'description': anime_description, 'description': anime_description,
} }
extract_entries(html, video_id, common_info) for e in extract_entries(html, video_id, common_info):
yield e
extract_episodes(webpage) def entries():
has_episodes = False
for e in extract_episodes(webpage):
has_episodes = True
yield e
if not entries: if not has_episodes:
extract_film(webpage, anime_id) for e in extract_film(webpage, anime_id):
yield e
return self.playlist_result(entries, anime_id, anime_title, anime_description) return self.playlist_result(
entries(), anime_id, anime_title, anime_description)
+26 -1
View File
@@ -8,11 +8,14 @@ from ..utils import (
ExtractorError, ExtractorError,
extract_attributes, extract_attributes,
find_xpath_attr, find_xpath_attr,
get_element_by_attribute,
get_element_by_class, get_element_by_class,
int_or_none, int_or_none,
js_to_json, js_to_json,
merge_dicts, merge_dicts,
parse_iso8601,
smuggle_url, smuggle_url,
str_to_int,
unescapeHTML, unescapeHTML,
) )
from .senateisvp import SenateISVPIE from .senateisvp import SenateISVPIE
@@ -116,8 +119,30 @@ class CSpanIE(InfoExtractor):
jwsetup, video_id, require_title=False, m3u8_id='hls', jwsetup, video_id, require_title=False, m3u8_id='hls',
base_url=url) base_url=url)
add_referer(info['formats']) add_referer(info['formats'])
for subtitles in info['subtitles'].values():
for subtitle in subtitles:
ext = determine_ext(subtitle['url'])
if ext == 'php':
ext = 'vtt'
subtitle['ext'] = ext
ld_info = self._search_json_ld(webpage, video_id, default={}) ld_info = self._search_json_ld(webpage, video_id, default={})
return merge_dicts(info, ld_info) title = get_element_by_class('video-page-title', webpage) or \
self._og_search_title(webpage)
description = get_element_by_attribute('itemprop', 'description', webpage) or \
self._html_search_meta(['og:description', 'description'], webpage)
return merge_dicts(info, ld_info, {
'title': title,
'thumbnail': get_element_by_attribute('itemprop', 'thumbnailUrl', webpage),
'description': description,
'timestamp': parse_iso8601(get_element_by_attribute('itemprop', 'uploadDate', webpage)),
'location': get_element_by_attribute('itemprop', 'contentLocation', webpage),
'duration': int_or_none(self._search_regex(
r'jwsetup\.seclength\s*=\s*(\d+);',
webpage, 'duration', fatal=False)),
'view_count': str_to_int(self._search_regex(
r"<span[^>]+class='views'[^>]*>([\d,]+)\s+Views</span>",
webpage, 'views', fatal=False)),
})
# Obsolete # Obsolete
# We first look for clipid, because clipprog always appears before # We first look for clipid, because clipprog always appears before
+5 -1
View File
@@ -551,7 +551,10 @@ from .karaoketv import KaraoketvIE
from .karrierevideos import KarriereVideosIE from .karrierevideos import KarriereVideosIE
from .keezmovies import KeezMoviesIE from .keezmovies import KeezMoviesIE
from .ketnet import KetnetIE from .ketnet import KetnetIE
from .khanacademy import KhanAcademyIE from .khanacademy import (
KhanAcademyIE,
KhanAcademyUnitIE,
)
from .kickstarter import KickStarterIE from .kickstarter import KickStarterIE
from .kinja import KinjaEmbedIE from .kinja import KinjaEmbedIE
from .kinopoisk import KinoPoiskIE from .kinopoisk import KinoPoiskIE
@@ -1262,6 +1265,7 @@ from .toutv import TouTvIE
from .toypics import ToypicsUserIE, ToypicsIE from .toypics import ToypicsUserIE, ToypicsIE
from .traileraddict import TrailerAddictIE from .traileraddict import TrailerAddictIE
from .trilulilu import TriluliluIE from .trilulilu import TriluliluIE
from .trovolive import TrovoLiveIE
from .trunews import TruNewsIE from .trunews import TruNewsIE
from .trutv import TruTVIE from .trutv import TruTVIE
from .tube8 import Tube8IE from .tube8 import Tube8IE
+81 -56
View File
@@ -1,82 +1,107 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import re import json
from .common import InfoExtractor from .common import InfoExtractor
from ..utils import ( from ..utils import (
unified_strdate, int_or_none,
parse_iso8601,
try_get,
) )
class KhanAcademyIE(InfoExtractor): class KhanAcademyBaseIE(InfoExtractor):
_VALID_URL = r'^https?://(?:(?:www|api)\.)?khanacademy\.org/(?P<key>[^/]+)/(?:[^/]+/){,2}(?P<id>[^?#/]+)(?:$|[?#])' _VALID_URL_TEMPL = r'https?://(?:www\.)?khanacademy\.org/(?P<id>(?:[^/]+/){%s}%s[^?#/&]+)'
IE_NAME = 'KhanAcademy'
_TESTS = [{ def _parse_video(self, video):
'url': 'http://www.khanacademy.org/video/one-time-pad', return {
'md5': '7b391cce85e758fb94f763ddc1bbb979', '_type': 'url_transparent',
'url': video['youtubeId'],
'id': video.get('slug'),
'title': video.get('title'),
'thumbnail': video.get('imageUrl') or video.get('thumbnailUrl'),
'duration': int_or_none(video.get('duration')),
'description': video.get('description'),
'ie_key': 'Youtube',
}
def _real_extract(self, url):
display_id = self._match_id(url)
component_props = self._parse_json(self._download_json(
'https://www.khanacademy.org/api/internal/graphql',
display_id, query={
'hash': 1604303425,
'variables': json.dumps({
'path': display_id,
'queryParams': '',
}),
})['data']['contentJson'], display_id)['componentProps']
return self._parse_component_props(component_props)
class KhanAcademyIE(KhanAcademyBaseIE):
IE_NAME = 'khanacademy'
_VALID_URL = KhanAcademyBaseIE._VALID_URL_TEMPL % ('4', 'v/')
_TEST = {
'url': 'https://www.khanacademy.org/computing/computer-science/cryptography/crypt/v/one-time-pad',
'md5': '9c84b7b06f9ebb80d22a5c8dedefb9a0',
'info_dict': { 'info_dict': {
'id': 'one-time-pad', 'id': 'FlIG3TvQCBQ',
'ext': 'webm', 'ext': 'mp4',
'title': 'The one-time pad', 'title': 'The one-time pad',
'description': 'The perfect cipher', 'description': 'The perfect cipher',
'duration': 176, 'duration': 176,
'uploader': 'Brit Cruise', 'uploader': 'Brit Cruise',
'uploader_id': 'khanacademy', 'uploader_id': 'khanacademy',
'upload_date': '20120411', 'upload_date': '20120411',
'timestamp': 1334170113,
'license': 'cc-by-nc-sa',
}, },
'add_ie': ['Youtube'], 'add_ie': ['Youtube'],
}, { }
'url': 'https://www.khanacademy.org/math/applied-math/cryptography',
def _parse_component_props(self, component_props):
video = component_props['tutorialPageData']['contentModel']
info = self._parse_video(video)
author_names = video.get('authorNames')
info.update({
'uploader': ', '.join(author_names) if author_names else None,
'timestamp': parse_iso8601(video.get('dateAdded')),
'license': video.get('kaUserLicense'),
})
return info
class KhanAcademyUnitIE(KhanAcademyBaseIE):
IE_NAME = 'khanacademy:unit'
_VALID_URL = (KhanAcademyBaseIE._VALID_URL_TEMPL % ('2', '')) + '/?(?:[?#&]|$)'
_TEST = {
'url': 'https://www.khanacademy.org/computing/computer-science/cryptography',
'info_dict': { 'info_dict': {
'id': 'cryptography', 'id': 'cryptography',
'title': 'Journey into cryptography', 'title': 'Cryptography',
'description': 'How have humans protected their secret messages through history? What has changed today?', 'description': 'How have humans protected their secret messages through history? What has changed today?',
}, },
'playlist_mincount': 3, 'playlist_mincount': 31,
}] }
def _real_extract(self, url): def _parse_component_props(self, component_props):
m = re.match(self._VALID_URL, url) curation = component_props['curation']
video_id = m.group('id')
if m.group('key') == 'video': entries = []
data = self._download_json( tutorials = try_get(curation, lambda x: x['tabs'][0]['modules'][0]['tutorials'], list) or []
'http://api.khanacademy.org/api/v1/videos/' + video_id, for tutorial_number, tutorial in enumerate(tutorials, 1):
video_id, 'Downloading video info') chapter_info = {
'chapter': tutorial.get('title'),
upload_date = unified_strdate(data['date_added']) 'chapter_number': tutorial_number,
uploader = ', '.join(data['author_names']) 'chapter_id': tutorial.get('id'),
return {
'_type': 'url_transparent',
'url': data['url'],
'id': video_id,
'title': data['title'],
'thumbnail': data['image_url'],
'duration': data['duration'],
'description': data['description'],
'uploader': uploader,
'upload_date': upload_date,
} }
else: for content_item in (tutorial.get('contentItems') or []):
# topic if content_item.get('kind') == 'Video':
data = self._download_json( info = self._parse_video(content_item)
'http://api.khanacademy.org/api/v1/topic/' + video_id, info.update(chapter_info)
video_id, 'Downloading topic info') entries.append(info)
entries = [ return self.playlist_result(
{ entries, curation.get('unit'), curation.get('title'),
'_type': 'url', curation.get('description'))
'url': c['url'],
'id': c['id'],
'title': c['title'],
}
for c in data['children'] if c['kind'] in ('Video', 'Topic')]
return {
'_type': 'playlist',
'id': video_id,
'title': data['title'],
'description': data['description'],
'entries': entries,
}
+7 -2
View File
@@ -251,8 +251,11 @@ class MixcloudPlaylistBaseIE(MixcloudBaseIE):
cloudcast_url = cloudcast.get('url') cloudcast_url = cloudcast.get('url')
if not cloudcast_url: if not cloudcast_url:
continue continue
slug = try_get(cloudcast, lambda x: x['slug'], compat_str)
owner_username = try_get(cloudcast, lambda x: x['owner']['username'], compat_str)
video_id = '%s_%s' % (owner_username, slug) if slug and owner_username else None
entries.append(self.url_result( entries.append(self.url_result(
cloudcast_url, MixcloudIE.ie_key(), cloudcast.get('slug'))) cloudcast_url, MixcloudIE.ie_key(), video_id))
page_info = items['pageInfo'] page_info = items['pageInfo']
has_next_page = page_info['hasNextPage'] has_next_page = page_info['hasNextPage']
@@ -321,7 +324,8 @@ class MixcloudUserIE(MixcloudPlaylistBaseIE):
_DESCRIPTION_KEY = 'biog' _DESCRIPTION_KEY = 'biog'
_ROOT_TYPE = 'user' _ROOT_TYPE = 'user'
_NODE_TEMPLATE = '''slug _NODE_TEMPLATE = '''slug
url''' url
owner { username }'''
def _get_playlist_title(self, title, slug): def _get_playlist_title(self, title, slug):
return '%s (%s)' % (title, slug) return '%s (%s)' % (title, slug)
@@ -345,6 +349,7 @@ class MixcloudPlaylistIE(MixcloudPlaylistBaseIE):
_NODE_TEMPLATE = '''cloudcast { _NODE_TEMPLATE = '''cloudcast {
slug slug
url url
owner { username }
}''' }'''
def _get_cloudcast(self, node): def _get_cloudcast(self, node):
+21 -1
View File
@@ -450,6 +450,18 @@ class PeerTubeIE(InfoExtractor):
'tags': ['framasoft', 'peertube'], 'tags': ['framasoft', 'peertube'],
'categories': ['Science & Technology'], 'categories': ['Science & Technology'],
} }
}, {
# Issue #26002
'url': 'peertube:spacepub.space:d8943b2d-8280-497b-85ec-bc282ec2afdc',
'info_dict': {
'id': 'd8943b2d-8280-497b-85ec-bc282ec2afdc',
'ext': 'mp4',
'title': 'Dot matrix printer shell demo',
'uploader_id': '3',
'timestamp': 1587401293,
'upload_date': '20200420',
'uploader': 'Drew DeVault',
}
}, { }, {
'url': 'https://peertube.tamanoir.foucry.net/videos/watch/0b04f13d-1e18-4f1d-814e-4979aa7c9c44', 'url': 'https://peertube.tamanoir.foucry.net/videos/watch/0b04f13d-1e18-4f1d-814e-4979aa7c9c44',
'only_matching': True, 'only_matching': True,
@@ -526,7 +538,15 @@ class PeerTubeIE(InfoExtractor):
title = video['name'] title = video['name']
formats = [] formats = []
for file_ in video['files']: files = video.get('files') or []
for playlist in (video.get('streamingPlaylists') or []):
if not isinstance(playlist, dict):
continue
playlist_files = playlist.get('files')
if not (playlist_files and isinstance(playlist_files, list)):
continue
files.extend(playlist_files)
for file_ in files:
if not isinstance(file_, dict): if not isinstance(file_, dict):
continue continue
file_url = url_or_none(file_.get('fileUrl')) file_url = url_or_none(file_.get('fileUrl'))
+4 -1
View File
@@ -75,7 +75,7 @@ class PokemonIE(InfoExtractor):
class PokemonWatchIE(InfoExtractor): class PokemonWatchIE(InfoExtractor):
_VALID_URL = r'https?://watch\.pokemon\.com/[a-z]{2}-[a-z]{2}/player\.html\?id=(?P<id>[a-z0-9]{32})' _VALID_URL = r'https?://watch\.pokemon\.com/[a-z]{2}-[a-z]{2}/(?:#/)?player(?:\.html)?\?id=(?P<id>[a-z0-9]{32})'
_API_URL = 'https://www.pokemon.com/api/pokemontv/v2/channels/{0:}' _API_URL = 'https://www.pokemon.com/api/pokemontv/v2/channels/{0:}'
_TESTS = [{ _TESTS = [{
'url': 'https://watch.pokemon.com/en-us/player.html?id=8309a40969894a8e8d5bc1311e9c5667', 'url': 'https://watch.pokemon.com/en-us/player.html?id=8309a40969894a8e8d5bc1311e9c5667',
@@ -86,6 +86,9 @@ class PokemonWatchIE(InfoExtractor):
'title': 'Lillier and the Staff!', 'title': 'Lillier and the Staff!',
'description': 'md5:338841b8c21b283d24bdc9b568849f04', 'description': 'md5:338841b8c21b283d24bdc9b568849f04',
} }
}, {
'url': 'https://watch.pokemon.com/en-us/#/player?id=3fe7752ba09141f0b0f7756d1981c6b2',
'only_matching': True
}, { }, {
'url': 'https://watch.pokemon.com/de-de/player.html?id=b3c402e111a4459eb47e12160ab0ba07', 'url': 'https://watch.pokemon.com/de-de/player.html?id=b3c402e111a4459eb47e12160ab0ba07',
'only_matching': True 'only_matching': True
+15 -2
View File
@@ -30,6 +30,19 @@ class RoosterTeethIE(InfoExtractor):
'series': 'Million Dollars, But...', 'series': 'Million Dollars, But...',
'episode': 'Million Dollars, But... The Game Announcement', 'episode': 'Million Dollars, But... The Game Announcement',
}, },
}, {
'url': 'https://roosterteeth.com/watch/rwby-bonus-25',
'md5': 'fe8d9d976b272c18a24fe7f1f5830084',
'info_dict': {
'id': '31',
'display_id': 'rwby-bonus-25',
'title': 'Volume 2, World of Remnant 3',
'description': 'md5:8d58d3270292ea11da00ea712bbfb009',
'episode': 'Volume 2, World of Remnant 3',
'channel_id': 'fab60c1c-29cb-43bc-9383-5c3538d9e246',
'thumbnail': r're:^https?://.*\.(png|jpe?g)$',
'ext': 'mp4',
},
}, { }, {
'url': 'http://achievementhunter.roosterteeth.com/episode/off-topic-the-achievement-hunter-podcast-2016-i-didn-t-think-it-would-pass-31', 'url': 'http://achievementhunter.roosterteeth.com/episode/off-topic-the-achievement-hunter-podcast-2016-i-didn-t-think-it-would-pass-31',
'only_matching': True, 'only_matching': True,
@@ -50,7 +63,7 @@ class RoosterTeethIE(InfoExtractor):
'url': 'https://roosterteeth.com/watch/million-dollars-but-season-2-million-dollars-but-the-game-announcement', 'url': 'https://roosterteeth.com/watch/million-dollars-but-season-2-million-dollars-but-the-game-announcement',
'only_matching': True, 'only_matching': True,
}] }]
_EPISODE_BASE_URL = 'https://svod-be.roosterteeth.com/api/v1/episodes/' _EPISODE_BASE_URL = 'https://svod-be.roosterteeth.com/api/v1/watch/'
def _login(self): def _login(self):
username, password = self._get_login_info() username, password = self._get_login_info()
@@ -111,7 +124,7 @@ class RoosterTeethIE(InfoExtractor):
thumbnails = [] thumbnails = []
for image in episode.get('included', {}).get('images', []): for image in episode.get('included', {}).get('images', []):
if image.get('type') == 'episode_image': if image.get('type') in ('episode_image', 'bonus_feature_image'):
img_attributes = image.get('attributes') or {} img_attributes = image.get('attributes') or {}
for k in ('thumb', 'small', 'medium', 'large'): for k in ('thumb', 'small', 'medium', 'large'):
img_url = img_attributes.get(k) img_url = img_attributes.get(k)
+7 -1
View File
@@ -50,9 +50,15 @@ class ParamountNetworkIE(MTVServicesInfoExtractor):
}, },
}] }]
_FEED_URL = 'http://www.paramountnetwork.com/feeds/mrss/' _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
_GEO_COUNTRIES = ['US'] _GEO_COUNTRIES = ['US']
def _get_feed_query(self, uri):
return {
'arcEp': 'paramountnetwork.com',
'mgid': uri,
}
def _extract_mgid(self, webpage, url): def _extract_mgid(self, webpage, url):
root_data = self._parse_json(self._search_regex( root_data = self._parse_json(self._search_regex(
r'window\.__DATA__\s*=\s*({.+})', r'window\.__DATA__\s*=\s*({.+})',
+92 -70
View File
@@ -3,10 +3,13 @@ from __future__ import unicode_literals
import re import re
from .common import InfoExtractor from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import ( from ..utils import (
determine_ext, determine_ext,
js_to_json, ExtractorError,
mimetype2ext, float_or_none,
int_or_none,
parse_iso8601,
) )
@@ -15,29 +18,35 @@ class ThreeQSDNIE(InfoExtractor):
IE_DESC = '3Q SDN' IE_DESC = '3Q SDN'
_VALID_URL = r'https?://playout\.3qsdn\.com/(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})' _VALID_URL = r'https?://playout\.3qsdn\.com/(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})'
_TESTS = [{ _TESTS = [{
# ondemand from http://www.philharmonie.tv/veranstaltung/26/ # https://player.3qsdn.com/demo.html
'url': 'http://playout.3qsdn.com/0280d6b9-1215-11e6-b427-0cc47a188158?protocol=http', 'url': 'https://playout.3qsdn.com/7201c779-6b3c-11e7-a40e-002590c750be',
'md5': 'ab040e37bcfa2e0c079f92cb1dd7f6cd', 'md5': '64a57396b16fa011b15e0ea60edce918',
'info_dict': { 'info_dict': {
'id': '0280d6b9-1215-11e6-b427-0cc47a188158', 'id': '7201c779-6b3c-11e7-a40e-002590c750be',
'ext': 'mp4', 'ext': 'mp4',
'title': '0280d6b9-1215-11e6-b427-0cc47a188158', 'title': 'Video Ads',
'is_live': False, 'is_live': False,
'description': 'Video Ads Demo',
'timestamp': 1500334803,
'upload_date': '20170717',
'duration': 888.032,
'subtitles': {
'eng': 'count:1',
},
}, },
'expected_warnings': ['Failed to download MPD manifest', 'Failed to parse JSON'], 'expected_warnings': ['Unknown MIME type application/mp4 in DASH manifest'],
}, { }, {
# live video stream # live video stream
'url': 'https://playout.3qsdn.com/d755d94b-4ab9-11e3-9162-0025907ad44f?js=true', 'url': 'https://playout.3qsdn.com/66e68995-11ca-11e8-9273-002590c750be',
'info_dict': { 'info_dict': {
'id': 'd755d94b-4ab9-11e3-9162-0025907ad44f', 'id': '66e68995-11ca-11e8-9273-002590c750be',
'ext': 'mp4', 'ext': 'mp4',
'title': 're:^d755d94b-4ab9-11e3-9162-0025907ad44f [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$', 'title': 're:^66e68995-11ca-11e8-9273-002590c750be [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
'is_live': True, 'is_live': True,
}, },
'params': { 'params': {
'skip_download': True, # m3u8 downloads 'skip_download': True, # m3u8 downloads
}, },
'expected_warnings': ['Failed to download MPD manifest'],
}, { }, {
# live audio stream # live audio stream
'url': 'http://playout.3qsdn.com/9edf36e0-6bf2-11e2-a16a-9acf09e2db48', 'url': 'http://playout.3qsdn.com/9edf36e0-6bf2-11e2-a16a-9acf09e2db48',
@@ -58,6 +67,14 @@ class ThreeQSDNIE(InfoExtractor):
# live video with rtmp link # live video with rtmp link
'url': 'https://playout.3qsdn.com/6092bb9e-8f72-11e4-a173-002590c750be', 'url': 'https://playout.3qsdn.com/6092bb9e-8f72-11e4-a173-002590c750be',
'only_matching': True, 'only_matching': True,
}, {
# ondemand from http://www.philharmonie.tv/veranstaltung/26/
'url': 'http://playout.3qsdn.com/0280d6b9-1215-11e6-b427-0cc47a188158?protocol=http',
'only_matching': True,
}, {
# live video stream
'url': 'https://playout.3qsdn.com/d755d94b-4ab9-11e3-9162-0025907ad44f?js=true',
'only_matching': True,
}] }]
@staticmethod @staticmethod
@@ -70,73 +87,78 @@ class ThreeQSDNIE(InfoExtractor):
def _real_extract(self, url): def _real_extract(self, url):
video_id = self._match_id(url) video_id = self._match_id(url)
js = self._download_webpage( try:
'http://playout.3qsdn.com/%s' % video_id, video_id, config = self._download_json(
query={'js': 'true'}) url.replace('://playout.3qsdn.com/', '://playout.3qsdn.com/config/'), video_id)
except ExtractorError as e:
if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
self.raise_geo_restricted()
raise
if any(p in js for p in ( live = config.get('streamContent') == 'live'
'>This content is not available in your country', aspect = float_or_none(config.get('aspect'))
'playout.3qsdn.com/forbidden')):
self.raise_geo_restricted()
stream_content = self._search_regex(
r'streamContent\s*:\s*(["\'])(?P<content>.+?)\1', js,
'stream content', default='demand', group='content')
live = stream_content == 'live'
stream_type = self._search_regex(
r'streamType\s*:\s*(["\'])(?P<type>audio|video)\1', js,
'stream type', default='video', group='type')
formats = [] formats = []
urls = set() for source_type, source in (config.get('sources') or {}).items():
if not source:
def extract_formats(item_url, item={}):
if not item_url or item_url in urls:
return
urls.add(item_url)
ext = mimetype2ext(item.get('type')) or determine_ext(item_url, default_ext=None)
if ext == 'mpd':
formats.extend(self._extract_mpd_formats(
item_url, video_id, mpd_id='mpd', fatal=False))
elif ext == 'm3u8':
formats.extend(self._extract_m3u8_formats(
item_url, video_id, 'mp4',
entry_protocol='m3u8' if live else 'm3u8_native',
m3u8_id='hls', fatal=False))
elif ext == 'f4m':
formats.extend(self._extract_f4m_formats(
item_url, video_id, f4m_id='hds', fatal=False))
else:
if not self._is_valid_url(item_url, video_id):
return
formats.append({
'url': item_url,
'format_id': item.get('quality'),
'ext': 'mp4' if item_url.startswith('rtsp') else ext,
'vcodec': 'none' if stream_type == 'audio' else None,
})
for item_js in re.findall(r'({[^{]*?\b(?:src|source)\s*:\s*["\'].+?})', js):
f = self._parse_json(
item_js, video_id, transform_source=js_to_json, fatal=False)
if not f:
continue continue
extract_formats(f.get('src'), f) if source_type == 'dash':
formats.extend(self._extract_mpd_formats(
source, video_id, mpd_id='mpd', fatal=False))
elif source_type == 'hls':
formats.extend(self._extract_m3u8_formats(
source, video_id, 'mp4', 'm3u8' if live else 'm3u8_native',
m3u8_id='hls', fatal=False))
elif source_type == 'progressive':
for s in source:
src = s.get('src')
if not (src and self._is_valid_url(src, video_id)):
continue
width = None
format_id = ['http']
ext = determine_ext(src)
if ext:
format_id.append(ext)
height = int_or_none(s.get('height'))
if height:
format_id.append('%dp' % height)
if aspect:
width = int(height * aspect)
formats.append({
'ext': ext,
'format_id': '-'.join(format_id),
'height': height,
'source_preference': 0,
'url': src,
'vcodec': 'none' if height == 0 else None,
'width': width,
})
for f in formats:
if f.get('acodec') == 'none':
f['preference'] = -40
elif f.get('vcodec') == 'none':
f['preference'] = -50
self._sort_formats(formats, ('preference', 'width', 'height', 'source_preference', 'tbr', 'vbr', 'abr', 'ext', 'format_id'))
# More relaxed version to collect additional URLs and acting subtitles = {}
# as a future-proof fallback for subtitle in (config.get('subtitles') or []):
for _, src in re.findall(r'\b(?:src|source)\s*:\s*(["\'])((?:https?|rtsp)://.+?)\1', js): src = subtitle.get('src')
extract_formats(src) if not src:
continue
subtitles.setdefault(subtitle.get('label') or 'eng', []).append({
'url': src,
})
self._sort_formats(formats) title = config.get('title') or video_id
title = self._live_title(video_id) if live else video_id
return { return {
'id': video_id, 'id': video_id,
'title': title, 'title': self._live_title(title) if live else title,
'thumbnail': config.get('poster') or None,
'description': config.get('description') or None,
'timestamp': parse_iso8601(config.get('upload_date')),
'duration': float_or_none(config.get('vlength')) or None,
'is_live': live, 'is_live': live,
'formats': formats, 'formats': formats,
'subtitles': subtitles,
} }
+2 -2
View File
@@ -17,8 +17,8 @@ class TikTokBaseIE(InfoExtractor):
video_info = try_get( video_info = try_get(
video_data, lambda x: x['itemInfo']['itemStruct'], dict) video_data, lambda x: x['itemInfo']['itemStruct'], dict)
author_info = try_get( author_info = try_get(
video_data, lambda x: x['itemInfo']['itemStruct']['author'], dict) video_data, lambda x: x['itemInfo']['itemStruct']['author'], dict) or {}
share_info = try_get(video_data, lambda x: x['itemInfo']['shareMeta'], dict) share_info = try_get(video_data, lambda x: x['itemInfo']['shareMeta'], dict) or {}
unique_id = str_or_none(author_info.get('uniqueId')) unique_id = str_or_none(author_info.get('uniqueId'))
timestamp = try_get(video_info, lambda x: int(x['createTime']), int) timestamp = try_get(video_info, lambda x: int(x['createTime']), int)
+111
View File
@@ -0,0 +1,111 @@
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
js_to_json,
try_get,
int_or_none,
str_or_none,
url_or_none,
)
from ..compat import compat_str
class TrovoLiveIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?trovo\.live/video/(?P<id>[\w-]+)'
_TEST = {
'url': 'https://trovo.live/video/ltv-100759829_100759829_1610625308',
'md5': 'ea7b58427910e9af66a462d895201a30',
'info_dict': {
'id': 'ltv-100759829_100759829_1610625308',
'ext': 'ts',
'title': 'GTA RP ASTERIX doa najjaca',
'uploader': 'Peroo42',
'duration': 5872,
'view_count': int,
'like_count': int,
'comment_count': int,
'categories': list,
'is_live': False,
'thumbnail': r're:^https?://.*\.jpg$',
'uploader_id': '100759829',
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
nuxt = self._search_regex(r'\bwindow\.__NUXT__\s*=\s*(.+?);?\s*</script>', webpage, 'nuxt', default='')
mobj = re.search(r'\((?P<arg_names>[^(]+)\)\s*{\s*return\s+(?P<json>{.+})\s*\((?P<args>.+?)\)\s*\)$', nuxt)
vod_details = vod_info = {}
if mobj:
vod_details = self._parse_json(
js_to_json(
self._search_regex(r'VodDetailInfos\s*:({.+?}),\s*_', webpage, 'VodDetailInfos'),
dict(zip(
(i.strip() for i in mobj.group('arg_names').split(',')),
(i.strip() for i in mobj.group('args').split(','))))),
video_id)
vod_info = try_get(vod_details, lambda x: x['json'][video_id]['vodInfo'], dict) or {}
player_info = self._parse_json(
self._search_regex(
r'_playerInfo\s*=\s*({.+?})\s*</script>', webpage, 'player info'),
video_id)
title = (
vod_info.get('title')
or self._html_search_regex(r'<h3>(.+?)</h3>', webpage, 'title', fatal=False)
or self._og_search_title(webpage))
uploader = (
try_get(vod_details, lambda x: x['json'][video_id]['streamerInfo']['userName'], compat_str)
or self._search_regex(r'<div[^>]+userName\s=\s[\'"](.+?)[\'"]', webpage, 'uploader', fatal=False))
format_dicts = vod_info.get('playInfos') or player_info.get('urlArray') or []
def _extract_format_data(format_dict):
res = format_dict.get('desc')
enc = str_or_none(format_dict.get('encodeType'))
if enc:
notes = [enc.replace('VOD_ENCODE_TYPE_', '')]
level = str_or_none(format_dict.get('levelType'))
if level:
notes.append('level %s' % level)
height = int_or_none(res[:-1]) if res else None
bitrate = format_dict.get('bitrate')
fid = res or ('%sk' % str_or_none(bitrate) if bitrate else None) or ' '.join(notes)
return {
'url': format_dict['playUrl'],
'format_id': fid,
'format_note': ' '.join(notes),
'height': height,
'resolution': str_or_none(res),
'tbr': int_or_none(bitrate),
'filesize': int_or_none(format_dict.get('fileSize')),
'vcodec': 'avc3',
'acodec': 'aac',
'ext': 'ts'
}
formats = [_extract_format_data(f) for f in format_dicts]
self._sort_formats(formats)
return {
'id': video_id,
'title': title,
'uploader': uploader,
'duration': int_or_none(vod_info.get('duration')),
'formats': formats,
'view_count': int_or_none(vod_info.get('watchNum')),
'like_count': int_or_none(vod_info.get('likeNum')),
'comment_count': int_or_none(vod_info.get('commentNum')),
'categories': [str_or_none(vod_info.get('categoryName'))],
'is_live': try_get(player_info, lambda x: x['isLive'], bool),
'thumbnail': url_or_none(vod_info.get('coverUrl')),
'uploader_id': str_or_none(try_get(vod_details, lambda x: x['json'][video_id]['streamerInfo']['uid'])),
}
+11 -6
View File
@@ -17,6 +17,7 @@ from ..compat import (
) )
from ..utils import ( from ..utils import (
clean_html, clean_html,
dict_get,
ExtractorError, ExtractorError,
float_or_none, float_or_none,
int_or_none, int_or_none,
@@ -76,14 +77,14 @@ class TwitchBaseIE(InfoExtractor):
headers = { headers = {
'Referer': page_url, 'Referer': page_url,
'Origin': page_url, 'Origin': 'https://www.twitch.tv',
'Content-Type': 'text/plain;charset=UTF-8', 'Content-Type': 'text/plain;charset=UTF-8',
} }
response = self._download_json( response = self._download_json(
post_url, None, note, data=json.dumps(form).encode(), post_url, None, note, data=json.dumps(form).encode(),
headers=headers, expected_status=400) headers=headers, expected_status=400)
error = response.get('error_description') or response.get('error_code') error = dict_get(response, ('error', 'error_description', 'error_code'))
if error: if error:
fail(error) fail(error)
@@ -137,13 +138,17 @@ class TwitchBaseIE(InfoExtractor):
self._sort_formats(formats) self._sort_formats(formats)
def _download_base_gql(self, video_id, ops, note, fatal=True): def _download_base_gql(self, video_id, ops, note, fatal=True):
headers = {
'Content-Type': 'text/plain;charset=UTF-8',
'Client-ID': self._CLIENT_ID,
}
gql_auth = self._get_cookies('https://gql.twitch.tv').get('auth-token')
if gql_auth:
headers['Authorization'] = 'OAuth ' + gql_auth.value
return self._download_json( return self._download_json(
'https://gql.twitch.tv/gql', video_id, note, 'https://gql.twitch.tv/gql', video_id, note,
data=json.dumps(ops).encode(), data=json.dumps(ops).encode(),
headers={ headers=headers, fatal=fatal)
'Content-Type': 'text/plain;charset=UTF-8',
'Client-ID': self._CLIENT_ID,
}, fatal=fatal)
def _download_gql(self, video_id, ops, note, fatal=True): def _download_gql(self, video_id, ops, note, fatal=True):
for op in ops: for op in ops:
+45 -3
View File
@@ -373,6 +373,24 @@ class TwitterIE(TwitterBaseIE):
'uploader_id': '1eVjYOLGkGrQL', 'uploader_id': '1eVjYOLGkGrQL',
}, },
'add_ie': ['TwitterBroadcast'], 'add_ie': ['TwitterBroadcast'],
}, {
# unified card
'url': 'https://twitter.com/BrooklynNets/status/1349794411333394432?s=20',
'info_dict': {
'id': '1349794411333394432',
'ext': 'mp4',
'title': 'md5:d1c4941658e4caaa6cb579260d85dcba',
'thumbnail': r're:^https?://.*\.jpg',
'description': 'md5:71ead15ec44cee55071547d6447c6a3e',
'uploader': 'Brooklyn Nets',
'uploader_id': 'BrooklynNets',
'duration': 324.484,
'timestamp': 1610651040,
'upload_date': '20210114',
},
'params': {
'skip_download': True,
},
}, { }, {
# Twitch Clip Embed # Twitch Clip Embed
'url': 'https://twitter.com/GunB1g/status/1163218564784017422', 'url': 'https://twitter.com/GunB1g/status/1163218564784017422',
@@ -389,6 +407,22 @@ class TwitterIE(TwitterBaseIE):
# appplayer card # appplayer card
'url': 'https://twitter.com/poco_dandy/status/1150646424461176832', 'url': 'https://twitter.com/poco_dandy/status/1150646424461176832',
'only_matching': True, 'only_matching': True,
}, {
# video_direct_message card
'url': 'https://twitter.com/qarev001/status/1348948114569269251',
'only_matching': True,
}, {
# poll2choice_video card
'url': 'https://twitter.com/CAF_Online/status/1349365911120195585',
'only_matching': True,
}, {
# poll3choice_video card
'url': 'https://twitter.com/SamsungMobileSA/status/1348609186725289984',
'only_matching': True,
}, {
# poll4choice_video card
'url': 'https://twitter.com/SouthamptonFC/status/1347577658079641604',
'only_matching': True,
}] }]
def _real_extract(self, url): def _real_extract(self, url):
@@ -433,8 +467,7 @@ class TwitterIE(TwitterBaseIE):
'tags': tags, 'tags': tags,
} }
media = try_get(status, lambda x: x['extended_entities']['media'][0]) def extract_from_video_info(media):
if media and media.get('type') != 'photo':
video_info = media.get('video_info') or {} video_info = media.get('video_info') or {}
formats = [] formats = []
@@ -461,6 +494,10 @@ class TwitterIE(TwitterBaseIE):
'thumbnails': thumbnails, 'thumbnails': thumbnails,
'duration': float_or_none(video_info.get('duration_millis'), 1000), 'duration': float_or_none(video_info.get('duration_millis'), 1000),
}) })
media = try_get(status, lambda x: x['extended_entities']['media'][0])
if media and media.get('type') != 'photo':
extract_from_video_info(media)
else: else:
card = status.get('card') card = status.get('card')
if card: if card:
@@ -493,7 +530,12 @@ class TwitterIE(TwitterBaseIE):
'_type': 'url', '_type': 'url',
'url': get_binding_value('card_url'), 'url': get_binding_value('card_url'),
}) })
# amplify, promo_video_website, promo_video_convo, appplayer, ... elif card_name == 'unified_card':
media_entities = self._parse_json(get_binding_value('unified_card'), twid)['media_entities']
extract_from_video_info(next(iter(media_entities.values())))
# amplify, promo_video_website, promo_video_convo, appplayer,
# video_direct_message, poll2choice_video, poll3choice_video,
# poll4choice_video, ...
else: else:
is_amplify = card_name == 'amplify' is_amplify = card_name == 'amplify'
vmap_url = get_binding_value('amplify_url_vmap') if is_amplify else get_binding_value('player_stream_url') vmap_url = get_binding_value('amplify_url_vmap') if is_amplify else get_binding_value('player_stream_url')
+7 -3
View File
@@ -60,6 +60,9 @@ class YouPornIE(InfoExtractor):
}, { }, {
'url': 'http://www.youporn.com/watch/505835', 'url': 'http://www.youporn.com/watch/505835',
'only_matching': True, 'only_matching': True,
}, {
'url': 'https://www.youporn.com/watch/13922959/femdom-principal/',
'only_matching': True,
}] }]
@staticmethod @staticmethod
@@ -88,7 +91,7 @@ class YouPornIE(InfoExtractor):
# Main source # Main source
definitions = self._parse_json( definitions = self._parse_json(
self._search_regex( self._search_regex(
r'mediaDefinition\s*=\s*(\[.+?\]);', webpage, r'mediaDefinition\s*[=:]\s*(\[.+?\])\s*[;,]', webpage,
'media definitions', default='[]'), 'media definitions', default='[]'),
video_id, fatal=False) video_id, fatal=False)
if definitions: if definitions:
@@ -100,7 +103,7 @@ class YouPornIE(InfoExtractor):
links.append(video_url) links.append(video_url)
# Fallback #1, this also contains extra low quality 180p format # Fallback #1, this also contains extra low quality 180p format
for _, link in re.findall(r'<a[^>]+href=(["\'])(http.+?)\1[^>]+title=["\']Download [Vv]ideo', webpage): for _, link in re.findall(r'<a[^>]+href=(["\'])(http(?:(?!\1).)+\.mp4(?:(?!\1).)*)\1[^>]+title=["\']Download [Vv]ideo', webpage):
links.append(link) links.append(link)
# Fallback #2 (unavailable as at 22.06.2017) # Fallback #2 (unavailable as at 22.06.2017)
@@ -128,8 +131,9 @@ class YouPornIE(InfoExtractor):
# Video URL's path looks like this: # Video URL's path looks like this:
# /201012/17/505835/720p_1500k_505835/YouPorn%20-%20Sex%20Ed%20Is%20It%20Safe%20To%20Masturbate%20Daily.mp4 # /201012/17/505835/720p_1500k_505835/YouPorn%20-%20Sex%20Ed%20Is%20It%20Safe%20To%20Masturbate%20Daily.mp4
# /201012/17/505835/vl_240p_240k_505835/YouPorn%20-%20Sex%20Ed%20Is%20It%20Safe%20To%20Masturbate%20Daily.mp4 # /201012/17/505835/vl_240p_240k_505835/YouPorn%20-%20Sex%20Ed%20Is%20It%20Safe%20To%20Masturbate%20Daily.mp4
# /videos/201703/11/109285532/1080P_4000K_109285532.mp4
# We will benefit from it by extracting some metadata # We will benefit from it by extracting some metadata
mobj = re.search(r'(?P<height>\d{3,4})[pP]_(?P<bitrate>\d+)[kK]_\d+/', video_url) mobj = re.search(r'(?P<height>\d{3,4})[pP]_(?P<bitrate>\d+)[kK]_\d+', video_url)
if mobj: if mobj:
height = int(mobj.group('height')) height = int(mobj.group('height'))
bitrate = int(mobj.group('bitrate')) bitrate = int(mobj.group('bitrate'))
+53 -80
View File
@@ -332,6 +332,36 @@ class YoutubeBaseInfoExtractor(InfoExtractor):
r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg', r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
default='{}'), video_id, fatal=False) default='{}'), video_id, fatal=False)
def _extract_video(self, renderer):
video_id = renderer.get('videoId')
title = try_get(
renderer,
(lambda x: x['title']['runs'][0]['text'],
lambda x: x['title']['simpleText']), compat_str)
description = try_get(
renderer, lambda x: x['descriptionSnippet']['runs'][0]['text'],
compat_str)
duration = parse_duration(try_get(
renderer, lambda x: x['lengthText']['simpleText'], compat_str))
view_count_text = try_get(
renderer, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
view_count = str_to_int(self._search_regex(
r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
'view count', default=None))
uploader = try_get(
renderer, lambda x: x['ownerText']['runs'][0]['text'], compat_str)
return {
'_type': 'url_transparent',
'ie_key': YoutubeIE.ie_key(),
'id': video_id,
'url': video_id,
'title': title,
'description': description,
'duration': duration,
'view_count': view_count,
'uploader': uploader,
}
class YoutubeIE(YoutubeBaseInfoExtractor): class YoutubeIE(YoutubeBaseInfoExtractor):
IE_DESC = 'YouTube.com' IE_DESC = 'YouTube.com'
@@ -2871,36 +2901,6 @@ class YoutubeTabIE(YoutubeBaseInfoExtractor):
if renderer: if renderer:
return renderer return renderer
def _extract_video(self, renderer):
video_id = renderer.get('videoId')
title = try_get(
renderer,
(lambda x: x['title']['runs'][0]['text'],
lambda x: x['title']['simpleText']), compat_str)
description = try_get(
renderer, lambda x: x['descriptionSnippet']['runs'][0]['text'],
compat_str)
duration = parse_duration(try_get(
renderer, lambda x: x['lengthText']['simpleText'], compat_str))
view_count_text = try_get(
renderer, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
view_count = str_to_int(self._search_regex(
r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
'view count', default=None))
uploader = try_get(
renderer, lambda x: x['ownerText']['runs'][0]['text'], compat_str)
return {
'_type': 'url_transparent',
'ie_key': YoutubeIE.ie_key(),
'id': video_id,
'url': video_id,
'title': title,
'description': description,
'duration': duration,
'view_count': view_count,
'uploader': uploader,
}
def _grid_entries(self, grid_renderer): def _grid_entries(self, grid_renderer):
for item in grid_renderer['items']: for item in grid_renderer['items']:
if not isinstance(item, dict): if not isinstance(item, dict):
@@ -3583,65 +3583,38 @@ class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
if not slr_contents: if not slr_contents:
break break
isr_contents = []
continuation_token = None
# Youtube sometimes adds promoted content to searches, # Youtube sometimes adds promoted content to searches,
# changing the index location of videos and token. # changing the index location of videos and token.
# So we search through all entries till we find them. # So we search through all entries till we find them.
for index, isr in enumerate(slr_contents): continuation_token = None
for slr_content in slr_contents:
isr_contents = try_get(
slr_content,
lambda x: x['itemSectionRenderer']['contents'],
list)
if not isr_contents: if not isr_contents:
isr_contents = try_get( continue
slr_contents, for content in isr_contents:
(lambda x: x[index]['itemSectionRenderer']['contents']), if not isinstance(content, dict):
list) continue
for content in isr_contents: video = content.get('videoRenderer')
if content.get('videoRenderer') is not None: if not isinstance(video, dict):
break continue
else: video_id = video.get('videoId')
isr_contents = [] if not video_id:
continue
yield self._extract_video(video)
total += 1
if total == n:
return
if continuation_token is None: if continuation_token is None:
continuation_token = try_get( continuation_token = try_get(
slr_contents, slr_content,
lambda x: x[index]['continuationItemRenderer']['continuationEndpoint']['continuationCommand'][ lambda x: x['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
'token'],
compat_str) compat_str)
if continuation_token is not None and isr_contents:
break
if not isr_contents:
break
for content in isr_contents:
if not isinstance(content, dict):
continue
video = content.get('videoRenderer')
if not isinstance(video, dict):
continue
video_id = video.get('videoId')
if not video_id:
continue
title = try_get(video, lambda x: x['title']['runs'][0]['text'], compat_str)
description = try_get(video, lambda x: x['descriptionSnippet']['runs'][0]['text'], compat_str)
duration = parse_duration(try_get(video, lambda x: x['lengthText']['simpleText'], compat_str))
view_count_text = try_get(video, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
view_count = str_to_int(self._search_regex(
r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
'view count', default=None))
uploader = try_get(video, lambda x: x['ownerText']['runs'][0]['text'], compat_str)
total += 1
yield {
'_type': 'url_transparent',
'ie_key': YoutubeIE.ie_key(),
'id': video_id,
'url': video_id,
'title': title,
'description': description,
'duration': duration,
'view_count': view_count,
'uploader': uploader,
}
if total == n:
return
if not continuation_token: if not continuation_token:
break break
data['continuation'] = continuation_token data['continuation'] = continuation_token
+141 -111
View File
@@ -54,42 +54,35 @@ def parseOpts(overrideArguments=None):
optionf.close() optionf.close()
return res return res
def _readUserConf(): def _readUserConf(package_name, default=[]):
xdg_config_home = compat_getenv('XDG_CONFIG_HOME') # .config
if xdg_config_home: xdg_config_home = compat_getenv('XDG_CONFIG_HOME') or compat_expanduser('~/.config')
userConfFile = os.path.join(xdg_config_home, 'youtube-dlc', 'config') userConfFile = os.path.join(xdg_config_home, package_name, 'config')
if not os.path.isfile(userConfFile): if not os.path.isfile(userConfFile):
userConfFile = os.path.join(xdg_config_home, 'youtube-dlc.conf') userConfFile = os.path.join(xdg_config_home, '%s.conf' % package_name)
else: userConf = _readOptions(userConfFile, default=None)
userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dlc', 'config') if userConf is not None:
if not os.path.isfile(userConfFile): return userConf
userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dlc.conf')
userConf = _readOptions(userConfFile, None)
if userConf is None: # appdata
appdata_dir = compat_getenv('appdata') appdata_dir = compat_getenv('appdata')
if appdata_dir: if appdata_dir:
userConf = _readOptions( userConfFile = os.path.join(appdata_dir, package_name, 'config')
os.path.join(appdata_dir, 'youtube-dlc', 'config'), userConf = _readOptions(userConfFile, default=None)
default=None) if userConf is None:
if userConf is None: userConf = _readOptions('%s.txt' % userConfFile, default=None)
userConf = _readOptions( if userConf is not None:
os.path.join(appdata_dir, 'youtube-dlc', 'config.txt'), return userConf
default=None)
# home
userConfFile = os.path.join(compat_expanduser('~'), '%s.conf' % package_name)
userConf = _readOptions(userConfFile, default=None)
if userConf is None: if userConf is None:
userConf = _readOptions( userConf = _readOptions('%s.txt' % userConfFile, default=None)
os.path.join(compat_expanduser('~'), 'youtube-dlc.conf'), if userConf is not None:
default=None) return userConf
if userConf is None:
userConf = _readOptions(
os.path.join(compat_expanduser('~'), 'youtube-dlc.conf.txt'),
default=None)
if userConf is None: return default
userConf = []
return userConf
def _format_option_string(option): def _format_option_string(option):
''' ('-o', '--option') -> -o, --format METAVAR''' ''' ('-o', '--option') -> -o, --format METAVAR'''
@@ -144,11 +137,11 @@ def parseOpts(overrideArguments=None):
general.add_option( general.add_option(
'-i', '--ignore-errors', '--no-abort-on-error', '-i', '--ignore-errors', '--no-abort-on-error',
action='store_true', dest='ignoreerrors', default=True, action='store_true', dest='ignoreerrors', default=True,
help='Continue on download errors, for example to skip unavailable videos in a playlist (default)') help='Continue on download errors, for example to skip unavailable videos in a playlist (default) (Alias: --no-abort-on-error)')
general.add_option( general.add_option(
'--abort-on-error', '--no-ignore-errors', '--abort-on-error', '--no-ignore-errors',
action='store_false', dest='ignoreerrors', action='store_false', dest='ignoreerrors',
help='Abort downloading of further videos if an error occurs') help='Abort downloading of further videos if an error occurs (Alias: --no-ignore-errors)')
general.add_option( general.add_option(
'--dump-user-agent', '--dump-user-agent',
action='store_true', dest='dump_user_agent', default=False, action='store_true', dest='dump_user_agent', default=False,
@@ -168,23 +161,23 @@ def parseOpts(overrideArguments=None):
general.add_option( general.add_option(
'--default-search', '--default-search',
dest='default_search', metavar='PREFIX', dest='default_search', metavar='PREFIX',
help='Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for youtube-dl "large apple". Use the value "auto" to let youtube-dl guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching.') help='Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for youtube-dl "large apple". Use the value "auto" to let youtube-dl guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching')
general.add_option( general.add_option(
'--ignore-config', '--no-config', '--ignore-config', '--no-config',
action='store_true', action='store_true',
help=( help=(
'Do not read configuration files. ' 'Disable loading any configuration files except the one provided by --config-location. '
'When given in the global configuration file /etc/youtube-dl.conf: ' 'When given inside a configuration file, no further configuration files are loaded. '
'Do not read the user configuration in ~/.config/youtube-dl/config ' 'Additionally, (for backward compatibility) if this option is found inside the '
'(%APPDATA%/youtube-dl/config.txt on Windows)')) 'system configuration file, the user configuration is not loaded'))
general.add_option( general.add_option(
'--config-location', '--config-location',
dest='config_location', metavar='PATH', dest='config_location', metavar='PATH',
help='Location of the configuration file; either the path to the config or its containing directory.') help='Location of the configuration file; either the path to the config or its containing directory')
general.add_option( general.add_option(
'--flat-playlist', '--flat-playlist',
action='store_const', dest='extract_flat', const='in_playlist', default=False, action='store_const', dest='extract_flat', const='in_playlist', default=False,
help='Do not extract the videos of a playlist, only list them.') help='Do not extract the videos of a playlist, only list them')
general.add_option( general.add_option(
'--flat-videos', '--flat-videos',
action='store_true', dest='extract_flat', action='store_true', dest='extract_flat',
@@ -202,7 +195,7 @@ def parseOpts(overrideArguments=None):
action='store_false', dest='mark_watched', default=False, action='store_false', dest='mark_watched', default=False,
help='Do not mark videos watched') help='Do not mark videos watched')
general.add_option( general.add_option(
'--no-color', '--no-colors', '--no-colors',
action='store_true', dest='no_color', action='store_true', dest='no_color',
default=False, default=False,
help='Do not emit color codes in output') help='Do not emit color codes in output')
@@ -242,7 +235,7 @@ def parseOpts(overrideArguments=None):
dest='geo_verification_proxy', default=None, metavar='URL', dest='geo_verification_proxy', default=None, metavar='URL',
help=( help=(
'Use this proxy to verify the IP address for some geo-restricted sites. ' 'Use this proxy to verify the IP address for some geo-restricted sites. '
'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading.')) 'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading'))
geo.add_option( geo.add_option(
'--cn-verification-proxy', '--cn-verification-proxy',
dest='cn_verification_proxy', default=None, metavar='URL', dest='cn_verification_proxy', default=None, metavar='URL',
@@ -276,7 +269,7 @@ def parseOpts(overrideArguments=None):
selection.add_option( selection.add_option(
'--playlist-items', '--playlist-items',
dest='playlist_items', metavar='ITEM_SPEC', default=None, dest='playlist_items', metavar='ITEM_SPEC', default=None,
help='Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13.') help='Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13')
selection.add_option( selection.add_option(
'--match-title', '--match-title',
dest='matchtitle', metavar='REGEX', dest='matchtitle', metavar='REGEX',
@@ -301,8 +294,8 @@ def parseOpts(overrideArguments=None):
'--date', '--date',
metavar='DATE', dest='date', default=None, metavar='DATE', dest='date', default=None,
help=( help=(
'Download only videos uploaded in this date.' 'Download only videos uploaded in this date. '
'The date can be "YYYYMMDD" or in the format' 'The date can be "YYYYMMDD" or in the format '
'"(now|today)[+-][0-9](day|week|month|year)(s)?"')) '"(now|today)[+-][0-9](day|week|month|year)(s)?"'))
selection.add_option( selection.add_option(
'--datebefore', '--datebefore',
@@ -329,10 +322,10 @@ def parseOpts(overrideArguments=None):
metavar='FILTER', dest='match_filter', default=None, metavar='FILTER', dest='match_filter', default=None,
help=( help=(
'Generic video filter. ' 'Generic video filter. '
'Specify any key (see the "OUTPUT TEMPLATE" for a list of available keys) to ' 'Specify any key (see "OUTPUT TEMPLATE" for a list of available keys) to '
'match if the key is present, ' 'match if the key is present, '
'!key to check if the key is not present, ' '!key to check if the key is not present, '
'key > NUMBER (like "comment_count > 12", also works with ' 'key>NUMBER (like "comment_count > 12", also works with '
'>=, <, <=, !=, =) to compare against a number, ' '>=, <, <=, !=, =) to compare against a number, '
'key = \'LITERAL\' (like "uploader = \'Mike Smith\'", also works with !=) ' 'key = \'LITERAL\' (like "uploader = \'Mike Smith\'", also works with !=) '
'to match against a string literal ' 'to match against a string literal '
@@ -343,7 +336,7 @@ def parseOpts(overrideArguments=None):
'100 times and disliked less than 50 times (or the dislike ' '100 times and disliked less than 50 times (or the dislike '
'functionality is not available at the given service), but who ' 'functionality is not available at the given service), but who '
'also have a description, use --match-filter ' 'also have a description, use --match-filter '
'"like_count > 100 & dislike_count <? 50 & description" .')) '"like_count > 100 & dislike_count <? 50 & description"'))
selection.add_option( selection.add_option(
'--no-match-filter', '--no-match-filter',
metavar='FILTER', dest='match_filter', action='store_const', const=None, metavar='FILTER', dest='match_filter', action='store_const', const=None,
@@ -351,11 +344,11 @@ def parseOpts(overrideArguments=None):
selection.add_option( selection.add_option(
'--no-playlist', '--no-playlist',
action='store_true', dest='noplaylist', default=False, action='store_true', dest='noplaylist', default=False,
help='Download only the video, if the URL refers to a video and a playlist.') help='Download only the video, if the URL refers to a video and a playlist')
selection.add_option( selection.add_option(
'--yes-playlist', '--yes-playlist',
action='store_false', dest='noplaylist', default=False, action='store_false', dest='noplaylist', default=False,
help='Download the playlist, if the URL refers to a video and a playlist.') help='Download the playlist, if the URL refers to a video and a playlist')
selection.add_option( selection.add_option(
'--age-limit', '--age-limit',
metavar='YEARS', dest='age_limit', default=None, type=int, metavar='YEARS', dest='age_limit', default=None, type=int,
@@ -363,11 +356,15 @@ def parseOpts(overrideArguments=None):
selection.add_option( selection.add_option(
'--download-archive', metavar='FILE', '--download-archive', metavar='FILE',
dest='download_archive', dest='download_archive',
help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.') help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it')
selection.add_option( selection.add_option(
'--break-on-existing', '--break-on-existing',
action='store_true', dest='break_on_existing', default=False, action='store_true', dest='break_on_existing', default=False,
help="Stop the download process after attempting to download a file that's in the archive.") help='Stop the download process when encountering a file that is in the archive')
selection.add_option(
'--break-on-reject',
action='store_true', dest='break_on_reject', default=False,
help='Stop the download process when encountering a file that has been filtered out')
selection.add_option( selection.add_option(
'--no-download-archive', '--no-download-archive',
dest='download_archive', action="store_const", const=None, dest='download_archive', action="store_const", const=None,
@@ -389,7 +386,7 @@ def parseOpts(overrideArguments=None):
authentication.add_option( authentication.add_option(
'-p', '--password', '-p', '--password',
dest='password', metavar='PASSWORD', dest='password', metavar='PASSWORD',
help='Account password. If this option is left out, youtube-dlc will ask interactively.') help='Account password. If this option is left out, youtube-dlc will ask interactively')
authentication.add_option( authentication.add_option(
'-2', '--twofactor', '-2', '--twofactor',
dest='twofactor', metavar='TWOFACTOR', dest='twofactor', metavar='TWOFACTOR',
@@ -415,7 +412,7 @@ def parseOpts(overrideArguments=None):
adobe_pass.add_option( adobe_pass.add_option(
'--ap-password', '--ap-password',
dest='ap_password', metavar='PASSWORD', dest='ap_password', metavar='PASSWORD',
help='Multiple-system operator account password. If this option is left out, youtube-dlc will ask interactively.') help='Multiple-system operator account password. If this option is left out, youtube-dlc will ask interactively')
adobe_pass.add_option( adobe_pass.add_option(
'--ap-list-mso', '--ap-list-mso',
action='store_true', dest='ap_list_mso', default=False, action='store_true', dest='ap_list_mso', default=False,
@@ -474,27 +471,27 @@ def parseOpts(overrideArguments=None):
video_format.add_option( video_format.add_option(
'--list-formats-as-table', '--list-formats-as-table',
action='store_true', dest='listformats_table', default=True, action='store_true', dest='listformats_table', default=True,
help='Present the output of -F in a more tabular form (default)') help='Present the output of -F in tabular form (default)')
video_format.add_option( video_format.add_option(
'--list-formats-old', '--no-list-formats-as-table', '--list-formats-old', '--no-list-formats-as-table',
action='store_false', dest='listformats_table', action='store_false', dest='listformats_table',
help='Present the output of -F in the old form') help='Present the output of -F in the old form (Alias: --no-list-formats-as-table)')
video_format.add_option( video_format.add_option(
'--youtube-include-dash-manifest', '--no-youtube-skip-dash-manifest', '--youtube-include-dash-manifest', '--no-youtube-skip-dash-manifest',
action='store_true', dest='youtube_include_dash_manifest', default=True, action='store_true', dest='youtube_include_dash_manifest', default=True,
help='Download the DASH manifests and related data on YouTube videos (default)') help='Download the DASH manifests and related data on YouTube videos (default) (Alias: --no-youtube-skip-dash-manifest)')
video_format.add_option( video_format.add_option(
'--youtube-skip-dash-manifest', '--no-youtube-include-dash-manifest', '--youtube-skip-dash-manifest', '--no-youtube-include-dash-manifest',
action='store_false', dest='youtube_include_dash_manifest', action='store_false', dest='youtube_include_dash_manifest',
help='Do not download the DASH manifests and related data on YouTube videos') help='Do not download the DASH manifests and related data on YouTube videos (Alias: --no-youtube-include-dash-manifest)')
video_format.add_option( video_format.add_option(
'--youtube-include-hls-manifest', '--no-youtube-skip-hls-manifest', '--youtube-include-hls-manifest', '--no-youtube-skip-hls-manifest',
action='store_true', dest='youtube_include_hls_manifest', default=True, action='store_true', dest='youtube_include_hls_manifest', default=True,
help='Download the HLS manifests and related data on YouTube videos (default)') help='Download the HLS manifests and related data on YouTube videos (default) (Alias: --no-youtube-skip-hls-manifest)')
video_format.add_option( video_format.add_option(
'--youtube-skip-hls-manifest', '--no-youtube-include-hls-manifest', '--youtube-skip-hls-manifest', '--no-youtube-include-hls-manifest',
action='store_false', dest='youtube_include_hls_manifest', action='store_false', dest='youtube_include_hls_manifest',
help='Do not download the HLS manifests and related data on YouTube videos') help='Do not download the HLS manifests and related data on YouTube videos (Alias: --no-youtube-include-hls-manifest)')
video_format.add_option( video_format.add_option(
'--merge-output-format', '--merge-output-format',
action='store', dest='merge_output_format', metavar='FORMAT', default=None, action='store', dest='merge_output_format', metavar='FORMAT', default=None,
@@ -546,7 +543,7 @@ def parseOpts(overrideArguments=None):
downloader.add_option( downloader.add_option(
'-R', '--retries', '-R', '--retries',
dest='retries', metavar='RETRIES', default=10, dest='retries', metavar='RETRIES', default=10,
help='Number of retries (default is %default), or "infinite".') help='Number of retries (default is %default), or "infinite"')
downloader.add_option( downloader.add_option(
'--fragment-retries', '--fragment-retries',
dest='fragment_retries', metavar='RETRIES', default=10, dest='fragment_retries', metavar='RETRIES', default=10,
@@ -554,11 +551,11 @@ def parseOpts(overrideArguments=None):
downloader.add_option( downloader.add_option(
'--skip-unavailable-fragments', '--no-abort-on-unavailable-fragment', '--skip-unavailable-fragments', '--no-abort-on-unavailable-fragment',
action='store_true', dest='skip_unavailable_fragments', default=True, action='store_true', dest='skip_unavailable_fragments', default=True,
help='Skip unavailable fragments for DASH, hlsnative and ISM (default)') help='Skip unavailable fragments for DASH, hlsnative and ISM (default) (Alias: --no-abort-on-unavailable-fragment)')
downloader.add_option( downloader.add_option(
'--abort-on-unavailable-fragment', '--no-skip-unavailable-fragments', '--abort-on-unavailable-fragment', '--no-skip-unavailable-fragments',
action='store_false', dest='skip_unavailable_fragments', action='store_false', dest='skip_unavailable_fragments',
help='Abort downloading when some fragment is unavailable') help='Abort downloading if a fragment is unavailable (Alias: --no-skip-unavailable-fragments)')
downloader.add_option( downloader.add_option(
'--keep-fragments', '--keep-fragments',
action='store_true', dest='keep_fragments', default=False, action='store_true', dest='keep_fragments', default=False,
@@ -668,14 +665,14 @@ def parseOpts(overrideArguments=None):
'Number of seconds to sleep before each download when used alone ' 'Number of seconds to sleep before each download when used alone '
'or a lower bound of a range for randomized sleep before each download ' 'or a lower bound of a range for randomized sleep before each download '
'(minimum possible number of seconds to sleep) when used along with ' '(minimum possible number of seconds to sleep) when used along with '
'--max-sleep-interval.')) '--max-sleep-interval'))
workarounds.add_option( workarounds.add_option(
'--max-sleep-interval', metavar='SECONDS', '--max-sleep-interval', metavar='SECONDS',
dest='max_sleep_interval', type=float, dest='max_sleep_interval', type=float,
help=( help=(
'Upper bound of a range for randomized sleep before each download ' 'Upper bound of a range for randomized sleep before each download '
'(maximum possible number of seconds to sleep). Must only be used ' '(maximum possible number of seconds to sleep). Must only be used '
'along with --min-sleep-interval.')) 'along with --min-sleep-interval'))
workarounds.add_option( workarounds.add_option(
'--sleep-subtitles', metavar='SECONDS', '--sleep-subtitles', metavar='SECONDS',
dest='sleep_interval_subtitles', default=0, type=int, dest='sleep_interval_subtitles', default=0, type=int,
@@ -733,23 +730,23 @@ def parseOpts(overrideArguments=None):
verbosity.add_option( verbosity.add_option(
'-j', '--dump-json', '-j', '--dump-json',
action='store_true', dest='dumpjson', default=False, action='store_true', dest='dumpjson', default=False,
help='Simulate, quiet but print JSON information. See the "OUTPUT TEMPLATE" for a description of available keys.') help='Simulate, quiet but print JSON information. See "OUTPUT TEMPLATE" for a description of available keys')
verbosity.add_option( verbosity.add_option(
'-J', '--dump-single-json', '-J', '--dump-single-json',
action='store_true', dest='dump_single_json', default=False, action='store_true', dest='dump_single_json', default=False,
help=( help=(
'Simulate, quiet but print JSON information for each command-line argument. ' 'Simulate, quiet but print JSON information for each command-line argument. '
'If the URL refers to a playlist, dump the whole playlist information in a single line.')) 'If the URL refers to a playlist, dump the whole playlist information in a single line'))
verbosity.add_option( verbosity.add_option(
'--print-json', '--print-json',
action='store_true', dest='print_json', default=False, action='store_true', dest='print_json', default=False,
help='Be quiet and print the video information as JSON (video is still being downloaded).') help='Be quiet and print the video information as JSON (video is still being downloaded)')
verbosity.add_option( verbosity.add_option(
'--force-write-archive', '--force-write-download-archive', '--force-download-archive', '--force-write-archive', '--force-write-download-archive', '--force-download-archive',
action='store_true', dest='force_write_download_archive', default=False, action='store_true', dest='force_write_download_archive', default=False,
help=( help=(
'Force download archive entries to be written as far as no errors occur,' 'Force download archive entries to be written as far as no errors occur,'
'even if -s or another simulation switch is used.')) 'even if -s or another simulation switch is used (Alias: --force-download-archive)'))
verbosity.add_option( verbosity.add_option(
'--newline', '--newline',
action='store_true', dest='progress_with_newline', default=False, action='store_true', dest='progress_with_newline', default=False,
@@ -796,14 +793,14 @@ def parseOpts(overrideArguments=None):
'-a', '--batch-file', '-a', '--batch-file',
dest='batchfile', metavar='FILE', dest='batchfile', metavar='FILE',
help="File containing URLs to download ('-' for stdin), one URL per line. " help="File containing URLs to download ('-' for stdin), one URL per line. "
"Lines starting with '#', ';' or ']' are considered as comments and ignored.") "Lines starting with '#', ';' or ']' are considered as comments and ignored")
filesystem.add_option( filesystem.add_option(
'--id', default=False, '--id', default=False,
action='store_true', dest='useid', help=optparse.SUPPRESS_HELP) action='store_true', dest='useid', help=optparse.SUPPRESS_HELP)
filesystem.add_option( filesystem.add_option(
'-o', '--output', '-o', '--output',
dest='outtmpl', metavar='TEMPLATE', dest='outtmpl', metavar='TEMPLATE',
help='Output filename template, see the "OUTPUT TEMPLATE" for details') help='Output filename template, see "OUTPUT TEMPLATE" for details')
filesystem.add_option( filesystem.add_option(
'--autonumber-size', '--autonumber-size',
dest='autonumber_size', metavar='NUMBER', type=int, dest='autonumber_size', metavar='NUMBER', type=int,
@@ -906,7 +903,7 @@ def parseOpts(overrideArguments=None):
help='Do not read/dump cookies (default)') help='Do not read/dump cookies (default)')
filesystem.add_option( filesystem.add_option(
'--cache-dir', dest='cachedir', default=None, metavar='DIR', '--cache-dir', dest='cachedir', default=None, metavar='DIR',
help='Location in the filesystem where youtube-dl can store some downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl . At the moment, only YouTube player files (for videos with obfuscated signatures) are cached, but that may change.') help='Location in the filesystem where youtube-dl can store some downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl . At the moment, only YouTube player files (for videos with obfuscated signatures) are cached, but that may change')
filesystem.add_option( filesystem.add_option(
'--no-cache-dir', action='store_false', dest='cachedir', '--no-cache-dir', action='store_false', dest='cachedir',
help='Disable filesystem caching') help='Disable filesystem caching')
@@ -941,19 +938,19 @@ def parseOpts(overrideArguments=None):
link.add_option( link.add_option(
'--write-link', '--write-link',
action='store_true', dest='writelink', default=False, action='store_true', dest='writelink', default=False,
help='Write an internet shortcut file, depending on the current platform (.url/.webloc/.desktop). The URL may be cached by the OS.') help='Write an internet shortcut file, depending on the current platform (.url, .webloc or .desktop). The URL may be cached by the OS')
link.add_option( link.add_option(
'--write-url-link', '--write-url-link',
action='store_true', dest='writeurllink', default=False, action='store_true', dest='writeurllink', default=False,
help='Write a Windows internet shortcut file (.url). Note that the OS caches the URL based on the file path.') help='Write a .url Windows internet shortcut. The OS caches the URL based on the file path')
link.add_option( link.add_option(
'--write-webloc-link', '--write-webloc-link',
action='store_true', dest='writewebloclink', default=False, action='store_true', dest='writewebloclink', default=False,
help='Write a macOS internet shortcut file (.webloc)') help='Write a .webloc macOS internet shortcut')
link.add_option( link.add_option(
'--write-desktop-link', '--write-desktop-link',
action='store_true', dest='writedesktoplink', default=False, action='store_true', dest='writedesktoplink', default=False,
help='Write a Linux internet shortcut file (.desktop)') help='Write a .desktop Linux internet shortcut')
postproc = optparse.OptionGroup(parser, 'Post-Processing Options') postproc = optparse.OptionGroup(parser, 'Post-Processing Options')
postproc.add_option( postproc.add_option(
@@ -978,14 +975,18 @@ def parseOpts(overrideArguments=None):
metavar='FORMAT', dest='recodevideo', default=None, metavar='FORMAT', dest='recodevideo', default=None,
help='Re-encode the video into another format if re-encoding is necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)') help='Re-encode the video into another format if re-encoding is necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')
postproc.add_option( postproc.add_option(
'--postprocessor-args', metavar='NAME:ARGS', '--postprocessor-args', '--ppa', metavar='NAME:ARGS',
dest='postprocessor_args', action='append', dest='postprocessor_args', action='append',
help=( help=(
'Give these arguments to the postprocessors. ' 'Give these arguments to the postprocessors. '
"Specify the postprocessor name and the arguments separated by a colon ':' " 'Specify the postprocessor/executable name and the arguments separated by a colon ":" '
'to give the argument to only the specified postprocessor. Supported names are ' 'to give the argument to only the specified postprocessor/executable. Supported postprocessors are: '
'ExtractAudio, VideoRemuxer, VideoConvertor, EmbedSubtitle, Metadata, Merger, FixupStretched, FixupM4a, FixupM3u8, SubtitlesConvertor, SponSkrub and Default' 'SponSkrub, ExtractAudio, VideoRemuxer, VideoConvertor, EmbedSubtitle, Metadata, Merger, '
'. You can use this option multiple times to give different arguments to different postprocessors')) 'FixupStretched, FixupM4a, FixupM3u8, SubtitlesConvertor and EmbedThumbnail. '
'The supported executables are: SponSkrub, FFmpeg, FFprobe, avconf, avprobe and AtomicParsley. '
'You can use this option multiple times to give different arguments to different postprocessors. '
'You can also specify "PP+EXE:ARGS" to give the arguments to the specified executable '
'only when being used by the specified postprocessor (Alias: --ppa)'))
postproc.add_option( postproc.add_option(
'-k', '--keep-video', '-k', '--keep-video',
action='store_true', dest='keepvideo', default=False, action='store_true', dest='keepvideo', default=False,
@@ -1051,15 +1052,15 @@ def parseOpts(overrideArguments=None):
postproc.add_option( postproc.add_option(
'--prefer-avconv', '--no-prefer-ffmpeg', '--prefer-avconv', '--no-prefer-ffmpeg',
action='store_false', dest='prefer_ffmpeg', action='store_false', dest='prefer_ffmpeg',
help='Prefer avconv over ffmpeg for running the postprocessors') help='Prefer avconv over ffmpeg for running the postprocessors (Alias: --no-prefer-ffmpeg)')
postproc.add_option( postproc.add_option(
'--prefer-ffmpeg', '--no-prefer-avconv', '--prefer-ffmpeg', '--no-prefer-avconv',
action='store_true', dest='prefer_ffmpeg', action='store_true', dest='prefer_ffmpeg',
help='Prefer ffmpeg over avconv for running the postprocessors (default)') help='Prefer ffmpeg over avconv for running the postprocessors (default) (Alias: --no-prefer-avconv)')
postproc.add_option( postproc.add_option(
'--ffmpeg-location', '--avconv-location', metavar='PATH', '--ffmpeg-location', '--avconv-location', metavar='PATH',
dest='ffmpeg_location', dest='ffmpeg_location',
help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.') help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory (Alias: --avconv-location)')
postproc.add_option( postproc.add_option(
'--exec', '--exec',
metavar='CMD', dest='exec_cmd', metavar='CMD', dest='exec_cmd',
@@ -1069,12 +1070,14 @@ def parseOpts(overrideArguments=None):
metavar='FORMAT', dest='convertsubtitles', default=None, metavar='FORMAT', dest='convertsubtitles', default=None,
help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)') help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)')
sponskrub = optparse.OptionGroup(parser, 'SponSkrub Options (SponsorBlock)') sponskrub = optparse.OptionGroup(parser, 'SponSkrub (SponsorBlock) Options', description=(
'SponSkrub (https://github.com/pukkandan/SponSkrub) is a utility to mark/remove sponsor segments '
'from downloaded YouTube videos using SponsorBlock API (https://sponsor.ajay.app)'))
sponskrub.add_option( sponskrub.add_option(
'--sponskrub', '--sponskrub',
action='store_true', dest='sponskrub', default=None, action='store_true', dest='sponskrub', default=None,
help=( help=(
'Use sponskrub to mark sponsored sections with the data available in SponsorBlock API. ' 'Use sponskrub to mark sponsored sections. '
'This is enabled by default if the sponskrub binary exists (Youtube only)')) 'This is enabled by default if the sponskrub binary exists (Youtube only)'))
sponskrub.add_option( sponskrub.add_option(
'--no-sponskrub', '--no-sponskrub',
@@ -1099,7 +1102,7 @@ def parseOpts(overrideArguments=None):
sponskrub.add_option( sponskrub.add_option(
'--sponskrub-location', metavar='PATH', '--sponskrub-location', metavar='PATH',
dest='sponskrub_path', default='', dest='sponskrub_path', default='',
help='Location of the sponskrub binary; either the path to the binary or its containing directory.') help='Location of the sponskrub binary; either the path to the binary or its containing directory')
sponskrub.add_option( sponskrub.add_option(
'--sponskrub-args', dest='sponskrub_args', metavar='ARGS', '--sponskrub-args', dest='sponskrub_args', metavar='ARGS',
help=optparse.SUPPRESS_HELP) help=optparse.SUPPRESS_HELP)
@@ -1108,11 +1111,11 @@ def parseOpts(overrideArguments=None):
extractor.add_option( extractor.add_option(
'--allow-dynamic-mpd', '--no-ignore-dynamic-mpd', '--allow-dynamic-mpd', '--no-ignore-dynamic-mpd',
action='store_true', dest='dynamic_mpd', default=True, action='store_true', dest='dynamic_mpd', default=True,
help='Process dynamic DASH manifests (default)') help='Process dynamic DASH manifests (default) (Alias: --no-ignore-dynamic-mpd)')
extractor.add_option( extractor.add_option(
'--ignore-dynamic-mpd', '--no-allow-dynamic-mpd', '--ignore-dynamic-mpd', '--no-allow-dynamic-mpd',
action='store_false', dest='dynamic_mpd', action='store_false', dest='dynamic_mpd',
help='Do not process dynamic DASH manifests') help='Do not process dynamic DASH manifests (Alias: --no-allow-dynamic-mpd)')
parser.add_option_group(general) parser.add_option_group(general)
parser.add_option_group(network) parser.add_option_group(network)
@@ -1142,33 +1145,60 @@ def parseOpts(overrideArguments=None):
return [a.decode(preferredencoding(), 'replace') for a in conf] return [a.decode(preferredencoding(), 'replace') for a in conf]
return conf return conf
command_line_conf = compat_conf(sys.argv[1:]) configs = {
opts, args = parser.parse_args(command_line_conf) 'command_line': compat_conf(sys.argv[1:]),
'custom': [], 'portable': [], 'user': [], 'system': []}
opts, args = parser.parse_args(configs['command_line'])
system_conf = user_conf = custom_conf = [] def get_configs():
if '--config-location' in configs['command_line']:
location = compat_expanduser(opts.config_location)
if os.path.isdir(location):
location = os.path.join(location, 'youtube-dlc.conf')
if not os.path.exists(location):
parser.error('config-location %s does not exist.' % location)
configs['custom'] = _readOptions(location)
if '--config-location' in command_line_conf: if '--ignore-config' in configs['command_line']:
location = compat_expanduser(opts.config_location) return
if os.path.isdir(location): if '--ignore-config' in configs['custom']:
location = os.path.join(location, 'youtube-dlc.conf') return
if not os.path.exists(location):
parser.error('config-location %s does not exist.' % location)
custom_conf = _readOptions(location)
elif '--ignore-config' in command_line_conf:
pass
else:
system_conf = _readOptions('/etc/youtube-dlc.conf')
if '--ignore-config' not in system_conf:
user_conf = _readUserConf()
argv = system_conf + user_conf + custom_conf + command_line_conf def get_portable_path():
path = os.path.dirname(sys.argv[0])
if os.path.abspath(sys.argv[0]) != os.path.abspath(sys.executable): # Not packaged
path = os.path.join(path, '..')
return os.path.abspath(path)
run_path = get_portable_path()
configs['portable'] = _readOptions(os.path.join(run_path, 'yt-dlp.conf'), default=None)
if configs['portable'] is None:
configs['portable'] = _readOptions(os.path.join(run_path, 'youtube-dlc.conf'))
if '--ignore-config' in configs['portable']:
return
configs['system'] = _readOptions('/etc/yt-dlp.conf', default=None)
if configs['system'] is None:
configs['system'] = _readOptions('/etc/youtube-dlc.conf')
if '--ignore-config' in configs['system']:
return
configs['user'] = _readUserConf('yt-dlp', default=None)
if configs['user'] is None:
configs['user'] = _readUserConf('youtube-dlc')
if '--ignore-config' in configs['user']:
configs['system'] = []
get_configs()
argv = configs['system'] + configs['user'] + configs['portable'] + configs['custom'] + configs['command_line']
opts, args = parser.parse_args(argv) opts, args = parser.parse_args(argv)
if opts.verbose: if opts.verbose:
for conf_label, conf in ( for conf_label, conf in (
('System config', system_conf), ('System config', configs['system']),
('User config', user_conf), ('User config', configs['user']),
('Custom config', custom_conf), ('Portable config', configs['portable']),
('Command-line args', command_line_conf)): ('Custom config', configs['custom']),
('Command-line args', configs['command_line'])):
write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf)))) write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf))))
return parser, opts, args return parser, opts, args
+46 -11
View File
@@ -2,9 +2,9 @@ from __future__ import unicode_literals
import os import os
from ..compat import compat_str
from ..utils import ( from ..utils import (
PostProcessingError, PostProcessingError,
cli_configuration_args,
encodeFilename, encodeFilename,
) )
@@ -33,12 +33,17 @@ class PostProcessor(object):
def __init__(self, downloader=None): def __init__(self, downloader=None):
self._downloader = downloader self._downloader = downloader
if not hasattr(self, 'PP_NAME'): self.PP_NAME = self.pp_key()
self.PP_NAME = self.__class__.__name__[:-2]
def to_screen(self, text, *args, **kwargs): @classmethod
def pp_key(cls):
name = cls.__name__[:-2]
return compat_str(name[6:]) if name[:6].lower() == 'ffmpeg' else name
def to_screen(self, text, prefix=True, *args, **kwargs):
tag = '[%s] ' % self.PP_NAME if prefix else ''
if self._downloader: if self._downloader:
return self._downloader.to_screen('[%s] %s' % (self.PP_NAME, text), *args, **kwargs) return self._downloader.to_screen('%s%s' % (tag, text), *args, **kwargs)
def report_warning(self, text, *args, **kwargs): def report_warning(self, text, *args, **kwargs):
if self._downloader: if self._downloader:
@@ -48,9 +53,10 @@ class PostProcessor(object):
if self._downloader: if self._downloader:
return self._downloader.report_error(text, *args, **kwargs) return self._downloader.report_error(text, *args, **kwargs)
def write_debug(self, text, *args, **kwargs): def write_debug(self, text, prefix=True, *args, **kwargs):
tag = '[debug] ' if prefix else ''
if self.get_param('verbose', False): if self.get_param('verbose', False):
return self._downloader.to_screen('[debug] %s' % text, *args, **kwargs) return self._downloader.to_screen('%s%s' % (tag, text), *args, **kwargs)
def get_param(self, name, default=None, *args, **kwargs): def get_param(self, name, default=None, *args, **kwargs):
if self._downloader: if self._downloader:
@@ -84,11 +90,40 @@ class PostProcessor(object):
except Exception: except Exception:
self.report_warning(errnote) self.report_warning(errnote)
def _configuration_args(self, default=[]): def _configuration_args(self, default=[], exe=None):
args = self.get_param('postprocessor_args', {}) args = self.get_param('postprocessor_args', {})
if isinstance(args, list): # for backward compatibility pp_key = self.pp_key().lower()
args = {'default': args, 'sponskrub': []}
return cli_configuration_args(args, self.PP_NAME.lower(), args.get('default', [])) if isinstance(args, (list, tuple)): # for backward compatibility
return default if pp_key == 'sponskrub' else args
if args is None:
return default
assert isinstance(args, dict)
exe_args = None
if exe is not None:
assert isinstance(exe, compat_str)
exe = exe.lower()
specific_args = args.get('%s+%s' % (pp_key, exe))
if specific_args is not None:
assert isinstance(specific_args, (list, tuple))
return specific_args
exe_args = args.get(exe)
pp_args = args.get(pp_key) if pp_key != exe else None
if pp_args is None and exe_args is None:
default = args.get('default', default)
assert isinstance(default, (list, tuple))
return default
if pp_args is None:
pp_args = []
elif exe_args is None:
exe_args = []
assert isinstance(pp_args, (list, tuple))
assert isinstance(exe_args, (list, tuple))
return pp_args + exe_args
class AudioConversionError(PostProcessingError): class AudioConversionError(PostProcessingError):
+13 -32
View File
@@ -24,7 +24,6 @@ class EmbedThumbnailPPError(PostProcessingError):
class EmbedThumbnailPP(FFmpegPostProcessor): class EmbedThumbnailPP(FFmpegPostProcessor):
PP_NAME = 'EmbedThumbnail'
def __init__(self, downloader=None, already_have_thumbnail=False): def __init__(self, downloader=None, already_have_thumbnail=False):
super(EmbedThumbnailPP, self).__init__(downloader) super(EmbedThumbnailPP, self).__init__(downloader)
@@ -75,42 +74,23 @@ class EmbedThumbnailPP(FFmpegPostProcessor):
os.rename(encodeFilename(escaped_thumbnail_jpg_filename), encodeFilename(thumbnail_jpg_filename)) os.rename(encodeFilename(escaped_thumbnail_jpg_filename), encodeFilename(thumbnail_jpg_filename))
thumbnail_filename = thumbnail_jpg_filename thumbnail_filename = thumbnail_jpg_filename
success = True
if info['ext'] == 'mp3': if info['ext'] == 'mp3':
options = [ options = [
'-c', 'copy', '-map', '0:0', '-map', '1:0', '-id3v2_version', '3', '-c', 'copy', '-map', '0:0', '-map', '1:0', '-id3v2_version', '3',
'-metadata:s:v', 'title="Album cover"', '-metadata:s:v', 'comment="Cover (front)"'] '-metadata:s:v', 'title="Album cover"', '-metadata:s:v', 'comment="Cover (front)"']
self.to_screen('Adding thumbnail to "%s"' % filename) self.to_screen('Adding thumbnail to "%s"' % filename)
self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options) self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)
if not self._already_have_thumbnail:
os.remove(encodeFilename(thumbnail_filename))
os.remove(encodeFilename(filename))
os.rename(encodeFilename(temp_filename), encodeFilename(filename))
elif info['ext'] == 'mkv': elif info['ext'] == 'mkv':
old_thumbnail_filename = thumbnail_filename
thumbnail_filename = os.path.join(os.path.dirname(old_thumbnail_filename), 'cover.jpg')
if os.path.exists(thumbnail_filename):
os.remove(encodeFilename(thumbnail_filename))
os.rename(encodeFilename(old_thumbnail_filename), encodeFilename(thumbnail_filename))
options = [ options = [
'-c', 'copy', '-map', '0', '-dn', '-c', 'copy', '-map', '0', '-dn', '-attach', thumbnail_filename,
'-attach', thumbnail_filename, '-metadata:s:t', 'mimetype=image/jpeg'] '-metadata:s:t', 'mimetype=image/jpeg', '-metadata:s:t', 'filename=cover.jpg']
self.to_screen('Adding thumbnail to "%s"' % filename) self.to_screen('Adding thumbnail to "%s"' % filename)
self.run_ffmpeg_multiple_files([filename], temp_filename, options) self.run_ffmpeg_multiple_files([filename], temp_filename, options)
if not self._already_have_thumbnail:
os.remove(encodeFilename(thumbnail_filename))
else:
os.rename(encodeFilename(thumbnail_filename), encodeFilename(old_thumbnail_filename))
os.remove(encodeFilename(filename))
os.rename(encodeFilename(temp_filename), encodeFilename(filename))
elif info['ext'] in ['m4a', 'mp4']: elif info['ext'] in ['m4a', 'mp4']:
if not check_executable('AtomicParsley', ['-v']): if not check_executable('AtomicParsley', ['-v']):
raise EmbedThumbnailPPError('AtomicParsley was not found. Please install.') raise EmbedThumbnailPPError('AtomicParsley was not found. Please install.')
@@ -121,10 +101,10 @@ class EmbedThumbnailPP(FFmpegPostProcessor):
encodeFilename(thumbnail_filename, True), encodeFilename(thumbnail_filename, True),
encodeArgument('-o'), encodeArgument('-o'),
encodeFilename(temp_filename, True)] encodeFilename(temp_filename, True)]
cmd += [encodeArgument(o) for o in self._configuration_args(exe='AtomicParsley')]
self.to_screen('Adding thumbnail to "%s"' % filename) self.to_screen('Adding thumbnail to "%s"' % filename)
self.write_debug('AtomicParsley command line: %s' % shell_quote(cmd))
self.verbose_message('AtomicParsley command line: %s' % shell_quote(cmd))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process_communicate_or_kill(p) stdout, stderr = process_communicate_or_kill(p)
@@ -132,17 +112,18 @@ class EmbedThumbnailPP(FFmpegPostProcessor):
if p.returncode != 0: if p.returncode != 0:
msg = stderr.decode('utf-8', 'replace').strip() msg = stderr.decode('utf-8', 'replace').strip()
raise EmbedThumbnailPPError(msg) raise EmbedThumbnailPPError(msg)
if not self._already_have_thumbnail:
os.remove(encodeFilename(thumbnail_filename))
# for formats that don't support thumbnails (like 3gp) AtomicParsley # for formats that don't support thumbnails (like 3gp) AtomicParsley
# won't create to the temporary file # won't create to the temporary file
if b'No changes' in stdout: if b'No changes' in stdout:
self.report_warning('The file format doesn\'t support embedding a thumbnail') self.report_warning('The file format doesn\'t support embedding a thumbnail')
else: success = False
os.remove(encodeFilename(filename))
os.rename(encodeFilename(temp_filename), encodeFilename(filename))
else: else:
raise EmbedThumbnailPPError('Only mp3, mkv, m4a and mp4 are supported for thumbnail embedding for now.') raise EmbedThumbnailPPError('Only mp3, mkv, m4a and mp4 are supported for thumbnail embedding for now.')
return [], info if success:
os.remove(encodeFilename(filename))
os.rename(encodeFilename(temp_filename), encodeFilename(filename))
files_to_delete = [] if self._already_have_thumbnail else [thumbnail_filename]
return files_to_delete, info
@@ -11,12 +11,15 @@ from ..utils import (
class ExecAfterDownloadPP(PostProcessor): class ExecAfterDownloadPP(PostProcessor):
PP_NAME = 'Exec'
def __init__(self, downloader, exec_cmd): def __init__(self, downloader, exec_cmd):
super(ExecAfterDownloadPP, self).__init__(downloader) super(ExecAfterDownloadPP, self).__init__(downloader)
self.exec_cmd = exec_cmd self.exec_cmd = exec_cmd
@classmethod
def pp_key(cls):
return 'Exec'
def run(self, information): def run(self, information):
cmd = self.exec_cmd cmd = self.exec_cmd
if '{}' not in cmd: if '{}' not in cmd:
+1 -3
View File
@@ -54,8 +54,6 @@ class FFmpegPostProcessorError(PostProcessingError):
class FFmpegPostProcessor(PostProcessor): class FFmpegPostProcessor(PostProcessor):
def __init__(self, downloader=None): def __init__(self, downloader=None):
if not hasattr(self, 'PP_NAME'):
self.PP_NAME = self.__class__.__name__[6:-2] # Remove ffmpeg from the front
PostProcessor.__init__(self, downloader) PostProcessor.__init__(self, downloader)
self._determine_executables() self._determine_executables()
@@ -209,7 +207,7 @@ class FFmpegPostProcessor(PostProcessor):
oldest_mtime = min( oldest_mtime = min(
os.stat(encodeFilename(path)).st_mtime for path in input_paths) os.stat(encodeFilename(path)).st_mtime for path in input_paths)
opts += self._configuration_args() opts += self._configuration_args(exe=self.basename)
files_cmd = [] files_cmd = []
for path in input_paths: for path in input_paths:
+17 -13
View File
@@ -7,22 +7,23 @@ from ..compat import compat_shlex_split
from ..utils import ( from ..utils import (
check_executable, check_executable,
encodeArgument, encodeArgument,
encodeFilename,
shell_quote, shell_quote,
str_or_none,
PostProcessingError, PostProcessingError,
prepend_extension,
) )
class SponSkrubPP(PostProcessor): class SponSkrubPP(PostProcessor):
_temp_ext = 'spons' _temp_ext = 'spons'
_def_args = []
_exe_name = 'sponskrub' _exe_name = 'sponskrub'
def __init__(self, downloader, path='', args=None, ignoreerror=False, cut=False, force=False): def __init__(self, downloader, path='', args=None, ignoreerror=False, cut=False, force=False):
PostProcessor.__init__(self, downloader) PostProcessor.__init__(self, downloader)
self.force = force self.force = force
self.cutout = cut self.cutout = cut
self.args = ['-chapter'] if not cut else [] self.args = str_or_none(args) or '' # For backward compatibility
self.args += self._configuration_args(self._def_args) if args is None else compat_shlex_split(args)
self.path = self.get_exe(path) self.path = self.get_exe(path)
if not ignoreerror and self.path is None: if not ignoreerror and self.path is None:
@@ -58,13 +59,15 @@ class SponSkrubPP(PostProcessor):
self.report_warning('If sponskrub is run multiple times, unintended parts of the video could be cut out.') self.report_warning('If sponskrub is run multiple times, unintended parts of the video could be cut out.')
filename = information['filepath'] filename = information['filepath']
temp_filename = filename + '.' + self._temp_ext + os.path.splitext(filename)[1] temp_filename = prepend_extension(filename, self._temp_ext)
if os.path.exists(temp_filename): if os.path.exists(encodeFilename(temp_filename)):
os.remove(temp_filename) os.remove(encodeFilename(temp_filename))
cmd = [self.path] cmd = [self.path]
if self.args: if not self.cutout:
cmd += self.args cmd += ['-chapter']
cmd += compat_shlex_split(self.args) # For backward compatibility
cmd += self._configuration_args(exe=self._exe_name)
cmd += ['--', information['id'], filename, temp_filename] cmd += ['--', information['id'], filename, temp_filename]
cmd = [encodeArgument(i) for i in cmd] cmd = [encodeArgument(i) for i in cmd]
@@ -73,13 +76,14 @@ class SponSkrubPP(PostProcessor):
stdout, stderr = p.communicate() stdout, stderr = p.communicate()
if p.returncode == 0: if p.returncode == 0:
os.remove(filename) os.remove(encodeFilename(filename))
os.rename(temp_filename, filename) os.rename(encodeFilename(temp_filename), encodeFilename(filename))
self.to_screen('Sponsor sections have been %s' % ('removed' if self.cutout else 'marked')) self.to_screen('Sponsor sections have been %s' % ('removed' if self.cutout else 'marked'))
elif p.returncode == 3: elif p.returncode == 3:
self.to_screen('No segments in the SponsorBlock database') self.to_screen('No segments in the SponsorBlock database')
else: else:
stderr = stderr.decode('utf-8', 'replace') msg = stderr.decode('utf-8', 'replace').strip() or stdout.decode('utf-8', 'replace').strip()
msg = stderr.strip().split('\n')[-1] self.write_debug(msg, prefix=False)
raise PostProcessingError(msg if msg else 'sponskrub failed with error code %s!' % p.returncode) msg = msg.split('\n')[-1]
raise PostProcessingError(msg if msg else 'sponskrub failed with error code %s' % p.returncode)
return [], information return [], information
+1 -1
View File
@@ -32,7 +32,7 @@ def rsa_verify(message, signature, key):
def update_self(to_screen, verbose, opener): def update_self(to_screen, verbose, opener):
"""Update the program file with the latest version from the repository""" """Update the program file with the latest version from the repository"""
return to_screen('Update is currently broken.\nVisit https://github.com/pukkandan/yt-dlc/releases/latest to get the latest version') return to_screen('Update is currently broken.\nVisit https://github.com/pukkandan/yt-dlp/releases/latest to get the latest version')
UPDATE_URL = 'https://blackjack4494.github.io//update/' UPDATE_URL = 'https://blackjack4494.github.io//update/'
VERSION_URL = UPDATE_URL + 'LATEST_VERSION' VERSION_URL = UPDATE_URL + 'LATEST_VERSION'
+17 -3
View File
@@ -2332,8 +2332,8 @@ def bug_reports_message():
if ytdl_is_updateable(): if ytdl_is_updateable():
update_cmd = 'type youtube-dlc -U to update' update_cmd = 'type youtube-dlc -U to update'
else: else:
update_cmd = 'see https://github.com/pukkandan/yt-dlc on how to update' update_cmd = 'see https://github.com/pukkandan/yt-dlp on how to update'
msg = '; please report this issue on https://github.com/pukkandan/yt-dlc .' msg = '; please report this issue on https://github.com/pukkandan/yt-dlp .'
msg += ' Make sure you are using the latest version; %s.' % update_cmd msg += ' Make sure you are using the latest version; %s.' % update_cmd
msg += ' Be sure to call youtube-dlc with the --verbose flag and include its complete output.' msg += ' Be sure to call youtube-dlc with the --verbose flag and include its complete output.'
return msg return msg
@@ -2433,6 +2433,16 @@ class PostProcessingError(YoutubeDLError):
self.msg = msg self.msg = msg
class ExistingVideoReached(YoutubeDLError):
""" --max-downloads limit has been reached. """
pass
class RejectedVideoReached(YoutubeDLError):
""" --max-downloads limit has been reached. """
pass
class MaxDownloadsReached(YoutubeDLError): class MaxDownloadsReached(YoutubeDLError):
""" --max-downloads limit has been reached. """ """ --max-downloads limit has been reached. """
pass pass
@@ -4089,7 +4099,8 @@ def strip_jsonp(code):
r'\g<callback_data>', code) r'\g<callback_data>', code)
def js_to_json(code): def js_to_json(code, vars={}):
# vars is a dict of var, val pairs to substitute
COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*' COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*'
SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE) SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
INTEGER_TABLE = ( INTEGER_TABLE = (
@@ -4118,6 +4129,9 @@ def js_to_json(code):
i = int(im.group(1), base) i = int(im.group(1), base)
return '"%d":' % i if v.endswith(':') else '%d' % i return '"%d":' % i if v.endswith(':') else '%d' % i
if v in vars:
return vars[v]
return '"%s"' % v return '"%s"' % v
return re.sub(r'''(?sx) return re.sub(r'''(?sx)
+1 -1
View File
@@ -1,3 +1,3 @@
from __future__ import unicode_literals from __future__ import unicode_literals
__version__ = '2021.01.10' __version__ = '2021.01.16'