Skip to content

Commit

Permalink
[newgrounds] extend 'format' option (#5709)
Browse files Browse the repository at this point in the history
- check more extensions for original formats (mp4, webm, m4v, mov, mkv)
- allow specifying which extensions and recoded formats to check
  • Loading branch information
mikf committed Jun 12, 2024
1 parent 86f0c3b commit c6fc028
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 32 deletions.
10 changes: 8 additions & 2 deletions docs/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2758,17 +2758,23 @@ Description
extractor.newgrounds.format
---------------------------
Type
``string``
* ``string``
* ``list`` of ``string``
Default
``"original"``
Example
``"720p"``
* ``"720p"``
* ``["mp4", "mov", "1080p", "720p"]``
Description
Selects the preferred format for video downloads.

If the selected format is not available,
the next smaller one gets chosen.

If this is a ``list``, try each given
filename extension in original resolution or recoded format
until an available format is found.


extractor.newgrounds.include
----------------------------
Expand Down
68 changes: 39 additions & 29 deletions gallery_dl/extractor/newgrounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from .. import text, util, exception
from ..cache import cache
import itertools
import re


class NewgroundsExtractor(Extractor):
Expand All @@ -33,10 +34,16 @@ def __init__(self, match):
def _init(self):
self.flash = self.config("flash", True)

fmt = self.config("format", "original")
self.format = (True if not fmt or fmt == "original" else
fmt if isinstance(fmt, int) else
text.parse_int(fmt.rstrip("p")))
fmt = self.config("format")
if not fmt or fmt == "original":
self.format = ("mp4", "webm", "m4v", "mov", "mkv",
1080, 720, 360)
elif isinstance(fmt, (list, tuple)):
self.format = fmt
else:
self._video_formats = self._video_formats_limit
self.format = (fmt if isinstance(fmt, int) else
text.parse_int(fmt.rstrip("p")))

def items(self):
self.login()
Expand Down Expand Up @@ -266,7 +273,7 @@ def _extract_media_data(self, extr, url):

if src:
src = src.replace("\\/", "/")
fallback = ()
formats = ()
date = text.parse_datetime(extr(
'itemprop="datePublished" content="', '"'))
else:
Expand All @@ -276,23 +283,8 @@ def _extract_media_data(self, extr, url):
"X-Requested-With": "XMLHttpRequest",
}
sources = self.request(url, headers=headers).json()["sources"]

if self.format is True:
src = sources["360p"][0]["src"].replace(".360p.", ".")
formats = sources
else:
formats = []
for fmt, src in sources.items():
width = text.parse_int(fmt.rstrip("p"))
if width <= self.format:
formats.append((width, src))
if formats:
formats.sort(reverse=True)
src, formats = formats[0][1][0]["src"], formats[1:]
else:
src = ""

fallback = self._video_fallback(formats)
formats = self._video_formats(sources)
src = next(formats, "")
date = text.parse_timestamp(src.rpartition("?")[2])

return {
Expand All @@ -306,15 +298,33 @@ def _extract_media_data(self, extr, url):
"rating" : extr('class="rated-', '"'),
"index" : text.parse_int(index),
"_index" : index,
"_fallback" : fallback,
"_fallback" : formats,
}

@staticmethod
def _video_fallback(formats):
if isinstance(formats, dict):
formats = list(formats.items())
formats.sort(key=lambda fmt: text.parse_int(fmt[0].rstrip("p")),
reverse=True)
def _video_formats(self, sources):
src = sources["360p"][0]["src"]
sub = re.compile(r"\.360p\.\w+").sub

for fmt in self.format:
try:
if isinstance(fmt, int):
yield sources[str(fmt) + "p"][0]["src"]
elif fmt in sources:
yield sources[fmt][0]["src"]
else:
yield sub("." + fmt, src, 1)
except Exception as exc:
self.log.debug("Video format '%s' not available (%s: %s)",
fmt, exc.__class__.__name__, exc)

def _video_formats_limit(self, sources):
formats = []
for fmt, src in sources.items():
width = text.parse_int(fmt.rstrip("p"))
if width <= self.format:
formats.append((width, src))

formats.sort(reverse=True)
for fmt in formats:
yield fmt[1][0]["src"]

Expand Down
18 changes: 17 additions & 1 deletion test/results/newgrounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@
"#url" : "https://www.newgrounds.com/portal/view/595355",
"#category": ("", "newgrounds", "media"),
"#class" : newgrounds.NewgroundsMediaExtractor,
"#pattern" : r"https://uploads\.ungrounded\.net/alternate/564000/564957_alternate_31\.mp4\?1359712249",
"#urls" : "https://uploads.ungrounded.net/alternate/564000/564957_alternate_31.mp4?1359712249",

"artist" : [
"kickinthehead",
Expand All @@ -131,6 +131,22 @@
"user" : "kickinthehead",
},

{
"#url" : "https://www.newgrounds.com/portal/view/595355",
"#category": ("", "newgrounds", "media"),
"#class" : newgrounds.NewgroundsMediaExtractor,
"#options" : {"format": ["mkv", "mov", 1080]},
"#urls" : "https://uploads.ungrounded.net/alternate/564000/564957_alternate_31.mkv?1359712249",
},

{
"#url" : "https://www.newgrounds.com/portal/view/595355",
"#category": ("", "newgrounds", "media"),
"#class" : newgrounds.NewgroundsMediaExtractor,
"#options" : {"format": "720p"},
"#urls" : "https://uploads.ungrounded.net/alternate/564000/564957_alternate_31.720p.mp4?1359712249",
},

{
"#url" : "https://www.newgrounds.com/audio/listen/609768",
"#category": ("", "newgrounds", "media"),
Expand Down

0 comments on commit c6fc028

Please sign in to comment.