]> git.phdru.name Git - dotfiles.git/blob - bin/wget-download
Feat(recode-filenames-recursive): Allow to omit parameters
[dotfiles.git] / bin / wget-download
1 #! /usr/bin/env python3
2
3 from getopt import getopt, GetoptError
4 from urllib.parse import urlsplit, parse_qsl, quote, quote_plus, urlencode
5 import os
6 import posixpath
7 import sys
8 from m_lib.defenc import default_encoding
9
10
11 def usage():
12     sys.exit('Usage: %s [-e|--encoding=encoding] [-n|--newwin|-t|--tab] URL'
13              % sys.argv[0])
14
15
16 try:
17     options, arguments = getopt(sys.argv[1:], 'e:', ['encoding='])
18 except GetoptError:
19     usage()
20
21 if len(arguments) != 1:
22     usage()
23
24 encoding = None
25
26 for option, value in options:
27     if option in ('-e', '--encoding'):
28         encoding = value
29
30 if not encoding:
31     encoding = default_encoding
32
33 url = arguments[0]
34
35 split_results = urlsplit(url)
36 protocol, netloc, path, query, tag = split_results
37 user = split_results.username
38 password = split_results.password
39 host = split_results.hostname
40 port = split_results.port
41
42 if query:
43     qlist = []
44     for name, value in parse_qsl(query):
45         if isinstance(name, bytes):
46             name = name.decode(default_encoding)
47             value = value.decode(default_encoding)
48         name = name.encode(encoding)
49         value = value.encode(encoding)
50         qlist.append((name, value))
51
52 url = protocol + "://"
53 if user:
54     if isinstance(user, bytes):
55         user = user.decode(default_encoding)
56     url += quote(user.encode(encoding))
57     if password:
58         if isinstance(password, bytes):
59             password = password.decode(default_encoding)
60         url += ':' + quote(password.encode(encoding))
61     url += '@'
62 if host:
63     if isinstance(host, bytes):
64         host = host.decode(encoding)
65     url += host.encode('idna').decode('ascii')
66     if port:
67         url += ':%d' % port
68 if path:
69     if protocol == "file":
70         url += quote(path)
71     else:
72         if isinstance(path, bytes):
73             path = path.decode(default_encoding)
74         url += quote(path.encode(encoding))
75 if query:
76     url += '?' + urlencode(qlist)
77 if tag:
78     if isinstance(tag, bytes):
79         tag = tag.decode(default_encoding)
80     url += '#' + quote_plus(tag.encode(encoding))
81
82 name = posixpath.basename(path)
83 os.system('exec wget-wrapper -O "%s" "%s"' % (name, url))