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