| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# This program is free software; you can redistribute it and/or modify |
| 4 |
# it under the terms of the GNU General Public License version 2 as |
| 5 |
# published by the Free Software Foundation. |
| 6 |
|
| 7 |
"""Generic information extractor""" |
| 8 |
|
| 9 |
from .common import Extractor, Message |
| 10 |
from .. import config, text |
| 11 |
import os.path |
| 12 |
|
| 13 |
|
| 14 |
class GenericExtractor(Extractor): |
| 15 |
"""Extractor for images in a generic web page.""" |
| 16 |
category = "generic" |
| 17 |
directory_fmt = ("{category}", "{subcategory}", "{path}") |
| 18 |
archive_fmt = "{imageurl}" |
| 19 |
|
| 20 |
# By default, the generic extractor is disabled |
| 21 |
# and the "g(eneric):" prefix in url is required. |
| 22 |
# If the extractor is enabled, make the prefix optional |
| 23 |
pattern = r"(?i)(?P<generic>g(?:eneric)?:)" |
| 24 |
if config.get(("extractor", "generic"), "enabled"): |
| 25 |
pattern += r"?" |
| 26 |
|
| 27 |
# The generic extractor pattern should match (almost) any valid url |
| 28 |
# Based on: https://tools.ietf.org/html/rfc3986#appendix-B |
| 29 |
pattern += ( |
| 30 |
r"(?P<scheme>https?://)?" # optional http(s) scheme |
| 31 |
r"(?P<domain>[-\w\.]+)" # required domain |
| 32 |
r"(?P<path>/[^?#]*)?" # optional path |
| 33 |
r"(?:\?(?P<query>[^#]*))?" # optional query |
| 34 |
r"(?:\#(?P<fragment>.*))?" # optional fragment |
| 35 |
) |
| 36 |
example = "generic:https://www.nongnu.org/lzip/" |
| 37 |
|
| 38 |
def __init__(self, match): |
| 39 |
self.subcategory = match['domain'] |
| 40 |
Extractor.__init__(self, match) |
| 41 |
|
| 42 |
# Strip the "g(eneric):" prefix |
| 43 |
# and inform about "forced" or "fallback" mode |
| 44 |
if match['generic']: |
| 45 |
self.url = match[0].partition(":")[2] |
| 46 |
else: |
| 47 |
self.log.info("Falling back on generic information extractor.") |
| 48 |
self.url = match[0] |
| 49 |
|
| 50 |
# Make sure we have a scheme, or use https |
| 51 |
if match['scheme']: |
| 52 |
self.scheme = match['scheme'] |
| 53 |
else: |
| 54 |
self.scheme = 'https://' |
| 55 |
self.url = text.ensure_http_scheme(self.url, self.scheme) |
| 56 |
|
| 57 |
self.path = match['path'] |
| 58 |
|
| 59 |
# Used to resolve relative image urls |
| 60 |
self.root = self.scheme + match['domain'] |
| 61 |
|
| 62 |
def items(self): |
| 63 |
"""Get page, extract metadata & images, yield them in suitable messages |
| 64 |
|
| 65 |
Adapted from common.GalleryExtractor.items() |
| 66 |
|
| 67 |
""" |
| 68 |
page = self.request(self.url).text |
| 69 |
data = self.metadata(page) |
| 70 |
imgs = self.images(page) |
| 71 |
|
| 72 |
try: |
| 73 |
data["count"] = len(imgs) |
| 74 |
except TypeError: |
| 75 |
pass |
| 76 |
images = enumerate(imgs, 1) |
| 77 |
|
| 78 |
yield Message.Directory, "", data |
| 79 |
|
| 80 |
for data["num"], (url, imgdata) in images: |
| 81 |
if imgdata: |
| 82 |
data.update(imgdata) |
| 83 |
if "extension" not in imgdata: |
| 84 |
text.nameext_from_url(url, data) |
| 85 |
else: |
| 86 |
text.nameext_from_url(url, data) |
| 87 |
yield Message.Url, url, data |
| 88 |
|
| 89 |
def metadata(self, page): |
| 90 |
"""Extract generic webpage metadata, return them in a dict.""" |
| 91 |
data = { |
| 92 |
"title" : text.extr( |
| 93 |
page, "<title>", "</title>"), |
| 94 |
"description" : text.extr( |
| 95 |
page, '<meta name="description" content="', '"'), |
| 96 |
"keywords" : text.extr( |
| 97 |
page, '<meta name="keywords" content="', '"'), |
| 98 |
"language" : text.extr( |
| 99 |
page, '<meta name="language" content="', '"'), |
| 100 |
"name" : text.extr( |
| 101 |
page, '<meta itemprop="name" content="', '"'), |
| 102 |
"copyright" : text.extr( |
| 103 |
page, '<meta name="copyright" content="', '"'), |
| 104 |
"og_site" : text.extr( |
| 105 |
page, '<meta property="og:site" content="', '"'), |
| 106 |
"og_site_name" : text.extr( |
| 107 |
page, '<meta property="og:site_name" content="', '"'), |
| 108 |
"og_title" : text.extr( |
| 109 |
page, '<meta property="og:title" content="', '"'), |
| 110 |
"og_description": text.extr( |
| 111 |
page, '<meta property="og:description" content="', '"'), |
| 112 |
|
| 113 |
} |
| 114 |
|
| 115 |
data = {k: text.unescape(v) for k, v in data.items() if v} |
| 116 |
data["path"] = self.path.replace("/", "") |
| 117 |
data["pageurl"] = self.url |
| 118 |
|
| 119 |
return data |
| 120 |
|
| 121 |
def images(self, page): |
| 122 |
"""Extract image urls, return a list of (image url, metadata) tuples. |
| 123 |
|
| 124 |
The extractor aims at finding as many _likely_ image urls as possible, |
| 125 |
using two strategies (see below); since these often overlap, any |
| 126 |
duplicate urls will be removed at the end of the process. |
| 127 |
|
| 128 |
Note: since we are using re.findall() (see below), it's essential that |
| 129 |
the following patterns contain 0 or at most 1 capturing group, so that |
| 130 |
re.findall() return a list of urls (instead of a list of tuples of |
| 131 |
matching groups). All other groups used in the pattern should be |
| 132 |
non-capturing (?:...). |
| 133 |
|
| 134 |
1: Look in src/srcset attributes of img/video/source elements |
| 135 |
|
| 136 |
See: |
| 137 |
https://www.w3schools.com/tags/att_src.asp |
| 138 |
https://www.w3schools.com/tags/att_source_srcset.asp |
| 139 |
|
| 140 |
We allow both absolute and relative urls here. |
| 141 |
|
| 142 |
Note that srcset attributes often contain multiple space separated |
| 143 |
image urls; this pattern matches only the first url; remaining urls |
| 144 |
will be matched by the "imageurl_pattern_ext" pattern below. |
| 145 |
""" |
| 146 |
|
| 147 |
imageurl_pattern_src = ( |
| 148 |
r"(?i)" |
| 149 |
r"<(?:img|video|source)\s[^>]*" # <img>, <video> or <source> |
| 150 |
r"src(?:set)?=[\"']?" # src or srcset attributes |
| 151 |
r"(?P<URL>[^\"'\s>]+)" # url |
| 152 |
) |
| 153 |
|
| 154 |
""" |
| 155 |
2: Look anywhere for urls containing common image/video extensions |
| 156 |
|
| 157 |
The list of allowed extensions is borrowed from the directlink.py |
| 158 |
extractor; other could be added, see |
| 159 |
https://en.wikipedia.org/wiki/List_of_file_formats |
| 160 |
|
| 161 |
Compared to the "pattern" class variable, here we must exclude also |
| 162 |
other special characters (space, ", ', <, >), since we are looking for |
| 163 |
urls in html tags. |
| 164 |
""" |
| 165 |
|
| 166 |
imageurl_pattern_ext = ( |
| 167 |
r"(?i)" |
| 168 |
r"(?:[^?&#\"'>\s]+)" # anything until dot+extension |
| 169 |
# dot + image/video extensions |
| 170 |
r"\.(?:jpe?g|jpe|png|gif|web[mp]|mp4|mkv|og[gmv]|opus)" |
| 171 |
r"(?:[^\"'<>\s]*)?" # optional query and fragment |
| 172 |
) |
| 173 |
|
| 174 |
imageurls_src = text.re(imageurl_pattern_src).findall(page) |
| 175 |
imageurls_ext = text.re(imageurl_pattern_ext).findall(page) |
| 176 |
imageurls = imageurls_src + imageurls_ext |
| 177 |
|
| 178 |
# Resolve relative urls |
| 179 |
# |
| 180 |
# Image urls catched so far may be relative, so we must resolve them |
| 181 |
# by prepending a suitable base url. |
| 182 |
# |
| 183 |
# If the page contains a <base> element, use it as base url |
| 184 |
basematch = text.re( |
| 185 |
r"(?i)(?:<base\s.*?href=[\"']?)(?P<url>[^\"' >]+)").search(page) |
| 186 |
if basematch: |
| 187 |
self.baseurl = basematch['url'].rstrip('/') |
| 188 |
# Otherwise, extract the base url from self.url |
| 189 |
else: |
| 190 |
if self.url.endswith("/"): |
| 191 |
self.baseurl = self.url.rstrip('/') |
| 192 |
else: |
| 193 |
self.baseurl = os.path.dirname(self.url) |
| 194 |
|
| 195 |
# Build the list of absolute image urls |
| 196 |
absimageurls = [] |
| 197 |
for u in imageurls: |
| 198 |
# Absolute urls are taken as-is |
| 199 |
if u.startswith('http'): |
| 200 |
absimageurls.append(u) |
| 201 |
# // relative urls are prefixed with current scheme |
| 202 |
elif u.startswith('//'): |
| 203 |
absimageurls.append(self.scheme + u.lstrip('/')) |
| 204 |
# / relative urls are prefixed with current scheme+domain |
| 205 |
elif u.startswith('/'): |
| 206 |
absimageurls.append(self.root + u) |
| 207 |
# other relative urls are prefixed with baseurl |
| 208 |
else: |
| 209 |
absimageurls.append(self.baseurl + '/' + u) |
| 210 |
|
| 211 |
# Remove duplicates |
| 212 |
absimageurls = dict.fromkeys(absimageurls) |
| 213 |
|
| 214 |
# Create the image metadata dict and add imageurl to it |
| 215 |
# (image filename and extension are added by items()) |
| 216 |
images = [(u, {'imageurl': u}) for u in absimageurls] |
| 217 |
|
| 218 |
return images |