mirror of
https://github.com/ytdl-org/youtube-dl
synced 2025-10-24 00:58:37 +09:00
Compare commits
1 Commits
2014.05.16
...
rtmp_test
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00b350d209 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -23,8 +23,6 @@ updates_key.pem
|
|||||||
*.vtt
|
*.vtt
|
||||||
*.flv
|
*.flv
|
||||||
*.mp4
|
*.mp4
|
||||||
*.m4a
|
|
||||||
*.m4v
|
|
||||||
*.part
|
*.part
|
||||||
test/testdata
|
test/testdata
|
||||||
.tox
|
.tox
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ python:
|
|||||||
- "2.6"
|
- "2.6"
|
||||||
- "2.7"
|
- "2.7"
|
||||||
- "3.3"
|
- "3.3"
|
||||||
- "3.4"
|
before_install:
|
||||||
|
- sudo apt-get update -qq
|
||||||
|
- sudo apt-get install -qq rtmpdump
|
||||||
script: nosetests test --verbose
|
script: nosetests test --verbose
|
||||||
notifications:
|
notifications:
|
||||||
email:
|
email:
|
||||||
|
|||||||
@@ -3,4 +3,3 @@ include test/*.py
|
|||||||
include test/*.json
|
include test/*.json
|
||||||
include youtube-dl.bash-completion
|
include youtube-dl.bash-completion
|
||||||
include youtube-dl.1
|
include youtube-dl.1
|
||||||
recursive-include docs Makefile conf.py *.rst
|
|
||||||
|
|||||||
9
Makefile
9
Makefile
@@ -1,7 +1,7 @@
|
|||||||
all: youtube-dl README.md README.txt youtube-dl.1 youtube-dl.bash-completion
|
all: youtube-dl README.md README.txt youtube-dl.1 youtube-dl.bash-completion
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf youtube-dl.1.temp.md youtube-dl.1 youtube-dl.bash-completion README.txt MANIFEST build/ dist/ .coverage cover/ youtube-dl.tar.gz
|
rm -rf youtube-dl.1 youtube-dl.bash-completion README.txt MANIFEST build/ dist/ .coverage cover/ youtube-dl.tar.gz
|
||||||
|
|
||||||
cleanall: clean
|
cleanall: clean
|
||||||
rm -f youtube-dl youtube-dl.exe
|
rm -f youtube-dl youtube-dl.exe
|
||||||
@@ -55,9 +55,7 @@ README.txt: README.md
|
|||||||
pandoc -f markdown -t plain README.md -o README.txt
|
pandoc -f markdown -t plain README.md -o README.txt
|
||||||
|
|
||||||
youtube-dl.1: README.md
|
youtube-dl.1: README.md
|
||||||
python devscripts/prepare_manpage.py >youtube-dl.1.temp.md
|
pandoc -s -f markdown -t man README.md -o youtube-dl.1
|
||||||
pandoc -s -f markdown -t man youtube-dl.1.temp.md -o youtube-dl.1
|
|
||||||
rm -f youtube-dl.1.temp.md
|
|
||||||
|
|
||||||
youtube-dl.bash-completion: youtube_dl/*.py youtube_dl/*/*.py devscripts/bash-completion.in
|
youtube-dl.bash-completion: youtube_dl/*.py youtube_dl/*/*.py devscripts/bash-completion.in
|
||||||
python devscripts/bash-completion.py
|
python devscripts/bash-completion.py
|
||||||
@@ -74,9 +72,8 @@ youtube-dl.tar.gz: youtube-dl README.md README.txt youtube-dl.1 youtube-dl.bash-
|
|||||||
--exclude '__pycache' \
|
--exclude '__pycache' \
|
||||||
--exclude '.git' \
|
--exclude '.git' \
|
||||||
--exclude 'testdata' \
|
--exclude 'testdata' \
|
||||||
--exclude 'docs/_build' \
|
|
||||||
-- \
|
-- \
|
||||||
bin devscripts test youtube_dl docs \
|
bin devscripts test youtube_dl \
|
||||||
CHANGELOG LICENSE README.md README.txt \
|
CHANGELOG LICENSE README.md README.txt \
|
||||||
Makefile MANIFEST.in youtube-dl.1 youtube-dl.bash-completion setup.py \
|
Makefile MANIFEST.in youtube-dl.1 youtube-dl.bash-completion setup.py \
|
||||||
youtube-dl
|
youtube-dl
|
||||||
|
|||||||
567
README.md
567
README.md
@@ -1,24 +1,11 @@
|
|||||||
|
% YOUTUBE-DL(1)
|
||||||
|
|
||||||
|
# NAME
|
||||||
youtube-dl - download videos from youtube.com or other video platforms
|
youtube-dl - download videos from youtube.com or other video platforms
|
||||||
|
|
||||||
# SYNOPSIS
|
# SYNOPSIS
|
||||||
**youtube-dl** [OPTIONS] URL [URL...]
|
**youtube-dl** [OPTIONS] URL [URL...]
|
||||||
|
|
||||||
# INSTALLATION
|
|
||||||
|
|
||||||
To install it right away for all UNIX users (Linux, OS X, etc.), type:
|
|
||||||
|
|
||||||
sudo curl https://yt-dl.org/latest/youtube-dl -o /usr/local/bin/youtube-dl
|
|
||||||
sudo chmod a+x /usr/local/bin/youtube-dl
|
|
||||||
|
|
||||||
If you do not have curl, you can alternatively use a recent wget:
|
|
||||||
|
|
||||||
sudo wget https://yt-dl.org/downloads/2014.05.13/youtube-dl -O /usr/local/bin/youtube-dl
|
|
||||||
sudo chmod a+x /usr/local/bin/youtube-dl
|
|
||||||
|
|
||||||
Windows users can [download a .exe file](https://yt-dl.org/latest/youtube-dl.exe) and place it in their home directory or any other location on their [PATH](http://en.wikipedia.org/wiki/PATH_%28variable%29).
|
|
||||||
|
|
||||||
Alternatively, refer to the developer instructions below for how to check out and work with the git repository. For further options, including PGP signatures, see https://rg3.github.io/youtube-dl/download.html .
|
|
||||||
|
|
||||||
# DESCRIPTION
|
# DESCRIPTION
|
||||||
**youtube-dl** is a small command-line program to download videos from
|
**youtube-dl** is a small command-line program to download videos from
|
||||||
YouTube.com and a few more sites. It requires the Python interpreter, version
|
YouTube.com and a few more sites. It requires the Python interpreter, version
|
||||||
@@ -27,254 +14,175 @@ your Unix box, on Windows or on Mac OS X. It is released to the public domain,
|
|||||||
which means you can modify it, redistribute it or use it however you like.
|
which means you can modify it, redistribute it or use it however you like.
|
||||||
|
|
||||||
# OPTIONS
|
# OPTIONS
|
||||||
-h, --help print this help text and exit
|
-h, --help print this help text and exit
|
||||||
--version print program version and exit
|
--version print program version and exit
|
||||||
-U, --update update this program to latest version. Make
|
-U, --update update this program to latest version. Make sure
|
||||||
sure that you have sufficient permissions
|
that you have sufficient permissions (run with
|
||||||
(run with sudo if needed)
|
sudo if needed)
|
||||||
-i, --ignore-errors continue on download errors, for example to
|
-i, --ignore-errors continue on download errors, for example to to
|
||||||
skip unavailable videos in a playlist
|
skip unavailable videos in a playlist
|
||||||
--abort-on-error Abort downloading of further videos (in the
|
--abort-on-error Abort downloading of further videos (in the
|
||||||
playlist or the command line) if an error
|
playlist or the command line) if an error occurs
|
||||||
occurs
|
--dump-user-agent display the current browser identification
|
||||||
--dump-user-agent display the current browser identification
|
--user-agent UA specify a custom user agent
|
||||||
--user-agent UA specify a custom user agent
|
--referer REF specify a custom referer, use if the video access
|
||||||
--referer REF specify a custom referer, use if the video
|
is restricted to one domain
|
||||||
access is restricted to one domain
|
--list-extractors List all supported extractors and the URLs they
|
||||||
--add-header FIELD:VALUE specify a custom HTTP header and its value,
|
would handle
|
||||||
separated by a colon ':'. You can use this
|
--extractor-descriptions Output descriptions of all supported extractors
|
||||||
option multiple times
|
--proxy URL Use the specified HTTP/HTTPS proxy
|
||||||
--list-extractors List all supported extractors and the URLs
|
--no-check-certificate Suppress HTTPS certificate validation.
|
||||||
they would handle
|
--cache-dir DIR Location in the filesystem where youtube-dl can
|
||||||
--extractor-descriptions Output descriptions of all supported
|
store downloaded information permanently. By
|
||||||
extractors
|
default $XDG_CACHE_HOME/youtube-dl or ~/.cache
|
||||||
--proxy URL Use the specified HTTP/HTTPS proxy. Pass in
|
/youtube-dl .
|
||||||
an empty string (--proxy "") for direct
|
--no-cache-dir Disable filesystem caching
|
||||||
connection
|
|
||||||
--no-check-certificate Suppress HTTPS certificate validation.
|
|
||||||
--prefer-insecure Use an unencrypted connection to retrieve
|
|
||||||
information about the video. (Currently
|
|
||||||
supported only for YouTube)
|
|
||||||
--cache-dir DIR 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.
|
|
||||||
--no-cache-dir Disable filesystem caching
|
|
||||||
--socket-timeout None Time to wait before giving up, in seconds
|
|
||||||
--bidi-workaround Work around terminals that lack
|
|
||||||
bidirectional text support. Requires bidiv
|
|
||||||
or fribidi executable in PATH
|
|
||||||
--default-search PREFIX Use this prefix for unqualified URLs. For
|
|
||||||
example "gvsearch2:" downloads two videos
|
|
||||||
from google videos for youtube-dl "large
|
|
||||||
apple". By default (with value "auto")
|
|
||||||
youtube-dl guesses.
|
|
||||||
--ignore-config Do not read configuration files. When given
|
|
||||||
in the global configuration file /etc
|
|
||||||
/youtube-dl.conf: do not read the user
|
|
||||||
configuration in ~/.config/youtube-dl.conf
|
|
||||||
(%APPDATA%/youtube-dl/config.txt on
|
|
||||||
Windows)
|
|
||||||
--encoding ENCODING Force the specified encoding (experimental)
|
|
||||||
|
|
||||||
## Video Selection:
|
## Video Selection:
|
||||||
--playlist-start NUMBER playlist video to start at (default is 1)
|
--playlist-start NUMBER playlist video to start at (default is 1)
|
||||||
--playlist-end NUMBER playlist video to end at (default is last)
|
--playlist-end NUMBER playlist video to end at (default is last)
|
||||||
--match-title REGEX download only matching titles (regex or
|
--match-title REGEX download only matching titles (regex or caseless
|
||||||
caseless sub-string)
|
sub-string)
|
||||||
--reject-title REGEX skip download for matching titles (regex or
|
--reject-title REGEX skip download for matching titles (regex or
|
||||||
caseless sub-string)
|
caseless sub-string)
|
||||||
--max-downloads NUMBER Abort after downloading NUMBER files
|
--max-downloads NUMBER Abort after downloading NUMBER files
|
||||||
--min-filesize SIZE Do not download any videos smaller than
|
--min-filesize SIZE Do not download any videos smaller than SIZE
|
||||||
SIZE (e.g. 50k or 44.6m)
|
(e.g. 50k or 44.6m)
|
||||||
--max-filesize SIZE Do not download any videos larger than SIZE
|
--max-filesize SIZE Do not download any videos larger than SIZE (e.g.
|
||||||
(e.g. 50k or 44.6m)
|
50k or 44.6m)
|
||||||
--date DATE download only videos uploaded in this date
|
--date DATE download only videos uploaded in this date
|
||||||
--datebefore DATE download only videos uploaded on or before
|
--datebefore DATE download only videos uploaded before this date
|
||||||
this date (i.e. inclusive)
|
--dateafter DATE download only videos uploaded after this date
|
||||||
--dateafter DATE download only videos uploaded on or after
|
--no-playlist download only the currently playing video
|
||||||
this date (i.e. inclusive)
|
--age-limit YEARS download only videos suitable for the given age
|
||||||
--min-views COUNT Do not download any videos with less than
|
--download-archive FILE Download only videos not present in the archive
|
||||||
COUNT views
|
file. Record all downloaded videos in it.
|
||||||
--max-views COUNT Do not download any videos with more than
|
|
||||||
COUNT views
|
|
||||||
--no-playlist download only the currently playing video
|
|
||||||
--age-limit YEARS download only videos suitable for the given
|
|
||||||
age
|
|
||||||
--download-archive FILE Download only videos not listed in the
|
|
||||||
archive file. Record the IDs of all
|
|
||||||
downloaded videos in it.
|
|
||||||
--include-ads Download advertisements as well
|
|
||||||
(experimental)
|
|
||||||
--youtube-include-dash-manifest Try to download the DASH manifest on
|
|
||||||
YouTube videos (experimental)
|
|
||||||
|
|
||||||
## Download Options:
|
## Download Options:
|
||||||
-r, --rate-limit LIMIT maximum download rate in bytes per second
|
-r, --rate-limit LIMIT maximum download rate in bytes per second (e.g.
|
||||||
(e.g. 50K or 4.2M)
|
50K or 4.2M)
|
||||||
-R, --retries RETRIES number of retries (default is 10)
|
-R, --retries RETRIES number of retries (default is 10)
|
||||||
--buffer-size SIZE size of download buffer (e.g. 1024 or 16K)
|
--buffer-size SIZE size of download buffer (e.g. 1024 or 16K)
|
||||||
(default is 1024)
|
(default is 1024)
|
||||||
--no-resize-buffer do not automatically adjust the buffer
|
--no-resize-buffer do not automatically adjust the buffer size. By
|
||||||
size. By default, the buffer size is
|
default, the buffer size is automatically resized
|
||||||
automatically resized from an initial value
|
from an initial value of SIZE.
|
||||||
of SIZE.
|
|
||||||
|
|
||||||
## Filesystem Options:
|
## Filesystem Options:
|
||||||
-t, --title use title in file name (default)
|
-t, --title use title in file name (default)
|
||||||
--id use only video ID in file name
|
--id use only video ID in file name
|
||||||
-l, --literal [deprecated] alias of --title
|
-l, --literal [deprecated] alias of --title
|
||||||
-A, --auto-number number downloaded files starting from 00000
|
-A, --auto-number number downloaded files starting from 00000
|
||||||
-o, --output TEMPLATE output filename template. Use %(title)s to
|
-o, --output TEMPLATE output filename template. Use %(title)s to get
|
||||||
get the title, %(uploader)s for the
|
the title, %(uploader)s for the uploader name,
|
||||||
uploader name, %(uploader_id)s for the
|
%(uploader_id)s for the uploader nickname if
|
||||||
uploader nickname if different,
|
different, %(autonumber)s to get an automatically
|
||||||
%(autonumber)s to get an automatically
|
incremented number, %(ext)s for the filename
|
||||||
incremented number, %(ext)s for the
|
extension, %(format)s for the format description
|
||||||
filename extension, %(format)s for the
|
(like "22 - 1280x720" or "HD"),%(format_id)s for
|
||||||
format description (like "22 - 1280x720" or
|
the unique id of the format (like Youtube's
|
||||||
"HD"), %(format_id)s for the unique id of
|
itags: "137"),%(upload_date)s for the upload date
|
||||||
the format (like Youtube's itags: "137"),
|
(YYYYMMDD), %(extractor)s for the provider
|
||||||
%(upload_date)s for the upload date
|
(youtube, metacafe, etc), %(id)s for the video id
|
||||||
(YYYYMMDD), %(extractor)s for the provider
|
, %(playlist)s for the playlist the video is in,
|
||||||
(youtube, metacafe, etc), %(id)s for the
|
%(playlist_index)s for the position in the
|
||||||
video id, %(playlist)s for the playlist the
|
playlist and %% for a literal percent. Use - to
|
||||||
video is in, %(playlist_index)s for the
|
output to stdout. Can also be used to download to
|
||||||
position in the playlist and %% for a
|
a different directory, for example with -o '/my/d
|
||||||
literal percent. %(height)s and %(width)s
|
ownloads/%(uploader)s/%(title)s-%(id)s.%(ext)s' .
|
||||||
for the width and height of the video
|
--autonumber-size NUMBER Specifies the number of digits in %(autonumber)s
|
||||||
format. %(resolution)s for a textual
|
when it is present in output filename template or
|
||||||
description of the resolution of the video
|
--auto-number option is given
|
||||||
format. Use - to output to stdout. Can also
|
--restrict-filenames Restrict filenames to only ASCII characters, and
|
||||||
be used to download to a different
|
avoid "&" and spaces in filenames
|
||||||
directory, for example with -o '/my/downloa
|
-a, --batch-file FILE file containing URLs to download ('-' for stdin)
|
||||||
ds/%(uploader)s/%(title)s-%(id)s.%(ext)s' .
|
-w, --no-overwrites do not overwrite files
|
||||||
--autonumber-size NUMBER Specifies the number of digits in
|
-c, --continue force resume of partially downloaded files. By
|
||||||
%(autonumber)s when it is present in output
|
default, youtube-dl will resume downloads if
|
||||||
filename template or --auto-number option
|
possible.
|
||||||
is given
|
--no-continue do not resume partially downloaded files (restart
|
||||||
--restrict-filenames Restrict filenames to only ASCII
|
from beginning)
|
||||||
characters, and avoid "&" and spaces in
|
--cookies FILE file to read cookies from and dump cookie jar in
|
||||||
filenames
|
--no-part do not use .part files
|
||||||
-a, --batch-file FILE file containing URLs to download ('-' for
|
--no-mtime do not use the Last-modified header to set the
|
||||||
stdin)
|
file modification time
|
||||||
--load-info FILE json file containing the video information
|
--write-description write video description to a .description file
|
||||||
(created with the "--write-json" option)
|
--write-info-json write video metadata to a .info.json file
|
||||||
-w, --no-overwrites do not overwrite files
|
--write-annotations write video annotations to a .annotation file
|
||||||
-c, --continue force resume of partially downloaded files.
|
--write-thumbnail write thumbnail image to disk
|
||||||
By default, youtube-dl will resume
|
|
||||||
downloads if possible.
|
|
||||||
--no-continue do not resume partially downloaded files
|
|
||||||
(restart from beginning)
|
|
||||||
--cookies FILE file to read cookies from and dump cookie
|
|
||||||
jar in
|
|
||||||
--no-part do not use .part files
|
|
||||||
--no-mtime do not use the Last-modified header to set
|
|
||||||
the file modification time
|
|
||||||
--write-description write video description to a .description
|
|
||||||
file
|
|
||||||
--write-info-json write video metadata to a .info.json file
|
|
||||||
--write-annotations write video annotations to a .annotation
|
|
||||||
file
|
|
||||||
--write-thumbnail write thumbnail image to disk
|
|
||||||
|
|
||||||
## Verbosity / Simulation Options:
|
## Verbosity / Simulation Options:
|
||||||
-q, --quiet activates quiet mode
|
-q, --quiet activates quiet mode
|
||||||
--no-warnings Ignore warnings
|
-s, --simulate do not download the video and do not write
|
||||||
-s, --simulate do not download the video and do not write
|
anything to disk
|
||||||
anything to disk
|
--skip-download do not download the video
|
||||||
--skip-download do not download the video
|
-g, --get-url simulate, quiet but print URL
|
||||||
-g, --get-url simulate, quiet but print URL
|
-e, --get-title simulate, quiet but print title
|
||||||
-e, --get-title simulate, quiet but print title
|
--get-id simulate, quiet but print id
|
||||||
--get-id simulate, quiet but print id
|
--get-thumbnail simulate, quiet but print thumbnail URL
|
||||||
--get-thumbnail simulate, quiet but print thumbnail URL
|
--get-description simulate, quiet but print video description
|
||||||
--get-description simulate, quiet but print video description
|
--get-filename simulate, quiet but print output filename
|
||||||
--get-duration simulate, quiet but print video length
|
--get-format simulate, quiet but print output format
|
||||||
--get-filename simulate, quiet but print output filename
|
-j, --dump-json simulate, quiet but print JSON information
|
||||||
--get-format simulate, quiet but print output format
|
--newline output progress bar as new lines
|
||||||
-j, --dump-json simulate, quiet but print JSON information.
|
--no-progress do not print progress bar
|
||||||
See --output for a description of available
|
--console-title display progress in console titlebar
|
||||||
keys.
|
-v, --verbose print various debugging information
|
||||||
--newline output progress bar as new lines
|
--dump-intermediate-pages print downloaded pages to debug problems(very
|
||||||
--no-progress do not print progress bar
|
verbose)
|
||||||
--console-title display progress in console titlebar
|
--write-pages Write downloaded pages to files in the current
|
||||||
-v, --verbose print various debugging information
|
directory
|
||||||
--dump-intermediate-pages print downloaded pages to debug problems
|
|
||||||
(very verbose)
|
|
||||||
--write-pages Write downloaded intermediary pages to
|
|
||||||
files in the current directory to debug
|
|
||||||
problems
|
|
||||||
--print-traffic Display sent and read HTTP traffic
|
|
||||||
|
|
||||||
## Video Format Options:
|
## Video Format Options:
|
||||||
-f, --format FORMAT video format code, specify the order of
|
-f, --format FORMAT video format code, specifiy the order of
|
||||||
preference using slashes: "-f 22/17/18".
|
preference using slashes: "-f 22/17/18". "-f mp4"
|
||||||
"-f mp4" and "-f flv" are also supported.
|
and "-f flv" are also supported
|
||||||
You can also use the special names "best",
|
--all-formats download all available video formats
|
||||||
"bestvideo", "bestaudio", "worst",
|
--prefer-free-formats prefer free video formats unless a specific one
|
||||||
"worstvideo" and "worstaudio". By default,
|
is requested
|
||||||
youtube-dl will pick the best quality.
|
--max-quality FORMAT highest quality format to download
|
||||||
--all-formats download all available video formats
|
-F, --list-formats list all available formats (currently youtube
|
||||||
--prefer-free-formats prefer free video formats unless a specific
|
only)
|
||||||
one is requested
|
|
||||||
--max-quality FORMAT highest quality format to download
|
|
||||||
-F, --list-formats list all available formats
|
|
||||||
|
|
||||||
## Subtitle Options:
|
## Subtitle Options:
|
||||||
--write-sub write subtitle file
|
--write-sub write subtitle file
|
||||||
--write-auto-sub write automatic subtitle file (youtube
|
--write-auto-sub write automatic subtitle file (youtube only)
|
||||||
only)
|
--all-subs downloads all the available subtitles of the
|
||||||
--all-subs downloads all the available subtitles of
|
video
|
||||||
the video
|
--list-subs lists all available subtitles for the video
|
||||||
--list-subs lists all available subtitles for the video
|
--sub-format FORMAT subtitle format (default=srt) ([sbv/vtt] youtube
|
||||||
--sub-format FORMAT subtitle format (default=srt) ([sbv/vtt]
|
only)
|
||||||
youtube only)
|
--sub-lang LANGS languages of the subtitles to download (optional)
|
||||||
--sub-lang LANGS languages of the subtitles to download
|
separated by commas, use IETF language tags like
|
||||||
(optional) separated by commas, use IETF
|
'en,pt'
|
||||||
language tags like 'en,pt'
|
|
||||||
|
|
||||||
## Authentication Options:
|
## Authentication Options:
|
||||||
-u, --username USERNAME account username
|
-u, --username USERNAME account username
|
||||||
-p, --password PASSWORD account password
|
-p, --password PASSWORD account password
|
||||||
-n, --netrc use .netrc authentication data
|
-n, --netrc use .netrc authentication data
|
||||||
--video-password PASSWORD video password (vimeo, smotri)
|
--video-password PASSWORD video password (vimeo only)
|
||||||
|
|
||||||
## Post-processing Options:
|
## Post-processing Options:
|
||||||
-x, --extract-audio convert video files to audio-only files
|
-x, --extract-audio convert video files to audio-only files (requires
|
||||||
(requires ffmpeg or avconv and ffprobe or
|
ffmpeg or avconv and ffprobe or avprobe)
|
||||||
avprobe)
|
--audio-format FORMAT "best", "aac", "vorbis", "mp3", "m4a", "opus", or
|
||||||
--audio-format FORMAT "best", "aac", "vorbis", "mp3", "m4a",
|
"wav"; best by default
|
||||||
"opus", or "wav"; best by default
|
--audio-quality QUALITY ffmpeg/avconv audio quality specification, insert
|
||||||
--audio-quality QUALITY ffmpeg/avconv audio quality specification,
|
a value between 0 (better) and 9 (worse) for VBR
|
||||||
insert a value between 0 (better) and 9
|
or a specific bitrate like 128K (default 5)
|
||||||
(worse) for VBR or a specific bitrate like
|
--recode-video FORMAT Encode the video to another format if necessary
|
||||||
128K (default 5)
|
(currently supported: mp4|flv|ogg|webm)
|
||||||
--recode-video FORMAT Encode the video to another format if
|
-k, --keep-video keeps the video file on disk after the post-
|
||||||
necessary (currently supported:
|
processing; the video is erased by default
|
||||||
mp4|flv|ogg|webm)
|
--no-post-overwrites do not overwrite post-processed files; the post-
|
||||||
-k, --keep-video keeps the video file on disk after the
|
processed files are overwritten by default
|
||||||
post-processing; the video is erased by
|
--embed-subs embed subtitles in the video (only for mp4
|
||||||
default
|
videos)
|
||||||
--no-post-overwrites do not overwrite post-processed files; the
|
--add-metadata add metadata to the files
|
||||||
post-processed files are overwritten by
|
|
||||||
default
|
|
||||||
--embed-subs embed subtitles in the video (only for mp4
|
|
||||||
videos)
|
|
||||||
--embed-thumbnail embed thumbnail in the audio as cover art
|
|
||||||
--add-metadata write metadata to the video file
|
|
||||||
--xattrs write metadata to the video file's xattrs
|
|
||||||
(using dublin core and xdg standards)
|
|
||||||
--prefer-avconv Prefer avconv over ffmpeg for running the
|
|
||||||
postprocessors (default)
|
|
||||||
--prefer-ffmpeg Prefer ffmpeg over avconv for running the
|
|
||||||
postprocessors
|
|
||||||
|
|
||||||
# CONFIGURATION
|
# CONFIGURATION
|
||||||
|
|
||||||
You can configure youtube-dl by placing default arguments (such as `--extract-audio --no-mtime` to always extract the audio and not copy the mtime) into `/etc/youtube-dl.conf` and/or `~/.config/youtube-dl/config`. On Windows, the configuration file locations are `%APPDATA%\youtube-dl\config.txt` and `C:\Users\<Yourname>\youtube-dl.conf`.
|
You can configure youtube-dl by placing default arguments (such as `--extract-audio --no-mtime` to always extract the audio and not copy the mtime) into `/etc/youtube-dl.conf` and/or `~/.config/youtube-dl.conf`.
|
||||||
|
|
||||||
# OUTPUT TEMPLATE
|
# OUTPUT TEMPLATE
|
||||||
|
|
||||||
@@ -309,14 +217,9 @@ Videos can be filtered by their upload date using the options `--date`, `--dateb
|
|||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
|
|
||||||
# Download only the videos uploaded in the last 6 months
|
$ youtube-dl --dateafter now-6months #will only download the videos uploaded in the last 6 months
|
||||||
$ youtube-dl --dateafter now-6months
|
$ youtube-dl --date 19700101 #will only download the videos uploaded in January 1, 1970
|
||||||
|
$ youtube-dl --dateafter 20000101 --datebefore 20100101 #will only download the videos uploaded between 2000 and 2010
|
||||||
# Download only the videos uploaded on January 1, 1970
|
|
||||||
$ youtube-dl --date 19700101
|
|
||||||
|
|
||||||
$ # will only download the videos uploaded in the 200x decade
|
|
||||||
$ youtube-dl --dateafter 20000101 --datebefore 20091231
|
|
||||||
|
|
||||||
# FAQ
|
# FAQ
|
||||||
|
|
||||||
@@ -361,152 +264,22 @@ Since June 2012 (#342) youtube-dl is packed as an executable zipfile, simply unz
|
|||||||
|
|
||||||
To run the exe you need to install first the [Microsoft Visual C++ 2008 Redistributable Package](http://www.microsoft.com/en-us/download/details.aspx?id=29).
|
To run the exe you need to install first the [Microsoft Visual C++ 2008 Redistributable Package](http://www.microsoft.com/en-us/download/details.aspx?id=29).
|
||||||
|
|
||||||
# DEVELOPER INSTRUCTIONS
|
|
||||||
|
|
||||||
Most users do not need to build youtube-dl and can [download the builds](http://rg3.github.io/youtube-dl/download.html) or get them from their distribution.
|
|
||||||
|
|
||||||
To run youtube-dl as a developer, you don't need to build anything either. Simply execute
|
|
||||||
|
|
||||||
python -m youtube_dl
|
|
||||||
|
|
||||||
To run the test, simply invoke your favorite test runner, or execute a test file directly; any of the following work:
|
|
||||||
|
|
||||||
python -m unittest discover
|
|
||||||
python test/test_download.py
|
|
||||||
nosetests
|
|
||||||
|
|
||||||
If you want to create a build of youtube-dl yourself, you'll need
|
|
||||||
|
|
||||||
* python
|
|
||||||
* make
|
|
||||||
* pandoc
|
|
||||||
* zip
|
|
||||||
* nosetests
|
|
||||||
|
|
||||||
### Adding support for a new site
|
|
||||||
|
|
||||||
If you want to add support for a new site, you can follow this quick list (assuming your service is called `yourextractor`):
|
|
||||||
|
|
||||||
1. [Fork this repository](https://github.com/rg3/youtube-dl/fork)
|
|
||||||
2. Check out the source code with `git clone git@github.com:YOUR_GITHUB_USERNAME/youtube-dl.git`
|
|
||||||
3. Start a new git branch with `cd youtube-dl; git checkout -b yourextractor`
|
|
||||||
4. Start with this simple template and save it to `youtube_dl/extractor/yourextractor.py`:
|
|
||||||
|
|
||||||
# coding: utf-8
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
|
|
||||||
|
|
||||||
class YourExtractorIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'https?://(?:www\.)?yourextractor\.com/watch/(?P<id>[0-9]+)'
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://yourextractor.com/watch/42',
|
|
||||||
'md5': 'TODO: md5 sum of the first 10KiB of the video file',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '42',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Video title goes here',
|
|
||||||
# TODO more properties, either as:
|
|
||||||
# * A value
|
|
||||||
# * MD5 checksum; start the string with md5:
|
|
||||||
# * A regular expression; start the string with re:
|
|
||||||
# * Any Python type (for example int or float)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
|
|
||||||
# TODO more code goes here, for example ...
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
title = self._html_search_regex(r'<h1>(.*?)</h1>', webpage, 'title')
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'title': title,
|
|
||||||
# TODO more properties (see youtube_dl/extractor/common.py)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
5. Add an import in [`youtube_dl/extractor/__init__.py`](https://github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/__init__.py).
|
|
||||||
6. Run `python test/test_download.py TestDownload.test_YourExtractor`. This *should fail* at first, but you can continually re-run it until you're done.
|
|
||||||
7. Have a look at [`youtube_dl/common/extractor/common.py`](https://github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/common.py) for possible helper methods and a [detailed description of what your extractor should return](https://github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/common.py#L38). Add tests and code for as many as you want.
|
|
||||||
8. If you can, check the code with [pyflakes](https://pypi.python.org/pypi/pyflakes) (a good idea) and [pep8](https://pypi.python.org/pypi/pep8) (optional, ignore E501).
|
|
||||||
9. When the tests pass, [add](https://www.kernel.org/pub/software/scm/git/docs/git-add.html) the new files and [commit](https://www.kernel.org/pub/software/scm/git/docs/git-commit.html) them and [push](https://www.kernel.org/pub/software/scm/git/docs/git-push.html) the result, like this:
|
|
||||||
|
|
||||||
$ git add youtube_dl/extractor/__init__.py
|
|
||||||
$ git add youtube_dl/extractor/yourextractor.py
|
|
||||||
$ git commit -m '[yourextractor] Add new extractor'
|
|
||||||
$ git push origin yourextractor
|
|
||||||
|
|
||||||
10. Finally, [create a pull request](https://help.github.com/articles/creating-a-pull-request). We'll then review and merge it.
|
|
||||||
|
|
||||||
In any case, thank you very much for your contributions!
|
|
||||||
|
|
||||||
# BUGS
|
|
||||||
|
|
||||||
Bugs and suggestions should be reported at: <https://github.com/rg3/youtube-dl/issues> . Unless you were prompted so or there is another pertinent reason (e.g. GitHub fails to accept the bug report), please do not send bug reports via personal email.
|
|
||||||
|
|
||||||
Please include the full output of the command when run with `--verbose`. The output (including the first lines) contain important debugging information. Issues without the full output are often not reproducible and therefore do not get solved in short order, if ever.
|
|
||||||
|
|
||||||
For discussions, join us in the irc channel #youtube-dl on freenode.
|
|
||||||
|
|
||||||
When you submit a request, please re-read it once to avoid a couple of mistakes (you can and should use this as a checklist):
|
|
||||||
|
|
||||||
### Is the description of the issue itself sufficient?
|
|
||||||
|
|
||||||
We often get issue reports that we cannot really decipher. While in most cases we eventually get the required information after asking back multiple times, this poses an unnecessary drain on our resources. Many contributors, including myself, are also not native speakers, so we may misread some parts.
|
|
||||||
|
|
||||||
So please elaborate on what feature you are requesting, or what bug you want to be fixed. Make sure that it's obvious
|
|
||||||
|
|
||||||
- What the problem is
|
|
||||||
- How it could be fixed
|
|
||||||
- How your proposed solution would look like
|
|
||||||
|
|
||||||
If your report is shorter than two lines, it is almost certainly missing some of these, which makes it hard for us to respond to it. We're often too polite to close the issue outright, but the missing info makes misinterpretation likely. As a commiter myself, I often get frustrated by these issues, since the only possible way for me to move forward on them is to ask for clarification over and over.
|
|
||||||
|
|
||||||
For bug reports, this means that your report should contain the *complete* output of youtube-dl when called with the -v flag. The error message you get for (most) bugs even says so, but you would not believe how many of our bug reports do not contain this information.
|
|
||||||
|
|
||||||
Site support requests **must contain an example URL**. An example URL is a URL you might want to download, like http://www.youtube.com/watch?v=BaW_jenozKc . There should be an obvious video present. Except under very special circumstances, the main page of a video service (e.g. http://www.youtube.com/ ) is *not* an example URL.
|
|
||||||
|
|
||||||
### Are you using the latest version?
|
|
||||||
|
|
||||||
Before reporting any issue, type youtube-dl -U. This should report that you're up-to-date. About 20% of the reports we receive are already fixed, but people are using outdated versions. This goes for feature requests as well.
|
|
||||||
|
|
||||||
### Is the issue already documented?
|
|
||||||
|
|
||||||
Make sure that someone has not already opened the issue you're trying to open. Search at the top of the window or at https://github.com/rg3/youtube-dl/search?type=Issues . If there is an issue, feel free to write something along the lines of "This affects me as well, with version 2015.01.01. Here is some more information on the issue: ...". While some issues may be old, a new post into them often spurs rapid activity.
|
|
||||||
|
|
||||||
### Why are existing options not enough?
|
|
||||||
|
|
||||||
Before requesting a new feature, please have a quick peek at [the list of supported options](https://github.com/rg3/youtube-dl/blob/master/README.md#synopsis). Many feature requests are for features that actually exist already! Please, absolutely do show off your work in the issue report and detail how the existing similar options do *not* solve your problem.
|
|
||||||
|
|
||||||
### Is there enough context in your bug report?
|
|
||||||
|
|
||||||
People want to solve problems, and often think they do us a favor by breaking down their larger problems (e.g. wanting to skip already downloaded files) to a specific request (e.g. requesting us to look whether the file exists before downloading the info page). However, what often happens is that they break down the problem into two steps: One simple, and one impossible (or extremely complicated one).
|
|
||||||
|
|
||||||
We are then presented with a very complicated request when the original problem could be solved far easier, e.g. by recording the downloaded video IDs in a separate file. To avoid this, you must include the greater context where it is non-obvious. In particular, every feature request that does not consist of adding support for a new site should contain a use case scenario that explains in what situation the missing feature would be useful.
|
|
||||||
|
|
||||||
### Does the issue involve one problem, and one problem only?
|
|
||||||
|
|
||||||
Some of our users seem to think there is a limit of issues they can or should open. There is no limit of issues they can or should open. While it may seem appealing to be able to dump all your issues into one ticket, that means that someone who solves one of your issues cannot mark the issue as closed. Typically, reporting a bunch of issues leads to the ticket lingering since nobody wants to attack that behemoth, until someone mercifully splits the issue into multiple ones.
|
|
||||||
|
|
||||||
In particular, every site support request issue should only pertain to services at one site (generally under a common domain, but always using the same backend technology). Do not request support for vimeo user videos, Whitehouse podcasts, and Google Plus pages in the same issue. Also, make sure that you don't post bug reports alongside feature requests. As a rule of thumb, a feature request does not include outputs of youtube-dl that are not immediately related to the feature at hand. Do not post reports of a network error alongside the request for a new video service.
|
|
||||||
|
|
||||||
### Is anyone going to need the feature?
|
|
||||||
|
|
||||||
Only post features that you (or an incapicated friend you can personally talk to) require. Do not post features because they seem like a good idea. If they are really useful, they will be requested by someone who requires them.
|
|
||||||
|
|
||||||
### Is your question about youtube-dl?
|
|
||||||
|
|
||||||
It may sound strange, but some bug reports we receive are completely unrelated to youtube-dl and relate to a different or even the reporter's own application. Please make sure that you are actually using youtube-dl. If you are using a UI for youtube-dl, report the bug to the maintainer of the actual application providing the UI. On the other hand, if your UI for youtube-dl fails in some way you believe is related to youtube-dl, by all means, go ahead and report the bug.
|
|
||||||
|
|
||||||
# COPYRIGHT
|
# COPYRIGHT
|
||||||
|
|
||||||
youtube-dl is released into the public domain by the copyright holders.
|
youtube-dl is released into the public domain by the copyright holders.
|
||||||
|
|
||||||
This README file was originally written by Daniel Bolton (<https://github.com/dbbolton>) and is likewise released into the public domain.
|
This README file was originally written by Daniel Bolton (<https://github.com/dbbolton>) and is likewise released into the public domain.
|
||||||
|
|
||||||
|
# BUGS
|
||||||
|
|
||||||
|
Bugs and suggestions should be reported at: <https://github.com/rg3/youtube-dl/issues>
|
||||||
|
|
||||||
|
Please include:
|
||||||
|
|
||||||
|
* Your exact command line, like `youtube-dl -t "http://www.youtube.com/watch?v=uHlDtZ6Oc3s&feature=channel_video_title"`. A common mistake is not to escape the `&`. Putting URLs in quotes should solve this problem.
|
||||||
|
* If possible re-run the command with `--verbose`, and include the full output, it is really helpful to us.
|
||||||
|
* The output of `youtube-dl --version`
|
||||||
|
* The output of `python --version`
|
||||||
|
* The name and version of your Operating System ("Ubuntu 11.04 x64" or "Windows 7 x64" is usually enough).
|
||||||
|
|
||||||
|
For discussions, join us in the irc channel #youtube-dl on freenode.
|
||||||
|
|||||||
@@ -1,21 +1,10 @@
|
|||||||
__youtube_dl()
|
__youtube_dl()
|
||||||
{
|
{
|
||||||
local cur prev opts fileopts diropts keywords
|
local cur prev opts
|
||||||
COMPREPLY=()
|
COMPREPLY=()
|
||||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
|
||||||
opts="{{flags}}"
|
opts="{{flags}}"
|
||||||
keywords=":ytfavorites :ytrecommended :ytsubscriptions :ytwatchlater :ythistory"
|
keywords=":ytfavorites :ytrecommended :ytsubscriptions :ytwatchlater"
|
||||||
fileopts="-a|--batch-file|--download-archive|--cookies|--load-info"
|
|
||||||
diropts="--cache-dir"
|
|
||||||
|
|
||||||
if [[ ${prev} =~ ${fileopts} ]]; then
|
|
||||||
COMPREPLY=( $(compgen -f -- ${cur}) )
|
|
||||||
return 0
|
|
||||||
elif [[ ${prev} =~ ${diropts} ]]; then
|
|
||||||
COMPREPLY=( $(compgen -d -- ${cur}) )
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ${cur} =~ : ]]; then
|
if [[ ${cur} =~ : ]]; then
|
||||||
COMPREPLY=( $(compgen -W "${keywords}" -- ${cur}) )
|
COMPREPLY=( $(compgen -W "${keywords}" -- ${cur}) )
|
||||||
|
|||||||
@@ -3,9 +3,6 @@
|
|||||||
"""
|
"""
|
||||||
This script employs a VERY basic heuristic ('porn' in webpage.lower()) to check
|
This script employs a VERY basic heuristic ('porn' in webpage.lower()) to check
|
||||||
if we are not 'age_limit' tagging some porn site
|
if we are not 'age_limit' tagging some porn site
|
||||||
|
|
||||||
A second approach implemented relies on a list of porn domains, to activate it
|
|
||||||
pass the list filename as the only argument
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Allow direct execution
|
# Allow direct execution
|
||||||
@@ -14,42 +11,25 @@ import sys
|
|||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
from test.helper import get_testcases
|
from test.helper import get_testcases
|
||||||
from youtube_dl.utils import compat_urllib_parse_urlparse
|
|
||||||
from youtube_dl.utils import compat_urllib_request
|
from youtube_dl.utils import compat_urllib_request
|
||||||
|
|
||||||
if len(sys.argv) > 1:
|
|
||||||
METHOD = 'LIST'
|
|
||||||
LIST = open(sys.argv[1]).read().decode('utf8').strip()
|
|
||||||
else:
|
|
||||||
METHOD = 'EURISTIC'
|
|
||||||
|
|
||||||
for test in get_testcases():
|
for test in get_testcases():
|
||||||
if METHOD == 'EURISTIC':
|
try:
|
||||||
try:
|
webpage = compat_urllib_request.urlopen(test['url'], timeout=10).read()
|
||||||
webpage = compat_urllib_request.urlopen(test['url'], timeout=10).read()
|
except:
|
||||||
except:
|
print('\nFail: {0}'.format(test['name']))
|
||||||
print('\nFail: {0}'.format(test['name']))
|
continue
|
||||||
continue
|
|
||||||
|
|
||||||
webpage = webpage.decode('utf8', 'replace')
|
webpage = webpage.decode('utf8', 'replace')
|
||||||
|
|
||||||
RESULT = 'porn' in webpage.lower()
|
if 'porn' in webpage.lower() and ('info_dict' not in test
|
||||||
|
or 'age_limit' not in test['info_dict']
|
||||||
elif METHOD == 'LIST':
|
or test['info_dict']['age_limit'] != 18):
|
||||||
domain = compat_urllib_parse_urlparse(test['url']).netloc
|
|
||||||
if not domain:
|
|
||||||
print('\nFail: {0}'.format(test['name']))
|
|
||||||
continue
|
|
||||||
domain = '.'.join(domain.split('.')[-2:])
|
|
||||||
|
|
||||||
RESULT = ('.' + domain + '\n' in LIST or '\n' + domain + '\n' in LIST)
|
|
||||||
|
|
||||||
if RESULT and ('info_dict' not in test or 'age_limit' not in test['info_dict']
|
|
||||||
or test['info_dict']['age_limit'] != 18):
|
|
||||||
print('\nPotential missing age_limit check: {0}'.format(test['name']))
|
print('\nPotential missing age_limit check: {0}'.format(test['name']))
|
||||||
|
|
||||||
elif not RESULT and ('info_dict' in test and 'age_limit' in test['info_dict']
|
elif 'porn' not in webpage.lower() and ('info_dict' in test and
|
||||||
and test['info_dict']['age_limit'] == 18):
|
'age_limit' in test['info_dict'] and
|
||||||
|
test['info_dict']['age_limit'] == 18):
|
||||||
print('\nPotential false negative: {0}'.format(test['name']))
|
print('\nPotential false negative: {0}'.format(test['name']))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -1,76 +1,56 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
import datetime
|
import datetime
|
||||||
import io
|
|
||||||
import json
|
|
||||||
import textwrap
|
import textwrap
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
atom_template = textwrap.dedent("""\
|
atom_template=textwrap.dedent("""\
|
||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version='1.0' encoding='utf-8'?>
|
||||||
<feed xmlns="http://www.w3.org/2005/Atom">
|
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom">
|
||||||
<link rel="self" href="http://rg3.github.io/youtube-dl/update/releases.atom" />
|
<atom:title>youtube-dl releases</atom:title>
|
||||||
<title>youtube-dl releases</title>
|
<atom:id>youtube-dl-updates-feed</atom:id>
|
||||||
<id>https://yt-dl.org/feed/youtube-dl-updates-feed</id>
|
<atom:updated>@TIMESTAMP@</atom:updated>
|
||||||
<updated>@TIMESTAMP@</updated>
|
@ENTRIES@
|
||||||
@ENTRIES@
|
</atom:feed>""")
|
||||||
</feed>""")
|
|
||||||
|
|
||||||
entry_template = textwrap.dedent("""
|
entry_template=textwrap.dedent("""
|
||||||
<entry>
|
<atom:entry>
|
||||||
<id>https://yt-dl.org/feed/youtube-dl-updates-feed/youtube-dl-@VERSION@</id>
|
<atom:id>youtube-dl-@VERSION@</atom:id>
|
||||||
<title>New version @VERSION@</title>
|
<atom:title>New version @VERSION@</atom:title>
|
||||||
<link href="http://rg3.github.io/youtube-dl" />
|
<atom:link href="http://rg3.github.io/youtube-dl" />
|
||||||
<content type="xhtml">
|
<atom:content type="xhtml">
|
||||||
<div xmlns="http://www.w3.org/1999/xhtml">
|
<div xmlns="http://www.w3.org/1999/xhtml">
|
||||||
Downloads available at <a href="https://yt-dl.org/downloads/@VERSION@/">https://yt-dl.org/downloads/@VERSION@/</a>
|
Downloads available at <a href="https://yt-dl.org/downloads/@VERSION@/">https://yt-dl.org/downloads/@VERSION@/</a>
|
||||||
</div>
|
</div>
|
||||||
</content>
|
</atom:content>
|
||||||
<author>
|
<atom:author>
|
||||||
<name>The youtube-dl maintainers</name>
|
<atom:name>The youtube-dl maintainers</atom:name>
|
||||||
</author>
|
</atom:author>
|
||||||
<updated>@TIMESTAMP@</updated>
|
<atom:updated>@TIMESTAMP@</atom:updated>
|
||||||
</entry>
|
</atom:entry>
|
||||||
""")
|
""")
|
||||||
|
|
||||||
now = datetime.datetime.now()
|
now = datetime.datetime.now()
|
||||||
now_iso = now.isoformat() + 'Z'
|
now_iso = now.isoformat()
|
||||||
|
|
||||||
atom_template = atom_template.replace('@TIMESTAMP@', now_iso)
|
atom_template = atom_template.replace('@TIMESTAMP@',now_iso)
|
||||||
|
|
||||||
|
entries=[]
|
||||||
|
|
||||||
versions_info = json.load(open('update/versions.json'))
|
versions_info = json.load(open('update/versions.json'))
|
||||||
versions = list(versions_info['versions'].keys())
|
versions = list(versions_info['versions'].keys())
|
||||||
versions.sort()
|
versions.sort()
|
||||||
|
|
||||||
entries = []
|
|
||||||
for v in versions:
|
for v in versions:
|
||||||
fields = v.split('.')
|
entry = entry_template.replace('@TIMESTAMP@',v.replace('.','-'))
|
||||||
year, month, day = map(int, fields[:3])
|
entry = entry.replace('@VERSION@',v)
|
||||||
faked = 0
|
entries.append(entry)
|
||||||
patchlevel = 0
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
datetime.date(year, month, day)
|
|
||||||
except ValueError:
|
|
||||||
day -= 1
|
|
||||||
faked += 1
|
|
||||||
assert day > 0
|
|
||||||
continue
|
|
||||||
break
|
|
||||||
if len(fields) >= 4:
|
|
||||||
try:
|
|
||||||
patchlevel = int(fields[3])
|
|
||||||
except ValueError:
|
|
||||||
patchlevel = 1
|
|
||||||
timestamp = '%04d-%02d-%02dT00:%02d:%02dZ' % (year, month, day, faked, patchlevel)
|
|
||||||
|
|
||||||
entry = entry_template.replace('@TIMESTAMP@', timestamp)
|
|
||||||
entry = entry.replace('@VERSION@', v)
|
|
||||||
entries.append(entry)
|
|
||||||
|
|
||||||
entries_str = textwrap.indent(''.join(entries), '\t')
|
entries_str = textwrap.indent(''.join(entries), '\t')
|
||||||
atom_template = atom_template.replace('@ENTRIES@', entries_str)
|
atom_template = atom_template.replace('@ENTRIES@', entries_str)
|
||||||
|
|
||||||
with io.open('update/releases.atom', 'w', encoding='utf-8') as atom_file:
|
with open('update/releases.atom','w',encoding='utf-8') as atom_file:
|
||||||
atom_file.write(atom_template)
|
atom_file.write(atom_template)
|
||||||
|
|
||||||
|
|||||||
@@ -1,24 +1,20 @@
|
|||||||
import io
|
|
||||||
import sys
|
import sys
|
||||||
import re
|
import re
|
||||||
|
|
||||||
README_FILE = 'README.md'
|
README_FILE = 'README.md'
|
||||||
helptext = sys.stdin.read()
|
helptext = sys.stdin.read()
|
||||||
|
|
||||||
if isinstance(helptext, bytes):
|
with open(README_FILE) as f:
|
||||||
helptext = helptext.decode('utf-8')
|
|
||||||
|
|
||||||
with io.open(README_FILE, encoding='utf-8') as f:
|
|
||||||
oldreadme = f.read()
|
oldreadme = f.read()
|
||||||
|
|
||||||
header = oldreadme[:oldreadme.index('# OPTIONS')]
|
header = oldreadme[:oldreadme.index('# OPTIONS')]
|
||||||
footer = oldreadme[oldreadme.index('# CONFIGURATION'):]
|
footer = oldreadme[oldreadme.index('# CONFIGURATION'):]
|
||||||
|
|
||||||
options = helptext[helptext.index(' General Options:') + 19:]
|
options = helptext[helptext.index(' General Options:')+19:]
|
||||||
options = re.sub(r'(?m)^ (\w.+)$', r'## \1', options)
|
options = re.sub(r'^ (\w.+)$', r'## \1', options, flags=re.M)
|
||||||
options = '# OPTIONS\n' + options + '\n'
|
options = '# OPTIONS\n' + options + '\n'
|
||||||
|
|
||||||
with io.open(README_FILE, 'w', encoding='utf-8') as f:
|
with open(README_FILE, 'w') as f:
|
||||||
f.write(header)
|
f.write(header)
|
||||||
f.write(options)
|
f.write(options)
|
||||||
f.write(footer)
|
f.write(footer)
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
|
|
||||||
import io
|
|
||||||
import os.path
|
|
||||||
import sys
|
|
||||||
import re
|
|
||||||
|
|
||||||
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
README_FILE = os.path.join(ROOT_DIR, 'README.md')
|
|
||||||
|
|
||||||
with io.open(README_FILE, encoding='utf-8') as f:
|
|
||||||
readme = f.read()
|
|
||||||
|
|
||||||
PREFIX = '%YOUTUBE-DL(1)\n\n# NAME\n'
|
|
||||||
readme = re.sub(r'(?s)# INSTALLATION.*?(?=# DESCRIPTION)', '', readme)
|
|
||||||
readme = PREFIX + readme
|
|
||||||
|
|
||||||
if sys.version_info < (3, 0):
|
|
||||||
print(readme.encode('utf-8'))
|
|
||||||
else:
|
|
||||||
print(readme)
|
|
||||||
@@ -14,24 +14,16 @@
|
|||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
skip_tests=true
|
skip_tests=false
|
||||||
if [ "$1" = '--run-tests' ]; then
|
if [ "$1" = '--skip-test' ]; then
|
||||||
skip_tests=false
|
skip_tests=true
|
||||||
shift
|
shift
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ -z "$1" ]; then echo "ERROR: specify version number like this: $0 1994.09.06"; exit 1; fi
|
if [ -z "$1" ]; then echo "ERROR: specify version number like this: $0 1994.09.06"; exit 1; fi
|
||||||
version="$1"
|
version="$1"
|
||||||
major_version=$(echo "$version" | sed -n 's#^\([0-9]*\.[0-9]*\.[0-9]*\).*#\1#p')
|
|
||||||
if test "$major_version" '!=' "$(date '+%Y.%m.%d')"; then
|
|
||||||
echo "$version does not start with today's date!"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ ! -z "`git tag | grep "$version"`" ]; then echo 'ERROR: version already present'; exit 1; fi
|
if [ ! -z "`git tag | grep "$version"`" ]; then echo 'ERROR: version already present'; exit 1; fi
|
||||||
if [ ! -z "`git status --porcelain | grep -v CHANGELOG`" ]; then echo 'ERROR: the working directory is not clean; commit or stash changes'; exit 1; fi
|
if [ ! -z "`git status --porcelain | grep -v CHANGELOG`" ]; then echo 'ERROR: the working directory is not clean; commit or stash changes'; exit 1; fi
|
||||||
useless_files=$(find youtube_dl -type f -not -name '*.py')
|
|
||||||
if [ ! -z "$useless_files" ]; then echo "ERROR: Non-.py files in youtube_dl: $useless_files"; exit 1; fi
|
|
||||||
if [ ! -f "updates_key.pem" ]; then echo 'ERROR: updates_key.pem missing'; exit 1; fi
|
if [ ! -f "updates_key.pem" ]; then echo 'ERROR: updates_key.pem missing'; exit 1; fi
|
||||||
|
|
||||||
/bin/echo -e "\n### First of all, testing..."
|
/bin/echo -e "\n### First of all, testing..."
|
||||||
@@ -76,7 +68,7 @@ RELEASE_FILES="youtube-dl youtube-dl.exe youtube-dl-$version.tar.gz"
|
|||||||
git checkout HEAD -- youtube-dl youtube-dl.exe
|
git checkout HEAD -- youtube-dl youtube-dl.exe
|
||||||
|
|
||||||
/bin/echo -e "\n### Signing and uploading the new binaries to yt-dl.org ..."
|
/bin/echo -e "\n### Signing and uploading the new binaries to yt-dl.org ..."
|
||||||
for f in $RELEASE_FILES; do gpg --passphrase-repeat 5 --detach-sig "build/$version/$f"; done
|
for f in $RELEASE_FILES; do gpg --detach-sig "build/$version/$f"; done
|
||||||
scp -r "build/$version" ytdl@yt-dl.org:html/tmp/
|
scp -r "build/$version" ytdl@yt-dl.org:html/tmp/
|
||||||
ssh ytdl@yt-dl.org "mv html/tmp/$version html/downloads/"
|
ssh ytdl@yt-dl.org "mv html/tmp/$version html/downloads/"
|
||||||
ssh ytdl@yt-dl.org "sh html/update_latest.sh $version"
|
ssh ytdl@yt-dl.org "sh html/update_latest.sh $version"
|
||||||
@@ -103,7 +95,7 @@ rm -rf build
|
|||||||
|
|
||||||
make pypi-files
|
make pypi-files
|
||||||
echo "Uploading to PyPi ..."
|
echo "Uploading to PyPi ..."
|
||||||
python setup.py sdist bdist_wheel upload
|
python setup.py sdist upload
|
||||||
make clean
|
make clean
|
||||||
|
|
||||||
/bin/echo -e "\n### DONE!"
|
/bin/echo -e "\n### DONE!"
|
||||||
|
|||||||
1
docs/.gitignore
vendored
1
docs/.gitignore
vendored
@@ -1 +0,0 @@
|
|||||||
_build/
|
|
||||||
177
docs/Makefile
177
docs/Makefile
@@ -1,177 +0,0 @@
|
|||||||
# Makefile for Sphinx documentation
|
|
||||||
#
|
|
||||||
|
|
||||||
# You can set these variables from the command line.
|
|
||||||
SPHINXOPTS =
|
|
||||||
SPHINXBUILD = sphinx-build
|
|
||||||
PAPER =
|
|
||||||
BUILDDIR = _build
|
|
||||||
|
|
||||||
# User-friendly check for sphinx-build
|
|
||||||
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
|
|
||||||
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
|
|
||||||
endif
|
|
||||||
|
|
||||||
# Internal variables.
|
|
||||||
PAPEROPT_a4 = -D latex_paper_size=a4
|
|
||||||
PAPEROPT_letter = -D latex_paper_size=letter
|
|
||||||
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
|
|
||||||
# the i18n builder cannot share the environment and doctrees with the others
|
|
||||||
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
|
|
||||||
|
|
||||||
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
|
|
||||||
|
|
||||||
help:
|
|
||||||
@echo "Please use \`make <target>' where <target> is one of"
|
|
||||||
@echo " html to make standalone HTML files"
|
|
||||||
@echo " dirhtml to make HTML files named index.html in directories"
|
|
||||||
@echo " singlehtml to make a single large HTML file"
|
|
||||||
@echo " pickle to make pickle files"
|
|
||||||
@echo " json to make JSON files"
|
|
||||||
@echo " htmlhelp to make HTML files and a HTML help project"
|
|
||||||
@echo " qthelp to make HTML files and a qthelp project"
|
|
||||||
@echo " devhelp to make HTML files and a Devhelp project"
|
|
||||||
@echo " epub to make an epub"
|
|
||||||
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
|
|
||||||
@echo " latexpdf to make LaTeX files and run them through pdflatex"
|
|
||||||
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
|
|
||||||
@echo " text to make text files"
|
|
||||||
@echo " man to make manual pages"
|
|
||||||
@echo " texinfo to make Texinfo files"
|
|
||||||
@echo " info to make Texinfo files and run them through makeinfo"
|
|
||||||
@echo " gettext to make PO message catalogs"
|
|
||||||
@echo " changes to make an overview of all changed/added/deprecated items"
|
|
||||||
@echo " xml to make Docutils-native XML files"
|
|
||||||
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
|
|
||||||
@echo " linkcheck to check all external links for integrity"
|
|
||||||
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
|
|
||||||
|
|
||||||
clean:
|
|
||||||
rm -rf $(BUILDDIR)/*
|
|
||||||
|
|
||||||
html:
|
|
||||||
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
|
|
||||||
@echo
|
|
||||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
|
|
||||||
|
|
||||||
dirhtml:
|
|
||||||
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
|
|
||||||
@echo
|
|
||||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
|
|
||||||
|
|
||||||
singlehtml:
|
|
||||||
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
|
|
||||||
@echo
|
|
||||||
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
|
|
||||||
|
|
||||||
pickle:
|
|
||||||
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
|
|
||||||
@echo
|
|
||||||
@echo "Build finished; now you can process the pickle files."
|
|
||||||
|
|
||||||
json:
|
|
||||||
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
|
|
||||||
@echo
|
|
||||||
@echo "Build finished; now you can process the JSON files."
|
|
||||||
|
|
||||||
htmlhelp:
|
|
||||||
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
|
|
||||||
@echo
|
|
||||||
@echo "Build finished; now you can run HTML Help Workshop with the" \
|
|
||||||
".hhp project file in $(BUILDDIR)/htmlhelp."
|
|
||||||
|
|
||||||
qthelp:
|
|
||||||
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
|
|
||||||
@echo
|
|
||||||
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
|
|
||||||
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
|
|
||||||
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/youtube-dl.qhcp"
|
|
||||||
@echo "To view the help file:"
|
|
||||||
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/youtube-dl.qhc"
|
|
||||||
|
|
||||||
devhelp:
|
|
||||||
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
|
|
||||||
@echo
|
|
||||||
@echo "Build finished."
|
|
||||||
@echo "To view the help file:"
|
|
||||||
@echo "# mkdir -p $$HOME/.local/share/devhelp/youtube-dl"
|
|
||||||
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/youtube-dl"
|
|
||||||
@echo "# devhelp"
|
|
||||||
|
|
||||||
epub:
|
|
||||||
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
|
|
||||||
@echo
|
|
||||||
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
|
|
||||||
|
|
||||||
latex:
|
|
||||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
|
||||||
@echo
|
|
||||||
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
|
|
||||||
@echo "Run \`make' in that directory to run these through (pdf)latex" \
|
|
||||||
"(use \`make latexpdf' here to do that automatically)."
|
|
||||||
|
|
||||||
latexpdf:
|
|
||||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
|
||||||
@echo "Running LaTeX files through pdflatex..."
|
|
||||||
$(MAKE) -C $(BUILDDIR)/latex all-pdf
|
|
||||||
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
|
||||||
|
|
||||||
latexpdfja:
|
|
||||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
|
||||||
@echo "Running LaTeX files through platex and dvipdfmx..."
|
|
||||||
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
|
|
||||||
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
|
||||||
|
|
||||||
text:
|
|
||||||
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
|
|
||||||
@echo
|
|
||||||
@echo "Build finished. The text files are in $(BUILDDIR)/text."
|
|
||||||
|
|
||||||
man:
|
|
||||||
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
|
|
||||||
@echo
|
|
||||||
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
|
|
||||||
|
|
||||||
texinfo:
|
|
||||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
|
||||||
@echo
|
|
||||||
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
|
|
||||||
@echo "Run \`make' in that directory to run these through makeinfo" \
|
|
||||||
"(use \`make info' here to do that automatically)."
|
|
||||||
|
|
||||||
info:
|
|
||||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
|
||||||
@echo "Running Texinfo files through makeinfo..."
|
|
||||||
make -C $(BUILDDIR)/texinfo info
|
|
||||||
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
|
|
||||||
|
|
||||||
gettext:
|
|
||||||
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
|
|
||||||
@echo
|
|
||||||
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
|
|
||||||
|
|
||||||
changes:
|
|
||||||
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
|
|
||||||
@echo
|
|
||||||
@echo "The overview file is in $(BUILDDIR)/changes."
|
|
||||||
|
|
||||||
linkcheck:
|
|
||||||
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
|
|
||||||
@echo
|
|
||||||
@echo "Link check complete; look for any errors in the above output " \
|
|
||||||
"or in $(BUILDDIR)/linkcheck/output.txt."
|
|
||||||
|
|
||||||
doctest:
|
|
||||||
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
|
|
||||||
@echo "Testing of doctests in the sources finished, look at the " \
|
|
||||||
"results in $(BUILDDIR)/doctest/output.txt."
|
|
||||||
|
|
||||||
xml:
|
|
||||||
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
|
|
||||||
@echo
|
|
||||||
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
|
|
||||||
|
|
||||||
pseudoxml:
|
|
||||||
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
|
|
||||||
@echo
|
|
||||||
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
|
|
||||||
71
docs/conf.py
71
docs/conf.py
@@ -1,71 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
#
|
|
||||||
# youtube-dl documentation build configuration file, created by
|
|
||||||
# sphinx-quickstart on Fri Mar 14 21:05:43 2014.
|
|
||||||
#
|
|
||||||
# This file is execfile()d with the current directory set to its
|
|
||||||
# containing dir.
|
|
||||||
#
|
|
||||||
# Note that not all possible configuration values are present in this
|
|
||||||
# autogenerated file.
|
|
||||||
#
|
|
||||||
# All configuration values have a default; values that are commented out
|
|
||||||
# serve to show the default.
|
|
||||||
|
|
||||||
import sys
|
|
||||||
import os
|
|
||||||
# Allows to import youtube_dl
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
||||||
|
|
||||||
# -- General configuration ------------------------------------------------
|
|
||||||
|
|
||||||
# Add any Sphinx extension module names here, as strings. They can be
|
|
||||||
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
|
|
||||||
# ones.
|
|
||||||
extensions = [
|
|
||||||
'sphinx.ext.autodoc',
|
|
||||||
]
|
|
||||||
|
|
||||||
# Add any paths that contain templates here, relative to this directory.
|
|
||||||
templates_path = ['_templates']
|
|
||||||
|
|
||||||
# The suffix of source filenames.
|
|
||||||
source_suffix = '.rst'
|
|
||||||
|
|
||||||
# The master toctree document.
|
|
||||||
master_doc = 'index'
|
|
||||||
|
|
||||||
# General information about the project.
|
|
||||||
project = u'youtube-dl'
|
|
||||||
copyright = u'2014, Ricardo Garcia Gonzalez'
|
|
||||||
|
|
||||||
# The version info for the project you're documenting, acts as replacement for
|
|
||||||
# |version| and |release|, also used in various other places throughout the
|
|
||||||
# built documents.
|
|
||||||
#
|
|
||||||
# The short X.Y version.
|
|
||||||
import youtube_dl
|
|
||||||
version = youtube_dl.__version__
|
|
||||||
# The full version, including alpha/beta/rc tags.
|
|
||||||
release = version
|
|
||||||
|
|
||||||
# List of patterns, relative to source directory, that match files and
|
|
||||||
# directories to ignore when looking for source files.
|
|
||||||
exclude_patterns = ['_build']
|
|
||||||
|
|
||||||
# The name of the Pygments (syntax highlighting) style to use.
|
|
||||||
pygments_style = 'sphinx'
|
|
||||||
|
|
||||||
# -- Options for HTML output ----------------------------------------------
|
|
||||||
|
|
||||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
|
||||||
# a list of builtin themes.
|
|
||||||
html_theme = 'default'
|
|
||||||
|
|
||||||
# Add any paths that contain custom static files (such as style sheets) here,
|
|
||||||
# relative to this directory. They are copied after the builtin static files,
|
|
||||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
|
||||||
html_static_path = ['_static']
|
|
||||||
|
|
||||||
# Output file base name for HTML help builder.
|
|
||||||
htmlhelp_basename = 'youtube-dldoc'
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
Welcome to youtube-dl's documentation!
|
|
||||||
======================================
|
|
||||||
|
|
||||||
*youtube-dl* is a command-line program to download videos from YouTube.com and more sites.
|
|
||||||
It can also be used in Python code.
|
|
||||||
|
|
||||||
Developer guide
|
|
||||||
---------------
|
|
||||||
|
|
||||||
This section contains information for using *youtube-dl* from Python programs.
|
|
||||||
|
|
||||||
.. toctree::
|
|
||||||
:maxdepth: 2
|
|
||||||
|
|
||||||
module_guide
|
|
||||||
|
|
||||||
Indices and tables
|
|
||||||
==================
|
|
||||||
|
|
||||||
* :ref:`genindex`
|
|
||||||
* :ref:`modindex`
|
|
||||||
* :ref:`search`
|
|
||||||
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
Using the ``youtube_dl`` module
|
|
||||||
===============================
|
|
||||||
|
|
||||||
When using the ``youtube_dl`` module, you start by creating an instance of :class:`YoutubeDL` and adding all the available extractors:
|
|
||||||
|
|
||||||
.. code-block:: python
|
|
||||||
|
|
||||||
>>> from youtube_dl import YoutubeDL
|
|
||||||
>>> ydl = YoutubeDL()
|
|
||||||
>>> ydl.add_default_info_extractors()
|
|
||||||
|
|
||||||
Extracting video information
|
|
||||||
----------------------------
|
|
||||||
|
|
||||||
You use the :meth:`YoutubeDL.extract_info` method for getting the video information, which returns a dictionary:
|
|
||||||
|
|
||||||
.. code-block:: python
|
|
||||||
|
|
||||||
>>> info = ydl.extract_info('http://www.youtube.com/watch?v=BaW_jenozKc', download=False)
|
|
||||||
[youtube] Setting language
|
|
||||||
[youtube] BaW_jenozKc: Downloading webpage
|
|
||||||
[youtube] BaW_jenozKc: Downloading video info webpage
|
|
||||||
[youtube] BaW_jenozKc: Extracting video information
|
|
||||||
>>> info['title']
|
|
||||||
'youtube-dl test video "\'/\\ä↭𝕐'
|
|
||||||
>>> info['height'], info['width']
|
|
||||||
(720, 1280)
|
|
||||||
|
|
||||||
If you want to download or play the video you can get its url:
|
|
||||||
|
|
||||||
.. code-block:: python
|
|
||||||
|
|
||||||
>>> info['url']
|
|
||||||
'https://...'
|
|
||||||
|
|
||||||
Extracting playlist information
|
|
||||||
-------------------------------
|
|
||||||
|
|
||||||
The playlist information is extracted in a similar way, but the dictionary is a bit different:
|
|
||||||
|
|
||||||
.. code-block:: python
|
|
||||||
|
|
||||||
>>> playlist = ydl.extract_info('http://www.ted.com/playlists/13/open_source_open_world', download=False)
|
|
||||||
[TED] open_source_open_world: Downloading playlist webpage
|
|
||||||
...
|
|
||||||
>>> playlist['title']
|
|
||||||
'Open-source, open world'
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
You can access the videos in the playlist with the ``entries`` field:
|
|
||||||
|
|
||||||
.. code-block:: python
|
|
||||||
|
|
||||||
>>> for video in playlist['entries']:
|
|
||||||
... print('Video #%d: %s' % (video['playlist_index'], video['title']))
|
|
||||||
|
|
||||||
Video #1: How Arduino is open-sourcing imagination
|
|
||||||
Video #2: The year open data went worldwide
|
|
||||||
Video #3: Massive-scale online collaboration
|
|
||||||
Video #4: The art of asking
|
|
||||||
Video #5: How cognitive surplus will change the world
|
|
||||||
Video #6: The birth of Wikipedia
|
|
||||||
Video #7: Coding a better government
|
|
||||||
Video #8: The era of open innovation
|
|
||||||
Video #9: The currency of the new economy is trust
|
|
||||||
|
|
||||||
29
setup.py
29
setup.py
@@ -3,9 +3,7 @@
|
|||||||
|
|
||||||
from __future__ import print_function
|
from __future__ import print_function
|
||||||
|
|
||||||
import os.path
|
|
||||||
import pkg_resources
|
import pkg_resources
|
||||||
import warnings
|
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -46,24 +44,12 @@ py2exe_params = {
|
|||||||
if len(sys.argv) >= 2 and sys.argv[1] == 'py2exe':
|
if len(sys.argv) >= 2 and sys.argv[1] == 'py2exe':
|
||||||
params = py2exe_params
|
params = py2exe_params
|
||||||
else:
|
else:
|
||||||
files_spec = [
|
|
||||||
('etc/bash_completion.d', ['youtube-dl.bash-completion']),
|
|
||||||
('share/doc/youtube_dl', ['README.txt']),
|
|
||||||
('share/man/man1', ['youtube-dl.1'])
|
|
||||||
]
|
|
||||||
root = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
data_files = []
|
|
||||||
for dirname, files in files_spec:
|
|
||||||
resfiles = []
|
|
||||||
for fn in files:
|
|
||||||
if not os.path.exists(fn):
|
|
||||||
warnings.warn('Skipping file %s since it is not present. Type make to build all automatically generated files.' % fn)
|
|
||||||
else:
|
|
||||||
resfiles.append(fn)
|
|
||||||
data_files.append((dirname, resfiles))
|
|
||||||
|
|
||||||
params = {
|
params = {
|
||||||
'data_files': data_files,
|
'data_files': [ # Installing system-wide would require sudo...
|
||||||
|
('etc/bash_completion.d', ['youtube-dl.bash-completion']),
|
||||||
|
('share/doc/youtube_dl', ['README.txt']),
|
||||||
|
('share/man/man1', ['youtube-dl.1'])
|
||||||
|
]
|
||||||
}
|
}
|
||||||
if setuptools_available:
|
if setuptools_available:
|
||||||
params['entry_points'] = {'console_scripts': ['youtube-dl = youtube_dl:main']}
|
params['entry_points'] = {'console_scripts': ['youtube-dl = youtube_dl:main']}
|
||||||
@@ -85,10 +71,7 @@ setup(
|
|||||||
author_email='ytdl@yt-dl.org',
|
author_email='ytdl@yt-dl.org',
|
||||||
maintainer='Philipp Hagemeister',
|
maintainer='Philipp Hagemeister',
|
||||||
maintainer_email='phihag@phihag.de',
|
maintainer_email='phihag@phihag.de',
|
||||||
packages=[
|
packages=['youtube_dl', 'youtube_dl.extractor'],
|
||||||
'youtube_dl',
|
|
||||||
'youtube_dl.extractor', 'youtube_dl.downloader',
|
|
||||||
'youtube_dl.postprocessor'],
|
|
||||||
|
|
||||||
# Provokes warning on most systems (why?!)
|
# Provokes warning on most systems (why?!)
|
||||||
# test_suite = 'nose.collector',
|
# test_suite = 'nose.collector',
|
||||||
|
|||||||
@@ -9,10 +9,7 @@ import sys
|
|||||||
|
|
||||||
import youtube_dl.extractor
|
import youtube_dl.extractor
|
||||||
from youtube_dl import YoutubeDL
|
from youtube_dl import YoutubeDL
|
||||||
from youtube_dl.utils import (
|
from youtube_dl.utils import preferredencoding
|
||||||
compat_str,
|
|
||||||
preferredencoding,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def get_params(override=None):
|
def get_params(override=None):
|
||||||
@@ -74,77 +71,15 @@ class FakeYDL(YoutubeDL):
|
|||||||
old_report_warning(message)
|
old_report_warning(message)
|
||||||
self.report_warning = types.MethodType(report_warning, self)
|
self.report_warning = types.MethodType(report_warning, self)
|
||||||
|
|
||||||
|
def get_testcases():
|
||||||
def gettestcases(include_onlymatching=False):
|
|
||||||
for ie in youtube_dl.extractor.gen_extractors():
|
for ie in youtube_dl.extractor.gen_extractors():
|
||||||
t = getattr(ie, '_TEST', None)
|
t = getattr(ie, '_TEST', None)
|
||||||
if t:
|
if t:
|
||||||
assert not hasattr(ie, '_TESTS'), \
|
t['name'] = type(ie).__name__[:-len('IE')]
|
||||||
'%s has _TEST and _TESTS' % type(ie).__name__
|
yield t
|
||||||
tests = [t]
|
for t in getattr(ie, '_TESTS', []):
|
||||||
else:
|
|
||||||
tests = getattr(ie, '_TESTS', [])
|
|
||||||
for t in tests:
|
|
||||||
if not include_onlymatching and t.get('only_matching', False):
|
|
||||||
continue
|
|
||||||
t['name'] = type(ie).__name__[:-len('IE')]
|
t['name'] = type(ie).__name__[:-len('IE')]
|
||||||
yield t
|
yield t
|
||||||
|
|
||||||
|
|
||||||
md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()
|
md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
def expect_info_dict(self, expected_dict, got_dict):
|
|
||||||
for info_field, expected in expected_dict.items():
|
|
||||||
if isinstance(expected, compat_str) and expected.startswith('re:'):
|
|
||||||
got = got_dict.get(info_field)
|
|
||||||
match_str = expected[len('re:'):]
|
|
||||||
match_rex = re.compile(match_str)
|
|
||||||
|
|
||||||
self.assertTrue(
|
|
||||||
isinstance(got, compat_str) and match_rex.match(got),
|
|
||||||
u'field %s (value: %r) should match %r' % (info_field, got, match_str))
|
|
||||||
elif isinstance(expected, type):
|
|
||||||
got = got_dict.get(info_field)
|
|
||||||
self.assertTrue(isinstance(got, expected),
|
|
||||||
u'Expected type %r for field %s, but got value %r of type %r' % (expected, info_field, got, type(got)))
|
|
||||||
else:
|
|
||||||
if isinstance(expected, compat_str) and expected.startswith('md5:'):
|
|
||||||
got = 'md5:' + md5(got_dict.get(info_field))
|
|
||||||
else:
|
|
||||||
got = got_dict.get(info_field)
|
|
||||||
self.assertEqual(expected, got,
|
|
||||||
u'invalid value for field %s, expected %r, got %r' % (info_field, expected, got))
|
|
||||||
|
|
||||||
# Check for the presence of mandatory fields
|
|
||||||
for key in ('id', 'url', 'title', 'ext'):
|
|
||||||
self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
|
|
||||||
# Check for mandatory fields that are automatically set by YoutubeDL
|
|
||||||
for key in ['webpage_url', 'extractor', 'extractor_key']:
|
|
||||||
self.assertTrue(got_dict.get(key), u'Missing field: %s' % key)
|
|
||||||
|
|
||||||
# Are checkable fields missing from the test case definition?
|
|
||||||
test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
|
|
||||||
for key, value in got_dict.items()
|
|
||||||
if value and key in ('title', 'description', 'uploader', 'upload_date', 'timestamp', 'uploader_id', 'location'))
|
|
||||||
missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
|
|
||||||
if missing_keys:
|
|
||||||
sys.stderr.write(u'\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=4) + u'\n')
|
|
||||||
self.assertFalse(
|
|
||||||
missing_keys,
|
|
||||||
'Missing keys in test definition: %s' % (
|
|
||||||
', '.join(sorted(missing_keys))))
|
|
||||||
|
|
||||||
|
|
||||||
def assertRegexpMatches(self, text, regexp, msg=None):
|
|
||||||
if hasattr(self, 'assertRegexpMatches'):
|
|
||||||
return self.assertRegexpMatches(text, regexp, msg)
|
|
||||||
else:
|
|
||||||
m = re.match(regexp, text)
|
|
||||||
if not m:
|
|
||||||
note = 'Regexp didn\'t match: %r not found in %r' % (regexp, text)
|
|
||||||
if msg is None:
|
|
||||||
msg = note
|
|
||||||
else:
|
|
||||||
msg = note + ', ' + msg
|
|
||||||
self.assertTrue(m, msg)
|
|
||||||
|
|||||||
@@ -39,6 +39,5 @@
|
|||||||
"writeinfojson": true,
|
"writeinfojson": true,
|
||||||
"writesubtitles": false,
|
"writesubtitles": false,
|
||||||
"allsubtitles": false,
|
"allsubtitles": false,
|
||||||
"listssubtitles": false,
|
"listssubtitles": false
|
||||||
"socket_timeout": 20
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
#!/usr/bin/env python
|
|
||||||
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
# Allow direct execution
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import unittest
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
||||||
|
|
||||||
from test.helper import FakeYDL
|
|
||||||
from youtube_dl.extractor.common import InfoExtractor
|
|
||||||
from youtube_dl.extractor import YoutubeIE, get_info_extractor
|
|
||||||
|
|
||||||
|
|
||||||
class TestIE(InfoExtractor):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class TestInfoExtractor(unittest.TestCase):
|
|
||||||
def setUp(self):
|
|
||||||
self.ie = TestIE(FakeYDL())
|
|
||||||
|
|
||||||
def test_ie_key(self):
|
|
||||||
self.assertEqual(get_info_extractor(YoutubeIE.ie_key()), YoutubeIE)
|
|
||||||
|
|
||||||
def test_html_search_regex(self):
|
|
||||||
html = '<p id="foo">Watch this <a href="http://www.youtube.com/watch?v=BaW_jenozKc">video</a></p>'
|
|
||||||
search = lambda re, *args: self.ie._html_search_regex(re, html, *args)
|
|
||||||
self.assertEqual(search(r'<p id="foo">(.+?)</p>', 'foo'), 'Watch this video')
|
|
||||||
|
|
||||||
def test_opengraph(self):
|
|
||||||
ie = self.ie
|
|
||||||
html = '''
|
|
||||||
<meta name="og:title" content='Foo'/>
|
|
||||||
<meta content="Some video's description " name="og:description"/>
|
|
||||||
<meta property='og:image' content='http://domain.com/pic.jpg?key1=val1&key2=val2'/>
|
|
||||||
'''
|
|
||||||
self.assertEqual(ie._og_search_title(html), 'Foo')
|
|
||||||
self.assertEqual(ie._og_search_description(html), 'Some video\'s description ')
|
|
||||||
self.assertEqual(ie._og_search_thumbnail(html), 'http://domain.com/pic.jpg?key1=val1&key2=val2')
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
unittest.main()
|
|
||||||
@@ -1,16 +1,12 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
# Allow direct execution
|
# Allow direct execution
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
from test.helper import FakeYDL, assertRegexpMatches
|
from test.helper import FakeYDL
|
||||||
from youtube_dl import YoutubeDL
|
|
||||||
from youtube_dl.extractor import YoutubeIE
|
|
||||||
|
|
||||||
|
|
||||||
class YDL(FakeYDL):
|
class YDL(FakeYDL):
|
||||||
@@ -26,227 +22,111 @@ class YDL(FakeYDL):
|
|||||||
self.msgs.append(msg)
|
self.msgs.append(msg)
|
||||||
|
|
||||||
|
|
||||||
def _make_result(formats, **kwargs):
|
|
||||||
res = {
|
|
||||||
'formats': formats,
|
|
||||||
'id': 'testid',
|
|
||||||
'title': 'testttitle',
|
|
||||||
'extractor': 'testex',
|
|
||||||
}
|
|
||||||
res.update(**kwargs)
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
class TestFormatSelection(unittest.TestCase):
|
class TestFormatSelection(unittest.TestCase):
|
||||||
def test_prefer_free_formats(self):
|
def test_prefer_free_formats(self):
|
||||||
# Same resolution => download webm
|
# Same resolution => download webm
|
||||||
ydl = YDL()
|
ydl = YDL()
|
||||||
ydl.params['prefer_free_formats'] = True
|
ydl.params['prefer_free_formats'] = True
|
||||||
formats = [
|
formats = [
|
||||||
{'ext': 'webm', 'height': 460, 'url': 'x'},
|
{u'ext': u'webm', u'height': 460},
|
||||||
{'ext': 'mp4', 'height': 460, 'url': 'y'},
|
{u'ext': u'mp4', u'height': 460},
|
||||||
]
|
]
|
||||||
info_dict = _make_result(formats)
|
info_dict = {u'formats': formats, u'extractor': u'test'}
|
||||||
yie = YoutubeIE(ydl)
|
|
||||||
yie._sort_formats(info_dict['formats'])
|
|
||||||
ydl.process_ie_result(info_dict)
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['ext'], 'webm')
|
self.assertEqual(downloaded[u'ext'], u'webm')
|
||||||
|
|
||||||
# Different resolution => download best quality (mp4)
|
# Different resolution => download best quality (mp4)
|
||||||
ydl = YDL()
|
ydl = YDL()
|
||||||
ydl.params['prefer_free_formats'] = True
|
ydl.params['prefer_free_formats'] = True
|
||||||
formats = [
|
formats = [
|
||||||
{'ext': 'webm', 'height': 720, 'url': 'a'},
|
{u'ext': u'webm', u'height': 720},
|
||||||
{'ext': 'mp4', 'height': 1080, 'url': 'b'},
|
{u'ext': u'mp4', u'height': 1080},
|
||||||
]
|
]
|
||||||
info_dict['formats'] = formats
|
info_dict[u'formats'] = formats
|
||||||
yie = YoutubeIE(ydl)
|
|
||||||
yie._sort_formats(info_dict['formats'])
|
|
||||||
ydl.process_ie_result(info_dict)
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['ext'], 'mp4')
|
self.assertEqual(downloaded[u'ext'], u'mp4')
|
||||||
|
|
||||||
# No prefer_free_formats => prefer mp4 and flv for greater compatibilty
|
# No prefer_free_formats => keep original formats order
|
||||||
ydl = YDL()
|
ydl = YDL()
|
||||||
ydl.params['prefer_free_formats'] = False
|
ydl.params['prefer_free_formats'] = False
|
||||||
formats = [
|
formats = [
|
||||||
{'ext': 'webm', 'height': 720, 'url': '_'},
|
{u'ext': u'webm', u'height': 720},
|
||||||
{'ext': 'mp4', 'height': 720, 'url': '_'},
|
{u'ext': u'flv', u'height': 720},
|
||||||
{'ext': 'flv', 'height': 720, 'url': '_'},
|
|
||||||
]
|
]
|
||||||
info_dict['formats'] = formats
|
info_dict[u'formats'] = formats
|
||||||
yie = YoutubeIE(ydl)
|
|
||||||
yie._sort_formats(info_dict['formats'])
|
|
||||||
ydl.process_ie_result(info_dict)
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['ext'], 'mp4')
|
self.assertEqual(downloaded[u'ext'], u'flv')
|
||||||
|
|
||||||
ydl = YDL()
|
|
||||||
ydl.params['prefer_free_formats'] = False
|
|
||||||
formats = [
|
|
||||||
{'ext': 'flv', 'height': 720, 'url': '_'},
|
|
||||||
{'ext': 'webm', 'height': 720, 'url': '_'},
|
|
||||||
]
|
|
||||||
info_dict['formats'] = formats
|
|
||||||
yie = YoutubeIE(ydl)
|
|
||||||
yie._sort_formats(info_dict['formats'])
|
|
||||||
ydl.process_ie_result(info_dict)
|
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
|
||||||
self.assertEqual(downloaded['ext'], 'flv')
|
|
||||||
|
|
||||||
def test_format_limit(self):
|
def test_format_limit(self):
|
||||||
formats = [
|
formats = [
|
||||||
{'format_id': 'meh', 'url': 'http://example.com/meh', 'preference': 1},
|
{u'format_id': u'meh', u'url': u'http://example.com/meh'},
|
||||||
{'format_id': 'good', 'url': 'http://example.com/good', 'preference': 2},
|
{u'format_id': u'good', u'url': u'http://example.com/good'},
|
||||||
{'format_id': 'great', 'url': 'http://example.com/great', 'preference': 3},
|
{u'format_id': u'great', u'url': u'http://example.com/great'},
|
||||||
{'format_id': 'excellent', 'url': 'http://example.com/exc', 'preference': 4},
|
{u'format_id': u'excellent', u'url': u'http://example.com/exc'},
|
||||||
]
|
]
|
||||||
info_dict = _make_result(formats)
|
info_dict = {
|
||||||
|
u'formats': formats, u'extractor': u'test', 'id': 'testvid'}
|
||||||
|
|
||||||
ydl = YDL()
|
ydl = YDL()
|
||||||
ydl.process_ie_result(info_dict)
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['format_id'], 'excellent')
|
self.assertEqual(downloaded[u'format_id'], u'excellent')
|
||||||
|
|
||||||
ydl = YDL({'format_limit': 'good'})
|
ydl = YDL({'format_limit': 'good'})
|
||||||
assert ydl.params['format_limit'] == 'good'
|
assert ydl.params['format_limit'] == 'good'
|
||||||
ydl.process_ie_result(info_dict.copy())
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['format_id'], 'good')
|
self.assertEqual(downloaded[u'format_id'], u'good')
|
||||||
|
|
||||||
ydl = YDL({'format_limit': 'great', 'format': 'all'})
|
ydl = YDL({'format_limit': 'great', 'format': 'all'})
|
||||||
ydl.process_ie_result(info_dict.copy())
|
ydl.process_ie_result(info_dict)
|
||||||
self.assertEqual(ydl.downloaded_info_dicts[0]['format_id'], 'meh')
|
self.assertEqual(ydl.downloaded_info_dicts[0][u'format_id'], u'meh')
|
||||||
self.assertEqual(ydl.downloaded_info_dicts[1]['format_id'], 'good')
|
self.assertEqual(ydl.downloaded_info_dicts[1][u'format_id'], u'good')
|
||||||
self.assertEqual(ydl.downloaded_info_dicts[2]['format_id'], 'great')
|
self.assertEqual(ydl.downloaded_info_dicts[2][u'format_id'], u'great')
|
||||||
self.assertTrue('3' in ydl.msgs[0])
|
self.assertTrue('3' in ydl.msgs[0])
|
||||||
|
|
||||||
ydl = YDL()
|
ydl = YDL()
|
||||||
ydl.params['format_limit'] = 'excellent'
|
ydl.params['format_limit'] = 'excellent'
|
||||||
ydl.process_ie_result(info_dict.copy())
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['format_id'], 'excellent')
|
self.assertEqual(downloaded[u'format_id'], u'excellent')
|
||||||
|
|
||||||
def test_format_selection(self):
|
def test_format_selection(self):
|
||||||
formats = [
|
formats = [
|
||||||
{'format_id': '35', 'ext': 'mp4', 'preference': 1, 'url': '_'},
|
{u'format_id': u'35', u'ext': u'mp4'},
|
||||||
{'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': '_'},
|
{u'format_id': u'45', u'ext': u'webm'},
|
||||||
{'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': '_'},
|
{u'format_id': u'47', u'ext': u'webm'},
|
||||||
{'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': '_'},
|
{u'format_id': u'2', u'ext': u'flv'},
|
||||||
]
|
]
|
||||||
info_dict = _make_result(formats)
|
info_dict = {u'formats': formats, u'extractor': u'test'}
|
||||||
|
|
||||||
ydl = YDL({'format': '20/47'})
|
ydl = YDL({'format': u'20/47'})
|
||||||
ydl.process_ie_result(info_dict.copy())
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['format_id'], '47')
|
self.assertEqual(downloaded['format_id'], u'47')
|
||||||
|
|
||||||
ydl = YDL({'format': '20/71/worst'})
|
ydl = YDL({'format': u'20/71/worst'})
|
||||||
ydl.process_ie_result(info_dict.copy())
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['format_id'], '35')
|
self.assertEqual(downloaded['format_id'], u'35')
|
||||||
|
|
||||||
ydl = YDL()
|
ydl = YDL()
|
||||||
ydl.process_ie_result(info_dict.copy())
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['format_id'], '2')
|
self.assertEqual(downloaded['format_id'], u'2')
|
||||||
|
|
||||||
ydl = YDL({'format': 'webm/mp4'})
|
ydl = YDL({'format': u'webm/mp4'})
|
||||||
ydl.process_ie_result(info_dict.copy())
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['format_id'], '47')
|
self.assertEqual(downloaded['format_id'], u'47')
|
||||||
|
|
||||||
ydl = YDL({'format': '3gp/40/mp4'})
|
ydl = YDL({'format': u'3gp/40/mp4'})
|
||||||
ydl.process_ie_result(info_dict.copy())
|
ydl.process_ie_result(info_dict)
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
downloaded = ydl.downloaded_info_dicts[0]
|
||||||
self.assertEqual(downloaded['format_id'], '35')
|
self.assertEqual(downloaded['format_id'], u'35')
|
||||||
|
|
||||||
def test_format_selection_audio(self):
|
|
||||||
formats = [
|
|
||||||
{'format_id': 'audio-low', 'ext': 'webm', 'preference': 1, 'vcodec': 'none', 'url': '_'},
|
|
||||||
{'format_id': 'audio-mid', 'ext': 'webm', 'preference': 2, 'vcodec': 'none', 'url': '_'},
|
|
||||||
{'format_id': 'audio-high', 'ext': 'flv', 'preference': 3, 'vcodec': 'none', 'url': '_'},
|
|
||||||
{'format_id': 'vid', 'ext': 'mp4', 'preference': 4, 'url': '_'},
|
|
||||||
]
|
|
||||||
info_dict = _make_result(formats)
|
|
||||||
|
|
||||||
ydl = YDL({'format': 'bestaudio'})
|
|
||||||
ydl.process_ie_result(info_dict.copy())
|
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
|
||||||
self.assertEqual(downloaded['format_id'], 'audio-high')
|
|
||||||
|
|
||||||
ydl = YDL({'format': 'worstaudio'})
|
|
||||||
ydl.process_ie_result(info_dict.copy())
|
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
|
||||||
self.assertEqual(downloaded['format_id'], 'audio-low')
|
|
||||||
|
|
||||||
formats = [
|
|
||||||
{'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': '_'},
|
|
||||||
{'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': '_'},
|
|
||||||
]
|
|
||||||
info_dict = _make_result(formats)
|
|
||||||
|
|
||||||
ydl = YDL({'format': 'bestaudio/worstaudio/best'})
|
|
||||||
ydl.process_ie_result(info_dict.copy())
|
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
|
||||||
self.assertEqual(downloaded['format_id'], 'vid-high')
|
|
||||||
|
|
||||||
def test_format_selection_video(self):
|
|
||||||
formats = [
|
|
||||||
{'format_id': 'dash-video-low', 'ext': 'mp4', 'preference': 1, 'acodec': 'none', 'url': '_'},
|
|
||||||
{'format_id': 'dash-video-high', 'ext': 'mp4', 'preference': 2, 'acodec': 'none', 'url': '_'},
|
|
||||||
{'format_id': 'vid', 'ext': 'mp4', 'preference': 3, 'url': '_'},
|
|
||||||
]
|
|
||||||
info_dict = _make_result(formats)
|
|
||||||
|
|
||||||
ydl = YDL({'format': 'bestvideo'})
|
|
||||||
ydl.process_ie_result(info_dict.copy())
|
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
|
||||||
self.assertEqual(downloaded['format_id'], 'dash-video-high')
|
|
||||||
|
|
||||||
ydl = YDL({'format': 'worstvideo'})
|
|
||||||
ydl.process_ie_result(info_dict.copy())
|
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
|
||||||
self.assertEqual(downloaded['format_id'], 'dash-video-low')
|
|
||||||
|
|
||||||
def test_youtube_format_selection(self):
|
|
||||||
order = [
|
|
||||||
'38', '37', '46', '22', '45', '35', '44', '18', '34', '43', '6', '5', '36', '17', '13',
|
|
||||||
# Apple HTTP Live Streaming
|
|
||||||
'96', '95', '94', '93', '92', '132', '151',
|
|
||||||
# 3D
|
|
||||||
'85', '84', '102', '83', '101', '82', '100',
|
|
||||||
# Dash video
|
|
||||||
'138', '137', '248', '136', '247', '135', '246',
|
|
||||||
'245', '244', '134', '243', '133', '242', '160',
|
|
||||||
# Dash audio
|
|
||||||
'141', '172', '140', '139', '171',
|
|
||||||
]
|
|
||||||
|
|
||||||
for f1id, f2id in zip(order, order[1:]):
|
|
||||||
f1 = YoutubeIE._formats[f1id].copy()
|
|
||||||
f1['format_id'] = f1id
|
|
||||||
f1['url'] = 'url:' + f1id
|
|
||||||
f2 = YoutubeIE._formats[f2id].copy()
|
|
||||||
f2['format_id'] = f2id
|
|
||||||
f2['url'] = 'url:' + f2id
|
|
||||||
|
|
||||||
info_dict = _make_result([f1, f2], extractor='youtube')
|
|
||||||
ydl = YDL()
|
|
||||||
yie = YoutubeIE(ydl)
|
|
||||||
yie._sort_formats(info_dict['formats'])
|
|
||||||
ydl.process_ie_result(info_dict)
|
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
|
||||||
self.assertEqual(downloaded['format_id'], f1id)
|
|
||||||
|
|
||||||
info_dict = _make_result([f2, f1], extractor='youtube')
|
|
||||||
ydl = YDL()
|
|
||||||
yie = YoutubeIE(ydl)
|
|
||||||
yie._sort_formats(info_dict['formats'])
|
|
||||||
ydl.process_ie_result(info_dict)
|
|
||||||
downloaded = ydl.downloaded_info_dicts[0]
|
|
||||||
self.assertEqual(downloaded['format_id'], f1id)
|
|
||||||
|
|
||||||
def test_add_extra_info(self):
|
def test_add_extra_info(self):
|
||||||
test_dict = {
|
test_dict = {
|
||||||
@@ -260,26 +140,6 @@ class TestFormatSelection(unittest.TestCase):
|
|||||||
self.assertEqual(test_dict['extractor'], 'Foo')
|
self.assertEqual(test_dict['extractor'], 'Foo')
|
||||||
self.assertEqual(test_dict['playlist'], 'funny videos')
|
self.assertEqual(test_dict['playlist'], 'funny videos')
|
||||||
|
|
||||||
def test_prepare_filename(self):
|
|
||||||
info = {
|
|
||||||
'id': '1234',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'width': None,
|
|
||||||
}
|
|
||||||
def fname(templ):
|
|
||||||
ydl = YoutubeDL({'outtmpl': templ})
|
|
||||||
return ydl.prepare_filename(info)
|
|
||||||
self.assertEqual(fname('%(id)s.%(ext)s'), '1234.mp4')
|
|
||||||
self.assertEqual(fname('%(id)s-%(width)s.%(ext)s'), '1234-NA.mp4')
|
|
||||||
# Replace missing fields with 'NA'
|
|
||||||
self.assertEqual(fname('%(uploader_date)s-%(id)s.%(ext)s'), 'NA-1234.mp4')
|
|
||||||
|
|
||||||
def test_format_note(self):
|
|
||||||
ydl = YoutubeDL()
|
|
||||||
self.assertEqual(ydl._format_note({}), '')
|
|
||||||
assertRegexpMatches(self, ydl._format_note({
|
|
||||||
'vbr': 10,
|
|
||||||
}), '^x\s*10k$')
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
# Allow direct execution
|
# Allow direct execution
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
@@ -9,13 +7,11 @@ import unittest
|
|||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
|
||||||
from test.helper import gettestcases
|
from test.helper import get_testcases
|
||||||
|
|
||||||
from youtube_dl.extractor import (
|
from youtube_dl.extractor import (
|
||||||
FacebookIE,
|
|
||||||
gen_extractors,
|
gen_extractors,
|
||||||
JustinTVIE,
|
JustinTVIE,
|
||||||
PBSIE,
|
|
||||||
YoutubeIE,
|
YoutubeIE,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -32,24 +28,21 @@ class TestAllURLsMatching(unittest.TestCase):
|
|||||||
|
|
||||||
def test_youtube_playlist_matching(self):
|
def test_youtube_playlist_matching(self):
|
||||||
assertPlaylist = lambda url: self.assertMatch(url, ['youtube:playlist'])
|
assertPlaylist = lambda url: self.assertMatch(url, ['youtube:playlist'])
|
||||||
assertPlaylist('ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8')
|
assertPlaylist(u'ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8')
|
||||||
assertPlaylist('UUBABnxM4Ar9ten8Mdjj1j0Q') #585
|
assertPlaylist(u'UUBABnxM4Ar9ten8Mdjj1j0Q') #585
|
||||||
assertPlaylist('PL63F0C78739B09958')
|
assertPlaylist(u'PL63F0C78739B09958')
|
||||||
assertPlaylist('https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q')
|
assertPlaylist(u'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q')
|
||||||
assertPlaylist('https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8')
|
assertPlaylist(u'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8')
|
||||||
assertPlaylist('https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC')
|
assertPlaylist(u'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC')
|
||||||
assertPlaylist('https://www.youtube.com/watch?v=AV6J6_AeFEQ&playnext=1&list=PL4023E734DA416012') #668
|
assertPlaylist(u'https://www.youtube.com/watch?v=AV6J6_AeFEQ&playnext=1&list=PL4023E734DA416012') #668
|
||||||
self.assertFalse('youtube:playlist' in self.matching_ies('PLtS2H6bU1M'))
|
self.assertFalse('youtube:playlist' in self.matching_ies(u'PLtS2H6bU1M'))
|
||||||
# Top tracks
|
|
||||||
assertPlaylist('https://www.youtube.com/playlist?list=MCUS.20142101')
|
|
||||||
|
|
||||||
def test_youtube_matching(self):
|
def test_youtube_matching(self):
|
||||||
self.assertTrue(YoutubeIE.suitable('PLtS2H6bU1M'))
|
self.assertTrue(YoutubeIE.suitable(u'PLtS2H6bU1M'))
|
||||||
self.assertFalse(YoutubeIE.suitable('https://www.youtube.com/watch?v=AV6J6_AeFEQ&playnext=1&list=PL4023E734DA416012')) #668
|
self.assertFalse(YoutubeIE.suitable(u'https://www.youtube.com/watch?v=AV6J6_AeFEQ&playnext=1&list=PL4023E734DA416012')) #668
|
||||||
self.assertMatch('http://youtu.be/BaW_jenozKc', ['youtube'])
|
self.assertMatch('http://youtu.be/BaW_jenozKc', ['youtube'])
|
||||||
self.assertMatch('http://www.youtube.com/v/BaW_jenozKc', ['youtube'])
|
self.assertMatch('http://www.youtube.com/v/BaW_jenozKc', ['youtube'])
|
||||||
self.assertMatch('https://youtube.googleapis.com/v/BaW_jenozKc', ['youtube'])
|
self.assertMatch('https://youtube.googleapis.com/v/BaW_jenozKc', ['youtube'])
|
||||||
self.assertMatch('http://www.cleanvideosearch.com/media/action/yt/watch?videoId=8v_4O44sfjM', ['youtube'])
|
|
||||||
|
|
||||||
def test_youtube_channel_matching(self):
|
def test_youtube_channel_matching(self):
|
||||||
assertChannel = lambda url: self.assertMatch(url, ['youtube:channel'])
|
assertChannel = lambda url: self.assertMatch(url, ['youtube:channel'])
|
||||||
@@ -69,31 +62,24 @@ class TestAllURLsMatching(unittest.TestCase):
|
|||||||
def test_youtube_show_matching(self):
|
def test_youtube_show_matching(self):
|
||||||
self.assertMatch('http://www.youtube.com/show/airdisasters', ['youtube:show'])
|
self.assertMatch('http://www.youtube.com/show/airdisasters', ['youtube:show'])
|
||||||
|
|
||||||
def test_youtube_truncated(self):
|
|
||||||
self.assertMatch('http://www.youtube.com/watch?', ['youtube:truncated_url'])
|
|
||||||
|
|
||||||
def test_youtube_search_matching(self):
|
|
||||||
self.assertMatch('http://www.youtube.com/results?search_query=making+mustard', ['youtube:search_url'])
|
|
||||||
self.assertMatch('https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video', ['youtube:search_url'])
|
|
||||||
|
|
||||||
def test_justin_tv_channelid_matching(self):
|
def test_justin_tv_channelid_matching(self):
|
||||||
self.assertTrue(JustinTVIE.suitable('justin.tv/vanillatv'))
|
self.assertTrue(JustinTVIE.suitable(u"justin.tv/vanillatv"))
|
||||||
self.assertTrue(JustinTVIE.suitable('twitch.tv/vanillatv'))
|
self.assertTrue(JustinTVIE.suitable(u"twitch.tv/vanillatv"))
|
||||||
self.assertTrue(JustinTVIE.suitable('www.justin.tv/vanillatv'))
|
self.assertTrue(JustinTVIE.suitable(u"www.justin.tv/vanillatv"))
|
||||||
self.assertTrue(JustinTVIE.suitable('www.twitch.tv/vanillatv'))
|
self.assertTrue(JustinTVIE.suitable(u"www.twitch.tv/vanillatv"))
|
||||||
self.assertTrue(JustinTVIE.suitable('http://www.justin.tv/vanillatv'))
|
self.assertTrue(JustinTVIE.suitable(u"http://www.justin.tv/vanillatv"))
|
||||||
self.assertTrue(JustinTVIE.suitable('http://www.twitch.tv/vanillatv'))
|
self.assertTrue(JustinTVIE.suitable(u"http://www.twitch.tv/vanillatv"))
|
||||||
self.assertTrue(JustinTVIE.suitable('http://www.justin.tv/vanillatv/'))
|
self.assertTrue(JustinTVIE.suitable(u"http://www.justin.tv/vanillatv/"))
|
||||||
self.assertTrue(JustinTVIE.suitable('http://www.twitch.tv/vanillatv/'))
|
self.assertTrue(JustinTVIE.suitable(u"http://www.twitch.tv/vanillatv/"))
|
||||||
|
|
||||||
def test_justintv_videoid_matching(self):
|
def test_justintv_videoid_matching(self):
|
||||||
self.assertTrue(JustinTVIE.suitable('http://www.twitch.tv/vanillatv/b/328087483'))
|
self.assertTrue(JustinTVIE.suitable(u"http://www.twitch.tv/vanillatv/b/328087483"))
|
||||||
|
|
||||||
def test_justin_tv_chapterid_matching(self):
|
def test_justin_tv_chapterid_matching(self):
|
||||||
self.assertTrue(JustinTVIE.suitable('http://www.twitch.tv/tsm_theoddone/c/2349361'))
|
self.assertTrue(JustinTVIE.suitable(u"http://www.twitch.tv/tsm_theoddone/c/2349361"))
|
||||||
|
|
||||||
def test_youtube_extract(self):
|
def test_youtube_extract(self):
|
||||||
assertExtractId = lambda url, id: self.assertEqual(YoutubeIE.extract_id(url), id)
|
assertExtractId = lambda url, id: self.assertEqual(YoutubeIE()._extract_id(url), id)
|
||||||
assertExtractId('http://www.youtube.com/watch?&v=BaW_jenozKc', 'BaW_jenozKc')
|
assertExtractId('http://www.youtube.com/watch?&v=BaW_jenozKc', 'BaW_jenozKc')
|
||||||
assertExtractId('https://www.youtube.com/watch?&v=BaW_jenozKc', 'BaW_jenozKc')
|
assertExtractId('https://www.youtube.com/watch?&v=BaW_jenozKc', 'BaW_jenozKc')
|
||||||
assertExtractId('https://www.youtube.com/watch?feature=player_embedded&v=BaW_jenozKc', 'BaW_jenozKc')
|
assertExtractId('https://www.youtube.com/watch?feature=player_embedded&v=BaW_jenozKc', 'BaW_jenozKc')
|
||||||
@@ -101,15 +87,12 @@ class TestAllURLsMatching(unittest.TestCase):
|
|||||||
assertExtractId('http://www.youtube.com/watch?v=BaW_jenozKcsharePLED17F32AD9753930', 'BaW_jenozKc')
|
assertExtractId('http://www.youtube.com/watch?v=BaW_jenozKcsharePLED17F32AD9753930', 'BaW_jenozKc')
|
||||||
assertExtractId('BaW_jenozKc', 'BaW_jenozKc')
|
assertExtractId('BaW_jenozKc', 'BaW_jenozKc')
|
||||||
|
|
||||||
def test_facebook_matching(self):
|
|
||||||
self.assertTrue(FacebookIE.suitable('https://www.facebook.com/Shiniknoh#!/photo.php?v=10153317450565268'))
|
|
||||||
|
|
||||||
def test_no_duplicates(self):
|
def test_no_duplicates(self):
|
||||||
ies = gen_extractors()
|
ies = gen_extractors()
|
||||||
for tc in gettestcases(include_onlymatching=True):
|
for tc in get_testcases():
|
||||||
url = tc['url']
|
url = tc['url']
|
||||||
for ie in ies:
|
for ie in ies:
|
||||||
if type(ie).__name__ in ('GenericIE', tc['name'] + 'IE'):
|
if type(ie).__name__ in ['GenericIE', tc['name'] + 'IE']:
|
||||||
self.assertTrue(ie.suitable(url), '%s should match URL %r' % (type(ie).__name__, url))
|
self.assertTrue(ie.suitable(url), '%s should match URL %r' % (type(ie).__name__, url))
|
||||||
else:
|
else:
|
||||||
self.assertFalse(ie.suitable(url), '%s should not match URL %r' % (type(ie).__name__, url))
|
self.assertFalse(ie.suitable(url), '%s should not match URL %r' % (type(ie).__name__, url))
|
||||||
@@ -123,59 +106,6 @@ class TestAllURLsMatching(unittest.TestCase):
|
|||||||
self.assertMatch(':colbertreport', ['ComedyCentralShows'])
|
self.assertMatch(':colbertreport', ['ComedyCentralShows'])
|
||||||
self.assertMatch(':cr', ['ComedyCentralShows'])
|
self.assertMatch(':cr', ['ComedyCentralShows'])
|
||||||
|
|
||||||
def test_vimeo_matching(self):
|
|
||||||
self.assertMatch('http://vimeo.com/channels/tributes', ['vimeo:channel'])
|
|
||||||
self.assertMatch('http://vimeo.com/channels/31259', ['vimeo:channel'])
|
|
||||||
self.assertMatch('http://vimeo.com/channels/31259/53576664', ['vimeo'])
|
|
||||||
self.assertMatch('http://vimeo.com/user7108434', ['vimeo:user'])
|
|
||||||
self.assertMatch('http://vimeo.com/user7108434/videos', ['vimeo:user'])
|
|
||||||
self.assertMatch('https://vimeo.com/user21297594/review/75524534/3c257a1b5d', ['vimeo:review'])
|
|
||||||
|
|
||||||
# https://github.com/rg3/youtube-dl/issues/1930
|
|
||||||
def test_soundcloud_not_matching_sets(self):
|
|
||||||
self.assertMatch('http://soundcloud.com/floex/sets/gone-ep', ['soundcloud:set'])
|
|
||||||
|
|
||||||
def test_tumblr(self):
|
|
||||||
self.assertMatch('http://tatianamaslanydaily.tumblr.com/post/54196191430/orphan-black-dvd-extra-behind-the-scenes', ['Tumblr'])
|
|
||||||
self.assertMatch('http://tatianamaslanydaily.tumblr.com/post/54196191430', ['Tumblr'])
|
|
||||||
|
|
||||||
def test_pbs(self):
|
|
||||||
# https://github.com/rg3/youtube-dl/issues/2350
|
|
||||||
self.assertMatch('http://video.pbs.org/viralplayer/2365173446/', ['PBS'])
|
|
||||||
self.assertMatch('http://video.pbs.org/widget/partnerplayer/980042464/', ['PBS'])
|
|
||||||
|
|
||||||
def test_ComedyCentralShows(self):
|
|
||||||
self.assertMatch(
|
|
||||||
'http://thedailyshow.cc.com/extended-interviews/xm3fnq/andrew-napolitano-extended-interview',
|
|
||||||
['ComedyCentralShows'])
|
|
||||||
self.assertMatch(
|
|
||||||
'http://thecolbertreport.cc.com/videos/29w6fx/-realhumanpraise-for-fox-news',
|
|
||||||
['ComedyCentralShows'])
|
|
||||||
self.assertMatch(
|
|
||||||
'http://thecolbertreport.cc.com/videos/gh6urb/neil-degrasse-tyson-pt--1?xrs=eml_col_031114',
|
|
||||||
['ComedyCentralShows'])
|
|
||||||
self.assertMatch(
|
|
||||||
'http://thedailyshow.cc.com/guests/michael-lewis/3efna8/exclusive---michael-lewis-extended-interview-pt--3',
|
|
||||||
['ComedyCentralShows'])
|
|
||||||
self.assertMatch(
|
|
||||||
'http://thedailyshow.cc.com/episodes/sy7yv0/april-8--2014---denis-leary',
|
|
||||||
['ComedyCentralShows'])
|
|
||||||
self.assertMatch(
|
|
||||||
'http://thecolbertreport.cc.com/episodes/8ase07/april-8--2014---jane-goodall',
|
|
||||||
['ComedyCentralShows'])
|
|
||||||
self.assertMatch(
|
|
||||||
'http://thedailyshow.cc.com/video-playlists/npde3s/the-daily-show-19088-highlights',
|
|
||||||
['ComedyCentralShows'])
|
|
||||||
self.assertMatch(
|
|
||||||
'http://thedailyshow.cc.com/special-editions/2l8fdb/special-edition---a-look-back-at-food',
|
|
||||||
['ComedyCentralShows'])
|
|
||||||
|
|
||||||
def test_yahoo_https(self):
|
|
||||||
# https://github.com/rg3/youtube-dl/issues/2701
|
|
||||||
self.assertMatch(
|
|
||||||
'https://screen.yahoo.com/smartwatches-latest-wearable-gadgets-163745379-cbs.html',
|
|
||||||
['Yahoo'])
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -8,11 +8,10 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|||||||
|
|
||||||
from test.helper import (
|
from test.helper import (
|
||||||
get_params,
|
get_params,
|
||||||
gettestcases,
|
get_testcases,
|
||||||
expect_info_dict,
|
|
||||||
md5,
|
|
||||||
try_rm,
|
try_rm,
|
||||||
report_warning,
|
md5,
|
||||||
|
report_warning
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -23,7 +22,6 @@ import socket
|
|||||||
|
|
||||||
import youtube_dl.YoutubeDL
|
import youtube_dl.YoutubeDL
|
||||||
from youtube_dl.utils import (
|
from youtube_dl.utils import (
|
||||||
compat_http_client,
|
|
||||||
compat_str,
|
compat_str,
|
||||||
compat_urllib_error,
|
compat_urllib_error,
|
||||||
compat_HTTPError,
|
compat_HTTPError,
|
||||||
@@ -51,7 +49,7 @@ def _file_md5(fn):
|
|||||||
with open(fn, 'rb') as f:
|
with open(fn, 'rb') as f:
|
||||||
return hashlib.md5(f.read()).hexdigest()
|
return hashlib.md5(f.read()).hexdigest()
|
||||||
|
|
||||||
defs = gettestcases()
|
defs = get_testcases()
|
||||||
|
|
||||||
|
|
||||||
class TestDownload(unittest.TestCase):
|
class TestDownload(unittest.TestCase):
|
||||||
@@ -73,7 +71,9 @@ def generator(test_case):
|
|||||||
if 'playlist' not in test_case:
|
if 'playlist' not in test_case:
|
||||||
info_dict = test_case.get('info_dict', {})
|
info_dict = test_case.get('info_dict', {})
|
||||||
if not test_case.get('file') and not (info_dict.get('id') and info_dict.get('ext')):
|
if not test_case.get('file') and not (info_dict.get('id') and info_dict.get('ext')):
|
||||||
raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
|
print_skipping('The output file cannot be know, the "file" '
|
||||||
|
'key is missing or the info_dict is incomplete')
|
||||||
|
return
|
||||||
if 'skip' in test_case:
|
if 'skip' in test_case:
|
||||||
print_skipping(test_case['skip'])
|
print_skipping(test_case['skip'])
|
||||||
return
|
return
|
||||||
@@ -90,7 +90,7 @@ def generator(test_case):
|
|||||||
def _hook(status):
|
def _hook(status):
|
||||||
if status['status'] == 'finished':
|
if status['status'] == 'finished':
|
||||||
finished_hook_called.add(status['filename'])
|
finished_hook_called.add(status['filename'])
|
||||||
ydl.add_progress_hook(_hook)
|
ydl.fd.add_progress_hook(_hook)
|
||||||
|
|
||||||
def get_tc_filename(tc):
|
def get_tc_filename(tc):
|
||||||
return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
|
return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
|
||||||
@@ -110,7 +110,7 @@ def generator(test_case):
|
|||||||
ydl.download([test_case['url']])
|
ydl.download([test_case['url']])
|
||||||
except (DownloadError, ExtractorError) as err:
|
except (DownloadError, ExtractorError) as err:
|
||||||
# Check if the exception is not a network related one
|
# Check if the exception is not a network related one
|
||||||
if not err.exc_info[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError, compat_http_client.BadStatusLine) or (err.exc_info[0] == compat_HTTPError and err.exc_info[1].code == 503):
|
if not err.exc_info[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError) or (err.exc_info[0] == compat_HTTPError and err.exc_info[1].code == 503):
|
||||||
raise
|
raise
|
||||||
|
|
||||||
if try_num == RETRIES:
|
if try_num == RETRIES:
|
||||||
@@ -135,8 +135,27 @@ def generator(test_case):
|
|||||||
self.assertEqual(md5_for_file, tc['md5'])
|
self.assertEqual(md5_for_file, tc['md5'])
|
||||||
with io.open(info_json_fn, encoding='utf-8') as infof:
|
with io.open(info_json_fn, encoding='utf-8') as infof:
|
||||||
info_dict = json.load(infof)
|
info_dict = json.load(infof)
|
||||||
|
for (info_field, expected) in tc.get('info_dict', {}).items():
|
||||||
|
if isinstance(expected, compat_str) and expected.startswith('md5:'):
|
||||||
|
got = 'md5:' + md5(info_dict.get(info_field))
|
||||||
|
else:
|
||||||
|
got = info_dict.get(info_field)
|
||||||
|
self.assertEqual(expected, got,
|
||||||
|
u'invalid value for field %s, expected %r, got %r' % (info_field, expected, got))
|
||||||
|
|
||||||
expect_info_dict(self, tc.get('info_dict', {}), info_dict)
|
# If checkable fields are missing from the test case, print the info_dict
|
||||||
|
test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
|
||||||
|
for key, value in info_dict.items()
|
||||||
|
if value and key in ('title', 'description', 'uploader', 'upload_date', 'uploader_id', 'location'))
|
||||||
|
if not all(key in tc.get('info_dict', {}).keys() for key in test_info_dict.keys()):
|
||||||
|
sys.stderr.write(u'\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=2) + u'\n')
|
||||||
|
|
||||||
|
# Check for the presence of mandatory fields
|
||||||
|
for key in ('id', 'url', 'title', 'ext'):
|
||||||
|
self.assertTrue(key in info_dict.keys() and info_dict[key])
|
||||||
|
# Check for mandatory fields that are automatically set by YoutubeDL
|
||||||
|
for key in ['webpage_url', 'extractor', 'extractor_key']:
|
||||||
|
self.assertTrue(info_dict.get(key), u'Missing field: %s' % key)
|
||||||
finally:
|
finally:
|
||||||
try_rm_tcs_files()
|
try_rm_tcs_files()
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
# encoding: utf-8
|
# encoding: utf-8
|
||||||
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
# Allow direct execution
|
# Allow direct execution
|
||||||
import os
|
import os
|
||||||
@@ -9,44 +8,20 @@ import sys
|
|||||||
import unittest
|
import unittest
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
from test.helper import (
|
from test.helper import FakeYDL
|
||||||
assertRegexpMatches,
|
|
||||||
expect_info_dict,
|
|
||||||
FakeYDL,
|
|
||||||
)
|
|
||||||
|
|
||||||
from youtube_dl.extractor import (
|
from youtube_dl.extractor import (
|
||||||
AcademicEarthCourseIE,
|
|
||||||
DailymotionPlaylistIE,
|
DailymotionPlaylistIE,
|
||||||
DailymotionUserIE,
|
DailymotionUserIE,
|
||||||
VimeoChannelIE,
|
VimeoChannelIE,
|
||||||
VimeoUserIE,
|
|
||||||
VimeoAlbumIE,
|
|
||||||
VimeoGroupsIE,
|
|
||||||
VineUserIE,
|
|
||||||
UstreamChannelIE,
|
UstreamChannelIE,
|
||||||
SoundcloudSetIE,
|
SoundcloudSetIE,
|
||||||
SoundcloudUserIE,
|
SoundcloudUserIE,
|
||||||
SoundcloudPlaylistIE,
|
|
||||||
LivestreamIE,
|
LivestreamIE,
|
||||||
NHLVideocenterIE,
|
NHLVideocenterIE,
|
||||||
BambuserChannelIE,
|
BambuserChannelIE,
|
||||||
BandcampAlbumIE,
|
BandcampAlbumIE
|
||||||
SmotriCommunityIE,
|
|
||||||
SmotriUserIE,
|
|
||||||
IviCompilationIE,
|
|
||||||
ImdbListIE,
|
|
||||||
KhanAcademyIE,
|
|
||||||
EveryonesMixtapeIE,
|
|
||||||
RutubeChannelIE,
|
|
||||||
GoogleSearchIE,
|
|
||||||
GenericIE,
|
|
||||||
TEDIE,
|
|
||||||
ToypicsUserIE,
|
|
||||||
XTubeUserIE,
|
|
||||||
InstagramUserIE,
|
|
||||||
CSpanIE,
|
|
||||||
AolIE,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -60,70 +35,39 @@ class TestPlaylists(unittest.TestCase):
|
|||||||
ie = DailymotionPlaylistIE(dl)
|
ie = DailymotionPlaylistIE(dl)
|
||||||
result = ie.extract('http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q')
|
result = ie.extract('http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['title'], 'SPORT')
|
self.assertEqual(result['title'], u'SPORT')
|
||||||
self.assertTrue(len(result['entries']) > 20)
|
self.assertTrue(len(result['entries']) > 20)
|
||||||
|
|
||||||
def test_dailymotion_user(self):
|
def test_dailymotion_user(self):
|
||||||
dl = FakeYDL()
|
dl = FakeYDL()
|
||||||
ie = DailymotionUserIE(dl)
|
ie = DailymotionUserIE(dl)
|
||||||
result = ie.extract('https://www.dailymotion.com/user/nqtv')
|
result = ie.extract('http://www.dailymotion.com/user/generation-quoi/')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['title'], 'Rémi Gaillard')
|
self.assertEqual(result['title'], u'Génération Quoi')
|
||||||
self.assertTrue(len(result['entries']) >= 100)
|
self.assertTrue(len(result['entries']) >= 26)
|
||||||
|
|
||||||
def test_vimeo_channel(self):
|
def test_vimeo_channel(self):
|
||||||
dl = FakeYDL()
|
dl = FakeYDL()
|
||||||
ie = VimeoChannelIE(dl)
|
ie = VimeoChannelIE(dl)
|
||||||
result = ie.extract('http://vimeo.com/channels/tributes')
|
result = ie.extract('http://vimeo.com/channels/tributes')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['title'], 'Vimeo Tributes')
|
self.assertEqual(result['title'], u'Vimeo Tributes')
|
||||||
self.assertTrue(len(result['entries']) > 24)
|
self.assertTrue(len(result['entries']) > 24)
|
||||||
|
|
||||||
def test_vimeo_user(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = VimeoUserIE(dl)
|
|
||||||
result = ie.extract('http://vimeo.com/nkistudio/videos')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['title'], 'Nki')
|
|
||||||
self.assertTrue(len(result['entries']) > 65)
|
|
||||||
|
|
||||||
def test_vimeo_album(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = VimeoAlbumIE(dl)
|
|
||||||
result = ie.extract('http://vimeo.com/album/2632481')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['title'], 'Staff Favorites: November 2013')
|
|
||||||
self.assertTrue(len(result['entries']) > 12)
|
|
||||||
|
|
||||||
def test_vimeo_groups(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = VimeoGroupsIE(dl)
|
|
||||||
result = ie.extract('http://vimeo.com/groups/rolexawards')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['title'], 'Rolex Awards for Enterprise')
|
|
||||||
self.assertTrue(len(result['entries']) > 72)
|
|
||||||
|
|
||||||
def test_vine_user(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = VineUserIE(dl)
|
|
||||||
result = ie.extract('https://vine.co/Visa')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertTrue(len(result['entries']) >= 50)
|
|
||||||
|
|
||||||
def test_ustream_channel(self):
|
def test_ustream_channel(self):
|
||||||
dl = FakeYDL()
|
dl = FakeYDL()
|
||||||
ie = UstreamChannelIE(dl)
|
ie = UstreamChannelIE(dl)
|
||||||
result = ie.extract('http://www.ustream.tv/channel/young-americans-for-liberty')
|
result = ie.extract('http://www.ustream.tv/channel/young-americans-for-liberty')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['id'], '5124905')
|
self.assertEqual(result['id'], u'5124905')
|
||||||
self.assertTrue(len(result['entries']) >= 6)
|
self.assertTrue(len(result['entries']) >= 11)
|
||||||
|
|
||||||
def test_soundcloud_set(self):
|
def test_soundcloud_set(self):
|
||||||
dl = FakeYDL()
|
dl = FakeYDL()
|
||||||
ie = SoundcloudSetIE(dl)
|
ie = SoundcloudSetIE(dl)
|
||||||
result = ie.extract('https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep')
|
result = ie.extract('https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['title'], 'The Royal Concept EP')
|
self.assertEqual(result['title'], u'The Royal Concept EP')
|
||||||
self.assertTrue(len(result['entries']) >= 6)
|
self.assertTrue(len(result['entries']) >= 6)
|
||||||
|
|
||||||
def test_soundcloud_user(self):
|
def test_soundcloud_user(self):
|
||||||
@@ -131,26 +75,15 @@ class TestPlaylists(unittest.TestCase):
|
|||||||
ie = SoundcloudUserIE(dl)
|
ie = SoundcloudUserIE(dl)
|
||||||
result = ie.extract('https://soundcloud.com/the-concept-band')
|
result = ie.extract('https://soundcloud.com/the-concept-band')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['id'], '9615865')
|
self.assertEqual(result['id'], u'9615865')
|
||||||
self.assertTrue(len(result['entries']) >= 12)
|
self.assertTrue(len(result['entries']) >= 12)
|
||||||
|
|
||||||
def test_soundcloud_playlist(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = SoundcloudPlaylistIE(dl)
|
|
||||||
result = ie.extract('http://api.soundcloud.com/playlists/4110309')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], '4110309')
|
|
||||||
self.assertEqual(result['title'], 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]')
|
|
||||||
assertRegexpMatches(
|
|
||||||
self, result['description'], r'TILT Brass - Bowery Poetry Club')
|
|
||||||
self.assertEqual(len(result['entries']), 6)
|
|
||||||
|
|
||||||
def test_livestream_event(self):
|
def test_livestream_event(self):
|
||||||
dl = FakeYDL()
|
dl = FakeYDL()
|
||||||
ie = LivestreamIE(dl)
|
ie = LivestreamIE(dl)
|
||||||
result = ie.extract('http://new.livestream.com/tedx/cityenglish')
|
result = ie.extract('http://new.livestream.com/tedx/cityenglish')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['title'], 'TEDCity2.0 (English)')
|
self.assertEqual(result['title'], u'TEDCity2.0 (English)')
|
||||||
self.assertTrue(len(result['entries']) >= 4)
|
self.assertTrue(len(result['entries']) >= 4)
|
||||||
|
|
||||||
def test_nhl_videocenter(self):
|
def test_nhl_videocenter(self):
|
||||||
@@ -158,8 +91,8 @@ class TestPlaylists(unittest.TestCase):
|
|||||||
ie = NHLVideocenterIE(dl)
|
ie = NHLVideocenterIE(dl)
|
||||||
result = ie.extract('http://video.canucks.nhl.com/videocenter/console?catid=999')
|
result = ie.extract('http://video.canucks.nhl.com/videocenter/console?catid=999')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['id'], '999')
|
self.assertEqual(result['id'], u'999')
|
||||||
self.assertEqual(result['title'], 'Highlights')
|
self.assertEqual(result['title'], u'Highlights')
|
||||||
self.assertEqual(len(result['entries']), 12)
|
self.assertEqual(len(result['entries']), 12)
|
||||||
|
|
||||||
def test_bambuser_channel(self):
|
def test_bambuser_channel(self):
|
||||||
@@ -167,7 +100,7 @@ class TestPlaylists(unittest.TestCase):
|
|||||||
ie = BambuserChannelIE(dl)
|
ie = BambuserChannelIE(dl)
|
||||||
result = ie.extract('http://bambuser.com/channel/pixelversity')
|
result = ie.extract('http://bambuser.com/channel/pixelversity')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['title'], 'pixelversity')
|
self.assertEqual(result['title'], u'pixelversity')
|
||||||
self.assertTrue(len(result['entries']) >= 60)
|
self.assertTrue(len(result['entries']) >= 60)
|
||||||
|
|
||||||
def test_bandcamp_album(self):
|
def test_bandcamp_album(self):
|
||||||
@@ -175,190 +108,8 @@ class TestPlaylists(unittest.TestCase):
|
|||||||
ie = BandcampAlbumIE(dl)
|
ie = BandcampAlbumIE(dl)
|
||||||
result = ie.extract('http://mpallante.bandcamp.com/album/nightmare-night-ep')
|
result = ie.extract('http://mpallante.bandcamp.com/album/nightmare-night-ep')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['title'], 'Nightmare Night EP')
|
self.assertEqual(result['title'], u'Nightmare Night EP')
|
||||||
self.assertTrue(len(result['entries']) >= 4)
|
self.assertTrue(len(result['entries']) >= 4)
|
||||||
|
|
||||||
def test_smotri_community(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = SmotriCommunityIE(dl)
|
|
||||||
result = ie.extract('http://smotri.com/community/video/kommuna')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'kommuna')
|
|
||||||
self.assertEqual(result['title'], 'КПРФ')
|
|
||||||
self.assertTrue(len(result['entries']) >= 4)
|
|
||||||
|
|
||||||
def test_smotri_user(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = SmotriUserIE(dl)
|
|
||||||
result = ie.extract('http://smotri.com/user/inspector')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'inspector')
|
|
||||||
self.assertEqual(result['title'], 'Inspector')
|
|
||||||
self.assertTrue(len(result['entries']) >= 9)
|
|
||||||
|
|
||||||
def test_AcademicEarthCourse(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = AcademicEarthCourseIE(dl)
|
|
||||||
result = ie.extract('http://academicearth.org/playlists/laws-of-nature/')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'laws-of-nature')
|
|
||||||
self.assertEqual(result['title'], 'Laws of Nature')
|
|
||||||
self.assertEqual(result['description'],u'Introduce yourself to the laws of nature with these free online college lectures from Yale, Harvard, and MIT.')# u"Today's websites are increasingly dynamic. Pages are no longer static HTML files but instead generated by scripts and database calls. User interfaces are more seamless, with technologies like Ajax replacing traditional page reloads. This course teaches students how to build dynamic websites with Ajax and with Linux, Apache, MySQL, and PHP (LAMP), one of today's most popular frameworks. Students learn how to set up domain names with DNS, how to structure pages with XHTML and CSS, how to program in JavaScript and PHP, how to configure Apache and MySQL, how to design and query databases with SQL, how to use Ajax with both XML and JSON, and how to build mashups. The course explores issues of security, scalability, and cross-browser support and also discusses enterprise-level deployments of websites, including third-party hosting, virtualization, colocation in data centers, firewalling, and load-balancing.")
|
|
||||||
self.assertEqual(len(result['entries']), 4)
|
|
||||||
|
|
||||||
def test_ivi_compilation(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = IviCompilationIE(dl)
|
|
||||||
result = ie.extract('http://www.ivi.ru/watch/dezhurnyi_angel')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'dezhurnyi_angel')
|
|
||||||
self.assertEqual(result['title'], 'Дежурный ангел (2010 - 2012)')
|
|
||||||
self.assertTrue(len(result['entries']) >= 23)
|
|
||||||
|
|
||||||
def test_ivi_compilation_season(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = IviCompilationIE(dl)
|
|
||||||
result = ie.extract('http://www.ivi.ru/watch/dezhurnyi_angel/season2')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'dezhurnyi_angel/season2')
|
|
||||||
self.assertEqual(result['title'], 'Дежурный ангел (2010 - 2012) 2 сезон')
|
|
||||||
self.assertTrue(len(result['entries']) >= 7)
|
|
||||||
|
|
||||||
def test_imdb_list(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = ImdbListIE(dl)
|
|
||||||
result = ie.extract('http://www.imdb.com/list/JFs9NWw6XI0')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'JFs9NWw6XI0')
|
|
||||||
self.assertEqual(result['title'], 'March 23, 2012 Releases')
|
|
||||||
self.assertEqual(len(result['entries']), 7)
|
|
||||||
|
|
||||||
def test_khanacademy_topic(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = KhanAcademyIE(dl)
|
|
||||||
result = ie.extract('https://www.khanacademy.org/math/applied-math/cryptography')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'cryptography')
|
|
||||||
self.assertEqual(result['title'], 'Journey into cryptography')
|
|
||||||
self.assertEqual(result['description'], 'How have humans protected their secret messages through history? What has changed today?')
|
|
||||||
self.assertTrue(len(result['entries']) >= 3)
|
|
||||||
|
|
||||||
def test_EveryonesMixtape(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = EveryonesMixtapeIE(dl)
|
|
||||||
result = ie.extract('http://everyonesmixtape.com/#/mix/m7m0jJAbMQi')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'm7m0jJAbMQi')
|
|
||||||
self.assertEqual(result['title'], 'Driving')
|
|
||||||
self.assertEqual(len(result['entries']), 24)
|
|
||||||
|
|
||||||
def test_rutube_channel(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = RutubeChannelIE(dl)
|
|
||||||
result = ie.extract('http://rutube.ru/tags/video/1409')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], '1409')
|
|
||||||
self.assertTrue(len(result['entries']) >= 34)
|
|
||||||
|
|
||||||
def test_multiple_brightcove_videos(self):
|
|
||||||
# https://github.com/rg3/youtube-dl/issues/2283
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = GenericIE(dl)
|
|
||||||
result = ie.extract('http://www.newyorker.com/online/blogs/newsdesk/2014/01/always-never-nuclear-command-and-control.html')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'always-never-nuclear-command-and-control')
|
|
||||||
self.assertEqual(result['title'], 'Always/Never: A Little-Seen Movie About Nuclear Command and Control : The New Yorker')
|
|
||||||
self.assertEqual(len(result['entries']), 3)
|
|
||||||
|
|
||||||
def test_GoogleSearch(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = GoogleSearchIE(dl)
|
|
||||||
result = ie.extract('gvsearch15:python language')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'python language')
|
|
||||||
self.assertEqual(result['title'], 'python language')
|
|
||||||
self.assertEqual(len(result['entries']), 15)
|
|
||||||
|
|
||||||
def test_generic_rss_feed(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = GenericIE(dl)
|
|
||||||
result = ie.extract('http://phihag.de/2014/youtube-dl/rss.xml')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'http://phihag.de/2014/youtube-dl/rss.xml')
|
|
||||||
self.assertEqual(result['title'], 'Zero Punctuation')
|
|
||||||
self.assertTrue(len(result['entries']) > 10)
|
|
||||||
|
|
||||||
def test_ted_playlist(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = TEDIE(dl)
|
|
||||||
result = ie.extract('http://www.ted.com/playlists/who_are_the_hackers')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], '10')
|
|
||||||
self.assertEqual(result['title'], 'Who are the hackers?')
|
|
||||||
self.assertTrue(len(result['entries']) >= 6)
|
|
||||||
|
|
||||||
def test_toypics_user(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = ToypicsUserIE(dl)
|
|
||||||
result = ie.extract('http://videos.toypics.net/Mikey')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'Mikey')
|
|
||||||
self.assertTrue(len(result['entries']) >= 17)
|
|
||||||
|
|
||||||
def test_xtube_user(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = XTubeUserIE(dl)
|
|
||||||
result = ie.extract('http://www.xtube.com/community/profile.php?user=greenshowers')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'greenshowers')
|
|
||||||
self.assertTrue(len(result['entries']) >= 155)
|
|
||||||
|
|
||||||
def test_InstagramUser(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = InstagramUserIE(dl)
|
|
||||||
result = ie.extract('http://instagram.com/porsche')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], 'porsche')
|
|
||||||
self.assertTrue(len(result['entries']) >= 2)
|
|
||||||
test_video = next(
|
|
||||||
e for e in result['entries']
|
|
||||||
if e['id'] == '614605558512799803_462752227')
|
|
||||||
dl.add_default_extra_info(test_video, ie, '(irrelevant URL)')
|
|
||||||
dl.process_video_result(test_video, download=False)
|
|
||||||
EXPECTED = {
|
|
||||||
'id': '614605558512799803_462752227',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': '#Porsche Intelligent Performance.',
|
|
||||||
'thumbnail': 're:^https?://.*\.jpg',
|
|
||||||
'uploader': 'Porsche',
|
|
||||||
'uploader_id': 'porsche',
|
|
||||||
'timestamp': 1387486713,
|
|
||||||
'upload_date': '20131219',
|
|
||||||
}
|
|
||||||
expect_info_dict(self, EXPECTED, test_video)
|
|
||||||
|
|
||||||
def test_CSpan_playlist(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = CSpanIE(dl)
|
|
||||||
result = ie.extract(
|
|
||||||
'http://www.c-span.org/video/?318608-1/gm-ignition-switch-recall')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], '342759')
|
|
||||||
self.assertEqual(
|
|
||||||
result['title'], 'General Motors Ignition Switch Recall')
|
|
||||||
whole_duration = sum(e['duration'] for e in result['entries'])
|
|
||||||
self.assertEqual(whole_duration, 14855)
|
|
||||||
|
|
||||||
def test_aol_playlist(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = AolIE(dl)
|
|
||||||
result = ie.extract(
|
|
||||||
'http://on.aol.com/playlist/brace-yourself---todays-weirdest-news-152147?icid=OnHomepageC4_Omg_Img#_videoid=518184316')
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['id'], '152147')
|
|
||||||
self.assertEqual(
|
|
||||||
result['title'], 'Brace Yourself - Today\'s Weirdest News')
|
|
||||||
self.assertTrue(len(result['entries']) >= 10)
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -10,11 +10,9 @@ from test.helper import FakeYDL, md5
|
|||||||
|
|
||||||
|
|
||||||
from youtube_dl.extractor import (
|
from youtube_dl.extractor import (
|
||||||
BlipTVIE,
|
|
||||||
YoutubeIE,
|
YoutubeIE,
|
||||||
DailymotionIE,
|
DailymotionIE,
|
||||||
TEDIE,
|
TEDIE,
|
||||||
VimeoIE,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -38,6 +36,10 @@ class TestYoutubeSubtitles(BaseTestSubtitles):
|
|||||||
url = 'QRS8MkLhQmM'
|
url = 'QRS8MkLhQmM'
|
||||||
IE = YoutubeIE
|
IE = YoutubeIE
|
||||||
|
|
||||||
|
def getSubtitles(self):
|
||||||
|
info_dict = self.getInfoDict()
|
||||||
|
return info_dict[0]['subtitles']
|
||||||
|
|
||||||
def test_youtube_no_writesubtitles(self):
|
def test_youtube_no_writesubtitles(self):
|
||||||
self.DL.params['writesubtitles'] = False
|
self.DL.params['writesubtitles'] = False
|
||||||
subtitles = self.getSubtitles()
|
subtitles = self.getSubtitles()
|
||||||
@@ -70,7 +72,7 @@ class TestYoutubeSubtitles(BaseTestSubtitles):
|
|||||||
self.DL.params['writesubtitles'] = True
|
self.DL.params['writesubtitles'] = True
|
||||||
self.DL.params['subtitlesformat'] = 'vtt'
|
self.DL.params['subtitlesformat'] = 'vtt'
|
||||||
subtitles = self.getSubtitles()
|
subtitles = self.getSubtitles()
|
||||||
self.assertEqual(md5(subtitles['en']), '3cb210999d3e021bd6c7f0ea751eab06')
|
self.assertEqual(md5(subtitles['en']), '356cdc577fde0c6783b9b822e7206ff7')
|
||||||
|
|
||||||
def test_youtube_list_subtitles(self):
|
def test_youtube_list_subtitles(self):
|
||||||
self.DL.expect_warning(u'Video doesn\'t have automatic captions')
|
self.DL.expect_warning(u'Video doesn\'t have automatic captions')
|
||||||
@@ -169,19 +171,19 @@ class TestTedSubtitles(BaseTestSubtitles):
|
|||||||
def test_subtitles(self):
|
def test_subtitles(self):
|
||||||
self.DL.params['writesubtitles'] = True
|
self.DL.params['writesubtitles'] = True
|
||||||
subtitles = self.getSubtitles()
|
subtitles = self.getSubtitles()
|
||||||
self.assertEqual(md5(subtitles['en']), '4262c1665ff928a2dada178f62cb8d14')
|
self.assertEqual(md5(subtitles['en']), '2154f31ff9b9f89a0aa671537559c21d')
|
||||||
|
|
||||||
def test_subtitles_lang(self):
|
def test_subtitles_lang(self):
|
||||||
self.DL.params['writesubtitles'] = True
|
self.DL.params['writesubtitles'] = True
|
||||||
self.DL.params['subtitleslangs'] = ['fr']
|
self.DL.params['subtitleslangs'] = ['fr']
|
||||||
subtitles = self.getSubtitles()
|
subtitles = self.getSubtitles()
|
||||||
self.assertEqual(md5(subtitles['fr']), '66a63f7f42c97a50f8c0e90bc7797bb5')
|
self.assertEqual(md5(subtitles['fr']), '7616cbc6df20ec2c1204083c83871cf6')
|
||||||
|
|
||||||
def test_allsubtitles(self):
|
def test_allsubtitles(self):
|
||||||
self.DL.params['writesubtitles'] = True
|
self.DL.params['writesubtitles'] = True
|
||||||
self.DL.params['allsubtitles'] = True
|
self.DL.params['allsubtitles'] = True
|
||||||
subtitles = self.getSubtitles()
|
subtitles = self.getSubtitles()
|
||||||
self.assertTrue(len(subtitles.keys()) >= 28)
|
self.assertEqual(len(subtitles.keys()), 28)
|
||||||
|
|
||||||
def test_list_subtitles(self):
|
def test_list_subtitles(self):
|
||||||
self.DL.expect_warning(u'Automatic Captions not supported by this server')
|
self.DL.expect_warning(u'Automatic Captions not supported by this server')
|
||||||
@@ -204,80 +206,5 @@ class TestTedSubtitles(BaseTestSubtitles):
|
|||||||
for lang in langs:
|
for lang in langs:
|
||||||
self.assertTrue(subtitles.get(lang) is not None, u'Subtitles for \'%s\' not extracted' % lang)
|
self.assertTrue(subtitles.get(lang) is not None, u'Subtitles for \'%s\' not extracted' % lang)
|
||||||
|
|
||||||
|
|
||||||
class TestBlipTVSubtitles(BaseTestSubtitles):
|
|
||||||
url = 'http://blip.tv/a/a-6603250'
|
|
||||||
IE = BlipTVIE
|
|
||||||
|
|
||||||
def test_list_subtitles(self):
|
|
||||||
self.DL.expect_warning(u'Automatic Captions not supported by this server')
|
|
||||||
self.DL.params['listsubtitles'] = True
|
|
||||||
info_dict = self.getInfoDict()
|
|
||||||
self.assertEqual(info_dict, None)
|
|
||||||
|
|
||||||
def test_allsubtitles(self):
|
|
||||||
self.DL.expect_warning(u'Automatic Captions not supported by this server')
|
|
||||||
self.DL.params['writesubtitles'] = True
|
|
||||||
self.DL.params['allsubtitles'] = True
|
|
||||||
subtitles = self.getSubtitles()
|
|
||||||
self.assertEqual(set(subtitles.keys()), set(['en']))
|
|
||||||
self.assertEqual(md5(subtitles['en']), '5b75c300af65fe4476dff79478bb93e4')
|
|
||||||
|
|
||||||
|
|
||||||
class TestVimeoSubtitles(BaseTestSubtitles):
|
|
||||||
url = 'http://vimeo.com/76979871'
|
|
||||||
IE = VimeoIE
|
|
||||||
|
|
||||||
def test_no_writesubtitles(self):
|
|
||||||
subtitles = self.getSubtitles()
|
|
||||||
self.assertEqual(subtitles, None)
|
|
||||||
|
|
||||||
def test_subtitles(self):
|
|
||||||
self.DL.params['writesubtitles'] = True
|
|
||||||
subtitles = self.getSubtitles()
|
|
||||||
self.assertEqual(md5(subtitles['en']), '8062383cf4dec168fc40a088aa6d5888')
|
|
||||||
|
|
||||||
def test_subtitles_lang(self):
|
|
||||||
self.DL.params['writesubtitles'] = True
|
|
||||||
self.DL.params['subtitleslangs'] = ['fr']
|
|
||||||
subtitles = self.getSubtitles()
|
|
||||||
self.assertEqual(md5(subtitles['fr']), 'b6191146a6c5d3a452244d853fde6dc8')
|
|
||||||
|
|
||||||
def test_allsubtitles(self):
|
|
||||||
self.DL.params['writesubtitles'] = True
|
|
||||||
self.DL.params['allsubtitles'] = True
|
|
||||||
subtitles = self.getSubtitles()
|
|
||||||
self.assertEqual(set(subtitles.keys()), set(['de', 'en', 'es', 'fr']))
|
|
||||||
|
|
||||||
def test_list_subtitles(self):
|
|
||||||
self.DL.expect_warning(u'Automatic Captions not supported by this server')
|
|
||||||
self.DL.params['listsubtitles'] = True
|
|
||||||
info_dict = self.getInfoDict()
|
|
||||||
self.assertEqual(info_dict, None)
|
|
||||||
|
|
||||||
def test_automatic_captions(self):
|
|
||||||
self.DL.expect_warning(u'Automatic Captions not supported by this server')
|
|
||||||
self.DL.params['writeautomaticsub'] = True
|
|
||||||
self.DL.params['subtitleslang'] = ['en']
|
|
||||||
subtitles = self.getSubtitles()
|
|
||||||
self.assertTrue(len(subtitles.keys()) == 0)
|
|
||||||
|
|
||||||
def test_nosubtitles(self):
|
|
||||||
self.DL.expect_warning(u'video doesn\'t have subtitles')
|
|
||||||
self.url = 'http://vimeo.com/56015672'
|
|
||||||
self.DL.params['writesubtitles'] = True
|
|
||||||
self.DL.params['allsubtitles'] = True
|
|
||||||
subtitles = self.getSubtitles()
|
|
||||||
self.assertEqual(len(subtitles), 0)
|
|
||||||
|
|
||||||
def test_multiple_langs(self):
|
|
||||||
self.DL.params['writesubtitles'] = True
|
|
||||||
langs = ['es', 'fr', 'de']
|
|
||||||
self.DL.params['subtitleslangs'] = langs
|
|
||||||
subtitles = self.getSubtitles()
|
|
||||||
for lang in langs:
|
|
||||||
self.assertTrue(subtitles.get(lang) is not None, u'Subtitles for \'%s\' not extracted' % lang)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import io
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import unittest
|
|
||||||
|
|
||||||
rootDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
|
|
||||||
IGNORED_FILES = [
|
|
||||||
'setup.py', # http://bugs.python.org/issue13943
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
class TestUnicodeLiterals(unittest.TestCase):
|
|
||||||
def test_all_files(self):
|
|
||||||
print('Skipping this test (not yet fully implemented)')
|
|
||||||
return
|
|
||||||
|
|
||||||
for dirpath, _, filenames in os.walk(rootDir):
|
|
||||||
for basename in filenames:
|
|
||||||
if not basename.endswith('.py'):
|
|
||||||
continue
|
|
||||||
if basename in IGNORED_FILES:
|
|
||||||
continue
|
|
||||||
|
|
||||||
fn = os.path.join(dirpath, basename)
|
|
||||||
with io.open(fn, encoding='utf-8') as inf:
|
|
||||||
code = inf.read()
|
|
||||||
|
|
||||||
if "'" not in code and '"' not in code:
|
|
||||||
continue
|
|
||||||
imps = 'from __future__ import unicode_literals'
|
|
||||||
self.assertTrue(
|
|
||||||
imps in code,
|
|
||||||
' %s missing in %s' % (imps, fn))
|
|
||||||
|
|
||||||
m = re.search(r'(?<=\s)u[\'"](?!\)|,|$)', code)
|
|
||||||
if m is not None:
|
|
||||||
self.assertTrue(
|
|
||||||
m is None,
|
|
||||||
'u present in %s, around %s' % (
|
|
||||||
fn, code[m.start() - 10:m.end() + 10]))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
unittest.main()
|
|
||||||
@@ -9,36 +9,23 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|||||||
|
|
||||||
|
|
||||||
# Various small unit tests
|
# Various small unit tests
|
||||||
import io
|
|
||||||
import json
|
|
||||||
import xml.etree.ElementTree
|
import xml.etree.ElementTree
|
||||||
|
|
||||||
#from youtube_dl.utils import htmlentity_transform
|
#from youtube_dl.utils import htmlentity_transform
|
||||||
from youtube_dl.utils import (
|
from youtube_dl.utils import (
|
||||||
DateRange,
|
|
||||||
encodeFilename,
|
|
||||||
find_xpath_attr,
|
|
||||||
fix_xml_ampersands,
|
|
||||||
get_meta_content,
|
|
||||||
orderedSet,
|
|
||||||
PagedList,
|
|
||||||
parse_duration,
|
|
||||||
read_batch_urls,
|
|
||||||
sanitize_filename,
|
|
||||||
shell_quote,
|
|
||||||
smuggle_url,
|
|
||||||
str_to_int,
|
|
||||||
struct_unpack,
|
|
||||||
timeconvert,
|
timeconvert,
|
||||||
|
sanitize_filename,
|
||||||
unescapeHTML,
|
unescapeHTML,
|
||||||
|
orderedSet,
|
||||||
|
DateRange,
|
||||||
unified_strdate,
|
unified_strdate,
|
||||||
unsmuggle_url,
|
find_xpath_attr,
|
||||||
url_basename,
|
get_meta_content,
|
||||||
urlencode_postdata,
|
|
||||||
xpath_with_ns,
|
xpath_with_ns,
|
||||||
parse_iso8601,
|
smuggle_url,
|
||||||
strip_jsonp,
|
unsmuggle_url,
|
||||||
uppercase_escape,
|
shell_quote,
|
||||||
|
encodeFilename,
|
||||||
)
|
)
|
||||||
|
|
||||||
if sys.version_info < (3, 0):
|
if sys.version_info < (3, 0):
|
||||||
@@ -135,7 +122,6 @@ class TestUtil(unittest.TestCase):
|
|||||||
self.assertEqual(unified_strdate('8/7/2009'), '20090708')
|
self.assertEqual(unified_strdate('8/7/2009'), '20090708')
|
||||||
self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
|
self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
|
||||||
self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
|
self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
|
||||||
self.assertEqual(unified_strdate('1968-12-10'), '19681210')
|
|
||||||
|
|
||||||
def test_find_xpath_attr(self):
|
def test_find_xpath_attr(self):
|
||||||
testxml = u'''<root>
|
testxml = u'''<root>
|
||||||
@@ -190,99 +176,6 @@ class TestUtil(unittest.TestCase):
|
|||||||
args = ['ffmpeg', '-i', encodeFilename(u'ñ€ß\'.mp4')]
|
args = ['ffmpeg', '-i', encodeFilename(u'ñ€ß\'.mp4')]
|
||||||
self.assertEqual(shell_quote(args), u"""ffmpeg -i 'ñ€ß'"'"'.mp4'""")
|
self.assertEqual(shell_quote(args), u"""ffmpeg -i 'ñ€ß'"'"'.mp4'""")
|
||||||
|
|
||||||
def test_str_to_int(self):
|
|
||||||
self.assertEqual(str_to_int('123,456'), 123456)
|
|
||||||
self.assertEqual(str_to_int('123.456'), 123456)
|
|
||||||
|
|
||||||
def test_url_basename(self):
|
|
||||||
self.assertEqual(url_basename(u'http://foo.de/'), u'')
|
|
||||||
self.assertEqual(url_basename(u'http://foo.de/bar/baz'), u'baz')
|
|
||||||
self.assertEqual(url_basename(u'http://foo.de/bar/baz?x=y'), u'baz')
|
|
||||||
self.assertEqual(url_basename(u'http://foo.de/bar/baz#x=y'), u'baz')
|
|
||||||
self.assertEqual(url_basename(u'http://foo.de/bar/baz/'), u'baz')
|
|
||||||
self.assertEqual(
|
|
||||||
url_basename(u'http://media.w3.org/2010/05/sintel/trailer.mp4'),
|
|
||||||
u'trailer.mp4')
|
|
||||||
|
|
||||||
def test_parse_duration(self):
|
|
||||||
self.assertEqual(parse_duration(None), None)
|
|
||||||
self.assertEqual(parse_duration('1'), 1)
|
|
||||||
self.assertEqual(parse_duration('1337:12'), 80232)
|
|
||||||
self.assertEqual(parse_duration('9:12:43'), 33163)
|
|
||||||
self.assertEqual(parse_duration('12:00'), 720)
|
|
||||||
self.assertEqual(parse_duration('00:01:01'), 61)
|
|
||||||
self.assertEqual(parse_duration('x:y'), None)
|
|
||||||
self.assertEqual(parse_duration('3h11m53s'), 11513)
|
|
||||||
self.assertEqual(parse_duration('62m45s'), 3765)
|
|
||||||
self.assertEqual(parse_duration('6m59s'), 419)
|
|
||||||
self.assertEqual(parse_duration('49s'), 49)
|
|
||||||
self.assertEqual(parse_duration('0h0m0s'), 0)
|
|
||||||
self.assertEqual(parse_duration('0m0s'), 0)
|
|
||||||
self.assertEqual(parse_duration('0s'), 0)
|
|
||||||
|
|
||||||
def test_fix_xml_ampersands(self):
|
|
||||||
self.assertEqual(
|
|
||||||
fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
|
|
||||||
self.assertEqual(
|
|
||||||
fix_xml_ampersands('"&x=y&wrong;&z=a'),
|
|
||||||
'"&x=y&wrong;&z=a')
|
|
||||||
self.assertEqual(
|
|
||||||
fix_xml_ampersands('&'><"'),
|
|
||||||
'&'><"')
|
|
||||||
self.assertEqual(
|
|
||||||
fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
|
|
||||||
self.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
|
|
||||||
|
|
||||||
def test_paged_list(self):
|
|
||||||
def testPL(size, pagesize, sliceargs, expected):
|
|
||||||
def get_page(pagenum):
|
|
||||||
firstid = pagenum * pagesize
|
|
||||||
upto = min(size, pagenum * pagesize + pagesize)
|
|
||||||
for i in range(firstid, upto):
|
|
||||||
yield i
|
|
||||||
|
|
||||||
pl = PagedList(get_page, pagesize)
|
|
||||||
got = pl.getslice(*sliceargs)
|
|
||||||
self.assertEqual(got, expected)
|
|
||||||
|
|
||||||
testPL(5, 2, (), [0, 1, 2, 3, 4])
|
|
||||||
testPL(5, 2, (1,), [1, 2, 3, 4])
|
|
||||||
testPL(5, 2, (2,), [2, 3, 4])
|
|
||||||
testPL(5, 2, (4,), [4])
|
|
||||||
testPL(5, 2, (0, 3), [0, 1, 2])
|
|
||||||
testPL(5, 2, (1, 4), [1, 2, 3])
|
|
||||||
testPL(5, 2, (2, 99), [2, 3, 4])
|
|
||||||
testPL(5, 2, (20, 99), [])
|
|
||||||
|
|
||||||
def test_struct_unpack(self):
|
|
||||||
self.assertEqual(struct_unpack(u'!B', b'\x00'), (0,))
|
|
||||||
|
|
||||||
def test_read_batch_urls(self):
|
|
||||||
f = io.StringIO(u'''\xef\xbb\xbf foo
|
|
||||||
bar\r
|
|
||||||
baz
|
|
||||||
# More after this line\r
|
|
||||||
; or after this
|
|
||||||
bam''')
|
|
||||||
self.assertEqual(read_batch_urls(f), [u'foo', u'bar', u'baz', u'bam'])
|
|
||||||
|
|
||||||
def test_urlencode_postdata(self):
|
|
||||||
data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
|
|
||||||
self.assertTrue(isinstance(data, bytes))
|
|
||||||
|
|
||||||
def test_parse_iso8601(self):
|
|
||||||
self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
|
|
||||||
self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
|
|
||||||
self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
|
|
||||||
|
|
||||||
def test_strip_jsonp(self):
|
|
||||||
stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
|
|
||||||
d = json.loads(stripped)
|
|
||||||
self.assertEqual(d, [{"id": "532cb", "x": 3}])
|
|
||||||
|
|
||||||
def test_uppercase_escpae(self):
|
|
||||||
self.assertEqual(uppercase_escape(u'aä'), u'aä')
|
|
||||||
self.assertEqual(uppercase_escape(u'\\U0001d550'), u'𝕐')
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -33,7 +33,6 @@ TEST_ID = 'BaW_jenozKc'
|
|||||||
INFO_JSON_FILE = TEST_ID + '.info.json'
|
INFO_JSON_FILE = TEST_ID + '.info.json'
|
||||||
DESCRIPTION_FILE = TEST_ID + '.mp4.description'
|
DESCRIPTION_FILE = TEST_ID + '.mp4.description'
|
||||||
EXPECTED_DESCRIPTION = u'''test chars: "'/\ä↭𝕐
|
EXPECTED_DESCRIPTION = u'''test chars: "'/\ä↭𝕐
|
||||||
test URL: https://github.com/rg3/youtube-dl/issues/1892
|
|
||||||
|
|
||||||
This is a test video for youtube-dl.
|
This is a test video for youtube-dl.
|
||||||
|
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ from youtube_dl.extractor import (
|
|||||||
YoutubeIE,
|
YoutubeIE,
|
||||||
YoutubeChannelIE,
|
YoutubeChannelIE,
|
||||||
YoutubeShowIE,
|
YoutubeShowIE,
|
||||||
YoutubeTopListIE,
|
|
||||||
YoutubeSearchURLIE,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -31,7 +29,7 @@ class TestYoutubeLists(unittest.TestCase):
|
|||||||
result = ie.extract('https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re')
|
result = ie.extract('https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re')
|
||||||
self.assertIsPlaylist(result)
|
self.assertIsPlaylist(result)
|
||||||
self.assertEqual(result['title'], 'ytdl test PL')
|
self.assertEqual(result['title'], 'ytdl test PL')
|
||||||
ytie_results = [YoutubeIE().extract_id(url['url']) for url in result['entries']]
|
ytie_results = [YoutubeIE()._extract_id(url['url']) for url in result['entries']]
|
||||||
self.assertEqual(ytie_results, [ 'bV9L5Ht9LgY', 'FXxLjLQi3Fg', 'tU3Bgo5qJZE'])
|
self.assertEqual(ytie_results, [ 'bV9L5Ht9LgY', 'FXxLjLQi3Fg', 'tU3Bgo5qJZE'])
|
||||||
|
|
||||||
def test_youtube_playlist_noplaylist(self):
|
def test_youtube_playlist_noplaylist(self):
|
||||||
@@ -40,7 +38,7 @@ class TestYoutubeLists(unittest.TestCase):
|
|||||||
ie = YoutubePlaylistIE(dl)
|
ie = YoutubePlaylistIE(dl)
|
||||||
result = ie.extract('https://www.youtube.com/watch?v=FXxLjLQi3Fg&list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re')
|
result = ie.extract('https://www.youtube.com/watch?v=FXxLjLQi3Fg&list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re')
|
||||||
self.assertEqual(result['_type'], 'url')
|
self.assertEqual(result['_type'], 'url')
|
||||||
self.assertEqual(YoutubeIE().extract_id(result['url']), 'FXxLjLQi3Fg')
|
self.assertEqual(YoutubeIE()._extract_id(result['url']), 'FXxLjLQi3Fg')
|
||||||
|
|
||||||
def test_issue_673(self):
|
def test_issue_673(self):
|
||||||
dl = FakeYDL()
|
dl = FakeYDL()
|
||||||
@@ -60,7 +58,7 @@ class TestYoutubeLists(unittest.TestCase):
|
|||||||
dl = FakeYDL()
|
dl = FakeYDL()
|
||||||
ie = YoutubePlaylistIE(dl)
|
ie = YoutubePlaylistIE(dl)
|
||||||
result = ie.extract('https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC')
|
result = ie.extract('https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC')
|
||||||
ytie_results = [YoutubeIE().extract_id(url['url']) for url in result['entries']]
|
ytie_results = [YoutubeIE()._extract_id(url['url']) for url in result['entries']]
|
||||||
self.assertFalse('pElCt5oNDuI' in ytie_results)
|
self.assertFalse('pElCt5oNDuI' in ytie_results)
|
||||||
self.assertFalse('KdPEApIVdWM' in ytie_results)
|
self.assertFalse('KdPEApIVdWM' in ytie_results)
|
||||||
|
|
||||||
@@ -77,9 +75,9 @@ class TestYoutubeLists(unittest.TestCase):
|
|||||||
# TODO find a > 100 (paginating?) videos course
|
# TODO find a > 100 (paginating?) videos course
|
||||||
result = ie.extract('https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8')
|
result = ie.extract('https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8')
|
||||||
entries = result['entries']
|
entries = result['entries']
|
||||||
self.assertEqual(YoutubeIE().extract_id(entries[0]['url']), 'j9WZyLZCBzs')
|
self.assertEqual(YoutubeIE()._extract_id(entries[0]['url']), 'j9WZyLZCBzs')
|
||||||
self.assertEqual(len(entries), 25)
|
self.assertEqual(len(entries), 25)
|
||||||
self.assertEqual(YoutubeIE().extract_id(entries[-1]['url']), 'rYefUsYuEp0')
|
self.assertEqual(YoutubeIE()._extract_id(entries[-1]['url']), 'rYefUsYuEp0')
|
||||||
|
|
||||||
def test_youtube_channel(self):
|
def test_youtube_channel(self):
|
||||||
dl = FakeYDL()
|
dl = FakeYDL()
|
||||||
@@ -109,39 +107,5 @@ class TestYoutubeLists(unittest.TestCase):
|
|||||||
result = ie.extract('http://www.youtube.com/show/airdisasters')
|
result = ie.extract('http://www.youtube.com/show/airdisasters')
|
||||||
self.assertTrue(len(result) >= 3)
|
self.assertTrue(len(result) >= 3)
|
||||||
|
|
||||||
def test_youtube_mix(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = YoutubePlaylistIE(dl)
|
|
||||||
result = ie.extract('http://www.youtube.com/watch?v=lLJf9qJHR3E&list=RDrjFaenf1T-Y')
|
|
||||||
entries = result['entries']
|
|
||||||
self.assertTrue(len(entries) >= 20)
|
|
||||||
original_video = entries[0]
|
|
||||||
self.assertEqual(original_video['id'], 'rjFaenf1T-Y')
|
|
||||||
|
|
||||||
def test_youtube_toptracks(self):
|
|
||||||
print('Skipping: The playlist page gives error 500')
|
|
||||||
return
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = YoutubePlaylistIE(dl)
|
|
||||||
result = ie.extract('https://www.youtube.com/playlist?list=MCUS')
|
|
||||||
entries = result['entries']
|
|
||||||
self.assertEqual(len(entries), 100)
|
|
||||||
|
|
||||||
def test_youtube_toplist(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = YoutubeTopListIE(dl)
|
|
||||||
result = ie.extract('yttoplist:music:Trending')
|
|
||||||
entries = result['entries']
|
|
||||||
self.assertTrue(len(entries) >= 5)
|
|
||||||
|
|
||||||
def test_youtube_search_url(self):
|
|
||||||
dl = FakeYDL()
|
|
||||||
ie = YoutubeSearchURLIE(dl)
|
|
||||||
result = ie.extract('https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video')
|
|
||||||
entries = result['entries']
|
|
||||||
self.assertIsPlaylist(result)
|
|
||||||
self.assertEqual(result['title'], 'youtube-dl test video')
|
|
||||||
self.assertTrue(len(entries) >= 5)
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -28,10 +28,10 @@ _TESTS = [
|
|||||||
u'3456789a0cdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRS[UVWXYZ!"#$%&\'()*+,-./:;<=>?@',
|
u'3456789a0cdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRS[UVWXYZ!"#$%&\'()*+,-./:;<=>?@',
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
u'https://s.ytimg.com/yts/jsbin/html5player-vfle-mVwz.js',
|
u'https://s.ytimg.com/yts/swfbin/watch_as3-vflg5GhxU.swf',
|
||||||
u'js',
|
u'swf',
|
||||||
90,
|
82,
|
||||||
u']\\[@?>=<;:/.-,+*)(\'&%$#"hZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjiagfedcb39876',
|
u':/.-,+*)=\'&%$#"!ZYX0VUTSRQPONMLKJIHGFEDCBAzyxw>utsrqponmlkjihgfedcba987654321'
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
# This allows the youtube-dl command to be installed in ZSH using antigen.
|
|
||||||
# Antigen is a bundle manager. It allows you to enhance the functionality of
|
|
||||||
# your zsh session by installing bundles and themes easily.
|
|
||||||
|
|
||||||
# Antigen documentation:
|
|
||||||
# http://antigen.sharats.me/
|
|
||||||
# https://github.com/zsh-users/antigen
|
|
||||||
|
|
||||||
# Install youtube-dl:
|
|
||||||
# antigen bundle rg3/youtube-dl
|
|
||||||
# Bundles installed by antigen are available for use immediately.
|
|
||||||
|
|
||||||
# Update youtube-dl (and all other antigen bundles):
|
|
||||||
# antigen update
|
|
||||||
|
|
||||||
# The antigen command will download the git repository to a folder and then
|
|
||||||
# execute an enabling script (this file). The complete process for loading the
|
|
||||||
# code is documented here:
|
|
||||||
# https://github.com/zsh-users/antigen#notes-on-writing-plugins
|
|
||||||
|
|
||||||
# This specific script just aliases youtube-dl to the python script that this
|
|
||||||
# library provides. This requires updating the PYTHONPATH to ensure that the
|
|
||||||
# full set of code can be located.
|
|
||||||
alias youtube-dl="PYTHONPATH=$(dirname $0) $(dirname $0)/bin/youtube-dl"
|
|
||||||
@@ -1,12 +1,683 @@
|
|||||||
# Legacy file for backwards compatibility, use youtube_dl.downloader instead!
|
import os
|
||||||
from .downloader import FileDownloader as RealFileDownloader
|
import re
|
||||||
from .downloader import get_suitable_downloader
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
from .utils import (
|
||||||
|
compat_urllib_error,
|
||||||
|
compat_urllib_request,
|
||||||
|
ContentTooShortError,
|
||||||
|
determine_ext,
|
||||||
|
encodeFilename,
|
||||||
|
format_bytes,
|
||||||
|
sanitize_open,
|
||||||
|
timeconvert,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FileDownloader(object):
|
||||||
|
"""File Downloader class.
|
||||||
|
|
||||||
|
File downloader objects are the ones responsible of downloading the
|
||||||
|
actual video file and writing it to disk.
|
||||||
|
|
||||||
|
File downloaders accept a lot of parameters. In order not to saturate
|
||||||
|
the object constructor with arguments, it receives a dictionary of
|
||||||
|
options instead.
|
||||||
|
|
||||||
|
Available options:
|
||||||
|
|
||||||
|
verbose: Print additional info to stdout.
|
||||||
|
quiet: Do not print messages to stdout.
|
||||||
|
ratelimit: Download speed limit, in bytes/sec.
|
||||||
|
retries: Number of times to retry for HTTP error 5xx
|
||||||
|
buffersize: Size of download buffer in bytes.
|
||||||
|
noresizebuffer: Do not automatically resize the download buffer.
|
||||||
|
continuedl: Try to continue downloads if possible.
|
||||||
|
noprogress: Do not print the progress bar.
|
||||||
|
logtostderr: Log messages to stderr instead of stdout.
|
||||||
|
consoletitle: Display progress in console window's titlebar.
|
||||||
|
nopart: Do not use temporary .part files.
|
||||||
|
updatetime: Use the Last-modified header to set output file timestamps.
|
||||||
|
test: Download only first bytes to test the downloader.
|
||||||
|
min_filesize: Skip files smaller than this size
|
||||||
|
max_filesize: Skip files larger than this size
|
||||||
|
"""
|
||||||
|
|
||||||
|
params = None
|
||||||
|
|
||||||
|
def __init__(self, ydl, params):
|
||||||
|
"""Create a FileDownloader object with the given options."""
|
||||||
|
self.ydl = ydl
|
||||||
|
self._progress_hooks = []
|
||||||
|
self.params = params
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def format_seconds(seconds):
|
||||||
|
(mins, secs) = divmod(seconds, 60)
|
||||||
|
(hours, mins) = divmod(mins, 60)
|
||||||
|
if hours > 99:
|
||||||
|
return '--:--:--'
|
||||||
|
if hours == 0:
|
||||||
|
return '%02d:%02d' % (mins, secs)
|
||||||
|
else:
|
||||||
|
return '%02d:%02d:%02d' % (hours, mins, secs)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def calc_percent(byte_counter, data_len):
|
||||||
|
if data_len is None:
|
||||||
|
return None
|
||||||
|
return float(byte_counter) / float(data_len) * 100.0
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def format_percent(percent):
|
||||||
|
if percent is None:
|
||||||
|
return '---.-%'
|
||||||
|
return '%6s' % ('%3.1f%%' % percent)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def calc_eta(start, now, total, current):
|
||||||
|
if total is None:
|
||||||
|
return None
|
||||||
|
dif = now - start
|
||||||
|
if current == 0 or dif < 0.001: # One millisecond
|
||||||
|
return None
|
||||||
|
rate = float(current) / dif
|
||||||
|
return int((float(total) - float(current)) / rate)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def format_eta(eta):
|
||||||
|
if eta is None:
|
||||||
|
return '--:--'
|
||||||
|
return FileDownloader.format_seconds(eta)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def calc_speed(start, now, bytes):
|
||||||
|
dif = now - start
|
||||||
|
if bytes == 0 or dif < 0.001: # One millisecond
|
||||||
|
return None
|
||||||
|
return float(bytes) / dif
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def format_speed(speed):
|
||||||
|
if speed is None:
|
||||||
|
return '%10s' % '---b/s'
|
||||||
|
return '%10s' % ('%s/s' % format_bytes(speed))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def best_block_size(elapsed_time, bytes):
|
||||||
|
new_min = max(bytes / 2.0, 1.0)
|
||||||
|
new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
|
||||||
|
if elapsed_time < 0.001:
|
||||||
|
return int(new_max)
|
||||||
|
rate = bytes / elapsed_time
|
||||||
|
if rate > new_max:
|
||||||
|
return int(new_max)
|
||||||
|
if rate < new_min:
|
||||||
|
return int(new_min)
|
||||||
|
return int(rate)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def parse_bytes(bytestr):
|
||||||
|
"""Parse a string indicating a byte quantity into an integer."""
|
||||||
|
matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
|
||||||
|
if matchobj is None:
|
||||||
|
return None
|
||||||
|
number = float(matchobj.group(1))
|
||||||
|
multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
|
||||||
|
return int(round(number * multiplier))
|
||||||
|
|
||||||
|
def to_screen(self, *args, **kargs):
|
||||||
|
self.ydl.to_screen(*args, **kargs)
|
||||||
|
|
||||||
|
def to_stderr(self, message):
|
||||||
|
self.ydl.to_screen(message)
|
||||||
|
|
||||||
|
def to_console_title(self, message):
|
||||||
|
self.ydl.to_console_title(message)
|
||||||
|
|
||||||
|
def trouble(self, *args, **kargs):
|
||||||
|
self.ydl.trouble(*args, **kargs)
|
||||||
|
|
||||||
|
def report_warning(self, *args, **kargs):
|
||||||
|
self.ydl.report_warning(*args, **kargs)
|
||||||
|
|
||||||
|
def report_error(self, *args, **kargs):
|
||||||
|
self.ydl.report_error(*args, **kargs)
|
||||||
|
|
||||||
|
def slow_down(self, start_time, byte_counter):
|
||||||
|
"""Sleep if the download speed is over the rate limit."""
|
||||||
|
rate_limit = self.params.get('ratelimit', None)
|
||||||
|
if rate_limit is None or byte_counter == 0:
|
||||||
|
return
|
||||||
|
now = time.time()
|
||||||
|
elapsed = now - start_time
|
||||||
|
if elapsed <= 0.0:
|
||||||
|
return
|
||||||
|
speed = float(byte_counter) / elapsed
|
||||||
|
if speed > rate_limit:
|
||||||
|
time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
|
||||||
|
|
||||||
|
def temp_name(self, filename):
|
||||||
|
"""Returns a temporary filename for the given filename."""
|
||||||
|
if self.params.get('nopart', False) or filename == u'-' or \
|
||||||
|
(os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
|
||||||
|
return filename
|
||||||
|
return filename + u'.part'
|
||||||
|
|
||||||
|
def undo_temp_name(self, filename):
|
||||||
|
if filename.endswith(u'.part'):
|
||||||
|
return filename[:-len(u'.part')]
|
||||||
|
return filename
|
||||||
|
|
||||||
|
def try_rename(self, old_filename, new_filename):
|
||||||
|
try:
|
||||||
|
if old_filename == new_filename:
|
||||||
|
return
|
||||||
|
os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
|
||||||
|
except (IOError, OSError):
|
||||||
|
self.report_error(u'unable to rename file')
|
||||||
|
|
||||||
|
def try_utime(self, filename, last_modified_hdr):
|
||||||
|
"""Try to set the last-modified time of the given file."""
|
||||||
|
if last_modified_hdr is None:
|
||||||
|
return
|
||||||
|
if not os.path.isfile(encodeFilename(filename)):
|
||||||
|
return
|
||||||
|
timestr = last_modified_hdr
|
||||||
|
if timestr is None:
|
||||||
|
return
|
||||||
|
filetime = timeconvert(timestr)
|
||||||
|
if filetime is None:
|
||||||
|
return filetime
|
||||||
|
# Ignore obviously invalid dates
|
||||||
|
if filetime == 0:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
os.utime(filename, (time.time(), filetime))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
return filetime
|
||||||
|
|
||||||
|
def report_destination(self, filename):
|
||||||
|
"""Report destination filename."""
|
||||||
|
self.to_screen(u'[download] Destination: ' + filename)
|
||||||
|
|
||||||
|
def report_progress(self, percent, data_len_str, speed, eta):
|
||||||
|
"""Report download progress."""
|
||||||
|
if self.params.get('noprogress', False):
|
||||||
|
return
|
||||||
|
clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
|
||||||
|
if eta is not None:
|
||||||
|
eta_str = self.format_eta(eta)
|
||||||
|
else:
|
||||||
|
eta_str = 'Unknown ETA'
|
||||||
|
if percent is not None:
|
||||||
|
percent_str = self.format_percent(percent)
|
||||||
|
else:
|
||||||
|
percent_str = 'Unknown %'
|
||||||
|
speed_str = self.format_speed(speed)
|
||||||
|
if self.params.get('progress_with_newline', False):
|
||||||
|
self.to_screen(u'[download] %s of %s at %s ETA %s' %
|
||||||
|
(percent_str, data_len_str, speed_str, eta_str))
|
||||||
|
else:
|
||||||
|
self.to_screen(u'\r%s[download] %s of %s at %s ETA %s' %
|
||||||
|
(clear_line, percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
|
||||||
|
self.to_console_title(u'youtube-dl - %s of %s at %s ETA %s' %
|
||||||
|
(percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
|
||||||
|
|
||||||
|
def report_resuming_byte(self, resume_len):
|
||||||
|
"""Report attempt to resume at given byte."""
|
||||||
|
self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
|
||||||
|
|
||||||
|
def report_retry(self, count, retries):
|
||||||
|
"""Report retry in case of HTTP error 5xx"""
|
||||||
|
self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
|
||||||
|
|
||||||
|
def report_file_already_downloaded(self, file_name):
|
||||||
|
"""Report file has already been fully downloaded."""
|
||||||
|
try:
|
||||||
|
self.to_screen(u'[download] %s has already been downloaded' % file_name)
|
||||||
|
except UnicodeEncodeError:
|
||||||
|
self.to_screen(u'[download] The file has already been downloaded')
|
||||||
|
|
||||||
|
def report_unable_to_resume(self):
|
||||||
|
"""Report it was impossible to resume download."""
|
||||||
|
self.to_screen(u'[download] Unable to resume')
|
||||||
|
|
||||||
|
def report_finish(self, data_len_str, tot_time):
|
||||||
|
"""Report download finished."""
|
||||||
|
if self.params.get('noprogress', False):
|
||||||
|
self.to_screen(u'[download] Download completed')
|
||||||
|
else:
|
||||||
|
clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
|
||||||
|
self.to_screen(u'\r%s[download] 100%% of %s in %s' %
|
||||||
|
(clear_line, data_len_str, self.format_seconds(tot_time)))
|
||||||
|
|
||||||
|
def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path, tc_url, live):
|
||||||
|
def run_rtmpdump(args):
|
||||||
|
start = time.time()
|
||||||
|
resume_percent = None
|
||||||
|
resume_downloaded_data_len = None
|
||||||
|
proc = subprocess.Popen(args, stderr=subprocess.PIPE)
|
||||||
|
cursor_in_new_line = True
|
||||||
|
proc_stderr_closed = False
|
||||||
|
while not proc_stderr_closed:
|
||||||
|
# read line from stderr
|
||||||
|
line = u''
|
||||||
|
while True:
|
||||||
|
char = proc.stderr.read(1)
|
||||||
|
if not char:
|
||||||
|
proc_stderr_closed = True
|
||||||
|
break
|
||||||
|
if char in [b'\r', b'\n']:
|
||||||
|
break
|
||||||
|
line += char.decode('ascii', 'replace')
|
||||||
|
if not line:
|
||||||
|
# proc_stderr_closed is True
|
||||||
|
continue
|
||||||
|
mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec \(([0-9]{1,2}\.[0-9])%\)', line)
|
||||||
|
if mobj:
|
||||||
|
downloaded_data_len = int(float(mobj.group(1))*1024)
|
||||||
|
percent = float(mobj.group(2))
|
||||||
|
if not resume_percent:
|
||||||
|
resume_percent = percent
|
||||||
|
resume_downloaded_data_len = downloaded_data_len
|
||||||
|
eta = self.calc_eta(start, time.time(), 100-resume_percent, percent-resume_percent)
|
||||||
|
speed = self.calc_speed(start, time.time(), downloaded_data_len-resume_downloaded_data_len)
|
||||||
|
data_len = None
|
||||||
|
if percent > 0:
|
||||||
|
data_len = int(downloaded_data_len * 100 / percent)
|
||||||
|
data_len_str = u'~' + format_bytes(data_len)
|
||||||
|
self.report_progress(percent, data_len_str, speed, eta)
|
||||||
|
cursor_in_new_line = False
|
||||||
|
self._hook_progress({
|
||||||
|
'downloaded_bytes': downloaded_data_len,
|
||||||
|
'total_bytes': data_len,
|
||||||
|
'tmpfilename': tmpfilename,
|
||||||
|
'filename': filename,
|
||||||
|
'status': 'downloading',
|
||||||
|
'eta': eta,
|
||||||
|
'speed': speed,
|
||||||
|
})
|
||||||
|
elif self.params.get('verbose', False):
|
||||||
|
if not cursor_in_new_line:
|
||||||
|
self.to_screen(u'')
|
||||||
|
cursor_in_new_line = True
|
||||||
|
self.to_screen(u'[rtmpdump] '+line)
|
||||||
|
proc.wait()
|
||||||
|
if not cursor_in_new_line:
|
||||||
|
self.to_screen(u'')
|
||||||
|
return proc.returncode
|
||||||
|
|
||||||
|
self.report_destination(filename)
|
||||||
|
tmpfilename = self.temp_name(filename)
|
||||||
|
test = self.params.get('test', False)
|
||||||
|
|
||||||
|
# Check for rtmpdump first
|
||||||
|
try:
|
||||||
|
subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
|
||||||
|
except (OSError, IOError):
|
||||||
|
self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Download using rtmpdump. rtmpdump returns exit code 2 when
|
||||||
|
# the connection was interrumpted and resuming appears to be
|
||||||
|
# possible. This is part of rtmpdump's normal usage, AFAIK.
|
||||||
|
basic_args = ['rtmpdump', '--verbose', '-r', url, '-o', tmpfilename]
|
||||||
|
if player_url is not None:
|
||||||
|
basic_args += ['--swfVfy', player_url]
|
||||||
|
if page_url is not None:
|
||||||
|
basic_args += ['--pageUrl', page_url]
|
||||||
|
if play_path is not None:
|
||||||
|
basic_args += ['--playpath', play_path]
|
||||||
|
if tc_url is not None:
|
||||||
|
basic_args += ['--tcUrl', url]
|
||||||
|
if test:
|
||||||
|
basic_args += ['--stop', '1']
|
||||||
|
if live:
|
||||||
|
basic_args += ['--live']
|
||||||
|
args = basic_args + [[], ['--resume', '--skip', '1']][self.params.get('continuedl', False)]
|
||||||
|
|
||||||
|
if sys.platform == 'win32' and sys.version_info < (3, 0):
|
||||||
|
# Windows subprocess module does not actually support Unicode
|
||||||
|
# on Python 2.x
|
||||||
|
# See http://stackoverflow.com/a/9951851/35070
|
||||||
|
subprocess_encoding = sys.getfilesystemencoding()
|
||||||
|
args = [a.encode(subprocess_encoding, 'ignore') for a in args]
|
||||||
|
else:
|
||||||
|
subprocess_encoding = None
|
||||||
|
|
||||||
|
if self.params.get('verbose', False):
|
||||||
|
if subprocess_encoding:
|
||||||
|
str_args = [
|
||||||
|
a.decode(subprocess_encoding) if isinstance(a, bytes) else a
|
||||||
|
for a in args]
|
||||||
|
else:
|
||||||
|
str_args = args
|
||||||
|
try:
|
||||||
|
import pipes
|
||||||
|
shell_quote = lambda args: ' '.join(map(pipes.quote, str_args))
|
||||||
|
except ImportError:
|
||||||
|
shell_quote = repr
|
||||||
|
self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(str_args))
|
||||||
|
|
||||||
|
retval = run_rtmpdump(args)
|
||||||
|
|
||||||
|
while (retval == 2 or retval == 1) and not test:
|
||||||
|
prevsize = os.path.getsize(encodeFilename(tmpfilename))
|
||||||
|
self.to_screen(u'[rtmpdump] %s bytes' % prevsize)
|
||||||
|
time.sleep(5.0) # This seems to be needed
|
||||||
|
retval = run_rtmpdump(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
|
||||||
|
cursize = os.path.getsize(encodeFilename(tmpfilename))
|
||||||
|
if prevsize == cursize and retval == 1:
|
||||||
|
break
|
||||||
|
# Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
|
||||||
|
if prevsize == cursize and retval == 2 and cursize > 1024:
|
||||||
|
self.to_screen(u'[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
|
||||||
|
retval = 0
|
||||||
|
break
|
||||||
|
if retval == 0 or (test and retval == 2):
|
||||||
|
fsize = os.path.getsize(encodeFilename(tmpfilename))
|
||||||
|
self.to_screen(u'[rtmpdump] %s bytes' % fsize)
|
||||||
|
self.try_rename(tmpfilename, filename)
|
||||||
|
self._hook_progress({
|
||||||
|
'downloaded_bytes': fsize,
|
||||||
|
'total_bytes': fsize,
|
||||||
|
'filename': filename,
|
||||||
|
'status': 'finished',
|
||||||
|
})
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
self.to_stderr(u"\n")
|
||||||
|
self.report_error(u'rtmpdump exited with code %d' % retval)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _download_with_mplayer(self, filename, url):
|
||||||
|
self.report_destination(filename)
|
||||||
|
tmpfilename = self.temp_name(filename)
|
||||||
|
|
||||||
|
args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
|
||||||
|
# Check for mplayer first
|
||||||
|
try:
|
||||||
|
subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
|
||||||
|
except (OSError, IOError):
|
||||||
|
self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0] )
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Download using mplayer.
|
||||||
|
retval = subprocess.call(args)
|
||||||
|
if retval == 0:
|
||||||
|
fsize = os.path.getsize(encodeFilename(tmpfilename))
|
||||||
|
self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
|
||||||
|
self.try_rename(tmpfilename, filename)
|
||||||
|
self._hook_progress({
|
||||||
|
'downloaded_bytes': fsize,
|
||||||
|
'total_bytes': fsize,
|
||||||
|
'filename': filename,
|
||||||
|
'status': 'finished',
|
||||||
|
})
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
self.to_stderr(u"\n")
|
||||||
|
self.report_error(u'mplayer exited with code %d' % retval)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _download_m3u8_with_ffmpeg(self, filename, url):
|
||||||
|
self.report_destination(filename)
|
||||||
|
tmpfilename = self.temp_name(filename)
|
||||||
|
|
||||||
|
args = ['-y', '-i', url, '-f', 'mp4', '-c', 'copy',
|
||||||
|
'-bsf:a', 'aac_adtstoasc', tmpfilename]
|
||||||
|
|
||||||
|
for program in ['avconv', 'ffmpeg']:
|
||||||
|
try:
|
||||||
|
subprocess.call([program, '-version'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
|
||||||
|
break
|
||||||
|
except (OSError, IOError):
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
self.report_error(u'm3u8 download detected but ffmpeg or avconv could not be found')
|
||||||
|
cmd = [program] + args
|
||||||
|
|
||||||
|
retval = subprocess.call(cmd)
|
||||||
|
if retval == 0:
|
||||||
|
fsize = os.path.getsize(encodeFilename(tmpfilename))
|
||||||
|
self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
|
||||||
|
self.try_rename(tmpfilename, filename)
|
||||||
|
self._hook_progress({
|
||||||
|
'downloaded_bytes': fsize,
|
||||||
|
'total_bytes': fsize,
|
||||||
|
'filename': filename,
|
||||||
|
'status': 'finished',
|
||||||
|
})
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
self.to_stderr(u"\n")
|
||||||
|
self.report_error(u'ffmpeg exited with code %d' % retval)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
# This class reproduces the old behaviour of FileDownloader
|
|
||||||
class FileDownloader(RealFileDownloader):
|
|
||||||
def _do_download(self, filename, info_dict):
|
def _do_download(self, filename, info_dict):
|
||||||
real_fd = get_suitable_downloader(info_dict)(self.ydl, self.params)
|
url = info_dict['url']
|
||||||
|
|
||||||
|
# Check file already present
|
||||||
|
if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
|
||||||
|
self.report_file_already_downloaded(filename)
|
||||||
|
self._hook_progress({
|
||||||
|
'filename': filename,
|
||||||
|
'status': 'finished',
|
||||||
|
'total_bytes': os.path.getsize(encodeFilename(filename)),
|
||||||
|
})
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Attempt to download using rtmpdump
|
||||||
|
if url.startswith('rtmp'):
|
||||||
|
return self._download_with_rtmpdump(filename, url,
|
||||||
|
info_dict.get('player_url', None),
|
||||||
|
info_dict.get('page_url', None),
|
||||||
|
info_dict.get('play_path', None),
|
||||||
|
info_dict.get('tc_url', None),
|
||||||
|
info_dict.get('rtmp_live', False))
|
||||||
|
|
||||||
|
# Attempt to download using mplayer
|
||||||
|
if url.startswith('mms') or url.startswith('rtsp'):
|
||||||
|
return self._download_with_mplayer(filename, url)
|
||||||
|
|
||||||
|
# m3u8 manifest are downloaded with ffmpeg
|
||||||
|
if determine_ext(url) == u'm3u8':
|
||||||
|
return self._download_m3u8_with_ffmpeg(filename, url)
|
||||||
|
|
||||||
|
tmpfilename = self.temp_name(filename)
|
||||||
|
stream = None
|
||||||
|
|
||||||
|
# Do not include the Accept-Encoding header
|
||||||
|
headers = {'Youtubedl-no-compression': 'True'}
|
||||||
|
if 'user_agent' in info_dict:
|
||||||
|
headers['Youtubedl-user-agent'] = info_dict['user_agent']
|
||||||
|
basic_request = compat_urllib_request.Request(url, None, headers)
|
||||||
|
request = compat_urllib_request.Request(url, None, headers)
|
||||||
|
|
||||||
|
if self.params.get('test', False):
|
||||||
|
request.add_header('Range','bytes=0-10240')
|
||||||
|
|
||||||
|
# Establish possible resume length
|
||||||
|
if os.path.isfile(encodeFilename(tmpfilename)):
|
||||||
|
resume_len = os.path.getsize(encodeFilename(tmpfilename))
|
||||||
|
else:
|
||||||
|
resume_len = 0
|
||||||
|
|
||||||
|
open_mode = 'wb'
|
||||||
|
if resume_len != 0:
|
||||||
|
if self.params.get('continuedl', False):
|
||||||
|
self.report_resuming_byte(resume_len)
|
||||||
|
request.add_header('Range','bytes=%d-' % resume_len)
|
||||||
|
open_mode = 'ab'
|
||||||
|
else:
|
||||||
|
resume_len = 0
|
||||||
|
|
||||||
|
count = 0
|
||||||
|
retries = self.params.get('retries', 0)
|
||||||
|
while count <= retries:
|
||||||
|
# Establish connection
|
||||||
|
try:
|
||||||
|
if count == 0 and 'urlhandle' in info_dict:
|
||||||
|
data = info_dict['urlhandle']
|
||||||
|
data = compat_urllib_request.urlopen(request)
|
||||||
|
break
|
||||||
|
except (compat_urllib_error.HTTPError, ) as err:
|
||||||
|
if (err.code < 500 or err.code >= 600) and err.code != 416:
|
||||||
|
# Unexpected HTTP error
|
||||||
|
raise
|
||||||
|
elif err.code == 416:
|
||||||
|
# Unable to resume (requested range not satisfiable)
|
||||||
|
try:
|
||||||
|
# Open the connection again without the range header
|
||||||
|
data = compat_urllib_request.urlopen(basic_request)
|
||||||
|
content_length = data.info()['Content-Length']
|
||||||
|
except (compat_urllib_error.HTTPError, ) as err:
|
||||||
|
if err.code < 500 or err.code >= 600:
|
||||||
|
raise
|
||||||
|
else:
|
||||||
|
# Examine the reported length
|
||||||
|
if (content_length is not None and
|
||||||
|
(resume_len - 100 < int(content_length) < resume_len + 100)):
|
||||||
|
# The file had already been fully downloaded.
|
||||||
|
# Explanation to the above condition: in issue #175 it was revealed that
|
||||||
|
# YouTube sometimes adds or removes a few bytes from the end of the file,
|
||||||
|
# changing the file size slightly and causing problems for some users. So
|
||||||
|
# I decided to implement a suggested change and consider the file
|
||||||
|
# completely downloaded if the file size differs less than 100 bytes from
|
||||||
|
# the one in the hard drive.
|
||||||
|
self.report_file_already_downloaded(filename)
|
||||||
|
self.try_rename(tmpfilename, filename)
|
||||||
|
self._hook_progress({
|
||||||
|
'filename': filename,
|
||||||
|
'status': 'finished',
|
||||||
|
})
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
# The length does not match, we start the download over
|
||||||
|
self.report_unable_to_resume()
|
||||||
|
open_mode = 'wb'
|
||||||
|
break
|
||||||
|
# Retry
|
||||||
|
count += 1
|
||||||
|
if count <= retries:
|
||||||
|
self.report_retry(count, retries)
|
||||||
|
|
||||||
|
if count > retries:
|
||||||
|
self.report_error(u'giving up after %s retries' % retries)
|
||||||
|
return False
|
||||||
|
|
||||||
|
data_len = data.info().get('Content-length', None)
|
||||||
|
if data_len is not None:
|
||||||
|
data_len = int(data_len) + resume_len
|
||||||
|
min_data_len = self.params.get("min_filesize", None)
|
||||||
|
max_data_len = self.params.get("max_filesize", None)
|
||||||
|
if min_data_len is not None and data_len < min_data_len:
|
||||||
|
self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
|
||||||
|
return False
|
||||||
|
if max_data_len is not None and data_len > max_data_len:
|
||||||
|
self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
|
||||||
|
return False
|
||||||
|
|
||||||
|
data_len_str = format_bytes(data_len)
|
||||||
|
byte_counter = 0 + resume_len
|
||||||
|
block_size = self.params.get('buffersize', 1024)
|
||||||
|
start = time.time()
|
||||||
|
while True:
|
||||||
|
# Download and write
|
||||||
|
before = time.time()
|
||||||
|
data_block = data.read(block_size)
|
||||||
|
after = time.time()
|
||||||
|
if len(data_block) == 0:
|
||||||
|
break
|
||||||
|
byte_counter += len(data_block)
|
||||||
|
|
||||||
|
# Open file just in time
|
||||||
|
if stream is None:
|
||||||
|
try:
|
||||||
|
(stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
|
||||||
|
assert stream is not None
|
||||||
|
filename = self.undo_temp_name(tmpfilename)
|
||||||
|
self.report_destination(filename)
|
||||||
|
except (OSError, IOError) as err:
|
||||||
|
self.report_error(u'unable to open for writing: %s' % str(err))
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
stream.write(data_block)
|
||||||
|
except (IOError, OSError) as err:
|
||||||
|
self.to_stderr(u"\n")
|
||||||
|
self.report_error(u'unable to write data: %s' % str(err))
|
||||||
|
return False
|
||||||
|
if not self.params.get('noresizebuffer', False):
|
||||||
|
block_size = self.best_block_size(after - before, len(data_block))
|
||||||
|
|
||||||
|
# Progress message
|
||||||
|
speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
|
||||||
|
if data_len is None:
|
||||||
|
eta = percent = None
|
||||||
|
else:
|
||||||
|
percent = self.calc_percent(byte_counter, data_len)
|
||||||
|
eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
|
||||||
|
self.report_progress(percent, data_len_str, speed, eta)
|
||||||
|
|
||||||
|
self._hook_progress({
|
||||||
|
'downloaded_bytes': byte_counter,
|
||||||
|
'total_bytes': data_len,
|
||||||
|
'tmpfilename': tmpfilename,
|
||||||
|
'filename': filename,
|
||||||
|
'status': 'downloading',
|
||||||
|
'eta': eta,
|
||||||
|
'speed': speed,
|
||||||
|
})
|
||||||
|
|
||||||
|
# Apply rate limit
|
||||||
|
self.slow_down(start, byte_counter - resume_len)
|
||||||
|
|
||||||
|
if stream is None:
|
||||||
|
self.to_stderr(u"\n")
|
||||||
|
self.report_error(u'Did not get any data blocks')
|
||||||
|
return False
|
||||||
|
stream.close()
|
||||||
|
self.report_finish(data_len_str, (time.time() - start))
|
||||||
|
if data_len is not None and byte_counter != data_len:
|
||||||
|
raise ContentTooShortError(byte_counter, int(data_len))
|
||||||
|
self.try_rename(tmpfilename, filename)
|
||||||
|
|
||||||
|
# Update file modification time
|
||||||
|
if self.params.get('updatetime', True):
|
||||||
|
info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
|
||||||
|
|
||||||
|
self._hook_progress({
|
||||||
|
'downloaded_bytes': byte_counter,
|
||||||
|
'total_bytes': byte_counter,
|
||||||
|
'filename': filename,
|
||||||
|
'status': 'finished',
|
||||||
|
})
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _hook_progress(self, status):
|
||||||
for ph in self._progress_hooks:
|
for ph in self._progress_hooks:
|
||||||
real_fd.add_progress_hook(ph)
|
ph(status)
|
||||||
return real_fd.download(filename, info_dict)
|
|
||||||
|
def add_progress_hook(self, ph):
|
||||||
|
""" ph gets called on download progress, with a dictionary with the entries
|
||||||
|
* filename: The final filename
|
||||||
|
* status: One of "downloading" and "finished"
|
||||||
|
|
||||||
|
It can also have some of the following entries:
|
||||||
|
|
||||||
|
* downloaded_bytes: Bytes on disks
|
||||||
|
* total_bytes: Total bytes, None if unknown
|
||||||
|
* tmpfilename: The filename we're currently writing to
|
||||||
|
* eta: The estimated time in seconds, None if unknown
|
||||||
|
* speed: The download speed in bytes/second, None if unknown
|
||||||
|
|
||||||
|
Hooks are guaranteed to be called at least once (with status "finished")
|
||||||
|
if the download is successful.
|
||||||
|
"""
|
||||||
|
self._progress_hooks.append(ph)
|
||||||
|
|||||||
4
youtube_dl/InfoExtractors.py
Executable file
4
youtube_dl/InfoExtractors.py
Executable file
@@ -0,0 +1,4 @@
|
|||||||
|
# Legacy file for backwards compatibility, use youtube_dl.extractor instead!
|
||||||
|
|
||||||
|
from .extractor.common import InfoExtractor, SearchInfoExtractor
|
||||||
|
from .extractor import gen_extractors, get_info_extractor
|
||||||
@@ -4,23 +4,64 @@ import sys
|
|||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
||||||
from .common import AudioConversionError, PostProcessor
|
from .utils import (
|
||||||
|
|
||||||
from ..utils import (
|
|
||||||
check_executable,
|
|
||||||
compat_subprocess_get_DEVNULL,
|
compat_subprocess_get_DEVNULL,
|
||||||
encodeFilename,
|
encodeFilename,
|
||||||
PostProcessingError,
|
PostProcessingError,
|
||||||
prepend_extension,
|
|
||||||
shell_quote,
|
shell_quote,
|
||||||
subtitles_filename,
|
subtitles_filename,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PostProcessor(object):
|
||||||
|
"""Post Processor class.
|
||||||
|
|
||||||
|
PostProcessor objects can be added to downloaders with their
|
||||||
|
add_post_processor() method. When the downloader has finished a
|
||||||
|
successful download, it will take its internal chain of PostProcessors
|
||||||
|
and start calling the run() method on each one of them, first with
|
||||||
|
an initial argument and then with the returned value of the previous
|
||||||
|
PostProcessor.
|
||||||
|
|
||||||
|
The chain will be stopped if one of them ever returns None or the end
|
||||||
|
of the chain is reached.
|
||||||
|
|
||||||
|
PostProcessor objects follow a "mutual registration" process similar
|
||||||
|
to InfoExtractor objects.
|
||||||
|
"""
|
||||||
|
|
||||||
|
_downloader = None
|
||||||
|
|
||||||
|
def __init__(self, downloader=None):
|
||||||
|
self._downloader = downloader
|
||||||
|
|
||||||
|
def set_downloader(self, downloader):
|
||||||
|
"""Sets the downloader for this PP."""
|
||||||
|
self._downloader = downloader
|
||||||
|
|
||||||
|
def run(self, information):
|
||||||
|
"""Run the PostProcessor.
|
||||||
|
|
||||||
|
The "information" argument is a dictionary like the ones
|
||||||
|
composed by InfoExtractors. The only difference is that this
|
||||||
|
one has an extra field called "filepath" that points to the
|
||||||
|
downloaded file.
|
||||||
|
|
||||||
|
This method returns a tuple, the first element of which describes
|
||||||
|
whether the original file should be kept (i.e. not deleted - None for
|
||||||
|
no preference), and the second of which is the updated information.
|
||||||
|
|
||||||
|
In addition, this method may raise a PostProcessingError
|
||||||
|
exception if post processing fails.
|
||||||
|
"""
|
||||||
|
return None, information # by default, keep file and do nothing
|
||||||
|
|
||||||
class FFmpegPostProcessorError(PostProcessingError):
|
class FFmpegPostProcessorError(PostProcessingError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
class AudioConversionError(PostProcessingError):
|
||||||
|
pass
|
||||||
|
|
||||||
class FFmpegPostProcessor(PostProcessor):
|
class FFmpegPostProcessor(PostProcessor):
|
||||||
def __init__(self,downloader=None):
|
def __init__(self,downloader=None):
|
||||||
PostProcessor.__init__(self, downloader)
|
PostProcessor.__init__(self, downloader)
|
||||||
@@ -28,33 +69,30 @@ class FFmpegPostProcessor(PostProcessor):
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def detect_executables():
|
def detect_executables():
|
||||||
|
def executable(exe):
|
||||||
|
try:
|
||||||
|
subprocess.Popen([exe, '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
return exe
|
||||||
programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
|
programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
|
||||||
return dict((program, check_executable(program, ['-version'])) for program in programs)
|
return dict((program, executable(program)) for program in programs)
|
||||||
|
|
||||||
def _get_executable(self):
|
|
||||||
if self._downloader.params.get('prefer_ffmpeg', False):
|
|
||||||
return self._exes['ffmpeg'] or self._exes['avconv']
|
|
||||||
else:
|
|
||||||
return self._exes['avconv'] or self._exes['ffmpeg']
|
|
||||||
|
|
||||||
def _uses_avconv(self):
|
|
||||||
return self._get_executable() == self._exes['avconv']
|
|
||||||
|
|
||||||
def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
|
def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
|
||||||
if not self._get_executable():
|
if not self._exes['ffmpeg'] and not self._exes['avconv']:
|
||||||
raise FFmpegPostProcessorError(u'ffmpeg or avconv not found. Please install one.')
|
raise FFmpegPostProcessorError(u'ffmpeg or avconv not found. Please install one.')
|
||||||
|
|
||||||
files_cmd = []
|
files_cmd = []
|
||||||
for path in input_paths:
|
for path in input_paths:
|
||||||
files_cmd.extend(['-i', encodeFilename(path, True)])
|
files_cmd.extend(['-i', encodeFilename(path)])
|
||||||
cmd = ([self._get_executable(), '-y'] + files_cmd
|
cmd = ([self._exes['avconv'] or self._exes['ffmpeg'], '-y'] + files_cmd
|
||||||
+ opts +
|
+ opts +
|
||||||
[encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
|
[encodeFilename(self._ffmpeg_filename_argument(out_path))])
|
||||||
|
|
||||||
if self._downloader.params.get('verbose', False):
|
if self._downloader.params.get('verbose', False):
|
||||||
self._downloader.to_screen(u'[debug] ffmpeg command line: %s' % shell_quote(cmd))
|
self._downloader.to_screen(u'[debug] ffmpeg 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 = p.communicate()
|
stdout,stderr = p.communicate()
|
||||||
if p.returncode != 0:
|
if p.returncode != 0:
|
||||||
stderr = stderr.decode('utf-8', 'replace')
|
stderr = stderr.decode('utf-8', 'replace')
|
||||||
msg = stderr.strip().split('\n')[-1]
|
msg = stderr.strip().split('\n')[-1]
|
||||||
@@ -69,7 +107,6 @@ class FFmpegPostProcessor(PostProcessor):
|
|||||||
return u'./' + fn
|
return u'./' + fn
|
||||||
return fn
|
return fn
|
||||||
|
|
||||||
|
|
||||||
class FFmpegExtractAudioPP(FFmpegPostProcessor):
|
class FFmpegExtractAudioPP(FFmpegPostProcessor):
|
||||||
def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
|
def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
|
||||||
FFmpegPostProcessor.__init__(self, downloader)
|
FFmpegPostProcessor.__init__(self, downloader)
|
||||||
@@ -83,10 +120,7 @@ class FFmpegExtractAudioPP(FFmpegPostProcessor):
|
|||||||
if not self._exes['ffprobe'] and not self._exes['avprobe']:
|
if not self._exes['ffprobe'] and not self._exes['avprobe']:
|
||||||
raise PostProcessingError(u'ffprobe or avprobe not found. Please install one.')
|
raise PostProcessingError(u'ffprobe or avprobe not found. Please install one.')
|
||||||
try:
|
try:
|
||||||
cmd = [
|
cmd = [self._exes['avprobe'] or self._exes['ffprobe'], '-show_streams', encodeFilename(self._ffmpeg_filename_argument(path))]
|
||||||
self._exes['avprobe'] or self._exes['ffprobe'],
|
|
||||||
'-show_streams',
|
|
||||||
encodeFilename(self._ffmpeg_filename_argument(path), True)]
|
|
||||||
handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
|
handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
|
||||||
output = handle.communicate()[0]
|
output = handle.communicate()[0]
|
||||||
if handle.wait() != 0:
|
if handle.wait() != 0:
|
||||||
@@ -102,6 +136,8 @@ class FFmpegExtractAudioPP(FFmpegPostProcessor):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def run_ffmpeg(self, path, out_path, codec, more_opts):
|
def run_ffmpeg(self, path, out_path, codec, more_opts):
|
||||||
|
if not self._exes['ffmpeg'] and not self._exes['avconv']:
|
||||||
|
raise AudioConversionError('ffmpeg or avconv not found. Please install one.')
|
||||||
if codec is None:
|
if codec is None:
|
||||||
acodec_opts = []
|
acodec_opts = []
|
||||||
else:
|
else:
|
||||||
@@ -119,14 +155,13 @@ class FFmpegExtractAudioPP(FFmpegPostProcessor):
|
|||||||
if filecodec is None:
|
if filecodec is None:
|
||||||
raise PostProcessingError(u'WARNING: unable to obtain file audio codec with ffprobe')
|
raise PostProcessingError(u'WARNING: unable to obtain file audio codec with ffprobe')
|
||||||
|
|
||||||
uses_avconv = self._uses_avconv()
|
|
||||||
more_opts = []
|
more_opts = []
|
||||||
if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
|
if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
|
||||||
if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
|
if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
|
||||||
# Lossless, but in another container
|
# Lossless, but in another container
|
||||||
acodec = 'copy'
|
acodec = 'copy'
|
||||||
extension = 'm4a'
|
extension = 'm4a'
|
||||||
more_opts = ['-bsf:a' if uses_avconv else '-absf', 'aac_adtstoasc']
|
more_opts = [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
|
||||||
elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
|
elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
|
||||||
# Lossless if possible
|
# Lossless if possible
|
||||||
acodec = 'copy'
|
acodec = 'copy'
|
||||||
@@ -142,9 +177,9 @@ class FFmpegExtractAudioPP(FFmpegPostProcessor):
|
|||||||
more_opts = []
|
more_opts = []
|
||||||
if self._preferredquality is not None:
|
if self._preferredquality is not None:
|
||||||
if int(self._preferredquality) < 10:
|
if int(self._preferredquality) < 10:
|
||||||
more_opts += ['-q:a' if uses_avconv else '-aq', self._preferredquality]
|
more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
|
||||||
else:
|
else:
|
||||||
more_opts += ['-b:a' if uses_avconv else '-ab', self._preferredquality + 'k']
|
more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
|
||||||
else:
|
else:
|
||||||
# We convert the audio (lossy)
|
# We convert the audio (lossy)
|
||||||
acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
|
acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
|
||||||
@@ -153,13 +188,13 @@ class FFmpegExtractAudioPP(FFmpegPostProcessor):
|
|||||||
if self._preferredquality is not None:
|
if self._preferredquality is not None:
|
||||||
# The opus codec doesn't support the -aq option
|
# The opus codec doesn't support the -aq option
|
||||||
if int(self._preferredquality) < 10 and extension != 'opus':
|
if int(self._preferredquality) < 10 and extension != 'opus':
|
||||||
more_opts += ['-q:a' if uses_avconv else '-aq', self._preferredquality]
|
more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
|
||||||
else:
|
else:
|
||||||
more_opts += ['-b:a' if uses_avconv else '-ab', self._preferredquality + 'k']
|
more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
|
||||||
if self._preferredcodec == 'aac':
|
if self._preferredcodec == 'aac':
|
||||||
more_opts += ['-f', 'adts']
|
more_opts += ['-f', 'adts']
|
||||||
if self._preferredcodec == 'm4a':
|
if self._preferredcodec == 'm4a':
|
||||||
more_opts += ['-bsf:a' if uses_avconv else '-absf', 'aac_adtstoasc']
|
more_opts += [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
|
||||||
if self._preferredcodec == 'vorbis':
|
if self._preferredcodec == 'vorbis':
|
||||||
extension = 'ogg'
|
extension = 'ogg'
|
||||||
if self._preferredcodec == 'wav':
|
if self._preferredcodec == 'wav':
|
||||||
@@ -177,14 +212,14 @@ class FFmpegExtractAudioPP(FFmpegPostProcessor):
|
|||||||
if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
|
if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
|
||||||
self._downloader.to_screen(u'[youtube] Post-process file %s exists, skipping' % new_path)
|
self._downloader.to_screen(u'[youtube] Post-process file %s exists, skipping' % new_path)
|
||||||
else:
|
else:
|
||||||
self._downloader.to_screen(u'[' + self._get_executable() + '] Destination: ' + new_path)
|
self._downloader.to_screen(u'[' + (self._exes['avconv'] and 'avconv' or 'ffmpeg') + '] Destination: ' + new_path)
|
||||||
self.run_ffmpeg(path, new_path, acodec, more_opts)
|
self.run_ffmpeg(path, new_path, acodec, more_opts)
|
||||||
except:
|
except:
|
||||||
etype,e,tb = sys.exc_info()
|
etype,e,tb = sys.exc_info()
|
||||||
if isinstance(e, AudioConversionError):
|
if isinstance(e, AudioConversionError):
|
||||||
msg = u'audio conversion failed: ' + e.msg
|
msg = u'audio conversion failed: ' + e.msg
|
||||||
else:
|
else:
|
||||||
msg = u'error running ' + self._get_executable()
|
msg = u'error running ' + (self._exes['avconv'] and 'avconv' or 'ffmpeg')
|
||||||
raise PostProcessingError(msg)
|
raise PostProcessingError(msg)
|
||||||
|
|
||||||
# Try to update the date time for extracted audio file.
|
# Try to update the date time for extracted audio file.
|
||||||
@@ -197,7 +232,6 @@ class FFmpegExtractAudioPP(FFmpegPostProcessor):
|
|||||||
information['filepath'] = new_path
|
information['filepath'] = new_path
|
||||||
return self._nopostoverwrites,information
|
return self._nopostoverwrites,information
|
||||||
|
|
||||||
|
|
||||||
class FFmpegVideoConvertor(FFmpegPostProcessor):
|
class FFmpegVideoConvertor(FFmpegPostProcessor):
|
||||||
def __init__(self, downloader=None,preferedformat=None):
|
def __init__(self, downloader=None,preferedformat=None):
|
||||||
super(FFmpegVideoConvertor, self).__init__(downloader)
|
super(FFmpegVideoConvertor, self).__init__(downloader)
|
||||||
@@ -462,42 +496,16 @@ class FFmpegMetadataPP(FFmpegPostProcessor):
|
|||||||
return True, info
|
return True, info
|
||||||
|
|
||||||
filename = info['filepath']
|
filename = info['filepath']
|
||||||
temp_filename = prepend_extension(filename, 'temp')
|
ext = os.path.splitext(filename)[1][1:]
|
||||||
|
temp_filename = filename + u'.temp'
|
||||||
if info['ext'] == u'm4a':
|
|
||||||
options = ['-vn', '-acodec', 'copy']
|
|
||||||
else:
|
|
||||||
options = ['-c', 'copy']
|
|
||||||
|
|
||||||
|
options = ['-c', 'copy']
|
||||||
for (name, value) in metadata.items():
|
for (name, value) in metadata.items():
|
||||||
options.extend(['-metadata', '%s=%s' % (name, value)])
|
options.extend(['-metadata', '%s=%s' % (name, value)])
|
||||||
|
options.extend(['-f', ext])
|
||||||
|
|
||||||
self._downloader.to_screen(u'[ffmpeg] Adding metadata to \'%s\'' % filename)
|
self._downloader.to_screen(u'[ffmpeg] Adding metadata to \'%s\'' % filename)
|
||||||
self.run_ffmpeg(filename, temp_filename, options)
|
self.run_ffmpeg(filename, temp_filename, options)
|
||||||
os.remove(encodeFilename(filename))
|
os.remove(encodeFilename(filename))
|
||||||
os.rename(encodeFilename(temp_filename), encodeFilename(filename))
|
os.rename(encodeFilename(temp_filename), encodeFilename(filename))
|
||||||
return True, info
|
return True, info
|
||||||
|
|
||||||
|
|
||||||
class FFmpegMergerPP(FFmpegPostProcessor):
|
|
||||||
def run(self, info):
|
|
||||||
filename = info['filepath']
|
|
||||||
args = ['-c', 'copy']
|
|
||||||
self._downloader.to_screen(u'[ffmpeg] Merging formats into "%s"' % filename)
|
|
||||||
self.run_ffmpeg_multiple_files(info['__files_to_merge'], filename, args)
|
|
||||||
return True, info
|
|
||||||
|
|
||||||
|
|
||||||
class FFmpegAudioFixPP(FFmpegPostProcessor):
|
|
||||||
def run(self, info):
|
|
||||||
filename = info['filepath']
|
|
||||||
temp_filename = prepend_extension(filename, 'temp')
|
|
||||||
|
|
||||||
options = ['-vn', '-acodec', 'copy']
|
|
||||||
self._downloader.to_screen(u'[ffmpeg] Fixing audio file "%s"' % filename)
|
|
||||||
self.run_ffmpeg(filename, temp_filename, options)
|
|
||||||
|
|
||||||
os.remove(encodeFilename(filename))
|
|
||||||
os.rename(encodeFilename(temp_filename), encodeFilename(filename))
|
|
||||||
|
|
||||||
return True, info
|
|
||||||
803
youtube_dl/YoutubeDL.py
Executable file → Normal file
803
youtube_dl/YoutubeDL.py
Executable file → Normal file
File diff suppressed because it is too large
Load Diff
@@ -36,55 +36,31 @@ __authors__ = (
|
|||||||
'Marcin Cieślak',
|
'Marcin Cieślak',
|
||||||
'Anton Larionov',
|
'Anton Larionov',
|
||||||
'Takuya Tsuchida',
|
'Takuya Tsuchida',
|
||||||
'Sergey M.',
|
|
||||||
'Michael Orlitzky',
|
|
||||||
'Chris Gahan',
|
|
||||||
'Saimadhav Heblikar',
|
|
||||||
'Mike Col',
|
|
||||||
'Oleg Prutz',
|
|
||||||
'pulpe',
|
|
||||||
'Andreas Schmitz',
|
|
||||||
'Michael Kaiser',
|
|
||||||
'Niklas Laxström',
|
|
||||||
'David Triendl',
|
|
||||||
'Anthony Weems',
|
|
||||||
'David Wagner',
|
|
||||||
'Juan C. Olivares',
|
|
||||||
'Mattias Harrysson',
|
|
||||||
'phaer',
|
|
||||||
'Sainyam Kapoor',
|
|
||||||
'Nicolas Évrard',
|
|
||||||
'Jason Normore',
|
|
||||||
'Hoje Lee',
|
|
||||||
)
|
)
|
||||||
|
|
||||||
__license__ = 'Public Domain'
|
__license__ = 'Public Domain'
|
||||||
|
|
||||||
import codecs
|
import codecs
|
||||||
import io
|
import getpass
|
||||||
import locale
|
|
||||||
import optparse
|
import optparse
|
||||||
import os
|
import os
|
||||||
import random
|
import random
|
||||||
import re
|
import re
|
||||||
import shlex
|
import shlex
|
||||||
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
|
||||||
from .utils import (
|
from .utils import (
|
||||||
compat_getpass,
|
|
||||||
compat_print,
|
compat_print,
|
||||||
DateRange,
|
DateRange,
|
||||||
DEFAULT_OUTTMPL,
|
|
||||||
decodeOption,
|
decodeOption,
|
||||||
get_term_width,
|
determine_ext,
|
||||||
DownloadError,
|
DownloadError,
|
||||||
get_cachedir,
|
get_cachedir,
|
||||||
MaxDownloadsReached,
|
MaxDownloadsReached,
|
||||||
preferredencoding,
|
preferredencoding,
|
||||||
read_batch_urls,
|
|
||||||
SameFileError,
|
SameFileError,
|
||||||
setproctitle,
|
|
||||||
std_headers,
|
std_headers,
|
||||||
write_string,
|
write_string,
|
||||||
)
|
)
|
||||||
@@ -95,23 +71,20 @@ from .FileDownloader import (
|
|||||||
from .extractor import gen_extractors
|
from .extractor import gen_extractors
|
||||||
from .version import __version__
|
from .version import __version__
|
||||||
from .YoutubeDL import YoutubeDL
|
from .YoutubeDL import YoutubeDL
|
||||||
from .postprocessor import (
|
from .PostProcessor import (
|
||||||
AtomicParsleyPP,
|
|
||||||
FFmpegAudioFixPP,
|
|
||||||
FFmpegMetadataPP,
|
FFmpegMetadataPP,
|
||||||
FFmpegVideoConvertor,
|
FFmpegVideoConvertor,
|
||||||
FFmpegExtractAudioPP,
|
FFmpegExtractAudioPP,
|
||||||
FFmpegEmbedSubtitlePP,
|
FFmpegEmbedSubtitlePP,
|
||||||
XAttrMetadataPP,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def parseOpts(overrideArguments=None):
|
def parseOpts(overrideArguments=None):
|
||||||
def _readOptions(filename_bytes, default=[]):
|
def _readOptions(filename_bytes):
|
||||||
try:
|
try:
|
||||||
optionf = open(filename_bytes)
|
optionf = open(filename_bytes)
|
||||||
except IOError:
|
except IOError:
|
||||||
return default # silently skip if file is not present
|
return [] # silently skip if file is not present
|
||||||
try:
|
try:
|
||||||
res = []
|
res = []
|
||||||
for l in optionf:
|
for l in optionf:
|
||||||
@@ -120,43 +93,6 @@ def parseOpts(overrideArguments=None):
|
|||||||
optionf.close()
|
optionf.close()
|
||||||
return res
|
return res
|
||||||
|
|
||||||
def _readUserConf():
|
|
||||||
xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
|
|
||||||
if xdg_config_home:
|
|
||||||
userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
|
|
||||||
if not os.path.isfile(userConfFile):
|
|
||||||
userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
|
|
||||||
else:
|
|
||||||
userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl', 'config')
|
|
||||||
if not os.path.isfile(userConfFile):
|
|
||||||
userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
|
|
||||||
userConf = _readOptions(userConfFile, None)
|
|
||||||
|
|
||||||
if userConf is None:
|
|
||||||
appdata_dir = os.environ.get('appdata')
|
|
||||||
if appdata_dir:
|
|
||||||
userConf = _readOptions(
|
|
||||||
os.path.join(appdata_dir, 'youtube-dl', 'config'),
|
|
||||||
default=None)
|
|
||||||
if userConf is None:
|
|
||||||
userConf = _readOptions(
|
|
||||||
os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),
|
|
||||||
default=None)
|
|
||||||
|
|
||||||
if userConf is None:
|
|
||||||
userConf = _readOptions(
|
|
||||||
os.path.join(os.path.expanduser('~'), 'youtube-dl.conf'),
|
|
||||||
default=None)
|
|
||||||
if userConf is None:
|
|
||||||
userConf = _readOptions(
|
|
||||||
os.path.join(os.path.expanduser('~'), 'youtube-dl.conf.txt'),
|
|
||||||
default=None)
|
|
||||||
|
|
||||||
if userConf is None:
|
|
||||||
userConf = []
|
|
||||||
|
|
||||||
return userConf
|
|
||||||
|
|
||||||
def _format_option_string(option):
|
def _format_option_string(option):
|
||||||
''' ('-o', '--option') -> -o, --format METAVAR'''
|
''' ('-o', '--option') -> -o, --format METAVAR'''
|
||||||
|
|
||||||
@@ -176,6 +112,19 @@ def parseOpts(overrideArguments=None):
|
|||||||
def _comma_separated_values_options_callback(option, opt_str, value, parser):
|
def _comma_separated_values_options_callback(option, opt_str, value, parser):
|
||||||
setattr(parser.values, option.dest, value.split(','))
|
setattr(parser.values, option.dest, value.split(','))
|
||||||
|
|
||||||
|
def _find_term_columns():
|
||||||
|
columns = os.environ.get('COLUMNS', None)
|
||||||
|
if columns:
|
||||||
|
return int(columns)
|
||||||
|
|
||||||
|
try:
|
||||||
|
sp = subprocess.Popen(['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||||
|
out,err = sp.communicate()
|
||||||
|
return int(out.split()[1])
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
def _hide_login_info(opts):
|
def _hide_login_info(opts):
|
||||||
opts = list(opts)
|
opts = list(opts)
|
||||||
for private_opt in ['-p', '--password', '-u', '--username', '--video-password']:
|
for private_opt in ['-p', '--password', '-u', '--username', '--video-password']:
|
||||||
@@ -190,7 +139,7 @@ def parseOpts(overrideArguments=None):
|
|||||||
max_help_position = 80
|
max_help_position = 80
|
||||||
|
|
||||||
# No need to wrap help messages if we're on a wide console
|
# No need to wrap help messages if we're on a wide console
|
||||||
columns = get_term_width()
|
columns = _find_term_columns()
|
||||||
if columns: max_width = columns
|
if columns: max_width = columns
|
||||||
|
|
||||||
fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
|
fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
|
||||||
@@ -223,7 +172,7 @@ def parseOpts(overrideArguments=None):
|
|||||||
general.add_option('-U', '--update',
|
general.add_option('-U', '--update',
|
||||||
action='store_true', dest='update_self', help='update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
|
action='store_true', dest='update_self', help='update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
|
||||||
general.add_option('-i', '--ignore-errors',
|
general.add_option('-i', '--ignore-errors',
|
||||||
action='store_true', dest='ignoreerrors', help='continue on download errors, for example to skip unavailable videos in a playlist', default=False)
|
action='store_true', dest='ignoreerrors', help='continue on download errors, for example to to skip unavailable videos in a playlist', default=False)
|
||||||
general.add_option('--abort-on-error',
|
general.add_option('--abort-on-error',
|
||||||
action='store_false', dest='ignoreerrors',
|
action='store_false', dest='ignoreerrors',
|
||||||
help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
|
help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
|
||||||
@@ -235,54 +184,26 @@ def parseOpts(overrideArguments=None):
|
|||||||
general.add_option('--referer',
|
general.add_option('--referer',
|
||||||
dest='referer', help='specify a custom referer, use if the video access is restricted to one domain',
|
dest='referer', help='specify a custom referer, use if the video access is restricted to one domain',
|
||||||
metavar='REF', default=None)
|
metavar='REF', default=None)
|
||||||
general.add_option('--add-header',
|
|
||||||
dest='headers', help='specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times', action="append",
|
|
||||||
metavar='FIELD:VALUE')
|
|
||||||
general.add_option('--list-extractors',
|
general.add_option('--list-extractors',
|
||||||
action='store_true', dest='list_extractors',
|
action='store_true', dest='list_extractors',
|
||||||
help='List all supported extractors and the URLs they would handle', default=False)
|
help='List all supported extractors and the URLs they would handle', default=False)
|
||||||
general.add_option('--extractor-descriptions',
|
general.add_option('--extractor-descriptions',
|
||||||
action='store_true', dest='list_extractor_descriptions',
|
action='store_true', dest='list_extractor_descriptions',
|
||||||
help='Output descriptions of all supported extractors', default=False)
|
help='Output descriptions of all supported extractors', default=False)
|
||||||
general.add_option(
|
general.add_option('--proxy', dest='proxy', default=None, help='Use the specified HTTP/HTTPS proxy', metavar='URL')
|
||||||
'--proxy', dest='proxy', default=None, metavar='URL',
|
|
||||||
help='Use the specified HTTP/HTTPS proxy. Pass in an empty string (--proxy "") for direct connection')
|
|
||||||
general.add_option('--no-check-certificate', action='store_true', dest='no_check_certificate', default=False, help='Suppress HTTPS certificate validation.')
|
general.add_option('--no-check-certificate', action='store_true', dest='no_check_certificate', default=False, help='Suppress HTTPS certificate validation.')
|
||||||
general.add_option(
|
|
||||||
'--prefer-insecure', '--prefer-unsecure', action='store_true', dest='prefer_insecure',
|
|
||||||
help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
|
|
||||||
general.add_option(
|
general.add_option(
|
||||||
'--cache-dir', dest='cachedir', default=get_cachedir(), metavar='DIR',
|
'--cache-dir', dest='cachedir', default=get_cachedir(), 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 downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl .')
|
||||||
general.add_option(
|
general.add_option(
|
||||||
'--no-cache-dir', action='store_const', const=None, dest='cachedir',
|
'--no-cache-dir', action='store_const', const=None, dest='cachedir',
|
||||||
help='Disable filesystem caching')
|
help='Disable filesystem caching')
|
||||||
general.add_option(
|
|
||||||
'--socket-timeout', dest='socket_timeout',
|
|
||||||
type=float, default=None, help=u'Time to wait before giving up, in seconds')
|
|
||||||
general.add_option(
|
|
||||||
'--bidi-workaround', dest='bidi_workaround', action='store_true',
|
|
||||||
help=u'Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
|
|
||||||
general.add_option(
|
|
||||||
'--default-search',
|
|
||||||
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". By default (with value "auto") youtube-dl guesses.')
|
|
||||||
general.add_option(
|
|
||||||
'--ignore-config',
|
|
||||||
action='store_true',
|
|
||||||
help='Do not read configuration files. When given in the global configuration file /etc/youtube-dl.conf: do not read the user configuration in ~/.config/youtube-dl.conf (%APPDATA%/youtube-dl/config.txt on Windows)')
|
|
||||||
general.add_option(
|
|
||||||
'--encoding', dest='encoding', metavar='ENCODING',
|
|
||||||
help='Force the specified encoding (experimental)')
|
|
||||||
|
|
||||||
selection.add_option(
|
|
||||||
'--playlist-start',
|
selection.add_option('--playlist-start',
|
||||||
dest='playliststart', metavar='NUMBER', default=1, type=int,
|
dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is %default)', default=1)
|
||||||
help='playlist video to start at (default is %default)')
|
selection.add_option('--playlist-end',
|
||||||
selection.add_option(
|
dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
|
||||||
'--playlist-end',
|
|
||||||
dest='playlistend', metavar='NUMBER', default=None, type=int,
|
|
||||||
help='playlist video to end at (default is last)')
|
|
||||||
selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
|
selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
|
||||||
selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
|
selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
|
||||||
selection.add_option('--max-downloads', metavar='NUMBER',
|
selection.add_option('--max-downloads', metavar='NUMBER',
|
||||||
@@ -291,35 +212,16 @@ def parseOpts(overrideArguments=None):
|
|||||||
selection.add_option('--min-filesize', metavar='SIZE', dest='min_filesize', help="Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)", default=None)
|
selection.add_option('--min-filesize', metavar='SIZE', dest='min_filesize', help="Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)", default=None)
|
||||||
selection.add_option('--max-filesize', metavar='SIZE', dest='max_filesize', help="Do not download any videos larger than SIZE (e.g. 50k or 44.6m)", default=None)
|
selection.add_option('--max-filesize', metavar='SIZE', dest='max_filesize', help="Do not download any videos larger than SIZE (e.g. 50k or 44.6m)", default=None)
|
||||||
selection.add_option('--date', metavar='DATE', dest='date', help='download only videos uploaded in this date', default=None)
|
selection.add_option('--date', metavar='DATE', dest='date', help='download only videos uploaded in this date', default=None)
|
||||||
selection.add_option(
|
selection.add_option('--datebefore', metavar='DATE', dest='datebefore', help='download only videos uploaded before this date', default=None)
|
||||||
'--datebefore', metavar='DATE', dest='datebefore', default=None,
|
selection.add_option('--dateafter', metavar='DATE', dest='dateafter', help='download only videos uploaded after this date', default=None)
|
||||||
help='download only videos uploaded on or before this date (i.e. inclusive)')
|
|
||||||
selection.add_option(
|
|
||||||
'--dateafter', metavar='DATE', dest='dateafter', default=None,
|
|
||||||
help='download only videos uploaded on or after this date (i.e. inclusive)')
|
|
||||||
selection.add_option(
|
|
||||||
'--min-views', metavar='COUNT', dest='min_views',
|
|
||||||
default=None, type=int,
|
|
||||||
help="Do not download any videos with less than COUNT views",)
|
|
||||||
selection.add_option(
|
|
||||||
'--max-views', metavar='COUNT', dest='max_views',
|
|
||||||
default=None, type=int,
|
|
||||||
help="Do not download any videos with more than COUNT views",)
|
|
||||||
selection.add_option('--no-playlist', action='store_true', dest='noplaylist', help='download only the currently playing video', default=False)
|
selection.add_option('--no-playlist', action='store_true', dest='noplaylist', help='download only the currently playing video', default=False)
|
||||||
selection.add_option('--age-limit', metavar='YEARS', dest='age_limit',
|
selection.add_option('--age-limit', metavar='YEARS', dest='age_limit',
|
||||||
help='download only videos suitable for the given age',
|
help='download only videos suitable for the given age',
|
||||||
default=None, type=int)
|
default=None, type=int)
|
||||||
selection.add_option('--download-archive', metavar='FILE',
|
selection.add_option('--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 present in the archive file. Record all downloaded videos in it.')
|
||||||
selection.add_option(
|
|
||||||
'--include-ads', dest='include_ads',
|
|
||||||
action='store_true',
|
|
||||||
help='Download advertisements as well (experimental)')
|
|
||||||
selection.add_option(
|
|
||||||
'--youtube-include-dash-manifest', action='store_true',
|
|
||||||
dest='youtube_include_dash_manifest', default=False,
|
|
||||||
help='Try to download the DASH manifest on YouTube videos (experimental)')
|
|
||||||
|
|
||||||
authentication.add_option('-u', '--username',
|
authentication.add_option('-u', '--username',
|
||||||
dest='username', metavar='USERNAME', help='account username')
|
dest='username', metavar='USERNAME', help='account username')
|
||||||
@@ -328,12 +230,12 @@ def parseOpts(overrideArguments=None):
|
|||||||
authentication.add_option('-n', '--netrc',
|
authentication.add_option('-n', '--netrc',
|
||||||
action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
|
action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
|
||||||
authentication.add_option('--video-password',
|
authentication.add_option('--video-password',
|
||||||
dest='videopassword', metavar='PASSWORD', help='video password (vimeo, smotri)')
|
dest='videopassword', metavar='PASSWORD', help='video password (vimeo only)')
|
||||||
|
|
||||||
|
|
||||||
video_format.add_option('-f', '--format',
|
video_format.add_option('-f', '--format',
|
||||||
action='store', dest='format', metavar='FORMAT', default=None,
|
action='store', dest='format', metavar='FORMAT', default='best',
|
||||||
help='video format code, specify the order of preference using slashes: "-f 22/17/18". "-f mp4" and "-f flv" are also supported. You can also use the special names "best", "bestvideo", "bestaudio", "worst", "worstvideo" and "worstaudio". By default, youtube-dl will pick the best quality.')
|
help='video format code, specifiy the order of preference using slashes: "-f 22/17/18". "-f mp4" and "-f flv" are also supported')
|
||||||
video_format.add_option('--all-formats',
|
video_format.add_option('--all-formats',
|
||||||
action='store_const', dest='format', help='download all available video formats', const='all')
|
action='store_const', dest='format', help='download all available video formats', const='all')
|
||||||
video_format.add_option('--prefer-free-formats',
|
video_format.add_option('--prefer-free-formats',
|
||||||
@@ -341,7 +243,7 @@ def parseOpts(overrideArguments=None):
|
|||||||
video_format.add_option('--max-quality',
|
video_format.add_option('--max-quality',
|
||||||
action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
|
action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
|
||||||
video_format.add_option('-F', '--list-formats',
|
video_format.add_option('-F', '--list-formats',
|
||||||
action='store_true', dest='listformats', help='list all available formats')
|
action='store_true', dest='listformats', help='list all available formats (currently youtube only)')
|
||||||
|
|
||||||
subtitles.add_option('--write-sub', '--write-srt',
|
subtitles.add_option('--write-sub', '--write-srt',
|
||||||
action='store_true', dest='writesubtitles',
|
action='store_true', dest='writesubtitles',
|
||||||
@@ -376,10 +278,6 @@ def parseOpts(overrideArguments=None):
|
|||||||
|
|
||||||
verbosity.add_option('-q', '--quiet',
|
verbosity.add_option('-q', '--quiet',
|
||||||
action='store_true', dest='quiet', help='activates quiet mode', default=False)
|
action='store_true', dest='quiet', help='activates quiet mode', default=False)
|
||||||
verbosity.add_option(
|
|
||||||
'--no-warnings',
|
|
||||||
dest='no_warnings', action='store_true', default=False,
|
|
||||||
help='Ignore warnings')
|
|
||||||
verbosity.add_option('-s', '--simulate',
|
verbosity.add_option('-s', '--simulate',
|
||||||
action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
|
action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
|
||||||
verbosity.add_option('--skip-download',
|
verbosity.add_option('--skip-download',
|
||||||
@@ -396,9 +294,6 @@ def parseOpts(overrideArguments=None):
|
|||||||
verbosity.add_option('--get-description',
|
verbosity.add_option('--get-description',
|
||||||
action='store_true', dest='getdescription',
|
action='store_true', dest='getdescription',
|
||||||
help='simulate, quiet but print video description', default=False)
|
help='simulate, quiet but print video description', default=False)
|
||||||
verbosity.add_option('--get-duration',
|
|
||||||
action='store_true', dest='getduration',
|
|
||||||
help='simulate, quiet but print video length', default=False)
|
|
||||||
verbosity.add_option('--get-filename',
|
verbosity.add_option('--get-filename',
|
||||||
action='store_true', dest='getfilename',
|
action='store_true', dest='getfilename',
|
||||||
help='simulate, quiet but print output filename', default=False)
|
help='simulate, quiet but print output filename', default=False)
|
||||||
@@ -407,7 +302,7 @@ def parseOpts(overrideArguments=None):
|
|||||||
help='simulate, quiet but print output format', default=False)
|
help='simulate, quiet but print output format', default=False)
|
||||||
verbosity.add_option('-j', '--dump-json',
|
verbosity.add_option('-j', '--dump-json',
|
||||||
action='store_true', dest='dumpjson',
|
action='store_true', dest='dumpjson',
|
||||||
help='simulate, quiet but print JSON information. See --output for a description of available keys.', default=False)
|
help='simulate, quiet but print JSON information', default=False)
|
||||||
verbosity.add_option('--newline',
|
verbosity.add_option('--newline',
|
||||||
action='store_true', dest='progress_with_newline', help='output progress bar as new lines', default=False)
|
action='store_true', dest='progress_with_newline', help='output progress bar as new lines', default=False)
|
||||||
verbosity.add_option('--no-progress',
|
verbosity.add_option('--no-progress',
|
||||||
@@ -419,16 +314,13 @@ def parseOpts(overrideArguments=None):
|
|||||||
action='store_true', dest='verbose', help='print various debugging information', default=False)
|
action='store_true', dest='verbose', help='print various debugging information', default=False)
|
||||||
verbosity.add_option('--dump-intermediate-pages',
|
verbosity.add_option('--dump-intermediate-pages',
|
||||||
action='store_true', dest='dump_intermediate_pages', default=False,
|
action='store_true', dest='dump_intermediate_pages', default=False,
|
||||||
help='print downloaded pages to debug problems (very verbose)')
|
help='print downloaded pages to debug problems(very verbose)')
|
||||||
verbosity.add_option('--write-pages',
|
verbosity.add_option('--write-pages',
|
||||||
action='store_true', dest='write_pages', default=False,
|
action='store_true', dest='write_pages', default=False,
|
||||||
help='Write downloaded intermediary pages to files in the current directory to debug problems')
|
help='Write downloaded pages to files in the current directory')
|
||||||
verbosity.add_option('--youtube-print-sig-code',
|
verbosity.add_option('--youtube-print-sig-code',
|
||||||
action='store_true', dest='youtube_print_sig_code', default=False,
|
action='store_true', dest='youtube_print_sig_code', default=False,
|
||||||
help=optparse.SUPPRESS_HELP)
|
help=optparse.SUPPRESS_HELP)
|
||||||
verbosity.add_option('--print-traffic',
|
|
||||||
dest='debug_printtraffic', action='store_true', default=False,
|
|
||||||
help='Display sent and read HTTP traffic')
|
|
||||||
|
|
||||||
|
|
||||||
filesystem.add_option('-t', '--title',
|
filesystem.add_option('-t', '--title',
|
||||||
@@ -446,14 +338,12 @@ def parseOpts(overrideArguments=None):
|
|||||||
'%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
|
'%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
|
||||||
'%(autonumber)s to get an automatically incremented number, '
|
'%(autonumber)s to get an automatically incremented number, '
|
||||||
'%(ext)s for the filename extension, '
|
'%(ext)s for the filename extension, '
|
||||||
'%(format)s for the format description (like "22 - 1280x720" or "HD"), '
|
'%(format)s for the format description (like "22 - 1280x720" or "HD"),'
|
||||||
'%(format_id)s for the unique id of the format (like Youtube\'s itags: "137"), '
|
'%(format_id)s for the unique id of the format (like Youtube\'s itags: "137"),'
|
||||||
'%(upload_date)s for the upload date (YYYYMMDD), '
|
'%(upload_date)s for the upload date (YYYYMMDD), '
|
||||||
'%(extractor)s for the provider (youtube, metacafe, etc), '
|
'%(extractor)s for the provider (youtube, metacafe, etc), '
|
||||||
'%(id)s for the video id, %(playlist)s for the playlist the video is in, '
|
'%(id)s for the video id , %(playlist)s for the playlist the video is in, '
|
||||||
'%(playlist_index)s for the position in the playlist and %% for a literal percent. '
|
'%(playlist_index)s for the position in the playlist and %% for a literal percent. '
|
||||||
'%(height)s and %(width)s for the width and height of the video format. '
|
|
||||||
'%(resolution)s for a textual description of the resolution of the video format. '
|
|
||||||
'Use - to output to stdout. Can also be used to download to a different directory, '
|
'Use - to output to stdout. Can also be used to download to a different directory, '
|
||||||
'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
|
'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
|
||||||
filesystem.add_option('--autonumber-size',
|
filesystem.add_option('--autonumber-size',
|
||||||
@@ -464,9 +354,6 @@ def parseOpts(overrideArguments=None):
|
|||||||
help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
|
help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
|
||||||
filesystem.add_option('-a', '--batch-file',
|
filesystem.add_option('-a', '--batch-file',
|
||||||
dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
|
dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
|
||||||
filesystem.add_option('--load-info',
|
|
||||||
dest='load_info_filename', metavar='FILE',
|
|
||||||
help='json file containing the video information (created with the "--write-json" option)')
|
|
||||||
filesystem.add_option('-w', '--no-overwrites',
|
filesystem.add_option('-w', '--no-overwrites',
|
||||||
action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
|
action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
|
||||||
filesystem.add_option('-c', '--continue',
|
filesystem.add_option('-c', '--continue',
|
||||||
@@ -509,16 +396,8 @@ def parseOpts(overrideArguments=None):
|
|||||||
help='do not overwrite post-processed files; the post-processed files are overwritten by default')
|
help='do not overwrite post-processed files; the post-processed files are overwritten by default')
|
||||||
postproc.add_option('--embed-subs', action='store_true', dest='embedsubtitles', default=False,
|
postproc.add_option('--embed-subs', action='store_true', dest='embedsubtitles', default=False,
|
||||||
help='embed subtitles in the video (only for mp4 videos)')
|
help='embed subtitles in the video (only for mp4 videos)')
|
||||||
postproc.add_option('--embed-thumbnail', action='store_true', dest='embedthumbnail', default=False,
|
|
||||||
help='embed thumbnail in the audio as cover art')
|
|
||||||
postproc.add_option('--add-metadata', action='store_true', dest='addmetadata', default=False,
|
postproc.add_option('--add-metadata', action='store_true', dest='addmetadata', default=False,
|
||||||
help='write metadata to the video file')
|
help='add metadata to the files')
|
||||||
postproc.add_option('--xattrs', action='store_true', dest='xattrs', default=False,
|
|
||||||
help='write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
|
|
||||||
postproc.add_option('--prefer-avconv', action='store_false', dest='prefer_ffmpeg',
|
|
||||||
help='Prefer avconv over ffmpeg for running the postprocessors (default)')
|
|
||||||
postproc.add_option('--prefer-ffmpeg', action='store_true', dest='prefer_ffmpeg',
|
|
||||||
help='Prefer ffmpeg over avconv for running the postprocessors')
|
|
||||||
|
|
||||||
|
|
||||||
parser.add_option_group(general)
|
parser.add_option_group(general)
|
||||||
@@ -536,18 +415,19 @@ def parseOpts(overrideArguments=None):
|
|||||||
if opts.verbose:
|
if opts.verbose:
|
||||||
write_string(u'[debug] Override config: ' + repr(overrideArguments) + '\n')
|
write_string(u'[debug] Override config: ' + repr(overrideArguments) + '\n')
|
||||||
else:
|
else:
|
||||||
commandLineConf = sys.argv[1:]
|
xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
|
||||||
if '--ignore-config' in commandLineConf:
|
if xdg_config_home:
|
||||||
systemConf = []
|
userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
|
||||||
userConf = []
|
if not os.path.isfile(userConfFile):
|
||||||
|
userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
|
||||||
else:
|
else:
|
||||||
systemConf = _readOptions('/etc/youtube-dl.conf')
|
userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl', 'config')
|
||||||
if '--ignore-config' in systemConf:
|
if not os.path.isfile(userConfFile):
|
||||||
userConf = []
|
userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
|
||||||
else:
|
systemConf = _readOptions('/etc/youtube-dl.conf')
|
||||||
userConf = _readUserConf()
|
userConf = _readOptions(userConfFile)
|
||||||
|
commandLineConf = sys.argv[1:]
|
||||||
argv = systemConf + userConf + commandLineConf
|
argv = systemConf + userConf + commandLineConf
|
||||||
|
|
||||||
opts, args = parser.parse_args(argv)
|
opts, args = parser.parse_args(argv)
|
||||||
if opts.verbose:
|
if opts.verbose:
|
||||||
write_string(u'[debug] System config: ' + repr(_hide_login_info(systemConf)) + '\n')
|
write_string(u'[debug] System config: ' + repr(_hide_login_info(systemConf)) + '\n')
|
||||||
@@ -556,15 +436,12 @@ def parseOpts(overrideArguments=None):
|
|||||||
|
|
||||||
return parser, opts, args
|
return parser, opts, args
|
||||||
|
|
||||||
|
|
||||||
def _real_main(argv=None):
|
def _real_main(argv=None):
|
||||||
# Compatibility fixes for Windows
|
# Compatibility fixes for Windows
|
||||||
if sys.platform == 'win32':
|
if sys.platform == 'win32':
|
||||||
# https://github.com/rg3/youtube-dl/issues/820
|
# https://github.com/rg3/youtube-dl/issues/820
|
||||||
codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
|
codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
|
||||||
|
|
||||||
setproctitle(u'youtube-dl')
|
|
||||||
|
|
||||||
parser, opts, args = parseOpts(argv)
|
parser, opts, args = parseOpts(argv)
|
||||||
|
|
||||||
# Set user agent
|
# Set user agent
|
||||||
@@ -575,38 +452,28 @@ def _real_main(argv=None):
|
|||||||
if opts.referer is not None:
|
if opts.referer is not None:
|
||||||
std_headers['Referer'] = opts.referer
|
std_headers['Referer'] = opts.referer
|
||||||
|
|
||||||
# Custom HTTP headers
|
|
||||||
if opts.headers is not None:
|
|
||||||
for h in opts.headers:
|
|
||||||
if h.find(':', 1) < 0:
|
|
||||||
parser.error(u'wrong header formatting, it should be key:value, not "%s"'%h)
|
|
||||||
key, value = h.split(':', 2)
|
|
||||||
if opts.verbose:
|
|
||||||
write_string(u'[debug] Adding header from command line option %s:%s\n'%(key, value))
|
|
||||||
std_headers[key] = value
|
|
||||||
|
|
||||||
# Dump user agent
|
# Dump user agent
|
||||||
if opts.dump_user_agent:
|
if opts.dump_user_agent:
|
||||||
compat_print(std_headers['User-Agent'])
|
compat_print(std_headers['User-Agent'])
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
# Batch file verification
|
# Batch file verification
|
||||||
batch_urls = []
|
batchurls = []
|
||||||
if opts.batchfile is not None:
|
if opts.batchfile is not None:
|
||||||
try:
|
try:
|
||||||
if opts.batchfile == '-':
|
if opts.batchfile == '-':
|
||||||
batchfd = sys.stdin
|
batchfd = sys.stdin
|
||||||
else:
|
else:
|
||||||
batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
|
batchfd = open(opts.batchfile, 'r')
|
||||||
batch_urls = read_batch_urls(batchfd)
|
batchurls = batchfd.readlines()
|
||||||
|
batchurls = [x.strip() for x in batchurls]
|
||||||
|
batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
|
||||||
if opts.verbose:
|
if opts.verbose:
|
||||||
write_string(u'[debug] Batch file urls: ' + repr(batch_urls) + u'\n')
|
write_string(u'[debug] Batch file urls: ' + repr(batchurls) + u'\n')
|
||||||
except IOError:
|
except IOError:
|
||||||
sys.exit(u'ERROR: batch file could not be read')
|
sys.exit(u'ERROR: batch file could not be read')
|
||||||
all_urls = batch_urls + args
|
all_urls = batchurls + args
|
||||||
all_urls = [url.strip() for url in all_urls]
|
all_urls = [url.strip() for url in all_urls]
|
||||||
_enc = preferredencoding()
|
|
||||||
all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
|
|
||||||
|
|
||||||
extractors = gen_extractors()
|
extractors = gen_extractors()
|
||||||
|
|
||||||
@@ -614,6 +481,7 @@ def _real_main(argv=None):
|
|||||||
for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
|
for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
|
||||||
compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
|
compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
|
||||||
matchedUrls = [url for url in all_urls if ie.suitable(url)]
|
matchedUrls = [url for url in all_urls if ie.suitable(url)]
|
||||||
|
all_urls = [url for url in all_urls if url not in matchedUrls]
|
||||||
for mu in matchedUrls:
|
for mu in matchedUrls:
|
||||||
compat_print(u' ' + mu)
|
compat_print(u' ' + mu)
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
@@ -636,13 +504,13 @@ def _real_main(argv=None):
|
|||||||
if opts.usenetrc and (opts.username is not None or opts.password is not None):
|
if opts.usenetrc and (opts.username is not None or opts.password is not None):
|
||||||
parser.error(u'using .netrc conflicts with giving username/password')
|
parser.error(u'using .netrc conflicts with giving username/password')
|
||||||
if opts.password is not None and opts.username is None:
|
if opts.password is not None and opts.username is None:
|
||||||
parser.error(u'account username missing\n')
|
parser.error(u' account username missing\n')
|
||||||
if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
|
if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
|
||||||
parser.error(u'using output template conflicts with using title, video ID or auto number')
|
parser.error(u'using output template conflicts with using title, video ID or auto number')
|
||||||
if opts.usetitle and opts.useid:
|
if opts.usetitle and opts.useid:
|
||||||
parser.error(u'using title conflicts with using video ID')
|
parser.error(u'using title conflicts with using video ID')
|
||||||
if opts.username is not None and opts.password is None:
|
if opts.username is not None and opts.password is None:
|
||||||
opts.password = compat_getpass(u'Type account password and press [Return]: ')
|
opts.password = getpass.getpass(u'Type account password and press return:')
|
||||||
if opts.ratelimit is not None:
|
if opts.ratelimit is not None:
|
||||||
numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
|
numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
|
||||||
if numeric_limit is None:
|
if numeric_limit is None:
|
||||||
@@ -668,10 +536,18 @@ def _real_main(argv=None):
|
|||||||
if numeric_buffersize is None:
|
if numeric_buffersize is None:
|
||||||
parser.error(u'invalid buffer size specified')
|
parser.error(u'invalid buffer size specified')
|
||||||
opts.buffersize = numeric_buffersize
|
opts.buffersize = numeric_buffersize
|
||||||
if opts.playliststart <= 0:
|
try:
|
||||||
raise ValueError(u'Playlist start must be positive')
|
opts.playliststart = int(opts.playliststart)
|
||||||
if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
|
if opts.playliststart <= 0:
|
||||||
raise ValueError(u'Playlist end must be greater than playlist start')
|
raise ValueError(u'Playlist start must be positive')
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
parser.error(u'invalid playlist start number specified')
|
||||||
|
try:
|
||||||
|
opts.playlistend = int(opts.playlistend)
|
||||||
|
if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
|
||||||
|
raise ValueError(u'Playlist end must be greater than playlist start')
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
parser.error(u'invalid playlist end number specified')
|
||||||
if opts.extractaudio:
|
if opts.extractaudio:
|
||||||
if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
|
if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
|
||||||
parser.error(u'invalid audio format specified')
|
parser.error(u'invalid audio format specified')
|
||||||
@@ -680,18 +556,12 @@ def _real_main(argv=None):
|
|||||||
if not opts.audioquality.isdigit():
|
if not opts.audioquality.isdigit():
|
||||||
parser.error(u'invalid audio quality specified')
|
parser.error(u'invalid audio quality specified')
|
||||||
if opts.recodevideo is not None:
|
if opts.recodevideo is not None:
|
||||||
if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
|
if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg']:
|
||||||
parser.error(u'invalid video recode format specified')
|
parser.error(u'invalid video recode format specified')
|
||||||
if opts.date is not None:
|
if opts.date is not None:
|
||||||
date = DateRange.day(opts.date)
|
date = DateRange.day(opts.date)
|
||||||
else:
|
else:
|
||||||
date = DateRange(opts.dateafter, opts.datebefore)
|
date = DateRange(opts.dateafter, opts.datebefore)
|
||||||
if opts.default_search not in ('auto', 'auto_warning', None) and ':' not in opts.default_search:
|
|
||||||
parser.error(u'--default-search invalid; did you forget a colon (:) at the end?')
|
|
||||||
|
|
||||||
# Do not download videos when there are audio-only formats
|
|
||||||
if opts.extractaudio and not opts.keepvideo and opts.format is None:
|
|
||||||
opts.format = 'bestaudio/best'
|
|
||||||
|
|
||||||
# --all-sub automatically sets --write-sub if --write-auto-sub is not given
|
# --all-sub automatically sets --write-sub if --write-auto-sub is not given
|
||||||
# this was the old behaviour if only --all-sub was given.
|
# this was the old behaviour if only --all-sub was given.
|
||||||
@@ -709,33 +579,28 @@ def _real_main(argv=None):
|
|||||||
or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
|
or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
|
||||||
or (opts.useid and u'%(id)s.%(ext)s')
|
or (opts.useid and u'%(id)s.%(ext)s')
|
||||||
or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
|
or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
|
||||||
or DEFAULT_OUTTMPL)
|
or u'%(title)s-%(id)s.%(ext)s')
|
||||||
if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
|
if '%(ext)s' not in outtmpl and opts.extractaudio:
|
||||||
parser.error(u'Cannot download a video and extract audio into the same'
|
parser.error(u'Cannot download a video and extract audio into the same'
|
||||||
u' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
|
u' file! Use "%%(ext)s" instead of %r' %
|
||||||
u' template'.format(outtmpl))
|
determine_ext(outtmpl, u''))
|
||||||
|
|
||||||
any_printing = opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat or opts.getduration or opts.dumpjson
|
|
||||||
download_archive_fn = os.path.expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
|
|
||||||
|
|
||||||
ydl_opts = {
|
ydl_opts = {
|
||||||
'usenetrc': opts.usenetrc,
|
'usenetrc': opts.usenetrc,
|
||||||
'username': opts.username,
|
'username': opts.username,
|
||||||
'password': opts.password,
|
'password': opts.password,
|
||||||
'videopassword': opts.videopassword,
|
'videopassword': opts.videopassword,
|
||||||
'quiet': (opts.quiet or any_printing),
|
'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat or opts.dumpjson),
|
||||||
'no_warnings': opts.no_warnings,
|
|
||||||
'forceurl': opts.geturl,
|
'forceurl': opts.geturl,
|
||||||
'forcetitle': opts.gettitle,
|
'forcetitle': opts.gettitle,
|
||||||
'forceid': opts.getid,
|
'forceid': opts.getid,
|
||||||
'forcethumbnail': opts.getthumbnail,
|
'forcethumbnail': opts.getthumbnail,
|
||||||
'forcedescription': opts.getdescription,
|
'forcedescription': opts.getdescription,
|
||||||
'forceduration': opts.getduration,
|
|
||||||
'forcefilename': opts.getfilename,
|
'forcefilename': opts.getfilename,
|
||||||
'forceformat': opts.getformat,
|
'forceformat': opts.getformat,
|
||||||
'forcejson': opts.dumpjson,
|
'forcejson': opts.dumpjson,
|
||||||
'simulate': opts.simulate,
|
'simulate': opts.simulate,
|
||||||
'skip_download': (opts.skip_download or opts.simulate or any_printing),
|
'skip_download': (opts.skip_download or opts.simulate or opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat or opts.dumpjson),
|
||||||
'format': opts.format,
|
'format': opts.format,
|
||||||
'format_limit': opts.format_limit,
|
'format_limit': opts.format_limit,
|
||||||
'listformats': opts.listformats,
|
'listformats': opts.listformats,
|
||||||
@@ -779,25 +644,13 @@ def _real_main(argv=None):
|
|||||||
'keepvideo': opts.keepvideo,
|
'keepvideo': opts.keepvideo,
|
||||||
'min_filesize': opts.min_filesize,
|
'min_filesize': opts.min_filesize,
|
||||||
'max_filesize': opts.max_filesize,
|
'max_filesize': opts.max_filesize,
|
||||||
'min_views': opts.min_views,
|
|
||||||
'max_views': opts.max_views,
|
|
||||||
'daterange': date,
|
'daterange': date,
|
||||||
'cachedir': opts.cachedir,
|
'cachedir': opts.cachedir,
|
||||||
'youtube_print_sig_code': opts.youtube_print_sig_code,
|
'youtube_print_sig_code': opts.youtube_print_sig_code,
|
||||||
'age_limit': opts.age_limit,
|
'age_limit': opts.age_limit,
|
||||||
'download_archive': download_archive_fn,
|
'download_archive': opts.download_archive,
|
||||||
'cookiefile': opts.cookiefile,
|
'cookiefile': opts.cookiefile,
|
||||||
'nocheckcertificate': opts.no_check_certificate,
|
'nocheckcertificate': opts.no_check_certificate,
|
||||||
'prefer_insecure': opts.prefer_insecure,
|
|
||||||
'proxy': opts.proxy,
|
|
||||||
'socket_timeout': opts.socket_timeout,
|
|
||||||
'bidi_workaround': opts.bidi_workaround,
|
|
||||||
'debug_printtraffic': opts.debug_printtraffic,
|
|
||||||
'prefer_ffmpeg': opts.prefer_ffmpeg,
|
|
||||||
'include_ads': opts.include_ads,
|
|
||||||
'default_search': opts.default_search,
|
|
||||||
'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
|
|
||||||
'encoding': opts.encoding,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
with YoutubeDL(ydl_opts) as ydl:
|
with YoutubeDL(ydl_opts) as ydl:
|
||||||
@@ -814,29 +667,20 @@ def _real_main(argv=None):
|
|||||||
ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
|
ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
|
||||||
if opts.embedsubtitles:
|
if opts.embedsubtitles:
|
||||||
ydl.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat=opts.subtitlesformat))
|
ydl.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat=opts.subtitlesformat))
|
||||||
if opts.xattrs:
|
|
||||||
ydl.add_post_processor(XAttrMetadataPP())
|
|
||||||
if opts.embedthumbnail:
|
|
||||||
if not opts.addmetadata:
|
|
||||||
ydl.add_post_processor(FFmpegAudioFixPP())
|
|
||||||
ydl.add_post_processor(AtomicParsleyPP())
|
|
||||||
|
|
||||||
# Update version
|
# Update version
|
||||||
if opts.update_self:
|
if opts.update_self:
|
||||||
update_self(ydl.to_screen, opts.verbose)
|
update_self(ydl.to_screen, opts.verbose)
|
||||||
|
|
||||||
# Maybe do nothing
|
# Maybe do nothing
|
||||||
if (len(all_urls) < 1) and (opts.load_info_filename is None):
|
if len(all_urls) < 1:
|
||||||
if not opts.update_self:
|
if not opts.update_self:
|
||||||
parser.error(u'you must provide at least one URL')
|
parser.error(u'you must provide at least one URL')
|
||||||
else:
|
else:
|
||||||
sys.exit()
|
sys.exit()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if opts.load_info_filename is not None:
|
retcode = ydl.download(all_urls)
|
||||||
retcode = ydl.download_with_info_file(opts.load_info_filename)
|
|
||||||
else:
|
|
||||||
retcode = ydl.download(all_urls)
|
|
||||||
except MaxDownloadsReached:
|
except MaxDownloadsReached:
|
||||||
ydl.to_screen(u'--max-download limit reached, aborting.')
|
ydl.to_screen(u'--max-download limit reached, aborting.')
|
||||||
retcode = 101
|
retcode = 101
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text']
|
__all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_decrypt_text']
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
from math import ceil
|
from math import ceil
|
||||||
@@ -32,31 +32,6 @@ def aes_ctr_decrypt(data, key, counter):
|
|||||||
|
|
||||||
return decrypted_data
|
return decrypted_data
|
||||||
|
|
||||||
def aes_cbc_decrypt(data, key, iv):
|
|
||||||
"""
|
|
||||||
Decrypt with aes in CBC mode
|
|
||||||
|
|
||||||
@param {int[]} data cipher
|
|
||||||
@param {int[]} key 16/24/32-Byte cipher key
|
|
||||||
@param {int[]} iv 16-Byte IV
|
|
||||||
@returns {int[]} decrypted data
|
|
||||||
"""
|
|
||||||
expanded_key = key_expansion(key)
|
|
||||||
block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES))
|
|
||||||
|
|
||||||
decrypted_data=[]
|
|
||||||
previous_cipher_block = iv
|
|
||||||
for i in range(block_count):
|
|
||||||
block = data[i*BLOCK_SIZE_BYTES : (i+1)*BLOCK_SIZE_BYTES]
|
|
||||||
block += [0]*(BLOCK_SIZE_BYTES - len(block))
|
|
||||||
|
|
||||||
decrypted_block = aes_decrypt(block, expanded_key)
|
|
||||||
decrypted_data += xor(decrypted_block, previous_cipher_block)
|
|
||||||
previous_cipher_block = block
|
|
||||||
decrypted_data = decrypted_data[:len(data)]
|
|
||||||
|
|
||||||
return decrypted_data
|
|
||||||
|
|
||||||
def key_expansion(data):
|
def key_expansion(data):
|
||||||
"""
|
"""
|
||||||
Generate key schedule
|
Generate key schedule
|
||||||
@@ -100,7 +75,7 @@ def aes_encrypt(data, expanded_key):
|
|||||||
@returns {int[]} 16-Byte cipher
|
@returns {int[]} 16-Byte cipher
|
||||||
"""
|
"""
|
||||||
rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1
|
rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1
|
||||||
|
|
||||||
data = xor(data, expanded_key[:BLOCK_SIZE_BYTES])
|
data = xor(data, expanded_key[:BLOCK_SIZE_BYTES])
|
||||||
for i in range(1, rounds+1):
|
for i in range(1, rounds+1):
|
||||||
data = sub_bytes(data)
|
data = sub_bytes(data)
|
||||||
@@ -108,26 +83,6 @@ def aes_encrypt(data, expanded_key):
|
|||||||
if i != rounds:
|
if i != rounds:
|
||||||
data = mix_columns(data)
|
data = mix_columns(data)
|
||||||
data = xor(data, expanded_key[i*BLOCK_SIZE_BYTES : (i+1)*BLOCK_SIZE_BYTES])
|
data = xor(data, expanded_key[i*BLOCK_SIZE_BYTES : (i+1)*BLOCK_SIZE_BYTES])
|
||||||
|
|
||||||
return data
|
|
||||||
|
|
||||||
def aes_decrypt(data, expanded_key):
|
|
||||||
"""
|
|
||||||
Decrypt one block with aes
|
|
||||||
|
|
||||||
@param {int[]} data 16-Byte cipher
|
|
||||||
@param {int[]} expanded_key 176/208/240-Byte expanded key
|
|
||||||
@returns {int[]} 16-Byte state
|
|
||||||
"""
|
|
||||||
rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1
|
|
||||||
|
|
||||||
for i in range(rounds, 0, -1):
|
|
||||||
data = xor(data, expanded_key[i*BLOCK_SIZE_BYTES : (i+1)*BLOCK_SIZE_BYTES])
|
|
||||||
if i != rounds:
|
|
||||||
data = mix_columns_inv(data)
|
|
||||||
data = shift_rows_inv(data)
|
|
||||||
data = sub_bytes_inv(data)
|
|
||||||
data = xor(data, expanded_key[:BLOCK_SIZE_BYTES])
|
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
@@ -184,69 +139,14 @@ SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B,
|
|||||||
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
|
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
|
||||||
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
|
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
|
||||||
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)
|
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)
|
||||||
SBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
|
MIX_COLUMN_MATRIX = ((2,3,1,1),
|
||||||
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
|
(1,2,3,1),
|
||||||
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
|
(1,1,2,3),
|
||||||
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
|
(3,1,1,2))
|
||||||
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
|
|
||||||
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
|
|
||||||
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
|
|
||||||
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
|
|
||||||
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
|
|
||||||
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
|
|
||||||
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
|
|
||||||
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
|
|
||||||
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
|
|
||||||
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
|
|
||||||
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
|
|
||||||
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)
|
|
||||||
MIX_COLUMN_MATRIX = ((0x2,0x3,0x1,0x1),
|
|
||||||
(0x1,0x2,0x3,0x1),
|
|
||||||
(0x1,0x1,0x2,0x3),
|
|
||||||
(0x3,0x1,0x1,0x2))
|
|
||||||
MIX_COLUMN_MATRIX_INV = ((0xE,0xB,0xD,0x9),
|
|
||||||
(0x9,0xE,0xB,0xD),
|
|
||||||
(0xD,0x9,0xE,0xB),
|
|
||||||
(0xB,0xD,0x9,0xE))
|
|
||||||
RIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,
|
|
||||||
0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,
|
|
||||||
0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,
|
|
||||||
0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,
|
|
||||||
0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,
|
|
||||||
0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,
|
|
||||||
0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,
|
|
||||||
0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,
|
|
||||||
0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,
|
|
||||||
0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,
|
|
||||||
0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,
|
|
||||||
0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,
|
|
||||||
0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,
|
|
||||||
0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,
|
|
||||||
0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,
|
|
||||||
0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)
|
|
||||||
RIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,
|
|
||||||
0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,
|
|
||||||
0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,
|
|
||||||
0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,
|
|
||||||
0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,
|
|
||||||
0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,
|
|
||||||
0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,
|
|
||||||
0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,
|
|
||||||
0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,
|
|
||||||
0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,
|
|
||||||
0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,
|
|
||||||
0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,
|
|
||||||
0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,
|
|
||||||
0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,
|
|
||||||
0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,
|
|
||||||
0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)
|
|
||||||
|
|
||||||
def sub_bytes(data):
|
def sub_bytes(data):
|
||||||
return [SBOX[x] for x in data]
|
return [SBOX[x] for x in data]
|
||||||
|
|
||||||
def sub_bytes_inv(data):
|
|
||||||
return [SBOX_INV[x] for x in data]
|
|
||||||
|
|
||||||
def rotate(data):
|
def rotate(data):
|
||||||
return data[1:] + [data[0]]
|
return data[1:] + [data[0]]
|
||||||
|
|
||||||
@@ -260,31 +160,30 @@ def key_schedule_core(data, rcon_iteration):
|
|||||||
def xor(data1, data2):
|
def xor(data1, data2):
|
||||||
return [x^y for x, y in zip(data1, data2)]
|
return [x^y for x, y in zip(data1, data2)]
|
||||||
|
|
||||||
def rijndael_mul(a, b):
|
def mix_column(data):
|
||||||
if(a==0 or b==0):
|
|
||||||
return 0
|
|
||||||
return RIJNDAEL_EXP_TABLE[(RIJNDAEL_LOG_TABLE[a] + RIJNDAEL_LOG_TABLE[b]) % 0xFF]
|
|
||||||
|
|
||||||
def mix_column(data, matrix):
|
|
||||||
data_mixed = []
|
data_mixed = []
|
||||||
for row in range(4):
|
for row in range(4):
|
||||||
mixed = 0
|
mixed = 0
|
||||||
for column in range(4):
|
for column in range(4):
|
||||||
# xor is (+) and (-)
|
addend = data[column]
|
||||||
mixed ^= rijndael_mul(data[column], matrix[row][column])
|
if MIX_COLUMN_MATRIX[row][column] in (2,3):
|
||||||
|
addend <<= 1
|
||||||
|
if addend > 0xff:
|
||||||
|
addend &= 0xff
|
||||||
|
addend ^= 0x1b
|
||||||
|
if MIX_COLUMN_MATRIX[row][column] == 3:
|
||||||
|
addend ^= data[column]
|
||||||
|
mixed ^= addend & 0xff
|
||||||
data_mixed.append(mixed)
|
data_mixed.append(mixed)
|
||||||
return data_mixed
|
return data_mixed
|
||||||
|
|
||||||
def mix_columns(data, matrix=MIX_COLUMN_MATRIX):
|
def mix_columns(data):
|
||||||
data_mixed = []
|
data_mixed = []
|
||||||
for i in range(4):
|
for i in range(4):
|
||||||
column = data[i*4 : (i+1)*4]
|
column = data[i*4 : (i+1)*4]
|
||||||
data_mixed += mix_column(column, matrix)
|
data_mixed += mix_column(column)
|
||||||
return data_mixed
|
return data_mixed
|
||||||
|
|
||||||
def mix_columns_inv(data):
|
|
||||||
return mix_columns(data, MIX_COLUMN_MATRIX_INV)
|
|
||||||
|
|
||||||
def shift_rows(data):
|
def shift_rows(data):
|
||||||
data_shifted = []
|
data_shifted = []
|
||||||
for column in range(4):
|
for column in range(4):
|
||||||
@@ -292,13 +191,6 @@ def shift_rows(data):
|
|||||||
data_shifted.append( data[((column + row) & 0b11) * 4 + row] )
|
data_shifted.append( data[((column + row) & 0b11) * 4 + row] )
|
||||||
return data_shifted
|
return data_shifted
|
||||||
|
|
||||||
def shift_rows_inv(data):
|
|
||||||
data_shifted = []
|
|
||||||
for column in range(4):
|
|
||||||
for row in range(4):
|
|
||||||
data_shifted.append( data[((column - row) & 0b11) * 4 + row] )
|
|
||||||
return data_shifted
|
|
||||||
|
|
||||||
def inc(data):
|
def inc(data):
|
||||||
data = data[:] # copy
|
data = data[:] # copy
|
||||||
for i in range(len(data)-1,-1,-1):
|
for i in range(len(data)-1,-1,-1):
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
from .common import FileDownloader
|
|
||||||
from .hls import HlsFD
|
|
||||||
from .http import HttpFD
|
|
||||||
from .mplayer import MplayerFD
|
|
||||||
from .rtmp import RtmpFD
|
|
||||||
from .f4m import F4mFD
|
|
||||||
|
|
||||||
from ..utils import (
|
|
||||||
determine_ext,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def get_suitable_downloader(info_dict):
|
|
||||||
"""Get the downloader class that can handle the info dict."""
|
|
||||||
url = info_dict['url']
|
|
||||||
protocol = info_dict.get('protocol')
|
|
||||||
|
|
||||||
if url.startswith('rtmp'):
|
|
||||||
return RtmpFD
|
|
||||||
if (protocol == 'm3u8') or (protocol is None and determine_ext(url) == 'm3u8'):
|
|
||||||
return HlsFD
|
|
||||||
if url.startswith('mms') or url.startswith('rtsp'):
|
|
||||||
return MplayerFD
|
|
||||||
if determine_ext(url) == 'f4m':
|
|
||||||
return F4mFD
|
|
||||||
else:
|
|
||||||
return HttpFD
|
|
||||||
@@ -1,317 +0,0 @@
|
|||||||
import os
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
|
|
||||||
from ..utils import (
|
|
||||||
compat_str,
|
|
||||||
encodeFilename,
|
|
||||||
format_bytes,
|
|
||||||
timeconvert,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class FileDownloader(object):
|
|
||||||
"""File Downloader class.
|
|
||||||
|
|
||||||
File downloader objects are the ones responsible of downloading the
|
|
||||||
actual video file and writing it to disk.
|
|
||||||
|
|
||||||
File downloaders accept a lot of parameters. In order not to saturate
|
|
||||||
the object constructor with arguments, it receives a dictionary of
|
|
||||||
options instead.
|
|
||||||
|
|
||||||
Available options:
|
|
||||||
|
|
||||||
verbose: Print additional info to stdout.
|
|
||||||
quiet: Do not print messages to stdout.
|
|
||||||
ratelimit: Download speed limit, in bytes/sec.
|
|
||||||
retries: Number of times to retry for HTTP error 5xx
|
|
||||||
buffersize: Size of download buffer in bytes.
|
|
||||||
noresizebuffer: Do not automatically resize the download buffer.
|
|
||||||
continuedl: Try to continue downloads if possible.
|
|
||||||
noprogress: Do not print the progress bar.
|
|
||||||
logtostderr: Log messages to stderr instead of stdout.
|
|
||||||
consoletitle: Display progress in console window's titlebar.
|
|
||||||
nopart: Do not use temporary .part files.
|
|
||||||
updatetime: Use the Last-modified header to set output file timestamps.
|
|
||||||
test: Download only first bytes to test the downloader.
|
|
||||||
min_filesize: Skip files smaller than this size
|
|
||||||
max_filesize: Skip files larger than this size
|
|
||||||
|
|
||||||
Subclasses of this one must re-define the real_download method.
|
|
||||||
"""
|
|
||||||
|
|
||||||
params = None
|
|
||||||
|
|
||||||
def __init__(self, ydl, params):
|
|
||||||
"""Create a FileDownloader object with the given options."""
|
|
||||||
self.ydl = ydl
|
|
||||||
self._progress_hooks = []
|
|
||||||
self.params = params
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def format_seconds(seconds):
|
|
||||||
(mins, secs) = divmod(seconds, 60)
|
|
||||||
(hours, mins) = divmod(mins, 60)
|
|
||||||
if hours > 99:
|
|
||||||
return '--:--:--'
|
|
||||||
if hours == 0:
|
|
||||||
return '%02d:%02d' % (mins, secs)
|
|
||||||
else:
|
|
||||||
return '%02d:%02d:%02d' % (hours, mins, secs)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def calc_percent(byte_counter, data_len):
|
|
||||||
if data_len is None:
|
|
||||||
return None
|
|
||||||
return float(byte_counter) / float(data_len) * 100.0
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def format_percent(percent):
|
|
||||||
if percent is None:
|
|
||||||
return '---.-%'
|
|
||||||
return '%6s' % ('%3.1f%%' % percent)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def calc_eta(start, now, total, current):
|
|
||||||
if total is None:
|
|
||||||
return None
|
|
||||||
dif = now - start
|
|
||||||
if current == 0 or dif < 0.001: # One millisecond
|
|
||||||
return None
|
|
||||||
rate = float(current) / dif
|
|
||||||
return int((float(total) - float(current)) / rate)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def format_eta(eta):
|
|
||||||
if eta is None:
|
|
||||||
return '--:--'
|
|
||||||
return FileDownloader.format_seconds(eta)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def calc_speed(start, now, bytes):
|
|
||||||
dif = now - start
|
|
||||||
if bytes == 0 or dif < 0.001: # One millisecond
|
|
||||||
return None
|
|
||||||
return float(bytes) / dif
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def format_speed(speed):
|
|
||||||
if speed is None:
|
|
||||||
return '%10s' % '---b/s'
|
|
||||||
return '%10s' % ('%s/s' % format_bytes(speed))
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def best_block_size(elapsed_time, bytes):
|
|
||||||
new_min = max(bytes / 2.0, 1.0)
|
|
||||||
new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
|
|
||||||
if elapsed_time < 0.001:
|
|
||||||
return int(new_max)
|
|
||||||
rate = bytes / elapsed_time
|
|
||||||
if rate > new_max:
|
|
||||||
return int(new_max)
|
|
||||||
if rate < new_min:
|
|
||||||
return int(new_min)
|
|
||||||
return int(rate)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def parse_bytes(bytestr):
|
|
||||||
"""Parse a string indicating a byte quantity into an integer."""
|
|
||||||
matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
|
|
||||||
if matchobj is None:
|
|
||||||
return None
|
|
||||||
number = float(matchobj.group(1))
|
|
||||||
multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
|
|
||||||
return int(round(number * multiplier))
|
|
||||||
|
|
||||||
def to_screen(self, *args, **kargs):
|
|
||||||
self.ydl.to_screen(*args, **kargs)
|
|
||||||
|
|
||||||
def to_stderr(self, message):
|
|
||||||
self.ydl.to_screen(message)
|
|
||||||
|
|
||||||
def to_console_title(self, message):
|
|
||||||
self.ydl.to_console_title(message)
|
|
||||||
|
|
||||||
def trouble(self, *args, **kargs):
|
|
||||||
self.ydl.trouble(*args, **kargs)
|
|
||||||
|
|
||||||
def report_warning(self, *args, **kargs):
|
|
||||||
self.ydl.report_warning(*args, **kargs)
|
|
||||||
|
|
||||||
def report_error(self, *args, **kargs):
|
|
||||||
self.ydl.report_error(*args, **kargs)
|
|
||||||
|
|
||||||
def slow_down(self, start_time, byte_counter):
|
|
||||||
"""Sleep if the download speed is over the rate limit."""
|
|
||||||
rate_limit = self.params.get('ratelimit', None)
|
|
||||||
if rate_limit is None or byte_counter == 0:
|
|
||||||
return
|
|
||||||
now = time.time()
|
|
||||||
elapsed = now - start_time
|
|
||||||
if elapsed <= 0.0:
|
|
||||||
return
|
|
||||||
speed = float(byte_counter) / elapsed
|
|
||||||
if speed > rate_limit:
|
|
||||||
time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
|
|
||||||
|
|
||||||
def temp_name(self, filename):
|
|
||||||
"""Returns a temporary filename for the given filename."""
|
|
||||||
if self.params.get('nopart', False) or filename == u'-' or \
|
|
||||||
(os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
|
|
||||||
return filename
|
|
||||||
return filename + u'.part'
|
|
||||||
|
|
||||||
def undo_temp_name(self, filename):
|
|
||||||
if filename.endswith(u'.part'):
|
|
||||||
return filename[:-len(u'.part')]
|
|
||||||
return filename
|
|
||||||
|
|
||||||
def try_rename(self, old_filename, new_filename):
|
|
||||||
try:
|
|
||||||
if old_filename == new_filename:
|
|
||||||
return
|
|
||||||
os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
|
|
||||||
except (IOError, OSError) as err:
|
|
||||||
self.report_error(u'unable to rename file: %s' % compat_str(err))
|
|
||||||
|
|
||||||
def try_utime(self, filename, last_modified_hdr):
|
|
||||||
"""Try to set the last-modified time of the given file."""
|
|
||||||
if last_modified_hdr is None:
|
|
||||||
return
|
|
||||||
if not os.path.isfile(encodeFilename(filename)):
|
|
||||||
return
|
|
||||||
timestr = last_modified_hdr
|
|
||||||
if timestr is None:
|
|
||||||
return
|
|
||||||
filetime = timeconvert(timestr)
|
|
||||||
if filetime is None:
|
|
||||||
return filetime
|
|
||||||
# Ignore obviously invalid dates
|
|
||||||
if filetime == 0:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
os.utime(filename, (time.time(), filetime))
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
return filetime
|
|
||||||
|
|
||||||
def report_destination(self, filename):
|
|
||||||
"""Report destination filename."""
|
|
||||||
self.to_screen(u'[download] Destination: ' + filename)
|
|
||||||
|
|
||||||
def _report_progress_status(self, msg, is_last_line=False):
|
|
||||||
fullmsg = u'[download] ' + msg
|
|
||||||
if self.params.get('progress_with_newline', False):
|
|
||||||
self.to_screen(fullmsg)
|
|
||||||
else:
|
|
||||||
if os.name == 'nt':
|
|
||||||
prev_len = getattr(self, '_report_progress_prev_line_length',
|
|
||||||
0)
|
|
||||||
if prev_len > len(fullmsg):
|
|
||||||
fullmsg += u' ' * (prev_len - len(fullmsg))
|
|
||||||
self._report_progress_prev_line_length = len(fullmsg)
|
|
||||||
clear_line = u'\r'
|
|
||||||
else:
|
|
||||||
clear_line = (u'\r\x1b[K' if sys.stderr.isatty() else u'\r')
|
|
||||||
self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line)
|
|
||||||
self.to_console_title(u'youtube-dl ' + msg)
|
|
||||||
|
|
||||||
def report_progress(self, percent, data_len_str, speed, eta):
|
|
||||||
"""Report download progress."""
|
|
||||||
if self.params.get('noprogress', False):
|
|
||||||
return
|
|
||||||
if eta is not None:
|
|
||||||
eta_str = self.format_eta(eta)
|
|
||||||
else:
|
|
||||||
eta_str = 'Unknown ETA'
|
|
||||||
if percent is not None:
|
|
||||||
percent_str = self.format_percent(percent)
|
|
||||||
else:
|
|
||||||
percent_str = 'Unknown %'
|
|
||||||
speed_str = self.format_speed(speed)
|
|
||||||
|
|
||||||
msg = (u'%s of %s at %s ETA %s' %
|
|
||||||
(percent_str, data_len_str, speed_str, eta_str))
|
|
||||||
self._report_progress_status(msg)
|
|
||||||
|
|
||||||
def report_progress_live_stream(self, downloaded_data_len, speed, elapsed):
|
|
||||||
if self.params.get('noprogress', False):
|
|
||||||
return
|
|
||||||
downloaded_str = format_bytes(downloaded_data_len)
|
|
||||||
speed_str = self.format_speed(speed)
|
|
||||||
elapsed_str = FileDownloader.format_seconds(elapsed)
|
|
||||||
msg = u'%s at %s (%s)' % (downloaded_str, speed_str, elapsed_str)
|
|
||||||
self._report_progress_status(msg)
|
|
||||||
|
|
||||||
def report_finish(self, data_len_str, tot_time):
|
|
||||||
"""Report download finished."""
|
|
||||||
if self.params.get('noprogress', False):
|
|
||||||
self.to_screen(u'[download] Download completed')
|
|
||||||
else:
|
|
||||||
self._report_progress_status(
|
|
||||||
(u'100%% of %s in %s' %
|
|
||||||
(data_len_str, self.format_seconds(tot_time))),
|
|
||||||
is_last_line=True)
|
|
||||||
|
|
||||||
def report_resuming_byte(self, resume_len):
|
|
||||||
"""Report attempt to resume at given byte."""
|
|
||||||
self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
|
|
||||||
|
|
||||||
def report_retry(self, count, retries):
|
|
||||||
"""Report retry in case of HTTP error 5xx"""
|
|
||||||
self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
|
|
||||||
|
|
||||||
def report_file_already_downloaded(self, file_name):
|
|
||||||
"""Report file has already been fully downloaded."""
|
|
||||||
try:
|
|
||||||
self.to_screen(u'[download] %s has already been downloaded' % file_name)
|
|
||||||
except UnicodeEncodeError:
|
|
||||||
self.to_screen(u'[download] The file has already been downloaded')
|
|
||||||
|
|
||||||
def report_unable_to_resume(self):
|
|
||||||
"""Report it was impossible to resume download."""
|
|
||||||
self.to_screen(u'[download] Unable to resume')
|
|
||||||
|
|
||||||
def download(self, filename, info_dict):
|
|
||||||
"""Download to a filename using the info from info_dict
|
|
||||||
Return True on success and False otherwise
|
|
||||||
"""
|
|
||||||
# Check file already present
|
|
||||||
if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
|
|
||||||
self.report_file_already_downloaded(filename)
|
|
||||||
self._hook_progress({
|
|
||||||
'filename': filename,
|
|
||||||
'status': 'finished',
|
|
||||||
'total_bytes': os.path.getsize(encodeFilename(filename)),
|
|
||||||
})
|
|
||||||
return True
|
|
||||||
|
|
||||||
return self.real_download(filename, info_dict)
|
|
||||||
|
|
||||||
def real_download(self, filename, info_dict):
|
|
||||||
"""Real download process. Redefine in subclasses."""
|
|
||||||
raise NotImplementedError(u'This method must be implemented by sublcasses')
|
|
||||||
|
|
||||||
def _hook_progress(self, status):
|
|
||||||
for ph in self._progress_hooks:
|
|
||||||
ph(status)
|
|
||||||
|
|
||||||
def add_progress_hook(self, ph):
|
|
||||||
""" ph gets called on download progress, with a dictionary with the entries
|
|
||||||
* filename: The final filename
|
|
||||||
* status: One of "downloading" and "finished"
|
|
||||||
|
|
||||||
It can also have some of the following entries:
|
|
||||||
|
|
||||||
* downloaded_bytes: Bytes on disks
|
|
||||||
* total_bytes: Total bytes, None if unknown
|
|
||||||
* tmpfilename: The filename we're currently writing to
|
|
||||||
* eta: The estimated time in seconds, None if unknown
|
|
||||||
* speed: The download speed in bytes/second, None if unknown
|
|
||||||
|
|
||||||
Hooks are guaranteed to be called at least once (with status "finished")
|
|
||||||
if the download is successful.
|
|
||||||
"""
|
|
||||||
self._progress_hooks.append(ph)
|
|
||||||
@@ -1,315 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import base64
|
|
||||||
import io
|
|
||||||
import itertools
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import xml.etree.ElementTree as etree
|
|
||||||
|
|
||||||
from .common import FileDownloader
|
|
||||||
from .http import HttpFD
|
|
||||||
from ..utils import (
|
|
||||||
struct_pack,
|
|
||||||
struct_unpack,
|
|
||||||
compat_urlparse,
|
|
||||||
format_bytes,
|
|
||||||
encodeFilename,
|
|
||||||
sanitize_open,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class FlvReader(io.BytesIO):
|
|
||||||
"""
|
|
||||||
Reader for Flv files
|
|
||||||
The file format is documented in https://www.adobe.com/devnet/f4v.html
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Utility functions for reading numbers and strings
|
|
||||||
def read_unsigned_long_long(self):
|
|
||||||
return struct_unpack('!Q', self.read(8))[0]
|
|
||||||
|
|
||||||
def read_unsigned_int(self):
|
|
||||||
return struct_unpack('!I', self.read(4))[0]
|
|
||||||
|
|
||||||
def read_unsigned_char(self):
|
|
||||||
return struct_unpack('!B', self.read(1))[0]
|
|
||||||
|
|
||||||
def read_string(self):
|
|
||||||
res = b''
|
|
||||||
while True:
|
|
||||||
char = self.read(1)
|
|
||||||
if char == b'\x00':
|
|
||||||
break
|
|
||||||
res += char
|
|
||||||
return res
|
|
||||||
|
|
||||||
def read_box_info(self):
|
|
||||||
"""
|
|
||||||
Read a box and return the info as a tuple: (box_size, box_type, box_data)
|
|
||||||
"""
|
|
||||||
real_size = size = self.read_unsigned_int()
|
|
||||||
box_type = self.read(4)
|
|
||||||
header_end = 8
|
|
||||||
if size == 1:
|
|
||||||
real_size = self.read_unsigned_long_long()
|
|
||||||
header_end = 16
|
|
||||||
return real_size, box_type, self.read(real_size-header_end)
|
|
||||||
|
|
||||||
def read_asrt(self):
|
|
||||||
# version
|
|
||||||
self.read_unsigned_char()
|
|
||||||
# flags
|
|
||||||
self.read(3)
|
|
||||||
quality_entry_count = self.read_unsigned_char()
|
|
||||||
# QualityEntryCount
|
|
||||||
for i in range(quality_entry_count):
|
|
||||||
self.read_string()
|
|
||||||
|
|
||||||
segment_run_count = self.read_unsigned_int()
|
|
||||||
segments = []
|
|
||||||
for i in range(segment_run_count):
|
|
||||||
first_segment = self.read_unsigned_int()
|
|
||||||
fragments_per_segment = self.read_unsigned_int()
|
|
||||||
segments.append((first_segment, fragments_per_segment))
|
|
||||||
|
|
||||||
return {
|
|
||||||
'segment_run': segments,
|
|
||||||
}
|
|
||||||
|
|
||||||
def read_afrt(self):
|
|
||||||
# version
|
|
||||||
self.read_unsigned_char()
|
|
||||||
# flags
|
|
||||||
self.read(3)
|
|
||||||
# time scale
|
|
||||||
self.read_unsigned_int()
|
|
||||||
|
|
||||||
quality_entry_count = self.read_unsigned_char()
|
|
||||||
# QualitySegmentUrlModifiers
|
|
||||||
for i in range(quality_entry_count):
|
|
||||||
self.read_string()
|
|
||||||
|
|
||||||
fragments_count = self.read_unsigned_int()
|
|
||||||
fragments = []
|
|
||||||
for i in range(fragments_count):
|
|
||||||
first = self.read_unsigned_int()
|
|
||||||
first_ts = self.read_unsigned_long_long()
|
|
||||||
duration = self.read_unsigned_int()
|
|
||||||
if duration == 0:
|
|
||||||
discontinuity_indicator = self.read_unsigned_char()
|
|
||||||
else:
|
|
||||||
discontinuity_indicator = None
|
|
||||||
fragments.append({
|
|
||||||
'first': first,
|
|
||||||
'ts': first_ts,
|
|
||||||
'duration': duration,
|
|
||||||
'discontinuity_indicator': discontinuity_indicator,
|
|
||||||
})
|
|
||||||
|
|
||||||
return {
|
|
||||||
'fragments': fragments,
|
|
||||||
}
|
|
||||||
|
|
||||||
def read_abst(self):
|
|
||||||
# version
|
|
||||||
self.read_unsigned_char()
|
|
||||||
# flags
|
|
||||||
self.read(3)
|
|
||||||
|
|
||||||
self.read_unsigned_int() # BootstrapinfoVersion
|
|
||||||
# Profile,Live,Update,Reserved
|
|
||||||
self.read(1)
|
|
||||||
# time scale
|
|
||||||
self.read_unsigned_int()
|
|
||||||
# CurrentMediaTime
|
|
||||||
self.read_unsigned_long_long()
|
|
||||||
# SmpteTimeCodeOffset
|
|
||||||
self.read_unsigned_long_long()
|
|
||||||
|
|
||||||
self.read_string() # MovieIdentifier
|
|
||||||
server_count = self.read_unsigned_char()
|
|
||||||
# ServerEntryTable
|
|
||||||
for i in range(server_count):
|
|
||||||
self.read_string()
|
|
||||||
quality_count = self.read_unsigned_char()
|
|
||||||
# QualityEntryTable
|
|
||||||
for i in range(quality_count):
|
|
||||||
self.read_string()
|
|
||||||
# DrmData
|
|
||||||
self.read_string()
|
|
||||||
# MetaData
|
|
||||||
self.read_string()
|
|
||||||
|
|
||||||
segments_count = self.read_unsigned_char()
|
|
||||||
segments = []
|
|
||||||
for i in range(segments_count):
|
|
||||||
box_size, box_type, box_data = self.read_box_info()
|
|
||||||
assert box_type == b'asrt'
|
|
||||||
segment = FlvReader(box_data).read_asrt()
|
|
||||||
segments.append(segment)
|
|
||||||
fragments_run_count = self.read_unsigned_char()
|
|
||||||
fragments = []
|
|
||||||
for i in range(fragments_run_count):
|
|
||||||
box_size, box_type, box_data = self.read_box_info()
|
|
||||||
assert box_type == b'afrt'
|
|
||||||
fragments.append(FlvReader(box_data).read_afrt())
|
|
||||||
|
|
||||||
return {
|
|
||||||
'segments': segments,
|
|
||||||
'fragments': fragments,
|
|
||||||
}
|
|
||||||
|
|
||||||
def read_bootstrap_info(self):
|
|
||||||
total_size, box_type, box_data = self.read_box_info()
|
|
||||||
assert box_type == b'abst'
|
|
||||||
return FlvReader(box_data).read_abst()
|
|
||||||
|
|
||||||
|
|
||||||
def read_bootstrap_info(bootstrap_bytes):
|
|
||||||
return FlvReader(bootstrap_bytes).read_bootstrap_info()
|
|
||||||
|
|
||||||
|
|
||||||
def build_fragments_list(boot_info):
|
|
||||||
""" Return a list of (segment, fragment) for each fragment in the video """
|
|
||||||
res = []
|
|
||||||
segment_run_table = boot_info['segments'][0]
|
|
||||||
# I've only found videos with one segment
|
|
||||||
segment_run_entry = segment_run_table['segment_run'][0]
|
|
||||||
n_frags = segment_run_entry[1]
|
|
||||||
fragment_run_entry_table = boot_info['fragments'][0]['fragments']
|
|
||||||
first_frag_number = fragment_run_entry_table[0]['first']
|
|
||||||
for (i, frag_number) in zip(range(1, n_frags+1), itertools.count(first_frag_number)):
|
|
||||||
res.append((1, frag_number))
|
|
||||||
return res
|
|
||||||
|
|
||||||
|
|
||||||
def write_flv_header(stream, metadata):
|
|
||||||
"""Writes the FLV header and the metadata to stream"""
|
|
||||||
# FLV header
|
|
||||||
stream.write(b'FLV\x01')
|
|
||||||
stream.write(b'\x05')
|
|
||||||
stream.write(b'\x00\x00\x00\x09')
|
|
||||||
# FLV File body
|
|
||||||
stream.write(b'\x00\x00\x00\x00')
|
|
||||||
# FLVTAG
|
|
||||||
# Script data
|
|
||||||
stream.write(b'\x12')
|
|
||||||
# Size of the metadata with 3 bytes
|
|
||||||
stream.write(struct_pack('!L', len(metadata))[1:])
|
|
||||||
stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
|
|
||||||
stream.write(metadata)
|
|
||||||
# Magic numbers extracted from the output files produced by AdobeHDS.php
|
|
||||||
#(https://github.com/K-S-V/Scripts)
|
|
||||||
stream.write(b'\x00\x00\x01\x73')
|
|
||||||
|
|
||||||
|
|
||||||
def _add_ns(prop):
|
|
||||||
return '{http://ns.adobe.com/f4m/1.0}%s' % prop
|
|
||||||
|
|
||||||
|
|
||||||
class HttpQuietDownloader(HttpFD):
|
|
||||||
def to_screen(self, *args, **kargs):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class F4mFD(FileDownloader):
|
|
||||||
"""
|
|
||||||
A downloader for f4m manifests or AdobeHDS.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def real_download(self, filename, info_dict):
|
|
||||||
man_url = info_dict['url']
|
|
||||||
self.to_screen('[download] Downloading f4m manifest')
|
|
||||||
manifest = self.ydl.urlopen(man_url).read()
|
|
||||||
self.report_destination(filename)
|
|
||||||
http_dl = HttpQuietDownloader(self.ydl,
|
|
||||||
{
|
|
||||||
'continuedl': True,
|
|
||||||
'quiet': True,
|
|
||||||
'noprogress': True,
|
|
||||||
'test': self.params.get('test', False),
|
|
||||||
})
|
|
||||||
|
|
||||||
doc = etree.fromstring(manifest)
|
|
||||||
formats = [(int(f.attrib.get('bitrate', -1)), f) for f in doc.findall(_add_ns('media'))]
|
|
||||||
formats = sorted(formats, key=lambda f: f[0])
|
|
||||||
rate, media = formats[-1]
|
|
||||||
base_url = compat_urlparse.urljoin(man_url, media.attrib['url'])
|
|
||||||
bootstrap = base64.b64decode(doc.find(_add_ns('bootstrapInfo')).text)
|
|
||||||
metadata = base64.b64decode(media.find(_add_ns('metadata')).text)
|
|
||||||
boot_info = read_bootstrap_info(bootstrap)
|
|
||||||
fragments_list = build_fragments_list(boot_info)
|
|
||||||
if self.params.get('test', False):
|
|
||||||
# We only download the first fragment
|
|
||||||
fragments_list = fragments_list[:1]
|
|
||||||
total_frags = len(fragments_list)
|
|
||||||
|
|
||||||
tmpfilename = self.temp_name(filename)
|
|
||||||
(dest_stream, tmpfilename) = sanitize_open(tmpfilename, 'wb')
|
|
||||||
write_flv_header(dest_stream, metadata)
|
|
||||||
|
|
||||||
# This dict stores the download progress, it's updated by the progress
|
|
||||||
# hook
|
|
||||||
state = {
|
|
||||||
'downloaded_bytes': 0,
|
|
||||||
'frag_counter': 0,
|
|
||||||
}
|
|
||||||
start = time.time()
|
|
||||||
|
|
||||||
def frag_progress_hook(status):
|
|
||||||
frag_total_bytes = status.get('total_bytes', 0)
|
|
||||||
estimated_size = (state['downloaded_bytes'] +
|
|
||||||
(total_frags - state['frag_counter']) * frag_total_bytes)
|
|
||||||
if status['status'] == 'finished':
|
|
||||||
state['downloaded_bytes'] += frag_total_bytes
|
|
||||||
state['frag_counter'] += 1
|
|
||||||
progress = self.calc_percent(state['frag_counter'], total_frags)
|
|
||||||
byte_counter = state['downloaded_bytes']
|
|
||||||
else:
|
|
||||||
frag_downloaded_bytes = status['downloaded_bytes']
|
|
||||||
byte_counter = state['downloaded_bytes'] + frag_downloaded_bytes
|
|
||||||
frag_progress = self.calc_percent(frag_downloaded_bytes,
|
|
||||||
frag_total_bytes)
|
|
||||||
progress = self.calc_percent(state['frag_counter'], total_frags)
|
|
||||||
progress += frag_progress / float(total_frags)
|
|
||||||
|
|
||||||
eta = self.calc_eta(start, time.time(), estimated_size, byte_counter)
|
|
||||||
self.report_progress(progress, format_bytes(estimated_size),
|
|
||||||
status.get('speed'), eta)
|
|
||||||
http_dl.add_progress_hook(frag_progress_hook)
|
|
||||||
|
|
||||||
frags_filenames = []
|
|
||||||
for (seg_i, frag_i) in fragments_list:
|
|
||||||
name = 'Seg%d-Frag%d' % (seg_i, frag_i)
|
|
||||||
url = base_url + name
|
|
||||||
frag_filename = '%s-%s' % (tmpfilename, name)
|
|
||||||
success = http_dl.download(frag_filename, {'url': url})
|
|
||||||
if not success:
|
|
||||||
return False
|
|
||||||
with open(frag_filename, 'rb') as down:
|
|
||||||
down_data = down.read()
|
|
||||||
reader = FlvReader(down_data)
|
|
||||||
while True:
|
|
||||||
_, box_type, box_data = reader.read_box_info()
|
|
||||||
if box_type == b'mdat':
|
|
||||||
dest_stream.write(box_data)
|
|
||||||
break
|
|
||||||
frags_filenames.append(frag_filename)
|
|
||||||
|
|
||||||
dest_stream.close()
|
|
||||||
self.report_finish(format_bytes(state['downloaded_bytes']), time.time() - start)
|
|
||||||
|
|
||||||
self.try_rename(tmpfilename, filename)
|
|
||||||
for frag_file in frags_filenames:
|
|
||||||
os.remove(frag_file)
|
|
||||||
|
|
||||||
fsize = os.path.getsize(encodeFilename(filename))
|
|
||||||
self._hook_progress({
|
|
||||||
'downloaded_bytes': fsize,
|
|
||||||
'total_bytes': fsize,
|
|
||||||
'filename': filename,
|
|
||||||
'status': 'finished',
|
|
||||||
})
|
|
||||||
|
|
||||||
return True
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import os
|
|
||||||
import subprocess
|
|
||||||
|
|
||||||
from .common import FileDownloader
|
|
||||||
from ..utils import (
|
|
||||||
encodeFilename,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class HlsFD(FileDownloader):
|
|
||||||
def real_download(self, filename, info_dict):
|
|
||||||
url = info_dict['url']
|
|
||||||
self.report_destination(filename)
|
|
||||||
tmpfilename = self.temp_name(filename)
|
|
||||||
|
|
||||||
args = [
|
|
||||||
'-y', '-i', url, '-f', 'mp4', '-c', 'copy',
|
|
||||||
'-bsf:a', 'aac_adtstoasc',
|
|
||||||
encodeFilename(tmpfilename, for_subprocess=True)]
|
|
||||||
|
|
||||||
for program in ['avconv', 'ffmpeg']:
|
|
||||||
try:
|
|
||||||
subprocess.call([program, '-version'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
|
|
||||||
break
|
|
||||||
except (OSError, IOError):
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
self.report_error(u'm3u8 download detected but ffmpeg or avconv could not be found')
|
|
||||||
cmd = [program] + args
|
|
||||||
|
|
||||||
retval = subprocess.call(cmd)
|
|
||||||
if retval == 0:
|
|
||||||
fsize = os.path.getsize(encodeFilename(tmpfilename))
|
|
||||||
self.to_screen(u'\r[%s] %s bytes' % (cmd[0], fsize))
|
|
||||||
self.try_rename(tmpfilename, filename)
|
|
||||||
self._hook_progress({
|
|
||||||
'downloaded_bytes': fsize,
|
|
||||||
'total_bytes': fsize,
|
|
||||||
'filename': filename,
|
|
||||||
'status': 'finished',
|
|
||||||
})
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
self.to_stderr(u"\n")
|
|
||||||
self.report_error(u'ffmpeg exited with code %d' % retval)
|
|
||||||
return False
|
|
||||||
@@ -1,205 +0,0 @@
|
|||||||
import os
|
|
||||||
import time
|
|
||||||
|
|
||||||
from .common import FileDownloader
|
|
||||||
from ..utils import (
|
|
||||||
compat_urllib_request,
|
|
||||||
compat_urllib_error,
|
|
||||||
ContentTooShortError,
|
|
||||||
|
|
||||||
encodeFilename,
|
|
||||||
sanitize_open,
|
|
||||||
format_bytes,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class HttpFD(FileDownloader):
|
|
||||||
_TEST_FILE_SIZE = 10241
|
|
||||||
|
|
||||||
def real_download(self, filename, info_dict):
|
|
||||||
url = info_dict['url']
|
|
||||||
tmpfilename = self.temp_name(filename)
|
|
||||||
stream = None
|
|
||||||
|
|
||||||
# Do not include the Accept-Encoding header
|
|
||||||
headers = {'Youtubedl-no-compression': 'True'}
|
|
||||||
if 'user_agent' in info_dict:
|
|
||||||
headers['Youtubedl-user-agent'] = info_dict['user_agent']
|
|
||||||
if 'http_referer' in info_dict:
|
|
||||||
headers['Referer'] = info_dict['http_referer']
|
|
||||||
basic_request = compat_urllib_request.Request(url, None, headers)
|
|
||||||
request = compat_urllib_request.Request(url, None, headers)
|
|
||||||
|
|
||||||
is_test = self.params.get('test', False)
|
|
||||||
|
|
||||||
if is_test:
|
|
||||||
request.add_header('Range', 'bytes=0-%s' % str(self._TEST_FILE_SIZE - 1))
|
|
||||||
|
|
||||||
# Establish possible resume length
|
|
||||||
if os.path.isfile(encodeFilename(tmpfilename)):
|
|
||||||
resume_len = os.path.getsize(encodeFilename(tmpfilename))
|
|
||||||
else:
|
|
||||||
resume_len = 0
|
|
||||||
|
|
||||||
open_mode = 'wb'
|
|
||||||
if resume_len != 0:
|
|
||||||
if self.params.get('continuedl', False):
|
|
||||||
self.report_resuming_byte(resume_len)
|
|
||||||
request.add_header('Range', 'bytes=%d-' % resume_len)
|
|
||||||
open_mode = 'ab'
|
|
||||||
else:
|
|
||||||
resume_len = 0
|
|
||||||
|
|
||||||
count = 0
|
|
||||||
retries = self.params.get('retries', 0)
|
|
||||||
while count <= retries:
|
|
||||||
# Establish connection
|
|
||||||
try:
|
|
||||||
data = self.ydl.urlopen(request)
|
|
||||||
break
|
|
||||||
except (compat_urllib_error.HTTPError, ) as err:
|
|
||||||
if (err.code < 500 or err.code >= 600) and err.code != 416:
|
|
||||||
# Unexpected HTTP error
|
|
||||||
raise
|
|
||||||
elif err.code == 416:
|
|
||||||
# Unable to resume (requested range not satisfiable)
|
|
||||||
try:
|
|
||||||
# Open the connection again without the range header
|
|
||||||
data = self.ydl.urlopen(basic_request)
|
|
||||||
content_length = data.info()['Content-Length']
|
|
||||||
except (compat_urllib_error.HTTPError, ) as err:
|
|
||||||
if err.code < 500 or err.code >= 600:
|
|
||||||
raise
|
|
||||||
else:
|
|
||||||
# Examine the reported length
|
|
||||||
if (content_length is not None and
|
|
||||||
(resume_len - 100 < int(content_length) < resume_len + 100)):
|
|
||||||
# The file had already been fully downloaded.
|
|
||||||
# Explanation to the above condition: in issue #175 it was revealed that
|
|
||||||
# YouTube sometimes adds or removes a few bytes from the end of the file,
|
|
||||||
# changing the file size slightly and causing problems for some users. So
|
|
||||||
# I decided to implement a suggested change and consider the file
|
|
||||||
# completely downloaded if the file size differs less than 100 bytes from
|
|
||||||
# the one in the hard drive.
|
|
||||||
self.report_file_already_downloaded(filename)
|
|
||||||
self.try_rename(tmpfilename, filename)
|
|
||||||
self._hook_progress({
|
|
||||||
'filename': filename,
|
|
||||||
'status': 'finished',
|
|
||||||
})
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
# The length does not match, we start the download over
|
|
||||||
self.report_unable_to_resume()
|
|
||||||
resume_len = 0
|
|
||||||
open_mode = 'wb'
|
|
||||||
break
|
|
||||||
# Retry
|
|
||||||
count += 1
|
|
||||||
if count <= retries:
|
|
||||||
self.report_retry(count, retries)
|
|
||||||
|
|
||||||
if count > retries:
|
|
||||||
self.report_error(u'giving up after %s retries' % retries)
|
|
||||||
return False
|
|
||||||
|
|
||||||
data_len = data.info().get('Content-length', None)
|
|
||||||
|
|
||||||
# Range HTTP header may be ignored/unsupported by a webserver
|
|
||||||
# (e.g. extractor/scivee.py, extractor/bambuser.py).
|
|
||||||
# However, for a test we still would like to download just a piece of a file.
|
|
||||||
# To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
|
|
||||||
# block size when downloading a file.
|
|
||||||
if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):
|
|
||||||
data_len = self._TEST_FILE_SIZE
|
|
||||||
|
|
||||||
if data_len is not None:
|
|
||||||
data_len = int(data_len) + resume_len
|
|
||||||
min_data_len = self.params.get("min_filesize", None)
|
|
||||||
max_data_len = self.params.get("max_filesize", None)
|
|
||||||
if min_data_len is not None and data_len < min_data_len:
|
|
||||||
self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
|
|
||||||
return False
|
|
||||||
if max_data_len is not None and data_len > max_data_len:
|
|
||||||
self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
|
|
||||||
return False
|
|
||||||
|
|
||||||
data_len_str = format_bytes(data_len)
|
|
||||||
byte_counter = 0 + resume_len
|
|
||||||
block_size = self.params.get('buffersize', 1024)
|
|
||||||
start = time.time()
|
|
||||||
while True:
|
|
||||||
# Download and write
|
|
||||||
before = time.time()
|
|
||||||
data_block = data.read(block_size if not is_test else min(block_size, data_len - byte_counter))
|
|
||||||
after = time.time()
|
|
||||||
if len(data_block) == 0:
|
|
||||||
break
|
|
||||||
byte_counter += len(data_block)
|
|
||||||
|
|
||||||
# Open file just in time
|
|
||||||
if stream is None:
|
|
||||||
try:
|
|
||||||
(stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
|
|
||||||
assert stream is not None
|
|
||||||
filename = self.undo_temp_name(tmpfilename)
|
|
||||||
self.report_destination(filename)
|
|
||||||
except (OSError, IOError) as err:
|
|
||||||
self.report_error(u'unable to open for writing: %s' % str(err))
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
stream.write(data_block)
|
|
||||||
except (IOError, OSError) as err:
|
|
||||||
self.to_stderr(u"\n")
|
|
||||||
self.report_error(u'unable to write data: %s' % str(err))
|
|
||||||
return False
|
|
||||||
if not self.params.get('noresizebuffer', False):
|
|
||||||
block_size = self.best_block_size(after - before, len(data_block))
|
|
||||||
|
|
||||||
# Progress message
|
|
||||||
speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
|
|
||||||
if data_len is None:
|
|
||||||
eta = percent = None
|
|
||||||
else:
|
|
||||||
percent = self.calc_percent(byte_counter, data_len)
|
|
||||||
eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
|
|
||||||
self.report_progress(percent, data_len_str, speed, eta)
|
|
||||||
|
|
||||||
self._hook_progress({
|
|
||||||
'downloaded_bytes': byte_counter,
|
|
||||||
'total_bytes': data_len,
|
|
||||||
'tmpfilename': tmpfilename,
|
|
||||||
'filename': filename,
|
|
||||||
'status': 'downloading',
|
|
||||||
'eta': eta,
|
|
||||||
'speed': speed,
|
|
||||||
})
|
|
||||||
|
|
||||||
if is_test and byte_counter == data_len:
|
|
||||||
break
|
|
||||||
|
|
||||||
# Apply rate limit
|
|
||||||
self.slow_down(start, byte_counter - resume_len)
|
|
||||||
|
|
||||||
if stream is None:
|
|
||||||
self.to_stderr(u"\n")
|
|
||||||
self.report_error(u'Did not get any data blocks')
|
|
||||||
return False
|
|
||||||
stream.close()
|
|
||||||
self.report_finish(data_len_str, (time.time() - start))
|
|
||||||
if data_len is not None and byte_counter != data_len:
|
|
||||||
raise ContentTooShortError(byte_counter, int(data_len))
|
|
||||||
self.try_rename(tmpfilename, filename)
|
|
||||||
|
|
||||||
# Update file modification time
|
|
||||||
if self.params.get('updatetime', True):
|
|
||||||
info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
|
|
||||||
|
|
||||||
self._hook_progress({
|
|
||||||
'downloaded_bytes': byte_counter,
|
|
||||||
'total_bytes': byte_counter,
|
|
||||||
'filename': filename,
|
|
||||||
'status': 'finished',
|
|
||||||
})
|
|
||||||
|
|
||||||
return True
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
import os
|
|
||||||
import subprocess
|
|
||||||
|
|
||||||
from .common import FileDownloader
|
|
||||||
from ..utils import (
|
|
||||||
encodeFilename,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class MplayerFD(FileDownloader):
|
|
||||||
def real_download(self, filename, info_dict):
|
|
||||||
url = info_dict['url']
|
|
||||||
self.report_destination(filename)
|
|
||||||
tmpfilename = self.temp_name(filename)
|
|
||||||
|
|
||||||
args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
|
|
||||||
# Check for mplayer first
|
|
||||||
try:
|
|
||||||
subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
|
|
||||||
except (OSError, IOError):
|
|
||||||
self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0])
|
|
||||||
return False
|
|
||||||
|
|
||||||
# Download using mplayer.
|
|
||||||
retval = subprocess.call(args)
|
|
||||||
if retval == 0:
|
|
||||||
fsize = os.path.getsize(encodeFilename(tmpfilename))
|
|
||||||
self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
|
|
||||||
self.try_rename(tmpfilename, filename)
|
|
||||||
self._hook_progress({
|
|
||||||
'downloaded_bytes': fsize,
|
|
||||||
'total_bytes': fsize,
|
|
||||||
'filename': filename,
|
|
||||||
'status': 'finished',
|
|
||||||
})
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
self.to_stderr(u"\n")
|
|
||||||
self.report_error(u'mplayer exited with code %d' % retval)
|
|
||||||
return False
|
|
||||||
@@ -1,199 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
|
|
||||||
from .common import FileDownloader
|
|
||||||
from ..utils import (
|
|
||||||
encodeFilename,
|
|
||||||
format_bytes,
|
|
||||||
compat_str,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class RtmpFD(FileDownloader):
|
|
||||||
def real_download(self, filename, info_dict):
|
|
||||||
def run_rtmpdump(args):
|
|
||||||
start = time.time()
|
|
||||||
resume_percent = None
|
|
||||||
resume_downloaded_data_len = None
|
|
||||||
proc = subprocess.Popen(args, stderr=subprocess.PIPE)
|
|
||||||
cursor_in_new_line = True
|
|
||||||
proc_stderr_closed = False
|
|
||||||
while not proc_stderr_closed:
|
|
||||||
# read line from stderr
|
|
||||||
line = ''
|
|
||||||
while True:
|
|
||||||
char = proc.stderr.read(1)
|
|
||||||
if not char:
|
|
||||||
proc_stderr_closed = True
|
|
||||||
break
|
|
||||||
if char in [b'\r', b'\n']:
|
|
||||||
break
|
|
||||||
line += char.decode('ascii', 'replace')
|
|
||||||
if not line:
|
|
||||||
# proc_stderr_closed is True
|
|
||||||
continue
|
|
||||||
mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec \(([0-9]{1,2}\.[0-9])%\)', line)
|
|
||||||
if mobj:
|
|
||||||
downloaded_data_len = int(float(mobj.group(1))*1024)
|
|
||||||
percent = float(mobj.group(2))
|
|
||||||
if not resume_percent:
|
|
||||||
resume_percent = percent
|
|
||||||
resume_downloaded_data_len = downloaded_data_len
|
|
||||||
eta = self.calc_eta(start, time.time(), 100-resume_percent, percent-resume_percent)
|
|
||||||
speed = self.calc_speed(start, time.time(), downloaded_data_len-resume_downloaded_data_len)
|
|
||||||
data_len = None
|
|
||||||
if percent > 0:
|
|
||||||
data_len = int(downloaded_data_len * 100 / percent)
|
|
||||||
data_len_str = '~' + format_bytes(data_len)
|
|
||||||
self.report_progress(percent, data_len_str, speed, eta)
|
|
||||||
cursor_in_new_line = False
|
|
||||||
self._hook_progress({
|
|
||||||
'downloaded_bytes': downloaded_data_len,
|
|
||||||
'total_bytes': data_len,
|
|
||||||
'tmpfilename': tmpfilename,
|
|
||||||
'filename': filename,
|
|
||||||
'status': 'downloading',
|
|
||||||
'eta': eta,
|
|
||||||
'speed': speed,
|
|
||||||
})
|
|
||||||
else:
|
|
||||||
# no percent for live streams
|
|
||||||
mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec', line)
|
|
||||||
if mobj:
|
|
||||||
downloaded_data_len = int(float(mobj.group(1))*1024)
|
|
||||||
time_now = time.time()
|
|
||||||
speed = self.calc_speed(start, time_now, downloaded_data_len)
|
|
||||||
self.report_progress_live_stream(downloaded_data_len, speed, time_now - start)
|
|
||||||
cursor_in_new_line = False
|
|
||||||
self._hook_progress({
|
|
||||||
'downloaded_bytes': downloaded_data_len,
|
|
||||||
'tmpfilename': tmpfilename,
|
|
||||||
'filename': filename,
|
|
||||||
'status': 'downloading',
|
|
||||||
'speed': speed,
|
|
||||||
})
|
|
||||||
elif self.params.get('verbose', False):
|
|
||||||
if not cursor_in_new_line:
|
|
||||||
self.to_screen('')
|
|
||||||
cursor_in_new_line = True
|
|
||||||
self.to_screen('[rtmpdump] '+line)
|
|
||||||
proc.wait()
|
|
||||||
if not cursor_in_new_line:
|
|
||||||
self.to_screen('')
|
|
||||||
return proc.returncode
|
|
||||||
|
|
||||||
url = info_dict['url']
|
|
||||||
player_url = info_dict.get('player_url', None)
|
|
||||||
page_url = info_dict.get('page_url', None)
|
|
||||||
app = info_dict.get('app', None)
|
|
||||||
play_path = info_dict.get('play_path', None)
|
|
||||||
tc_url = info_dict.get('tc_url', None)
|
|
||||||
flash_version = info_dict.get('flash_version', None)
|
|
||||||
live = info_dict.get('rtmp_live', False)
|
|
||||||
conn = info_dict.get('rtmp_conn', None)
|
|
||||||
|
|
||||||
self.report_destination(filename)
|
|
||||||
tmpfilename = self.temp_name(filename)
|
|
||||||
test = self.params.get('test', False)
|
|
||||||
|
|
||||||
# Check for rtmpdump first
|
|
||||||
try:
|
|
||||||
subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
|
|
||||||
except (OSError, IOError):
|
|
||||||
self.report_error('RTMP download detected but "rtmpdump" could not be run')
|
|
||||||
return False
|
|
||||||
|
|
||||||
# Download using rtmpdump. rtmpdump returns exit code 2 when
|
|
||||||
# the connection was interrumpted and resuming appears to be
|
|
||||||
# possible. This is part of rtmpdump's normal usage, AFAIK.
|
|
||||||
basic_args = ['rtmpdump', '--verbose', '-r', url, '-o', tmpfilename]
|
|
||||||
if player_url is not None:
|
|
||||||
basic_args += ['--swfVfy', player_url]
|
|
||||||
if page_url is not None:
|
|
||||||
basic_args += ['--pageUrl', page_url]
|
|
||||||
if app is not None:
|
|
||||||
basic_args += ['--app', app]
|
|
||||||
if play_path is not None:
|
|
||||||
basic_args += ['--playpath', play_path]
|
|
||||||
if tc_url is not None:
|
|
||||||
basic_args += ['--tcUrl', url]
|
|
||||||
if test:
|
|
||||||
basic_args += ['--stop', '1']
|
|
||||||
if flash_version is not None:
|
|
||||||
basic_args += ['--flashVer', flash_version]
|
|
||||||
if live:
|
|
||||||
basic_args += ['--live']
|
|
||||||
if isinstance(conn, list):
|
|
||||||
for entry in conn:
|
|
||||||
basic_args += ['--conn', entry]
|
|
||||||
elif isinstance(conn, compat_str):
|
|
||||||
basic_args += ['--conn', conn]
|
|
||||||
args = basic_args + [[], ['--resume', '--skip', '1']][not live and self.params.get('continuedl', False)]
|
|
||||||
|
|
||||||
if sys.platform == 'win32' and sys.version_info < (3, 0):
|
|
||||||
# Windows subprocess module does not actually support Unicode
|
|
||||||
# on Python 2.x
|
|
||||||
# See http://stackoverflow.com/a/9951851/35070
|
|
||||||
subprocess_encoding = sys.getfilesystemencoding()
|
|
||||||
args = [a.encode(subprocess_encoding, 'ignore') for a in args]
|
|
||||||
else:
|
|
||||||
subprocess_encoding = None
|
|
||||||
|
|
||||||
if self.params.get('verbose', False):
|
|
||||||
if subprocess_encoding:
|
|
||||||
str_args = [
|
|
||||||
a.decode(subprocess_encoding) if isinstance(a, bytes) else a
|
|
||||||
for a in args]
|
|
||||||
else:
|
|
||||||
str_args = args
|
|
||||||
try:
|
|
||||||
import pipes
|
|
||||||
shell_quote = lambda args: ' '.join(map(pipes.quote, str_args))
|
|
||||||
except ImportError:
|
|
||||||
shell_quote = repr
|
|
||||||
self.to_screen('[debug] rtmpdump command line: ' + shell_quote(str_args))
|
|
||||||
|
|
||||||
RD_SUCCESS = 0
|
|
||||||
RD_FAILED = 1
|
|
||||||
RD_INCOMPLETE = 2
|
|
||||||
RD_NO_CONNECT = 3
|
|
||||||
|
|
||||||
retval = run_rtmpdump(args)
|
|
||||||
|
|
||||||
if retval == RD_NO_CONNECT:
|
|
||||||
self.report_error('[rtmpdump] Could not connect to RTMP server.')
|
|
||||||
return False
|
|
||||||
|
|
||||||
while (retval == RD_INCOMPLETE or retval == RD_FAILED) and not test and not live:
|
|
||||||
prevsize = os.path.getsize(encodeFilename(tmpfilename))
|
|
||||||
self.to_screen('[rtmpdump] %s bytes' % prevsize)
|
|
||||||
time.sleep(5.0) # This seems to be needed
|
|
||||||
retval = run_rtmpdump(basic_args + ['-e'] + [[], ['-k', '1']][retval == RD_FAILED])
|
|
||||||
cursize = os.path.getsize(encodeFilename(tmpfilename))
|
|
||||||
if prevsize == cursize and retval == RD_FAILED:
|
|
||||||
break
|
|
||||||
# Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
|
|
||||||
if prevsize == cursize and retval == RD_INCOMPLETE and cursize > 1024:
|
|
||||||
self.to_screen('[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
|
|
||||||
retval = RD_SUCCESS
|
|
||||||
break
|
|
||||||
if retval == RD_SUCCESS or (test and retval == RD_INCOMPLETE):
|
|
||||||
fsize = os.path.getsize(encodeFilename(tmpfilename))
|
|
||||||
self.to_screen('[rtmpdump] %s bytes' % fsize)
|
|
||||||
self.try_rename(tmpfilename, filename)
|
|
||||||
self._hook_progress({
|
|
||||||
'downloaded_bytes': fsize,
|
|
||||||
'total_bytes': fsize,
|
|
||||||
'filename': filename,
|
|
||||||
'status': 'finished',
|
|
||||||
})
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
self.to_stderr('\n')
|
|
||||||
self.report_error('rtmpdump exited with code %d' % retval)
|
|
||||||
return False
|
|
||||||
@@ -1,58 +1,31 @@
|
|||||||
from .academicearth import AcademicEarthCourseIE
|
|
||||||
from .addanime import AddAnimeIE
|
|
||||||
from .aftonbladet import AftonbladetIE
|
|
||||||
from .anitube import AnitubeIE
|
|
||||||
from .aol import AolIE
|
|
||||||
from .aparat import AparatIE
|
|
||||||
from .appletrailers import AppleTrailersIE
|
from .appletrailers import AppleTrailersIE
|
||||||
|
from .addanime import AddAnimeIE
|
||||||
|
from .anitube import AnitubeIE
|
||||||
from .archiveorg import ArchiveOrgIE
|
from .archiveorg import ArchiveOrgIE
|
||||||
from .ard import ARDIE
|
from .ard import ARDIE
|
||||||
from .arte import (
|
from .arte import (
|
||||||
ArteTvIE,
|
ArteTvIE,
|
||||||
ArteTVPlus7IE,
|
ArteTVPlus7IE,
|
||||||
ArteTVCreativeIE,
|
ArteTVCreativeIE,
|
||||||
ArteTVConcertIE,
|
|
||||||
ArteTVFutureIE,
|
ArteTVFutureIE,
|
||||||
ArteTVDDCIE,
|
|
||||||
ArteTVEmbedIE,
|
|
||||||
)
|
)
|
||||||
from .auengine import AUEngineIE
|
from .auengine import AUEngineIE
|
||||||
from .bambuser import BambuserIE, BambuserChannelIE
|
from .bambuser import BambuserIE, BambuserChannelIE
|
||||||
from .bandcamp import BandcampIE, BandcampAlbumIE
|
from .bandcamp import BandcampIE, BandcampAlbumIE
|
||||||
from .bbccouk import BBCCoUkIE
|
|
||||||
from .bilibili import BiliBiliIE
|
|
||||||
from .blinkx import BlinkxIE
|
|
||||||
from .bliptv import BlipTVIE, BlipTVUserIE
|
from .bliptv import BlipTVIE, BlipTVUserIE
|
||||||
from .bloomberg import BloombergIE
|
from .bloomberg import BloombergIE
|
||||||
from .br import BRIE
|
|
||||||
from .breakcom import BreakIE
|
from .breakcom import BreakIE
|
||||||
from .brightcove import BrightcoveIE
|
from .brightcove import BrightcoveIE
|
||||||
from .byutv import BYUtvIE
|
|
||||||
from .c56 import C56IE
|
from .c56 import C56IE
|
||||||
from .canal13cl import Canal13clIE
|
|
||||||
from .canalplus import CanalplusIE
|
from .canalplus import CanalplusIE
|
||||||
from .canalc2 import Canalc2IE
|
from .canalc2 import Canalc2IE
|
||||||
from .cbs import CBSIE
|
|
||||||
from .cbsnews import CBSNewsIE
|
|
||||||
from .ceskatelevize import CeskaTelevizeIE
|
|
||||||
from .channel9 import Channel9IE
|
|
||||||
from .chilloutzone import ChilloutzoneIE
|
|
||||||
from .cinemassacre import CinemassacreIE
|
from .cinemassacre import CinemassacreIE
|
||||||
from .clipfish import ClipfishIE
|
from .clipfish import ClipfishIE
|
||||||
from .cliphunter import CliphunterIE
|
from .cnn import CNNIE
|
||||||
from .clipsyndicate import ClipsyndicateIE
|
|
||||||
from .clubic import ClubicIE
|
|
||||||
from .cmt import CMTIE
|
|
||||||
from .cnet import CNETIE
|
|
||||||
from .cnn import (
|
|
||||||
CNNIE,
|
|
||||||
CNNBlogsIE,
|
|
||||||
)
|
|
||||||
from .collegehumor import CollegeHumorIE
|
from .collegehumor import CollegeHumorIE
|
||||||
from .comedycentral import ComedyCentralIE, ComedyCentralShowsIE
|
from .comedycentral import ComedyCentralIE, ComedyCentralShowsIE
|
||||||
from .condenast import CondeNastIE
|
from .condenast import CondeNastIE
|
||||||
from .criterion import CriterionIE
|
from .criterion import CriterionIE
|
||||||
from .crunchyroll import CrunchyrollIE
|
|
||||||
from .cspan import CSpanIE
|
from .cspan import CSpanIE
|
||||||
from .d8 import D8IE
|
from .d8 import D8IE
|
||||||
from .dailymotion import (
|
from .dailymotion import (
|
||||||
@@ -61,193 +34,92 @@ from .dailymotion import (
|
|||||||
DailymotionUserIE,
|
DailymotionUserIE,
|
||||||
)
|
)
|
||||||
from .daum import DaumIE
|
from .daum import DaumIE
|
||||||
|
from .depositfiles import DepositFilesIE
|
||||||
from .dotsub import DotsubIE
|
from .dotsub import DotsubIE
|
||||||
from .dreisat import DreiSatIE
|
from .dreisat import DreiSatIE
|
||||||
from .defense import DefenseGouvFrIE
|
from .defense import DefenseGouvFrIE
|
||||||
from .discovery import DiscoveryIE
|
|
||||||
from .divxstage import DivxStageIE
|
|
||||||
from .dropbox import DropboxIE
|
|
||||||
from .ebaumsworld import EbaumsWorldIE
|
from .ebaumsworld import EbaumsWorldIE
|
||||||
from .ehow import EHowIE
|
from .ehow import EHowIE
|
||||||
from .eighttracks import EightTracksIE
|
from .eighttracks import EightTracksIE
|
||||||
from .eitb import EitbIE
|
from .eitb import EitbIE
|
||||||
from .elpais import ElPaisIE
|
|
||||||
from .empflix import EmpflixIE
|
|
||||||
from .engadget import EngadgetIE
|
|
||||||
from .escapist import EscapistIE
|
from .escapist import EscapistIE
|
||||||
from .everyonesmixtape import EveryonesMixtapeIE
|
|
||||||
from .exfm import ExfmIE
|
from .exfm import ExfmIE
|
||||||
from .extremetube import ExtremeTubeIE
|
from .extremetube import ExtremeTubeIE
|
||||||
from .facebook import FacebookIE
|
from .facebook import FacebookIE
|
||||||
from .faz import FazIE
|
from .faz import FazIE
|
||||||
from .fc2 import FC2IE
|
|
||||||
from .firstpost import FirstpostIE
|
|
||||||
from .firsttv import FirstTVIE
|
|
||||||
from .fivemin import FiveMinIE
|
|
||||||
from .fktv import (
|
from .fktv import (
|
||||||
FKTVIE,
|
FKTVIE,
|
||||||
FKTVPosteckeIE,
|
FKTVPosteckeIE,
|
||||||
)
|
)
|
||||||
from .flickr import FlickrIE
|
from .flickr import FlickrIE
|
||||||
from .fourtube import FourTubeIE
|
|
||||||
from .franceculture import FranceCultureIE
|
|
||||||
from .franceinter import FranceInterIE
|
|
||||||
from .francetv import (
|
from .francetv import (
|
||||||
PluzzIE,
|
PluzzIE,
|
||||||
FranceTvInfoIE,
|
FranceTvInfoIE,
|
||||||
FranceTVIE,
|
France2IE,
|
||||||
GenerationQuoiIE,
|
GenerationQuoiIE
|
||||||
CultureboxIE,
|
|
||||||
)
|
)
|
||||||
from .freesound import FreesoundIE
|
from .freesound import FreesoundIE
|
||||||
from .freespeech import FreespeechIE
|
|
||||||
from .funnyordie import FunnyOrDieIE
|
from .funnyordie import FunnyOrDieIE
|
||||||
from .gamekings import GamekingsIE
|
from .gamekings import GamekingsIE
|
||||||
from .gamespot import GameSpotIE
|
from .gamespot import GameSpotIE
|
||||||
from .gametrailers import GametrailersIE
|
from .gametrailers import GametrailersIE
|
||||||
from .gdcvault import GDCVaultIE
|
|
||||||
from .generic import GenericIE
|
from .generic import GenericIE
|
||||||
from .googleplus import GooglePlusIE
|
from .googleplus import GooglePlusIE
|
||||||
from .googlesearch import GoogleSearchIE
|
from .googlesearch import GoogleSearchIE
|
||||||
from .hark import HarkIE
|
from .hark import HarkIE
|
||||||
from .helsinki import HelsinkiIE
|
|
||||||
from .hentaistigma import HentaiStigmaIE
|
|
||||||
from .hotnewhiphop import HotNewHipHopIE
|
from .hotnewhiphop import HotNewHipHopIE
|
||||||
from .howcast import HowcastIE
|
from .howcast import HowcastIE
|
||||||
from .huffpost import HuffPostIE
|
|
||||||
from .hypem import HypemIE
|
from .hypem import HypemIE
|
||||||
from .iconosquare import IconosquareIE
|
|
||||||
from .ign import IGNIE, OneUPIE
|
from .ign import IGNIE, OneUPIE
|
||||||
from .imdb import (
|
|
||||||
ImdbIE,
|
|
||||||
ImdbListIE
|
|
||||||
)
|
|
||||||
from .ina import InaIE
|
from .ina import InaIE
|
||||||
from .infoq import InfoQIE
|
from .infoq import InfoQIE
|
||||||
from .instagram import InstagramIE, InstagramUserIE
|
from .instagram import InstagramIE
|
||||||
from .internetvideoarchive import InternetVideoArchiveIE
|
from .internetvideoarchive import InternetVideoArchiveIE
|
||||||
from .iprima import IPrimaIE
|
|
||||||
from .ivi import (
|
|
||||||
IviIE,
|
|
||||||
IviCompilationIE
|
|
||||||
)
|
|
||||||
from .jadorecettepub import JadoreCettePubIE
|
|
||||||
from .jeuxvideo import JeuxVideoIE
|
from .jeuxvideo import JeuxVideoIE
|
||||||
from .jukebox import JukeboxIE
|
from .jukebox import JukeboxIE
|
||||||
from .justintv import JustinTVIE
|
from .justintv import JustinTVIE
|
||||||
from .jpopsukitv import JpopsukiIE
|
|
||||||
from .kankan import KankanIE
|
from .kankan import KankanIE
|
||||||
from .keezmovies import KeezMoviesIE
|
from .keezmovies import KeezMoviesIE
|
||||||
from .khanacademy import KhanAcademyIE
|
|
||||||
from .kickstarter import KickStarterIE
|
from .kickstarter import KickStarterIE
|
||||||
from .keek import KeekIE
|
from .keek import KeekIE
|
||||||
from .kontrtube import KontrTubeIE
|
|
||||||
from .la7 import LA7IE
|
|
||||||
from .lifenews import LifeNewsIE
|
|
||||||
from .liveleak import LiveLeakIE
|
from .liveleak import LiveLeakIE
|
||||||
from .livestream import LivestreamIE, LivestreamOriginalIE
|
from .livestream import LivestreamIE, LivestreamOriginalIE
|
||||||
from .lynda import (
|
|
||||||
LyndaIE,
|
|
||||||
LyndaCourseIE
|
|
||||||
)
|
|
||||||
from .m6 import M6IE
|
|
||||||
from .macgamestore import MacGameStoreIE
|
|
||||||
from .mailru import MailRuIE
|
|
||||||
from .malemotion import MalemotionIE
|
|
||||||
from .mdr import MDRIE
|
|
||||||
from .metacafe import MetacafeIE
|
from .metacafe import MetacafeIE
|
||||||
from .metacritic import MetacriticIE
|
from .metacritic import MetacriticIE
|
||||||
from .mit import TechTVMITIE, MITIE, OCWMITIE
|
from .mit import TechTVMITIE, MITIE
|
||||||
from .mixcloud import MixcloudIE
|
from .mixcloud import MixcloudIE
|
||||||
from .mpora import MporaIE
|
|
||||||
from .mofosex import MofosexIE
|
from .mofosex import MofosexIE
|
||||||
from .mooshare import MooshareIE
|
from .mtv import MTVIE
|
||||||
from .morningstar import MorningstarIE
|
|
||||||
from .motorsport import MotorsportIE
|
|
||||||
from .moviezine import MoviezineIE
|
|
||||||
from .movshare import MovShareIE
|
|
||||||
from .mtv import (
|
|
||||||
MTVIE,
|
|
||||||
MTVIggyIE,
|
|
||||||
)
|
|
||||||
from .musicplayon import MusicPlayOnIE
|
|
||||||
from .muzu import MuzuTVIE
|
from .muzu import MuzuTVIE
|
||||||
from .myspace import MySpaceIE
|
from .myspace import MySpaceIE
|
||||||
from .myspass import MySpassIE
|
from .myspass import MySpassIE
|
||||||
from .myvideo import MyVideoIE
|
from .myvideo import MyVideoIE
|
||||||
from .naver import NaverIE
|
from .naver import NaverIE
|
||||||
from .nba import NBAIE
|
from .nba import NBAIE
|
||||||
from .nbc import (
|
from .nbc import NBCNewsIE
|
||||||
NBCIE,
|
|
||||||
NBCNewsIE,
|
|
||||||
)
|
|
||||||
from .ndr import NDRIE
|
|
||||||
from .ndtv import NDTVIE
|
|
||||||
from .newgrounds import NewgroundsIE
|
from .newgrounds import NewgroundsIE
|
||||||
from .newstube import NewstubeIE
|
|
||||||
from .nfb import NFBIE
|
|
||||||
from .nhl import NHLIE, NHLVideocenterIE
|
from .nhl import NHLIE, NHLVideocenterIE
|
||||||
from .niconico import NiconicoIE
|
from .niconico import NiconicoIE
|
||||||
from .ninegag import NineGagIE
|
|
||||||
from .noco import NocoIE
|
|
||||||
from .normalboots import NormalbootsIE
|
|
||||||
from .novamov import NovaMovIE
|
|
||||||
from .nowness import NownessIE
|
|
||||||
from .nowvideo import NowVideoIE
|
from .nowvideo import NowVideoIE
|
||||||
from .nrk import NRKIE
|
|
||||||
from .ntv import NTVIE
|
|
||||||
from .nytimes import NYTimesIE
|
|
||||||
from .nuvid import NuvidIE
|
|
||||||
from .oe1 import OE1IE
|
|
||||||
from .ooyala import OoyalaIE
|
from .ooyala import OoyalaIE
|
||||||
from .orf import ORFIE
|
from .orf import ORFIE
|
||||||
from .parliamentliveuk import ParliamentLiveUKIE
|
|
||||||
from .pbs import PBSIE
|
from .pbs import PBSIE
|
||||||
from .photobucket import PhotobucketIE
|
from .photobucket import PhotobucketIE
|
||||||
from .playvid import PlayvidIE
|
|
||||||
from .podomatic import PodomaticIE
|
|
||||||
from .pornhd import PornHdIE
|
|
||||||
from .pornhub import PornHubIE
|
from .pornhub import PornHubIE
|
||||||
from .pornotube import PornotubeIE
|
from .pornotube import PornotubeIE
|
||||||
from .prosiebensat1 import ProSiebenSat1IE
|
|
||||||
from .pyvideo import PyvideoIE
|
|
||||||
from .radiofrance import RadioFranceIE
|
|
||||||
from .rbmaradio import RBMARadioIE
|
from .rbmaradio import RBMARadioIE
|
||||||
from .redtube import RedTubeIE
|
from .redtube import RedTubeIE
|
||||||
from .ringtv import RingTVIE
|
from .ringtv import RingTVIE
|
||||||
from .ro220 import Ro220IE
|
from .ro220 import Ro220IE
|
||||||
from .rottentomatoes import RottenTomatoesIE
|
from .rottentomatoes import RottenTomatoesIE
|
||||||
from .roxwel import RoxwelIE
|
from .roxwel import RoxwelIE
|
||||||
from .rtbf import RTBFIE
|
|
||||||
from .rtlnow import RTLnowIE
|
from .rtlnow import RTLnowIE
|
||||||
from .rts import RTSIE
|
from .rutube import RutubeIE
|
||||||
from .rtve import RTVEALaCartaIE
|
|
||||||
from .rutube import (
|
|
||||||
RutubeIE,
|
|
||||||
RutubeChannelIE,
|
|
||||||
RutubeMovieIE,
|
|
||||||
RutubePersonIE,
|
|
||||||
)
|
|
||||||
from .rutv import RUTVIE
|
|
||||||
from .savefrom import SaveFromIE
|
|
||||||
from .scivee import SciVeeIE
|
|
||||||
from .servingsys import ServingSysIE
|
|
||||||
from .sina import SinaIE
|
from .sina import SinaIE
|
||||||
|
from .slashdot import SlashdotIE
|
||||||
from .slideshare import SlideshareIE
|
from .slideshare import SlideshareIE
|
||||||
from .slutload import SlutloadIE
|
|
||||||
from .smotri import (
|
|
||||||
SmotriIE,
|
|
||||||
SmotriCommunityIE,
|
|
||||||
SmotriUserIE,
|
|
||||||
SmotriBroadcastIE,
|
|
||||||
)
|
|
||||||
from .sohu import SohuIE
|
from .sohu import SohuIE
|
||||||
from .soundcloud import (
|
from .soundcloud import SoundcloudIE, SoundcloudSetIE, SoundcloudUserIE
|
||||||
SoundcloudIE,
|
|
||||||
SoundcloudSetIE,
|
|
||||||
SoundcloudUserIE,
|
|
||||||
SoundcloudPlaylistIE
|
|
||||||
)
|
|
||||||
from .southparkstudios import (
|
from .southparkstudios import (
|
||||||
SouthParkStudiosIE,
|
SouthParkStudiosIE,
|
||||||
SouthparkDeIE,
|
SouthparkDeIE,
|
||||||
@@ -255,110 +127,66 @@ from .southparkstudios import (
|
|||||||
from .space import SpaceIE
|
from .space import SpaceIE
|
||||||
from .spankwire import SpankwireIE
|
from .spankwire import SpankwireIE
|
||||||
from .spiegel import SpiegelIE
|
from .spiegel import SpiegelIE
|
||||||
from .spike import SpikeIE
|
|
||||||
from .stanfordoc import StanfordOpenClassroomIE
|
from .stanfordoc import StanfordOpenClassroomIE
|
||||||
|
from .statigram import StatigramIE
|
||||||
from .steam import SteamIE
|
from .steam import SteamIE
|
||||||
from .streamcloud import StreamcloudIE
|
from .streamcloud import StreamcloudIE
|
||||||
from .streamcz import StreamCZIE
|
|
||||||
from .syfy import SyfyIE
|
|
||||||
from .sztvhu import SztvHuIE
|
from .sztvhu import SztvHuIE
|
||||||
from .teamcoco import TeamcocoIE
|
from .teamcoco import TeamcocoIE
|
||||||
from .techtalks import TechTalksIE
|
from .techtalks import TechTalksIE
|
||||||
from .ted import TEDIE
|
from .ted import TEDIE
|
||||||
from .testurl import TestURLIE
|
|
||||||
from .tf1 import TF1IE
|
from .tf1 import TF1IE
|
||||||
from .theplatform import ThePlatformIE
|
|
||||||
from .thisav import ThisAVIE
|
from .thisav import ThisAVIE
|
||||||
from .tinypic import TinyPicIE
|
|
||||||
from .tlc import TlcIE, TlcDeIE
|
|
||||||
from .toutv import TouTvIE
|
from .toutv import TouTvIE
|
||||||
from .toypics import ToypicsUserIE, ToypicsIE
|
|
||||||
from .traileraddict import TrailerAddictIE
|
from .traileraddict import TrailerAddictIE
|
||||||
from .trilulilu import TriluliluIE
|
from .trilulilu import TriluliluIE
|
||||||
from .trutube import TruTubeIE
|
|
||||||
from .tube8 import Tube8IE
|
from .tube8 import Tube8IE
|
||||||
from .tudou import TudouIE
|
from .tudou import TudouIE
|
||||||
from .tumblr import TumblrIE
|
from .tumblr import TumblrIE
|
||||||
from .tutv import TutvIE
|
from .tutv import TutvIE
|
||||||
from .tvigle import TvigleIE
|
|
||||||
from .tvp import TvpIE
|
from .tvp import TvpIE
|
||||||
from .udemy import (
|
|
||||||
UdemyIE,
|
|
||||||
UdemyCourseIE
|
|
||||||
)
|
|
||||||
from .unistra import UnistraIE
|
from .unistra import UnistraIE
|
||||||
from .urort import UrortIE
|
|
||||||
from .ustream import UstreamIE, UstreamChannelIE
|
from .ustream import UstreamIE, UstreamChannelIE
|
||||||
from .vbox7 import Vbox7IE
|
from .vbox7 import Vbox7IE
|
||||||
from .veehd import VeeHDIE
|
from .veehd import VeeHDIE
|
||||||
from .veoh import VeohIE
|
from .veoh import VeohIE
|
||||||
from .vesti import VestiIE
|
|
||||||
from .vevo import VevoIE
|
from .vevo import VevoIE
|
||||||
|
from .vice import ViceIE
|
||||||
from .viddler import ViddlerIE
|
from .viddler import ViddlerIE
|
||||||
from .videobam import VideoBamIE
|
|
||||||
from .videodetective import VideoDetectiveIE
|
from .videodetective import VideoDetectiveIE
|
||||||
from .videolecturesnet import VideoLecturesNetIE
|
|
||||||
from .videofyme import VideofyMeIE
|
from .videofyme import VideofyMeIE
|
||||||
from .videopremium import VideoPremiumIE
|
from .videopremium import VideoPremiumIE
|
||||||
from .videott import VideoTtIE
|
from .vimeo import VimeoIE, VimeoChannelIE
|
||||||
from .videoweed import VideoWeedIE
|
from .vine import VineIE
|
||||||
from .vimeo import (
|
|
||||||
VimeoIE,
|
|
||||||
VimeoChannelIE,
|
|
||||||
VimeoUserIE,
|
|
||||||
VimeoAlbumIE,
|
|
||||||
VimeoGroupsIE,
|
|
||||||
VimeoReviewIE,
|
|
||||||
VimeoWatchLaterIE,
|
|
||||||
)
|
|
||||||
from .vine import (
|
|
||||||
VineIE,
|
|
||||||
VineUserIE,
|
|
||||||
)
|
|
||||||
from .viki import VikiIE
|
from .viki import VikiIE
|
||||||
from .vk import VKIE
|
from .vk import VKIE
|
||||||
from .vube import VubeIE
|
|
||||||
from .vuclip import VuClipIE
|
|
||||||
from .washingtonpost import WashingtonPostIE
|
|
||||||
from .wat import WatIE
|
from .wat import WatIE
|
||||||
from .wdr import (
|
from .websurg import WeBSurgIE
|
||||||
WDRIE,
|
|
||||||
WDRMobileIE,
|
|
||||||
WDRMausIE,
|
|
||||||
)
|
|
||||||
from .weibo import WeiboIE
|
from .weibo import WeiboIE
|
||||||
from .wimp import WimpIE
|
from .wimp import WimpIE
|
||||||
from .wistia import WistiaIE
|
|
||||||
from .worldstarhiphop import WorldStarHipHopIE
|
from .worldstarhiphop import WorldStarHipHopIE
|
||||||
from .xbef import XBefIE
|
|
||||||
from .xhamster import XHamsterIE
|
from .xhamster import XHamsterIE
|
||||||
from .xnxx import XNXXIE
|
from .xnxx import XNXXIE
|
||||||
from .xvideos import XVideosIE
|
from .xvideos import XVideosIE
|
||||||
from .xtube import XTubeUserIE, XTubeIE
|
from .xtube import XTubeIE
|
||||||
from .yahoo import (
|
from .yahoo import YahooIE, YahooSearchIE
|
||||||
YahooIE,
|
|
||||||
YahooNewsIE,
|
|
||||||
YahooSearchIE,
|
|
||||||
)
|
|
||||||
from .youjizz import YouJizzIE
|
from .youjizz import YouJizzIE
|
||||||
from .youku import YoukuIE
|
from .youku import YoukuIE
|
||||||
from .youporn import YouPornIE
|
from .youporn import YouPornIE
|
||||||
from .youtube import (
|
from .youtube import (
|
||||||
YoutubeIE,
|
YoutubeIE,
|
||||||
YoutubeChannelIE,
|
|
||||||
YoutubeFavouritesIE,
|
|
||||||
YoutubeHistoryIE,
|
|
||||||
YoutubePlaylistIE,
|
YoutubePlaylistIE,
|
||||||
YoutubeRecommendedIE,
|
|
||||||
YoutubeSearchDateIE,
|
|
||||||
YoutubeSearchIE,
|
YoutubeSearchIE,
|
||||||
YoutubeSearchURLIE,
|
YoutubeSearchDateIE,
|
||||||
|
YoutubeUserIE,
|
||||||
|
YoutubeChannelIE,
|
||||||
YoutubeShowIE,
|
YoutubeShowIE,
|
||||||
YoutubeSubscriptionsIE,
|
YoutubeSubscriptionsIE,
|
||||||
YoutubeTopListIE,
|
YoutubeRecommendedIE,
|
||||||
YoutubeTruncatedURLIE,
|
YoutubeTruncatedURLIE,
|
||||||
YoutubeUserIE,
|
|
||||||
YoutubeWatchLaterIE,
|
YoutubeWatchLaterIE,
|
||||||
|
YoutubeFavouritesIE,
|
||||||
|
YoutubeHistoryIE,
|
||||||
)
|
)
|
||||||
from .zdf import ZDFIE
|
from .zdf import ZDFIE
|
||||||
|
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
|
|
||||||
|
|
||||||
class AcademicEarthCourseIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'^https?://(?:www\.)?academicearth\.org/playlists/(?P<id>[^?#/]+)'
|
|
||||||
IE_NAME = 'AcademicEarth:Course'
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
m = re.match(self._VALID_URL, url)
|
|
||||||
playlist_id = m.group('id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, playlist_id)
|
|
||||||
title = self._html_search_regex(
|
|
||||||
r'<h1 class="playlist-name"[^>]*?>(.*?)</h1>', webpage, u'title')
|
|
||||||
description = self._html_search_regex(
|
|
||||||
r'<p class="excerpt"[^>]*?>(.*?)</p>',
|
|
||||||
webpage, u'description', fatal=False)
|
|
||||||
urls = re.findall(
|
|
||||||
r'<li class="lecture-preview">\s*?<a target="_blank" href="([^"]+)">',
|
|
||||||
webpage)
|
|
||||||
entries = [self.url_result(u) for u in urls]
|
|
||||||
|
|
||||||
return {
|
|
||||||
'_type': 'playlist',
|
|
||||||
'id': playlist_id,
|
|
||||||
'title': title,
|
|
||||||
'description': description,
|
|
||||||
'entries': entries,
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
@@ -15,15 +13,15 @@ from ..utils import (
|
|||||||
|
|
||||||
class AddAnimeIE(InfoExtractor):
|
class AddAnimeIE(InfoExtractor):
|
||||||
|
|
||||||
_VALID_URL = r'^http://(?:\w+\.)?add-anime\.net/watch_video\.php\?(?:.*?)v=(?P<video_id>[\w_]+)(?:.*)'
|
_VALID_URL = r'^http://(?:\w+\.)?add-anime\.net/watch_video.php\?(?:.*?)v=(?P<video_id>[\w_]+)(?:.*)'
|
||||||
|
IE_NAME = u'AddAnime'
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://www.add-anime.net/watch_video.php?v=24MR3YO5SAS9',
|
u'url': u'http://www.add-anime.net/watch_video.php?v=24MR3YO5SAS9',
|
||||||
'md5': '72954ea10bc979ab5e2eb288b21425a0',
|
u'file': u'24MR3YO5SAS9.mp4',
|
||||||
'info_dict': {
|
u'md5': u'72954ea10bc979ab5e2eb288b21425a0',
|
||||||
'id': '24MR3YO5SAS9',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u"description": u"One Piece 606",
|
||||||
'description': 'One Piece 606',
|
u"title": u"One Piece 606"
|
||||||
'title': 'One Piece 606',
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,10 +38,10 @@ class AddAnimeIE(InfoExtractor):
|
|||||||
redir_webpage = ee.cause.read().decode('utf-8')
|
redir_webpage = ee.cause.read().decode('utf-8')
|
||||||
action = self._search_regex(
|
action = self._search_regex(
|
||||||
r'<form id="challenge-form" action="([^"]+)"',
|
r'<form id="challenge-form" action="([^"]+)"',
|
||||||
redir_webpage, 'Redirect form')
|
redir_webpage, u'Redirect form')
|
||||||
vc = self._search_regex(
|
vc = self._search_regex(
|
||||||
r'<input type="hidden" name="jschl_vc" value="([^"]+)"/>',
|
r'<input type="hidden" name="jschl_vc" value="([^"]+)"/>',
|
||||||
redir_webpage, 'redirect vc value')
|
redir_webpage, u'redirect vc value')
|
||||||
av = re.search(
|
av = re.search(
|
||||||
r'a\.value = ([0-9]+)[+]([0-9]+)[*]([0-9]+);',
|
r'a\.value = ([0-9]+)[+]([0-9]+)[*]([0-9]+);',
|
||||||
redir_webpage)
|
redir_webpage)
|
||||||
@@ -54,19 +52,19 @@ class AddAnimeIE(InfoExtractor):
|
|||||||
parsed_url = compat_urllib_parse_urlparse(url)
|
parsed_url = compat_urllib_parse_urlparse(url)
|
||||||
av_val = av_res + len(parsed_url.netloc)
|
av_val = av_res + len(parsed_url.netloc)
|
||||||
confirm_url = (
|
confirm_url = (
|
||||||
parsed_url.scheme + '://' + parsed_url.netloc +
|
parsed_url.scheme + u'://' + parsed_url.netloc +
|
||||||
action + '?' +
|
action + '?' +
|
||||||
compat_urllib_parse.urlencode({
|
compat_urllib_parse.urlencode({
|
||||||
'jschl_vc': vc, 'jschl_answer': compat_str(av_val)}))
|
'jschl_vc': vc, 'jschl_answer': compat_str(av_val)}))
|
||||||
self._download_webpage(
|
self._download_webpage(
|
||||||
confirm_url, video_id,
|
confirm_url, video_id,
|
||||||
note='Confirming after redirect')
|
note=u'Confirming after redirect')
|
||||||
webpage = self._download_webpage(url, video_id)
|
webpage = self._download_webpage(url, video_id)
|
||||||
|
|
||||||
formats = []
|
formats = []
|
||||||
for format_id in ('normal', 'hq'):
|
for format_id in ('normal', 'hq'):
|
||||||
rex = r"var %s_video_file = '(.*?)';" % re.escape(format_id)
|
rex = r"var %s_video_file = '(.*?)';" % re.escape(format_id)
|
||||||
video_url = self._search_regex(rex, webpage, 'video file URLx',
|
video_url = self._search_regex(rex, webpage, u'video file URLx',
|
||||||
fatal=False)
|
fatal=False)
|
||||||
if not video_url:
|
if not video_url:
|
||||||
continue
|
continue
|
||||||
@@ -74,13 +72,14 @@ class AddAnimeIE(InfoExtractor):
|
|||||||
'format_id': format_id,
|
'format_id': format_id,
|
||||||
'url': video_url,
|
'url': video_url,
|
||||||
})
|
})
|
||||||
self._sort_formats(formats)
|
if not formats:
|
||||||
|
raise ExtractorError(u'Cannot find any video format!')
|
||||||
video_title = self._og_search_title(webpage)
|
video_title = self._og_search_title(webpage)
|
||||||
video_description = self._og_search_description(webpage)
|
video_description = self._og_search_description(webpage)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'_type': 'video',
|
'_type': 'video',
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
'formats': formats,
|
'formats': formats,
|
||||||
'title': video_title,
|
'title': video_title,
|
||||||
'description': video_description
|
'description': video_description
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
# encoding: utf-8
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import datetime
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
|
|
||||||
|
|
||||||
class AftonbladetIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'^http://tv\.aftonbladet\.se/webbtv.+?(?P<video_id>article[0-9]+)\.ab(?:$|[?#])'
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://tv.aftonbladet.se/webbtv/nyheter/vetenskap/rymden/article36015.ab',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'article36015',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Vulkanutbrott i rymden - nu släpper NASA bilderna',
|
|
||||||
'description': 'Jupiters måne mest aktiv av alla himlakroppar',
|
|
||||||
'upload_date': '20140306',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.search(self._VALID_URL, url)
|
|
||||||
|
|
||||||
video_id = mobj.group('video_id')
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
|
|
||||||
# find internal video meta data
|
|
||||||
META_URL = 'http://aftonbladet-play.drlib.aptoma.no/video/%s.json'
|
|
||||||
internal_meta_id = self._html_search_regex(
|
|
||||||
r'data-aptomaId="([\w\d]+)"', webpage, 'internal_meta_id')
|
|
||||||
internal_meta_url = META_URL % internal_meta_id
|
|
||||||
internal_meta_json = self._download_json(
|
|
||||||
internal_meta_url, video_id, 'Downloading video meta data')
|
|
||||||
|
|
||||||
# find internal video formats
|
|
||||||
FORMATS_URL = 'http://aftonbladet-play.videodata.drvideo.aptoma.no/actions/video/?id=%s'
|
|
||||||
internal_video_id = internal_meta_json['videoId']
|
|
||||||
internal_formats_url = FORMATS_URL % internal_video_id
|
|
||||||
internal_formats_json = self._download_json(
|
|
||||||
internal_formats_url, video_id, 'Downloading video formats')
|
|
||||||
|
|
||||||
formats = []
|
|
||||||
for fmt in internal_formats_json['formats']['http']['pseudostreaming']['mp4']:
|
|
||||||
p = fmt['paths'][0]
|
|
||||||
formats.append({
|
|
||||||
'url': 'http://%s:%d/%s/%s' % (p['address'], p['port'], p['path'], p['filename']),
|
|
||||||
'ext': 'mp4',
|
|
||||||
'width': fmt['width'],
|
|
||||||
'height': fmt['height'],
|
|
||||||
'tbr': fmt['bitrate'],
|
|
||||||
'protocol': 'http',
|
|
||||||
})
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
timestamp = datetime.datetime.fromtimestamp(internal_meta_json['timePublished'])
|
|
||||||
upload_date = timestamp.strftime('%Y%m%d')
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'title': internal_meta_json['title'],
|
|
||||||
'formats': formats,
|
|
||||||
'thumbnail': internal_meta_json['imageUrl'],
|
|
||||||
'description': internal_meta_json['shortPreamble'],
|
|
||||||
'upload_date': upload_date,
|
|
||||||
'duration': internal_meta_json['duration'],
|
|
||||||
'view_count': internal_meta_json['views'],
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import re
|
import re
|
||||||
|
import xml.etree.ElementTree
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
|
|
||||||
@@ -27,8 +28,9 @@ class AnitubeIE(InfoExtractor):
|
|||||||
key = self._html_search_regex(r'http://www\.anitube\.se/embed/([A-Za-z0-9_-]*)',
|
key = self._html_search_regex(r'http://www\.anitube\.se/embed/([A-Za-z0-9_-]*)',
|
||||||
webpage, u'key')
|
webpage, u'key')
|
||||||
|
|
||||||
config_xml = self._download_xml('http://www.anitube.se/nuevo/econfig.php?key=%s' % key,
|
webpage_config = self._download_webpage('http://www.anitube.se/nuevo/econfig.php?key=%s' % key,
|
||||||
key)
|
key)
|
||||||
|
config_xml = xml.etree.ElementTree.fromstring(webpage_config.encode('utf-8'))
|
||||||
|
|
||||||
video_title = config_xml.find('title').text
|
video_title = config_xml.find('title').text
|
||||||
|
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from .fivemin import FiveMinIE
|
|
||||||
|
|
||||||
|
|
||||||
class AolIE(InfoExtractor):
|
|
||||||
IE_NAME = 'on.aol.com'
|
|
||||||
_VALID_URL = r'''(?x)
|
|
||||||
(?:
|
|
||||||
aol-video:|
|
|
||||||
http://on\.aol\.com/
|
|
||||||
(?:
|
|
||||||
video/.*-|
|
|
||||||
playlist/(?P<playlist_display_id>[^/?#]+?)-(?P<playlist_id>[0-9]+)[?#].*_videoid=
|
|
||||||
)
|
|
||||||
)
|
|
||||||
(?P<id>[0-9]+)
|
|
||||||
(?:$|\?)
|
|
||||||
'''
|
|
||||||
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://on.aol.com/video/u-s--official-warns-of-largest-ever-irs-phone-scam-518167793?icid=OnHomepageC2Wide_MustSee_Img',
|
|
||||||
'md5': '18ef68f48740e86ae94b98da815eec42',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '518167793',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'U.S. Official Warns Of \'Largest Ever\' IRS Phone Scam',
|
|
||||||
},
|
|
||||||
'add_ie': ['FiveMin'],
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
|
|
||||||
playlist_id = mobj.group('playlist_id')
|
|
||||||
if playlist_id and not self._downloader.params.get('noplaylist'):
|
|
||||||
self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, playlist_id)
|
|
||||||
title = self._html_search_regex(
|
|
||||||
r'<h1 class="video-title[^"]*">(.+?)</h1>', webpage, 'title')
|
|
||||||
playlist_html = self._search_regex(
|
|
||||||
r"(?s)<ul\s+class='video-related[^']*'>(.*?)</ul>", webpage,
|
|
||||||
'playlist HTML')
|
|
||||||
entries = [{
|
|
||||||
'_type': 'url',
|
|
||||||
'url': 'aol-video:%s' % m.group('id'),
|
|
||||||
'ie_key': 'Aol',
|
|
||||||
} for m in re.finditer(
|
|
||||||
r"<a\s+href='.*videoid=(?P<id>[0-9]+)'\s+class='video-thumb'>",
|
|
||||||
playlist_html)]
|
|
||||||
|
|
||||||
return {
|
|
||||||
'_type': 'playlist',
|
|
||||||
'id': playlist_id,
|
|
||||||
'display_id': mobj.group('playlist_display_id'),
|
|
||||||
'title': title,
|
|
||||||
'entries': entries,
|
|
||||||
}
|
|
||||||
|
|
||||||
return FiveMinIE._build_result(video_id)
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
#coding: utf-8
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import (
|
|
||||||
ExtractorError,
|
|
||||||
HEADRequest,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class AparatIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'^https?://(?:www\.)?aparat\.com/(?:v/|video/video/embed/videohash/)(?P<id>[a-zA-Z0-9]+)'
|
|
||||||
|
|
||||||
_TEST = {
|
|
||||||
u'url': u'http://www.aparat.com/v/wP8On',
|
|
||||||
u'file': u'wP8On.mp4',
|
|
||||||
u'md5': u'6714e0af7e0d875c5a39c4dc4ab46ad1',
|
|
||||||
u'info_dict': {
|
|
||||||
u"title": u"تیم گلکسی 11 - زومیت",
|
|
||||||
},
|
|
||||||
#u'skip': u'Extremely unreliable',
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
m = re.match(self._VALID_URL, url)
|
|
||||||
video_id = m.group('id')
|
|
||||||
|
|
||||||
# Note: There is an easier-to-parse configuration at
|
|
||||||
# http://www.aparat.com/video/video/config/videohash/%video_id
|
|
||||||
# but the URL in there does not work
|
|
||||||
embed_url = (u'http://www.aparat.com/video/video/embed/videohash/' +
|
|
||||||
video_id + u'/vt/frame')
|
|
||||||
webpage = self._download_webpage(embed_url, video_id)
|
|
||||||
|
|
||||||
video_urls = re.findall(r'fileList\[[0-9]+\]\s*=\s*"([^"]+)"', webpage)
|
|
||||||
for i, video_url in enumerate(video_urls):
|
|
||||||
req = HEADRequest(video_url)
|
|
||||||
res = self._request_webpage(
|
|
||||||
req, video_id, note=u'Testing video URL %d' % i, errnote=False)
|
|
||||||
if res:
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
raise ExtractorError(u'No working video URLs found')
|
|
||||||
|
|
||||||
title = self._search_regex(r'\s+title:\s*"([^"]+)"', webpage, u'title')
|
|
||||||
thumbnail = self._search_regex(
|
|
||||||
r'\s+image:\s*"([^"]+)"', webpage, u'thumbnail', fatal=False)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'title': title,
|
|
||||||
'url': video_url,
|
|
||||||
'ext': 'mp4',
|
|
||||||
'thumbnail': thumbnail,
|
|
||||||
}
|
|
||||||
@@ -1,63 +1,59 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import xml.etree.ElementTree
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import (
|
from ..utils import (
|
||||||
compat_urlparse,
|
compat_urlparse,
|
||||||
|
determine_ext,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class AppleTrailersIE(InfoExtractor):
|
class AppleTrailersIE(InfoExtractor):
|
||||||
_VALID_URL = r'https?://(?:www\.)?trailers\.apple\.com/trailers/(?P<company>[^/]+)/(?P<movie>[^/]+)'
|
_VALID_URL = r'https?://(?:www\.)?trailers.apple.com/trailers/(?P<company>[^/]+)/(?P<movie>[^/]+)'
|
||||||
_TEST = {
|
_TEST = {
|
||||||
"url": "http://trailers.apple.com/trailers/wb/manofsteel/",
|
u"url": u"http://trailers.apple.com/trailers/wb/manofsteel/",
|
||||||
"playlist": [
|
u"playlist": [
|
||||||
{
|
{
|
||||||
"md5": "d97a8e575432dbcb81b7c3acb741f8a8",
|
u"file": u"manofsteel-trailer4.mov",
|
||||||
"info_dict": {
|
u"md5": u"d97a8e575432dbcb81b7c3acb741f8a8",
|
||||||
"id": "manofsteel-trailer4",
|
u"info_dict": {
|
||||||
"ext": "mov",
|
u"duration": 111,
|
||||||
"duration": 111,
|
u"title": u"Trailer 4",
|
||||||
"title": "Trailer 4",
|
u"upload_date": u"20130523",
|
||||||
"upload_date": "20130523",
|
u"uploader_id": u"wb",
|
||||||
"uploader_id": "wb",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"md5": "b8017b7131b721fb4e8d6f49e1df908c",
|
u"file": u"manofsteel-trailer3.mov",
|
||||||
"info_dict": {
|
u"md5": u"b8017b7131b721fb4e8d6f49e1df908c",
|
||||||
"id": "manofsteel-trailer3",
|
u"info_dict": {
|
||||||
"ext": "mov",
|
u"duration": 182,
|
||||||
"duration": 182,
|
u"title": u"Trailer 3",
|
||||||
"title": "Trailer 3",
|
u"upload_date": u"20130417",
|
||||||
"upload_date": "20130417",
|
u"uploader_id": u"wb",
|
||||||
"uploader_id": "wb",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"md5": "d0f1e1150989b9924679b441f3404d48",
|
u"file": u"manofsteel-trailer.mov",
|
||||||
"info_dict": {
|
u"md5": u"d0f1e1150989b9924679b441f3404d48",
|
||||||
"id": "manofsteel-trailer",
|
u"info_dict": {
|
||||||
"ext": "mov",
|
u"duration": 148,
|
||||||
"duration": 148,
|
u"title": u"Trailer",
|
||||||
"title": "Trailer",
|
u"upload_date": u"20121212",
|
||||||
"upload_date": "20121212",
|
u"uploader_id": u"wb",
|
||||||
"uploader_id": "wb",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"md5": "5fe08795b943eb2e757fa95cb6def1cb",
|
u"file": u"manofsteel-teaser.mov",
|
||||||
"info_dict": {
|
u"md5": u"5fe08795b943eb2e757fa95cb6def1cb",
|
||||||
"id": "manofsteel-teaser",
|
u"info_dict": {
|
||||||
"ext": "mov",
|
u"duration": 93,
|
||||||
"duration": 93,
|
u"title": u"Teaser",
|
||||||
"title": "Teaser",
|
u"upload_date": u"20120721",
|
||||||
"upload_date": "20120721",
|
u"uploader_id": u"wb",
|
||||||
"uploader_id": "wb",
|
|
||||||
},
|
},
|
||||||
},
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,24 +64,24 @@ class AppleTrailersIE(InfoExtractor):
|
|||||||
movie = mobj.group('movie')
|
movie = mobj.group('movie')
|
||||||
uploader_id = mobj.group('company')
|
uploader_id = mobj.group('company')
|
||||||
|
|
||||||
playlist_url = compat_urlparse.urljoin(url, 'includes/playlists/itunes.inc')
|
playlist_url = compat_urlparse.urljoin(url, u'includes/playlists/itunes.inc')
|
||||||
def fix_html(s):
|
playlist_snippet = self._download_webpage(playlist_url, movie)
|
||||||
s = re.sub(r'(?s)<script[^<]*?>.*?</script>', '', s)
|
playlist_cleaned = re.sub(r'(?s)<script[^<]*?>.*?</script>', u'', playlist_snippet)
|
||||||
s = re.sub(r'<img ([^<]*?)>', r'<img \1/>', s)
|
playlist_cleaned = re.sub(r'<img ([^<]*?)>', r'<img \1/>', playlist_cleaned)
|
||||||
# The ' in the onClick attributes are not escaped, it couldn't be parsed
|
# The ' in the onClick attributes are not escaped, it couldn't be parsed
|
||||||
# like: http://trailers.apple.com/trailers/wb/gravity/
|
# with xml.etree.ElementTree.fromstring
|
||||||
def _clean_json(m):
|
# like: http://trailers.apple.com/trailers/wb/gravity/
|
||||||
return 'iTunes.playURL(%s);' % m.group(1).replace('\'', ''')
|
def _clean_json(m):
|
||||||
s = re.sub(self._JSON_RE, _clean_json, s)
|
return u'iTunes.playURL(%s);' % m.group(1).replace('\'', ''')
|
||||||
s = '<html>' + s + u'</html>'
|
playlist_cleaned = re.sub(self._JSON_RE, _clean_json, playlist_cleaned)
|
||||||
return s
|
playlist_html = u'<html>' + playlist_cleaned + u'</html>'
|
||||||
doc = self._download_xml(playlist_url, movie, transform_source=fix_html)
|
|
||||||
|
|
||||||
|
doc = xml.etree.ElementTree.fromstring(playlist_html)
|
||||||
playlist = []
|
playlist = []
|
||||||
for li in doc.findall('./div/ul/li'):
|
for li in doc.findall('./div/ul/li'):
|
||||||
on_click = li.find('.//a').attrib['onClick']
|
on_click = li.find('.//a').attrib['onClick']
|
||||||
trailer_info_json = self._search_regex(self._JSON_RE,
|
trailer_info_json = self._search_regex(self._JSON_RE,
|
||||||
on_click, 'trailer info')
|
on_click, u'trailer info')
|
||||||
trailer_info = json.loads(trailer_info_json)
|
trailer_info = json.loads(trailer_info_json)
|
||||||
title = trailer_info['title']
|
title = trailer_info['title']
|
||||||
video_id = movie + '-' + re.sub(r'[^a-zA-Z0-9]', '', title).lower()
|
video_id = movie + '-' + re.sub(r'[^a-zA-Z0-9]', '', title).lower()
|
||||||
@@ -101,7 +97,8 @@ class AppleTrailersIE(InfoExtractor):
|
|||||||
first_url = trailer_info['url']
|
first_url = trailer_info['url']
|
||||||
trailer_id = first_url.split('/')[-1].rpartition('_')[0].lower()
|
trailer_id = first_url.split('/')[-1].rpartition('_')[0].lower()
|
||||||
settings_json_url = compat_urlparse.urljoin(url, 'includes/settings/%s.json' % trailer_id)
|
settings_json_url = compat_urlparse.urljoin(url, 'includes/settings/%s.json' % trailer_id)
|
||||||
settings = self._download_json(settings_json_url, trailer_id, 'Downloading settings json')
|
settings_json = self._download_webpage(settings_json_url, trailer_id, u'Downloading settings json')
|
||||||
|
settings = json.loads(settings_json)
|
||||||
|
|
||||||
formats = []
|
formats = []
|
||||||
for format in settings['metadata']['sizes']:
|
for format in settings['metadata']['sizes']:
|
||||||
@@ -109,14 +106,14 @@ class AppleTrailersIE(InfoExtractor):
|
|||||||
format_url = re.sub(r'_(\d*p.mov)', r'_h\1', format['src'])
|
format_url = re.sub(r'_(\d*p.mov)', r'_h\1', format['src'])
|
||||||
formats.append({
|
formats.append({
|
||||||
'url': format_url,
|
'url': format_url,
|
||||||
|
'ext': determine_ext(format_url),
|
||||||
'format': format['type'],
|
'format': format['type'],
|
||||||
'width': format['width'],
|
'width': format['width'],
|
||||||
'height': int(format['height']),
|
'height': int(format['height']),
|
||||||
})
|
})
|
||||||
|
formats = sorted(formats, key=lambda f: (f['height'], f['width']))
|
||||||
|
|
||||||
self._sort_formats(formats)
|
info = {
|
||||||
|
|
||||||
playlist.append({
|
|
||||||
'_type': 'video',
|
'_type': 'video',
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
'title': title,
|
'title': title,
|
||||||
@@ -127,7 +124,12 @@ class AppleTrailersIE(InfoExtractor):
|
|||||||
'upload_date': upload_date,
|
'upload_date': upload_date,
|
||||||
'uploader_id': uploader_id,
|
'uploader_id': uploader_id,
|
||||||
'user_agent': 'QuickTime compatible (youtube-dl)',
|
'user_agent': 'QuickTime compatible (youtube-dl)',
|
||||||
})
|
}
|
||||||
|
# TODO: Remove when #980 has been merged
|
||||||
|
info['url'] = formats[-1]['url']
|
||||||
|
info['ext'] = formats[-1]['ext']
|
||||||
|
|
||||||
|
playlist.append(info)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'_type': 'playlist',
|
'_type': 'playlist',
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import (
|
from ..utils import (
|
||||||
|
determine_ext,
|
||||||
unified_strdate,
|
unified_strdate,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -12,24 +11,25 @@ from ..utils import (
|
|||||||
class ArchiveOrgIE(InfoExtractor):
|
class ArchiveOrgIE(InfoExtractor):
|
||||||
IE_NAME = 'archive.org'
|
IE_NAME = 'archive.org'
|
||||||
IE_DESC = 'archive.org videos'
|
IE_DESC = 'archive.org videos'
|
||||||
_VALID_URL = r'(?:https?://)?(?:www\.)?archive\.org/details/(?P<id>[^?/]+)(?:[?].*)?$'
|
_VALID_URL = r'(?:https?://)?(?:www\.)?archive.org/details/(?P<id>[^?/]+)(?:[?].*)?$'
|
||||||
_TEST = {
|
_TEST = {
|
||||||
"url": "http://archive.org/details/XD300-23_68HighlightsAResearchCntAugHumanIntellect",
|
u"url": u"http://archive.org/details/XD300-23_68HighlightsAResearchCntAugHumanIntellect",
|
||||||
'file': 'XD300-23_68HighlightsAResearchCntAugHumanIntellect.ogv',
|
u'file': u'XD300-23_68HighlightsAResearchCntAugHumanIntellect.ogv',
|
||||||
'md5': '8af1d4cf447933ed3c7f4871162602db',
|
u'md5': u'8af1d4cf447933ed3c7f4871162602db',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
"title": "1968 Demo - FJCC Conference Presentation Reel #1",
|
u"title": u"1968 Demo - FJCC Conference Presentation Reel #1",
|
||||||
"description": "Reel 1 of 3: Also known as the \"Mother of All Demos\", Doug Engelbart's presentation at the Fall Joint Computer Conference in San Francisco, December 9, 1968 titled \"A Research Center for Augmenting Human Intellect.\" For this presentation, Doug and his team astonished the audience by not only relating their research, but demonstrating it live. This was the debut of the mouse, interactive computing, hypermedia, computer supported software engineering, video teleconferencing, etc. See also <a href=\"http://dougengelbart.org/firsts/dougs-1968-demo.html\" rel=\"nofollow\">Doug's 1968 Demo page</a> for more background, highlights, links, and the detailed paper published in this conference proceedings. Filmed on 3 reels: Reel 1 | <a href=\"http://www.archive.org/details/XD300-24_68HighlightsAResearchCntAugHumanIntellect\" rel=\"nofollow\">Reel 2</a> | <a href=\"http://www.archive.org/details/XD300-25_68HighlightsAResearchCntAugHumanIntellect\" rel=\"nofollow\">Reel 3</a>",
|
u"description": u"Reel 1 of 3: Also known as the \"Mother of All Demos\", Doug Engelbart's presentation at the Fall Joint Computer Conference in San Francisco, December 9, 1968 titled \"A Research Center for Augmenting Human Intellect.\" For this presentation, Doug and his team astonished the audience by not only relating their research, but demonstrating it live. This was the debut of the mouse, interactive computing, hypermedia, computer supported software engineering, video teleconferencing, etc. See also <a href=\"http://dougengelbart.org/firsts/dougs-1968-demo.html\" rel=\"nofollow\">Doug's 1968 Demo page</a> for more background, highlights, links, and the detailed paper published in this conference proceedings. Filmed on 3 reels: Reel 1 | <a href=\"http://www.archive.org/details/XD300-24_68HighlightsAResearchCntAugHumanIntellect\" rel=\"nofollow\">Reel 2</a> | <a href=\"http://www.archive.org/details/XD300-25_68HighlightsAResearchCntAugHumanIntellect\" rel=\"nofollow\">Reel 3</a>",
|
||||||
"upload_date": "19681210",
|
u"upload_date": u"19681210",
|
||||||
"uploader": "SRI International"
|
u"uploader": u"SRI International"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
video_id = mobj.group('id')
|
video_id = mobj.group('id')
|
||||||
|
|
||||||
json_url = url + ('?' if '?' in url else '&') + 'output=json'
|
json_url = url + (u'?' if u'?' in url else '&') + u'output=json'
|
||||||
json_data = self._download_webpage(json_url, video_id)
|
json_data = self._download_webpage(json_url, video_id)
|
||||||
data = json.loads(json_data)
|
data = json.loads(json_data)
|
||||||
|
|
||||||
@@ -38,18 +38,18 @@ class ArchiveOrgIE(InfoExtractor):
|
|||||||
uploader = data['metadata']['creator'][0]
|
uploader = data['metadata']['creator'][0]
|
||||||
upload_date = unified_strdate(data['metadata']['date'][0])
|
upload_date = unified_strdate(data['metadata']['date'][0])
|
||||||
|
|
||||||
formats = [
|
formats = [{
|
||||||
{
|
|
||||||
'format': fdata['format'],
|
'format': fdata['format'],
|
||||||
'url': 'http://' + data['server'] + data['dir'] + fn,
|
'url': 'http://' + data['server'] + data['dir'] + fn,
|
||||||
'file_size': int(fdata['size']),
|
'file_size': int(fdata['size']),
|
||||||
}
|
}
|
||||||
for fn, fdata in data['files'].items()
|
for fn,fdata in data['files'].items()
|
||||||
if 'Video' in fdata['format']]
|
if 'Video' in fdata['format']]
|
||||||
|
formats.sort(key=lambda fdata: fdata['file_size'])
|
||||||
|
for f in formats:
|
||||||
|
f['ext'] = determine_ext(f['url'])
|
||||||
|
|
||||||
self._sort_formats(formats)
|
info = {
|
||||||
|
|
||||||
return {
|
|
||||||
'_type': 'video',
|
'_type': 'video',
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
'title': title,
|
'title': title,
|
||||||
@@ -57,5 +57,12 @@ class ArchiveOrgIE(InfoExtractor):
|
|||||||
'description': description,
|
'description': description,
|
||||||
'uploader': uploader,
|
'uploader': uploader,
|
||||||
'upload_date': upload_date,
|
'upload_date': upload_date,
|
||||||
'thumbnail': data.get('misc', {}).get('image'),
|
|
||||||
}
|
}
|
||||||
|
thumbnail = data.get('misc', {}).get('image')
|
||||||
|
if thumbnail:
|
||||||
|
info['thumbnail'] = thumbnail
|
||||||
|
|
||||||
|
# TODO: Remove when #980 has been merged
|
||||||
|
info.update(formats[-1])
|
||||||
|
|
||||||
|
return info
|
||||||
|
|||||||
@@ -1,28 +1,22 @@
|
|||||||
# coding: utf-8
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import (
|
from ..utils import (
|
||||||
determine_ext,
|
|
||||||
ExtractorError,
|
ExtractorError,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ARDIE(InfoExtractor):
|
class ARDIE(InfoExtractor):
|
||||||
_VALID_URL = r'^https?://(?:(?:www\.)?ardmediathek\.de|mediathek\.daserste\.de)/(?:.*/)(?P<video_id>[^/\?]+)(?:\?.*)?'
|
_VALID_URL = r'^(?:https?://)?(?:(?:www\.)?ardmediathek\.de|mediathek\.daserste\.de)/(?:.*/)(?P<video_id>[^/\?]+)(?:\?.*)?'
|
||||||
|
_TITLE = r'<h1(?: class="boxTopHeadline")?>(?P<title>.*)</h1>'
|
||||||
|
_MEDIA_STREAM = r'mediaCollection\.addMediaStream\((?P<media_type>\d+), (?P<quality>\d+), "(?P<rtmp_url>[^"]*)", "(?P<video_url>[^"]*)", "[^"]*"\)'
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://www.ardmediathek.de/das-erste/guenther-jauch/edward-snowden-im-interview-held-oder-verraeter?documentId=19288786',
|
u'url': u'http://www.ardmediathek.de/das-erste/tagesschau-in-100-sek?documentId=14077640',
|
||||||
'file': '19288786.mp4',
|
u'file': u'14077640.mp4',
|
||||||
'md5': '515bf47ce209fb3f5a61b7aad364634c',
|
u'md5': u'6ca8824255460c787376353f9e20bbd8',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'title': 'Edward Snowden im Interview - Held oder Verräter?',
|
u"title": u"11.04.2013 09:23 Uhr - Tagesschau in 100 Sekunden"
|
||||||
'description': 'Edward Snowden hat alles aufs Spiel gesetzt, um die weltweite \xdcberwachung durch die Geheimdienste zu enttarnen. Nun stellt sich der ehemalige NSA-Mitarbeiter erstmals weltweit in einem TV-Interview den Fragen eines NDR-Journalisten. Die Sendung vom Sonntagabend.',
|
|
||||||
'thumbnail': 'http://www.ardmediathek.de/ard/servlet/contentblob/19/28/87/90/19288790/bild/2250037',
|
|
||||||
},
|
},
|
||||||
'skip': 'Blocked outside of Germany',
|
u'skip': u'Requires rtmpdump'
|
||||||
}
|
}
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
@@ -35,49 +29,26 @@ class ARDIE(InfoExtractor):
|
|||||||
else:
|
else:
|
||||||
video_id = m.group('video_id')
|
video_id = m.group('video_id')
|
||||||
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
# determine title and media streams from webpage
|
||||||
|
html = self._download_webpage(url, video_id)
|
||||||
title = self._html_search_regex(
|
title = re.search(self._TITLE, html).group('title')
|
||||||
r'<h1(?:\s+class="boxTopHeadline")?>(.*?)</h1>', webpage, 'title')
|
streams = [mo.groupdict() for mo in re.finditer(self._MEDIA_STREAM, html)]
|
||||||
description = self._html_search_meta(
|
|
||||||
'dcterms.abstract', webpage, 'description')
|
|
||||||
thumbnail = self._og_search_thumbnail(webpage)
|
|
||||||
|
|
||||||
streams = [
|
|
||||||
mo.groupdict()
|
|
||||||
for mo in re.finditer(
|
|
||||||
r'mediaCollection\.addMediaStream\((?P<media_type>\d+), (?P<quality>\d+), "(?P<rtmp_url>[^"]*)", "(?P<video_url>[^"]*)", "[^"]*"\)', webpage)]
|
|
||||||
if not streams:
|
if not streams:
|
||||||
if '"fsk"' in webpage:
|
assert '"fsk"' in html
|
||||||
raise ExtractorError('This video is only available after 20:00')
|
raise ExtractorError(u'This video is only available after 8:00 pm')
|
||||||
|
|
||||||
formats = []
|
# choose default media type and highest quality for now
|
||||||
for s in streams:
|
stream = max([s for s in streams if int(s["media_type"]) == 0],
|
||||||
format = {
|
key=lambda s: int(s["quality"]))
|
||||||
'quality': int(s['quality']),
|
|
||||||
}
|
|
||||||
if s.get('rtmp_url'):
|
|
||||||
format['protocol'] = 'rtmp'
|
|
||||||
format['url'] = s['rtmp_url']
|
|
||||||
format['playpath'] = s['video_url']
|
|
||||||
else:
|
|
||||||
format['url'] = s['video_url']
|
|
||||||
|
|
||||||
quality_name = self._search_regex(
|
# there's two possibilities: RTMP stream or HTTP download
|
||||||
r'[,.]([a-zA-Z0-9_-]+),?\.mp4', format['url'],
|
info = {'id': video_id, 'title': title, 'ext': 'mp4'}
|
||||||
'quality name', default='NA')
|
if stream['rtmp_url']:
|
||||||
format['format_id'] = '%s-%s-%s-%s' % (
|
self.to_screen(u'RTMP download detected')
|
||||||
determine_ext(format['url']), quality_name, s['media_type'],
|
assert stream['video_url'].startswith('mp4:')
|
||||||
s['quality'])
|
info["url"] = stream["rtmp_url"]
|
||||||
|
info["play_path"] = stream['video_url']
|
||||||
formats.append(format)
|
else:
|
||||||
|
assert stream["video_url"].endswith('.mp4')
|
||||||
self._sort_formats(formats)
|
info["url"] = stream["video_url"]
|
||||||
|
return [info]
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'title': title,
|
|
||||||
'description': description,
|
|
||||||
'formats': formats,
|
|
||||||
'thumbnail': thumbnail,
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# encoding: utf-8
|
# encoding: utf-8
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import json
|
||||||
|
import xml.etree.ElementTree
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import (
|
from ..utils import (
|
||||||
@@ -11,53 +11,123 @@ from ..utils import (
|
|||||||
determine_ext,
|
determine_ext,
|
||||||
get_element_by_id,
|
get_element_by_id,
|
||||||
compat_str,
|
compat_str,
|
||||||
get_element_by_attribute,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# There are different sources of video in arte.tv, the extraction process
|
# There are different sources of video in arte.tv, the extraction process
|
||||||
# is different for each one. The videos usually expire in 7 days, so we can't
|
# is different for each one. The videos usually expire in 7 days, so we can't
|
||||||
# add tests.
|
# add tests.
|
||||||
|
|
||||||
|
|
||||||
class ArteTvIE(InfoExtractor):
|
class ArteTvIE(InfoExtractor):
|
||||||
_VALID_URL = r'http://videos\.arte\.tv/(?P<lang>fr|de)/.*-(?P<id>.*?)\.html'
|
_VIDEOS_URL = r'(?:http://)?videos.arte.tv/(?P<lang>fr|de)/.*-(?P<id>.*?).html'
|
||||||
IE_NAME = 'arte.tv'
|
_LIVEWEB_URL = r'(?:http://)?liveweb.arte.tv/(?P<lang>fr|de)/(?P<subpage>.+?)/(?P<name>.+)'
|
||||||
|
_LIVE_URL = r'index-[0-9]+\.html$'
|
||||||
|
|
||||||
|
IE_NAME = u'arte.tv'
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def suitable(cls, url):
|
||||||
|
return any(re.match(regex, url) for regex in (cls._VIDEOS_URL, cls._LIVEWEB_URL))
|
||||||
|
|
||||||
|
# TODO implement Live Stream
|
||||||
|
# from ..utils import compat_urllib_parse
|
||||||
|
# def extractLiveStream(self, url):
|
||||||
|
# video_lang = url.split('/')[-4]
|
||||||
|
# info = self.grep_webpage(
|
||||||
|
# url,
|
||||||
|
# r'src="(.*?/videothek_js.*?\.js)',
|
||||||
|
# 0,
|
||||||
|
# [
|
||||||
|
# (1, 'url', u'Invalid URL: %s' % url)
|
||||||
|
# ]
|
||||||
|
# )
|
||||||
|
# http_host = url.split('/')[2]
|
||||||
|
# next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
|
||||||
|
# info = self.grep_webpage(
|
||||||
|
# next_url,
|
||||||
|
# r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
|
||||||
|
# '(http://.*?\.swf).*?' +
|
||||||
|
# '(rtmp://.*?)\'',
|
||||||
|
# re.DOTALL,
|
||||||
|
# [
|
||||||
|
# (1, 'path', u'could not extract video path: %s' % url),
|
||||||
|
# (2, 'player', u'could not extract video player: %s' % url),
|
||||||
|
# (3, 'url', u'could not extract video url: %s' % url)
|
||||||
|
# ]
|
||||||
|
# )
|
||||||
|
# video_url = u'%s/%s' % (info.get('url'), info.get('path'))
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VIDEOS_URL, url)
|
||||||
lang = mobj.group('lang')
|
if mobj is not None:
|
||||||
video_id = mobj.group('id')
|
id = mobj.group('id')
|
||||||
|
lang = mobj.group('lang')
|
||||||
|
return self._extract_video(url, id, lang)
|
||||||
|
|
||||||
|
mobj = re.match(self._LIVEWEB_URL, url)
|
||||||
|
if mobj is not None:
|
||||||
|
name = mobj.group('name')
|
||||||
|
lang = mobj.group('lang')
|
||||||
|
return self._extract_liveweb(url, name, lang)
|
||||||
|
|
||||||
|
if re.search(self._LIVE_URL, url) is not None:
|
||||||
|
raise ExtractorError(u'Arte live streams are not yet supported, sorry')
|
||||||
|
# self.extractLiveStream(url)
|
||||||
|
# return
|
||||||
|
|
||||||
|
def _extract_video(self, url, video_id, lang):
|
||||||
|
"""Extract from videos.arte.tv"""
|
||||||
ref_xml_url = url.replace('/videos/', '/do_delegate/videos/')
|
ref_xml_url = url.replace('/videos/', '/do_delegate/videos/')
|
||||||
ref_xml_url = ref_xml_url.replace('.html', ',view,asPlayerXml.xml')
|
ref_xml_url = ref_xml_url.replace('.html', ',view,asPlayerXml.xml')
|
||||||
ref_xml_doc = self._download_xml(
|
ref_xml = self._download_webpage(ref_xml_url, video_id, note=u'Downloading metadata')
|
||||||
ref_xml_url, video_id, note='Downloading metadata')
|
ref_xml_doc = xml.etree.ElementTree.fromstring(ref_xml)
|
||||||
config_node = find_xpath_attr(ref_xml_doc, './/video', 'lang', lang)
|
config_node = find_xpath_attr(ref_xml_doc, './/video', 'lang', lang)
|
||||||
config_xml_url = config_node.attrib['ref']
|
config_xml_url = config_node.attrib['ref']
|
||||||
config = self._download_xml(
|
config_xml = self._download_webpage(config_xml_url, video_id, note=u'Downloading configuration')
|
||||||
config_xml_url, video_id, note='Downloading configuration')
|
|
||||||
|
|
||||||
formats = [{
|
video_urls = list(re.finditer(r'<url quality="(?P<quality>.*?)">(?P<url>.*?)</url>', config_xml))
|
||||||
'forma_id': q.attrib['quality'],
|
def _key(m):
|
||||||
'url': q.text,
|
quality = m.group('quality')
|
||||||
'ext': 'flv',
|
if quality == 'hd':
|
||||||
'quality': 2 if q.attrib['quality'] == 'hd' else 1,
|
return 2
|
||||||
} for q in config.findall('./urls/url')]
|
else:
|
||||||
self._sort_formats(formats)
|
return 1
|
||||||
|
# We pick the best quality
|
||||||
|
video_urls = sorted(video_urls, key=_key)
|
||||||
|
video_url = list(video_urls)[-1].group('url')
|
||||||
|
|
||||||
|
title = self._html_search_regex(r'<name>(.*?)</name>', config_xml, 'title')
|
||||||
|
thumbnail = self._html_search_regex(r'<firstThumbnailUrl>(.*?)</firstThumbnailUrl>',
|
||||||
|
config_xml, 'thumbnail')
|
||||||
|
return {'id': video_id,
|
||||||
|
'title': title,
|
||||||
|
'thumbnail': thumbnail,
|
||||||
|
'url': video_url,
|
||||||
|
'ext': 'flv',
|
||||||
|
}
|
||||||
|
|
||||||
title = config.find('.//name').text
|
def _extract_liveweb(self, url, name, lang):
|
||||||
thumbnail = config.find('.//firstThumbnailUrl').text
|
"""Extract form http://liveweb.arte.tv/"""
|
||||||
return {
|
webpage = self._download_webpage(url, name)
|
||||||
'id': video_id,
|
video_id = self._search_regex(r'eventId=(\d+?)("|&)', webpage, u'event id')
|
||||||
'title': title,
|
config_xml = self._download_webpage('http://download.liveweb.arte.tv/o21/liveweb/events/event-%s.xml' % video_id,
|
||||||
'thumbnail': thumbnail,
|
video_id, u'Downloading information')
|
||||||
'formats': formats,
|
config_doc = xml.etree.ElementTree.fromstring(config_xml.encode('utf-8'))
|
||||||
}
|
event_doc = config_doc.find('event')
|
||||||
|
url_node = event_doc.find('video').find('urlHd')
|
||||||
|
if url_node is None:
|
||||||
|
url_node = event_doc.find('urlSd')
|
||||||
|
|
||||||
|
return {'id': video_id,
|
||||||
|
'title': event_doc.find('name%s' % lang.capitalize()).text,
|
||||||
|
'url': url_node.text.replace('MP4', 'mp4'),
|
||||||
|
'ext': 'flv',
|
||||||
|
'thumbnail': self._og_search_thumbnail(webpage),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class ArteTVPlus7IE(InfoExtractor):
|
class ArteTVPlus7IE(InfoExtractor):
|
||||||
IE_NAME = 'arte.tv:+7'
|
IE_NAME = u'arte.tv:+7'
|
||||||
_VALID_URL = r'https?://(?:www\.)?arte\.tv/guide/(?P<lang>fr|de)/(?:(?:sendungen|emissions)/)?(?P<id>.*?)/(?P<name>.*?)(\?.*)?'
|
_VALID_URL = r'https?://www\.arte.tv/guide/(?P<lang>fr|de)/(?:(?:sendungen|emissions)/)?(?P<id>.*?)/(?P<name>.*?)(\?.*)?'
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _extract_url_info(cls, url):
|
def _extract_url_info(cls, url):
|
||||||
@@ -74,12 +144,11 @@ class ArteTVPlus7IE(InfoExtractor):
|
|||||||
return self._extract_from_webpage(webpage, video_id, lang)
|
return self._extract_from_webpage(webpage, video_id, lang)
|
||||||
|
|
||||||
def _extract_from_webpage(self, webpage, video_id, lang):
|
def _extract_from_webpage(self, webpage, video_id, lang):
|
||||||
json_url = self._html_search_regex(
|
json_url = self._html_search_regex(r'arte_vp_url="(.*?)"', webpage, 'json url')
|
||||||
r'arte_vp_url="(.*?)"', webpage, 'json vp url')
|
|
||||||
return self._extract_from_json_url(json_url, video_id, lang)
|
|
||||||
|
|
||||||
def _extract_from_json_url(self, json_url, video_id, lang):
|
json_info = self._download_webpage(json_url, video_id, 'Downloading info json')
|
||||||
info = self._download_json(json_url, video_id)
|
self.report_extraction(video_id)
|
||||||
|
info = json.loads(json_info)
|
||||||
player_info = info['videoJsonPlayer']
|
player_info = info['videoJsonPlayer']
|
||||||
|
|
||||||
info_dict = {
|
info_dict = {
|
||||||
@@ -101,8 +170,6 @@ class ArteTVPlus7IE(InfoExtractor):
|
|||||||
l = 'F'
|
l = 'F'
|
||||||
elif lang == 'de':
|
elif lang == 'de':
|
||||||
l = 'A'
|
l = 'A'
|
||||||
else:
|
|
||||||
l = lang
|
|
||||||
regexes = [r'VO?%s' % l, r'VO?.-ST%s' % l]
|
regexes = [r'VO?%s' % l, r'VO?.-ST%s' % l]
|
||||||
return any(re.match(r, f['versionCode']) for r in regexes)
|
return any(re.match(r, f['versionCode']) for r in regexes)
|
||||||
# Some formats may not be in the same language as the url
|
# Some formats may not be in the same language as the url
|
||||||
@@ -121,19 +188,14 @@ class ArteTVPlus7IE(InfoExtractor):
|
|||||||
return ['HQ', 'MQ', 'EQ', 'SQ'].index(f['quality'])
|
return ['HQ', 'MQ', 'EQ', 'SQ'].index(f['quality'])
|
||||||
else:
|
else:
|
||||||
def sort_key(f):
|
def sort_key(f):
|
||||||
versionCode = f.get('versionCode')
|
|
||||||
if versionCode is None:
|
|
||||||
versionCode = ''
|
|
||||||
return (
|
return (
|
||||||
# Sort first by quality
|
# Sort first by quality
|
||||||
int(f.get('height', -1)),
|
int(f.get('height',-1)),
|
||||||
int(f.get('bitrate', -1)),
|
int(f.get('bitrate',-1)),
|
||||||
# The original version with subtitles has lower relevance
|
# The original version with subtitles has lower relevance
|
||||||
re.match(r'VO-ST(F|A)', versionCode) is None,
|
re.match(r'VO-ST(F|A)', f.get('versionCode', '')) is None,
|
||||||
# The version with sourds/mal subtitles has also lower relevance
|
# The version with sourds/mal subtitles has also lower relevance
|
||||||
re.match(r'VO?(F|A)-STM\1', versionCode) is None,
|
re.match(r'VO?(F|A)-STM\1', f.get('versionCode', '')) is None,
|
||||||
# Prefer http downloads over m3u8
|
|
||||||
0 if f['url'].endswith('m3u8') else 1,
|
|
||||||
)
|
)
|
||||||
formats = sorted(formats, key=sort_key)
|
formats = sorted(formats, key=sort_key)
|
||||||
def _format(format_info):
|
def _format(format_info):
|
||||||
@@ -145,7 +207,7 @@ class ArteTVPlus7IE(InfoExtractor):
|
|||||||
if bitrate is not None:
|
if bitrate is not None:
|
||||||
quality += '-%d' % bitrate
|
quality += '-%d' % bitrate
|
||||||
if format_info.get('versionCode') is not None:
|
if format_info.get('versionCode') is not None:
|
||||||
format_id = '%s-%s' % (quality, format_info['versionCode'])
|
format_id = u'%s-%s' % (quality, format_info['versionCode'])
|
||||||
else:
|
else:
|
||||||
format_id = quality
|
format_id = quality
|
||||||
info = {
|
info = {
|
||||||
@@ -154,7 +216,7 @@ class ArteTVPlus7IE(InfoExtractor):
|
|||||||
'width': format_info.get('width'),
|
'width': format_info.get('width'),
|
||||||
'height': height,
|
'height': height,
|
||||||
}
|
}
|
||||||
if format_info['mediaType'] == 'rtmp':
|
if format_info['mediaType'] == u'rtmp':
|
||||||
info['url'] = format_info['streamer']
|
info['url'] = format_info['streamer']
|
||||||
info['play_path'] = 'mp4:' + format_info['url']
|
info['play_path'] = 'mp4:' + format_info['url']
|
||||||
info['ext'] = 'flv'
|
info['ext'] = 'flv'
|
||||||
@@ -169,29 +231,27 @@ class ArteTVPlus7IE(InfoExtractor):
|
|||||||
|
|
||||||
# It also uses the arte_vp_url url from the webpage to extract the information
|
# It also uses the arte_vp_url url from the webpage to extract the information
|
||||||
class ArteTVCreativeIE(ArteTVPlus7IE):
|
class ArteTVCreativeIE(ArteTVPlus7IE):
|
||||||
IE_NAME = 'arte.tv:creative'
|
IE_NAME = u'arte.tv:creative'
|
||||||
_VALID_URL = r'https?://creative\.arte\.tv/(?P<lang>fr|de)/magazine?/(?P<id>.+)'
|
_VALID_URL = r'https?://creative\.arte\.tv/(?P<lang>fr|de)/magazine?/(?P<id>.+)'
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://creative.arte.tv/de/magazin/agentur-amateur-corporate-design',
|
u'url': u'http://creative.arte.tv/de/magazin/agentur-amateur-corporate-design',
|
||||||
'info_dict': {
|
u'file': u'050489-002.mp4',
|
||||||
'id': '050489-002',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u'title': u'Agentur Amateur / Agence Amateur #2 : Corporate Design',
|
||||||
'title': 'Agentur Amateur / Agence Amateur #2 : Corporate Design',
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class ArteTVFutureIE(ArteTVPlus7IE):
|
class ArteTVFutureIE(ArteTVPlus7IE):
|
||||||
IE_NAME = 'arte.tv:future'
|
IE_NAME = u'arte.tv:future'
|
||||||
_VALID_URL = r'https?://future\.arte\.tv/(?P<lang>fr|de)/(thema|sujet)/.*?#article-anchor-(?P<id>\d+)'
|
_VALID_URL = r'https?://future\.arte\.tv/(?P<lang>fr|de)/(thema|sujet)/.*?#article-anchor-(?P<id>\d+)'
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://future.arte.tv/fr/sujet/info-sciences#article-anchor-7081',
|
u'url': u'http://future.arte.tv/fr/sujet/info-sciences#article-anchor-7081',
|
||||||
'info_dict': {
|
u'file': u'050940-003.mp4',
|
||||||
'id': '050940-003',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u'title': u'Les champignons au secours de la planète',
|
||||||
'title': 'Les champignons au secours de la planète',
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,57 +260,3 @@ class ArteTVFutureIE(ArteTVPlus7IE):
|
|||||||
webpage = self._download_webpage(url, anchor_id)
|
webpage = self._download_webpage(url, anchor_id)
|
||||||
row = get_element_by_id(anchor_id, webpage)
|
row = get_element_by_id(anchor_id, webpage)
|
||||||
return self._extract_from_webpage(row, anchor_id, lang)
|
return self._extract_from_webpage(row, anchor_id, lang)
|
||||||
|
|
||||||
|
|
||||||
class ArteTVDDCIE(ArteTVPlus7IE):
|
|
||||||
IE_NAME = 'arte.tv:ddc'
|
|
||||||
_VALID_URL = r'https?://ddc\.arte\.tv/(?P<lang>emission|folge)/(?P<id>.+)'
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
video_id, lang = self._extract_url_info(url)
|
|
||||||
if lang == 'folge':
|
|
||||||
lang = 'de'
|
|
||||||
elif lang == 'emission':
|
|
||||||
lang = 'fr'
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
scriptElement = get_element_by_attribute('class', 'visu_video_block', webpage)
|
|
||||||
script_url = self._html_search_regex(r'src="(.*?)"', scriptElement, 'script url')
|
|
||||||
javascriptPlayerGenerator = self._download_webpage(script_url, video_id, 'Download javascript player generator')
|
|
||||||
json_url = self._search_regex(r"json_url=(.*)&rendering_place.*", javascriptPlayerGenerator, 'json url')
|
|
||||||
return self._extract_from_json_url(json_url, video_id, lang)
|
|
||||||
|
|
||||||
|
|
||||||
class ArteTVConcertIE(ArteTVPlus7IE):
|
|
||||||
IE_NAME = 'arte.tv:concert'
|
|
||||||
_VALID_URL = r'https?://concert\.arte\.tv/(?P<lang>de|fr)/(?P<id>.+)'
|
|
||||||
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://concert.arte.tv/de/notwist-im-pariser-konzertclub-divan-du-monde',
|
|
||||||
'md5': '9ea035b7bd69696b67aa2ccaaa218161',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '186',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'The Notwist im Pariser Konzertclub "Divan du Monde"',
|
|
||||||
'upload_date': '20140128',
|
|
||||||
'description': 'md5:486eb08f991552ade77439fe6d82c305',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class ArteTVEmbedIE(ArteTVPlus7IE):
|
|
||||||
IE_NAME = 'arte.tv:embed'
|
|
||||||
_VALID_URL = r'''(?x)
|
|
||||||
http://www\.arte\.tv
|
|
||||||
/playerv2/embed\.php\?json_url=
|
|
||||||
(?P<json_url>
|
|
||||||
http://arte\.tv/papi/tvguide/videos/stream/player/
|
|
||||||
(?P<lang>[^/]+)/(?P<id>[^/]+)[^&]*
|
|
||||||
)
|
|
||||||
'''
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
lang = mobj.group('lang')
|
|
||||||
json_url = mobj.group('json_url')
|
|
||||||
return self._extract_from_json_url(json_url, video_id, lang)
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
@@ -9,26 +7,23 @@ from ..utils import (
|
|||||||
ExtractorError,
|
ExtractorError,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class AUEngineIE(InfoExtractor):
|
class AUEngineIE(InfoExtractor):
|
||||||
_VALID_URL = r'http://(?:www\.)?auengine\.com/embed\.php\?.*?file=(?P<id>[^&]+).*?'
|
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://auengine.com/embed.php?file=lfvlytY6&w=650&h=370',
|
u'url': u'http://auengine.com/embed.php?file=lfvlytY6&w=650&h=370',
|
||||||
'md5': '48972bdbcf1a3a2f5533e62425b41d4f',
|
u'file': u'lfvlytY6.mp4',
|
||||||
'info_dict': {
|
u'md5': u'48972bdbcf1a3a2f5533e62425b41d4f',
|
||||||
'id': 'lfvlytY6',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u"title": u"[Commie]The Legend of the Legendary Heroes - 03 - Replication Eye (Alpha Stigma)[F9410F5A]"
|
||||||
'title': '[Commie]The Legend of the Legendary Heroes - 03 - Replication Eye (Alpha Stigma)[F9410F5A]'
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_VALID_URL = r'(?:http://)?(?:www\.)?auengine\.com/embed.php\?.*?file=([^&]+).*?'
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
video_id = mobj.group('id')
|
video_id = mobj.group(1)
|
||||||
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
webpage = self._download_webpage(url, video_id)
|
||||||
title = self._html_search_regex(r'<title>(?P<title>.+?)</title>', webpage, 'title')
|
title = self._html_search_regex(r'<title>(?P<title>.+?)</title>',
|
||||||
|
webpage, u'title')
|
||||||
title = title.strip()
|
title = title.strip()
|
||||||
links = re.findall(r'\s(?:file|url):\s*["\']([^\'"]+)["\']', webpage)
|
links = re.findall(r'\s(?:file|url):\s*["\']([^\'"]+)["\']', webpage)
|
||||||
links = map(compat_urllib_parse.unquote, links)
|
links = map(compat_urllib_parse.unquote, links)
|
||||||
@@ -41,15 +36,14 @@ class AUEngineIE(InfoExtractor):
|
|||||||
elif '/videos/' in link:
|
elif '/videos/' in link:
|
||||||
video_url = link
|
video_url = link
|
||||||
if not video_url:
|
if not video_url:
|
||||||
raise ExtractorError('Could not find video URL')
|
raise ExtractorError(u'Could not find video URL')
|
||||||
ext = '.' + determine_ext(video_url)
|
ext = u'.' + determine_ext(video_url)
|
||||||
if ext == title[-len(ext):]:
|
if ext == title[-len(ext):]:
|
||||||
title = title[:-len(ext)]
|
title = title[:-len(ext)]
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
'url': video_url,
|
'url': video_url,
|
||||||
'title': title,
|
'title': title,
|
||||||
'thumbnail': thumbnail,
|
'thumbnail': thumbnail,
|
||||||
'http_referer': 'http://www.auengine.com/flowplayer/flowplayer.commercial-3.2.14.swf',
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
import itertools
|
import itertools
|
||||||
@@ -11,26 +9,26 @@ from ..utils import (
|
|||||||
|
|
||||||
|
|
||||||
class BambuserIE(InfoExtractor):
|
class BambuserIE(InfoExtractor):
|
||||||
IE_NAME = 'bambuser'
|
IE_NAME = u'bambuser'
|
||||||
_VALID_URL = r'https?://bambuser\.com/v/(?P<id>\d+)'
|
_VALID_URL = r'https?://bambuser\.com/v/(?P<id>\d+)'
|
||||||
_API_KEY = '005f64509e19a868399060af746a00aa'
|
_API_KEY = '005f64509e19a868399060af746a00aa'
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://bambuser.com/v/4050584',
|
u'url': u'http://bambuser.com/v/4050584',
|
||||||
# MD5 seems to be flaky, see https://travis-ci.org/rg3/youtube-dl/jobs/14051016#L388
|
# MD5 seems to be flaky, see https://travis-ci.org/rg3/youtube-dl/jobs/14051016#L388
|
||||||
#u'md5': 'fba8f7693e48fd4e8641b3fd5539a641',
|
#u'md5': u'fba8f7693e48fd4e8641b3fd5539a641',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'id': '4050584',
|
u'id': u'4050584',
|
||||||
'ext': 'flv',
|
u'ext': u'flv',
|
||||||
'title': 'Education engineering days - lightning talks',
|
u'title': u'Education engineering days - lightning talks',
|
||||||
'duration': 3741,
|
u'duration': 3741,
|
||||||
'uploader': 'pixelversity',
|
u'uploader': u'pixelversity',
|
||||||
'uploader_id': '344706',
|
u'uploader_id': u'344706',
|
||||||
},
|
},
|
||||||
'params': {
|
u'params': {
|
||||||
# It doesn't respect the 'Range' header, it would download the whole video
|
# It doesn't respect the 'Range' header, it would download the whole video
|
||||||
# caused the travis builds to fail: https://travis-ci.org/rg3/youtube-dl/jobs/14493845#L59
|
# caused the travis builds to fail: https://travis-ci.org/rg3/youtube-dl/jobs/14493845#L59
|
||||||
'skip_download': True,
|
u'skip_download': True,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,8 +53,8 @@ class BambuserIE(InfoExtractor):
|
|||||||
|
|
||||||
|
|
||||||
class BambuserChannelIE(InfoExtractor):
|
class BambuserChannelIE(InfoExtractor):
|
||||||
IE_NAME = 'bambuser:channel'
|
IE_NAME = u'bambuser:channel'
|
||||||
_VALID_URL = r'https?://bambuser\.com/channel/(?P<user>.*?)(?:/|#|\?|$)'
|
_VALID_URL = r'http://bambuser.com/channel/(?P<user>.*?)(?:/|#|\?|$)'
|
||||||
# The maximum number we can get with each request
|
# The maximum number we can get with each request
|
||||||
_STEP = 50
|
_STEP = 50
|
||||||
|
|
||||||
@@ -74,7 +72,7 @@ class BambuserChannelIE(InfoExtractor):
|
|||||||
# Without setting this header, we wouldn't get any result
|
# Without setting this header, we wouldn't get any result
|
||||||
req.add_header('Referer', 'http://bambuser.com/channel/%s' % user)
|
req.add_header('Referer', 'http://bambuser.com/channel/%s' % user)
|
||||||
info_json = self._download_webpage(req, user,
|
info_json = self._download_webpage(req, user,
|
||||||
'Downloading page %d' % i)
|
u'Downloading page %d' % i)
|
||||||
results = json.loads(info_json)['result']
|
results = json.loads(info_json)['result']
|
||||||
if len(results) == 0:
|
if len(results) == 0:
|
||||||
break
|
break
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
|
|
||||||
@@ -12,16 +10,16 @@ from ..utils import (
|
|||||||
|
|
||||||
|
|
||||||
class BandcampIE(InfoExtractor):
|
class BandcampIE(InfoExtractor):
|
||||||
_VALID_URL = r'https?://.*?\.bandcamp\.com/track/(?P<title>.*)'
|
IE_NAME = u'Bandcamp'
|
||||||
|
_VALID_URL = r'http://.*?\.bandcamp\.com/track/(?P<title>.*)'
|
||||||
_TESTS = [{
|
_TESTS = [{
|
||||||
'url': 'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
|
u'url': u'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
|
||||||
'file': '1812978515.mp3',
|
u'file': u'1812978515.mp3',
|
||||||
'md5': 'c557841d5e50261777a6585648adf439',
|
u'md5': u'cdeb30cdae1921719a3cbcab696ef53c',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
"title": "youtube-dl \"'/\\\u00e4\u21ad - youtube-dl test song \"'/\\\u00e4\u21ad",
|
u"title": u"youtube-dl test song \"'/\\\u00e4\u21ad"
|
||||||
"duration": 10,
|
|
||||||
},
|
},
|
||||||
'_skip': 'There is a limit of 200 free downloads / month for the test song'
|
u'skip': u'There is a limit of 200 free downloads / month for the test song'
|
||||||
}]
|
}]
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
@@ -32,117 +30,100 @@ class BandcampIE(InfoExtractor):
|
|||||||
m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
|
m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
|
||||||
if m_download is None:
|
if m_download is None:
|
||||||
m_trackinfo = re.search(r'trackinfo: (.+),\s*?\n', webpage)
|
m_trackinfo = re.search(r'trackinfo: (.+),\s*?\n', webpage)
|
||||||
if m_trackinfo:
|
if m_trackinfo:
|
||||||
json_code = m_trackinfo.group(1)
|
json_code = m_trackinfo.group(1)
|
||||||
data = json.loads(json_code)
|
data = json.loads(json_code)
|
||||||
d = data[0]
|
|
||||||
|
|
||||||
duration = int(round(d['duration']))
|
|
||||||
formats = []
|
|
||||||
for format_id, format_url in d['file'].items():
|
|
||||||
ext, _, abr_str = format_id.partition('-')
|
|
||||||
|
|
||||||
formats.append({
|
|
||||||
'format_id': format_id,
|
|
||||||
'url': format_url,
|
|
||||||
'ext': format_id.partition('-')[0],
|
|
||||||
'vcodec': 'none',
|
|
||||||
'acodec': format_id.partition('-')[0],
|
|
||||||
'abr': int(format_id.partition('-')[2]),
|
|
||||||
})
|
|
||||||
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
|
for d in data:
|
||||||
|
formats = [{
|
||||||
|
'format_id': 'format_id',
|
||||||
|
'url': format_url,
|
||||||
|
'ext': format_id.partition('-')[0]
|
||||||
|
} for format_id, format_url in sorted(d['file'].items())]
|
||||||
return {
|
return {
|
||||||
'id': compat_str(d['id']),
|
'id': compat_str(d['id']),
|
||||||
'title': d['title'],
|
'title': d['title'],
|
||||||
'formats': formats,
|
'formats': formats,
|
||||||
'duration': duration,
|
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
raise ExtractorError('No free songs found')
|
raise ExtractorError(u'No free songs found')
|
||||||
|
|
||||||
download_link = m_download.group(1)
|
download_link = m_download.group(1)
|
||||||
video_id = re.search(
|
id = re.search(r'var TralbumData = {(.*?)id: (?P<id>\d*?)$',
|
||||||
r'var TralbumData = {(.*?)id: (?P<id>\d*?)$',
|
webpage, re.MULTILINE|re.DOTALL).group('id')
|
||||||
webpage, re.MULTILINE | re.DOTALL).group('id')
|
|
||||||
|
|
||||||
download_webpage = self._download_webpage(download_link, video_id,
|
download_webpage = self._download_webpage(download_link, id,
|
||||||
'Downloading free downloads page')
|
'Downloading free downloads page')
|
||||||
# We get the dictionary of the track from some javascrip code
|
# We get the dictionary of the track from some javascrip code
|
||||||
info = re.search(r'items: (.*?),$',
|
info = re.search(r'items: (.*?),$',
|
||||||
download_webpage, re.MULTILINE).group(1)
|
download_webpage, re.MULTILINE).group(1)
|
||||||
info = json.loads(info)[0]
|
info = json.loads(info)[0]
|
||||||
# We pick mp3-320 for now, until format selection can be easily implemented.
|
# We pick mp3-320 for now, until format selection can be easily implemented.
|
||||||
mp3_info = info['downloads']['mp3-320']
|
mp3_info = info[u'downloads'][u'mp3-320']
|
||||||
# If we try to use this url it says the link has expired
|
# If we try to use this url it says the link has expired
|
||||||
initial_url = mp3_info['url']
|
initial_url = mp3_info[u'url']
|
||||||
re_url = r'(?P<server>http://(.*?)\.bandcamp\.com)/download/track\?enc=mp3-320&fsig=(?P<fsig>.*?)&id=(?P<id>.*?)&ts=(?P<ts>.*)$'
|
re_url = r'(?P<server>http://(.*?)\.bandcamp\.com)/download/track\?enc=mp3-320&fsig=(?P<fsig>.*?)&id=(?P<id>.*?)&ts=(?P<ts>.*)$'
|
||||||
m_url = re.match(re_url, initial_url)
|
m_url = re.match(re_url, initial_url)
|
||||||
#We build the url we will use to get the final track url
|
#We build the url we will use to get the final track url
|
||||||
# This url is build in Bandcamp in the script download_bunde_*.js
|
# This url is build in Bandcamp in the script download_bunde_*.js
|
||||||
request_url = '%s/statdownload/track?enc=mp3-320&fsig=%s&id=%s&ts=%s&.rand=665028774616&.vrs=1' % (m_url.group('server'), m_url.group('fsig'), video_id, m_url.group('ts'))
|
request_url = '%s/statdownload/track?enc=mp3-320&fsig=%s&id=%s&ts=%s&.rand=665028774616&.vrs=1' % (m_url.group('server'), m_url.group('fsig'), id, m_url.group('ts'))
|
||||||
final_url_webpage = self._download_webpage(request_url, video_id, 'Requesting download url')
|
final_url_webpage = self._download_webpage(request_url, id, 'Requesting download url')
|
||||||
# If we could correctly generate the .rand field the url would be
|
# If we could correctly generate the .rand field the url would be
|
||||||
#in the "download_url" key
|
#in the "download_url" key
|
||||||
final_url = re.search(r'"retry_url":"(.*?)"', final_url_webpage).group(1)
|
final_url = re.search(r'"retry_url":"(.*?)"', final_url_webpage).group(1)
|
||||||
|
|
||||||
return {
|
track_info = {'id':id,
|
||||||
'id': video_id,
|
'title' : info[u'title'],
|
||||||
'title': info['title'],
|
'ext' : 'mp3',
|
||||||
'ext': 'mp3',
|
'url' : final_url,
|
||||||
'vcodec': 'none',
|
'thumbnail' : info[u'thumb_url'],
|
||||||
'url': final_url,
|
'uploader' : info[u'artist']
|
||||||
'thumbnail': info.get('thumb_url'),
|
}
|
||||||
'uploader': info.get('artist'),
|
|
||||||
}
|
return [track_info]
|
||||||
|
|
||||||
|
|
||||||
class BandcampAlbumIE(InfoExtractor):
|
class BandcampAlbumIE(InfoExtractor):
|
||||||
IE_NAME = 'Bandcamp:album'
|
IE_NAME = u'Bandcamp:album'
|
||||||
_VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com(?:/album/(?P<title>[^?#]+))?'
|
_VALID_URL = r'http://.*?\.bandcamp\.com/album/(?P<title>.*)'
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
|
u'url': u'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
|
||||||
'playlist': [
|
u'playlist': [
|
||||||
{
|
{
|
||||||
'file': '1353101989.mp3',
|
u'file': u'1353101989.mp3',
|
||||||
'md5': '39bc1eded3476e927c724321ddf116cf',
|
u'md5': u'39bc1eded3476e927c724321ddf116cf',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'title': 'Intro',
|
u'title': u'Intro',
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'file': '38097443.mp3',
|
u'file': u'38097443.mp3',
|
||||||
'md5': '1a2c32e2691474643e912cc6cd4bffaa',
|
u'md5': u'1a2c32e2691474643e912cc6cd4bffaa',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'title': 'Kero One - Keep It Alive (Blazo remix)',
|
u'title': u'Kero One - Keep It Alive (Blazo remix)',
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
'params': {
|
u'params': {
|
||||||
'playlistend': 2
|
u'playlistend': 2
|
||||||
},
|
},
|
||||||
'skip': 'Bancamp imposes download limits. See test_playlists:test_bandcamp_album for the playlist test'
|
u'skip': u'Bancamp imposes download limits. See test_playlists:test_bandcamp_album for the playlist test'
|
||||||
}
|
}
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
playlist_id = mobj.group('subdomain')
|
|
||||||
title = mobj.group('title')
|
title = mobj.group('title')
|
||||||
display_id = title or playlist_id
|
webpage = self._download_webpage(url, title)
|
||||||
webpage = self._download_webpage(url, display_id)
|
|
||||||
tracks_paths = re.findall(r'<a href="(.*?)" itemprop="url">', webpage)
|
tracks_paths = re.findall(r'<a href="(.*?)" itemprop="url">', webpage)
|
||||||
if not tracks_paths:
|
if not tracks_paths:
|
||||||
raise ExtractorError('The page doesn\'t contain any tracks')
|
raise ExtractorError(u'The page doesn\'t contain any track')
|
||||||
entries = [
|
entries = [
|
||||||
self.url_result(compat_urlparse.urljoin(url, t_path), ie=BandcampIE.ie_key())
|
self.url_result(compat_urlparse.urljoin(url, t_path), ie=BandcampIE.ie_key())
|
||||||
for t_path in tracks_paths]
|
for t_path in tracks_paths]
|
||||||
title = self._search_regex(r'album_title : "(.*?)"', webpage, 'title')
|
title = self._search_regex(r'album_title : "(.*?)"', webpage, u'title')
|
||||||
return {
|
return {
|
||||||
'_type': 'playlist',
|
'_type': 'playlist',
|
||||||
'id': playlist_id,
|
|
||||||
'display_id': display_id,
|
|
||||||
'title': title,
|
'title': title,
|
||||||
'entries': entries,
|
'entries': entries,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,223 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .subtitles import SubtitlesInfoExtractor
|
|
||||||
from ..utils import ExtractorError
|
|
||||||
|
|
||||||
|
|
||||||
class BBCCoUkIE(SubtitlesInfoExtractor):
|
|
||||||
IE_NAME = 'bbc.co.uk'
|
|
||||||
IE_DESC = 'BBC iPlayer'
|
|
||||||
_VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:programmes|iplayer/episode)/(?P<id>[\da-z]{8})'
|
|
||||||
|
|
||||||
_TESTS = [
|
|
||||||
{
|
|
||||||
'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'b039d07m',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': 'Kaleidoscope: Leonard Cohen',
|
|
||||||
'description': 'md5:db4755d7a665ae72343779f7dacb402c',
|
|
||||||
'duration': 1740,
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
# rtmp download
|
|
||||||
'skip_download': True,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'b00yng1d',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': 'The Man in Black: Series 3: The Printed Name',
|
|
||||||
'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
|
|
||||||
'duration': 1800,
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
# rtmp download
|
|
||||||
'skip_download': True,
|
|
||||||
},
|
|
||||||
'skip': 'Episode is no longer available on BBC iPlayer Radio',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'b00yng1d',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': 'The Voice UK: Series 3: Blind Auditions 5',
|
|
||||||
'description': "Emma Willis and Marvin Humes present the fifth set of blind auditions in the singing competition, as the coaches continue to build their teams based on voice alone.",
|
|
||||||
'duration': 5100,
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
# rtmp download
|
|
||||||
'skip_download': True,
|
|
||||||
},
|
|
||||||
'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
def _extract_asx_playlist(self, connection, programme_id):
|
|
||||||
asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
|
|
||||||
return [ref.get('href') for ref in asx.findall('./Entry/ref')]
|
|
||||||
|
|
||||||
def _extract_connection(self, connection, programme_id):
|
|
||||||
formats = []
|
|
||||||
protocol = connection.get('protocol')
|
|
||||||
supplier = connection.get('supplier')
|
|
||||||
if protocol == 'http':
|
|
||||||
href = connection.get('href')
|
|
||||||
# ASX playlist
|
|
||||||
if supplier == 'asx':
|
|
||||||
for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
|
|
||||||
formats.append({
|
|
||||||
'url': ref,
|
|
||||||
'format_id': 'ref%s_%s' % (i, supplier),
|
|
||||||
})
|
|
||||||
# Direct link
|
|
||||||
else:
|
|
||||||
formats.append({
|
|
||||||
'url': href,
|
|
||||||
'format_id': supplier,
|
|
||||||
})
|
|
||||||
elif protocol == 'rtmp':
|
|
||||||
application = connection.get('application', 'ondemand')
|
|
||||||
auth_string = connection.get('authString')
|
|
||||||
identifier = connection.get('identifier')
|
|
||||||
server = connection.get('server')
|
|
||||||
formats.append({
|
|
||||||
'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
|
|
||||||
'play_path': identifier,
|
|
||||||
'app': '%s?%s' % (application, auth_string),
|
|
||||||
'page_url': 'http://www.bbc.co.uk',
|
|
||||||
'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
|
|
||||||
'rtmp_live': False,
|
|
||||||
'ext': 'flv',
|
|
||||||
'format_id': supplier,
|
|
||||||
})
|
|
||||||
return formats
|
|
||||||
|
|
||||||
def _extract_items(self, playlist):
|
|
||||||
return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
|
|
||||||
|
|
||||||
def _extract_medias(self, media_selection):
|
|
||||||
return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
|
|
||||||
|
|
||||||
def _extract_connections(self, media):
|
|
||||||
return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
|
|
||||||
|
|
||||||
def _extract_video(self, media, programme_id):
|
|
||||||
formats = []
|
|
||||||
vbr = int(media.get('bitrate'))
|
|
||||||
vcodec = media.get('encoding')
|
|
||||||
service = media.get('service')
|
|
||||||
width = int(media.get('width'))
|
|
||||||
height = int(media.get('height'))
|
|
||||||
file_size = int(media.get('media_file_size'))
|
|
||||||
for connection in self._extract_connections(media):
|
|
||||||
conn_formats = self._extract_connection(connection, programme_id)
|
|
||||||
for format in conn_formats:
|
|
||||||
format.update({
|
|
||||||
'format_id': '%s_%s' % (service, format['format_id']),
|
|
||||||
'width': width,
|
|
||||||
'height': height,
|
|
||||||
'vbr': vbr,
|
|
||||||
'vcodec': vcodec,
|
|
||||||
'filesize': file_size,
|
|
||||||
})
|
|
||||||
formats.extend(conn_formats)
|
|
||||||
return formats
|
|
||||||
|
|
||||||
def _extract_audio(self, media, programme_id):
|
|
||||||
formats = []
|
|
||||||
abr = int(media.get('bitrate'))
|
|
||||||
acodec = media.get('encoding')
|
|
||||||
service = media.get('service')
|
|
||||||
for connection in self._extract_connections(media):
|
|
||||||
conn_formats = self._extract_connection(connection, programme_id)
|
|
||||||
for format in conn_formats:
|
|
||||||
format.update({
|
|
||||||
'format_id': '%s_%s' % (service, format['format_id']),
|
|
||||||
'abr': abr,
|
|
||||||
'acodec': acodec,
|
|
||||||
})
|
|
||||||
formats.extend(conn_formats)
|
|
||||||
return formats
|
|
||||||
|
|
||||||
def _extract_captions(self, media, programme_id):
|
|
||||||
subtitles = {}
|
|
||||||
for connection in self._extract_connections(media):
|
|
||||||
captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
|
|
||||||
lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
|
|
||||||
ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/2006/10/ttaf1}'))
|
|
||||||
srt = ''
|
|
||||||
for pos, p in enumerate(ps):
|
|
||||||
srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), p.get('begin'), p.get('end'),
|
|
||||||
p.text.strip() if p.text is not None else '')
|
|
||||||
subtitles[lang] = srt
|
|
||||||
return subtitles
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
group_id = mobj.group('id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, group_id, 'Downloading video page')
|
|
||||||
if re.search(r'id="emp-error" class="notinuk">', webpage):
|
|
||||||
raise ExtractorError('Currently BBC iPlayer TV programmes are available to play in the UK only',
|
|
||||||
expected=True)
|
|
||||||
|
|
||||||
playlist = self._download_xml('http://www.bbc.co.uk/iplayer/playlist/%s' % group_id, group_id,
|
|
||||||
'Downloading playlist XML')
|
|
||||||
|
|
||||||
no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
|
|
||||||
if no_items is not None:
|
|
||||||
reason = no_items.get('reason')
|
|
||||||
if reason == 'preAvailability':
|
|
||||||
msg = 'Episode %s is not yet available' % group_id
|
|
||||||
elif reason == 'postAvailability':
|
|
||||||
msg = 'Episode %s is no longer available' % group_id
|
|
||||||
else:
|
|
||||||
msg = 'Episode %s is not available: %s' % (group_id, reason)
|
|
||||||
raise ExtractorError(msg, expected=True)
|
|
||||||
|
|
||||||
formats = []
|
|
||||||
subtitles = None
|
|
||||||
|
|
||||||
for item in self._extract_items(playlist):
|
|
||||||
kind = item.get('kind')
|
|
||||||
if kind != 'programme' and kind != 'radioProgramme':
|
|
||||||
continue
|
|
||||||
title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
|
|
||||||
description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
|
|
||||||
|
|
||||||
programme_id = item.get('identifier')
|
|
||||||
duration = int(item.get('duration'))
|
|
||||||
|
|
||||||
media_selection = self._download_xml(
|
|
||||||
'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s' % programme_id,
|
|
||||||
programme_id, 'Downloading media selection XML')
|
|
||||||
|
|
||||||
for media in self._extract_medias(media_selection):
|
|
||||||
kind = media.get('kind')
|
|
||||||
if kind == 'audio':
|
|
||||||
formats.extend(self._extract_audio(media, programme_id))
|
|
||||||
elif kind == 'video':
|
|
||||||
formats.extend(self._extract_video(media, programme_id))
|
|
||||||
elif kind == 'captions':
|
|
||||||
subtitles = self._extract_captions(media, programme_id)
|
|
||||||
|
|
||||||
if self._downloader.params.get('listsubtitles', False):
|
|
||||||
self._list_available_subtitles(programme_id, subtitles)
|
|
||||||
return
|
|
||||||
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': programme_id,
|
|
||||||
'title': title,
|
|
||||||
'description': description,
|
|
||||||
'duration': duration,
|
|
||||||
'formats': formats,
|
|
||||||
'subtitles': subtitles,
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
# coding: utf-8
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import (
|
|
||||||
compat_parse_qs,
|
|
||||||
ExtractorError,
|
|
||||||
int_or_none,
|
|
||||||
unified_strdate,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class BiliBiliIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'http://www\.bilibili\.tv/video/av(?P<id>[0-9]+)/'
|
|
||||||
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.bilibili.tv/video/av1074402/',
|
|
||||||
'md5': '2c301e4dab317596e837c3e7633e7d86',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '1074402',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': '【金坷垃】金泡沫',
|
|
||||||
'duration': 308,
|
|
||||||
'upload_date': '20140420',
|
|
||||||
'thumbnail': 're:^https?://.+\.jpg',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
video_code = self._search_regex(
|
|
||||||
r'(?s)<div itemprop="video".*?>(.*?)</div>', webpage, 'video code')
|
|
||||||
|
|
||||||
title = self._html_search_meta(
|
|
||||||
'media:title', video_code, 'title', fatal=True)
|
|
||||||
duration_str = self._html_search_meta(
|
|
||||||
'duration', video_code, 'duration')
|
|
||||||
if duration_str is None:
|
|
||||||
duration = None
|
|
||||||
else:
|
|
||||||
duration_mobj = re.match(
|
|
||||||
r'^T(?:(?P<hours>[0-9]+)H)?(?P<minutes>[0-9]+)M(?P<seconds>[0-9]+)S$',
|
|
||||||
duration_str)
|
|
||||||
duration = (
|
|
||||||
int_or_none(duration_mobj.group('hours'), default=0) * 3600 +
|
|
||||||
int(duration_mobj.group('minutes')) * 60 +
|
|
||||||
int(duration_mobj.group('seconds')))
|
|
||||||
upload_date = unified_strdate(self._html_search_meta(
|
|
||||||
'uploadDate', video_code, fatal=False))
|
|
||||||
thumbnail = self._html_search_meta(
|
|
||||||
'thumbnailUrl', video_code, 'thumbnail', fatal=False)
|
|
||||||
|
|
||||||
player_params = compat_parse_qs(self._html_search_regex(
|
|
||||||
r'<iframe .*?class="player" src="https://secure.bilibili.tv/secure,([^"]+)"',
|
|
||||||
webpage, 'player params'))
|
|
||||||
|
|
||||||
if 'cid' in player_params:
|
|
||||||
cid = player_params['cid'][0]
|
|
||||||
|
|
||||||
lq_doc = self._download_xml(
|
|
||||||
'http://interface.bilibili.cn/v_cdn_play?cid=%s' % cid,
|
|
||||||
video_id,
|
|
||||||
note='Downloading LQ video info'
|
|
||||||
)
|
|
||||||
lq_durl = lq_doc.find('.//durl')
|
|
||||||
formats = [{
|
|
||||||
'format_id': 'lq',
|
|
||||||
'quality': 1,
|
|
||||||
'url': lq_durl.find('./url').text,
|
|
||||||
'filesize': int_or_none(
|
|
||||||
lq_durl.find('./size'), get_attr='text'),
|
|
||||||
}]
|
|
||||||
|
|
||||||
hq_doc = self._download_xml(
|
|
||||||
'http://interface.bilibili.cn/playurl?cid=%s' % cid,
|
|
||||||
video_id,
|
|
||||||
note='Downloading HQ video info',
|
|
||||||
fatal=False,
|
|
||||||
)
|
|
||||||
if hq_doc is not False:
|
|
||||||
hq_durl = hq_doc.find('.//durl')
|
|
||||||
formats.append({
|
|
||||||
'format_id': 'hq',
|
|
||||||
'quality': 2,
|
|
||||||
'ext': 'flv',
|
|
||||||
'url': hq_durl.find('./url').text,
|
|
||||||
'filesize': int_or_none(
|
|
||||||
hq_durl.find('./size'), get_attr='text'),
|
|
||||||
})
|
|
||||||
else:
|
|
||||||
raise ExtractorError('Unsupported player parameters: %r' % (player_params,))
|
|
||||||
|
|
||||||
self._sort_formats(formats)
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'title': title,
|
|
||||||
'formats': formats,
|
|
||||||
'duration': duration,
|
|
||||||
'upload_date': upload_date,
|
|
||||||
'thumbnail': thumbnail,
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import datetime
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import (
|
|
||||||
remove_start,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class BlinkxIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'^(?:https?://(?:www\.)blinkx\.com/#?ce/|blinkx:)(?P<id>[^?]+)'
|
|
||||||
IE_NAME = 'blinkx'
|
|
||||||
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.blinkx.com/ce/8aQUy7GVFYgFzpKhT0oqsilwOGFRVXk3R1ZGWWdGenBLaFQwb3FzaWx3OGFRVXk3R1ZGWWdGenB',
|
|
||||||
'file': '8aQUy7GV.mp4',
|
|
||||||
'md5': '2e9a07364af40163a908edbf10bb2492',
|
|
||||||
'info_dict': {
|
|
||||||
"title": "Police Car Rolls Away",
|
|
||||||
"uploader": "stupidvideos.com",
|
|
||||||
"upload_date": "20131215",
|
|
||||||
"description": "A police car gently rolls away from a fight. Maybe it felt weird being around a confrontation and just had to get out of there!",
|
|
||||||
"duration": 14.886,
|
|
||||||
"thumbnails": [{
|
|
||||||
"width": 100,
|
|
||||||
"height": 76,
|
|
||||||
"url": "http://cdn.blinkx.com/stream/b/41/StupidVideos/20131215/1873969261/1873969261_tn_0.jpg",
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, rl):
|
|
||||||
m = re.match(self._VALID_URL, rl)
|
|
||||||
video_id = m.group('id')
|
|
||||||
display_id = video_id[:8]
|
|
||||||
|
|
||||||
api_url = (u'https://apib4.blinkx.com/api.php?action=play_video&' +
|
|
||||||
'video=%s' % video_id)
|
|
||||||
data_json = self._download_webpage(api_url, display_id)
|
|
||||||
data = json.loads(data_json)['api']['results'][0]
|
|
||||||
dt = datetime.datetime.fromtimestamp(data['pubdate_epoch'])
|
|
||||||
pload_date = dt.strftime('%Y%m%d')
|
|
||||||
|
|
||||||
duration = None
|
|
||||||
thumbnails = []
|
|
||||||
formats = []
|
|
||||||
for m in data['media']:
|
|
||||||
if m['type'] == 'jpg':
|
|
||||||
thumbnails.append({
|
|
||||||
'url': m['link'],
|
|
||||||
'width': int(m['w']),
|
|
||||||
'height': int(m['h']),
|
|
||||||
})
|
|
||||||
elif m['type'] == 'original':
|
|
||||||
duration = m['d']
|
|
||||||
elif m['type'] == 'youtube':
|
|
||||||
yt_id = m['link']
|
|
||||||
self.to_screen(u'Youtube video detected: %s' % yt_id)
|
|
||||||
return self.url_result(yt_id, 'Youtube', video_id=yt_id)
|
|
||||||
elif m['type'] in ('flv', 'mp4'):
|
|
||||||
vcodec = remove_start(m['vcodec'], 'ff')
|
|
||||||
acodec = remove_start(m['acodec'], 'ff')
|
|
||||||
tbr = (int(m['vbr']) + int(m['abr'])) // 1000
|
|
||||||
format_id = (u'%s-%sk-%s' %
|
|
||||||
(vcodec,
|
|
||||||
tbr,
|
|
||||||
m['w']))
|
|
||||||
formats.append({
|
|
||||||
'format_id': format_id,
|
|
||||||
'url': m['link'],
|
|
||||||
'vcodec': vcodec,
|
|
||||||
'acodec': acodec,
|
|
||||||
'abr': int(m['abr']) // 1000,
|
|
||||||
'vbr': int(m['vbr']) // 1000,
|
|
||||||
'tbr': tbr,
|
|
||||||
'width': int(m['w']),
|
|
||||||
'height': int(m['h']),
|
|
||||||
})
|
|
||||||
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': display_id,
|
|
||||||
'fullid': video_id,
|
|
||||||
'title': data['title'],
|
|
||||||
'formats': formats,
|
|
||||||
'uploader': data['channel_name'],
|
|
||||||
'upload_date': pload_date,
|
|
||||||
'description': data.get('description'),
|
|
||||||
'thumbnails': thumbnails,
|
|
||||||
'duration': duration,
|
|
||||||
}
|
|
||||||
@@ -1,169 +1,160 @@
|
|||||||
from __future__ import unicode_literals
|
import datetime
|
||||||
|
import json
|
||||||
|
import os
|
||||||
import re
|
import re
|
||||||
|
import socket
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from .subtitles import SubtitlesInfoExtractor
|
|
||||||
from ..utils import (
|
from ..utils import (
|
||||||
compat_urllib_request,
|
compat_http_client,
|
||||||
unescapeHTML,
|
compat_parse_qs,
|
||||||
parse_iso8601,
|
|
||||||
compat_urlparse,
|
|
||||||
clean_html,
|
|
||||||
compat_str,
|
compat_str,
|
||||||
|
compat_urllib_error,
|
||||||
|
compat_urllib_parse_urlparse,
|
||||||
|
compat_urllib_request,
|
||||||
|
|
||||||
|
ExtractorError,
|
||||||
|
unescapeHTML,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class BlipTVIE(SubtitlesInfoExtractor):
|
class BlipTVIE(InfoExtractor):
|
||||||
_VALID_URL = r'https?://(?:\w+\.)?blip\.tv/(?:(?:.+-|rss/flash/)(?P<id>\d+)|((?:play/|api\.swf#)(?P<lookup_id>[\da-zA-Z]+)))'
|
"""Information extractor for blip.tv"""
|
||||||
|
|
||||||
_TESTS = [
|
_VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
|
||||||
{
|
_URL_EXT = r'^.*\.([a-z0-9]+)$'
|
||||||
'url': 'http://blip.tv/cbr/cbr-exclusive-gotham-city-imposters-bats-vs-jokerz-short-3-5796352',
|
IE_NAME = u'blip.tv'
|
||||||
'md5': 'c6934ad0b6acf2bd920720ec888eb812',
|
_TEST = {
|
||||||
'info_dict': {
|
u'url': u'http://blip.tv/cbr/cbr-exclusive-gotham-city-imposters-bats-vs-jokerz-short-3-5796352',
|
||||||
'id': '5779306',
|
u'file': u'5779306.m4v',
|
||||||
'ext': 'mov',
|
u'md5': u'80baf1ec5c3d2019037c1c707d676b9f',
|
||||||
'title': 'CBR EXCLUSIVE: "Gotham City Imposters" Bats VS Jokerz Short 3',
|
u'info_dict': {
|
||||||
'description': 'md5:9bc31f227219cde65e47eeec8d2dc596',
|
u"upload_date": u"20111205",
|
||||||
'timestamp': 1323138843,
|
u"description": u"md5:9bc31f227219cde65e47eeec8d2dc596",
|
||||||
'upload_date': '20111206',
|
u"uploader": u"Comic Book Resources - CBR TV",
|
||||||
'uploader': 'cbr',
|
u"title": u"CBR EXCLUSIVE: \"Gotham City Imposters\" Bats VS Jokerz Short 3"
|
||||||
'uploader_id': '679425',
|
|
||||||
'duration': 81,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
# https://github.com/rg3/youtube-dl/pull/2274
|
|
||||||
'note': 'Video with subtitles',
|
|
||||||
'url': 'http://blip.tv/play/h6Uag5OEVgI.html',
|
|
||||||
'md5': '309f9d25b820b086ca163ffac8031806',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '6586561',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Red vs. Blue Season 11 Episode 1',
|
|
||||||
'description': 'One-Zero-One',
|
|
||||||
'timestamp': 1371261608,
|
|
||||||
'upload_date': '20130615',
|
|
||||||
'uploader': 'redvsblue',
|
|
||||||
'uploader_id': '792887',
|
|
||||||
'duration': 279,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
]
|
}
|
||||||
|
|
||||||
|
def report_direct_download(self, title):
|
||||||
|
"""Report information extraction."""
|
||||||
|
self.to_screen(u'%s: Direct download detected' % title)
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
lookup_id = mobj.group('lookup_id')
|
if mobj is None:
|
||||||
|
raise ExtractorError(u'Invalid URL: %s' % url)
|
||||||
|
|
||||||
# See https://github.com/rg3/youtube-dl/issues/857
|
# See https://github.com/rg3/youtube-dl/issues/857
|
||||||
if lookup_id:
|
api_mobj = re.match(r'http://a\.blip\.tv/api\.swf#(?P<video_id>[\d\w]+)', url)
|
||||||
info_page = self._download_webpage(
|
if api_mobj is not None:
|
||||||
'http://blip.tv/play/%s.x?p=1' % lookup_id, lookup_id, 'Resolving lookup id')
|
url = 'http://blip.tv/play/g_%s' % api_mobj.group('video_id')
|
||||||
video_id = self._search_regex(r'data-episode-id="([0-9]+)', info_page, 'video_id')
|
urlp = compat_urllib_parse_urlparse(url)
|
||||||
|
if urlp.path.startswith('/play/'):
|
||||||
|
request = compat_urllib_request.Request(url)
|
||||||
|
response = compat_urllib_request.urlopen(request)
|
||||||
|
redirecturl = response.geturl()
|
||||||
|
rurlp = compat_urllib_parse_urlparse(redirecturl)
|
||||||
|
file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
|
||||||
|
url = 'http://blip.tv/a/a-' + file_id
|
||||||
|
return self._real_extract(url)
|
||||||
|
|
||||||
|
|
||||||
|
if '?' in url:
|
||||||
|
cchar = '&'
|
||||||
else:
|
else:
|
||||||
video_id = mobj.group('id')
|
cchar = '?'
|
||||||
|
json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
|
||||||
rss = self._download_xml('http://blip.tv/rss/flash/%s' % video_id, video_id, 'Downloading video RSS')
|
request = compat_urllib_request.Request(json_url)
|
||||||
|
request.add_header('User-Agent', 'iTunes/10.6.1')
|
||||||
def blip(s):
|
self.report_extraction(mobj.group(1))
|
||||||
return '{http://blip.tv/dtd/blip/1.0}%s' % s
|
info = None
|
||||||
|
try:
|
||||||
def media(s):
|
urlh = compat_urllib_request.urlopen(request)
|
||||||
return '{http://search.yahoo.com/mrss/}%s' % s
|
if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
|
||||||
|
basename = url.split('/')[-1]
|
||||||
def itunes(s):
|
title,ext = os.path.splitext(basename)
|
||||||
return '{http://www.itunes.com/dtds/podcast-1.0.dtd}%s' % s
|
title = title.decode('UTF-8')
|
||||||
|
ext = ext.replace('.', '')
|
||||||
item = rss.find('channel/item')
|
self.report_direct_download(title)
|
||||||
|
info = {
|
||||||
video_id = item.find(blip('item_id')).text
|
'id': title,
|
||||||
title = item.find('./title').text
|
'url': url,
|
||||||
description = clean_html(compat_str(item.find(blip('puredescription')).text))
|
'uploader': None,
|
||||||
timestamp = parse_iso8601(item.find(blip('datestamp')).text)
|
'upload_date': None,
|
||||||
uploader = item.find(blip('user')).text
|
'title': title,
|
||||||
uploader_id = item.find(blip('userid')).text
|
'ext': ext,
|
||||||
duration = int(item.find(blip('runtime')).text)
|
'urlhandle': urlh
|
||||||
media_thumbnail = item.find(media('thumbnail'))
|
|
||||||
thumbnail = media_thumbnail.get('url') if media_thumbnail is not None else item.find(itunes('image')).text
|
|
||||||
categories = [category.text for category in item.findall('category')]
|
|
||||||
|
|
||||||
formats = []
|
|
||||||
subtitles = {}
|
|
||||||
|
|
||||||
media_group = item.find(media('group'))
|
|
||||||
for media_content in media_group.findall(media('content')):
|
|
||||||
url = media_content.get('url')
|
|
||||||
role = media_content.get(blip('role'))
|
|
||||||
msg = self._download_webpage(
|
|
||||||
url + '?showplayer=20140425131715&referrer=http://blip.tv&mask=7&skin=flashvars&view=url',
|
|
||||||
video_id, 'Resolving URL for %s' % role)
|
|
||||||
real_url = compat_urlparse.parse_qs(msg)['message'][0]
|
|
||||||
|
|
||||||
media_type = media_content.get('type')
|
|
||||||
if media_type == 'text/srt' or url.endswith('.srt'):
|
|
||||||
LANGS = {
|
|
||||||
'english': 'en',
|
|
||||||
}
|
}
|
||||||
lang = role.rpartition('-')[-1].strip().lower()
|
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
|
||||||
langcode = LANGS.get(lang, lang)
|
raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
|
||||||
subtitles[langcode] = url
|
if info is None: # Regular URL
|
||||||
elif media_type.startswith('video/'):
|
try:
|
||||||
formats.append({
|
json_code_bytes = urlh.read()
|
||||||
'url': real_url,
|
json_code = json_code_bytes.decode('utf-8')
|
||||||
'format_id': role,
|
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
|
||||||
'format_note': media_type,
|
raise ExtractorError(u'Unable to read video info webpage: %s' % compat_str(err))
|
||||||
'vcodec': media_content.get(blip('vcodec')),
|
|
||||||
'acodec': media_content.get(blip('acodec')),
|
|
||||||
'filesize': media_content.get('filesize'),
|
|
||||||
'width': int(media_content.get('width')),
|
|
||||||
'height': int(media_content.get('height')),
|
|
||||||
})
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
# subtitles
|
try:
|
||||||
video_subtitles = self.extract_subtitles(video_id, subtitles)
|
json_data = json.loads(json_code)
|
||||||
if self._downloader.params.get('listsubtitles', False):
|
if 'Post' in json_data:
|
||||||
self._list_available_subtitles(video_id, subtitles)
|
data = json_data['Post']
|
||||||
return
|
else:
|
||||||
|
data = json_data
|
||||||
|
|
||||||
return {
|
upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
|
||||||
'id': video_id,
|
if 'additionalMedia' in data:
|
||||||
'title': title,
|
formats = sorted(data['additionalMedia'], key=lambda f: int(f['media_height']))
|
||||||
'description': description,
|
best_format = formats[-1]
|
||||||
'timestamp': timestamp,
|
video_url = best_format['url']
|
||||||
'uploader': uploader,
|
else:
|
||||||
'uploader_id': uploader_id,
|
video_url = data['media']['url']
|
||||||
'duration': duration,
|
umobj = re.match(self._URL_EXT, video_url)
|
||||||
'thumbnail': thumbnail,
|
if umobj is None:
|
||||||
'categories': categories,
|
raise ValueError('Can not determine filename extension')
|
||||||
'formats': formats,
|
ext = umobj.group(1)
|
||||||
'subtitles': video_subtitles,
|
|
||||||
}
|
|
||||||
|
|
||||||
def _download_subtitle_url(self, sub_lang, url):
|
info = {
|
||||||
# For some weird reason, blip.tv serves a video instead of subtitles
|
'id': compat_str(data['item_id']),
|
||||||
# when we request with a common UA
|
'url': video_url,
|
||||||
req = compat_urllib_request.Request(url)
|
'uploader': data['display_name'],
|
||||||
req.add_header('Youtubedl-user-agent', 'youtube-dl')
|
'upload_date': upload_date,
|
||||||
return self._download_webpage(req, None, note=False)
|
'title': data['title'],
|
||||||
|
'ext': ext,
|
||||||
|
'format': data['media']['mimeType'],
|
||||||
|
'thumbnail': data['thumbnailUrl'],
|
||||||
|
'description': data['description'],
|
||||||
|
'player_url': data['embedUrl'],
|
||||||
|
'user_agent': 'iTunes/10.6.1',
|
||||||
|
}
|
||||||
|
except (ValueError,KeyError) as err:
|
||||||
|
raise ExtractorError(u'Unable to parse video information: %s' % repr(err))
|
||||||
|
|
||||||
|
return [info]
|
||||||
|
|
||||||
|
|
||||||
class BlipTVUserIE(InfoExtractor):
|
class BlipTVUserIE(InfoExtractor):
|
||||||
|
"""Information Extractor for blip.tv users."""
|
||||||
|
|
||||||
_VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
|
_VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
|
||||||
_PAGE_SIZE = 12
|
_PAGE_SIZE = 12
|
||||||
IE_NAME = 'blip.tv:user'
|
IE_NAME = u'blip.tv:user'
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
|
# Extract username
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
|
if mobj is None:
|
||||||
|
raise ExtractorError(u'Invalid URL: %s' % url)
|
||||||
|
|
||||||
username = mobj.group(1)
|
username = mobj.group(1)
|
||||||
|
|
||||||
page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
|
page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
|
||||||
|
|
||||||
page = self._download_webpage(url, username, 'Downloading user page')
|
page = self._download_webpage(url, username, u'Downloading user page')
|
||||||
mobj = re.search(r'data-users-id="([^"]+)"', page)
|
mobj = re.search(r'data-users-id="([^"]+)"', page)
|
||||||
page_base = page_base % mobj.group(1)
|
page_base = page_base % mobj.group(1)
|
||||||
|
|
||||||
|
|
||||||
# Download video ids using BlipTV Ajax calls. Result size per
|
# Download video ids using BlipTV Ajax calls. Result size per
|
||||||
# query is limited (currently to 12 videos) so we need to query
|
# query is limited (currently to 12 videos) so we need to query
|
||||||
# page by page until there are no video ids - it means we got
|
# page by page until there are no video ids - it means we got
|
||||||
@@ -174,8 +165,8 @@ class BlipTVUserIE(InfoExtractor):
|
|||||||
|
|
||||||
while True:
|
while True:
|
||||||
url = page_base + "&page=" + str(pagenum)
|
url = page_base + "&page=" + str(pagenum)
|
||||||
page = self._download_webpage(
|
page = self._download_webpage(url, username,
|
||||||
url, username, 'Downloading video ids from page %d' % pagenum)
|
u'Downloading video ids from page %d' % pagenum)
|
||||||
|
|
||||||
# Extract video identifiers
|
# Extract video identifiers
|
||||||
ids_in_page = []
|
ids_in_page = []
|
||||||
@@ -197,6 +188,6 @@ class BlipTVUserIE(InfoExtractor):
|
|||||||
|
|
||||||
pagenum += 1
|
pagenum += 1
|
||||||
|
|
||||||
urls = ['http://blip.tv/%s' % video_id for video_id in video_ids]
|
urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
|
||||||
url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
|
url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
|
||||||
return [self.playlist_result(url_entries, playlist_title=username)]
|
return [self.playlist_result(url_entries, playlist_title = username)]
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
|
|
||||||
|
|
||||||
class BloombergIE(InfoExtractor):
|
class BloombergIE(InfoExtractor):
|
||||||
_VALID_URL = r'https?://www\.bloomberg\.com/video/(?P<name>.+?)\.html'
|
_VALID_URL = r'https?://www\.bloomberg\.com/video/(?P<name>.+?).html'
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://www.bloomberg.com/video/shah-s-presentation-on-foreign-exchange-strategies-qurhIVlJSB6hzkVi229d8g.html',
|
u'url': u'http://www.bloomberg.com/video/shah-s-presentation-on-foreign-exchange-strategies-qurhIVlJSB6hzkVi229d8g.html',
|
||||||
'md5': '7bf08858ff7c203c870e8a6190e221e5',
|
u'file': u'12bzhqZTqQHmmlA8I-i0NpzJgcG5NNYX.mp4',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'id': 'qurhIVlJSB6hzkVi229d8g',
|
u'title': u'Shah\'s Presentation on Foreign-Exchange Strategies',
|
||||||
'ext': 'flv',
|
u'description': u'md5:abc86e5236f9f0e4866c59ad36736686',
|
||||||
'title': 'Shah\'s Presentation on Foreign-Exchange Strategies',
|
},
|
||||||
'description': 'md5:0681e0d30dcdfc6abf34594961d8ea88',
|
u'params': {
|
||||||
|
# Requires ffmpeg (m3u8 manifest)
|
||||||
|
u'skip_download': True,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,16 +23,5 @@ class BloombergIE(InfoExtractor):
|
|||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
name = mobj.group('name')
|
name = mobj.group('name')
|
||||||
webpage = self._download_webpage(url, name)
|
webpage = self._download_webpage(url, name)
|
||||||
f4m_url = self._search_regex(
|
ooyala_url = self._og_search_video_url(webpage)
|
||||||
r'<source src="(https?://[^"]+\.f4m.*?)"', webpage,
|
return self.url_result(ooyala_url, ie='Ooyala')
|
||||||
'f4m url')
|
|
||||||
title = re.sub(': Video$', '', self._og_search_title(webpage))
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': name.split('-')[-1],
|
|
||||||
'title': title,
|
|
||||||
'url': f4m_url,
|
|
||||||
'ext': 'flv',
|
|
||||||
'description': self._og_search_description(webpage),
|
|
||||||
'thumbnail': self._og_search_thumbnail(webpage),
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
# coding: utf-8
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import (
|
|
||||||
ExtractorError,
|
|
||||||
int_or_none,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class BRIE(InfoExtractor):
|
|
||||||
IE_DESC = 'Bayerischer Rundfunk Mediathek'
|
|
||||||
_VALID_URL = r'https?://(?:www\.)?br\.de/(?:[a-z0-9\-]+/)+(?P<id>[a-z0-9\-]+)\.html'
|
|
||||||
_BASE_URL = 'http://www.br.de'
|
|
||||||
|
|
||||||
_TESTS = [
|
|
||||||
{
|
|
||||||
'url': 'http://www.br.de/mediathek/video/anselm-gruen-114.html',
|
|
||||||
'md5': 'c4f83cf0f023ba5875aba0bf46860df2',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '2c8d81c5-6fb7-4a74-88d4-e768e5856532',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Feiern und Verzichten',
|
|
||||||
'description': 'Anselm Grün: Feiern und Verzichten',
|
|
||||||
'uploader': 'BR/Birgit Baier',
|
|
||||||
'upload_date': '20140301',
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://www.br.de/mediathek/video/sendungen/unter-unserem-himmel/unter-unserem-himmel-alpen-ueber-den-pass-100.html',
|
|
||||||
'md5': 'ab451b09d861dbed7d7cc9ab0be19ebe',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '2c060e69-3a27-4e13-b0f0-668fac17d812',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Über den Pass',
|
|
||||||
'description': 'Die Eroberung der Alpen: Über den Pass',
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://www.br.de/nachrichten/schaeuble-haushaltsentwurf-bundestag-100.html',
|
|
||||||
'md5': '3db0df1a9a9cd9fa0c70e6ea8aa8e820',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'c6aae3de-2cf9-43f2-957f-f17fef9afaab',
|
|
||||||
'ext': 'aac',
|
|
||||||
'title': '"Keine neuen Schulden im nächsten Jahr"',
|
|
||||||
'description': 'Haushaltsentwurf: "Keine neuen Schulden im nächsten Jahr"',
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://www.br.de/radio/bayern1/service/team/videos/team-video-erdelt100.html',
|
|
||||||
'md5': 'dbab0aef2e047060ea7a21fc1ce1078a',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '6ba73750-d405-45d3-861d-1ce8c524e059',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Umweltbewusster Häuslebauer',
|
|
||||||
'description': 'Uwe Erdelt: Umweltbewusster Häuslebauer',
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://www.br.de/fernsehen/br-alpha/sendungen/kant-fuer-anfaenger/kritik-der-reinen-vernunft/kant-kritik-01-metaphysik100.html',
|
|
||||||
'md5': '23bca295f1650d698f94fc570977dae3',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'd982c9ce-8648-4753-b358-98abb8aec43d',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Folge 1 - Metaphysik',
|
|
||||||
'description': 'Kant für Anfänger: Folge 1 - Metaphysik',
|
|
||||||
'uploader': 'Eva Maria Steimle',
|
|
||||||
'upload_date': '20140117',
|
|
||||||
}
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
display_id = mobj.group('id')
|
|
||||||
page = self._download_webpage(url, display_id)
|
|
||||||
xml_url = self._search_regex(
|
|
||||||
r"return BRavFramework\.register\(BRavFramework\('avPlayer_(?:[a-f0-9-]{36})'\)\.setup\({dataURL:'(/(?:[a-z0-9\-]+/)+[a-z0-9/~_.-]+)'}\)\);", page, 'XMLURL')
|
|
||||||
xml = self._download_xml(self._BASE_URL + xml_url, None)
|
|
||||||
|
|
||||||
medias = []
|
|
||||||
|
|
||||||
for xml_media in xml.findall('video') + xml.findall('audio'):
|
|
||||||
media = {
|
|
||||||
'id': xml_media.get('externalId'),
|
|
||||||
'title': xml_media.find('title').text,
|
|
||||||
'formats': self._extract_formats(xml_media.find('assets')),
|
|
||||||
'thumbnails': self._extract_thumbnails(xml_media.find('teaserImage/variants')),
|
|
||||||
'description': ' '.join(xml_media.find('shareTitle').text.splitlines()),
|
|
||||||
'webpage_url': xml_media.find('permalink').text
|
|
||||||
}
|
|
||||||
if xml_media.find('author').text:
|
|
||||||
media['uploader'] = xml_media.find('author').text
|
|
||||||
if xml_media.find('broadcastDate').text:
|
|
||||||
media['upload_date'] = ''.join(reversed(xml_media.find('broadcastDate').text.split('.')))
|
|
||||||
medias.append(media)
|
|
||||||
|
|
||||||
if len(medias) > 1:
|
|
||||||
self._downloader.report_warning(
|
|
||||||
'found multiple medias; please '
|
|
||||||
'report this with the video URL to http://yt-dl.org/bug')
|
|
||||||
if not medias:
|
|
||||||
raise ExtractorError('No media entries found')
|
|
||||||
return medias[0]
|
|
||||||
|
|
||||||
def _extract_formats(self, assets):
|
|
||||||
|
|
||||||
def text_or_none(asset, tag):
|
|
||||||
elem = asset.find(tag)
|
|
||||||
return None if elem is None else elem.text
|
|
||||||
|
|
||||||
formats = [{
|
|
||||||
'url': text_or_none(asset, 'downloadUrl'),
|
|
||||||
'ext': text_or_none(asset, 'mediaType'),
|
|
||||||
'format_id': asset.get('type'),
|
|
||||||
'width': int_or_none(text_or_none(asset, 'frameWidth')),
|
|
||||||
'height': int_or_none(text_or_none(asset, 'frameHeight')),
|
|
||||||
'tbr': int_or_none(text_or_none(asset, 'bitrateVideo')),
|
|
||||||
'abr': int_or_none(text_or_none(asset, 'bitrateAudio')),
|
|
||||||
'vcodec': text_or_none(asset, 'codecVideo'),
|
|
||||||
'acodec': text_or_none(asset, 'codecAudio'),
|
|
||||||
'container': text_or_none(asset, 'mediaType'),
|
|
||||||
'filesize': int_or_none(text_or_none(asset, 'size')),
|
|
||||||
} for asset in assets.findall('asset')
|
|
||||||
if asset.find('downloadUrl') is not None]
|
|
||||||
|
|
||||||
self._sort_formats(formats)
|
|
||||||
return formats
|
|
||||||
|
|
||||||
def _extract_thumbnails(self, variants):
|
|
||||||
thumbnails = [{
|
|
||||||
'url': self._BASE_URL + variant.find('url').text,
|
|
||||||
'width': int_or_none(variant.find('width').text),
|
|
||||||
'height': int_or_none(variant.find('height').text),
|
|
||||||
} for variant in variants.findall('variant')]
|
|
||||||
thumbnails.sort(key=lambda x: x['width'] * x['height'], reverse=True)
|
|
||||||
return thumbnails
|
|
||||||
@@ -1,20 +1,18 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
|
from ..utils import determine_ext
|
||||||
|
|
||||||
|
|
||||||
class BreakIE(InfoExtractor):
|
class BreakIE(InfoExtractor):
|
||||||
_VALID_URL = r'http://(?:www\.)?break\.com/video/([^/]+)'
|
_VALID_URL = r'(?:http://)?(?:www\.)?break\.com/video/([^/]+)'
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://www.break.com/video/when-girls-act-like-guys-2468056',
|
u'url': u'http://www.break.com/video/when-girls-act-like-guys-2468056',
|
||||||
'md5': 'a3513fb1547fba4fb6cfac1bffc6c46b',
|
u'file': u'2468056.mp4',
|
||||||
'info_dict': {
|
u'md5': u'a3513fb1547fba4fb6cfac1bffc6c46b',
|
||||||
'id': '2468056',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u"title": u"When Girls Act Like D-Bags"
|
||||||
'title': 'When Girls Act Like D-Bags',
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,18 +21,18 @@ class BreakIE(InfoExtractor):
|
|||||||
video_id = mobj.group(1).split("-")[-1]
|
video_id = mobj.group(1).split("-")[-1]
|
||||||
embed_url = 'http://www.break.com/embed/%s' % video_id
|
embed_url = 'http://www.break.com/embed/%s' % video_id
|
||||||
webpage = self._download_webpage(embed_url, video_id)
|
webpage = self._download_webpage(embed_url, video_id)
|
||||||
info_json = self._search_regex(r'var embedVars = ({.*})\s*?</script>',
|
info_json = self._search_regex(r'var embedVars = ({.*?});', webpage,
|
||||||
webpage, 'info json', flags=re.DOTALL)
|
u'info json', flags=re.DOTALL)
|
||||||
info = json.loads(info_json)
|
info = json.loads(info_json)
|
||||||
video_url = info['videoUri']
|
video_url = info['videoUri']
|
||||||
youtube_id = info.get('youtubeId')
|
m_youtube = re.search(r'(https?://www\.youtube\.com/watch\?v=.*)', video_url)
|
||||||
if youtube_id:
|
if m_youtube is not None:
|
||||||
return self.url_result(youtube_id, 'Youtube')
|
return self.url_result(m_youtube.group(1), 'Youtube')
|
||||||
|
|
||||||
final_url = video_url + '?' + info['AuthToken']
|
final_url = video_url + '?' + info['AuthToken']
|
||||||
return {
|
return [{
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
'url': final_url,
|
'url': final_url,
|
||||||
'title': info['contentName'],
|
'ext': determine_ext(final_url),
|
||||||
|
'title': info['contentName'],
|
||||||
'thumbnail': info['thumbUri'],
|
'thumbnail': info['thumbUri'],
|
||||||
}
|
}]
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
# encoding: utf-8
|
# encoding: utf-8
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
@@ -9,68 +8,53 @@ from .common import InfoExtractor
|
|||||||
from ..utils import (
|
from ..utils import (
|
||||||
compat_urllib_parse,
|
compat_urllib_parse,
|
||||||
find_xpath_attr,
|
find_xpath_attr,
|
||||||
fix_xml_ampersands,
|
|
||||||
compat_urlparse,
|
compat_urlparse,
|
||||||
compat_str,
|
compat_str,
|
||||||
compat_urllib_request,
|
compat_urllib_request,
|
||||||
compat_parse_qs,
|
|
||||||
|
|
||||||
ExtractorError,
|
ExtractorError,
|
||||||
unsmuggle_url,
|
|
||||||
unescapeHTML,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class BrightcoveIE(InfoExtractor):
|
class BrightcoveIE(InfoExtractor):
|
||||||
_VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*\?(?P<query>.*)'
|
_VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*\?(?P<query>.*)'
|
||||||
_FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
|
_FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
|
||||||
|
_PLAYLIST_URL_TEMPLATE = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s'
|
||||||
|
|
||||||
_TESTS = [
|
_TESTS = [
|
||||||
{
|
{
|
||||||
# From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
|
# From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
|
||||||
'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
|
u'url': u'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
|
||||||
'file': '2371591881001.mp4',
|
u'file': u'2371591881001.mp4',
|
||||||
'md5': '5423e113865d26e40624dce2e4b45d95',
|
u'md5': u'8eccab865181d29ec2958f32a6a754f5',
|
||||||
'note': 'Test Brightcove downloads and detection in GenericIE',
|
u'note': u'Test Brightcove downloads and detection in GenericIE',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
|
u'title': u'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
|
||||||
'uploader': '8TV',
|
u'uploader': u'8TV',
|
||||||
'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
|
u'description': u'md5:a950cc4285c43e44d763d036710cd9cd',
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
# From http://medianetwork.oracle.com/video/player/1785452137001
|
# From http://medianetwork.oracle.com/video/player/1785452137001
|
||||||
'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
|
u'url': u'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
|
||||||
'file': '1785452137001.flv',
|
u'file': u'1785452137001.flv',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
|
u'title': u'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
|
||||||
'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
|
u'description': u'John Rose speaks at the JVM Language Summit, August 1, 2012.',
|
||||||
'uploader': 'Oracle',
|
u'uploader': u'Oracle',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
# From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
|
# From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
|
||||||
'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
|
u'url': u'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'id': '2750934548001',
|
u'id': u'2750934548001',
|
||||||
'ext': 'mp4',
|
u'ext': u'mp4',
|
||||||
'title': 'This Bracelet Acts as a Personal Thermostat',
|
u'title': u'This Bracelet Acts as a Personal Thermostat',
|
||||||
'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
|
u'description': u'md5:547b78c64f4112766ccf4e151c20b6a0',
|
||||||
'uploader': 'Mashable',
|
u'uploader': u'Mashable',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
|
||||||
# test that the default referer works
|
|
||||||
# from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
|
|
||||||
'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '2878862109001',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Lost in Motion II',
|
|
||||||
'description': 'md5:363109c02998fee92ec02211bd8000df',
|
|
||||||
'uploader': 'National Ballet of Canada',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -84,34 +68,18 @@ class BrightcoveIE(InfoExtractor):
|
|||||||
object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
|
object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
|
||||||
lambda m: m.group(1) + '/>', object_str)
|
lambda m: m.group(1) + '/>', object_str)
|
||||||
# Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
|
# Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
|
||||||
object_str = object_str.replace('<--', '<!--')
|
object_str = object_str.replace(u'<--', u'<!--')
|
||||||
object_str = fix_xml_ampersands(object_str)
|
|
||||||
|
|
||||||
object_doc = xml.etree.ElementTree.fromstring(object_str.encode('utf-8'))
|
|
||||||
|
|
||||||
fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
|
|
||||||
if fv_el is not None:
|
|
||||||
flashvars = dict(
|
|
||||||
(k, v[0])
|
|
||||||
for k, v in compat_parse_qs(fv_el.attrib['value']).items())
|
|
||||||
else:
|
|
||||||
flashvars = {}
|
|
||||||
|
|
||||||
|
object_doc = xml.etree.ElementTree.fromstring(object_str)
|
||||||
|
assert u'BrightcoveExperience' in object_doc.attrib['class']
|
||||||
|
params = {'flashID': object_doc.attrib['id'],
|
||||||
|
'playerID': find_xpath_attr(object_doc, './param', 'name', 'playerID').attrib['value'],
|
||||||
|
}
|
||||||
def find_param(name):
|
def find_param(name):
|
||||||
if name in flashvars:
|
|
||||||
return flashvars[name]
|
|
||||||
node = find_xpath_attr(object_doc, './param', 'name', name)
|
node = find_xpath_attr(object_doc, './param', 'name', name)
|
||||||
if node is not None:
|
if node is not None:
|
||||||
return node.attrib['value']
|
return node.attrib['value']
|
||||||
return None
|
return None
|
||||||
|
|
||||||
params = {}
|
|
||||||
|
|
||||||
playerID = find_param('playerID')
|
|
||||||
if playerID is None:
|
|
||||||
raise ExtractorError('Cannot find player ID')
|
|
||||||
params['playerID'] = playerID
|
|
||||||
|
|
||||||
playerKey = find_param('playerKey')
|
playerKey = find_param('playerKey')
|
||||||
# Not all pages define this value
|
# Not all pages define this value
|
||||||
if playerKey is not None:
|
if playerKey is not None:
|
||||||
@@ -128,36 +96,18 @@ class BrightcoveIE(InfoExtractor):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _extract_brightcove_url(cls, webpage):
|
def _extract_brightcove_url(cls, webpage):
|
||||||
"""Try to extract the brightcove url from the webpage, returns None
|
"""Try to extract the brightcove url from the wepbage, returns None
|
||||||
if it can't be found
|
if it can't be found
|
||||||
"""
|
"""
|
||||||
urls = cls._extract_brightcove_urls(webpage)
|
m_brightcove = re.search(
|
||||||
return urls[0] if urls else None
|
r'<object[^>]+?class=([\'"])[^>]*?BrightcoveExperience.*?\1.+?</object>',
|
||||||
|
webpage, re.DOTALL)
|
||||||
@classmethod
|
if m_brightcove is not None:
|
||||||
def _extract_brightcove_urls(cls, webpage):
|
return cls._build_brighcove_url(m_brightcove.group())
|
||||||
"""Return a list of all Brightcove URLs from the webpage """
|
else:
|
||||||
|
return None
|
||||||
url_m = re.search(r'<meta\s+property="og:video"\s+content="(http://c.brightcove.com/[^"]+)"', webpage)
|
|
||||||
if url_m:
|
|
||||||
url = unescapeHTML(url_m.group(1))
|
|
||||||
# Some sites don't add it, we can't download with this url, for example:
|
|
||||||
# http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
|
|
||||||
if 'playerKey' in url:
|
|
||||||
return [url]
|
|
||||||
|
|
||||||
matches = re.findall(
|
|
||||||
r'''(?sx)<object
|
|
||||||
(?:
|
|
||||||
[^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
|
|
||||||
[^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
|
|
||||||
).+?</object>''',
|
|
||||||
webpage)
|
|
||||||
return [cls._build_brighcove_url(m) for m in matches]
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
url, smuggled_data = unsmuggle_url(url, {})
|
|
||||||
|
|
||||||
# Change the 'videoId' and others field to '@videoPlayer'
|
# Change the 'videoId' and others field to '@videoPlayer'
|
||||||
url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
|
url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
|
||||||
# Change bckey (used by bcove.me urls) to playerKey
|
# Change bckey (used by bcove.me urls) to playerKey
|
||||||
@@ -168,40 +118,33 @@ class BrightcoveIE(InfoExtractor):
|
|||||||
|
|
||||||
videoPlayer = query.get('@videoPlayer')
|
videoPlayer = query.get('@videoPlayer')
|
||||||
if videoPlayer:
|
if videoPlayer:
|
||||||
# We set the original url as the default 'Referer' header
|
return self._get_video_info(videoPlayer[0], query_str, query)
|
||||||
referer = smuggled_data.get('Referer', url)
|
|
||||||
return self._get_video_info(
|
|
||||||
videoPlayer[0], query_str, query, referer=referer)
|
|
||||||
else:
|
else:
|
||||||
player_key = query['playerKey']
|
player_key = query['playerKey']
|
||||||
return self._get_playlist_info(player_key[0])
|
return self._get_playlist_info(player_key[0])
|
||||||
|
|
||||||
def _get_video_info(self, video_id, query_str, query, referer=None):
|
def _get_video_info(self, video_id, query_str, query):
|
||||||
request_url = self._FEDERATED_URL_TEMPLATE % query_str
|
request_url = self._FEDERATED_URL_TEMPLATE % query_str
|
||||||
req = compat_urllib_request.Request(request_url)
|
req = compat_urllib_request.Request(request_url)
|
||||||
linkBase = query.get('linkBaseURL')
|
linkBase = query.get('linkBaseURL')
|
||||||
if linkBase is not None:
|
if linkBase is not None:
|
||||||
referer = linkBase[0]
|
req.add_header('Referer', linkBase[0])
|
||||||
if referer is not None:
|
|
||||||
req.add_header('Referer', referer)
|
|
||||||
webpage = self._download_webpage(req, video_id)
|
webpage = self._download_webpage(req, video_id)
|
||||||
|
|
||||||
self.report_extraction(video_id)
|
self.report_extraction(video_id)
|
||||||
info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
|
info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
|
||||||
info = json.loads(info)['data']
|
info = json.loads(info)['data']
|
||||||
video_info = info['programmedContent']['videoPlayer']['mediaDTO']
|
video_info = info['programmedContent']['videoPlayer']['mediaDTO']
|
||||||
video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
|
|
||||||
|
|
||||||
return self._extract_video_info(video_info)
|
return self._extract_video_info(video_info)
|
||||||
|
|
||||||
def _get_playlist_info(self, player_key):
|
def _get_playlist_info(self, player_key):
|
||||||
info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
|
playlist_info = self._download_webpage(self._PLAYLIST_URL_TEMPLATE % player_key,
|
||||||
playlist_info = self._download_webpage(
|
player_key, u'Downloading playlist information')
|
||||||
info_url, player_key, 'Downloading playlist information')
|
|
||||||
|
|
||||||
json_data = json.loads(playlist_info)
|
json_data = json.loads(playlist_info)
|
||||||
if 'videoList' not in json_data:
|
if 'videoList' not in json_data:
|
||||||
raise ExtractorError('Empty playlist')
|
raise ExtractorError(u'Empty playlist')
|
||||||
playlist_info = json_data['videoList']
|
playlist_info = json_data['videoList']
|
||||||
videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
|
videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
|
||||||
|
|
||||||
@@ -211,7 +154,7 @@ class BrightcoveIE(InfoExtractor):
|
|||||||
def _extract_video_info(self, video_info):
|
def _extract_video_info(self, video_info):
|
||||||
info = {
|
info = {
|
||||||
'id': compat_str(video_info['id']),
|
'id': compat_str(video_info['id']),
|
||||||
'title': video_info['displayName'].strip(),
|
'title': video_info['displayName'],
|
||||||
'description': video_info.get('shortDescription'),
|
'description': video_info.get('shortDescription'),
|
||||||
'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
|
'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
|
||||||
'uploader': video_info.get('publisherName'),
|
'uploader': video_info.get('publisherName'),
|
||||||
@@ -229,23 +172,6 @@ class BrightcoveIE(InfoExtractor):
|
|||||||
info.update({
|
info.update({
|
||||||
'url': video_info['FLVFullLengthURL'],
|
'url': video_info['FLVFullLengthURL'],
|
||||||
})
|
})
|
||||||
|
else:
|
||||||
if self._downloader.params.get('include_ads', False):
|
raise ExtractorError(u'Unable to extract video url for %s' % info['id'])
|
||||||
adServerURL = video_info.get('_youtubedl_adServerURL')
|
|
||||||
if adServerURL:
|
|
||||||
ad_info = {
|
|
||||||
'_type': 'url',
|
|
||||||
'url': adServerURL,
|
|
||||||
}
|
|
||||||
if 'url' in info:
|
|
||||||
return {
|
|
||||||
'_type': 'playlist',
|
|
||||||
'title': info['title'],
|
|
||||||
'entries': [ad_info, info],
|
|
||||||
}
|
|
||||||
else:
|
|
||||||
return ad_info
|
|
||||||
|
|
||||||
if 'url' not in info and not info.get('formats'):
|
|
||||||
raise ExtractorError('Unable to extract video url for %s' % info['id'])
|
|
||||||
return info
|
return info
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import ExtractorError
|
|
||||||
|
|
||||||
|
|
||||||
class BYUtvIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'^https?://(?:www\.)?byutv.org/watch/[0-9a-f-]+/(?P<video_id>[^/?#]+)'
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.byutv.org/watch/44e80f7b-e3ba-43ba-8c51-b1fd96c94a79/granite-flats-talking',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'granite-flats-talking',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'description': 'md5:4e9a7ce60f209a33eca0ac65b4918e1c',
|
|
||||||
'title': 'Talking',
|
|
||||||
'thumbnail': 're:^https?://.*promo.*'
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
'skip_download': True,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('video_id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
episode_code = self._search_regex(
|
|
||||||
r'(?s)episode:(.*?\}),\s*\n', webpage, 'episode information')
|
|
||||||
episode_json = re.sub(
|
|
||||||
r'(\n\s+)([a-zA-Z]+):\s+\'(.*?)\'', r'\1"\2": "\3"', episode_code)
|
|
||||||
ep = json.loads(episode_json)
|
|
||||||
|
|
||||||
if ep['providerType'] == 'Ooyala':
|
|
||||||
return {
|
|
||||||
'_type': 'url_transparent',
|
|
||||||
'ie_key': 'Ooyala',
|
|
||||||
'url': 'ooyala:%s' % ep['providerId'],
|
|
||||||
'id': video_id,
|
|
||||||
'title': ep['title'],
|
|
||||||
'description': ep.get('description'),
|
|
||||||
'thumbnail': ep.get('imageThumbnail'),
|
|
||||||
}
|
|
||||||
else:
|
|
||||||
raise ExtractorError('Unsupported provider %s' % ep['provider'])
|
|
||||||
@@ -1,47 +1,36 @@
|
|||||||
# coding: utf-8
|
# coding: utf-8
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import json
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
|
from ..utils import determine_ext
|
||||||
|
|
||||||
class C56IE(InfoExtractor):
|
class C56IE(InfoExtractor):
|
||||||
_VALID_URL = r'https?://(?:(?:www|player)\.)?56\.com/(?:.+?/)?(?:v_|(?:play_album.+-))(?P<textid>.+?)\.(?:html|swf)'
|
_VALID_URL = r'https?://((www|player)\.)?56\.com/(.+?/)?(v_|(play_album.+-))(?P<textid>.+?)\.(html|swf)'
|
||||||
IE_NAME = '56.com'
|
IE_NAME = u'56.com'
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.56.com/u39/v_OTM0NDA3MTY.html',
|
_TEST ={
|
||||||
'md5': 'e59995ac63d0457783ea05f93f12a866',
|
u'url': u'http://www.56.com/u39/v_OTM0NDA3MTY.html',
|
||||||
'info_dict': {
|
u'file': u'93440716.flv',
|
||||||
'id': '93440716',
|
u'md5': u'e59995ac63d0457783ea05f93f12a866',
|
||||||
'ext': 'flv',
|
u'info_dict': {
|
||||||
'title': '网事知多少 第32期:车怒',
|
u'title': u'网事知多少 第32期:车怒',
|
||||||
'duration': 283.813,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
|
mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
|
||||||
text_id = mobj.group('textid')
|
text_id = mobj.group('textid')
|
||||||
|
info_page = self._download_webpage('http://vxml.56.com/json/%s/' % text_id,
|
||||||
|
text_id, u'Downloading video info')
|
||||||
|
info = json.loads(info_page)['info']
|
||||||
|
best_format = sorted(info['rfiles'], key=lambda f: int(f['filesize']))[-1]
|
||||||
|
video_url = best_format['url']
|
||||||
|
|
||||||
page = self._download_json(
|
return {'id': info['vid'],
|
||||||
'http://vxml.56.com/json/%s/' % text_id, text_id, 'Downloading video info')
|
'title': info['Subject'],
|
||||||
|
'url': video_url,
|
||||||
info = page['info']
|
'ext': determine_ext(video_url),
|
||||||
|
'thumbnail': info.get('bimg') or info.get('img'),
|
||||||
formats = [
|
}
|
||||||
{
|
|
||||||
'format_id': f['type'],
|
|
||||||
'filesize': int(f['filesize']),
|
|
||||||
'url': f['url']
|
|
||||||
} for f in info['rfiles']
|
|
||||||
]
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': info['vid'],
|
|
||||||
'title': info['Subject'],
|
|
||||||
'duration': int(info['duration']) / 1000.0,
|
|
||||||
'formats': formats,
|
|
||||||
'thumbnail': info.get('bimg') or info.get('img'),
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
# coding: utf-8
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
|
|
||||||
|
|
||||||
class Canal13clIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'^http://(?:www\.)?13\.cl/(?:[^/?#]+/)*(?P<id>[^/?#]+)'
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.13.cl/t13/nacional/el-circulo-de-hierro-de-michelle-bachelet-en-su-regreso-a-la-moneda',
|
|
||||||
'md5': '4cb1fa38adcad8fea88487a078831755',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '1403022125',
|
|
||||||
'display_id': 'el-circulo-de-hierro-de-michelle-bachelet-en-su-regreso-a-la-moneda',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'El "círculo de hierro" de Michelle Bachelet en su regreso a La Moneda',
|
|
||||||
'description': '(Foto: Agencia Uno) En nueve días más, Michelle Bachelet va a asumir por segunda vez como presidenta de la República. Entre aquellos que la acompañarán hay caras que se repiten y otras que se consolidan en su entorno de colaboradores más cercanos.',
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
display_id = mobj.group('id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, display_id)
|
|
||||||
|
|
||||||
title = self._html_search_meta(
|
|
||||||
'twitter:title', webpage, 'title', fatal=True)
|
|
||||||
description = self._html_search_meta(
|
|
||||||
'twitter:description', webpage, 'description')
|
|
||||||
url = self._html_search_regex(
|
|
||||||
r'articuloVideo = \"(.*?)\"', webpage, 'url')
|
|
||||||
real_id = self._search_regex(
|
|
||||||
r'[^0-9]([0-9]{7,})[^0-9]', url, 'id', default=display_id)
|
|
||||||
thumbnail = self._html_search_regex(
|
|
||||||
r'articuloImagen = \"(.*?)\"', webpage, 'thumbnail')
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': real_id,
|
|
||||||
'display_id': display_id,
|
|
||||||
'url': url,
|
|
||||||
'title': title,
|
|
||||||
'description': description,
|
|
||||||
'ext': 'mp4',
|
|
||||||
'thumbnail': thumbnail,
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
# coding: utf-8
|
# coding: utf-8
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
@@ -11,12 +9,11 @@ class Canalc2IE(InfoExtractor):
|
|||||||
_VALID_URL = r'http://.*?\.canalc2\.tv/video\.asp\?.*?idVideo=(?P<id>\d+)'
|
_VALID_URL = r'http://.*?\.canalc2\.tv/video\.asp\?.*?idVideo=(?P<id>\d+)'
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://www.canalc2.tv/video.asp?idVideo=12163&voir=oui',
|
u'url': u'http://www.canalc2.tv/video.asp?idVideo=12163&voir=oui',
|
||||||
'md5': '060158428b650f896c542dfbb3d6487f',
|
u'file': u'12163.mp4',
|
||||||
'info_dict': {
|
u'md5': u'060158428b650f896c542dfbb3d6487f',
|
||||||
'id': '12163',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u'title': u'Terrasses du Numérique'
|
||||||
'title': 'Terrasses du Numérique'
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,11 +28,10 @@ class Canalc2IE(InfoExtractor):
|
|||||||
video_url = 'http://vod-flash.u-strasbg.fr:8080/' + file_name
|
video_url = 'http://vod-flash.u-strasbg.fr:8080/' + file_name
|
||||||
|
|
||||||
title = self._html_search_regex(
|
title = self._html_search_regex(
|
||||||
r'class="evenement8">(.*?)</a>', webpage, 'title')
|
r'class="evenement8">(.*?)</a>', webpage, u'title')
|
||||||
|
|
||||||
return {
|
return {'id': video_id,
|
||||||
'id': video_id,
|
'ext': 'mp4',
|
||||||
'ext': 'mp4',
|
'url': video_url,
|
||||||
'url': video_url,
|
'title': title,
|
||||||
'title': title,
|
}
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,72 +1,55 @@
|
|||||||
# encoding: utf-8
|
# encoding: utf-8
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import xml.etree.ElementTree
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import (
|
from ..utils import unified_strdate
|
||||||
unified_strdate,
|
|
||||||
url_basename,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class CanalplusIE(InfoExtractor):
|
class CanalplusIE(InfoExtractor):
|
||||||
_VALID_URL = r'https?://(?:www\.canalplus\.fr/.*?/(?P<path>.*)|player\.canalplus\.fr/#/(?P<id>[0-9]+))'
|
_VALID_URL = r'https?://(www\.canalplus\.fr/.*?/(?P<path>.*)|player\.canalplus\.fr/#/(?P<id>\d+))'
|
||||||
_VIDEO_INFO_TEMPLATE = 'http://service.canal-plus.com/video/rest/getVideosLiees/cplus/%s'
|
_VIDEO_INFO_TEMPLATE = 'http://service.canal-plus.com/video/rest/getVideosLiees/cplus/%s'
|
||||||
IE_NAME = 'canalplus.fr'
|
IE_NAME = u'canalplus.fr'
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://www.canalplus.fr/c-infos-documentaires/pid1830-c-zapping.html?vid=922470',
|
u'url': u'http://www.canalplus.fr/c-infos-documentaires/pid1830-c-zapping.html?vid=922470',
|
||||||
'md5': '3db39fb48b9685438ecf33a1078023e4',
|
u'file': u'922470.flv',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'id': '922470',
|
u'title': u'Zapping - 26/08/13',
|
||||||
'ext': 'flv',
|
u'description': u'Le meilleur de toutes les chaînes, tous les jours.\nEmission du 26 août 2013',
|
||||||
'title': 'Zapping - 26/08/13',
|
u'upload_date': u'20130826',
|
||||||
'description': 'Le meilleur de toutes les chaînes, tous les jours.\nEmission du 26 août 2013',
|
},
|
||||||
'upload_date': '20130826',
|
u'params': {
|
||||||
|
u'skip_download': True,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
video_id = mobj.groupdict().get('id')
|
video_id = mobj.groupdict().get('id')
|
||||||
|
|
||||||
# Beware, some subclasses do not define an id group
|
|
||||||
display_id = url_basename(mobj.group('path'))
|
|
||||||
|
|
||||||
if video_id is None:
|
if video_id is None:
|
||||||
webpage = self._download_webpage(url, display_id)
|
webpage = self._download_webpage(url, mobj.group('path'))
|
||||||
video_id = self._search_regex(r'<canal:player videoId="(\d+)"', webpage, 'video id')
|
video_id = self._search_regex(r'videoId = "(\d+)";', webpage, u'video id')
|
||||||
|
|
||||||
info_url = self._VIDEO_INFO_TEMPLATE % video_id
|
info_url = self._VIDEO_INFO_TEMPLATE % video_id
|
||||||
doc = self._download_xml(info_url, video_id, 'Downloading video XML')
|
info_page = self._download_webpage(info_url,video_id,
|
||||||
|
u'Downloading video info')
|
||||||
|
|
||||||
|
self.report_extraction(video_id)
|
||||||
|
doc = xml.etree.ElementTree.fromstring(info_page.encode('utf-8'))
|
||||||
video_info = [video for video in doc if video.find('ID').text == video_id][0]
|
video_info = [video for video in doc if video.find('ID').text == video_id][0]
|
||||||
media = video_info.find('MEDIA')
|
|
||||||
infos = video_info.find('INFOS')
|
infos = video_info.find('INFOS')
|
||||||
|
media = video_info.find('MEDIA')
|
||||||
|
formats = [media.find('VIDEOS/%s' % format)
|
||||||
|
for format in ['BAS_DEBIT', 'HAUT_DEBIT', 'HD']]
|
||||||
|
video_url = [format.text for format in formats if format is not None][-1]
|
||||||
|
|
||||||
preferences = ['MOBILE', 'BAS_DEBIT', 'HAUT_DEBIT', 'HD', 'HLS', 'HDS']
|
return {'id': video_id,
|
||||||
|
'title': u'%s - %s' % (infos.find('TITRAGE/TITRE').text,
|
||||||
formats = [
|
infos.find('TITRAGE/SOUS_TITRE').text),
|
||||||
{
|
'url': video_url,
|
||||||
'url': fmt.text + '?hdcore=2.11.3' if fmt.tag == 'HDS' else fmt.text,
|
'ext': 'flv',
|
||||||
'format_id': fmt.tag,
|
'upload_date': unified_strdate(infos.find('PUBLICATION/DATE').text),
|
||||||
'ext': 'mp4' if fmt.tag == 'HLS' else 'flv',
|
'thumbnail': media.find('IMAGES/GRAND').text,
|
||||||
'preference': preferences.index(fmt.tag) if fmt.tag in preferences else -1,
|
'description': infos.find('DESCRIPTION').text,
|
||||||
} for fmt in media.find('VIDEOS') if fmt.text
|
'view_count': int(infos.find('NB_VUES').text),
|
||||||
]
|
}
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'display_id': display_id,
|
|
||||||
'title': '%s - %s' % (infos.find('TITRAGE/TITRE').text,
|
|
||||||
infos.find('TITRAGE/SOUS_TITRE').text),
|
|
||||||
'upload_date': unified_strdate(infos.find('PUBLICATION/DATE').text),
|
|
||||||
'thumbnail': media.find('IMAGES/GRAND').text,
|
|
||||||
'description': infos.find('DESCRIPTION').text,
|
|
||||||
'view_count': int(infos.find('NB_VUES').text),
|
|
||||||
'like_count': int(infos.find('NB_LIKES').text),
|
|
||||||
'comment_count': int(infos.find('NB_COMMENTS').text),
|
|
||||||
'formats': formats,
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
|
|
||||||
|
|
||||||
class CBSIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'https?://(?:www\.)?cbs\.com/shows/[^/]+/video/(?P<id>[^/]+)/.*'
|
|
||||||
|
|
||||||
_TEST = {
|
|
||||||
u'url': u'http://www.cbs.com/shows/garth-brooks/video/_u7W953k6la293J7EPTd9oHkSPs6Xn6_/connect-chat-feat-garth-brooks/',
|
|
||||||
u'file': u'4JUVEwq3wUT7.flv',
|
|
||||||
u'info_dict': {
|
|
||||||
u'title': u'Connect Chat feat. Garth Brooks',
|
|
||||||
u'description': u'Connect with country music singer Garth Brooks, as he chats with fans on Wednesday November 27, 2013. Be sure to tune in to Garth Brooks: Live from Las Vegas, Friday November 29, at 9/8c on CBS!',
|
|
||||||
u'duration': 1495,
|
|
||||||
},
|
|
||||||
u'params': {
|
|
||||||
# rtmp download
|
|
||||||
u'skip_download': True,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
real_id = self._search_regex(
|
|
||||||
r"video\.settings\.pid\s*=\s*'([^']+)';",
|
|
||||||
webpage, u'real video ID')
|
|
||||||
return self.url_result(u'theplatform:%s' % real_id)
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
# encoding: utf-8
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
import json
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
|
|
||||||
|
|
||||||
class CBSNewsIE(InfoExtractor):
|
|
||||||
IE_DESC = 'CBS News'
|
|
||||||
_VALID_URL = r'http://(?:www\.)?cbsnews\.com/(?:[^/]+/)+(?P<id>[\da-z_-]+)'
|
|
||||||
|
|
||||||
_TESTS = [
|
|
||||||
{
|
|
||||||
'url': 'http://www.cbsnews.com/news/tesla-and-spacex-elon-musks-industrial-empire/',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'tesla-and-spacex-elon-musks-industrial-empire',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': 'Tesla and SpaceX: Elon Musk\'s industrial empire',
|
|
||||||
'thumbnail': 'http://beta.img.cbsnews.com/i/2014/03/30/60147937-2f53-4565-ad64-1bdd6eb64679/60-0330-pelley-640x360.jpg',
|
|
||||||
'duration': 791,
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
# rtmp download
|
|
||||||
'skip_download': True,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://www.cbsnews.com/videos/fort-hood-shooting-army-downplays-mental-illness-as-cause-of-attack/',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'fort-hood-shooting-army-downplays-mental-illness-as-cause-of-attack',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': 'Fort Hood shooting: Army downplays mental illness as cause of attack',
|
|
||||||
'thumbnail': 'http://cbsnews2.cbsistatic.com/hub/i/r/2014/04/04/0c9fbc66-576b-41ca-8069-02d122060dd2/thumbnail/140x90/6dad7a502f88875ceac38202984b6d58/en-0404-werner-replace-640x360.jpg',
|
|
||||||
'duration': 205,
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
# rtmp download
|
|
||||||
'skip_download': True,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
|
|
||||||
video_info = json.loads(self._html_search_regex(
|
|
||||||
r'(?:<ul class="media-list items" id="media-related-items"><li data-video-info|<div id="cbsNewsVideoPlayer" data-video-player-options)=\'({.+?})\'',
|
|
||||||
webpage, 'video JSON info'))
|
|
||||||
|
|
||||||
item = video_info['item'] if 'item' in video_info else video_info
|
|
||||||
title = item.get('articleTitle') or item.get('hed')
|
|
||||||
duration = item.get('duration')
|
|
||||||
thumbnail = item.get('mediaImage') or item.get('thumbnail')
|
|
||||||
|
|
||||||
formats = []
|
|
||||||
for format_id in ['RtmpMobileLow', 'RtmpMobileHigh', 'Hls', 'RtmpDesktop']:
|
|
||||||
uri = item.get('media' + format_id + 'URI')
|
|
||||||
if not uri:
|
|
||||||
continue
|
|
||||||
fmt = {
|
|
||||||
'url': uri,
|
|
||||||
'format_id': format_id,
|
|
||||||
}
|
|
||||||
if uri.startswith('rtmp'):
|
|
||||||
fmt.update({
|
|
||||||
'app': 'ondemand?auth=cbs',
|
|
||||||
'play_path': 'mp4:' + uri.split('<break>')[-1],
|
|
||||||
'player_url': 'http://www.cbsnews.com/[[IMPORT]]/vidtech.cbsinteractive.com/player/3_3_0/CBSI_PLAYER_HD.swf',
|
|
||||||
'page_url': 'http://www.cbsnews.com',
|
|
||||||
'ext': 'flv',
|
|
||||||
})
|
|
||||||
elif uri.endswith('.m3u8'):
|
|
||||||
fmt['ext'] = 'mp4'
|
|
||||||
formats.append(fmt)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'title': title,
|
|
||||||
'thumbnail': thumbnail,
|
|
||||||
'duration': duration,
|
|
||||||
'formats': formats,
|
|
||||||
}
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import (
|
|
||||||
compat_urllib_request,
|
|
||||||
compat_urllib_parse,
|
|
||||||
compat_urllib_parse_urlparse,
|
|
||||||
ExtractorError,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class CeskaTelevizeIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'https?://www\.ceskatelevize\.cz/(porady|ivysilani)/(.+/)?(?P<id>[^?#]+)'
|
|
||||||
|
|
||||||
_TESTS = [
|
|
||||||
{
|
|
||||||
'url': 'http://www.ceskatelevize.cz/ivysilani/10532695142-prvni-republika/213512120230004-spanelska-chripka',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '213512120230004',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': 'První republika: Španělská chřipka',
|
|
||||||
'duration': 3107.4,
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
'skip_download': True, # requires rtmpdump
|
|
||||||
},
|
|
||||||
'skip': 'Works only from Czech Republic.',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://www.ceskatelevize.cz/ivysilani/1030584952-tsatsiki-maminka-a-policajt',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '20138143440',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': 'Tsatsiki, maminka a policajt',
|
|
||||||
'duration': 6754.1,
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
'skip_download': True, # requires rtmpdump
|
|
||||||
},
|
|
||||||
'skip': 'Works only from Czech Republic.',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://www.ceskatelevize.cz/ivysilani/10532695142-prvni-republika/bonus/14716-zpevacka-z-duparny-bobina',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '14716',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': 'První republika: Zpěvačka z Dupárny Bobina',
|
|
||||||
'duration': 90,
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
'skip_download': True, # requires rtmpdump
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
url = url.replace('/porady/', '/ivysilani/').replace('/video/', '')
|
|
||||||
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
|
|
||||||
NOT_AVAILABLE_STRING = 'This content is not available at your territory due to limited copyright.'
|
|
||||||
if '%s</p>' % NOT_AVAILABLE_STRING in webpage:
|
|
||||||
raise ExtractorError(NOT_AVAILABLE_STRING, expected=True)
|
|
||||||
|
|
||||||
typ = self._html_search_regex(r'getPlaylistUrl\(\[\{"type":"(.+?)","id":".+?"\}\],', webpage, 'type')
|
|
||||||
episode_id = self._html_search_regex(r'getPlaylistUrl\(\[\{"type":".+?","id":"(.+?)"\}\],', webpage, 'episode_id')
|
|
||||||
|
|
||||||
data = {
|
|
||||||
'playlist[0][type]': typ,
|
|
||||||
'playlist[0][id]': episode_id,
|
|
||||||
'requestUrl': compat_urllib_parse_urlparse(url).path,
|
|
||||||
'requestSource': 'iVysilani',
|
|
||||||
}
|
|
||||||
|
|
||||||
req = compat_urllib_request.Request('http://www.ceskatelevize.cz/ivysilani/ajax/get-playlist-url',
|
|
||||||
data=compat_urllib_parse.urlencode(data))
|
|
||||||
|
|
||||||
req.add_header('Content-type', 'application/x-www-form-urlencoded')
|
|
||||||
req.add_header('x-addr', '127.0.0.1')
|
|
||||||
req.add_header('X-Requested-With', 'XMLHttpRequest')
|
|
||||||
req.add_header('Referer', url)
|
|
||||||
|
|
||||||
playlistpage = self._download_json(req, video_id)
|
|
||||||
|
|
||||||
req = compat_urllib_request.Request(compat_urllib_parse.unquote(playlistpage['url']))
|
|
||||||
req.add_header('Referer', url)
|
|
||||||
|
|
||||||
playlist = self._download_xml(req, video_id)
|
|
||||||
|
|
||||||
formats = []
|
|
||||||
for i in playlist.find('smilRoot/body'):
|
|
||||||
if 'AD' not in i.attrib['id']:
|
|
||||||
base_url = i.attrib['base']
|
|
||||||
parsedurl = compat_urllib_parse_urlparse(base_url)
|
|
||||||
duration = i.attrib['duration']
|
|
||||||
|
|
||||||
for video in i.findall('video'):
|
|
||||||
if video.attrib['label'] != 'AD':
|
|
||||||
format_id = video.attrib['label']
|
|
||||||
play_path = video.attrib['src']
|
|
||||||
vbr = int(video.attrib['system-bitrate'])
|
|
||||||
|
|
||||||
formats.append({
|
|
||||||
'format_id': format_id,
|
|
||||||
'url': base_url,
|
|
||||||
'vbr': vbr,
|
|
||||||
'play_path': play_path,
|
|
||||||
'app': parsedurl.path[1:] + '?' + parsedurl.query,
|
|
||||||
'rtmp_live': True,
|
|
||||||
'ext': 'flv',
|
|
||||||
})
|
|
||||||
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': episode_id,
|
|
||||||
'title': self._html_search_regex(r'<title>(.+?) — iVysílání — Česká televize</title>', webpage, 'title'),
|
|
||||||
'duration': float(duration),
|
|
||||||
'formats': formats,
|
|
||||||
}
|
|
||||||
@@ -1,273 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import ExtractorError
|
|
||||||
|
|
||||||
class Channel9IE(InfoExtractor):
|
|
||||||
'''
|
|
||||||
Common extractor for channel9.msdn.com.
|
|
||||||
|
|
||||||
The type of provided URL (video or playlist) is determined according to
|
|
||||||
meta Search.PageType from web page HTML rather than URL itself, as it is
|
|
||||||
not always possible to do.
|
|
||||||
'''
|
|
||||||
IE_DESC = 'Channel 9'
|
|
||||||
IE_NAME = 'channel9'
|
|
||||||
_VALID_URL = r'https?://(?:www\.)?channel9\.msdn\.com/(?P<contentpath>.+)/?'
|
|
||||||
|
|
||||||
_TESTS = [
|
|
||||||
{
|
|
||||||
'url': 'http://channel9.msdn.com/Events/TechEd/Australia/2013/KOS002',
|
|
||||||
'md5': 'bbd75296ba47916b754e73c3a4bbdf10',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'Events/TechEd/Australia/2013/KOS002',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Developer Kick-Off Session: Stuff We Love',
|
|
||||||
'description': 'md5:c08d72240b7c87fcecafe2692f80e35f',
|
|
||||||
'duration': 4576,
|
|
||||||
'thumbnail': 'http://media.ch9.ms/ch9/9d51/03902f2d-fc97-4d3c-b195-0bfe15a19d51/KOS002_220.jpg',
|
|
||||||
'session_code': 'KOS002',
|
|
||||||
'session_day': 'Day 1',
|
|
||||||
'session_room': 'Arena 1A',
|
|
||||||
'session_speakers': [ 'Ed Blankenship', 'Andrew Coates', 'Brady Gaster', 'Patrick Klug', 'Mads Kristensen' ],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://channel9.msdn.com/posts/Self-service-BI-with-Power-BI-nuclear-testing',
|
|
||||||
'md5': 'b43ee4529d111bc37ba7ee4f34813e68',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'posts/Self-service-BI-with-Power-BI-nuclear-testing',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Self-service BI with Power BI - nuclear testing',
|
|
||||||
'description': 'md5:d1e6ecaafa7fb52a2cacdf9599829f5b',
|
|
||||||
'duration': 1540,
|
|
||||||
'thumbnail': 'http://media.ch9.ms/ch9/87e1/0300391f-a455-4c72-bec3-4422f19287e1/selfservicenuk_512.jpg',
|
|
||||||
'authors': [ 'Mike Wilmot' ],
|
|
||||||
},
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
_RSS_URL = 'http://channel9.msdn.com/%s/RSS'
|
|
||||||
|
|
||||||
# Sorted by quality
|
|
||||||
_known_formats = ['MP3', 'MP4', 'Mid Quality WMV', 'Mid Quality MP4', 'High Quality WMV', 'High Quality MP4']
|
|
||||||
|
|
||||||
def _restore_bytes(self, formatted_size):
|
|
||||||
if not formatted_size:
|
|
||||||
return 0
|
|
||||||
m = re.match(r'^(?P<size>\d+(?:\.\d+)?)\s+(?P<units>[a-zA-Z]+)', formatted_size)
|
|
||||||
if not m:
|
|
||||||
return 0
|
|
||||||
units = m.group('units')
|
|
||||||
try:
|
|
||||||
exponent = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'].index(units.upper())
|
|
||||||
except ValueError:
|
|
||||||
return 0
|
|
||||||
size = float(m.group('size'))
|
|
||||||
return int(size * (1024 ** exponent))
|
|
||||||
|
|
||||||
def _formats_from_html(self, html):
|
|
||||||
FORMAT_REGEX = r'''
|
|
||||||
(?x)
|
|
||||||
<a\s+href="(?P<url>[^"]+)">(?P<quality>[^<]+)</a>\s*
|
|
||||||
<span\s+class="usage">\((?P<note>[^\)]+)\)</span>\s*
|
|
||||||
(?:<div\s+class="popup\s+rounded">\s*
|
|
||||||
<h3>File\s+size</h3>\s*(?P<filesize>.*?)\s*
|
|
||||||
</div>)? # File size part may be missing
|
|
||||||
'''
|
|
||||||
# Extract known formats
|
|
||||||
formats = [{
|
|
||||||
'url': x.group('url'),
|
|
||||||
'format_id': x.group('quality'),
|
|
||||||
'format_note': x.group('note'),
|
|
||||||
'format': '%s (%s)' % (x.group('quality'), x.group('note')),
|
|
||||||
'filesize': self._restore_bytes(x.group('filesize')), # File size is approximate
|
|
||||||
'preference': self._known_formats.index(x.group('quality')),
|
|
||||||
'vcodec': 'none' if x.group('note') == 'Audio only' else None,
|
|
||||||
} for x in list(re.finditer(FORMAT_REGEX, html)) if x.group('quality') in self._known_formats]
|
|
||||||
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
return formats
|
|
||||||
|
|
||||||
def _extract_title(self, html):
|
|
||||||
title = self._html_search_meta('title', html, 'title')
|
|
||||||
if title is None:
|
|
||||||
title = self._og_search_title(html)
|
|
||||||
TITLE_SUFFIX = ' (Channel 9)'
|
|
||||||
if title is not None and title.endswith(TITLE_SUFFIX):
|
|
||||||
title = title[:-len(TITLE_SUFFIX)]
|
|
||||||
return title
|
|
||||||
|
|
||||||
def _extract_description(self, html):
|
|
||||||
DESCRIPTION_REGEX = r'''(?sx)
|
|
||||||
<div\s+class="entry-content">\s*
|
|
||||||
<div\s+id="entry-body">\s*
|
|
||||||
(?P<description>.+?)\s*
|
|
||||||
</div>\s*
|
|
||||||
</div>
|
|
||||||
'''
|
|
||||||
m = re.search(DESCRIPTION_REGEX, html)
|
|
||||||
if m is not None:
|
|
||||||
return m.group('description')
|
|
||||||
return self._html_search_meta('description', html, 'description')
|
|
||||||
|
|
||||||
def _extract_duration(self, html):
|
|
||||||
m = re.search(r'data-video_duration="(?P<hours>\d{2}):(?P<minutes>\d{2}):(?P<seconds>\d{2})"', html)
|
|
||||||
return ((int(m.group('hours')) * 60 * 60) + (int(m.group('minutes')) * 60) + int(m.group('seconds'))) if m else None
|
|
||||||
|
|
||||||
def _extract_slides(self, html):
|
|
||||||
m = re.search(r'<a href="(?P<slidesurl>[^"]+)" class="slides">Slides</a>', html)
|
|
||||||
return m.group('slidesurl') if m is not None else None
|
|
||||||
|
|
||||||
def _extract_zip(self, html):
|
|
||||||
m = re.search(r'<a href="(?P<zipurl>[^"]+)" class="zip">Zip</a>', html)
|
|
||||||
return m.group('zipurl') if m is not None else None
|
|
||||||
|
|
||||||
def _extract_avg_rating(self, html):
|
|
||||||
m = re.search(r'<p class="avg-rating">Avg Rating: <span>(?P<avgrating>[^<]+)</span></p>', html)
|
|
||||||
return float(m.group('avgrating')) if m is not None else 0
|
|
||||||
|
|
||||||
def _extract_rating_count(self, html):
|
|
||||||
m = re.search(r'<div class="rating-count">\((?P<ratingcount>[^<]+)\)</div>', html)
|
|
||||||
return int(self._fix_count(m.group('ratingcount'))) if m is not None else 0
|
|
||||||
|
|
||||||
def _extract_view_count(self, html):
|
|
||||||
m = re.search(r'<li class="views">\s*<span class="count">(?P<viewcount>[^<]+)</span> Views\s*</li>', html)
|
|
||||||
return int(self._fix_count(m.group('viewcount'))) if m is not None else 0
|
|
||||||
|
|
||||||
def _extract_comment_count(self, html):
|
|
||||||
m = re.search(r'<li class="comments">\s*<a href="#comments">\s*<span class="count">(?P<commentcount>[^<]+)</span> Comments\s*</a>\s*</li>', html)
|
|
||||||
return int(self._fix_count(m.group('commentcount'))) if m is not None else 0
|
|
||||||
|
|
||||||
def _fix_count(self, count):
|
|
||||||
return int(str(count).replace(',', '')) if count is not None else None
|
|
||||||
|
|
||||||
def _extract_authors(self, html):
|
|
||||||
m = re.search(r'(?s)<li class="author">(.*?)</li>', html)
|
|
||||||
if m is None:
|
|
||||||
return None
|
|
||||||
return re.findall(r'<a href="/Niners/[^"]+">([^<]+)</a>', m.group(1))
|
|
||||||
|
|
||||||
def _extract_session_code(self, html):
|
|
||||||
m = re.search(r'<li class="code">\s*(?P<code>.+?)\s*</li>', html)
|
|
||||||
return m.group('code') if m is not None else None
|
|
||||||
|
|
||||||
def _extract_session_day(self, html):
|
|
||||||
m = re.search(r'<li class="day">\s*<a href="/Events/[^"]+">(?P<day>[^<]+)</a>\s*</li>', html)
|
|
||||||
return m.group('day') if m is not None else None
|
|
||||||
|
|
||||||
def _extract_session_room(self, html):
|
|
||||||
m = re.search(r'<li class="room">\s*(?P<room>.+?)\s*</li>', html)
|
|
||||||
return m.group('room') if m is not None else None
|
|
||||||
|
|
||||||
def _extract_session_speakers(self, html):
|
|
||||||
return re.findall(r'<a href="/Events/Speakers/[^"]+">([^<]+)</a>', html)
|
|
||||||
|
|
||||||
def _extract_content(self, html, content_path):
|
|
||||||
# Look for downloadable content
|
|
||||||
formats = self._formats_from_html(html)
|
|
||||||
slides = self._extract_slides(html)
|
|
||||||
zip_ = self._extract_zip(html)
|
|
||||||
|
|
||||||
# Nothing to download
|
|
||||||
if len(formats) == 0 and slides is None and zip_ is None:
|
|
||||||
self._downloader.report_warning('None of recording, slides or zip are available for %s' % content_path)
|
|
||||||
return
|
|
||||||
|
|
||||||
# Extract meta
|
|
||||||
title = self._extract_title(html)
|
|
||||||
description = self._extract_description(html)
|
|
||||||
thumbnail = self._og_search_thumbnail(html)
|
|
||||||
duration = self._extract_duration(html)
|
|
||||||
avg_rating = self._extract_avg_rating(html)
|
|
||||||
rating_count = self._extract_rating_count(html)
|
|
||||||
view_count = self._extract_view_count(html)
|
|
||||||
comment_count = self._extract_comment_count(html)
|
|
||||||
|
|
||||||
common = {'_type': 'video',
|
|
||||||
'id': content_path,
|
|
||||||
'description': description,
|
|
||||||
'thumbnail': thumbnail,
|
|
||||||
'duration': duration,
|
|
||||||
'avg_rating': avg_rating,
|
|
||||||
'rating_count': rating_count,
|
|
||||||
'view_count': view_count,
|
|
||||||
'comment_count': comment_count,
|
|
||||||
}
|
|
||||||
|
|
||||||
result = []
|
|
||||||
|
|
||||||
if slides is not None:
|
|
||||||
d = common.copy()
|
|
||||||
d.update({ 'title': title + '-Slides', 'url': slides })
|
|
||||||
result.append(d)
|
|
||||||
|
|
||||||
if zip_ is not None:
|
|
||||||
d = common.copy()
|
|
||||||
d.update({ 'title': title + '-Zip', 'url': zip_ })
|
|
||||||
result.append(d)
|
|
||||||
|
|
||||||
if len(formats) > 0:
|
|
||||||
d = common.copy()
|
|
||||||
d.update({ 'title': title, 'formats': formats })
|
|
||||||
result.append(d)
|
|
||||||
|
|
||||||
return result
|
|
||||||
|
|
||||||
def _extract_entry_item(self, html, content_path):
|
|
||||||
contents = self._extract_content(html, content_path)
|
|
||||||
if contents is None:
|
|
||||||
return contents
|
|
||||||
|
|
||||||
authors = self._extract_authors(html)
|
|
||||||
|
|
||||||
for content in contents:
|
|
||||||
content['authors'] = authors
|
|
||||||
|
|
||||||
return contents
|
|
||||||
|
|
||||||
def _extract_session(self, html, content_path):
|
|
||||||
contents = self._extract_content(html, content_path)
|
|
||||||
if contents is None:
|
|
||||||
return contents
|
|
||||||
|
|
||||||
session_meta = {'session_code': self._extract_session_code(html),
|
|
||||||
'session_day': self._extract_session_day(html),
|
|
||||||
'session_room': self._extract_session_room(html),
|
|
||||||
'session_speakers': self._extract_session_speakers(html),
|
|
||||||
}
|
|
||||||
|
|
||||||
for content in contents:
|
|
||||||
content.update(session_meta)
|
|
||||||
|
|
||||||
return contents
|
|
||||||
|
|
||||||
def _extract_list(self, content_path):
|
|
||||||
rss = self._download_xml(self._RSS_URL % content_path, content_path, 'Downloading RSS')
|
|
||||||
entries = [self.url_result(session_url.text, 'Channel9')
|
|
||||||
for session_url in rss.findall('./channel/item/link')]
|
|
||||||
title_text = rss.find('./channel/title').text
|
|
||||||
return self.playlist_result(entries, content_path, title_text)
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
content_path = mobj.group('contentpath')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, content_path, 'Downloading web page')
|
|
||||||
|
|
||||||
page_type_m = re.search(r'<meta name="Search.PageType" content="(?P<pagetype>[^"]+)"/>', webpage)
|
|
||||||
if page_type_m is None:
|
|
||||||
raise ExtractorError('Search.PageType not found, don\'t know how to process this page', expected=True)
|
|
||||||
|
|
||||||
page_type = page_type_m.group('pagetype')
|
|
||||||
if page_type == 'List': # List page, may contain list of 'item'-like objects
|
|
||||||
return self._extract_list(content_path)
|
|
||||||
elif page_type == 'Entry.Item': # Any 'item'-like page, may contain downloadable content
|
|
||||||
return self._extract_entry_item(webpage, content_path)
|
|
||||||
elif page_type == 'Session': # Event session page, may contain downloadable content
|
|
||||||
return self._extract_session(webpage, content_path)
|
|
||||||
else:
|
|
||||||
raise ExtractorError('Unexpected Search.PageType %s' % page_type, expected=True)
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
import base64
|
|
||||||
import json
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import (
|
|
||||||
clean_html,
|
|
||||||
ExtractorError
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ChilloutzoneIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'https?://(?:www\.)?chilloutzone\.net/video/(?P<id>[\w|-]+)\.html'
|
|
||||||
_TESTS = [{
|
|
||||||
'url': 'http://www.chilloutzone.net/video/enemene-meck-alle-katzen-weg.html',
|
|
||||||
'md5': 'a76f3457e813ea0037e5244f509e66d1',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'enemene-meck-alle-katzen-weg',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Enemene Meck - Alle Katzen weg',
|
|
||||||
'description': 'Ist das der Umkehrschluss des Niesenden Panda-Babys?',
|
|
||||||
},
|
|
||||||
}, {
|
|
||||||
'note': 'Video hosted at YouTube',
|
|
||||||
'url': 'http://www.chilloutzone.net/video/eine-sekunde-bevor.html',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '1YVQaAgHyRU',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': '16 Photos Taken 1 Second Before Disaster',
|
|
||||||
'description': 'md5:58a8fcf6a459fe0a08f54140f0ad1814',
|
|
||||||
'uploader': 'BuzzFeedVideo',
|
|
||||||
'uploader_id': 'BuzzFeedVideo',
|
|
||||||
'upload_date': '20131105',
|
|
||||||
},
|
|
||||||
}, {
|
|
||||||
'note': 'Video hosted at Vimeo',
|
|
||||||
'url': 'http://www.chilloutzone.net/video/icon-blending.html',
|
|
||||||
'md5': '2645c678b8dc4fefcc0e1b60db18dac1',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '85523671',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'The Sunday Times - Icons',
|
|
||||||
'description': 'md5:3e1c0dc6047498d6728dcdaad0891762',
|
|
||||||
'uploader': 'Us',
|
|
||||||
'uploader_id': 'usfilms',
|
|
||||||
'upload_date': '20140131'
|
|
||||||
},
|
|
||||||
}]
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
|
|
||||||
base64_video_info = self._html_search_regex(
|
|
||||||
r'var cozVidData = "(.+?)";', webpage, 'video data')
|
|
||||||
decoded_video_info = base64.b64decode(base64_video_info).decode("utf-8")
|
|
||||||
video_info_dict = json.loads(decoded_video_info)
|
|
||||||
|
|
||||||
# get video information from dict
|
|
||||||
video_url = video_info_dict['mediaUrl']
|
|
||||||
description = clean_html(video_info_dict.get('description'))
|
|
||||||
title = video_info_dict['title']
|
|
||||||
native_platform = video_info_dict['nativePlatform']
|
|
||||||
native_video_id = video_info_dict['nativeVideoId']
|
|
||||||
source_priority = video_info_dict['sourcePriority']
|
|
||||||
|
|
||||||
# If nativePlatform is None a fallback mechanism is used (i.e. youtube embed)
|
|
||||||
if native_platform is None:
|
|
||||||
youtube_url = self._html_search_regex(
|
|
||||||
r'<iframe.* src="((?:https?:)?//(?:[^.]+\.)?youtube\.com/.+?)"',
|
|
||||||
webpage, 'fallback video URL', default=None)
|
|
||||||
if youtube_url is not None:
|
|
||||||
return self.url_result(youtube_url, ie='Youtube')
|
|
||||||
|
|
||||||
# Non Fallback: Decide to use native source (e.g. youtube or vimeo) or
|
|
||||||
# the own CDN
|
|
||||||
if source_priority == 'native':
|
|
||||||
if native_platform == 'youtube':
|
|
||||||
return self.url_result(native_video_id, ie='Youtube')
|
|
||||||
if native_platform == 'vimeo':
|
|
||||||
return self.url_result(
|
|
||||||
'http://vimeo.com/' + native_video_id, ie='Vimeo')
|
|
||||||
|
|
||||||
if not video_url:
|
|
||||||
raise ExtractorError('No video found')
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'url': video_url,
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': title,
|
|
||||||
'description': description,
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
# encoding: utf-8
|
# encoding: utf-8
|
||||||
from __future__ import unicode_literals
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
@@ -9,71 +8,71 @@ from ..utils import (
|
|||||||
|
|
||||||
|
|
||||||
class CinemassacreIE(InfoExtractor):
|
class CinemassacreIE(InfoExtractor):
|
||||||
_VALID_URL = r'http://(?:www\.)?cinemassacre\.com/(?P<date_Y>[0-9]{4})/(?P<date_m>[0-9]{2})/(?P<date_d>[0-9]{2})/(?P<display_id>[^?#/]+)'
|
_VALID_URL = r'(?:http://)?(?:www\.)?(?P<url>cinemassacre\.com/(?P<date_Y>[0-9]{4})/(?P<date_m>[0-9]{2})/(?P<date_d>[0-9]{2})/.+?)(?:[/?].*)?'
|
||||||
_TESTS = [
|
_TESTS = [{
|
||||||
{
|
u'url': u'http://cinemassacre.com/2012/11/10/avgn-the-movie-trailer/',
|
||||||
'url': 'http://cinemassacre.com/2012/11/10/avgn-the-movie-trailer/',
|
u'file': u'19911.flv',
|
||||||
'file': '19911.mp4',
|
u'md5': u'f9bb7ede54d1229c9846e197b4737e06',
|
||||||
'md5': '782f8504ca95a0eba8fc9177c373eec7',
|
u'info_dict': {
|
||||||
'info_dict': {
|
u'upload_date': u'20121110',
|
||||||
'upload_date': '20121110',
|
u'title': u'“Angry Video Game Nerd: The Movie” – Trailer',
|
||||||
'title': '“Angry Video Game Nerd: The Movie” – Trailer',
|
u'description': u'md5:fb87405fcb42a331742a0dce2708560b',
|
||||||
'description': 'md5:fb87405fcb42a331742a0dce2708560b',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'url': 'http://cinemassacre.com/2013/10/02/the-mummys-hand-1940',
|
|
||||||
'file': '521be8ef82b16.mp4',
|
|
||||||
'md5': 'dec39ee5118f8d9cc067f45f9cbe3a35',
|
|
||||||
'info_dict': {
|
|
||||||
'upload_date': '20131002',
|
|
||||||
'title': 'The Mummy’s Hand (1940)',
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
]
|
},
|
||||||
|
{
|
||||||
|
u'url': u'http://cinemassacre.com/2013/10/02/the-mummys-hand-1940',
|
||||||
|
u'file': u'521be8ef82b16.flv',
|
||||||
|
u'md5': u'9509ee44dcaa7c1068604817c19a9e50',
|
||||||
|
u'info_dict': {
|
||||||
|
u'upload_date': u'20131002',
|
||||||
|
u'title': u'The Mummy’s Hand (1940)',
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
display_id = mobj.group('display_id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, display_id)
|
webpage_url = u'http://' + mobj.group('url')
|
||||||
|
webpage = self._download_webpage(webpage_url, None) # Don't know video id yet
|
||||||
video_date = mobj.group('date_Y') + mobj.group('date_m') + mobj.group('date_d')
|
video_date = mobj.group('date_Y') + mobj.group('date_m') + mobj.group('date_d')
|
||||||
mobj = re.search(r'src="(?P<embed_url>http://player\.screenwavemedia\.com/play/[a-zA-Z]+\.php\?id=(?:Cinemassacre-)?(?P<video_id>.+?))"', webpage)
|
mobj = re.search(r'src="(?P<embed_url>http://player\.screenwavemedia\.com/play/[a-zA-Z]+\.php\?id=(?:Cinemassacre-)?(?P<video_id>.+?))"', webpage)
|
||||||
if not mobj:
|
if not mobj:
|
||||||
raise ExtractorError('Can\'t extract embed url and video id')
|
raise ExtractorError(u'Can\'t extract embed url and video id')
|
||||||
playerdata_url = mobj.group('embed_url')
|
playerdata_url = mobj.group(u'embed_url')
|
||||||
video_id = mobj.group('video_id')
|
video_id = mobj.group(u'video_id')
|
||||||
|
|
||||||
video_title = self._html_search_regex(
|
video_title = self._html_search_regex(r'<title>(?P<title>.+?)\|',
|
||||||
r'<title>(?P<title>.+?)\|', webpage, 'title')
|
webpage, u'title')
|
||||||
video_description = self._html_search_regex(
|
video_description = self._html_search_regex(r'<div class="entry-content">(?P<description>.+?)</div>',
|
||||||
r'<div class="entry-content">(?P<description>.+?)</div>',
|
webpage, u'description', flags=re.DOTALL, fatal=False)
|
||||||
webpage, 'description', flags=re.DOTALL, fatal=False)
|
if len(video_description) == 0:
|
||||||
|
video_description = None
|
||||||
|
|
||||||
playerdata = self._download_webpage(playerdata_url, video_id)
|
playerdata = self._download_webpage(playerdata_url, video_id)
|
||||||
|
url = self._html_search_regex(r'\'streamer\': \'(?P<url>[^\']+)\'', playerdata, u'url')
|
||||||
|
|
||||||
sd_url = self._html_search_regex(r'file: \'([^\']+)\', label: \'SD\'', playerdata, 'sd_file')
|
sd_file = self._html_search_regex(r'\'file\': \'(?P<sd_file>[^\']+)\'', playerdata, u'sd_file')
|
||||||
hd_url = self._html_search_regex(
|
hd_file = self._html_search_regex(r'\'?file\'?: "(?P<hd_file>[^"]+)"', playerdata, u'hd_file')
|
||||||
r'file: \'([^\']+)\', label: \'HD\'', playerdata, 'hd_file',
|
video_thumbnail = self._html_search_regex(r'\'image\': \'(?P<thumbnail>[^\']+)\'', playerdata, u'thumbnail', fatal=False)
|
||||||
default=None)
|
|
||||||
video_thumbnail = self._html_search_regex(r'image: \'(?P<thumbnail>[^\']+)\'', playerdata, 'thumbnail', fatal=False)
|
|
||||||
|
|
||||||
formats = [{
|
formats = [
|
||||||
'url': sd_url,
|
{
|
||||||
'ext': 'mp4',
|
'url': url,
|
||||||
'format': 'sd',
|
'play_path': 'mp4:' + sd_file,
|
||||||
'format_id': 'sd',
|
'rtmp_live': True, # workaround
|
||||||
'quality': 1,
|
'ext': 'flv',
|
||||||
}]
|
'format': 'sd',
|
||||||
if hd_url:
|
'format_id': 'sd',
|
||||||
formats.append({
|
},
|
||||||
'url': hd_url,
|
{
|
||||||
'ext': 'mp4',
|
'url': url,
|
||||||
|
'play_path': 'mp4:' + hd_file,
|
||||||
|
'rtmp_live': True, # workaround
|
||||||
|
'ext': 'flv',
|
||||||
'format': 'hd',
|
'format': 'hd',
|
||||||
'format_id': 'hd',
|
'format_id': 'hd',
|
||||||
'quality': 2,
|
},
|
||||||
})
|
]
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
|
|||||||
@@ -1,30 +1,22 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
import time
|
import time
|
||||||
import xml.etree.ElementTree
|
import xml.etree.ElementTree
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import (
|
|
||||||
ExtractorError,
|
|
||||||
parse_duration,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ClipfishIE(InfoExtractor):
|
class ClipfishIE(InfoExtractor):
|
||||||
IE_NAME = 'clipfish'
|
IE_NAME = u'clipfish'
|
||||||
|
|
||||||
_VALID_URL = r'^https?://(?:www\.)?clipfish\.de/.*?/video/(?P<id>[0-9]+)/'
|
_VALID_URL = r'^https?://(?:www\.)?clipfish\.de/.*?/video/(?P<id>[0-9]+)/'
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://www.clipfish.de/special/game-trailer/video/3966754/fifa-14-e3-2013-trailer/',
|
u'url': u'http://www.clipfish.de/special/supertalent/video/4028320/supertalent-2013-ivana-opacak-singt-nobodys-perfect/',
|
||||||
'md5': '2521cd644e862936cf2e698206e47385',
|
u'file': u'4028320.f4v',
|
||||||
'info_dict': {
|
u'md5': u'5e38bda8c329fbfb42be0386a3f5a382',
|
||||||
'id': '3966754',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u'title': u'Supertalent 2013: Ivana Opacak singt Nobody\'s Perfect',
|
||||||
'title': 'FIFA 14 - E3 2013 Trailer',
|
u'duration': 399,
|
||||||
'duration': 82,
|
}
|
||||||
},
|
|
||||||
u'skip': 'Blocked in the US'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
@@ -33,16 +25,24 @@ class ClipfishIE(InfoExtractor):
|
|||||||
|
|
||||||
info_url = ('http://www.clipfish.de/devxml/videoinfo/%s?ts=%d' %
|
info_url = ('http://www.clipfish.de/devxml/videoinfo/%s?ts=%d' %
|
||||||
(video_id, int(time.time())))
|
(video_id, int(time.time())))
|
||||||
doc = self._download_xml(
|
info_xml = self._download_webpage(
|
||||||
info_url, video_id, note=u'Downloading info page')
|
info_url, video_id, note=u'Downloading info page')
|
||||||
|
doc = xml.etree.ElementTree.fromstring(info_xml)
|
||||||
title = doc.find('title').text
|
title = doc.find('title').text
|
||||||
video_url = doc.find('filename').text
|
video_url = doc.find('filename').text
|
||||||
if video_url is None:
|
|
||||||
xml_bytes = xml.etree.ElementTree.tostring(doc)
|
|
||||||
raise ExtractorError('Cannot find video URL in document %r' %
|
|
||||||
xml_bytes)
|
|
||||||
thumbnail = doc.find('imageurl').text
|
thumbnail = doc.find('imageurl').text
|
||||||
duration = parse_duration(doc.find('duration').text)
|
duration_str = doc.find('duration').text
|
||||||
|
m = re.match(
|
||||||
|
r'^(?P<hours>[0-9]+):(?P<minutes>[0-9]{2}):(?P<seconds>[0-9]{2}):(?P<ms>[0-9]*)$',
|
||||||
|
duration_str)
|
||||||
|
if m:
|
||||||
|
duration = (
|
||||||
|
(int(m.group('hours')) * 60 * 60) +
|
||||||
|
(int(m.group('minutes')) * 60) +
|
||||||
|
(int(m.group('seconds')))
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
duration = None
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
|
|
||||||
|
|
||||||
translation_table = {
|
|
||||||
'a': 'h', 'd': 'e', 'e': 'v', 'f': 'o', 'g': 'f', 'i': 'd', 'l': 'n',
|
|
||||||
'm': 'a', 'n': 'm', 'p': 'u', 'q': 't', 'r': 's', 'v': 'p', 'x': 'r',
|
|
||||||
'y': 'l', 'z': 'i',
|
|
||||||
'$': ':', '&': '.', '(': '=', '^': '&', '=': '/',
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class CliphunterIE(InfoExtractor):
|
|
||||||
IE_NAME = 'cliphunter'
|
|
||||||
|
|
||||||
_VALID_URL = r'''(?x)http://(?:www\.)?cliphunter\.com/w/
|
|
||||||
(?P<id>[0-9]+)/
|
|
||||||
(?P<seo>.+?)(?:$|[#\?])
|
|
||||||
'''
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.cliphunter.com/w/1012420/Fun_Jynx_Maze_solo',
|
|
||||||
'file': '1012420.flv',
|
|
||||||
'md5': '15e7740f30428abf70f4223478dc1225',
|
|
||||||
'info_dict': {
|
|
||||||
'title': 'Fun Jynx Maze solo',
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
|
|
||||||
pl_fiji = self._search_regex(
|
|
||||||
r'pl_fiji = \'([^\']+)\'', webpage, 'video data')
|
|
||||||
pl_c_qual = self._search_regex(
|
|
||||||
r'pl_c_qual = "(.)"', webpage, 'video quality')
|
|
||||||
video_title = self._search_regex(
|
|
||||||
r'mediaTitle = "([^"]+)"', webpage, 'title')
|
|
||||||
|
|
||||||
video_url = ''.join(translation_table.get(c, c) for c in pl_fiji)
|
|
||||||
|
|
||||||
formats = [{
|
|
||||||
'url': video_url,
|
|
||||||
'format_id': pl_c_qual,
|
|
||||||
}]
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'title': video_title,
|
|
||||||
'formats': formats,
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import (
|
|
||||||
find_xpath_attr,
|
|
||||||
fix_xml_ampersands
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ClipsyndicateIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'http://www\.clipsyndicate\.com/video/play(list/\d+)?/(?P<id>\d+)'
|
|
||||||
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.clipsyndicate.com/video/play/4629301/brick_briscoe',
|
|
||||||
'md5': '4d7d549451bad625e0ff3d7bd56d776c',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '4629301',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Brick Briscoe',
|
|
||||||
'duration': 612,
|
|
||||||
'thumbnail': 're:^https?://.+\.jpg',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
js_player = self._download_webpage(
|
|
||||||
'http://eplayer.clipsyndicate.com/embed/player.js?va_id=%s' % video_id,
|
|
||||||
video_id, 'Downlaoding player')
|
|
||||||
# it includes a required token
|
|
||||||
flvars = self._search_regex(r'flvars: "(.*?)"', js_player, 'flvars')
|
|
||||||
|
|
||||||
pdoc = self._download_xml(
|
|
||||||
'http://eplayer.clipsyndicate.com/osmf/playlist?%s' % flvars,
|
|
||||||
video_id, 'Downloading video info',
|
|
||||||
transform_source=fix_xml_ampersands)
|
|
||||||
|
|
||||||
track_doc = pdoc.find('trackList/track')
|
|
||||||
def find_param(name):
|
|
||||||
node = find_xpath_attr(track_doc, './/param', 'name', name)
|
|
||||||
if node is not None:
|
|
||||||
return node.attrib['value']
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'title': find_param('title'),
|
|
||||||
'url': track_doc.find('location').text,
|
|
||||||
'thumbnail': find_param('thumbnail'),
|
|
||||||
'duration': int(find_param('duration')),
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
# coding: utf-8
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import (
|
|
||||||
clean_html,
|
|
||||||
qualities,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ClubicIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'http://(?:www\.)?clubic\.com/video/[^/]+/video.*-(?P<id>[0-9]+)\.html'
|
|
||||||
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.clubic.com/video/clubic-week/video-clubic-week-2-0-le-fbi-se-lance-dans-la-photo-d-identite-448474.html',
|
|
||||||
'md5': '1592b694ba586036efac1776b0b43cd3',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '448474',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Clubic Week 2.0 : le FBI se lance dans la photo d\u0092identité',
|
|
||||||
'description': 're:Gueule de bois chez Nokia. Le constructeur a indiqué cette.*',
|
|
||||||
'thumbnail': 're:^http://img\.clubic\.com/.*\.jpg$',
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
|
|
||||||
player_url = 'http://player.m6web.fr/v1/player/clubic/%s.html' % video_id
|
|
||||||
player_page = self._download_webpage(player_url, video_id)
|
|
||||||
|
|
||||||
config_json = self._search_regex(
|
|
||||||
r'(?m)M6\.Player\.config\s*=\s*(\{.+?\});$', player_page,
|
|
||||||
'configuration')
|
|
||||||
config = json.loads(config_json)
|
|
||||||
|
|
||||||
video_info = config['videoInfo']
|
|
||||||
sources = config['sources']
|
|
||||||
quality_order = qualities(['sd', 'hq'])
|
|
||||||
|
|
||||||
formats = [{
|
|
||||||
'format_id': src['streamQuality'],
|
|
||||||
'url': src['src'],
|
|
||||||
'quality': quality_order(src['streamQuality']),
|
|
||||||
} for src in sources]
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'title': video_info['title'],
|
|
||||||
'formats': formats,
|
|
||||||
'description': clean_html(video_info.get('description')),
|
|
||||||
'thumbnail': config.get('poster'),
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
from .mtv import MTVIE
|
|
||||||
|
|
||||||
class CMTIE(MTVIE):
|
|
||||||
IE_NAME = u'cmt.com'
|
|
||||||
_VALID_URL = r'https?://www\.cmt\.com/videos/.+?/(?P<videoid>[^/]+)\.jhtml'
|
|
||||||
_FEED_URL = 'http://www.cmt.com/sitewide/apps/player/embed/rss/'
|
|
||||||
|
|
||||||
_TESTS = [
|
|
||||||
{
|
|
||||||
u'url': u'http://www.cmt.com/videos/garth-brooks/989124/the-call-featuring-trisha-yearwood.jhtml#artist=30061',
|
|
||||||
u'md5': u'e6b7ef3c4c45bbfae88061799bbba6c2',
|
|
||||||
u'info_dict': {
|
|
||||||
u'id': u'989124',
|
|
||||||
u'ext': u'mp4',
|
|
||||||
u'title': u'Garth Brooks - "The Call (featuring Trisha Yearwood)"',
|
|
||||||
u'description': u'Blame It All On My Roots',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
# coding: utf-8
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import (
|
|
||||||
ExtractorError,
|
|
||||||
int_or_none,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class CNETIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'https?://(?:www\.)?cnet\.com/videos/(?P<id>[^/]+)/'
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.cnet.com/videos/hands-on-with-microsofts-windows-8-1-update/',
|
|
||||||
'md5': '041233212a0d06b179c87cbcca1577b8',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '56f4ea68-bd21-4852-b08c-4de5b8354c60',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Hands-on with Microsoft Windows 8.1 Update',
|
|
||||||
'description': 'The new update to the Windows 8 OS brings improved performance for mouse and keyboard users.',
|
|
||||||
'thumbnail': 're:^http://.*/flmswindows8.jpg$',
|
|
||||||
'uploader_id': 'sarah.mitroff@cbsinteractive.com',
|
|
||||||
'uploader': 'Sarah Mitroff',
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
display_id = mobj.group('id')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(url, display_id)
|
|
||||||
data_json = self._html_search_regex(
|
|
||||||
r"<div class=\"cnetVideoPlayer\"\s+.*?data-cnet-video-options='([^']+)'",
|
|
||||||
webpage, 'data json')
|
|
||||||
data = json.loads(data_json)
|
|
||||||
vdata = data['video']
|
|
||||||
if not vdata:
|
|
||||||
vdata = data['videos'][0]
|
|
||||||
if not vdata:
|
|
||||||
raise ExtractorError('Cannot find video data')
|
|
||||||
|
|
||||||
video_id = vdata['id']
|
|
||||||
title = vdata['headline']
|
|
||||||
description = vdata.get('dek')
|
|
||||||
thumbnail = vdata.get('image', {}).get('path')
|
|
||||||
author = vdata.get('author')
|
|
||||||
if author:
|
|
||||||
uploader = '%s %s' % (author['firstName'], author['lastName'])
|
|
||||||
uploader_id = author.get('email')
|
|
||||||
else:
|
|
||||||
uploader = None
|
|
||||||
uploader_id = None
|
|
||||||
|
|
||||||
formats = [{
|
|
||||||
'format_id': '%s-%s-%s' % (
|
|
||||||
f['type'], f['format'],
|
|
||||||
int_or_none(f.get('bitrate'), 1000, default='')),
|
|
||||||
'url': f['uri'],
|
|
||||||
'tbr': int_or_none(f.get('bitrate'), 1000),
|
|
||||||
} for f in vdata['files']['data']]
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'display_id': display_id,
|
|
||||||
'title': title,
|
|
||||||
'formats': formats,
|
|
||||||
'description': description,
|
|
||||||
'uploader': uploader,
|
|
||||||
'uploader_id': uploader_id,
|
|
||||||
'thumbnail': thumbnail,
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,8 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import xml.etree.ElementTree
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import (
|
from ..utils import determine_ext
|
||||||
int_or_none,
|
|
||||||
parse_duration,
|
|
||||||
url_basename,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class CNNIE(InfoExtractor):
|
class CNNIE(InfoExtractor):
|
||||||
@@ -15,24 +10,21 @@ class CNNIE(InfoExtractor):
|
|||||||
(?P<path>.+?/(?P<title>[^/]+?)(?:\.cnn|(?=&)))'''
|
(?P<path>.+?/(?P<title>[^/]+?)(?:\.cnn|(?=&)))'''
|
||||||
|
|
||||||
_TESTS = [{
|
_TESTS = [{
|
||||||
'url': 'http://edition.cnn.com/video/?/video/sports/2013/06/09/nadal-1-on-1.cnn',
|
u'url': u'http://edition.cnn.com/video/?/video/sports/2013/06/09/nadal-1-on-1.cnn',
|
||||||
'file': 'sports_2013_06_09_nadal-1-on-1.cnn.mp4',
|
u'file': u'sports_2013_06_09_nadal-1-on-1.cnn.mp4',
|
||||||
'md5': '3e6121ea48df7e2259fe73a0628605c4',
|
u'md5': u'3e6121ea48df7e2259fe73a0628605c4',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'title': 'Nadal wins 8th French Open title',
|
u'title': u'Nadal wins 8th French Open title',
|
||||||
'description': 'World Sport\'s Amanda Davies chats with 2013 French Open champion Rafael Nadal.',
|
u'description': u'World Sport\'s Amanda Davies chats with 2013 French Open champion Rafael Nadal.',
|
||||||
'duration': 135,
|
|
||||||
'upload_date': '20130609',
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"url": "http://edition.cnn.com/video/?/video/us/2013/08/21/sot-student-gives-epic-speech.georgia-institute-of-technology&utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+rss%2Fcnn_topstories+%28RSS%3A+Top+Stories%29",
|
u"url": u"http://edition.cnn.com/video/?/video/us/2013/08/21/sot-student-gives-epic-speech.georgia-institute-of-technology&utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+rss%2Fcnn_topstories+%28RSS%3A+Top+Stories%29",
|
||||||
"file": "us_2013_08_21_sot-student-gives-epic-speech.georgia-institute-of-technology.mp4",
|
u"file": u"us_2013_08_21_sot-student-gives-epic-speech.georgia-institute-of-technology.mp4",
|
||||||
"md5": "b5cc60c60a3477d185af8f19a2a26f4e",
|
u"md5": u"b5cc60c60a3477d185af8f19a2a26f4e",
|
||||||
"info_dict": {
|
u"info_dict": {
|
||||||
"title": "Student's epic speech stuns new freshmen",
|
u"title": "Student's epic speech stuns new freshmen",
|
||||||
"description": "A Georgia Tech student welcomes the incoming freshmen with an epic speech backed by music from \"2001: A Space Odyssey.\"",
|
u"description": "A Georgia Tech student welcomes the incoming freshmen with an epic speech backed by music from \"2001: A Space Odyssey.\""
|
||||||
"upload_date": "20130821",
|
|
||||||
}
|
}
|
||||||
}]
|
}]
|
||||||
|
|
||||||
@@ -40,87 +32,27 @@ class CNNIE(InfoExtractor):
|
|||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
path = mobj.group('path')
|
path = mobj.group('path')
|
||||||
page_title = mobj.group('title')
|
page_title = mobj.group('title')
|
||||||
info_url = 'http://cnn.com/video/data/3.0/%s/index.xml' % path
|
info_url = u'http://cnn.com/video/data/3.0/%s/index.xml' % path
|
||||||
info = self._download_xml(info_url, page_title)
|
info_xml = self._download_webpage(info_url, page_title)
|
||||||
|
info = xml.etree.ElementTree.fromstring(info_xml.encode('utf-8'))
|
||||||
|
|
||||||
formats = []
|
formats = []
|
||||||
rex = re.compile(r'''(?x)
|
|
||||||
(?P<width>[0-9]+)x(?P<height>[0-9]+)
|
|
||||||
(?:_(?P<bitrate>[0-9]+)k)?
|
|
||||||
''')
|
|
||||||
for f in info.findall('files/file'):
|
for f in info.findall('files/file'):
|
||||||
video_url = 'http://ht.cdn.turner.com/cnn/big%s' % (f.text.strip())
|
mf = re.match(r'(\d+)x(\d+)(?:_(.*)k)?',f.attrib['bitrate'])
|
||||||
fdct = {
|
if mf is not None:
|
||||||
'format_id': f.attrib['bitrate'],
|
formats.append((int(mf.group(1)), int(mf.group(2)), int(mf.group(3) or 0), f.text))
|
||||||
'url': video_url,
|
formats = sorted(formats)
|
||||||
}
|
(_,_,_, video_path) = formats[-1]
|
||||||
|
video_url = 'http://ht.cdn.turner.com/cnn/big%s' % video_path
|
||||||
mf = rex.match(f.attrib['bitrate'])
|
|
||||||
if mf:
|
|
||||||
fdct['width'] = int(mf.group('width'))
|
|
||||||
fdct['height'] = int(mf.group('height'))
|
|
||||||
fdct['tbr'] = int_or_none(mf.group('bitrate'))
|
|
||||||
else:
|
|
||||||
mf = rex.search(f.text)
|
|
||||||
if mf:
|
|
||||||
fdct['width'] = int(mf.group('width'))
|
|
||||||
fdct['height'] = int(mf.group('height'))
|
|
||||||
fdct['tbr'] = int_or_none(mf.group('bitrate'))
|
|
||||||
else:
|
|
||||||
mi = re.match(r'ios_(audio|[0-9]+)$', f.attrib['bitrate'])
|
|
||||||
if mi:
|
|
||||||
if mi.group(1) == 'audio':
|
|
||||||
fdct['vcodec'] = 'none'
|
|
||||||
fdct['ext'] = 'm4a'
|
|
||||||
else:
|
|
||||||
fdct['tbr'] = int(mi.group(1))
|
|
||||||
|
|
||||||
formats.append(fdct)
|
|
||||||
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
thumbnails = sorted([((int(t.attrib['height']),int(t.attrib['width'])), t.text) for t in info.findall('images/image')])
|
thumbnails = sorted([((int(t.attrib['height']),int(t.attrib['width'])), t.text) for t in info.findall('images/image')])
|
||||||
thumbs_dict = [{'resolution': res, 'url': t_url} for (res, t_url) in thumbnails]
|
thumbs_dict = [{'resolution': res, 'url': t_url} for (res, t_url) in thumbnails]
|
||||||
|
|
||||||
metas_el = info.find('metas')
|
return {'id': info.attrib['id'],
|
||||||
upload_date = (
|
'title': info.find('headline').text,
|
||||||
metas_el.attrib.get('version') if metas_el is not None else None)
|
'url': video_url,
|
||||||
|
'ext': determine_ext(video_url),
|
||||||
duration_el = info.find('length')
|
'thumbnail': thumbnails[-1][1],
|
||||||
duration = parse_duration(duration_el.text)
|
'thumbnails': thumbs_dict,
|
||||||
|
'description': info.find('description').text,
|
||||||
return {
|
}
|
||||||
'id': info.attrib['id'],
|
|
||||||
'title': info.find('headline').text,
|
|
||||||
'formats': formats,
|
|
||||||
'thumbnail': thumbnails[-1][1],
|
|
||||||
'thumbnails': thumbs_dict,
|
|
||||||
'description': info.find('description').text,
|
|
||||||
'duration': duration,
|
|
||||||
'upload_date': upload_date,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class CNNBlogsIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'https?://[^\.]+\.blogs\.cnn\.com/.+'
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://reliablesources.blogs.cnn.com/2014/02/09/criminalizing-journalism/',
|
|
||||||
'md5': '3e56f97b0b6ffb4b79f4ea0749551084',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'bestoftv/2014/02/09/criminalizing-journalism.cnn',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Criminalizing journalism?',
|
|
||||||
'description': 'Glenn Greenwald responds to comments made this week on Capitol Hill that journalists could be criminal accessories.',
|
|
||||||
'upload_date': '20140209',
|
|
||||||
},
|
|
||||||
'add_ie': ['CNN'],
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
webpage = self._download_webpage(url, url_basename(url))
|
|
||||||
cnn_url = self._html_search_regex(r'data-url="(.+?)"', webpage, 'cnn url')
|
|
||||||
return {
|
|
||||||
'_type': 'url',
|
|
||||||
'url': cnn_url,
|
|
||||||
'ie_key': CNNIE.ie_key(),
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,102 +1,82 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import json
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import int_or_none
|
from ..utils import (
|
||||||
|
compat_urllib_parse_urlparse,
|
||||||
|
determine_ext,
|
||||||
|
|
||||||
|
ExtractorError,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class CollegeHumorIE(InfoExtractor):
|
class CollegeHumorIE(InfoExtractor):
|
||||||
_VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/(video|embed|e)/(?P<videoid>[0-9]+)/?(?P<shorttitle>.*)$'
|
_VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/(video|embed|e)/(?P<videoid>[0-9]+)/?(?P<shorttitle>.*)$'
|
||||||
|
|
||||||
_TESTS = [{
|
_TESTS = [{
|
||||||
'url': 'http://www.collegehumor.com/video/6902724/comic-con-cosplay-catastrophe',
|
u'url': u'http://www.collegehumor.com/video/6902724/comic-con-cosplay-catastrophe',
|
||||||
'md5': 'dcc0f5c1c8be98dc33889a191f4c26bd',
|
u'file': u'6902724.mp4',
|
||||||
'info_dict': {
|
u'md5': u'1264c12ad95dca142a9f0bf7968105a0',
|
||||||
'id': '6902724',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u'title': u'Comic-Con Cosplay Catastrophe',
|
||||||
'title': 'Comic-Con Cosplay Catastrophe',
|
u'description': u'Fans get creative this year at San Diego. Too creative. And yes, that\'s really Joss Whedon.',
|
||||||
'description': "Fans get creative this year at San Diego. Too creative. And yes, that's really Joss Whedon.",
|
|
||||||
'age_limit': 13,
|
|
||||||
'duration': 187,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'url': 'http://www.collegehumor.com/video/3505939/font-conference',
|
u'url': u'http://www.collegehumor.com/video/3505939/font-conference',
|
||||||
'md5': '72fa701d8ef38664a4dbb9e2ab721816',
|
u'file': u'3505939.mp4',
|
||||||
'info_dict': {
|
u'md5': u'c51ca16b82bb456a4397987791a835f5',
|
||||||
'id': '3505939',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u'title': u'Font Conference',
|
||||||
'title': 'Font Conference',
|
u'description': u'This video wasn\'t long enough, so we made it double-spaced.',
|
||||||
'description': "This video wasn't long enough, so we made it double-spaced.",
|
|
||||||
'age_limit': 10,
|
|
||||||
'duration': 179,
|
|
||||||
},
|
},
|
||||||
},
|
}]
|
||||||
# embedded youtube video
|
|
||||||
{
|
|
||||||
'url': 'http://www.collegehumor.com/embed/6950306',
|
|
||||||
'info_dict': {
|
|
||||||
'id': 'Z-bao9fg6Yc',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Young Americans Think President John F. Kennedy Died THIS MORNING IN A CAR ACCIDENT!!!',
|
|
||||||
'uploader': 'Mark Dice',
|
|
||||||
'uploader_id': 'MarkDice',
|
|
||||||
'description': 'md5:62c3dab9351fac7bb44b53b69511d87f',
|
|
||||||
'upload_date': '20140127',
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
'skip_download': True,
|
|
||||||
},
|
|
||||||
'add_ie': ['Youtube'],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
|
if mobj is None:
|
||||||
|
raise ExtractorError(u'Invalid URL: %s' % url)
|
||||||
video_id = mobj.group('videoid')
|
video_id = mobj.group('videoid')
|
||||||
|
|
||||||
jsonUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id + '.json'
|
info = {
|
||||||
data = json.loads(self._download_webpage(
|
|
||||||
jsonUrl, video_id, 'Downloading info JSON'))
|
|
||||||
vdata = data['video']
|
|
||||||
if vdata.get('youtubeId') is not None:
|
|
||||||
return {
|
|
||||||
'_type': 'url',
|
|
||||||
'url': vdata['youtubeId'],
|
|
||||||
'ie_key': 'Youtube',
|
|
||||||
}
|
|
||||||
|
|
||||||
AGE_LIMITS = {'nc17': 18, 'r': 18, 'pg13': 13, 'pg': 10, 'g': 0}
|
|
||||||
rating = vdata.get('rating')
|
|
||||||
if rating:
|
|
||||||
age_limit = AGE_LIMITS.get(rating.lower())
|
|
||||||
else:
|
|
||||||
age_limit = None # None = No idea
|
|
||||||
|
|
||||||
PREFS = {'high_quality': 2, 'low_quality': 0}
|
|
||||||
formats = []
|
|
||||||
for format_key in ('mp4', 'webm'):
|
|
||||||
for qname, qurl in vdata.get(format_key, {}).items():
|
|
||||||
formats.append({
|
|
||||||
'format_id': format_key + '_' + qname,
|
|
||||||
'url': qurl,
|
|
||||||
'format': format_key,
|
|
||||||
'preference': PREFS.get(qname),
|
|
||||||
})
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
duration = int_or_none(vdata.get('duration'), 1000)
|
|
||||||
like_count = int_or_none(vdata.get('likes'))
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
'title': vdata['title'],
|
'uploader': None,
|
||||||
'description': vdata.get('description'),
|
'upload_date': None,
|
||||||
'thumbnail': vdata.get('thumbnail'),
|
|
||||||
'formats': formats,
|
|
||||||
'age_limit': age_limit,
|
|
||||||
'duration': duration,
|
|
||||||
'like_count': like_count,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.report_extraction(video_id)
|
||||||
|
xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
|
||||||
|
mdoc = self._download_xml(xmlUrl, video_id,
|
||||||
|
u'Downloading info XML',
|
||||||
|
u'Unable to download video info XML')
|
||||||
|
|
||||||
|
try:
|
||||||
|
videoNode = mdoc.findall('./video')[0]
|
||||||
|
youtubeIdNode = videoNode.find('./youtubeID')
|
||||||
|
if youtubeIdNode is not None:
|
||||||
|
return self.url_result(youtubeIdNode.text, 'Youtube')
|
||||||
|
info['description'] = videoNode.findall('./description')[0].text
|
||||||
|
info['title'] = videoNode.findall('./caption')[0].text
|
||||||
|
info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
|
||||||
|
next_url = videoNode.findall('./file')[0].text
|
||||||
|
except IndexError:
|
||||||
|
raise ExtractorError(u'Invalid metadata XML file')
|
||||||
|
|
||||||
|
if next_url.endswith(u'manifest.f4m'):
|
||||||
|
manifest_url = next_url + '?hdcore=2.10.3'
|
||||||
|
adoc = self._download_xml(manifest_url, video_id,
|
||||||
|
u'Downloading XML manifest',
|
||||||
|
u'Unable to download video info XML')
|
||||||
|
|
||||||
|
try:
|
||||||
|
video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
|
||||||
|
except IndexError:
|
||||||
|
raise ExtractorError(u'Invalid manifest file')
|
||||||
|
url_pr = compat_urllib_parse_urlparse(info['thumbnail'])
|
||||||
|
info['url'] = url_pr.scheme + '://' + url_pr.netloc + video_id[:-2].replace('.csmil','').replace(',','')
|
||||||
|
info['ext'] = 'mp4'
|
||||||
|
else:
|
||||||
|
# Old-style direct links
|
||||||
|
info['url'] = next_url
|
||||||
|
info['ext'] = determine_ext(info['url'])
|
||||||
|
|
||||||
|
return info
|
||||||
|
|||||||
@@ -1,65 +1,73 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import xml.etree.ElementTree
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from .mtv import MTVServicesInfoExtractor
|
from .mtv import MTVIE, _media_xml_tag
|
||||||
from ..utils import (
|
from ..utils import (
|
||||||
compat_str,
|
compat_str,
|
||||||
compat_urllib_parse,
|
compat_urllib_parse,
|
||||||
|
|
||||||
ExtractorError,
|
ExtractorError,
|
||||||
float_or_none,
|
|
||||||
unified_strdate,
|
unified_strdate,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ComedyCentralIE(MTVServicesInfoExtractor):
|
class ComedyCentralIE(MTVIE):
|
||||||
_VALID_URL = r'''(?x)https?://(?:www\.)?(comedycentral|cc)\.com/
|
_VALID_URL = r'http://www.comedycentral.com/(video-clips|episodes|cc-studios)/(?P<title>.*)'
|
||||||
(video-clips|episodes|cc-studios|video-collections)
|
_FEED_URL = u'http://comedycentral.com/feeds/mrss/'
|
||||||
/(?P<title>.*)'''
|
|
||||||
_FEED_URL = 'http://comedycentral.com/feeds/mrss/'
|
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://www.comedycentral.com/video-clips/kllhuv/stand-up-greg-fitzsimmons--uncensored---too-good-of-a-mother',
|
u'url': u'http://www.comedycentral.com/video-clips/kllhuv/stand-up-greg-fitzsimmons--uncensored---too-good-of-a-mother',
|
||||||
'md5': 'c4f48e9eda1b16dd10add0744344b6d8',
|
u'md5': u'4167875aae411f903b751a21f357f1ee',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'id': 'cef0cbb3-e776-4bc9-b62e-8016deccb354',
|
u'id': u'cef0cbb3-e776-4bc9-b62e-8016deccb354',
|
||||||
'ext': 'mp4',
|
u'ext': u'mp4',
|
||||||
'title': 'CC:Stand-Up|Greg Fitzsimmons: Life on Stage|Uncensored - Too Good of a Mother',
|
u'title': u'Uncensored - Greg Fitzsimmons - Too Good of a Mother',
|
||||||
'description': 'After a certain point, breastfeeding becomes c**kblocking.',
|
u'description': u'After a certain point, breastfeeding becomes c**kblocking.',
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
# Overwrite MTVIE properties we don't want
|
||||||
|
_TESTS = []
|
||||||
|
|
||||||
|
def _get_thumbnail_url(self, uri, itemdoc):
|
||||||
|
search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
|
||||||
|
return itemdoc.find(search_path).attrib['url']
|
||||||
|
|
||||||
|
def _real_extract(self, url):
|
||||||
|
mobj = re.match(self._VALID_URL, url)
|
||||||
|
title = mobj.group('title')
|
||||||
|
webpage = self._download_webpage(url, title)
|
||||||
|
mgid = self._search_regex(r'data-mgid="(?P<mgid>mgid:.*?)"',
|
||||||
|
webpage, u'mgid')
|
||||||
|
return self._get_videos_info(mgid)
|
||||||
|
|
||||||
|
|
||||||
class ComedyCentralShowsIE(InfoExtractor):
|
class ComedyCentralShowsIE(InfoExtractor):
|
||||||
IE_DESC = 'The Daily Show / The Colbert Report'
|
IE_DESC = u'The Daily Show / Colbert Report'
|
||||||
# urls can be abbreviations like :thedailyshow or :colbert
|
# urls can be abbreviations like :thedailyshow or :colbert
|
||||||
# urls for episodes like:
|
# urls for episodes like:
|
||||||
# or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
|
# or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
|
||||||
# or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
|
# or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
|
||||||
# or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
|
# or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
|
||||||
_VALID_URL = r'''(?x)^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
|
_VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
|
||||||
|https?://(:www\.)?
|
|(https?://)?(www\.)?
|
||||||
(?P<showname>thedailyshow|thecolbertreport)\.(?:cc\.)?com/
|
(?P<showname>thedailyshow|colbertnation)\.com/
|
||||||
((?:full-)?episodes/(?:[0-9a-z]{6}/)?(?P<episode>.*)|
|
(full-episodes/(?P<episode>.*)|
|
||||||
(?P<clip>
|
(?P<clip>
|
||||||
(?:(?:guests/[^/]+|videos|video-playlists|special-editions)/[^/]+/(?P<videotitle>[^/?#]+))
|
(the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
|
||||||
|(the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
|
|(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))|
|
||||||
|(watch/(?P<date>[^/]*)/(?P<tdstitle>.*))
|
|
||||||
)|
|
|
||||||
(?P<interview>
|
(?P<interview>
|
||||||
extended-interviews/(?P<interID>[0-9a-z]+)/(?:playlist_tds_extended_)?(?P<interview_title>.*?)(/.*?)?)))
|
extended-interviews/(?P<interID>[0-9]+)/playlist_tds_extended_(?P<interview_title>.*?)/.*?)))
|
||||||
(?:[?#].*|$)'''
|
$"""
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://thedailyshow.cc.com/watch/thu-december-13-2012/kristen-stewart',
|
u'url': u'http://www.thedailyshow.com/watch/thu-december-13-2012/kristen-stewart',
|
||||||
'md5': '4e2f5cb088a83cd8cdb7756132f9739d',
|
u'file': u'422212.mp4',
|
||||||
'info_dict': {
|
u'md5': u'4e2f5cb088a83cd8cdb7756132f9739d',
|
||||||
'id': 'ab9ab3e7-5a98-4dbe-8b21-551dc0523d55',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u"upload_date": u"20121214",
|
||||||
'upload_date': '20121213',
|
u"description": u"Kristen Stewart",
|
||||||
'description': 'Kristen Stewart learns to let loose in "On the Road."',
|
u"uploader": u"thedailyshow",
|
||||||
'uploader': 'thedailyshow',
|
u"title": u"thedailyshow-kristen-stewart part 1"
|
||||||
'title': 'thedailyshow kristen-stewart part 1',
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,31 +90,34 @@ class ComedyCentralShowsIE(InfoExtractor):
|
|||||||
'400': (384, 216),
|
'400': (384, 216),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def suitable(cls, url):
|
||||||
|
"""Receives a URL and returns True if suitable for this IE."""
|
||||||
|
return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _transform_rtmp_url(rtmp_video_url):
|
def _transform_rtmp_url(rtmp_video_url):
|
||||||
m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\.comedystor/.*)$', rtmp_video_url)
|
m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
|
||||||
if not m:
|
if not m:
|
||||||
raise ExtractorError('Cannot transform RTMP url')
|
raise ExtractorError(u'Cannot transform RTMP url')
|
||||||
base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
|
base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
|
||||||
return base + m.group('finalid')
|
return base + m.group('finalid')
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url, re.VERBOSE)
|
mobj = re.match(self._VALID_URL, url, re.VERBOSE)
|
||||||
if mobj is None:
|
if mobj is None:
|
||||||
raise ExtractorError('Invalid URL: %s' % url)
|
raise ExtractorError(u'Invalid URL: %s' % url)
|
||||||
|
|
||||||
if mobj.group('shortname'):
|
if mobj.group('shortname'):
|
||||||
if mobj.group('shortname') in ('tds', 'thedailyshow'):
|
if mobj.group('shortname') in ('tds', 'thedailyshow'):
|
||||||
url = 'http://thedailyshow.cc.com/full-episodes/'
|
url = u'http://www.thedailyshow.com/full-episodes/'
|
||||||
else:
|
else:
|
||||||
url = 'http://thecolbertreport.cc.com/full-episodes/'
|
url = u'http://www.colbertnation.com/full-episodes/'
|
||||||
mobj = re.match(self._VALID_URL, url, re.VERBOSE)
|
mobj = re.match(self._VALID_URL, url, re.VERBOSE)
|
||||||
assert mobj is not None
|
assert mobj is not None
|
||||||
|
|
||||||
if mobj.group('clip'):
|
if mobj.group('clip'):
|
||||||
if mobj.group('videotitle'):
|
if mobj.group('showname') == 'thedailyshow':
|
||||||
epTitle = mobj.group('videotitle')
|
|
||||||
elif mobj.group('showname') == 'thedailyshow':
|
|
||||||
epTitle = mobj.group('tdstitle')
|
epTitle = mobj.group('tdstitle')
|
||||||
else:
|
else:
|
||||||
epTitle = mobj.group('cntitle')
|
epTitle = mobj.group('cntitle')
|
||||||
@@ -120,96 +131,88 @@ class ComedyCentralShowsIE(InfoExtractor):
|
|||||||
epTitle = mobj.group('showname')
|
epTitle = mobj.group('showname')
|
||||||
else:
|
else:
|
||||||
epTitle = mobj.group('episode')
|
epTitle = mobj.group('episode')
|
||||||
show_name = mobj.group('showname')
|
|
||||||
|
|
||||||
webpage, htmlHandle = self._download_webpage_handle(url, epTitle)
|
self.report_extraction(epTitle)
|
||||||
|
webpage,htmlHandle = self._download_webpage_handle(url, epTitle)
|
||||||
if dlNewest:
|
if dlNewest:
|
||||||
url = htmlHandle.geturl()
|
url = htmlHandle.geturl()
|
||||||
mobj = re.match(self._VALID_URL, url, re.VERBOSE)
|
mobj = re.match(self._VALID_URL, url, re.VERBOSE)
|
||||||
if mobj is None:
|
if mobj is None:
|
||||||
raise ExtractorError('Invalid redirected URL: ' + url)
|
raise ExtractorError(u'Invalid redirected URL: ' + url)
|
||||||
if mobj.group('episode') == '':
|
if mobj.group('episode') == '':
|
||||||
raise ExtractorError('Redirected URL is still not specific: ' + url)
|
raise ExtractorError(u'Redirected URL is still not specific: ' + url)
|
||||||
epTitle = mobj.group('episode').rpartition('/')[-1]
|
epTitle = mobj.group('episode')
|
||||||
|
|
||||||
mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
|
mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
|
||||||
|
|
||||||
if len(mMovieParams) == 0:
|
if len(mMovieParams) == 0:
|
||||||
# The Colbert Report embeds the information in a without
|
# The Colbert Report embeds the information in a without
|
||||||
# a URL prefix; so extract the alternate reference
|
# a URL prefix; so extract the alternate reference
|
||||||
# and then add the URL prefix manually.
|
# and then add the URL prefix manually.
|
||||||
|
|
||||||
altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video|playlist).*?:.*?)"', webpage)
|
altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
|
||||||
if len(altMovieParams) == 0:
|
if len(altMovieParams) == 0:
|
||||||
raise ExtractorError('unable to find Flash URL in webpage ' + url)
|
raise ExtractorError(u'unable to find Flash URL in webpage ' + url)
|
||||||
else:
|
else:
|
||||||
mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
|
mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
|
||||||
|
|
||||||
uri = mMovieParams[0][1]
|
uri = mMovieParams[0][1]
|
||||||
# Correct cc.com in uri
|
indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
|
||||||
uri = re.sub(r'(episode:[^.]+)(\.cc)?\.com', r'\1.cc.com', uri)
|
indexXml = self._download_webpage(indexUrl, epTitle,
|
||||||
|
u'Downloading show index',
|
||||||
|
u'unable to download episode index')
|
||||||
|
|
||||||
index_url = 'http://%s.cc.com/feeds/mrss?%s' % (show_name, compat_urllib_parse.urlencode({'uri': uri}))
|
results = []
|
||||||
idoc = self._download_xml(
|
|
||||||
index_url, epTitle,
|
|
||||||
'Downloading show index', 'Unable to download episode index')
|
|
||||||
|
|
||||||
title = idoc.find('./channel/title').text
|
idoc = xml.etree.ElementTree.fromstring(indexXml)
|
||||||
description = idoc.find('./channel/description').text
|
itemEls = idoc.findall('.//item')
|
||||||
|
for partNum,itemEl in enumerate(itemEls):
|
||||||
|
mediaId = itemEl.findall('./guid')[0].text
|
||||||
|
shortMediaId = mediaId.split(':')[-1]
|
||||||
|
showId = mediaId.split(':')[-2].replace('.com', '')
|
||||||
|
officialTitle = itemEl.findall('./title')[0].text
|
||||||
|
officialDate = unified_strdate(itemEl.findall('./pubDate')[0].text)
|
||||||
|
|
||||||
entries = []
|
configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
|
||||||
item_els = idoc.findall('.//item')
|
compat_urllib_parse.urlencode({'uri': mediaId}))
|
||||||
for part_num, itemEl in enumerate(item_els):
|
configXml = self._download_webpage(configUrl, epTitle,
|
||||||
upload_date = unified_strdate(itemEl.findall('./pubDate')[0].text)
|
u'Downloading configuration for %s' % shortMediaId)
|
||||||
thumbnail = itemEl.find('.//{http://search.yahoo.com/mrss/}thumbnail').attrib.get('url')
|
|
||||||
|
|
||||||
content = itemEl.find('.//{http://search.yahoo.com/mrss/}content')
|
|
||||||
duration = float_or_none(content.attrib.get('duration'))
|
|
||||||
mediagen_url = content.attrib['url']
|
|
||||||
guid = itemEl.find('./guid').text.rpartition(':')[-1]
|
|
||||||
|
|
||||||
cdoc = self._download_xml(
|
|
||||||
mediagen_url, epTitle,
|
|
||||||
'Downloading configuration for segment %d / %d' % (part_num + 1, len(item_els)))
|
|
||||||
|
|
||||||
|
cdoc = xml.etree.ElementTree.fromstring(configXml)
|
||||||
turls = []
|
turls = []
|
||||||
for rendition in cdoc.findall('.//rendition'):
|
for rendition in cdoc.findall('.//rendition'):
|
||||||
finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
|
finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
|
||||||
turls.append(finfo)
|
turls.append(finfo)
|
||||||
|
|
||||||
|
if len(turls) == 0:
|
||||||
|
self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
|
||||||
|
continue
|
||||||
|
|
||||||
formats = []
|
formats = []
|
||||||
for format, rtmp_video_url in turls:
|
for format, rtmp_video_url in turls:
|
||||||
w, h = self._video_dimensions.get(format, (None, None))
|
w, h = self._video_dimensions.get(format, (None, None))
|
||||||
formats.append({
|
formats.append({
|
||||||
'format_id': 'vhttp-%s' % format,
|
|
||||||
'url': self._transform_rtmp_url(rtmp_video_url),
|
'url': self._transform_rtmp_url(rtmp_video_url),
|
||||||
'ext': self._video_extensions.get(format, 'mp4'),
|
'ext': self._video_extensions.get(format, 'mp4'),
|
||||||
|
'format_id': format,
|
||||||
'height': h,
|
'height': h,
|
||||||
'width': w,
|
'width': w,
|
||||||
})
|
})
|
||||||
formats.append({
|
|
||||||
'format_id': 'rtmp-%s' % format,
|
|
||||||
'url': rtmp_video_url,
|
|
||||||
'ext': self._video_extensions.get(format, 'mp4'),
|
|
||||||
'height': h,
|
|
||||||
'width': w,
|
|
||||||
})
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
virtual_id = show_name + ' ' + epTitle + ' part ' + compat_str(part_num + 1)
|
effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
|
||||||
entries.append({
|
info = {
|
||||||
'id': guid,
|
'id': shortMediaId,
|
||||||
'title': virtual_id,
|
|
||||||
'formats': formats,
|
'formats': formats,
|
||||||
'uploader': show_name,
|
'uploader': showId,
|
||||||
'upload_date': upload_date,
|
'upload_date': officialDate,
|
||||||
'duration': duration,
|
'title': effTitle,
|
||||||
'thumbnail': thumbnail,
|
'thumbnail': None,
|
||||||
'description': description,
|
'description': compat_str(officialTitle),
|
||||||
})
|
}
|
||||||
|
|
||||||
return {
|
# TODO: Remove when #980 has been merged
|
||||||
'_type': 'playlist',
|
info.update(info['formats'][-1])
|
||||||
'entries': entries,
|
|
||||||
'title': show_name + ' ' + title,
|
results.append(info)
|
||||||
'description': description,
|
|
||||||
}
|
return results
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
import base64
|
import base64
|
||||||
import hashlib
|
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import socket
|
import socket
|
||||||
@@ -11,7 +9,6 @@ import xml.etree.ElementTree
|
|||||||
from ..utils import (
|
from ..utils import (
|
||||||
compat_http_client,
|
compat_http_client,
|
||||||
compat_urllib_error,
|
compat_urllib_error,
|
||||||
compat_urllib_parse_urlparse,
|
|
||||||
compat_str,
|
compat_str,
|
||||||
|
|
||||||
clean_html,
|
clean_html,
|
||||||
@@ -21,7 +18,6 @@ from ..utils import (
|
|||||||
sanitize_filename,
|
sanitize_filename,
|
||||||
unescapeHTML,
|
unescapeHTML,
|
||||||
)
|
)
|
||||||
_NO_DEFAULT = object()
|
|
||||||
|
|
||||||
|
|
||||||
class InfoExtractor(object):
|
class InfoExtractor(object):
|
||||||
@@ -38,83 +34,52 @@ class InfoExtractor(object):
|
|||||||
The dictionaries must include the following fields:
|
The dictionaries must include the following fields:
|
||||||
|
|
||||||
id: Video identifier.
|
id: Video identifier.
|
||||||
title: Video title, unescaped.
|
|
||||||
|
|
||||||
Additionally, it must contain either a formats entry or a url one:
|
|
||||||
|
|
||||||
formats: A list of dictionaries for each format available, ordered
|
|
||||||
from worst to best quality.
|
|
||||||
|
|
||||||
Potential fields:
|
|
||||||
* url Mandatory. The URL of the video file
|
|
||||||
* ext Will be calculated from url if missing
|
|
||||||
* format A human-readable description of the format
|
|
||||||
("mp4 container with h264/opus").
|
|
||||||
Calculated from the format_id, width, height.
|
|
||||||
and format_note fields if missing.
|
|
||||||
* format_id A short description of the format
|
|
||||||
("mp4_h264_opus" or "19").
|
|
||||||
Technically optional, but strongly recommended.
|
|
||||||
* format_note Additional info about the format
|
|
||||||
("3D" or "DASH video")
|
|
||||||
* width Width of the video, if known
|
|
||||||
* height Height of the video, if known
|
|
||||||
* resolution Textual description of width and height
|
|
||||||
* tbr Average bitrate of audio and video in KBit/s
|
|
||||||
* abr Average audio bitrate in KBit/s
|
|
||||||
* acodec Name of the audio codec in use
|
|
||||||
* asr Audio sampling rate in Hertz
|
|
||||||
* vbr Average video bitrate in KBit/s
|
|
||||||
* vcodec Name of the video codec in use
|
|
||||||
* container Name of the container format
|
|
||||||
* filesize The number of bytes, if known in advance
|
|
||||||
* player_url SWF Player URL (used for rtmpdump).
|
|
||||||
* protocol The protocol that will be used for the actual
|
|
||||||
download, lower-case.
|
|
||||||
"http", "https", "rtsp", "rtmp", "m3u8" or so.
|
|
||||||
* preference Order number of this format. If this field is
|
|
||||||
present and not None, the formats get sorted
|
|
||||||
by this field, regardless of all other values.
|
|
||||||
-1 for default (order by other properties),
|
|
||||||
-2 or smaller for less than default.
|
|
||||||
* quality Order number of the video quality of this
|
|
||||||
format, irrespective of the file format.
|
|
||||||
-1 for default (order by other properties),
|
|
||||||
-2 or smaller for less than default.
|
|
||||||
url: Final video URL.
|
url: Final video URL.
|
||||||
|
title: Video title, unescaped.
|
||||||
ext: Video filename extension.
|
ext: Video filename extension.
|
||||||
format: The video format, defaults to ext (used for --get-format)
|
|
||||||
player_url: SWF Player URL (used for rtmpdump).
|
Instead of url and ext, formats can also specified.
|
||||||
|
|
||||||
The following fields are optional:
|
The following fields are optional:
|
||||||
|
|
||||||
display_id An alternative identifier for the video, not necessarily
|
format: The video format, defaults to ext (used for --get-format)
|
||||||
unique, but available before title. Typically, id is
|
|
||||||
something like "4234987", title "Dancing naked mole rats",
|
|
||||||
and display_id "dancing-naked-mole-rats"
|
|
||||||
thumbnails: A list of dictionaries (with the entries "resolution" and
|
thumbnails: A list of dictionaries (with the entries "resolution" and
|
||||||
"url") for the varying thumbnails
|
"url") for the varying thumbnails
|
||||||
thumbnail: Full URL to a video thumbnail image.
|
thumbnail: Full URL to a video thumbnail image.
|
||||||
description: One-line video description.
|
description: One-line video description.
|
||||||
uploader: Full name of the video uploader.
|
uploader: Full name of the video uploader.
|
||||||
timestamp: UNIX timestamp of the moment the video became available.
|
|
||||||
upload_date: Video upload date (YYYYMMDD).
|
upload_date: Video upload date (YYYYMMDD).
|
||||||
If not explicitly set, calculated from timestamp.
|
|
||||||
uploader_id: Nickname or id of the video uploader.
|
uploader_id: Nickname or id of the video uploader.
|
||||||
location: Physical location of the video.
|
location: Physical location of the video.
|
||||||
|
player_url: SWF Player URL (used for rtmpdump).
|
||||||
subtitles: The subtitle file contents as a dictionary in the format
|
subtitles: The subtitle file contents as a dictionary in the format
|
||||||
{language: subtitles}.
|
{language: subtitles}.
|
||||||
duration: Length of the video in seconds, as an integer.
|
|
||||||
view_count: How many users have watched the video on the platform.
|
view_count: How many users have watched the video on the platform.
|
||||||
like_count: Number of positive ratings of the video
|
urlhandle: [internal] The urlHandle to be used to download the file,
|
||||||
dislike_count: Number of negative ratings of the video
|
like returned by urllib.request.urlopen
|
||||||
comment_count: Number of comments on the video
|
|
||||||
age_limit: Age restriction for the video, as an integer (years)
|
age_limit: Age restriction for the video, as an integer (years)
|
||||||
|
formats: A list of dictionaries for each format available, it must
|
||||||
|
be ordered from worst to best quality. Potential fields:
|
||||||
|
* url Mandatory. The URL of the video file
|
||||||
|
* ext Will be calculated from url if missing
|
||||||
|
* format A human-readable description of the format
|
||||||
|
("mp4 container with h264/opus").
|
||||||
|
Calculated from the format_id, width, height.
|
||||||
|
and format_note fields if missing.
|
||||||
|
* format_id A short description of the format
|
||||||
|
("mp4_h264_opus" or "19")
|
||||||
|
* format_note Additional info about the format
|
||||||
|
("3D" or "DASH video")
|
||||||
|
* width Width of the video, if known
|
||||||
|
* height Height of the video, if known
|
||||||
|
* abr Average audio bitrate in KBit/s
|
||||||
|
* acodec Name of the audio codec in use
|
||||||
|
* vbr Average video bitrate in KBit/s
|
||||||
|
* vcodec Name of the video codec in use
|
||||||
|
* filesize The number of bytes, if known in advance
|
||||||
webpage_url: The url to the video webpage, if given to youtube-dl it
|
webpage_url: The url to the video webpage, if given to youtube-dl it
|
||||||
should allow to get the same result again. (It will be set
|
should allow to get the same result again. (It will be set
|
||||||
by YoutubeDL if it's missing)
|
by YoutubeDL if it's missing)
|
||||||
categories: A list of categories that the video falls in, for example
|
|
||||||
["Sports", "Berlin"]
|
|
||||||
|
|
||||||
Unless mentioned otherwise, the fields should be Unicode strings.
|
Unless mentioned otherwise, the fields should be Unicode strings.
|
||||||
|
|
||||||
@@ -122,6 +87,9 @@ class InfoExtractor(object):
|
|||||||
_real_extract() methods and define a _VALID_URL regexp.
|
_real_extract() methods and define a _VALID_URL regexp.
|
||||||
Probably, they should also be added to the list of extractors.
|
Probably, they should also be added to the list of extractors.
|
||||||
|
|
||||||
|
_real_extract() must return a *list* of information dictionaries as
|
||||||
|
described above.
|
||||||
|
|
||||||
Finally, the _WORKING attribute should be set to False for broken IEs
|
Finally, the _WORKING attribute should be set to False for broken IEs
|
||||||
in order to warn the users and skip the tests.
|
in order to warn the users and skip the tests.
|
||||||
"""
|
"""
|
||||||
@@ -183,40 +151,27 @@ class InfoExtractor(object):
|
|||||||
def IE_NAME(self):
|
def IE_NAME(self):
|
||||||
return type(self).__name__[:-2]
|
return type(self).__name__[:-2]
|
||||||
|
|
||||||
def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
|
def _request_webpage(self, url_or_request, video_id, note=None, errnote=None):
|
||||||
""" Returns the response handle """
|
""" Returns the response handle """
|
||||||
if note is None:
|
if note is None:
|
||||||
self.report_download_webpage(video_id)
|
self.report_download_webpage(video_id)
|
||||||
elif note is not False:
|
elif note is not False:
|
||||||
if video_id is None:
|
self.to_screen(u'%s: %s' % (video_id, note))
|
||||||
self.to_screen(u'%s' % (note,))
|
|
||||||
else:
|
|
||||||
self.to_screen(u'%s: %s' % (video_id, note))
|
|
||||||
try:
|
try:
|
||||||
return self._downloader.urlopen(url_or_request)
|
return self._downloader.urlopen(url_or_request)
|
||||||
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
|
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
|
||||||
if errnote is False:
|
|
||||||
return False
|
|
||||||
if errnote is None:
|
if errnote is None:
|
||||||
errnote = u'Unable to download webpage'
|
errnote = u'Unable to download webpage'
|
||||||
errmsg = u'%s: %s' % (errnote, compat_str(err))
|
raise ExtractorError(u'%s: %s' % (errnote, compat_str(err)), sys.exc_info()[2], cause=err)
|
||||||
if fatal:
|
|
||||||
raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
|
|
||||||
else:
|
|
||||||
self._downloader.report_warning(errmsg)
|
|
||||||
return False
|
|
||||||
|
|
||||||
def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
|
def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None):
|
||||||
""" Returns a tuple (page content as string, URL handle) """
|
""" Returns a tuple (page content as string, URL handle) """
|
||||||
|
|
||||||
# Strip hashes from the URL (#1038)
|
# Strip hashes from the URL (#1038)
|
||||||
if isinstance(url_or_request, (compat_str, str)):
|
if isinstance(url_or_request, (compat_str, str)):
|
||||||
url_or_request = url_or_request.partition('#')[0]
|
url_or_request = url_or_request.partition('#')[0]
|
||||||
|
|
||||||
urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal)
|
urlh = self._request_webpage(url_or_request, video_id, note, errnote)
|
||||||
if urlh is False:
|
|
||||||
assert not fatal
|
|
||||||
return False
|
|
||||||
content_type = urlh.headers.get('Content-Type', '')
|
content_type = urlh.headers.get('Content-Type', '')
|
||||||
webpage_bytes = urlh.read()
|
webpage_bytes = urlh.read()
|
||||||
m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
|
m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
|
||||||
@@ -227,8 +182,6 @@ class InfoExtractor(object):
|
|||||||
webpage_bytes[:1024])
|
webpage_bytes[:1024])
|
||||||
if m:
|
if m:
|
||||||
encoding = m.group(1).decode('ascii')
|
encoding = m.group(1).decode('ascii')
|
||||||
elif webpage_bytes.startswith(b'\xff\xfe'):
|
|
||||||
encoding = 'utf-16'
|
|
||||||
else:
|
else:
|
||||||
encoding = 'utf-8'
|
encoding = 'utf-8'
|
||||||
if self._downloader.params.get('dump_intermediate_pages', False):
|
if self._downloader.params.get('dump_intermediate_pages', False):
|
||||||
@@ -244,71 +197,24 @@ class InfoExtractor(object):
|
|||||||
url = url_or_request.get_full_url()
|
url = url_or_request.get_full_url()
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
url = url_or_request
|
url = url_or_request
|
||||||
basen = '%s_%s' % (video_id, url)
|
raw_filename = ('%s_%s.dump' % (video_id, url))
|
||||||
if len(basen) > 240:
|
|
||||||
h = u'___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
|
|
||||||
basen = basen[:240 - len(h)] + h
|
|
||||||
raw_filename = basen + '.dump'
|
|
||||||
filename = sanitize_filename(raw_filename, restricted=True)
|
filename = sanitize_filename(raw_filename, restricted=True)
|
||||||
self.to_screen(u'Saving request to ' + filename)
|
self.to_screen(u'Saving request to ' + filename)
|
||||||
with open(filename, 'wb') as outf:
|
with open(filename, 'wb') as outf:
|
||||||
outf.write(webpage_bytes)
|
outf.write(webpage_bytes)
|
||||||
|
|
||||||
try:
|
content = webpage_bytes.decode(encoding, 'replace')
|
||||||
content = webpage_bytes.decode(encoding, 'replace')
|
|
||||||
except LookupError:
|
|
||||||
content = webpage_bytes.decode('utf-8', 'replace')
|
|
||||||
|
|
||||||
if (u'<title>Access to this site is blocked</title>' in content and
|
|
||||||
u'Websense' in content[:512]):
|
|
||||||
msg = u'Access to this webpage has been blocked by Websense filtering software in your network.'
|
|
||||||
blocked_iframe = self._html_search_regex(
|
|
||||||
r'<iframe src="([^"]+)"', content,
|
|
||||||
u'Websense information URL', default=None)
|
|
||||||
if blocked_iframe:
|
|
||||||
msg += u' Visit %s for more details' % blocked_iframe
|
|
||||||
raise ExtractorError(msg, expected=True)
|
|
||||||
|
|
||||||
return (content, urlh)
|
return (content, urlh)
|
||||||
|
|
||||||
def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
|
def _download_webpage(self, url_or_request, video_id, note=None, errnote=None):
|
||||||
""" Returns the data of the page as a string """
|
""" Returns the data of the page as a string """
|
||||||
res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal)
|
return self._download_webpage_handle(url_or_request, video_id, note, errnote)[0]
|
||||||
if res is False:
|
|
||||||
return res
|
|
||||||
else:
|
|
||||||
content, _ = res
|
|
||||||
return content
|
|
||||||
|
|
||||||
def _download_xml(self, url_or_request, video_id,
|
def _download_xml(self, url_or_request, video_id, note=u'Downloading XML', errnote=u'Unable to downloand XML'):
|
||||||
note=u'Downloading XML', errnote=u'Unable to download XML',
|
|
||||||
transform_source=None, fatal=True):
|
|
||||||
"""Return the xml as an xml.etree.ElementTree.Element"""
|
"""Return the xml as an xml.etree.ElementTree.Element"""
|
||||||
xml_string = self._download_webpage(
|
xml_string = self._download_webpage(url_or_request, video_id, note, errnote)
|
||||||
url_or_request, video_id, note, errnote, fatal=fatal)
|
|
||||||
if xml_string is False:
|
|
||||||
return xml_string
|
|
||||||
if transform_source:
|
|
||||||
xml_string = transform_source(xml_string)
|
|
||||||
return xml.etree.ElementTree.fromstring(xml_string.encode('utf-8'))
|
return xml.etree.ElementTree.fromstring(xml_string.encode('utf-8'))
|
||||||
|
|
||||||
def _download_json(self, url_or_request, video_id,
|
|
||||||
note=u'Downloading JSON metadata',
|
|
||||||
errnote=u'Unable to download JSON metadata',
|
|
||||||
transform_source=None):
|
|
||||||
json_string = self._download_webpage(url_or_request, video_id, note, errnote)
|
|
||||||
if transform_source:
|
|
||||||
json_string = transform_source(json_string)
|
|
||||||
try:
|
|
||||||
return json.loads(json_string)
|
|
||||||
except ValueError as ve:
|
|
||||||
raise ExtractorError('Failed to download JSON', cause=ve)
|
|
||||||
|
|
||||||
def report_warning(self, msg, video_id=None):
|
|
||||||
idstr = u'' if video_id is None else u'%s: ' % video_id
|
|
||||||
self._downloader.report_warning(
|
|
||||||
u'[%s] %s%s' % (self.IE_NAME, idstr, msg))
|
|
||||||
|
|
||||||
def to_screen(self, msg):
|
def to_screen(self, msg):
|
||||||
"""Print msg to screen, prefixing it with '[ie_name]'"""
|
"""Print msg to screen, prefixing it with '[ie_name]'"""
|
||||||
self._downloader.to_screen(u'[%s] %s' % (self.IE_NAME, msg))
|
self._downloader.to_screen(u'[%s] %s' % (self.IE_NAME, msg))
|
||||||
@@ -330,8 +236,7 @@ class InfoExtractor(object):
|
|||||||
self.to_screen(u'Logging in')
|
self.to_screen(u'Logging in')
|
||||||
|
|
||||||
#Methods for following #608
|
#Methods for following #608
|
||||||
@staticmethod
|
def url_result(self, url, ie=None, video_id=None):
|
||||||
def url_result(url, ie=None, video_id=None):
|
|
||||||
"""Returns a url that points to a page that should be processed"""
|
"""Returns a url that points to a page that should be processed"""
|
||||||
#TODO: ie should be the class used for getting the info
|
#TODO: ie should be the class used for getting the info
|
||||||
video_info = {'_type': 'url',
|
video_info = {'_type': 'url',
|
||||||
@@ -340,8 +245,7 @@ class InfoExtractor(object):
|
|||||||
if video_id is not None:
|
if video_id is not None:
|
||||||
video_info['id'] = video_id
|
video_info['id'] = video_id
|
||||||
return video_info
|
return video_info
|
||||||
@staticmethod
|
def playlist_result(self, entries, playlist_id=None, playlist_title=None):
|
||||||
def playlist_result(entries, playlist_id=None, playlist_title=None):
|
|
||||||
"""Returns a playlist"""
|
"""Returns a playlist"""
|
||||||
video_info = {'_type': 'playlist',
|
video_info = {'_type': 'playlist',
|
||||||
'entries': entries}
|
'entries': entries}
|
||||||
@@ -351,7 +255,7 @@ class InfoExtractor(object):
|
|||||||
video_info['title'] = playlist_title
|
video_info['title'] = playlist_title
|
||||||
return video_info
|
return video_info
|
||||||
|
|
||||||
def _search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0):
|
def _search_regex(self, pattern, string, name, default=None, fatal=True, flags=0):
|
||||||
"""
|
"""
|
||||||
Perform a regex search on the given string, using a single or a list of
|
Perform a regex search on the given string, using a single or a list of
|
||||||
patterns returning the first matching group.
|
patterns returning the first matching group.
|
||||||
@@ -365,7 +269,7 @@ class InfoExtractor(object):
|
|||||||
mobj = re.search(p, string, flags)
|
mobj = re.search(p, string, flags)
|
||||||
if mobj: break
|
if mobj: break
|
||||||
|
|
||||||
if os.name != 'nt' and sys.stderr.isatty():
|
if sys.stderr.isatty() and os.name != 'nt':
|
||||||
_name = u'\033[0;34m%s\033[0m' % name
|
_name = u'\033[0;34m%s\033[0m' % name
|
||||||
else:
|
else:
|
||||||
_name = name
|
_name = name
|
||||||
@@ -373,7 +277,7 @@ class InfoExtractor(object):
|
|||||||
if mobj:
|
if mobj:
|
||||||
# return the first matching group
|
# return the first matching group
|
||||||
return next(g for g in mobj.groups() if g is not None)
|
return next(g for g in mobj.groups() if g is not None)
|
||||||
elif default is not _NO_DEFAULT:
|
elif default is not None:
|
||||||
return default
|
return default
|
||||||
elif fatal:
|
elif fatal:
|
||||||
raise RegexNotFoundError(u'Unable to extract %s' % _name)
|
raise RegexNotFoundError(u'Unable to extract %s' % _name)
|
||||||
@@ -382,7 +286,7 @@ class InfoExtractor(object):
|
|||||||
u'please report this issue on http://yt-dl.org/bug' % _name)
|
u'please report this issue on http://yt-dl.org/bug' % _name)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _html_search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0):
|
def _html_search_regex(self, pattern, string, name, default=None, fatal=True, flags=0):
|
||||||
"""
|
"""
|
||||||
Like _search_regex, but strips HTML tags and unescapes entities.
|
Like _search_regex, but strips HTML tags and unescapes entities.
|
||||||
"""
|
"""
|
||||||
@@ -425,8 +329,8 @@ class InfoExtractor(object):
|
|||||||
# Helper functions for extracting OpenGraph info
|
# Helper functions for extracting OpenGraph info
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _og_regexes(prop):
|
def _og_regexes(prop):
|
||||||
content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')'
|
content_re = r'content=(?:"([^>]+?)"|\'(.+?)\')'
|
||||||
property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop)
|
property_re = r'property=[\'"]og:%s[\'"]' % re.escape(prop)
|
||||||
template = r'<meta[^>]+?%s[^>]+?%s'
|
template = r'<meta[^>]+?%s[^>]+?%s'
|
||||||
return [
|
return [
|
||||||
template % (property_re, content_re),
|
template % (property_re, content_re),
|
||||||
@@ -455,14 +359,13 @@ class InfoExtractor(object):
|
|||||||
if secure: regexes = self._og_regexes('video:secure_url') + regexes
|
if secure: regexes = self._og_regexes('video:secure_url') + regexes
|
||||||
return self._html_search_regex(regexes, html, name, **kargs)
|
return self._html_search_regex(regexes, html, name, **kargs)
|
||||||
|
|
||||||
def _html_search_meta(self, name, html, display_name=None, fatal=False):
|
def _html_search_meta(self, name, html, display_name=None):
|
||||||
if display_name is None:
|
if display_name is None:
|
||||||
display_name = name
|
display_name = name
|
||||||
return self._html_search_regex(
|
return self._html_search_regex(
|
||||||
r'''(?ix)<meta
|
r'''(?ix)<meta(?=[^>]+(?:name|property)=["\']%s["\'])
|
||||||
(?=[^>]+(?:itemprop|name|property)=["\']%s["\'])
|
|
||||||
[^>]+content=["\']([^"\']+)["\']''' % re.escape(name),
|
[^>]+content=["\']([^"\']+)["\']''' % re.escape(name),
|
||||||
html, display_name, fatal=fatal)
|
html, display_name, fatal=False)
|
||||||
|
|
||||||
def _dc_search_uploader(self, html):
|
def _dc_search_uploader(self, html):
|
||||||
return self._html_search_meta('dc.creator', html, 'uploader')
|
return self._html_search_meta('dc.creator', html, 'uploader')
|
||||||
@@ -491,82 +394,6 @@ class InfoExtractor(object):
|
|||||||
}
|
}
|
||||||
return RATING_TABLE.get(rating.lower(), None)
|
return RATING_TABLE.get(rating.lower(), None)
|
||||||
|
|
||||||
def _twitter_search_player(self, html):
|
|
||||||
return self._html_search_meta('twitter:player', html,
|
|
||||||
'twitter card player')
|
|
||||||
|
|
||||||
def _sort_formats(self, formats):
|
|
||||||
if not formats:
|
|
||||||
raise ExtractorError(u'No video formats found')
|
|
||||||
|
|
||||||
def _formats_key(f):
|
|
||||||
# TODO remove the following workaround
|
|
||||||
from ..utils import determine_ext
|
|
||||||
if not f.get('ext') and 'url' in f:
|
|
||||||
f['ext'] = determine_ext(f['url'])
|
|
||||||
|
|
||||||
preference = f.get('preference')
|
|
||||||
if preference is None:
|
|
||||||
proto = f.get('protocol')
|
|
||||||
if proto is None:
|
|
||||||
proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
|
|
||||||
|
|
||||||
preference = 0 if proto in ['http', 'https'] else -0.1
|
|
||||||
if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
|
|
||||||
preference -= 0.5
|
|
||||||
|
|
||||||
if f.get('vcodec') == 'none': # audio only
|
|
||||||
if self._downloader.params.get('prefer_free_formats'):
|
|
||||||
ORDER = [u'aac', u'mp3', u'm4a', u'webm', u'ogg', u'opus']
|
|
||||||
else:
|
|
||||||
ORDER = [u'webm', u'opus', u'ogg', u'mp3', u'aac', u'm4a']
|
|
||||||
ext_preference = 0
|
|
||||||
try:
|
|
||||||
audio_ext_preference = ORDER.index(f['ext'])
|
|
||||||
except ValueError:
|
|
||||||
audio_ext_preference = -1
|
|
||||||
else:
|
|
||||||
if self._downloader.params.get('prefer_free_formats'):
|
|
||||||
ORDER = [u'flv', u'mp4', u'webm']
|
|
||||||
else:
|
|
||||||
ORDER = [u'webm', u'flv', u'mp4']
|
|
||||||
try:
|
|
||||||
ext_preference = ORDER.index(f['ext'])
|
|
||||||
except ValueError:
|
|
||||||
ext_preference = -1
|
|
||||||
audio_ext_preference = 0
|
|
||||||
|
|
||||||
return (
|
|
||||||
preference,
|
|
||||||
f.get('quality') if f.get('quality') is not None else -1,
|
|
||||||
f.get('height') if f.get('height') is not None else -1,
|
|
||||||
f.get('width') if f.get('width') is not None else -1,
|
|
||||||
ext_preference,
|
|
||||||
f.get('tbr') if f.get('tbr') is not None else -1,
|
|
||||||
f.get('vbr') if f.get('vbr') is not None else -1,
|
|
||||||
f.get('abr') if f.get('abr') is not None else -1,
|
|
||||||
audio_ext_preference,
|
|
||||||
f.get('filesize') if f.get('filesize') is not None else -1,
|
|
||||||
f.get('format_id'),
|
|
||||||
)
|
|
||||||
formats.sort(key=_formats_key)
|
|
||||||
|
|
||||||
def http_scheme(self):
|
|
||||||
""" Either "https:" or "https:", depending on the user's preferences """
|
|
||||||
return (
|
|
||||||
'http:'
|
|
||||||
if self._downloader.params.get('prefer_insecure', False)
|
|
||||||
else 'https:')
|
|
||||||
|
|
||||||
def _proto_relative_url(self, url, scheme=None):
|
|
||||||
if url is None:
|
|
||||||
return url
|
|
||||||
if url.startswith('//'):
|
|
||||||
if scheme is None:
|
|
||||||
scheme = self.http_scheme()
|
|
||||||
return scheme + url
|
|
||||||
else:
|
|
||||||
return url
|
|
||||||
|
|
||||||
|
|
||||||
class SearchInfoExtractor(InfoExtractor):
|
class SearchInfoExtractor(InfoExtractor):
|
||||||
@@ -611,4 +438,3 @@ class SearchInfoExtractor(InfoExtractor):
|
|||||||
@property
|
@property
|
||||||
def SEARCH_KEY(self):
|
def SEARCH_KEY(self):
|
||||||
return self._SEARCH_KEY
|
return self._SEARCH_KEY
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
# coding: utf-8
|
# coding: utf-8
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
@@ -21,33 +20,30 @@ class CondeNastIE(InfoExtractor):
|
|||||||
|
|
||||||
# The keys are the supported sites and the values are the name to be shown
|
# The keys are the supported sites and the values are the name to be shown
|
||||||
# to the user and in the extractor description.
|
# to the user and in the extractor description.
|
||||||
_SITES = {
|
_SITES = {'wired': u'WIRED',
|
||||||
'wired': 'WIRED',
|
'gq': u'GQ',
|
||||||
'gq': 'GQ',
|
'vogue': u'Vogue',
|
||||||
'vogue': 'Vogue',
|
'glamour': u'Glamour',
|
||||||
'glamour': 'Glamour',
|
'wmagazine': u'W Magazine',
|
||||||
'wmagazine': 'W Magazine',
|
'vanityfair': u'Vanity Fair',
|
||||||
'vanityfair': 'Vanity Fair',
|
}
|
||||||
'cnevids': 'Condé Nast',
|
|
||||||
}
|
|
||||||
|
|
||||||
_VALID_URL = r'http://(video|www|player)\.(?P<site>%s)\.com/(?P<type>watch|series|video|embed)/(?P<id>[^/?#]+)' % '|'.join(_SITES.keys())
|
_VALID_URL = r'http://(video|www).(?P<site>%s).com/(?P<type>watch|series|video)/(?P<id>.+)' % '|'.join(_SITES.keys())
|
||||||
IE_DESC = 'Condé Nast media group: %s' % ', '.join(sorted(_SITES.values()))
|
IE_DESC = u'Condé Nast media group: %s' % ', '.join(sorted(_SITES.values()))
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://video.wired.com/watch/3d-printed-speakers-lit-with-led',
|
u'url': u'http://video.wired.com/watch/3d-printed-speakers-lit-with-led',
|
||||||
'md5': '1921f713ed48aabd715691f774c451f7',
|
u'file': u'5171b343c2b4c00dd0c1ccb3.mp4',
|
||||||
'info_dict': {
|
u'md5': u'1921f713ed48aabd715691f774c451f7',
|
||||||
'id': '5171b343c2b4c00dd0c1ccb3',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u'title': u'3D Printed Speakers Lit With LED',
|
||||||
'title': '3D Printed Speakers Lit With LED',
|
u'description': u'Check out these beautiful 3D printed LED speakers. You can\'t actually buy them, but LumiGeek is working on a board that will let you make you\'re own.',
|
||||||
'description': 'Check out these beautiful 3D printed LED speakers. You can\'t actually buy them, but LumiGeek is working on a board that will let you make you\'re own.',
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
def _extract_series(self, url, webpage):
|
def _extract_series(self, url, webpage):
|
||||||
title = self._html_search_regex(r'<div class="cne-series-info">.*?<h1>(.+?)</h1>',
|
title = self._html_search_regex(r'<div class="cne-series-info">.*?<h1>(.+?)</h1>',
|
||||||
webpage, 'series title', flags=re.DOTALL)
|
webpage, u'series title', flags=re.DOTALL)
|
||||||
url_object = compat_urllib_parse_urlparse(url)
|
url_object = compat_urllib_parse_urlparse(url)
|
||||||
base_url = '%s://%s' % (url_object.scheme, url_object.netloc)
|
base_url = '%s://%s' % (url_object.scheme, url_object.netloc)
|
||||||
m_paths = re.finditer(r'<p class="cne-thumb-title">.*?<a href="(/watch/.+?)["\?]',
|
m_paths = re.finditer(r'<p class="cne-thumb-title">.*?<a href="(/watch/.+?)["\?]',
|
||||||
@@ -57,60 +53,54 @@ class CondeNastIE(InfoExtractor):
|
|||||||
entries = [self.url_result(build_url(path), 'CondeNast') for path in paths]
|
entries = [self.url_result(build_url(path), 'CondeNast') for path in paths]
|
||||||
return self.playlist_result(entries, playlist_title=title)
|
return self.playlist_result(entries, playlist_title=title)
|
||||||
|
|
||||||
def _extract_video(self, webpage, url_type):
|
def _extract_video(self, webpage):
|
||||||
if url_type != 'embed':
|
description = self._html_search_regex([r'<div class="cne-video-description">(.+?)</div>',
|
||||||
description = self._html_search_regex(
|
r'<div class="video-post-content">(.+?)</div>',
|
||||||
[
|
],
|
||||||
r'<div class="cne-video-description">(.+?)</div>',
|
webpage, u'description',
|
||||||
r'<div class="video-post-content">(.+?)</div>',
|
fatal=False, flags=re.DOTALL)
|
||||||
],
|
|
||||||
webpage, 'description', fatal=False, flags=re.DOTALL)
|
|
||||||
else:
|
|
||||||
description = None
|
|
||||||
params = self._search_regex(r'var params = {(.+?)}[;,]', webpage,
|
params = self._search_regex(r'var params = {(.+?)}[;,]', webpage,
|
||||||
'player params', flags=re.DOTALL)
|
u'player params', flags=re.DOTALL)
|
||||||
video_id = self._search_regex(r'videoId: [\'"](.+?)[\'"]', params, 'video id')
|
video_id = self._search_regex(r'videoId: [\'"](.+?)[\'"]', params, u'video id')
|
||||||
player_id = self._search_regex(r'playerId: [\'"](.+?)[\'"]', params, 'player id')
|
player_id = self._search_regex(r'playerId: [\'"](.+?)[\'"]', params, u'player id')
|
||||||
target = self._search_regex(r'target: [\'"](.+?)[\'"]', params, 'target')
|
target = self._search_regex(r'target: [\'"](.+?)[\'"]', params, u'target')
|
||||||
data = compat_urllib_parse.urlencode({'videoId': video_id,
|
data = compat_urllib_parse.urlencode({'videoId': video_id,
|
||||||
'playerId': player_id,
|
'playerId': player_id,
|
||||||
'target': target,
|
'target': target,
|
||||||
})
|
})
|
||||||
base_info_url = self._search_regex(r'url = [\'"](.+?)[\'"][,;]',
|
base_info_url = self._search_regex(r'url = [\'"](.+?)[\'"][,;]',
|
||||||
webpage, 'base info url',
|
webpage, u'base info url',
|
||||||
default='http://player.cnevids.com/player/loader.js?')
|
default='http://player.cnevids.com/player/loader.js?')
|
||||||
info_url = base_info_url + data
|
info_url = base_info_url + data
|
||||||
info_page = self._download_webpage(info_url, video_id,
|
info_page = self._download_webpage(info_url, video_id,
|
||||||
'Downloading video info')
|
u'Downloading video info')
|
||||||
video_info = self._search_regex(r'var video = ({.+?});', info_page, 'video info')
|
video_info = self._search_regex(r'var video = ({.+?});', info_page, u'video info')
|
||||||
video_info = json.loads(video_info)
|
video_info = json.loads(video_info)
|
||||||
|
|
||||||
formats = [{
|
def _formats_sort_key(f):
|
||||||
'format_id': '%s-%s' % (fdata['type'].split('/')[-1], fdata['quality']),
|
type_ord = 1 if f['type'] == 'video/mp4' else 0
|
||||||
'url': fdata['src'],
|
quality_ord = 1 if f['quality'] == 'high' else 0
|
||||||
'ext': fdata['type'].split('/')[-1],
|
return (quality_ord, type_ord)
|
||||||
'quality': 1 if fdata['quality'] == 'high' else 0,
|
best_format = sorted(video_info['sources'][0], key=_formats_sort_key)[-1]
|
||||||
} for fdata in video_info['sources'][0]]
|
|
||||||
self._sort_formats(formats)
|
|
||||||
|
|
||||||
return {
|
return {'id': video_id,
|
||||||
'id': video_id,
|
'url': best_format['src'],
|
||||||
'formats': formats,
|
'ext': best_format['type'].split('/')[-1],
|
||||||
'title': video_info['title'],
|
'title': video_info['title'],
|
||||||
'thumbnail': video_info['poster_frame'],
|
'thumbnail': video_info['poster_frame'],
|
||||||
'description': description,
|
'description': description,
|
||||||
}
|
}
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
site = mobj.group('site')
|
site = mobj.group('site')
|
||||||
url_type = mobj.group('type')
|
url_type = mobj.group('type')
|
||||||
item_id = mobj.group('id')
|
id = mobj.group('id')
|
||||||
|
|
||||||
self.to_screen('Extracting from %s with the Condé Nast extractor' % self._SITES[site])
|
self.to_screen(u'Extracting from %s with the Condé Nast extractor' % self._SITES[site])
|
||||||
webpage = self._download_webpage(url, item_id)
|
webpage = self._download_webpage(url, id)
|
||||||
|
|
||||||
if url_type == 'series':
|
if url_type == 'series':
|
||||||
return self._extract_series(url, webpage)
|
return self._extract_series(url, webpage)
|
||||||
else:
|
else:
|
||||||
return self._extract_video(webpage, url_type)
|
return self._extract_video(webpage)
|
||||||
|
|||||||
@@ -1,188 +0,0 @@
|
|||||||
# encoding: utf-8
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
import json
|
|
||||||
import base64
|
|
||||||
import zlib
|
|
||||||
|
|
||||||
from hashlib import sha1
|
|
||||||
from math import pow, sqrt, floor
|
|
||||||
from .common import InfoExtractor
|
|
||||||
from ..utils import (
|
|
||||||
ExtractorError,
|
|
||||||
compat_urllib_parse,
|
|
||||||
compat_urllib_request,
|
|
||||||
bytes_to_intlist,
|
|
||||||
intlist_to_bytes,
|
|
||||||
unified_strdate,
|
|
||||||
clean_html,
|
|
||||||
)
|
|
||||||
from ..aes import (
|
|
||||||
aes_cbc_decrypt,
|
|
||||||
inc,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class CrunchyrollIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?:[^/]*/[^/?&]*?|media/\?id=)(?P<video_id>[0-9]+))(?:[/?&]|$)'
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
|
|
||||||
#'md5': 'b1639fd6ddfaa43788c85f6d1dddd412',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '645513',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
|
|
||||||
'description': 'md5:2d17137920c64f2f49981a7797d275ef',
|
|
||||||
'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
|
|
||||||
'uploader': 'Yomiuri Telecasting Corporation (YTV)',
|
|
||||||
'upload_date': '20131013',
|
|
||||||
},
|
|
||||||
'params': {
|
|
||||||
# rtmp
|
|
||||||
'skip_download': True,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
_FORMAT_IDS = {
|
|
||||||
'360': ('60', '106'),
|
|
||||||
'480': ('61', '106'),
|
|
||||||
'720': ('62', '106'),
|
|
||||||
'1080': ('80', '108'),
|
|
||||||
}
|
|
||||||
|
|
||||||
def _decrypt_subtitles(self, data, iv, id):
|
|
||||||
data = bytes_to_intlist(data)
|
|
||||||
iv = bytes_to_intlist(iv)
|
|
||||||
id = int(id)
|
|
||||||
|
|
||||||
def obfuscate_key_aux(count, modulo, start):
|
|
||||||
output = list(start)
|
|
||||||
for _ in range(count):
|
|
||||||
output.append(output[-1] + output[-2])
|
|
||||||
# cut off start values
|
|
||||||
output = output[2:]
|
|
||||||
output = list(map(lambda x: x % modulo + 33, output))
|
|
||||||
return output
|
|
||||||
|
|
||||||
def obfuscate_key(key):
|
|
||||||
num1 = int(floor(pow(2, 25) * sqrt(6.9)))
|
|
||||||
num2 = (num1 ^ key) << 5
|
|
||||||
num3 = key ^ num1
|
|
||||||
num4 = num3 ^ (num3 >> 3) ^ num2
|
|
||||||
prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
|
|
||||||
shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
|
|
||||||
# Extend 160 Bit hash to 256 Bit
|
|
||||||
return shaHash + [0] * 12
|
|
||||||
|
|
||||||
key = obfuscate_key(id)
|
|
||||||
class Counter:
|
|
||||||
__value = iv
|
|
||||||
def next_value(self):
|
|
||||||
temp = self.__value
|
|
||||||
self.__value = inc(self.__value)
|
|
||||||
return temp
|
|
||||||
decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
|
|
||||||
return zlib.decompress(decrypted_data)
|
|
||||||
|
|
||||||
def _convert_subtitles_to_srt(self, subtitles):
|
|
||||||
output = ''
|
|
||||||
for i, (start, end, text) in enumerate(re.findall(r'<event [^>]*?start="([^"]+)" [^>]*?end="([^"]+)" [^>]*?text="([^"]+)"[^>]*?>', subtitles), 1):
|
|
||||||
start = start.replace('.', ',')
|
|
||||||
end = end.replace('.', ',')
|
|
||||||
text = clean_html(text)
|
|
||||||
text = text.replace('\\N', '\n')
|
|
||||||
if not text:
|
|
||||||
continue
|
|
||||||
output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
|
|
||||||
return output
|
|
||||||
|
|
||||||
def _real_extract(self,url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('video_id')
|
|
||||||
|
|
||||||
if mobj.group('prefix') == 'm':
|
|
||||||
mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
|
|
||||||
webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
|
|
||||||
else:
|
|
||||||
webpage_url = 'http://www.' + mobj.group('url')
|
|
||||||
|
|
||||||
webpage = self._download_webpage(webpage_url, video_id, 'Downloading webpage')
|
|
||||||
note_m = self._html_search_regex(r'<div class="showmedia-trailer-notice">(.+?)</div>', webpage, 'trailer-notice', default='')
|
|
||||||
if note_m:
|
|
||||||
raise ExtractorError(note_m)
|
|
||||||
|
|
||||||
mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
|
|
||||||
if mobj:
|
|
||||||
msg = json.loads(mobj.group('msg'))
|
|
||||||
if msg.get('type') == 'error':
|
|
||||||
raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
|
|
||||||
|
|
||||||
video_title = self._html_search_regex(r'<h1[^>]*>(.+?)</h1>', webpage, 'video_title', flags=re.DOTALL)
|
|
||||||
video_title = re.sub(r' {2,}', ' ', video_title)
|
|
||||||
video_description = self._html_search_regex(r'"description":"([^"]+)', webpage, 'video_description', default='')
|
|
||||||
if not video_description:
|
|
||||||
video_description = None
|
|
||||||
video_upload_date = self._html_search_regex(r'<div>Availability for free users:(.+?)</div>', webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
|
|
||||||
if video_upload_date:
|
|
||||||
video_upload_date = unified_strdate(video_upload_date)
|
|
||||||
video_uploader = self._html_search_regex(r'<div>\s*Publisher:(.+?)</div>', webpage, 'video_uploader', fatal=False, flags=re.DOTALL)
|
|
||||||
|
|
||||||
playerdata_url = compat_urllib_parse.unquote(self._html_search_regex(r'"config_url":"([^"]+)', webpage, 'playerdata_url'))
|
|
||||||
playerdata_req = compat_urllib_request.Request(playerdata_url)
|
|
||||||
playerdata_req.data = compat_urllib_parse.urlencode({'current_page': webpage_url})
|
|
||||||
playerdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
|
|
||||||
playerdata = self._download_webpage(playerdata_req, video_id, note='Downloading media info')
|
|
||||||
|
|
||||||
stream_id = self._search_regex(r'<media_id>([^<]+)', playerdata, 'stream_id')
|
|
||||||
video_thumbnail = self._search_regex(r'<episode_image_url>([^<]+)', playerdata, 'thumbnail', fatal=False)
|
|
||||||
|
|
||||||
formats = []
|
|
||||||
for fmt in re.findall(r'\?p([0-9]{3,4})=1', webpage):
|
|
||||||
stream_quality, stream_format = self._FORMAT_IDS[fmt]
|
|
||||||
video_format = fmt+'p'
|
|
||||||
streamdata_req = compat_urllib_request.Request('http://www.crunchyroll.com/xml/')
|
|
||||||
# urlencode doesn't work!
|
|
||||||
streamdata_req.data = 'req=RpcApiVideoEncode%5FGetStreamInfo&video%5Fencode%5Fquality='+stream_quality+'&media%5Fid='+stream_id+'&video%5Fformat='+stream_format
|
|
||||||
streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
|
|
||||||
streamdata_req.add_header('Content-Length', str(len(streamdata_req.data)))
|
|
||||||
streamdata = self._download_webpage(streamdata_req, video_id, note='Downloading media info for '+video_format)
|
|
||||||
video_url = self._search_regex(r'<host>([^<]+)', streamdata, 'video_url')
|
|
||||||
video_play_path = self._search_regex(r'<file>([^<]+)', streamdata, 'video_play_path')
|
|
||||||
formats.append({
|
|
||||||
'url': video_url,
|
|
||||||
'play_path': video_play_path,
|
|
||||||
'ext': 'flv',
|
|
||||||
'format': video_format,
|
|
||||||
'format_id': video_format,
|
|
||||||
})
|
|
||||||
|
|
||||||
subtitles = {}
|
|
||||||
for sub_id, sub_name in re.findall(r'\?ssid=([0-9]+)" title="([^"]+)', webpage):
|
|
||||||
sub_page = self._download_webpage('http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id='+sub_id,\
|
|
||||||
video_id, note='Downloading subtitles for '+sub_name)
|
|
||||||
id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
|
|
||||||
iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
|
|
||||||
data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
|
|
||||||
if not id or not iv or not data:
|
|
||||||
continue
|
|
||||||
id = int(id)
|
|
||||||
iv = base64.b64decode(iv)
|
|
||||||
data = base64.b64decode(data)
|
|
||||||
|
|
||||||
subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
|
|
||||||
lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
|
|
||||||
if not lang_code:
|
|
||||||
continue
|
|
||||||
subtitles[lang_code] = self._convert_subtitles_to_srt(subtitle)
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': video_id,
|
|
||||||
'title': video_title,
|
|
||||||
'description': video_description,
|
|
||||||
'thumbnail': video_thumbnail,
|
|
||||||
'uploader': video_uploader,
|
|
||||||
'upload_date': video_upload_date,
|
|
||||||
'subtitles': subtitles,
|
|
||||||
'formats': formats,
|
|
||||||
}
|
|
||||||
@@ -1,83 +1,51 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import (
|
from ..utils import (
|
||||||
int_or_none,
|
compat_urllib_parse,
|
||||||
unescapeHTML,
|
|
||||||
find_xpath_attr,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class CSpanIE(InfoExtractor):
|
class CSpanIE(InfoExtractor):
|
||||||
_VALID_URL = r'http://(?:www\.)?c-span\.org/video/\?(?P<id>[0-9a-f]+)'
|
_VALID_URL = r'http://www.c-spanvideo.org/program/(.*)'
|
||||||
IE_DESC = 'C-SPAN'
|
_TEST = {
|
||||||
_TESTS = [{
|
u'url': u'http://www.c-spanvideo.org/program/HolderonV',
|
||||||
'url': 'http://www.c-span.org/video/?313572-1/HolderonV',
|
u'file': u'315139.flv',
|
||||||
'md5': '8e44ce11f0f725527daccc453f553eb0',
|
u'md5': u'74a623266956f69e4df0068ab6c80fe4',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'id': '315139',
|
u"title": u"Attorney General Eric Holder on Voting Rights Act Decision"
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'Attorney General Eric Holder on Voting Rights Act Decision',
|
|
||||||
'description': 'Attorney General Eric Holder spoke to reporters following the Supreme Court decision in Shelby County v. Holder in which the court ruled that the preclearance provisions of the Voting Rights Act could not be enforced until Congress established new guidelines for review.',
|
|
||||||
},
|
},
|
||||||
'skip': 'Regularly fails on travis, for unknown reasons',
|
u'skip': u'Requires rtmpdump'
|
||||||
}, {
|
}
|
||||||
'url': 'http://www.c-span.org/video/?c4486943/cspan-international-health-care-models',
|
|
||||||
# For whatever reason, the served video alternates between
|
|
||||||
# two different ones
|
|
||||||
#'md5': 'dbb0f047376d457f2ab8b3929cbb2d0c',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '340723',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'International Health Care Models',
|
|
||||||
'description': 'md5:7a985a2d595dba00af3d9c9f0783c967',
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
page_id = mobj.group('id')
|
prog_name = mobj.group(1)
|
||||||
webpage = self._download_webpage(url, page_id)
|
webpage = self._download_webpage(url, prog_name)
|
||||||
video_id = self._search_regex(r'progid=\'?([0-9]+)\'?>', webpage, 'video id')
|
video_id = self._search_regex(r'programid=(.*?)&', webpage, 'video id')
|
||||||
|
data = compat_urllib_parse.urlencode({'programid': video_id,
|
||||||
|
'dynamic':'1'})
|
||||||
|
info_url = 'http://www.c-spanvideo.org/common/services/flashXml.php?' + data
|
||||||
|
video_info = self._download_webpage(info_url, video_id, u'Downloading video info')
|
||||||
|
|
||||||
description = self._html_search_regex(
|
self.report_extraction(video_id)
|
||||||
[
|
|
||||||
# The full description
|
|
||||||
r'<div class=\'expandable\'>(.*?)<a href=\'#\'',
|
|
||||||
# If the description is small enough the other div is not
|
|
||||||
# present, otherwise this is a stripped version
|
|
||||||
r'<p class=\'initial\'>(.*?)</p>'
|
|
||||||
],
|
|
||||||
webpage, 'description', flags=re.DOTALL)
|
|
||||||
|
|
||||||
info_url = 'http://c-spanvideo.org/videoLibrary/assets/player/ajax-player.php?os=android&html5=program&id=' + video_id
|
title = self._html_search_regex(r'<string name="title">(.*?)</string>',
|
||||||
data = self._download_json(info_url, video_id)
|
video_info, 'title')
|
||||||
|
description = self._html_search_regex(r'<meta (?:property="og:|name=")description" content="(.*?)"',
|
||||||
|
webpage, 'description',
|
||||||
|
flags=re.MULTILINE|re.DOTALL)
|
||||||
|
|
||||||
doc = self._download_xml(
|
url = self._search_regex(r'<string name="URL">(.*?)</string>',
|
||||||
'http://www.c-span.org/common/services/flashXml.php?programid=' + video_id,
|
video_info, 'video url')
|
||||||
video_id)
|
url = url.replace('$(protocol)', 'rtmp').replace('$(port)', '443')
|
||||||
|
path = self._search_regex(r'<string name="path">(.*?)</string>',
|
||||||
|
video_info, 'rtmp play path')
|
||||||
|
|
||||||
title = find_xpath_attr(doc, './/string', 'name', 'title').text
|
return {'id': video_id,
|
||||||
thumbnail = find_xpath_attr(doc, './/string', 'name', 'poster').text
|
'title': title,
|
||||||
|
'ext': 'flv',
|
||||||
files = data['video']['files']
|
'url': url,
|
||||||
|
'play_path': path,
|
||||||
entries = [{
|
'description': description,
|
||||||
'id': '%s_%d' % (video_id, partnum + 1),
|
'thumbnail': self._og_search_thumbnail(webpage),
|
||||||
'title': (
|
}
|
||||||
title if len(files) == 1 else
|
|
||||||
'%s part %d' % (title, partnum + 1)),
|
|
||||||
'url': unescapeHTML(f['path']['#text']),
|
|
||||||
'description': description,
|
|
||||||
'thumbnail': thumbnail,
|
|
||||||
'duration': int_or_none(f.get('length', {}).get('#text')),
|
|
||||||
} for partnum, f in enumerate(files)]
|
|
||||||
|
|
||||||
return {
|
|
||||||
'_type': 'playlist',
|
|
||||||
'entries': entries,
|
|
||||||
'title': title,
|
|
||||||
'id': video_id,
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,25 +1,22 @@
|
|||||||
# encoding: utf-8
|
# encoding: utf-8
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
from .canalplus import CanalplusIE
|
from .canalplus import CanalplusIE
|
||||||
|
|
||||||
|
|
||||||
class D8IE(CanalplusIE):
|
class D8IE(CanalplusIE):
|
||||||
_VALID_URL = r'https?://www\.d8\.tv/.*?/(?P<path>.*)'
|
_VALID_URL = r'https?://www\.d8\.tv/.*?/(?P<path>.*)'
|
||||||
_VIDEO_INFO_TEMPLATE = 'http://service.canal-plus.com/video/rest/getVideosLiees/d8/%s'
|
_VIDEO_INFO_TEMPLATE = 'http://service.canal-plus.com/video/rest/getVideosLiees/d8/%s'
|
||||||
IE_NAME = 'd8.tv'
|
IE_NAME = u'd8.tv'
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://www.d8.tv/d8-docs-mags/pid6589-d8-campagne-intime.html',
|
u'url': u'http://www.d8.tv/d8-docs-mags/pid6589-d8-campagne-intime.html',
|
||||||
'file': '966289.flv',
|
u'file': u'966289.flv',
|
||||||
'info_dict': {
|
u'info_dict': {
|
||||||
'title': 'Campagne intime - Documentaire exceptionnel',
|
u'title': u'Campagne intime - Documentaire exceptionnel',
|
||||||
'description': 'md5:d2643b799fb190846ae09c61e59a859f',
|
u'description': u'md5:d2643b799fb190846ae09c61e59a859f',
|
||||||
'upload_date': '20131108',
|
u'upload_date': u'20131108',
|
||||||
},
|
},
|
||||||
'params': {
|
u'params': {
|
||||||
# rtmp
|
# rtmp
|
||||||
'skip_download': True,
|
u'skip_download': True,
|
||||||
},
|
},
|
||||||
'skip': 'videos get deleted after a while',
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,11 +8,11 @@ from .subtitles import SubtitlesInfoExtractor
|
|||||||
from ..utils import (
|
from ..utils import (
|
||||||
compat_urllib_request,
|
compat_urllib_request,
|
||||||
compat_str,
|
compat_str,
|
||||||
|
get_element_by_attribute,
|
||||||
|
get_element_by_id,
|
||||||
orderedSet,
|
orderedSet,
|
||||||
str_to_int,
|
|
||||||
int_or_none,
|
|
||||||
ExtractorError,
|
ExtractorError,
|
||||||
unescapeHTML,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
class DailymotionBaseInfoExtractor(InfoExtractor):
|
class DailymotionBaseInfoExtractor(InfoExtractor):
|
||||||
@@ -27,7 +27,7 @@ class DailymotionBaseInfoExtractor(InfoExtractor):
|
|||||||
class DailymotionIE(DailymotionBaseInfoExtractor, SubtitlesInfoExtractor):
|
class DailymotionIE(DailymotionBaseInfoExtractor, SubtitlesInfoExtractor):
|
||||||
"""Information Extractor for Dailymotion"""
|
"""Information Extractor for Dailymotion"""
|
||||||
|
|
||||||
_VALID_URL = r'(?i)(?:https?://)?(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(embed|#)/)?video/(?P<id>[^/?_]+)'
|
_VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/(?:embed/)?video/([^/]+)'
|
||||||
IE_NAME = u'dailymotion'
|
IE_NAME = u'dailymotion'
|
||||||
|
|
||||||
_FORMATS = [
|
_FORMATS = [
|
||||||
@@ -80,7 +80,7 @@ class DailymotionIE(DailymotionBaseInfoExtractor, SubtitlesInfoExtractor):
|
|||||||
# Extract id and simplified title from URL
|
# Extract id and simplified title from URL
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
|
|
||||||
video_id = mobj.group('id')
|
video_id = mobj.group(1).split('_')[0].split('?')[0]
|
||||||
|
|
||||||
url = 'http://www.dailymotion.com/video/%s' % video_id
|
url = 'http://www.dailymotion.com/video/%s' % video_id
|
||||||
|
|
||||||
@@ -100,6 +100,10 @@ class DailymotionIE(DailymotionBaseInfoExtractor, SubtitlesInfoExtractor):
|
|||||||
self.to_screen(u'Vevo video detected: %s' % vevo_id)
|
self.to_screen(u'Vevo video detected: %s' % vevo_id)
|
||||||
return self.url_result(u'vevo:%s' % vevo_id, ie='Vevo')
|
return self.url_result(u'vevo:%s' % vevo_id, ie='Vevo')
|
||||||
|
|
||||||
|
video_uploader = self._search_regex([r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>',
|
||||||
|
# Looking for official user
|
||||||
|
r'<(?:span|a) .*?rel="author".*?>([^<]+?)</'],
|
||||||
|
webpage, 'video uploader', fatal=False)
|
||||||
age_limit = self._rta_search(webpage)
|
age_limit = self._rta_search(webpage)
|
||||||
|
|
||||||
video_upload_date = None
|
video_upload_date = None
|
||||||
@@ -123,7 +127,7 @@ class DailymotionIE(DailymotionBaseInfoExtractor, SubtitlesInfoExtractor):
|
|||||||
if video_url is not None:
|
if video_url is not None:
|
||||||
m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
|
m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
|
||||||
if m_size is not None:
|
if m_size is not None:
|
||||||
width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
|
width, height = m_size.group(1), m_size.group(2)
|
||||||
else:
|
else:
|
||||||
width, height = None, None
|
width, height = None, None
|
||||||
formats.append({
|
formats.append({
|
||||||
@@ -142,21 +146,15 @@ class DailymotionIE(DailymotionBaseInfoExtractor, SubtitlesInfoExtractor):
|
|||||||
self._list_available_subtitles(video_id, webpage)
|
self._list_available_subtitles(video_id, webpage)
|
||||||
return
|
return
|
||||||
|
|
||||||
view_count = self._search_regex(
|
|
||||||
r'video_views_count[^>]+>\s+([\d\.,]+)', webpage, u'view count', fatal=False)
|
|
||||||
if view_count is not None:
|
|
||||||
view_count = str_to_int(view_count)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
'formats': formats,
|
'formats': formats,
|
||||||
'uploader': info['owner_screenname'],
|
'uploader': video_uploader,
|
||||||
'upload_date': video_upload_date,
|
'upload_date': video_upload_date,
|
||||||
'title': self._og_search_title(webpage),
|
'title': self._og_search_title(webpage),
|
||||||
'subtitles': video_subtitles,
|
'subtitles': video_subtitles,
|
||||||
'thumbnail': info['thumbnail_url'],
|
'thumbnail': info['thumbnail_url'],
|
||||||
'age_limit': age_limit,
|
'age_limit': age_limit,
|
||||||
'view_count': view_count,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def _get_available_subtitles(self, video_id, webpage):
|
def _get_available_subtitles(self, video_id, webpage):
|
||||||
@@ -178,7 +176,7 @@ class DailymotionIE(DailymotionBaseInfoExtractor, SubtitlesInfoExtractor):
|
|||||||
class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
|
class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
|
||||||
IE_NAME = u'dailymotion:playlist'
|
IE_NAME = u'dailymotion:playlist'
|
||||||
_VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>.+?)/'
|
_VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>.+?)/'
|
||||||
_MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
|
_MORE_PAGES_INDICATOR = r'<div class="next">.*?<a.*?href="/playlist/.+?".*?>.*?</a>.*?</div>'
|
||||||
_PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
|
_PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
|
||||||
|
|
||||||
def _extract_entries(self, id):
|
def _extract_entries(self, id):
|
||||||
@@ -188,9 +186,10 @@ class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
|
|||||||
webpage = self._download_webpage(request,
|
webpage = self._download_webpage(request,
|
||||||
id, u'Downloading page %s' % pagenum)
|
id, u'Downloading page %s' % pagenum)
|
||||||
|
|
||||||
video_ids.extend(re.findall(r'data-xid="(.+?)"', webpage))
|
playlist_el = get_element_by_attribute(u'class', u'row video_list', webpage)
|
||||||
|
video_ids.extend(re.findall(r'data-id="(.+?)"', playlist_el))
|
||||||
|
|
||||||
if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
|
if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
|
||||||
break
|
break
|
||||||
return [self.url_result('http://www.dailymotion.com/video/%s' % video_id, 'Dailymotion')
|
return [self.url_result('http://www.dailymotion.com/video/%s' % video_id, 'Dailymotion')
|
||||||
for video_id in orderedSet(video_ids)]
|
for video_id in orderedSet(video_ids)]
|
||||||
@@ -200,26 +199,26 @@ class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
|
|||||||
playlist_id = mobj.group('id')
|
playlist_id = mobj.group('id')
|
||||||
webpage = self._download_webpage(url, playlist_id)
|
webpage = self._download_webpage(url, playlist_id)
|
||||||
|
|
||||||
return {
|
return {'_type': 'playlist',
|
||||||
'_type': 'playlist',
|
'id': playlist_id,
|
||||||
'id': playlist_id,
|
'title': get_element_by_id(u'playlist_name', webpage),
|
||||||
'title': self._og_search_title(webpage),
|
'entries': self._extract_entries(playlist_id),
|
||||||
'entries': self._extract_entries(playlist_id),
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class DailymotionUserIE(DailymotionPlaylistIE):
|
class DailymotionUserIE(DailymotionPlaylistIE):
|
||||||
IE_NAME = u'dailymotion:user'
|
IE_NAME = u'dailymotion:user'
|
||||||
_VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/user/(?P<user>[^/]+)'
|
_VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/user/(?P<user>[^/]+)'
|
||||||
|
_MORE_PAGES_INDICATOR = r'<div class="next">.*?<a.*?href="/user/.+?".*?>.*?</a>.*?</div>'
|
||||||
_PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
|
_PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
user = mobj.group('user')
|
user = mobj.group('user')
|
||||||
webpage = self._download_webpage(url, user)
|
webpage = self._download_webpage(url, user)
|
||||||
full_user = unescapeHTML(self._html_search_regex(
|
full_user = self._html_search_regex(
|
||||||
r'<a class="nav-image" title="([^"]+)" href="/%s">' % re.escape(user),
|
r'<a class="label" href="/%s".*?>(.*?)</' % re.escape(user),
|
||||||
webpage, u'user', flags=re.DOTALL))
|
webpage, u'user', flags=re.DOTALL)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'_type': 'playlist',
|
'_type': 'playlist',
|
||||||
|
|||||||
@@ -1,28 +1,26 @@
|
|||||||
# encoding: utf-8
|
# encoding: utf-8
|
||||||
|
|
||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import xml.etree.ElementTree
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import (
|
from ..utils import (
|
||||||
compat_urllib_parse,
|
compat_urllib_parse,
|
||||||
|
determine_ext,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class DaumIE(InfoExtractor):
|
class DaumIE(InfoExtractor):
|
||||||
_VALID_URL = r'https?://(?:m\.)?tvpot\.daum\.net/.*?clipid=(?P<id>\d+)'
|
_VALID_URL = r'https?://tvpot\.daum\.net/.*?clipid=(?P<id>\d+)'
|
||||||
IE_NAME = 'daum.net'
|
IE_NAME = u'daum.net'
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://tvpot.daum.net/clip/ClipView.do?clipid=52554690',
|
u'url': u'http://tvpot.daum.net/clip/ClipView.do?clipid=52554690',
|
||||||
'info_dict': {
|
u'file': u'52554690.mp4',
|
||||||
'id': '52554690',
|
u'info_dict': {
|
||||||
'ext': 'mp4',
|
u'title': u'DOTA 2GETHER 시즌2 6회 - 2부',
|
||||||
'title': 'DOTA 2GETHER 시즌2 6회 - 2부',
|
u'description': u'DOTA 2GETHER 시즌2 6회 - 2부',
|
||||||
'description': 'DOTA 2GETHER 시즌2 6회 - 2부',
|
u'upload_date': u'20130831',
|
||||||
'upload_date': '20130831',
|
u'duration': 3868,
|
||||||
'duration': 3868,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,16 +29,17 @@ class DaumIE(InfoExtractor):
|
|||||||
video_id = mobj.group(1)
|
video_id = mobj.group(1)
|
||||||
canonical_url = 'http://tvpot.daum.net/v/%s' % video_id
|
canonical_url = 'http://tvpot.daum.net/v/%s' % video_id
|
||||||
webpage = self._download_webpage(canonical_url, video_id)
|
webpage = self._download_webpage(canonical_url, video_id)
|
||||||
full_id = self._search_regex(
|
full_id = self._search_regex(r'<link rel="video_src" href=".+?vid=(.+?)"',
|
||||||
r'<iframe src="http://videofarm.daum.net/controller/video/viewer/Video.html\?.*?vid=(.+?)[&"]',
|
webpage, u'full id')
|
||||||
webpage, 'full id')
|
|
||||||
query = compat_urllib_parse.urlencode({'vid': full_id})
|
query = compat_urllib_parse.urlencode({'vid': full_id})
|
||||||
info = self._download_xml(
|
info_xml = self._download_webpage(
|
||||||
'http://tvpot.daum.net/clip/ClipInfoXml.do?' + query, video_id,
|
'http://tvpot.daum.net/clip/ClipInfoXml.do?' + query, video_id,
|
||||||
'Downloading video info')
|
u'Downloading video info')
|
||||||
urls = self._download_xml(
|
urls_xml = self._download_webpage(
|
||||||
'http://videofarm.daum.net/controller/api/open/v1_2/MovieData.apixml?' + query,
|
'http://videofarm.daum.net/controller/api/open/v1_2/MovieData.apixml?' + query,
|
||||||
video_id, 'Downloading video formats info')
|
video_id, u'Downloading video formats info')
|
||||||
|
info = xml.etree.ElementTree.fromstring(info_xml.encode('utf-8'))
|
||||||
|
urls = xml.etree.ElementTree.fromstring(urls_xml.encode('utf-8'))
|
||||||
|
|
||||||
self.to_screen(u'%s: Getting video urls' % video_id)
|
self.to_screen(u'%s: Getting video urls' % video_id)
|
||||||
formats = []
|
formats = []
|
||||||
@@ -50,16 +49,18 @@ class DaumIE(InfoExtractor):
|
|||||||
'vid': full_id,
|
'vid': full_id,
|
||||||
'profile': profile,
|
'profile': profile,
|
||||||
})
|
})
|
||||||
url_doc = self._download_xml(
|
url_xml = self._download_webpage(
|
||||||
'http://videofarm.daum.net/controller/api/open/v1_2/MovieLocation.apixml?' + format_query,
|
'http://videofarm.daum.net/controller/api/open/v1_2/MovieLocation.apixml?' + format_query,
|
||||||
video_id, note=False)
|
video_id, note=False)
|
||||||
|
url_doc = xml.etree.ElementTree.fromstring(url_xml.encode('utf-8'))
|
||||||
format_url = url_doc.find('result/url').text
|
format_url = url_doc.find('result/url').text
|
||||||
formats.append({
|
formats.append({
|
||||||
'url': format_url,
|
'url': format_url,
|
||||||
|
'ext': determine_ext(format_url),
|
||||||
'format_id': profile,
|
'format_id': profile,
|
||||||
})
|
})
|
||||||
|
|
||||||
return {
|
info = {
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
'title': info.find('TITLE').text,
|
'title': info.find('TITLE').text,
|
||||||
'formats': formats,
|
'formats': formats,
|
||||||
@@ -68,3 +69,6 @@ class DaumIE(InfoExtractor):
|
|||||||
'duration': int(info.find('DURATION').text),
|
'duration': int(info.find('DURATION').text),
|
||||||
'upload_date': info.find('REGDTTM').text[:8],
|
'upload_date': info.find('REGDTTM').text[:8],
|
||||||
}
|
}
|
||||||
|
# TODO: Remove when #980 has been merged
|
||||||
|
info.update(formats[-1])
|
||||||
|
return info
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
|
|
||||||
@@ -7,14 +5,15 @@ from .common import InfoExtractor
|
|||||||
|
|
||||||
|
|
||||||
class DefenseGouvFrIE(InfoExtractor):
|
class DefenseGouvFrIE(InfoExtractor):
|
||||||
IE_NAME = 'defense.gouv.fr'
|
_IE_NAME = 'defense.gouv.fr'
|
||||||
_VALID_URL = (r'http://.*?\.defense\.gouv\.fr/layout/set/'
|
_VALID_URL = (r'http://.*?\.defense\.gouv\.fr/layout/set/'
|
||||||
r'ligthboxvideo/base-de-medias/webtv/(.*)')
|
r'ligthboxvideo/base-de-medias/webtv/(.*)')
|
||||||
|
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://www.defense.gouv.fr/layout/set/ligthboxvideo/base-de-medias/webtv/attaque-chimique-syrienne-du-21-aout-2013-1',
|
u'url': (u'http://www.defense.gouv.fr/layout/set/ligthboxvideo/'
|
||||||
'file': '11213.mp4',
|
u'base-de-medias/webtv/attaque-chimique-syrienne-du-21-aout-2013-1'),
|
||||||
'md5': '75bba6124da7e63d2d60b5244ec9430c',
|
u'file': u'11213.mp4',
|
||||||
|
u'md5': u'75bba6124da7e63d2d60b5244ec9430c',
|
||||||
"info_dict": {
|
"info_dict": {
|
||||||
"title": "attaque-chimique-syrienne-du-21-aout-2013-1"
|
"title": "attaque-chimique-syrienne-du-21-aout-2013-1"
|
||||||
}
|
}
|
||||||
|
|||||||
60
youtube_dl/extractor/depositfiles.py
Normal file
60
youtube_dl/extractor/depositfiles.py
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import re
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
|
||||||
|
from .common import InfoExtractor
|
||||||
|
from ..utils import (
|
||||||
|
compat_http_client,
|
||||||
|
compat_str,
|
||||||
|
compat_urllib_error,
|
||||||
|
compat_urllib_parse,
|
||||||
|
compat_urllib_request,
|
||||||
|
|
||||||
|
ExtractorError,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class DepositFilesIE(InfoExtractor):
|
||||||
|
"""Information extractor for depositfiles.com"""
|
||||||
|
|
||||||
|
_VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
|
||||||
|
|
||||||
|
def _real_extract(self, url):
|
||||||
|
file_id = url.split('/')[-1]
|
||||||
|
# Rebuild url in english locale
|
||||||
|
url = 'http://depositfiles.com/en/files/' + file_id
|
||||||
|
|
||||||
|
# Retrieve file webpage with 'Free download' button pressed
|
||||||
|
free_download_indication = {'gateway_result' : '1'}
|
||||||
|
request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
|
||||||
|
try:
|
||||||
|
self.report_download_webpage(file_id)
|
||||||
|
webpage = compat_urllib_request.urlopen(request).read()
|
||||||
|
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
|
||||||
|
raise ExtractorError(u'Unable to retrieve file webpage: %s' % compat_str(err))
|
||||||
|
|
||||||
|
# Search for the real file URL
|
||||||
|
mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
|
||||||
|
if (mobj is None) or (mobj.group(1) is None):
|
||||||
|
# Try to figure out reason of the error.
|
||||||
|
mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
|
||||||
|
if (mobj is not None) and (mobj.group(1) is not None):
|
||||||
|
restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
|
||||||
|
raise ExtractorError(u'%s' % restriction_message)
|
||||||
|
else:
|
||||||
|
raise ExtractorError(u'Unable to extract download URL from: %s' % url)
|
||||||
|
|
||||||
|
file_url = mobj.group(1)
|
||||||
|
file_extension = os.path.splitext(file_url)[1][1:]
|
||||||
|
|
||||||
|
# Search for file title
|
||||||
|
file_title = self._search_regex(r'<b title="(.*?)">', webpage, u'title')
|
||||||
|
|
||||||
|
return [{
|
||||||
|
'id': file_id.decode('utf-8'),
|
||||||
|
'url': file_url.decode('utf-8'),
|
||||||
|
'uploader': None,
|
||||||
|
'upload_date': None,
|
||||||
|
'title': file_title,
|
||||||
|
'ext': file_extension.decode('utf-8'),
|
||||||
|
}]
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
|
||||||
import json
|
|
||||||
|
|
||||||
from .common import InfoExtractor
|
|
||||||
|
|
||||||
|
|
||||||
class DiscoveryIE(InfoExtractor):
|
|
||||||
_VALID_URL = r'http://dsc\.discovery\.com\/[a-zA-Z0-9\-]*/[a-zA-Z0-9\-]*/videos/(?P<id>[a-zA-Z0-9\-]*)(.htm)?'
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://dsc.discovery.com/tv-shows/mythbusters/videos/mission-impossible-outtakes.htm',
|
|
||||||
'md5': 'e12614f9ee303a6ccef415cb0793eba2',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '614784',
|
|
||||||
'ext': 'mp4',
|
|
||||||
'title': 'MythBusters: Mission Impossible Outtakes',
|
|
||||||
'description': ('Watch Jamie Hyneman and Adam Savage practice being'
|
|
||||||
' each other -- to the point of confusing Jamie\'s dog -- and '
|
|
||||||
'don\'t miss Adam moon-walking as Jamie ... behind Jamie\'s'
|
|
||||||
' back.'),
|
|
||||||
'duration': 156,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
def _real_extract(self, url):
|
|
||||||
mobj = re.match(self._VALID_URL, url)
|
|
||||||
video_id = mobj.group('id')
|
|
||||||
webpage = self._download_webpage(url, video_id)
|
|
||||||
|
|
||||||
video_list_json = self._search_regex(r'var videoListJSON = ({.*?});',
|
|
||||||
webpage, 'video list', flags=re.DOTALL)
|
|
||||||
video_list = json.loads(video_list_json)
|
|
||||||
info = video_list['clips'][0]
|
|
||||||
formats = []
|
|
||||||
for f in info['mp4']:
|
|
||||||
formats.append(
|
|
||||||
{'url': f['src'], 'ext': 'mp4', 'tbr': int(f['bitrate'][:-1])})
|
|
||||||
|
|
||||||
return {
|
|
||||||
'id': info['contentId'],
|
|
||||||
'title': video_list['name'],
|
|
||||||
'formats': formats,
|
|
||||||
'description': info['videoCaption'],
|
|
||||||
'thumbnail': info.get('videoStillURL') or info.get('thumbnailURL'),
|
|
||||||
'duration': info['duration'],
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
from .novamov import NovaMovIE
|
|
||||||
|
|
||||||
|
|
||||||
class DivxStageIE(NovaMovIE):
|
|
||||||
IE_NAME = 'divxstage'
|
|
||||||
IE_DESC = 'DivxStage'
|
|
||||||
|
|
||||||
_VALID_URL = NovaMovIE._VALID_URL_TEMPLATE % {'host': 'divxstage\.(?:eu|net|ch|co|at|ag)'}
|
|
||||||
|
|
||||||
_HOST = 'www.divxstage.eu'
|
|
||||||
|
|
||||||
_FILE_DELETED_REGEX = r'>This file no longer exists on our servers.<'
|
|
||||||
_TITLE_REGEX = r'<div class="video_det">\s*<strong>([^<]+)</strong>'
|
|
||||||
_DESCRIPTION_REGEX = r'<div class="video_det">\s*<strong>[^<]+</strong>\s*<p>([^<]+)</p>'
|
|
||||||
|
|
||||||
_TEST = {
|
|
||||||
'url': 'http://www.divxstage.eu/video/57f238e2e5e01',
|
|
||||||
'md5': '63969f6eb26533a1968c4d325be63e72',
|
|
||||||
'info_dict': {
|
|
||||||
'id': '57f238e2e5e01',
|
|
||||||
'ext': 'flv',
|
|
||||||
'title': 'youtubedl test video',
|
|
||||||
'description': 'This is a test video for youtubedl.',
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,42 +1,41 @@
|
|||||||
from __future__ import unicode_literals
|
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import json
|
||||||
import time
|
import time
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
|
|
||||||
|
|
||||||
class DotsubIE(InfoExtractor):
|
class DotsubIE(InfoExtractor):
|
||||||
_VALID_URL = r'http://(?:www\.)?dotsub\.com/view/(?P<id>[^/]+)'
|
_VALID_URL = r'(?:http://)?(?:www\.)?dotsub\.com/view/([^/]+)'
|
||||||
_TEST = {
|
_TEST = {
|
||||||
'url': 'http://dotsub.com/view/aed3b8b2-1889-4df5-ae63-ad85f5572f27',
|
u'url': u'http://dotsub.com/view/aed3b8b2-1889-4df5-ae63-ad85f5572f27',
|
||||||
'md5': '0914d4d69605090f623b7ac329fea66e',
|
u'file': u'aed3b8b2-1889-4df5-ae63-ad85f5572f27.flv',
|
||||||
'info_dict': {
|
u'md5': u'0914d4d69605090f623b7ac329fea66e',
|
||||||
'id': 'aed3b8b2-1889-4df5-ae63-ad85f5572f27',
|
u'info_dict': {
|
||||||
'ext': 'flv',
|
u"title": u"Pyramids of Waste (2010), AKA The Lightbulb Conspiracy - Planned obsolescence documentary",
|
||||||
'title': 'Pyramids of Waste (2010), AKA The Lightbulb Conspiracy - Planned obsolescence documentary',
|
u"uploader": u"4v4l0n42",
|
||||||
'uploader': '4v4l0n42',
|
u'description': u'Pyramids of Waste (2010) also known as "The lightbulb conspiracy" is a documentary about how our economic system based on consumerism and planned obsolescence is breaking our planet down.\r\n\r\nSolutions to this can be found at:\r\nhttp://robotswillstealyourjob.com\r\nhttp://www.federicopistono.org\r\n\r\nhttp://opensourceecology.org\r\nhttp://thezeitgeistmovement.com',
|
||||||
'description': 'Pyramids of Waste (2010) also known as "The lightbulb conspiracy" is a documentary about how our economic system based on consumerism and planned obsolescence is breaking our planet down.\r\n\r\nSolutions to this can be found at:\r\nhttp://robotswillstealyourjob.com\r\nhttp://www.federicopistono.org\r\n\r\nhttp://opensourceecology.org\r\nhttp://thezeitgeistmovement.com',
|
u'thumbnail': u'http://dotsub.com/media/aed3b8b2-1889-4df5-ae63-ad85f5572f27/p',
|
||||||
'thumbnail': 'http://dotsub.com/media/aed3b8b2-1889-4df5-ae63-ad85f5572f27/p',
|
u'upload_date': u'20101213',
|
||||||
'upload_date': '20101213',
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
def _real_extract(self, url):
|
def _real_extract(self, url):
|
||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
video_id = mobj.group('id')
|
video_id = mobj.group(1)
|
||||||
info_url = "https://dotsub.com/api/media/%s/metadata" % video_id
|
info_url = "https://dotsub.com/api/media/%s/metadata" %(video_id)
|
||||||
info = self._download_json(info_url, video_id)
|
webpage = self._download_webpage(info_url, video_id)
|
||||||
|
info = json.loads(webpage)
|
||||||
date = time.gmtime(info['dateCreated']/1000) # The timestamp is in miliseconds
|
date = time.gmtime(info['dateCreated']/1000) # The timestamp is in miliseconds
|
||||||
|
|
||||||
return {
|
return [{
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
'url': info['mediaURI'],
|
'url': info['mediaURI'],
|
||||||
'ext': 'flv',
|
'ext': 'flv',
|
||||||
'title': info['title'],
|
'title': info['title'],
|
||||||
'thumbnail': info['screenshotURI'],
|
'thumbnail': info['screenshotURI'],
|
||||||
'description': info['description'],
|
'description': info['description'],
|
||||||
'uploader': info['user'],
|
'uploader': info['user'],
|
||||||
'view_count': info['numberOfViews'],
|
'view_count': info['numberOfViews'],
|
||||||
'upload_date': '%04i%02i%02i' % (date.tm_year, date.tm_mon, date.tm_mday),
|
'upload_date': u'%04i%02i%02i' % (date.tm_year, date.tm_mon, date.tm_mday),
|
||||||
}
|
}]
|
||||||
|
|||||||
@@ -1,20 +1,22 @@
|
|||||||
# coding: utf-8
|
# coding: utf-8
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import xml.etree.ElementTree
|
||||||
|
|
||||||
from .common import InfoExtractor
|
from .common import InfoExtractor
|
||||||
from ..utils import (
|
from ..utils import (
|
||||||
|
determine_ext,
|
||||||
unified_strdate,
|
unified_strdate,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class DreiSatIE(InfoExtractor):
|
class DreiSatIE(InfoExtractor):
|
||||||
IE_NAME = '3sat'
|
IE_NAME = '3sat'
|
||||||
_VALID_URL = r'(?:http://)?(?:www\.)?3sat\.de/mediathek/(?:index\.php)?\?(?:(?:mode|display)=[^&]+&)*obj=(?P<id>[0-9]+)$'
|
_VALID_URL = r'(?:http://)?(?:www\.)?3sat.de/mediathek/index.php\?(?:(?:mode|display)=[^&]+&)*obj=(?P<id>[0-9]+)$'
|
||||||
_TEST = {
|
_TEST = {
|
||||||
u"url": u"http://www.3sat.de/mediathek/index.php?obj=36983",
|
u"url": u"http://www.3sat.de/mediathek/index.php?obj=36983",
|
||||||
u'file': u'36983.mp4',
|
u'file': u'36983.webm',
|
||||||
u'md5': u'9dcfe344732808dbfcc901537973c922',
|
u'md5': u'57c97d0469d71cf874f6815aa2b7c944',
|
||||||
u'info_dict': {
|
u'info_dict': {
|
||||||
u"title": u"Kaffeeland Schweiz",
|
u"title": u"Kaffeeland Schweiz",
|
||||||
u"description": u"Über 80 Kaffeeröstereien liefern in der Schweiz das Getränk, in das das Land so vernarrt ist: Mehr als 1000 Tassen trinkt ein Schweizer pro Jahr. SCHWEIZWEIT nimmt die Kaffeekultur unter die...",
|
u"description": u"Über 80 Kaffeeröstereien liefern in der Schweiz das Getränk, in das das Land so vernarrt ist: Mehr als 1000 Tassen trinkt ein Schweizer pro Jahr. SCHWEIZWEIT nimmt die Kaffeekultur unter die...",
|
||||||
@@ -28,7 +30,8 @@ class DreiSatIE(InfoExtractor):
|
|||||||
mobj = re.match(self._VALID_URL, url)
|
mobj = re.match(self._VALID_URL, url)
|
||||||
video_id = mobj.group('id')
|
video_id = mobj.group('id')
|
||||||
details_url = 'http://www.3sat.de/mediathek/xmlservice/web/beitragsDetails?ak=web&id=%s' % video_id
|
details_url = 'http://www.3sat.de/mediathek/xmlservice/web/beitragsDetails?ak=web&id=%s' % video_id
|
||||||
details_doc = self._download_xml(details_url, video_id, note=u'Downloading video details')
|
details_xml = self._download_webpage(details_url, video_id, note=u'Downloading video details')
|
||||||
|
details_doc = xml.etree.ElementTree.fromstring(details_xml.encode('utf-8'))
|
||||||
|
|
||||||
thumbnail_els = details_doc.findall('.//teaserimage')
|
thumbnail_els = details_doc.findall('.//teaserimage')
|
||||||
thumbnails = [{
|
thumbnails = [{
|
||||||
@@ -51,14 +54,20 @@ class DreiSatIE(InfoExtractor):
|
|||||||
'width': int(fe.find('./width').text),
|
'width': int(fe.find('./width').text),
|
||||||
'height': int(fe.find('./height').text),
|
'height': int(fe.find('./height').text),
|
||||||
'url': fe.find('./url').text,
|
'url': fe.find('./url').text,
|
||||||
|
'ext': determine_ext(fe.find('./url').text),
|
||||||
'filesize': int(fe.find('./filesize').text),
|
'filesize': int(fe.find('./filesize').text),
|
||||||
'video_bitrate': int(fe.find('./videoBitrate').text),
|
'video_bitrate': int(fe.find('./videoBitrate').text),
|
||||||
|
'3sat_qualityname': fe.find('./quality').text,
|
||||||
} for fe in format_els
|
} for fe in format_els
|
||||||
if not fe.find('./url').text.startswith('http://www.metafilegenerator.de/')]
|
if not fe.find('./url').text.startswith('http://www.metafilegenerator.de/')]
|
||||||
|
|
||||||
self._sort_formats(formats)
|
def _sortkey(format):
|
||||||
|
qidx = ['low', 'med', 'high', 'veryhigh'].index(format['3sat_qualityname'])
|
||||||
|
prefer_http = 1 if 'rtmp' in format['url'] else 0
|
||||||
|
return (qidx, prefer_http, format['video_bitrate'])
|
||||||
|
formats.sort(key=_sortkey)
|
||||||
|
|
||||||
return {
|
info = {
|
||||||
'_type': 'video',
|
'_type': 'video',
|
||||||
'id': video_id,
|
'id': video_id,
|
||||||
'title': video_title,
|
'title': video_title,
|
||||||
@@ -69,3 +78,8 @@ class DreiSatIE(InfoExtractor):
|
|||||||
'uploader': video_uploader,
|
'uploader': video_uploader,
|
||||||
'upload_date': upload_date,
|
'upload_date': upload_date,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# TODO: Remove when #980 has been merged
|
||||||
|
info.update(formats[-1])
|
||||||
|
|
||||||
|
return info
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user