]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_rurllib_py3.py
Fix(Robots/bkmk_rurllib_py3.py): Restore opener
[bookmarks_db.git] / Robots / bkmk_rurllib_py3.py
1 """Simple, strightforward robot based on urllib
2
3 This file is a part of Bookmarks database and Internet robot.
4
5 """
6
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 2000-2023 PhiloSoft Design"
9 __license__ = "GNU GPL"
10
11 __all__ = ['robot_urllib_py3']
12
13
14 import sys
15 import urllib.request
16
17 from Robots.bkmk_robot_base import robot_base, get_error
18
19
20 class RedirectException(Exception):
21     def __init__(self, errcode, newurl):
22         Exception.__init__(self)
23         self.errcode = errcode
24         self.newurl = newurl
25
26
27 class MyURLopener(urllib.request.URLopener):
28     # Error 301 -- relocated (permanently)
29     def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
30         if 'location' in headers:
31             newurl = headers['location']
32         elif 'uri' in headers:
33             newurl = headers['uri']
34         else:
35             newurl = "Nowhere"
36         raise RedirectException(errcode, newurl)
37
38     # Error 302 -- relocated (temporarily)
39     http_error_302 = http_error_301
40     # Error 303 -- relocated (see other)
41     http_error_303 = http_error_301
42     # Error 307 -- relocated (temporarily)
43     http_error_307 = http_error_301
44
45     # Error 401 -- authentication required
46     def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
47         raise IOError(
48             ('http error', errcode, "Authentication required ", headers))
49
50     def http_error_default(self, url, fp, errcode, errmsg, headers):
51         if fp:
52             fp.read()
53             fp.close()
54         raise IOError(('http error', errcode, errmsg, headers))
55
56
57 urllib.request._opener = opener = MyURLopener()
58
59 # Fake headers to pretend this is a real browser
60 _user_agent = "Mozilla/5.0 (X11; U; Linux 2.6 i686; en)"
61 " Gecko/20001221 Firefox/2.0.0"
62 opener.addheaders[0] = ('User-Agent', _user_agent)
63 _x_user_agent = "bookmarks_db (Python %d.%d.%d; urllib/%s)" % (
64    sys.version_info[0], sys.version_info[1],
65    sys.version_info[2], urllib.request.__version__
66 )
67 opener.addheader('X-User-Agent', _x_user_agent)
68 opener.addheader('Referer', '')
69
70 opener.addheader('Accept', '*/*')
71 opener.addheader('Accept-Language', 'ru,en')
72 opener.addheader('Cache-Control', 'max-age=300')
73 opener.addheader('Connection', 'close')
74
75
76 urllib_ftpwrapper = urllib.request.ftpwrapper
77 ftpcache_key = None
78
79
80 class myftpwrapper(urllib_ftpwrapper):
81     def __init__(self, user, passwd, host, port, dirs):
82         urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
83         global ftpcache_key
84         ftpcache_key = (user, host, port, '/'.join(dirs))
85
86
87 urllib.request.ftpwrapper = myftpwrapper
88
89
90 class robot_urllib_py3(robot_base):
91     def get(self, bookmark, url, accept_charset=False):
92         try:
93             # Set fake referer to the base URL
94             opener.addheaders[2] = ('Referer', url)
95
96             if accept_charset and bookmark.charset:
97                 opener.addheader('Accept-Charset', bookmark.charset)
98             try:
99                 fname, headers = urllib.request.urlretrieve(url)
100             finally:
101                 if accept_charset and bookmark.charset:
102                     # Remove Accept-Charset
103                     del opener.addheaders[-1]
104
105             infile = open(fname, 'rt')
106             content = infile.read()
107             infile.close()
108
109             return None, None, None, headers, content
110
111         except RedirectException as e:
112             return None, e.errcode, e.newurl, None, None
113
114         except IOError as e:
115             if (e[0] == "http error") and (e[1] == -1):
116                 error = None
117                 bookmark.no_error = "The server did not return any header - "
118                 "it is not an error, actually"
119                 self.log('   no headers: %s' % bookmark.no_error)
120             else:
121                 error = get_error(e)
122                 self.log('   Error: %s' % error)
123
124             return error, None, None, None, None
125
126     def get_ftp_welcome(self):
127         global ftpcache_key
128         _welcome = opener.ftpcache[ftpcache_key].ftp.welcome
129         # I am assuming there are no duplicate ftp URLs in db.
130         # If there are - ftpcache_key in next line is invalid.
131         ftpcache_key = None
132         return _welcome
133
134     def finish_check_url(self, bookmark):
135         robot_base.finish_check_url(self, bookmark)
136         urllib.request.urlcleanup()
137         urllib.request._opener = opener