15
15
# You should have received a copy of the GNU General Public License
16
16
# along with this program. If not, see <http://www.gnu.org/licenses/>.
18
# Author: Daniel Fett advancedcaching@fragcom.de
18
# Author: Daniel Fett agtl@danielfett.de
19
# Jabber: fett.daniel@jaber.ccc.de
20
# Bugtracker and GIT Repository: http://github.com/webhamster/advancedcaching
25
logger = logging.getLogger('downloader')
26
27
class FileDownloader():
27
28
USER_AGENT = 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; de; rv:1.9.0.12) Gecko/2009070811 Windows NT Firefox/3.1'
29
opener_installed = False
29
def __init__(self, username, password, cookiefile):
31
def __init__(self, username, password, cookiefile, login_callback):
30
32
self.username = username
31
33
self.password = password
32
34
self.cookiefile = cookiefile
33
35
self.logged_in = False
36
from socket import setdefaulttimeout
38
self.opener_installed = False
39
self.login_callback = login_callback
35
41
def update_userdata(self, username, password):
42
from os import path, remove
36
43
self.username = username
37
44
self.password = password
38
45
self.logged_in = False
39
if os.path.exists(self.cookiefile):
46
if path.exists(self.cookiefile):
41
os.remove(self.cookiefile)
48
remove(self.cookiefile)
43
print "* Could not remove cookie file?!"
50
logger.info("Could not remove cookie file?!")
48
55
if self.username == '' or self.password == '':
49
raise Exception("Please configure your username and password.")
50
print "+ Checking Login status"
51
cj = cookielib.LWPCookieJar(self.cookiefile)
52
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
53
urllib2.install_opener(opener)
56
raise Exception("Please configure your username/password and restart the application")
57
logger.info("Checking Login status")
58
from cookielib import LWPCookieJar
59
cj = LWPCookieJar(self.cookiefile)
60
if not self.opener_installed:
61
from urllib2 import build_opener, install_opener, HTTPCookieProcessor
62
opener = build_opener(HTTPCookieProcessor(cj))
63
install_opener(opener)
64
self.opener_installed = True
57
print "+ Loaded cookie file"
68
logger.info("Loaded cookie file")
59
print "+ Couldn't load cookie file"
70
logger.info("Couldn't load cookie file")
61
print "+ Checking if still logged in..."
72
logger.info("Checking if still logged in...")
62
73
url = 'http://www.geocaching.com/seek/nearest.aspx'
63
74
page = self.get_reader(url, login = False)
65
76
if 'You are logged in as' in line:
66
77
self.logged_in = True
67
print "+ Seems as we're still logged in"
78
logger.info("Seems as we're still logged in")
69
81
elif 'You are not logged in.' in line:
70
print "+ Nope, not logged in anymore"
82
logger.info("Nope, not logged in anymore")
74
url = 'http://www.geocaching.com/Default.aspx'
75
values = {'ctl00$MiniProfile$loginUsername':self.username,
76
'ctl00$MiniProfile$loginPassword':self.password,
77
'ctl00$MiniProfile$loginRemember': 'on',
78
'ctl00$MiniProfile$LoginBtn': 'Go',
83
page = self.get_reader(url, values, login = False).read()
85
if 'combination does not match' in page:
86
raise Exception("Wrong password or username!")
87
print "+ Great success."
86
logger.info("Logging in")
87
url, values = self.login_callback(self.username, self.password)
89
page = self.get_reader(url, values, login = False)
92
if 'You are logged in as' in line:
94
elif 'You are not logged in.' in line or 'combination does not match' in line:
95
raise Exception("Wrong password or username!")
97
logger.info("Seems as if the language is set to something other than english")
98
raise Exception("Please go to geocaching.com and set the website language to english!")
100
logger.info("Great success.")
88
101
self.logged_in = True
91
except Exception as e:
92
print "+ Could not save cookies:", e
105
logger.info("Could not save cookies: %s" % e)
95
108
def get_reader(self, url, values=None, data=None, login = True):
109
from urllib import urlencode
110
from urllib2 import Request, urlopen
96
111
if login and not self.logged_in:
99
114
if values == None and data == None:
100
req = urllib2.Request(url)
101
116
self.add_headers(req)
102
return urllib2.urlopen(req)
104
119
elif data == None:
105
120
if (isinstance(values, dict)):
106
values = urllib.urlencode( values)
107
req = urllib2.Request(url, values)
121
values = urlencode( values)
122
req = Request(url, values)
108
123
self.add_headers(req)
109
return urllib2.urlopen(req)
110
125
elif values == None:
111
126
content_type, body = data
112
req = urllib2.Request(url)
113
128
req.add_header('Content-Type', content_type)
114
129
req.add_header('Content-Length', len(str(body)))
115
130
self.add_headers(req)
116
131
req.add_data(body)
117
return urllib2.urlopen(req)
119
134
def encode_multipart_formdata(self, fields, files):