2015-04-05 16:23:20 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
# Copyright 2015 Mike Fährmann
|
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License version 2 as
|
|
|
|
# published by the Free Software Foundation.
|
|
|
|
|
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import re
|
|
|
|
import importlib
|
|
|
|
|
2015-04-08 02:30:10 +02:00
|
|
|
from .extractor.common import Message
|
2015-04-05 16:23:20 +02:00
|
|
|
|
|
|
|
class DownloadManager():
|
|
|
|
|
2015-04-09 16:40:54 +02:00
|
|
|
def __init__(self, opts, config):
|
2015-04-05 16:23:20 +02:00
|
|
|
self.opts = opts
|
2015-04-09 16:40:54 +02:00
|
|
|
self.config = config
|
2015-04-08 19:06:50 +02:00
|
|
|
self.modules = {}
|
2015-04-09 16:40:54 +02:00
|
|
|
self.extractors = ExtractorFinder(config)
|
2015-04-08 01:51:48 +02:00
|
|
|
|
|
|
|
def add(self, url):
|
|
|
|
job = DownloadJob(self, url)
|
|
|
|
job.run()
|
|
|
|
|
|
|
|
def get_downloader_module(self, scheme):
|
|
|
|
"""Return a downloader module suitable for 'scheme'"""
|
2015-04-08 19:06:50 +02:00
|
|
|
module = self.modules.get(scheme)
|
2015-04-08 01:51:48 +02:00
|
|
|
if module is None:
|
|
|
|
module = importlib.import_module(".downloader."+scheme, __package__)
|
2015-04-08 19:06:50 +02:00
|
|
|
self.modules[scheme] = module
|
2015-04-08 01:51:48 +02:00
|
|
|
return module
|
2015-04-05 16:23:20 +02:00
|
|
|
|
2015-04-08 01:51:48 +02:00
|
|
|
def get_base_directory(self):
|
2015-04-10 01:21:35 +02:00
|
|
|
"""Return the base-destination-directory for downloads"""
|
2015-04-05 16:23:20 +02:00
|
|
|
if self.opts.dest:
|
2015-04-08 01:51:48 +02:00
|
|
|
return self.opts.dest
|
2015-04-05 16:23:20 +02:00
|
|
|
else:
|
2015-04-09 16:40:54 +02:00
|
|
|
return self.config.get("general", "destination", fallback="/tmp/")
|
2015-04-08 01:51:48 +02:00
|
|
|
|
|
|
|
|
|
|
|
class DownloadJob():
|
|
|
|
|
|
|
|
def __init__(self, mngr, url):
|
|
|
|
self.mngr = mngr
|
|
|
|
self.extractor, self.info = mngr.extractors.get_for_url(url)
|
2015-06-28 12:45:52 +02:00
|
|
|
if self.extractor is None:
|
|
|
|
return
|
2015-04-08 01:51:48 +02:00
|
|
|
self.directory = mngr.get_base_directory()
|
|
|
|
self.downloaders = {}
|
2015-04-09 16:40:54 +02:00
|
|
|
self.filename_fmt = mngr.config.get(
|
|
|
|
self.info["category"], "filename",
|
|
|
|
fallback=self.info["filename"]
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
segments = mngr.config.get(
|
|
|
|
self.info["category"], "directory"
|
|
|
|
).split("/")
|
|
|
|
except Exception:
|
|
|
|
segments = self.info["directory"]
|
|
|
|
self.directory_fmt = os.path.join(*segments)
|
2015-04-08 01:51:48 +02:00
|
|
|
|
|
|
|
def run(self):
|
2015-06-28 12:45:52 +02:00
|
|
|
"""Execute/Run the download job"""
|
2015-04-08 01:51:48 +02:00
|
|
|
if self.extractor is None:
|
|
|
|
return # TODO: error msg
|
|
|
|
|
|
|
|
for msg in self.extractor:
|
|
|
|
if msg[0] == Message.Url:
|
|
|
|
self.download(msg)
|
|
|
|
|
2015-04-08 19:06:50 +02:00
|
|
|
elif msg[0] == Message.Headers:
|
|
|
|
self.get_downloader("http:").set_headers(msg[1])
|
|
|
|
|
|
|
|
elif msg[0] == Message.Cookies:
|
|
|
|
self.get_downloader("http:").set_cookies(msg[1])
|
|
|
|
|
2015-04-08 01:51:48 +02:00
|
|
|
elif msg[0] == Message.Directory:
|
|
|
|
self.set_directory(msg)
|
|
|
|
|
|
|
|
elif msg[0] == Message.Version:
|
|
|
|
if msg[1] != 1:
|
|
|
|
raise "unsupported message-version ({}, {})".format(
|
|
|
|
self.info.category, msg[1]
|
|
|
|
)
|
|
|
|
# TODO: support for multiple message versions
|
|
|
|
|
|
|
|
def download(self, msg):
|
|
|
|
"""Download the resource specified in 'msg'"""
|
|
|
|
_, url, metadata = msg
|
2015-04-09 16:40:54 +02:00
|
|
|
filename = self.filename_fmt.format(**metadata)
|
2015-04-08 01:51:48 +02:00
|
|
|
path = os.path.join(self.directory, filename)
|
|
|
|
if os.path.exists(path):
|
|
|
|
self.print_skip(path)
|
|
|
|
return
|
2015-04-09 16:46:57 +02:00
|
|
|
downloader = self.get_downloader(url)
|
2015-04-08 01:51:48 +02:00
|
|
|
self.print_start(path)
|
2015-04-09 16:46:57 +02:00
|
|
|
tries = downloader.download(url, path)
|
2015-04-08 01:51:48 +02:00
|
|
|
self.print_success(path, tries)
|
|
|
|
|
|
|
|
def set_directory(self, msg):
|
|
|
|
"""Set and create the target directory for downloads"""
|
|
|
|
self.directory = os.path.join(
|
|
|
|
self.mngr.get_base_directory(),
|
2015-04-09 16:40:54 +02:00
|
|
|
self.directory_fmt.format(**msg[1])
|
2015-04-08 01:51:48 +02:00
|
|
|
)
|
|
|
|
os.makedirs(self.directory, exist_ok=True)
|
|
|
|
|
|
|
|
def get_downloader(self, url):
|
|
|
|
"""Return, and possibly construct, a downloader suitable for 'url'"""
|
|
|
|
pos = url.find(":")
|
|
|
|
scheme = url[:pos] if pos != -1 else "http"
|
|
|
|
if scheme == "https":
|
|
|
|
scheme = "http"
|
|
|
|
|
|
|
|
downloader = self.downloaders.get(scheme)
|
|
|
|
if downloader is None:
|
|
|
|
module = self.mngr.get_downloader_module(scheme)
|
2015-04-10 19:19:12 +02:00
|
|
|
downloader = module.Downloader()
|
2015-04-08 01:51:48 +02:00
|
|
|
self.downloaders[scheme] = downloader
|
|
|
|
|
|
|
|
return downloader
|
2015-04-05 16:23:20 +02:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def print_start(path):
|
2015-04-10 01:21:35 +02:00
|
|
|
"""Print a message indicating the start of a download"""
|
2015-04-05 16:23:20 +02:00
|
|
|
print(path, end="")
|
|
|
|
sys.stdout.flush()
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def print_skip(path):
|
2015-04-10 01:21:35 +02:00
|
|
|
"""Print a message indicating that a download has been skipped"""
|
2015-04-05 16:23:20 +02:00
|
|
|
print("\033[2m", path, "\033[0m", sep="")
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def print_success(path, tries):
|
2015-04-10 01:21:35 +02:00
|
|
|
"""Print a message indicating the completion of a download"""
|
2015-04-05 16:23:20 +02:00
|
|
|
if tries == 0:
|
|
|
|
print("\r", end="")
|
|
|
|
print("\r\033[1;32m", path, "\033[0m", sep="")
|
|
|
|
|
|
|
|
|
|
|
|
class ExtractorFinder():
|
|
|
|
|
|
|
|
def __init__(self, config):
|
|
|
|
self.config = config
|
|
|
|
|
2015-04-08 01:51:48 +02:00
|
|
|
def get_for_url(self, url):
|
2015-06-28 12:45:52 +02:00
|
|
|
"""Get an extractor-instance suitable for 'url'"""
|
2015-04-09 16:13:00 +02:00
|
|
|
name, match = self.find_pattern_match(url)
|
|
|
|
if match:
|
|
|
|
module = importlib.import_module(".extractor." + name, __package__)
|
|
|
|
klass = getattr(module, module.info["extractor"])
|
|
|
|
return klass(match, self.config), module.info
|
|
|
|
else:
|
2015-06-28 12:45:52 +02:00
|
|
|
print("no suitable extractor found")
|
|
|
|
return None, None
|
2015-04-05 16:23:20 +02:00
|
|
|
|
2015-04-09 16:13:00 +02:00
|
|
|
def find_pattern_match(self, url):
|
2015-04-10 01:21:35 +02:00
|
|
|
"""Find a pattern, that matches 'url', and return the (category,match) tuple"""
|
2015-04-09 16:13:00 +02:00
|
|
|
for category in self.config:
|
|
|
|
for key, value in self.config[category].items():
|
2015-04-09 16:46:57 +02:00
|
|
|
if key.startswith("regex"):
|
2015-04-09 16:13:00 +02:00
|
|
|
match = re.match(value, url)
|
|
|
|
if match:
|
|
|
|
return category, match
|
2015-04-10 01:21:35 +02:00
|
|
|
for category, info in self.extractor_metadata():
|
2015-04-09 16:13:00 +02:00
|
|
|
for pattern in info["pattern"]:
|
|
|
|
match = re.match(pattern, url)
|
|
|
|
if match:
|
2015-04-10 01:21:35 +02:00
|
|
|
return category, match
|
2015-04-09 16:46:57 +02:00
|
|
|
return None, None
|
2015-04-09 16:13:00 +02:00
|
|
|
|
|
|
|
def extractor_metadata(self):
|
2015-04-10 01:21:35 +02:00
|
|
|
"""Yield all extractor-name, -metadata tuples"""
|
2015-04-09 16:13:00 +02:00
|
|
|
path = os.path.join(os.path.dirname(__file__), "extractor")
|
|
|
|
for name in os.listdir(path):
|
|
|
|
extractor_path = os.path.join(path, name)
|
|
|
|
info = self.get_info_dict(extractor_path)
|
|
|
|
if info is not None:
|
|
|
|
yield os.path.splitext(name)[0], info
|
2015-04-05 16:23:20 +02:00
|
|
|
|
2015-04-09 16:13:00 +02:00
|
|
|
@staticmethod
|
|
|
|
def get_info_dict(extractor_path):
|
2015-04-10 01:21:35 +02:00
|
|
|
"""Get info-/metadata-dictionary for an extractor"""
|
2015-04-05 16:23:20 +02:00
|
|
|
try:
|
2015-04-09 16:46:57 +02:00
|
|
|
with open(extractor_path) as file:
|
|
|
|
for _ in range(30):
|
|
|
|
line = next(file)
|
2015-04-09 16:13:00 +02:00
|
|
|
if line.startswith("info ="):
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
info = [line[6:]]
|
2015-04-09 16:46:57 +02:00
|
|
|
for line in file:
|
2015-04-09 16:13:00 +02:00
|
|
|
info.append(line)
|
|
|
|
if line.startswith("}"):
|
|
|
|
break
|
|
|
|
except (StopIteration, OSError):
|
|
|
|
return None
|
|
|
|
return eval("".join(info))
|