]> git.phdru.name Git - bookmarks_db.git/blob - check_url_sub.py
This commit was manufactured by cvs2svn to create tag 'version2'.
[bookmarks_db.git] / check_url_sub.py
1 #! /usr/local/bin/python -O
2 """
3    Check URL - subprocess
4
5    Written by BroytMann, Mar 1999 - Feb 2000. Copyright (C) 1999-2000 PhiloSoft Design
6 """
7
8
9 import sys, os, stat, string, time
10 import urllib, www_util
11
12 import cPickle
13 pickle = cPickle
14 from subproc import RecordFile
15
16 from md5wrapper import md5wrapper
17
18
19 ftpcache_key = None
20 def myftpwrapper(user, passwd, host, port, dirs):
21    global ftpcache_key
22    ftpcache_key = (user, host, port, string.joinfields(dirs, '/'))
23    return _ftpwrapper(user, passwd, host, port, dirs)
24
25 _ftpwrapper = urllib.ftpwrapper
26 urllib.ftpwrapper = myftpwrapper
27
28 def get_welcome():
29    global ftpcache_key
30    _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
31    ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
32                        # If there are - ftpcache_key in prev line is invalid.
33    return _welcome
34
35
36 class RedirectException(Exception):
37    reloc_dict = {
38       301: "perm",
39       302: "temp"
40    }
41    def __init__(self, errcode, newurl):
42       Exception.__init__(self, "(%s.) to %s" % (self.reloc_dict[errcode], newurl))
43
44
45 class MyURLopener(urllib.URLopener):
46    # Error 302 -- relocated (temporarily)
47    def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): 
48       if headers.has_key('location'):
49          newurl = headers['location']
50       elif headers.has_key('uri'):
51          newurl = headers['uri']
52       else:
53          newurl = "Nowhere"
54       raise RedirectException(errcode, newurl)
55
56    # Error 301 -- also relocated (permanently)
57    http_error_301 = http_error_302
58
59    # Error 401 -- authentication required
60    def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): 
61       raise IOError, ('http error', errcode, "Authentication required ", headers)
62
63
64 def get_error(msg):
65    if type(msg) == type(""):
66       return msg
67
68    else:
69       s = []
70       for i in msg:
71          s.append("'%s'" % string.join(string.split(str(i), "\n"), "\\n"))
72       return "(%s)" % string.join(s)
73
74 def check_url(record):
75    try:
76       now = str(int(time.time()))
77       url_type, url_rest = urllib.splittype(record["URL"])
78       url_host, url_path = urllib.splithost(url_rest)
79       url_path, url_tag  = urllib.splittag(url_path)
80
81       tempfname = record["TEMPFILE"]
82       del record["TEMPFILE"]
83
84       fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), tempfname)
85
86       last_modified = None
87       record["Size"] = str(os.stat(tempfname)[stat.ST_SIZE])
88
89       if headers:
90          try:
91             last_modified = headers["Last-Modified"]
92          except KeyError:
93             last_modified = None
94
95          if last_modified:
96             last_modified = www_util.parse_time(last_modified)
97
98       if last_modified:
99          last_modified = str(int(last_modified))
100       else:
101          last_modified = record["LastVisit"]
102
103       record["LastModified"] = last_modified
104
105       md5 = md5wrapper()
106       if url_type == "ftp": # Pass welcome message through MD5
107          md5.update(get_welcome())
108
109       md5.md5file(tempfname)
110       record["MD5"] = str(md5)
111
112    except IOError, msg:
113       if (msg[0] == "http error") and (msg[1] == -1):
114          record["NoError"] = "The server did not return any header - it is not an error, actually"
115       else:
116          record["Error"] = get_error(msg)
117
118    except EOFError:
119       record["Error"] = "Unexpected EOF (FTP server closed connection)"
120
121    except RedirectException, msg:
122       record["Moved"] = str(msg)
123
124    # Mark this even in case of error
125    record["LastTested"] = now
126
127
128 def run():
129    urllib._urlopener = MyURLopener()
130
131    # Some sites allow only Mozilla-compatible browsers; way to stop robots?
132    server_version = "Mozilla/3.0 (compatible; Python-urllib/%s)" % urllib.__version__
133    urllib._urlopener.addheaders[0] = ('User-agent', server_version)
134
135    rec_in = RecordFile(sys.stdin)
136    rec_out = RecordFile(sys.stdout)
137
138    while 1:
139       record = pickle.loads(rec_in.read_record())
140       check_url(record)
141       rec_out.write_record(pickle.dumps(record))
142
143
144 if __name__ == '__main__':
145    run()