Debian Codegraph @

gallery_dl/extractor/tenor.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2025 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://tenor.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13
14 BASE_PATTERN = r"(?:https?://)?tenor\.com/(?:\w\w(?:-\w\w)?/)?"
15
16
17 class TenorExtractor(Extractor):
18 """Base class for tenor extractors"""
19 category = "tenor"
20 root = "https://tenor.com"
21 filename_fmt = "{id}{title:? //}.{extension}"
22 archive_fmt = "{id}"
23 request_interval = (0.5, 1.5)
24
25 def _init(self):
26 formats = self.config("format")
27 if formats is None:
28 self.formats = ("gif", "mp4", "webm", "webp")
29 else:
30 if isinstance(formats, str):
31 formats = formats.split(",")
32 self.formats = formats
33
34 def items(self):
35 for gif in self.gifs():
36
37 if not (fmt := self._extract_format(gif)):
38 self.log.warning("%s: Selected format(s) not available",
39 gif.get("id"))
40 continue
41
42 url = fmt["url"]
43 title = gif.pop("h1_title", "")
44 gif["title"] = title[:-4] if title.endswith(" GIF") else title
45 gif["width"], gif["height"] = fmt.pop("dims") or (0, 0)
46 gif["description"] = gif.pop("content_description", "")
47 gif["id_format"] = url.rsplit("/", 2)[1]
48 gif["format"] = fmt["name"]
49 gif["duration"] = fmt["duration"]
50 gif["size"] = fmt["size"]
51 gif["date"] = self.parse_timestamp(gif["created"])
52
53 yield Message.Directory, "", gif
54 yield Message.Url, url, text.nameext_from_url(url, gif)
55
56 def _extract_format(self, gif):
57 media_formats = gif["media_formats"]
58 for fmt in self.formats:
59 if fmt in media_formats:
60 media = media_formats[fmt]
61 media["name"] = fmt
62 return media
63
64 def _search_results(self, query):
65 url = "https://tenor.googleapis.com/v2/search"
66 params = {
67 "appversion": "browser-r20250225-1",
68 "prettyPrint": "false",
69 "key": "AIzaSyC-P6_qz3FzCoXGLk6tgitZo4jEJ5mLzD8",
70 "client_key": "tenor_web",
71 "locale": "en",
72 "anon_id": "",
73 "q": query,
74 "limit": "50",
75 "contentfilter": "low",
76 "media_filter": "gif,gif_transparent,mediumgif,tinygif,"
77 "tinygif_transparent,webp,webp_transparent,"
78 "tinywebp,tinywebp_transparent,tinymp4,mp4,webm,"
79 "originalgif,gifpreview",
80 "fields": "next,results.id,results.media_formats,results.title,"
81 "results.h1_title,results.long_title,results.itemurl,"
82 "results.url,results.created,results.user,"
83 "results.shares,results.embed,results.hasaudio,"
84 "results.policy_status,results.source_id,results.flags,"
85 "results.tags,results.content_rating,results.bg_color,"
86 "results.legacy_info,results.geographic_restriction,"
87 "results.content_description",
88 "pos": None,
89 "component": "web_desktop",
90 }
91
92 while True:
93 data = self.request_json(url, params=params)
94
95 yield from data["results"]
96
97 params["pos"] = data.get("next")
98 if not params["pos"]:
99 return
100
101 def metadata(self):
102 return False
103
104 def gifs(self):
105 return ()
106
107
108 class TenorImageExtractor(TenorExtractor):
109 subcategory = "image"
110 pattern = BASE_PATTERN + r"view/(?:[^/?#]*-)?(\d+)"
111 example = "https://tenor.com/view/SLUG-1234567890"
112
113 def gifs(self):
114 url = f"{self.root}/view/{self.groups[0]}"
115 page = self.request(url).text
116 pos = page.index('id="store-cache"')
117 data = util.json_loads(text.extract(page, ">", "</script>", pos)[0])
118 return (data["gifs"]["byId"].popitem()[1]["results"][0],)
119
120
121 class TenorSearchExtractor(TenorExtractor):
122 subcategory = "search"
123 directory_fmt = ("{category}", "{search_tags}")
124 pattern = BASE_PATTERN + r"search/([^/?#]+)"
125 example = "https://tenor.com/search/QUERY"
126
127 def gifs(self):
128 query = text.unquote(self.groups[0])
129 rest, _, last = query.rpartition("-")
130 if last == "gifs":
131 query = rest
132 self.kwdict["search_tags"] = search_tags = query.replace("-", " ")
133
134 return self._search_results(search_tags)
135
136
137 class TenorUserExtractor(TenorExtractor):
138 subcategory = "user"
139 directory_fmt = ("{category}", "@{user[username]}")
140 pattern = BASE_PATTERN + r"(?:users|official)/([^/?#]+)"
141 example = "https://tenor.com/users/USER"
142
143 def gifs(self):
144 return self._search_results("@" + self.groups[0])