~artfwo/apturl/ubuntu

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#!/usr/bin/python
#
# Copyright (c) 2007 Canonical
#
# AUTHOR:
# Michael Vogt <mvo@ubuntu.com>
#
# This file is part of AptUrl
#
# AptUrl is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# AptUrl is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with AptUrl; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

import sys
import apt
import apt_pkg
import subprocess

import os
import os.path

import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade

from tempfile import NamedTemporaryFile
from gettext import gettext as _
from optparse import OptionParser

import gettext
import time
import thread

from AptUrl import Parser

def error(summary, msg=""):
    d = gtk.MessageDialog(parent=None,
                          flags=gtk.DIALOG_MODAL,
                          type=gtk.MESSAGE_ERROR,
                          buttons=gtk.BUTTONS_CLOSE)
    d.set_title("")
    d.set_markup("<big><b>%s</b></big>\n\n%s" % (summary, msg))
    d.realize()
    d.window.set_functions(gtk.gdk.FUNC_MOVE)
    d.run()
    d.destroy()

def question(header, body):
    dia = gtk.MessageDialog(None, 0, gtk.MESSAGE_QUESTION,
                            gtk.BUTTONS_YES_NO, "")
    dia.set_markup("<b><big>%s</big></b>" % header)
    dia.set_icon(gtk.icon_theme_get_default().load_icon('deb', 16, False))
    dia.format_secondary_text(body)
    res = dia.run()
    if res != gtk.RESPONSE_YES:
        return False
    return True

def wait_for_p(p, lock):
    " helper for the thread to wait for process p to finish "
    p.wait()
    lock.release()

def get_dist():
    return subprocess.Popen(["lsb_release","-c","-s"],stdout=subprocess.PIPE).communicate()[0].strip()

def enable_section(apturl):
    for component in apturl.section:
        cmd = ["gksu", "--desktop",
               "/usr/share/applications/gnome-app-install.desktop",
               "--",
               "gnome-app-install-helper", "-e", component]
        try:
            output = subprocess.Popen(cmd,
                                      stdout=subprocess.PIPE).communicate()[0]
        except OSError, e:
            print >>sys.stderr, "Execution failed:", e
            return False
        #FIXME: Very ugly, but gksu doesn't return the correct exit states
        if output != "Enabled the %s component\n" % component:
            return False
        return True

def run_update(dia):
        p = subprocess.Popen(['gksu',
                              '--desktop',
                              '/usr/share/applications/synaptic.desktop',
                              '--',
                              '/usr/sbin/synaptic',
                              '--hide-main-window',
                              '--non-interactive',
                              '--update-at-startup',
                              ])
        wait_for_synaptic(dia, p)

def run_install(dia, apturl):
        # run synaptic
        temp = NamedTemporaryFile()
        temp.write("%s\t install\n" % apturl.package)
        temp.flush()
        #print temp.name
        p = subprocess.Popen(['gksu',
                              '--desktop',
                              '/usr/share/applications/synaptic.desktop',
                              '--',
                              '/usr/sbin/synaptic',
                              '--hide-main-window',
                              '--non-interactive',
                              '--set-selections-file', temp.name
                              ])
        wait_for_synaptic(dia, p)
        temp.close()    

def wait_for_synaptic(dia, p):
        # wait for synaptic
        lock = thread.allocate_lock()
        lock.acquire()
        thread.start_new_thread(wait_for_p, (p, lock))

        dia.set_sensitive(False)
        while lock.locked():
            while gtk.events_pending():
                gtk.main_iteration()
            time.sleep(0.01)
        dia.set_sensitive(True)
        return True

def debline(apturl):
    return "%s %s %s" % (apturl.repo_url, apturl.dist, " ".join(apturl.section))

def aptsources_file(apturl):
    dir = apt_pkg.Config.FindDir("Dir::Etc::sourceparts")
    file = apt_pkg.URItoFileName(debline(apturl))+".list")
    file = file.replace("%20","__")
    return os.path.join(dir, file)

def enable_repo(apturl):
    source = aptsources_file(apturl)
    if os.path.exists(source):
        return True
    temp = NamedTemporaryFile()
    temp.write("# added by apturl\n")
    temp.write("deb %s\n" % debline(apturl))
    temp.flush()
    # copy channel file in place
    cmd = ["gksu",
           "--desktop", "/usr/share/applications/gnome-app-install.desktop",
           "--",
           "install", "--mode=644","--owner=0",temp.name, source
          ]
    subprocess.call(cmd)
    # install the key as well (if needed)
    if apturl.keyfile:
        cmd = ["gksu",
               "--desktop",
               "/usr/share/applications/gnome-app-install.desktop",
               "--",
               "apt-key", "add",
               "/usr/share/app-install/channels/%s" % apturl.keyfile]
        subprocess.call(cmd)
    return True
    

if __name__ == "__main__":
    localesApp="apturl"
    localesDir="/usr/share/locale"
    gettext.bindtextdomain(localesApp, localesDir)
    gettext.textdomain(localesApp)

    parser = OptionParser()
    parser.add_option("-p", "--http-proxy", dest="http_proxy",
                      default=None, help="use http proxy")
    (options, args) = parser.parse_args()

    gtk.init_check()

    # eval and add proxy
    if options.http_proxy is not None:
        proxy = options.http_proxy
        if not ":" in proxy:
            proxy += ":3128"
        os.environ["http_proxy"] = "http://%s" % proxy

    try:
        apturl_list = Parser.parse(args[0])
    except IndexError, e:
        error(_("Need a url to continue, exiting"))
        sys.exit(1)
    except Parser.InvalidUrlException, e:
        error(_("Invalid url: '%s' given, exiting") % sys.argv[1])
        sys.exit(1)

    cache = apt.Cache()
    for apturl in apturl_list:
        if not (apturl.schema == "apt" or apturl.schema == "apt+http"):
            error(_("Can not deal with protocol '%s' ") % apturl.schema)
            continue

        if not cache.has_key(apturl.package):
            error(_("Can not find '%s' ") % apturl.package)
            continue
        if cache[apturl.package].isInstalled and apturl.minver is None:
            error(_("Package '%s' is already installed") % apturl.package)
            continue

        # FIXME: there should be a real window here
        header = _("Install additional software?")
        body = _("Do you want to install the package '%s' ?") % apturl.package

        dia_xml = gtk.glade.XML('/usr/share/apturl/apturl.glade', 
                                'confirmation_dialog')
        dia = dia_xml.get_widget('confirmation_dialog')
        dia.set_title('')
        header_label = dia_xml.get_widget('header_label')
        header_label.set_markup("<b><big>%s</big></b>" % header)
        body_label = dia_xml.get_widget('body_label')
        body_label.set_label(body)
        description_text_view = dia_xml.get_widget('description_text_view')
        description = gtk.TextBuffer()
        desc = "%s\n\n%s" % (cache[apturl.package].summary,
                             cache[apturl.package].description)
        description.set_text(desc)
        description_text_view.set_buffer(description)
        dia.set_icon(gtk.icon_theme_get_default().load_icon('deb', 16, False))
        res = dia.run()
        if res != gtk.RESPONSE_YES:
            dia.hide()
            continue

        # check if we need to fiddle with the sources.list
        if apturl.section and apturl.repo_url is None:
            if not enable_section(apturl):
                error(_("Enabling '%s' failed") % apturl.section)
                continue
            run_update(dia)
        #elif apturl.repo_url is not None:
        #    if not enable_repo(apturl):
        #        error(_("Enabling '%s' failed") % apturl.repo_url)
        #        continue
        #    run_update(dia)
            
        # try to install it
        try:
            cache[apturl.package].markInstall()
        except SystemError, e:
            error(_("Can not install '%s' (%s) ") % (apturl.package, e))
            continue
        if apturl.minver is not None:
            verStr = cache[apturl.package].candidateVersion
            if apt_pkg.VersionCompare(verStr, apturl.minver) < 1:
                error(_("Package '%s' requests minimal version '%s', but "
                        "only '%s' is available") % (apturl.package,
                                                     apturl.minver,
                                                     verStr))
                continue

        # install it
        run_install(dia, apturl)

        if apturl.repo_url is not None:
            header = _("Remove software channel?")
            body = _("For installing '%s' the software channel '%s' was "
                     "added, do you want to remove it again?") % (apturl.package, apturl.repo_url)
            res = question(header, body)
            if res:
                subprocess.call(["gksu","rm",aptsources_file(apturl)])

        # cleanup
        dia.hide()