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