~ubuntu-branches/debian/squeeze/upnp-inspector/squeeze

« back to all changes in this revision

Viewing changes to upnp_inspector/extract.py

  • Committer: Bazaar Package Importer
  • Author(s): Charlie Smotherman
  • Date: 2009-07-24 07:13:32 UTC
  • Revision ID: james.westby@ubuntu.com-20090724071332-t9knke5z11s63w0w
Tags: upstream-0.2.2+dfsg
ImportĀ upstreamĀ versionĀ 0.2.2+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding: utf-8 -*-
 
2
 
 
3
# Licensed under the MIT license
 
4
# http://opensource.org/licenses/mit-license.php
 
5
 
 
6
# Copyright 2009 - Frank Scholz <coherence@beebits.net>
 
7
 
 
8
import os
 
9
import tempfile
 
10
 
 
11
from twisted.internet import defer
 
12
from twisted.internet import protocol
 
13
 
 
14
from twisted.python.filepath import FilePath
 
15
 
 
16
try:
 
17
    from twisted.mail import smtp
 
18
 
 
19
    from twisted.names import client as namesclient
 
20
    from twisted.names import dns
 
21
 
 
22
    import StringIO
 
23
 
 
24
    EMAIL_RECIPIENT = 'upnp.fingerprint@googlemail.com'
 
25
 
 
26
    class SMTPClient(smtp.ESMTPClient):
 
27
 
 
28
        """ build an email message and send it to our googlemail account
 
29
        """
 
30
 
 
31
        def __init__(self, mail_from, mail_to, mail_subject, mail_file, *args, **kwargs):
 
32
            smtp.ESMTPClient.__init__(self, *args, **kwargs)
 
33
            self.mailFrom = mail_from
 
34
            self.mailTo = mail_to
 
35
            self.mailSubject = mail_subject
 
36
            self.mail_file =  mail_file
 
37
            self.mail_from =  mail_from
 
38
 
 
39
        def getMailFrom(self):
 
40
            result = self.mailFrom
 
41
            self.mailFrom = None
 
42
            return result
 
43
 
 
44
        def getMailTo(self):
 
45
            return [self.mailTo]
 
46
 
 
47
        def getMailData(self):
 
48
            from email.mime.application import MIMEApplication
 
49
            from email.mime.multipart import MIMEMultipart
 
50
 
 
51
            msg = MIMEMultipart()
 
52
            msg['Subject'] = self.mailSubject
 
53
            msg['From'] = self.mail_from
 
54
            msg['To'] = self.mailTo
 
55
            fp = open(self.mail_file, 'rb')
 
56
            tar = MIMEApplication(fp.read(),'x-tar')
 
57
            fp.close()
 
58
            tar.add_header('Content-Disposition', 'attachment', filename=os.path.basename(self.mail_file))
 
59
            msg.attach(tar)
 
60
            return StringIO.StringIO(msg.as_string())
 
61
 
 
62
        def sentMail(self, code, resp, numOk, addresses, log):
 
63
            print 'Sent', numOk, 'messages'
 
64
 
 
65
    class SMTPClientFactory(protocol.ClientFactory):
 
66
        protocol = SMTPClient
 
67
 
 
68
        def __init__(self, mail_from, mail_to, mail_subject, mail_file, *args, **kwargs):
 
69
            self.mail_from = mail_from
 
70
            self.mail_to = mail_to
 
71
            self.mail_subject = mail_subject
 
72
            self.mail_file = mail_file
 
73
 
 
74
        def buildProtocol(self, addr):
 
75
            return self.protocol(self.mail_from, self.mail_to,
 
76
                                 self.mail_subject, self.mail_file,
 
77
                                 secret=None, identity='localhost')
 
78
 
 
79
    haz_smtp = True
 
80
except ImportError:
 
81
    haz_smtp = False
 
82
 
 
83
from coherence.upnp.core.utils import downloadPage
 
84
 
 
85
import pygtk
 
86
pygtk.require("2.0")
 
87
import gtk
 
88
 
 
89
class Extract(object):
 
90
 
 
91
    def __init__(self,device):
 
92
        self.device = device
 
93
        self.window = gtk.Dialog(title="Extracting XMl descriptions",
 
94
                            parent=None,flags=0,buttons=None)
 
95
        self.window.connect("delete_event", self.hide)
 
96
        label = gtk.Label("Extracting XMl device and service descriptions\nfrom %s @ %s" % (device.friendly_name, device.host))
 
97
        self.window.vbox.pack_start(label, True, True, 10)
 
98
        tar_button = gtk.CheckButton("tar.gz them")
 
99
        tar_button.connect("toggled", self._toggle_tar)
 
100
        self.window.vbox.pack_start(tar_button, True, True, 5)
 
101
 
 
102
        if haz_smtp == True:
 
103
            self.email_button = gtk.CheckButton("email them to Coherence HQ (%s)" % EMAIL_RECIPIENT)
 
104
            self.email_button.set_sensitive(False)
 
105
            self.window.vbox.pack_start(self.email_button, True, True, 5)
 
106
 
 
107
        align = gtk.Alignment(0.5, 0.5, 0.9, 0)
 
108
        self.window.vbox.pack_start(align, False, False, 5)
 
109
        self.progressbar = gtk.ProgressBar()
 
110
        align.add(self.progressbar)
 
111
 
 
112
        button = gtk.Button(stock=gtk.STOCK_CANCEL)
 
113
        self.window.action_area.pack_start(button, True, True, 5)
 
114
        button.connect("clicked", lambda w: self.window.destroy())
 
115
        button = gtk.Button(stock=gtk.STOCK_OK)
 
116
        self.window.action_area.pack_start(button, True, True, 5)
 
117
        button.connect("clicked", lambda w: self.extract(w,tar_button.get_active()))
 
118
        self.window.show_all()
 
119
 
 
120
    def _toggle_tar(self,w):
 
121
        self.email_button.set_sensitive(w.get_active())
 
122
 
 
123
    def hide(self,w,e):
 
124
        w.hide()
 
125
        return True
 
126
 
 
127
    def extract(self,w,make_tar):
 
128
        print w, make_tar
 
129
        self.progressbar.pulse()
 
130
        try:
 
131
            l = []
 
132
            path = FilePath(tempfile.gettempdir())
 
133
 
 
134
            def device_extract(workdevice, workpath):
 
135
                tmp_dir = workpath.child(workdevice.get_uuid())
 
136
                if tmp_dir.exists():
 
137
                    tmp_dir.remove()
 
138
                tmp_dir.createDirectory()
 
139
                target = tmp_dir.child('device-description.xml')
 
140
                print "d",target,target.path
 
141
                d = downloadPage(workdevice.get_location(),target.path)
 
142
                l.append(d)
 
143
 
 
144
                for service in workdevice.services:
 
145
                    target = tmp_dir.child('%s-description.xml'%service.service_type.split(':',3)[3])
 
146
                    print "s",target,target.path
 
147
                    d = downloadPage(service.get_scpd_url(),target.path)
 
148
                    l.append(d)
 
149
 
 
150
                for ed in workdevice.devices:
 
151
                    device_extract(ed, tmp_dir)
 
152
 
 
153
            def finished(result):
 
154
                uuid = self.device.get_uuid()
 
155
                print "extraction of device %s finished" % uuid
 
156
                print "files have been saved to %s" % os.path.join(tempfile.gettempdir(),uuid)
 
157
                if make_tar == True:
 
158
                    tgz_file = self.create_tgz(path.child(uuid))
 
159
                    if haz_smtp == True and self.email_button.get_active() == True:
 
160
                        self.send_email(tgz_file)
 
161
                    path.child(uuid).remove()
 
162
                self.progressbar.set_fraction(0.0)
 
163
                self.window.hide()
 
164
 
 
165
            device_extract(self.device,path)
 
166
 
 
167
            dl = defer.DeferredList(l)
 
168
            dl.addCallback(finished)
 
169
        except Exception, msg:
 
170
            print "problem creating download directory: %r (%s)" % (Exception,msg)
 
171
            self.progressbar.set_fraction(0.0)
 
172
 
 
173
    def create_tgz(self,path):
 
174
        print "create_tgz", path, path.basename()
 
175
        cwd = os.getcwd()
 
176
        os.chdir(path.dirname())
 
177
        import tarfile
 
178
        tgz_file = os.path.join(tempfile.gettempdir(),path.basename()+'.tgz')
 
179
        tar = tarfile.open(tgz_file, "w:gz")
 
180
        for file in path.children():
 
181
            tar.add(os.path.join(path.basename(),file.basename()))
 
182
        tar.close()
 
183
        os.chdir(cwd)
 
184
        return tgz_file
 
185
 
 
186
    def send_email(self, file):
 
187
 
 
188
        def got_mx(result):
 
189
            mx_list = result[0]
 
190
            mx_list.sort(lambda x, y: cmp(x.payload.preference, y.payload.preference))
 
191
            if len(mx_list) > 0:
 
192
                import posix, pwd
 
193
                import socket
 
194
                from twisted.internet import reactor
 
195
                reactor.connectTCP(str(mx_list[0].payload.name), 25,
 
196
                    SMTPClientFactory('@'.join((pwd.getpwuid(posix.getuid())[0],socket.gethostname())), EMAIL_RECIPIENT, 'xml-files', file))
 
197
 
 
198
        mx = namesclient.lookupMailExchange('googlemail.com')
 
199
        mx.addCallback(got_mx)