~ubuntu-branches/debian/wheezy/agtl/wheezy

« back to all changes in this revision

Viewing changes to files/advancedcaching/downloader.py

  • Committer: Bazaar Package Importer
  • Author(s): Heiko Stuebner
  • Date: 2011-01-22 13:55:12 UTC
  • mfrom: (1.1.5 upstream)
  • Revision ID: james.westby@ubuntu.com-20110122135512-1mik0vssgpnx2fgu
Tags: 0.8.0.3-1
New upstream release

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
2
# -*- coding: utf-8 -*-
3
3
 
4
 
#        Copyright (C) 2009 Daniel Fett
5
 
#         This program is free software: you can redistribute it and/or modify
 
4
#   Copyright (C) 2010 Daniel Fett
 
5
#   This program is free software: you can redistribute it and/or modify
6
6
#   it under the terms of the GNU General Public License as published by
7
7
#   the Free Software Foundation, either version 3 of the License, or
8
8
#   (at your option) any later version.
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/>.
17
17
#
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
19
21
#
20
22
 
21
 
import os
22
 
import cookielib
23
 
import urllib
24
 
import urllib2
 
23
 
 
24
import logging
 
25
logger = logging.getLogger('downloader')
25
26
 
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
28
30
 
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
 
37
        setdefaulttimeout(30)
 
38
        self.opener_installed = False
 
39
        self.login_callback = login_callback
34
40
 
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):
40
47
            try:
41
 
                os.remove(self.cookiefile)
 
48
                remove(self.cookiefile)
42
49
            except:
43
 
                print "* Could not remove cookie file?!"
 
50
                logger.info("Could not remove cookie file?!")
44
51
                pass
45
52
 
46
53
 
47
54
    def login(self):
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
54
65
 
55
66
        try:
56
67
            cj.load()
57
 
            print "+ Loaded cookie file"
 
68
            logger.info("Loaded cookie file")
58
69
        except:
59
 
            print "+ Couldn't load cookie file"
 
70
            logger.info("Couldn't load cookie file")
60
71
        else:
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)
64
75
            for line in page:
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")
 
79
                    page.close()
68
80
                    return
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")
 
83
                    page.close()
71
84
                    break
72
85
        
73
 
        print "+ Logging in"
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',
79
 
            '__EVENTTARGET': '',
80
 
            '__EVENTARGUMENT': ''
81
 
        }
82
 
 
83
 
        page = self.get_reader(url, values, login = False).read()
84
 
 
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)
 
88
 
 
89
        page = self.get_reader(url, values, login = False)
 
90
 
 
91
        for line in page:
 
92
            if 'You are logged in as' in line:
 
93
                break
 
94
            elif 'You are not logged in.' in line or 'combination does not match' in line:
 
95
                raise Exception("Wrong password or username!")
 
96
        else:
 
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!")
 
99
 
 
100
        logger.info("Great success.")
88
101
        self.logged_in = True
89
102
        try:
90
103
            cj.save()
91
 
        except Exception as e:
92
 
            print "+ Could not save cookies:", e
 
104
        except Exception, e:
 
105
            logger.info("Could not save cookies: %s" % e)
93
106
 
94
107
 
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:
97
112
            self.login()
98
113
 
99
114
        if values == None and data == None:
100
 
            req = urllib2.Request(url)
 
115
            req = Request(url)
101
116
            self.add_headers(req)
102
 
            return urllib2.urlopen(req)
 
117
            return urlopen(req)
103
118
 
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)
 
124
            return urlopen(req)
110
125
        elif values == None:
111
126
            content_type, body = data
112
 
            req = urllib2.Request(url)
 
127
            req = 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)
 
132
            return urlopen(req)
118
133
 
119
134
    def encode_multipart_formdata(self, fields, files):
120
135
        """