| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2020-2026 Mike Fährmann |
| 4 |
# |
| 5 |
# This program is free software; you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License version 2 as |
| 7 |
# published by the Free Software Foundation. |
| 8 |
|
| 9 |
"""Extractors for https://redgifs.com/""" |
| 10 |
|
| 11 |
from .common import Extractor, Message |
| 12 |
from .. import text |
| 13 |
|
| 14 |
|
| 15 |
class RedgifsExtractor(Extractor): |
| 16 |
"""Base class for redgifs extractors""" |
| 17 |
category = "redgifs" |
| 18 |
filename_fmt = \ |
| 19 |
"{category}_{gallery:?//[:11]}{num:?_/_/>02}{id}.{extension}" |
| 20 |
archive_fmt = "{id}" |
| 21 |
root = "https://www.redgifs.com" |
| 22 |
page_start = 1 |
| 23 |
per_page = 100 |
| 24 |
|
| 25 |
def __init__(self, match): |
| 26 |
Extractor.__init__(self, match) |
| 27 |
self.key = match[1] |
| 28 |
|
| 29 |
def _init(self): |
| 30 |
self.api = RedgifsAPI(self) |
| 31 |
|
| 32 |
formats = self.config("format") |
| 33 |
if formats is None: |
| 34 |
formats = ("hd", "sd", "gif") |
| 35 |
elif isinstance(formats, str): |
| 36 |
formats = (formats, "hd", "sd", "gif") |
| 37 |
self.formats = formats |
| 38 |
|
| 39 |
def items(self): |
| 40 |
metadata = self.metadata() |
| 41 |
|
| 42 |
for gif in self.gifs(): |
| 43 |
|
| 44 |
if gallery := gif.get("gallery"): |
| 45 |
gifs = self.api.gallery(gallery)["gifs"] |
| 46 |
enum = 1 |
| 47 |
cnt = len(gifs) |
| 48 |
else: |
| 49 |
gifs = (gif,) |
| 50 |
enum = 0 |
| 51 |
cnt = 1 |
| 52 |
|
| 53 |
gif.update(metadata) |
| 54 |
gif["count"] = cnt |
| 55 |
gif["date"] = self.parse_timestamp(gif.get("createDate")) |
| 56 |
yield Message.Directory, "", gif |
| 57 |
|
| 58 |
for num, gif in enumerate(gifs, enum): |
| 59 |
gif["_fallback"] = formats = self._formats(gif) |
| 60 |
url = next(formats, None) |
| 61 |
|
| 62 |
if not url: |
| 63 |
self.log.warning( |
| 64 |
"Skipping '%s' (format not available)", gif["id"]) |
| 65 |
continue |
| 66 |
|
| 67 |
gif["num"] = num |
| 68 |
gif["count"] = cnt |
| 69 |
yield Message.Url, url, gif |
| 70 |
|
| 71 |
def _formats(self, gif): |
| 72 |
urls = gif["urls"] |
| 73 |
for fmt in self.formats: |
| 74 |
if url := urls.get(fmt): |
| 75 |
url = url.replace("//thumbs2.", "//thumbs3.", 1) |
| 76 |
text.nameext_from_url(url, gif) |
| 77 |
yield url |
| 78 |
|
| 79 |
def skip_posts(self, num): |
| 80 |
pages = num // self.per_page |
| 81 |
self.page_start += pages |
| 82 |
return pages * self.per_page |
| 83 |
|
| 84 |
def metadata(self): |
| 85 |
return {} |
| 86 |
|
| 87 |
def gifs(self): |
| 88 |
return () |
| 89 |
|
| 90 |
|
| 91 |
class RedgifsUserExtractor(RedgifsExtractor): |
| 92 |
"""Extractor for redgifs user profiles""" |
| 93 |
subcategory = "user" |
| 94 |
directory_fmt = ("{category}", "{userName}") |
| 95 |
pattern = (r"(?:https?://)?(?:\w+\.)?redgifs\.com/users/([^/?#]+)/?" |
| 96 |
r"(?:\?([^#]+))?$") |
| 97 |
example = "https://www.redgifs.com/users/USER" |
| 98 |
|
| 99 |
def metadata(self): |
| 100 |
return {"userName": self.key} |
| 101 |
|
| 102 |
def gifs(self): |
| 103 |
params = text.parse_query(self.groups[1]) |
| 104 |
if pnum := params.get("page"): |
| 105 |
params["page"] = text.parse_int(pnum) |
| 106 |
if type := params.get("type"): |
| 107 |
params["type"] = type[0].lower() |
| 108 |
if "order" not in params: |
| 109 |
params["order"] = "new" |
| 110 |
return self.api.user(self.key, params) |
| 111 |
|
| 112 |
|
| 113 |
class RedgifsCollectionExtractor(RedgifsExtractor): |
| 114 |
"""Extractor for an individual user collection""" |
| 115 |
subcategory = "collection" |
| 116 |
directory_fmt = ( |
| 117 |
"{category}", "{collection[userName]}", "{collection[folderName]}") |
| 118 |
archive_fmt = "{collection[folderId]}_{id}" |
| 119 |
pattern = (r"(?:https?://)?(?:www\.)?redgifs\.com/users" |
| 120 |
r"/([^/?#]+)/collections/([^/?#]+)") |
| 121 |
example = "https://www.redgifs.com/users/USER/collections/ID" |
| 122 |
|
| 123 |
def __init__(self, match): |
| 124 |
RedgifsExtractor.__init__(self, match) |
| 125 |
self.collection_id = match[2] |
| 126 |
|
| 127 |
def metadata(self): |
| 128 |
collection = self.api.collection_info(self.key, self.collection_id) |
| 129 |
collection["userName"] = self.key |
| 130 |
return {"collection": collection} |
| 131 |
|
| 132 |
def gifs(self): |
| 133 |
return self.api.collection(self.key, self.collection_id) |
| 134 |
|
| 135 |
|
| 136 |
class RedgifsCollectionsExtractor(RedgifsExtractor): |
| 137 |
"""Extractor for redgifs user collections""" |
| 138 |
subcategory = "collections" |
| 139 |
pattern = (r"(?:https?://)?(?:www\.)?redgifs\.com/users" |
| 140 |
r"/([^/?#]+)/collections/?$") |
| 141 |
example = "https://www.redgifs.com/users/USER/collections" |
| 142 |
|
| 143 |
def items(self): |
| 144 |
base = f"{self.root}/users/{self.key}/collections/" |
| 145 |
for collection in self.api.collections(self.key): |
| 146 |
url = base + collection["folderId"] |
| 147 |
collection["_extractor"] = RedgifsCollectionExtractor |
| 148 |
yield Message.Queue, url, collection |
| 149 |
|
| 150 |
|
| 151 |
class RedgifsNichesExtractor(RedgifsExtractor): |
| 152 |
"""Extractor for redgifs niches""" |
| 153 |
subcategory = "niches" |
| 154 |
pattern = (r"(?:https?://)?(?:www\.)?redgifs\.com/niches/([^/?#]+)/?" |
| 155 |
r"(?:\?([^#]+))?$") |
| 156 |
example = "https://www.redgifs.com/niches/NAME" |
| 157 |
|
| 158 |
def __init__(self, match): |
| 159 |
RedgifsExtractor.__init__(self, match) |
| 160 |
self.query = match[2] |
| 161 |
|
| 162 |
def gifs(self): |
| 163 |
order = text.parse_query(self.query).get("order") |
| 164 |
return self.api.niches(self.key, order or "new") |
| 165 |
|
| 166 |
|
| 167 |
class RedgifsSearchExtractor(RedgifsExtractor): |
| 168 |
"""Extractor for redgifs search results""" |
| 169 |
subcategory = "search" |
| 170 |
directory_fmt = ("{category}", "Search", "{search}") |
| 171 |
pattern = (r"(?:https?://)?(?:\w+\.)?redgifs\.com" |
| 172 |
r"/(?:gifs/([^/?#]+)|search(?:/gifs)?()|browse)" |
| 173 |
r"(?:/?\?([^#]+))?") |
| 174 |
example = "https://www.redgifs.com/gifs/TAG" |
| 175 |
|
| 176 |
def metadata(self): |
| 177 |
tag, self.search, query = self.groups |
| 178 |
|
| 179 |
self.params = params = text.parse_query(query) |
| 180 |
if tag is not None: |
| 181 |
params["tags"] = text.unquote(tag) |
| 182 |
|
| 183 |
return {"search": (params.get("query") or |
| 184 |
params.get("tags") or |
| 185 |
params.get("order") or |
| 186 |
"trending")} |
| 187 |
|
| 188 |
def gifs(self): |
| 189 |
if self.search is None: |
| 190 |
return self.api.gifs_search(self.params) |
| 191 |
else: |
| 192 |
return self.api.search_gifs(self.params) |
| 193 |
|
| 194 |
|
| 195 |
class RedgifsImageExtractor(RedgifsExtractor): |
| 196 |
"""Extractor for individual gifs from redgifs.com""" |
| 197 |
subcategory = "image" |
| 198 |
pattern = (r"(?:https?://)?(?:" |
| 199 |
r"(?:\w+\.)?redgifs\.com/(?:watch|ifr)|" |
| 200 |
r"(?:\w+\.)?gfycat\.com(?:/gifs/detail|/\w+)?|" |
| 201 |
r"(?:www\.)?gifdeliverynetwork\.com|" |
| 202 |
r"i\.redgifs\.com/i)/([A-Za-z0-9]+)") |
| 203 |
example = "https://redgifs.com/watch/ID" |
| 204 |
|
| 205 |
def gifs(self): |
| 206 |
return (self.api.gif(self.key),) |
| 207 |
|
| 208 |
|
| 209 |
class RedgifsAPI(): |
| 210 |
"""https://api.redgifs.com/docs/index.html""" |
| 211 |
|
| 212 |
API_ROOT = "https://api.redgifs.com" |
| 213 |
|
| 214 |
def __init__(self, extractor): |
| 215 |
self.extractor = extractor |
| 216 |
self.headers = { |
| 217 |
"Accept" : "application/json, text/plain, */*", |
| 218 |
"Authorization": None, |
| 219 |
} |
| 220 |
|
| 221 |
def gif(self, gif_id): |
| 222 |
endpoint = "/v2/gifs/" + gif_id.lower() |
| 223 |
return self._call(endpoint)["gif"] |
| 224 |
|
| 225 |
def gallery(self, gallery_id): |
| 226 |
endpoint = "/v2/gallery/" + gallery_id |
| 227 |
return self._call(endpoint) |
| 228 |
|
| 229 |
def user(self, user, params): |
| 230 |
endpoint = f"/v2/users/{user.lower()}/search" |
| 231 |
return self._pagination(endpoint, params) |
| 232 |
|
| 233 |
def collection(self, user, collection_id): |
| 234 |
endpoint = f"/v2/users/{user}/collections/{collection_id}/gifs" |
| 235 |
return self._pagination(endpoint) |
| 236 |
|
| 237 |
def collection_info(self, user, collection_id): |
| 238 |
endpoint = f"/v2/users/{user}/collections/{collection_id}" |
| 239 |
return self._call(endpoint) |
| 240 |
|
| 241 |
def collections(self, user): |
| 242 |
endpoint = f"/v2/users/{user}/collections" |
| 243 |
return self._pagination(endpoint, key="collections") |
| 244 |
|
| 245 |
def niches(self, niche, order): |
| 246 |
endpoint = f"/v2/niches/{niche}/gifs" |
| 247 |
params = {"count": 30, "order": order} |
| 248 |
return self._pagination(endpoint, params) |
| 249 |
|
| 250 |
def gifs_search(self, params): |
| 251 |
endpoint = "/v2/gifs/search" |
| 252 |
params["search_text"] = params.pop("tags", None) |
| 253 |
return self._pagination(endpoint, params) |
| 254 |
|
| 255 |
def search_gifs(self, params): |
| 256 |
endpoint = "/v2/search/gifs" |
| 257 |
return self._pagination(endpoint, params) |
| 258 |
|
| 259 |
def _call(self, endpoint, params=None): |
| 260 |
url = self.API_ROOT + endpoint |
| 261 |
self.headers["Authorization"] = self.extractor.cache( |
| 262 |
self._auth, _key=None, _exp=600) |
| 263 |
try: |
| 264 |
return self.extractor.request_json( |
| 265 |
url, params=params, headers=self.headers) |
| 266 |
except self.extractor.exc.HttpError as exc: |
| 267 |
self.extractor.log.debug(err := exc.response.text) |
| 268 |
|
| 269 |
msg = "API request failed" |
| 270 |
if err := (text.extr(err, '"message":"', '"') or |
| 271 |
text.extr(err, '"description":"', '"')): |
| 272 |
msg = f'''{msg} ("{err}")''' |
| 273 |
raise self.extractor.exc.AbortExtraction(msg) |
| 274 |
|
| 275 |
def _pagination(self, endpoint, params=None, key="gifs"): |
| 276 |
if params is None: |
| 277 |
params = {} |
| 278 |
if "page" not in params: |
| 279 |
params["page"] = self.extractor.page_start |
| 280 |
params["count"] = self.extractor.per_page |
| 281 |
|
| 282 |
while True: |
| 283 |
data = self._call(endpoint, params) |
| 284 |
yield from data[key] |
| 285 |
|
| 286 |
if params["page"] >= data["pages"]: |
| 287 |
return |
| 288 |
params["page"] += 1 |
| 289 |
|
| 290 |
def _auth(self): |
| 291 |
# https://github.com/Redgifs/api/wiki/Temporary-tokens |
| 292 |
url = self.API_ROOT + "/v2/auth/temporary" |
| 293 |
self.headers["Authorization"] = None |
| 294 |
return "Bearer " + self.extractor.request_json( |
| 295 |
url, headers=self.headers)["token"] |