예제 #1
0
파일: ppa.py 프로젝트: jderose/Repoman
 def list_all(self):
     sp = SoftwareProperties()
     isv_sources = sp.get_isv_sources()
     source_list = []
     for source in isv_sources:
         if not str(source).startswith("#"):
             source_list.append(str(source))
     return source_list
예제 #2
0
    def __init__(self, conn=None, object_path=None, bus_name=None):
        dbus.service.Object.__init__(self, conn, object_path, bus_name)

        # The following variables are used bu _check_polkit_privilege
        self.dbus_info = None
        self.polkit = None
        self.enforce_polkit = True
        self.sp = SoftwareProperties()
예제 #3
0
파일: service.py 프로젝트: pop-os/repoman
    def __init__(self, conn=None, object_path=None, bus_name=None):
        dbus.service.Object.__init__(self, conn, object_path, bus_name)

        # These are used by PolKit to check privileges
        self.dbus_info = None
        self.polkit = None
        self.enforce_polkit = True

        try:
            self.system_repo = repolib.SystemSource()
        except:
            self.system_repo = None
        self.sp = SoftwareProperties()
        self.cache = apt.Cache()
예제 #4
0
class Repos(plugin.Plugin):

    permissions = {'script': False,
                   'root': True,
                   'remove-pkg': False,
                   'system-config': True
                   }
    sp = SoftwareProperties()
    ppas_list = []

    def get_ppas(self):
        try:
            ppas_member = self.kettle_ark.getmember('data/repos/ppas.repos')
        except KeyError:
            raise BadKettle(_("The kettle is missing data for plugin: repos"))

        ppas_exfile = self.kettle_ark.extractfile(ppas_member)
        ppas_bytes = ppas_exfile.readlines()
        ppas_exfile.close()


        for i in ppas_bytes:
            line = i.decode('UTF-8')[:-1]
            self.ppas_list.append(line)
        return self.ppas_list


    def install_repos(self, repo_list):
        for i in repo_list:
            try:
                self.sp.add_source_from_line(i)
                self.sp.sourceslist.save()
                self.sp.reload_sourceslist()
            except:
                raise BadRepo(_("Couldn't add the repository %s" % i))

    def get_to_root(self):
        subprocess.call(["/usr/bin/sudo",
                         "/usr/bin/python3",
                         self.plugin_path + "/repos-data/as_root.py",
                         self.kettle.path])

    def run_install(self):
        self.get_to_root()
예제 #5
0
    def __init__(self, parent):
        self.sp = SoftwareProperties()
        Gtk.Box.__init__(self, False, 0)
        self.parent = parent
        self.ppa = ppa.PPA(self)

        self.content_grid = Gtk.Grid()
        self.content_grid.set_margin_top(24)
        self.content_grid.set_margin_left(12)
        self.content_grid.set_margin_right(12)
        self.content_grid.set_margin_bottom(12)
        self.content_grid.set_row_spacing(6)
        self.content_grid.set_hexpand(True)
        self.content_grid.set_vexpand(True)
        self.add(self.content_grid)

        sources_title = Gtk.Label("Extra Sources")
        Gtk.StyleContext.add_class(sources_title.get_style_context(), "h2")
        sources_title.set_halign(Gtk.Align.START)
        self.content_grid.attach(sources_title, 0, 0, 1, 1)

        sources_label = Gtk.Label(
            "These sources are for software provided by " +
            "a third party. They may present a security " +
            "risk or can cause system instability. " +
            "\nOnly add sources that you trust.")
        sources_label.set_line_wrap(True)
        sources_label.set_halign(Gtk.Align.START)
        sources_label.set_justify(Gtk.Justification.FILL)
        sources_label.set_hexpand(True)
        self.content_grid.attach(sources_label, 0, 1, 1, 1)

        list_grid = Gtk.Grid()
        self.content_grid.attach(list_grid, 0, 2, 1, 1)
        list_window = Gtk.ScrolledWindow()
        list_grid.attach(list_window, 0, 0, 1, 1)

        self.ppa_liststore = Gtk.ListStore(str, str)
        self.view = Gtk.TreeView(self.ppa_liststore)
        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn('Source', renderer, markup=0)
        self.view.append_column(column)
        self.view.set_hexpand(True)
        self.view.set_vexpand(True)
        tree_selection = self.view.get_selection()
        tree_selection.connect('changed', self.on_row_change)
        list_window.add(self.view)

        # add button
        add_button = Gtk.Button.new_from_icon_name("list-add-symbolic",
                                                   Gtk.IconSize.SMALL_TOOLBAR)
        Gtk.StyleContext.add_class(add_button.get_style_context(),
                                   "image-button")
        add_button.set_tooltip_text("Add New Source")
        add_button.connect("clicked", self.on_add_button_clicked)

        # edit button
        edit_button = Gtk.Button.new_from_icon_name("edit-symbolic",
                                                    Gtk.IconSize.SMALL_TOOLBAR)
        Gtk.StyleContext.add_class(edit_button.get_style_context(),
                                   "image-button")
        edit_button.set_tooltip_text("Modify Selected Source")
        edit_button.connect("clicked", self.on_edit_button_clicked)

        action_bar = Gtk.ActionBar()
        Gtk.StyleContext.add_class(action_bar.get_style_context(),
                                   "inline-toolbar")
        action_bar.add(edit_button)
        action_bar.add(add_button)
        list_grid.attach(action_bar, 0, 1, 1, 1)

        self.generate_entries(self.ppa.get_isv())
def on_install_button_active(button, model, itemSelectCount):
    global pulseTimer
    global installStatus
    global cache
    global view
    global p1

    # set busy flag
    installStatus = 'busy'

    # Remove CANCEL button
    Gtk.Container.remove(grid, cancelButton)

    # Count items
    itemCount = len(model)

    # Add PPA's
    # Set progress
    progressBar.set_fraction(0.1)
    label.set_text("Installing new software sources...")
    appendToLog("Installing new software sources...")

    # Use APT module and SoftwareProperties to add-apt
    sp = SoftwareProperties()
    for listItem in range(itemCount):
        # Check which items are selected True in list column 0
        itemSelected = model[listItem][0]
        if itemSelected:
            if ppaList[listItem] != '':
                progressBar.set_text("Adding PPA for " + model[listItem][1])
                # add-apt the python way ! taken from add-apt code
                try:
                    sp.add_source_from_line(ppaList[listItem])
                    debugPrint("Added PPA - %s" % ppaList[listItem])
                    appendToLog("Added PPA - %s" % ppaList[listItem])
                except:
                    debugPrint("[Error] Could not add PPA - %s" %
                               ppaList[listItem])
                    appendToLog("[Error] Could not add PPA - %s" %
                                ppaList[listItem])

    # Save new apt list
    sp.sourceslist.save()
    progressBar.set_fraction(0.2)

    # Add Keys
    for listItem in range(itemCount):
        # Check which items are selected True in list column 0
        itemSelected = model[listItem][0]
        if itemSelected:
            if getAptKeyList[listItem] != '':
                debugPrint("Name : %s" % model[listItem][1])
                debugPrint("Keys : %s" % getAptKeyList[listItem])
                progressBar.set_text("Adding software key for " +
                                     model[listItem][1])
                # Add key the bash way TODO do this differently to handle errors/timeout
                # First check type of key wget or apt-key adv
                if "recv-keys" in getAptKeyList[listItem]:
                    keyType = 'apt-key'
                else:
                    keyType = 'wget'
                try:
                    if keyType == 'wget':
                        # Just read Key URL and do the rest
                        p1 = subprocess.Popen(
                            ['wget', '-O', '-', getAptKeyList[listItem]],
                            stdout=subprocess.PIPE)
                        p2 = subprocess.Popen(
                            ['apt-key', 'add', '--yes', '--quiet', '-'],
                            stdin=p1.stdout,
                            stdout=subprocess.PIPE)
                        p1.stdout.close(
                        )  # Allow p1 to receive a SIGPIPE if p2 exits.
                    if keyType == 'apt-key':
                        # Run command as is
                        p6 = subprocess.Popen([getAptKeyList[listItem]],
                                              shell=True,
                                              stdout=subprocess.PIPE)

                    debugPrint("Key added for : %s" % model[listItem][1])
                    appendToLog("Key added for : %s" % model[listItem][1])
                    debugPrint("Key status:  %s" % output)
                    appendToLog("Key status:  %s" % output)
                except:
                    debugPrint("[Error] Could not add key from - %s" %
                               getAptKeyList[listItem])
                    appendToLog("[Error] Could not add key from - %s" %
                                getAptKeyList[listItem])

    progressBar.set_fraction(0.3)

    # Manually write to file to add APT for DEB repos
    for listItem in range(itemCount):
        # Check which items are selected True in list column 0
        itemSelected = model[listItem][0]
        if itemSelected:
            if aptListEntryList[listItem] != '':
                debugPrint("Name : %s" % model[listItem][1])
                debugPrint("APT : %s" % aptListEntryList[listItem])
                installTitles = installTitleList[listItem].split(' ')
                progressBar.set_text("Adding APT Repository for " +
                                     model[listItem][1])
                # write sources to file
                try:
                    writeToFile(
                        os.path.join(aptListPath, installTitles[0] + '.list'),
                        'deb ' + aptListEntryList[listItem] + '\n', 'w')
                    #writeToFile(os.path.join(aptListPath, installTitles[0]+'.list'), 'deb-src '+aptListEntryList[listItem]+'\n', 'a')
                    writeToFile(
                        os.path.join(aptListPath,
                                     installTitles[0] + '.list.save'),
                        'deb ' + aptListEntryList[listItem] + '\w', 'w')
                    #writeToFile(os.path.join(aptListPath, installTitles[0]+'.list.save'), 'deb-src '+aptListEntryList[listItem]+'\n', 'a')
                    debugPrint("Added APT - %s" % aptListEntryList[listItem])
                    appendToLog("Added APT - %s" % aptListEntryList[listItem])
                except:
                    debugPrint("[Error] Could not add APT - %s" %
                               aptListEntryList[listItem])
                    appendToLog("[Error] Could not add APT - %s" %
                                aptListEntryList[listItem])
                    onInstallError()

    # Save new apt list
    sp.sourceslist.save()

    # We need to open the cache again before updating
    progressBar.set_fraction(0.4)
    progressBar.set_text('Reading Software List...')
    debugPrint("[Progress] Open Cache...")
    appendToLog("[Progress] Open Cache...")

    cache.open()

    # Now, lets update the package list
    progressBar.set_fraction(0.5)
    progressBar.set_text('Updating Software Center...')
    debugPrint("[Progress] Cache update...")
    appendToLog("[Progress] Cache update...")
    pulseTimer = GLib.timeout_add(100, pulse)

    try:
        cache.update()
    except:
        appendToLog("[Warning] Cache update warnings. Not fatal - continue...")
        debugPrint("[Warning] Cache update warnings. Not fatal - continue...")

    GLib.source_remove(pulseTimer)

    # Now we can do the same as 'apt-get upgrade' does
    progressBar.set_fraction(0.7)
    #progressBar.set_text('Updating Software ...')
    #print "[progress] Updating Software ..."
    #cache.upgrade()
    # or we can play 'apt-get dist-upgrade'
    #cache.upgrade(True)
    # Q: Why does nothing happen?
    # A: You forgot to call commit()!
    debugPrint("[Progress] Commit Cache...")
    appendToLog("[Progress] Commit Cache...")
    progressBar.set_fraction(0.8)
    progressBar.set_text('Updating Software Center...')

    try:
        #cache.commit()
        cache.commit(aptAcquireProgress, aptInstallProgress)

    except:
        debugPrint("[Error] apt-get update failed")

    # Software sources added Done
    progressBar.set_fraction(1)
    progressBar.set_text('')
    label.set_text('Software sources added successfully')
    appendToLog('Software sources added successfully')

    # START installing apps one by one

    # using itemSelectCount to do progress increments
    progInc = float(100 / itemSelectCount) / 100
    itemIncCount = 0

    progressBar.set_fraction(0.02)

    for listItem in range(itemCount):
        # Check which items are selected True in list column 0
        itemSelected = model[listItem][0]
        if itemSelected:
            # With selected items ...
            label.set_text('Installing Software ' + str(itemIncCount + 1) +
                           ' of ' + str(itemSelectCount) + ' ...')
            appendToLog('[Notice] Installing Software ' +
                        str(itemIncCount + 1) + ' of ' + str(itemSelectCount) +
                        ' ...')

            # Un Install first if RE-install is selected
            if installStateList[listItem] == 'installed':

                progressBar.set_text("Removing " + model[listItem][1])
                # Set focus
                view.set_cursor(listItem)
                # open cache again for each install to update new packages list
                cache.open()
                # Get package list into array
                installTitles = installTitleList[listItem].split(' ')
                # mark packages for Remove
                for itemToRemove in installTitles:
                    try:
                        cache[itemToRemove].mark_delete()
                        debugPrint("[Remove] Marked for Removal %s" %
                                   itemToRemove)
                        appendToLog("[Remove] Marked for Removal %s" %
                                    itemToRemove)
                    except:
                        debugPrint("[Error] Packages not found for %s" %
                                   model[listItem][1])
                        appendToLog("[Error] Packages not found for %s" %
                                    model[listItem][1])
                        # TODO show install failed not done
                        installError = "[Error] Packages not found for " + model[
                            listItem][1]

                # Commit new cache and remove each set of packages
                try:
                    aptAcquireProgress.start()
                    progressTimer = GLib.timeout_add(200, renderCellProgress,
                                                     model, listItem, 'remove')
                    cache.commit(aptAcquireProgress, aptInstallProgress)
                    aptAcquireProgress.stop()
                    GLib.source_remove(progressTimer)
                    # Update icon after removal
                    model[listItem][4] = GdkPixbuf.Pixbuf.new_from_file(
                        iconPathBlank)
                    debugPrint("Un-Install complete for %s" %
                               model[listItem][1])
                    appendToLog("Un-Install complete for %s" %
                                model[listItem][1])
                except:
                    debugPrint("[Error] Un-Install failed for %s" %
                               model[listItem][1])
                    appendToLog("[Error] Un-Install failed for %s" %
                                model[listItem][1])
                    installError = "[Error] Un-Install failed for " + model[
                        listItem][1]

            # Run Pre-install commands
            # if item has pre-install run that now
            if preInstallList[listItem] != '':
                progressBar.set_text("Running pre-install for " +
                                     model[listItem][1])
                # Run pre install commands the bash way TODO do this differently to handle errors/timeout
                try:
                    p1 = subprocess.Popen([preInstallList[listItem]],
                                          shell=True,
                                          stdout=subprocess.PIPE)
                    output = p1.communicate()[0]
                    debugPrint("Running Pre install script for : %s" %
                               model[listItem][1])
                    debugPrint("Pre install script output:  %s" % output)
                    appendToLog("Running Pre install script for : %s" %
                                model[listItem][1])
                    appendToLog("Pre install script output:  %s" % output)
                except:
                    debugPrint("[Error] Pre install script error : %s" %
                               model[listItem][1])
                    appendToLog("[Error] Pre install script error : %s" %
                                model[listItem][1])

            # Install software item FINALLY
            installError = ''

            # Initial cell progressbar value
            model[listItem][3] = 0

            progressBar.set_text("Installing " + model[listItem][1])
            debugPrint("Installing %s" % model[listItem][1])
            appendToLog("Installing %s" % model[listItem][1])
            # Set focus
            view.set_cursor(listItem)
            # open cache again for each install to update new packages list
            cache.open()
            # Get package list into array
            installTitles = installTitleList[listItem].split(' ')
            # mark packages for install
            for itemToInstall in installTitles:
                try:
                    cache[itemToInstall].mark_install()
                    debugPrint("[Install] Marked for install %s" %
                               itemToInstall)
                    appendToLog("[Install] Marked for install %s" %
                                itemToInstall)
                except:
                    debugPrint("[Error] Packages not found for %s" %
                               model[listItem][1])
                    appendToLog("[Error] Packages not found for %s" %
                                model[listItem][1])
                    # TODO show install failed not done
                    installError = "[Error] Packages not found for " + model[
                        listItem][1]

            # Commit new cache and install each set of packages
            try:
                #cache.upgrade()
                aptAcquireProgress.start()
                progressTimer = GLib.timeout_add(200, renderCellProgress,
                                                 model, listItem, 'install')

                cache.commit(aptAcquireProgress, aptInstallProgress)

                #cache.commit()
                debugPrint("Install complete for %s" % model[listItem][1])
                appendToLog("Install complete for %s" % model[listItem][1])
            except:
                debugPrint("[Error] Installation failed for %s" %
                           model[listItem][1])
                # TODO show install failed not done
                installError = "[Error] Installation failed for " + model[
                    listItem][1]

            # END of Install

            # Run POST-install commands
            # if item has post-install run that now
            if postInstallList[listItem] != '':
                progressBar.set_text("Running post-install for " +
                                     model[listItem][1])
                # Run post install commands the bash way TODO do this differently to handle errors/timeout
                try:
                    p1 = subprocess.Popen([postInstallList[listItem]],
                                          shell=True,
                                          stdout=subprocess.PIPE)
                    output = p1.communicate()[0]
                    debugPrint("Running Post install script for : %s" %
                               model[listItem][1])
                    debugPrint("Post install script output:  %s" % output)
                    appendToLog("Running Post install script for : %s" %
                                model[listItem][1])
                    appendToLog("Post install script output:  %s" % output)
                except:
                    debugPrint("[Error] Post install script error : %s" %
                               model[listItem][1])
                    appendToLog("[Error] Post install script error : %s" %
                                model[listItem][1])

            # Set Cell Progress bar and deselect when done
            model[listItem][3] = 100
            model[listItem][0] = False
            GLib.source_remove(progressTimer)
            aptAcquireProgress.stop()

            time.sleep(0.1)
            refreshGui()
            time.sleep(0.1)

            # Check if install ok and set icon
            if installError == '':
                iconPathMod = iconPathOk
                installStateList[listItem] = 'installed'
            else:
                iconPathMod = iconPathError
                installStateList[listItem] = 'error'

            # Set icon
            model[listItem][4] = GdkPixbuf.Pixbuf.new_from_file(iconPathMod)

            # If selected Inc for each item as we know not how many here
            # Move progress incrementally depending on number of install items
            itemIncCount = itemIncCount + 1
            displayInc = progInc * itemIncCount

            # Update main progress bar at the end of each item install
            progressBar.set_fraction(displayInc)

    # All Done - The End -
    # Remove Timers
    GLib.source_remove(progressTimer)
    progressBar.set_fraction(1)
    progressBar.set_text('')

    # Stop Spinner
    spinner.stop()
    os.system("python notify.py")
    label.set_text('Installation Complete')
    debugPrint('[END] Installation Complete')
    appendToLog('[END] Installation Complete')
    # Set focus
    view.set_cursor(0)
    # Reset installstatus
    installStatus = 'complete'
    # Remove Cancel Button and spinner
    #Gtk.Container.remove(grid, cancelButton)
    Gtk.Container.remove(grid, spinner)

    # Activate Install Now/Done button
    button.set_sensitive(True)
예제 #7
0
파일: ppa.py 프로젝트: jderose/Repoman
class PPA:
    waiting = "Waiting for PPA"
    invalid = "Not a valid PPA"
    valid = "Valid PPA found"
    sources_path = "/etc/apt/sources.list.d/"
    cache = apt.Cache()
    sp = SoftwareProperties()

    def __init__(self, parent):
        self.parent = parent
        self.get_configuration()

    # Returns a list of all 3rd-party software sources.
    def get_isv(self):
        self.sp.reload_sourceslist()
        list = self.sp.get_isv_sources()
        print(list)
        return list

    # Returns the current distro Components.
    def get_distro_sources(self):
        components = self.sp.distro.source_template.components
        return components

    # Returns the current child repos (updates)
    def get_distro_child_repos(self):
        repos = self.sp.distro.source_template.children
        return repos

    # Get whether a component is enabled or not
    def get_comp_download_state(self, comp):
        (active, inconsistent) = self.sp.get_comp_download_state(comp)
        return (active, inconsistent)

    # Get whether a child repo is enabled or not
    def get_child_download_state(self, child):
        (active, inconsistent) = self.sp.get_comp_child_state(child)
        print(child.name + " (" + str(active) + ", " + str(inconsistent) + ")")
        return (active, inconsistent)

    # Get Source Code State
    def get_source_code_enabled(self):
        enabled = self.sp.get_source_code_state()
        if enabled == None:
            return (False, True)
        else:
            return (enabled, False)

    # Enable/Disable a component
    def set_comp_enabled(self, comp, enabled):
        if enabled == True:
            self.sp.enable_component(comp)
        else:
            self.sp.disable_component(comp)
        return 0

    # Enable/Disable a child repo
    def set_child_enabled(self, child, enabled):
        if enabled == True:
            self.sp.enable_child_source(child)
        else:
            self.sp.disable_child_source(child)
        return 0

    # Enable/Disable source code
    def set_source_code_enabled(self, enabled):
        if enabled == True:
            self.sp.enable_source_code_sources()
        elif enabled == False:
            self.sp.disable_source_code_sources()
        return 0

    # Get the current sources configuration
    def get_configuration(self):
        self.enabledDict = {}
        self.update_automation_level = self.sp.get_update_automation_level(
        )  #FIXME Doesn't change
        self.release_upgrades_policy = self.sp.get_release_upgrades_policy(
        )  #0 on, 2 off
        self.source_code_state = self.sp.get_source_code_state()  # Bool

        for comp in self.sp.distro.source_template.components:
            self.enabledDict[comp.name] = self.sp.get_comp_download_state(
                comp)[0]
        self.main_enabled = self.enabledDict['main']
        self.univ_enabled = self.enabledDict['universe']
        self.rest_enabled = self.enabledDict['restricted']
        self.mult_enabled = self.enabledDict['multiverse']

        for child in self.sp.distro.source_template.children:
            if child.type != 'deb-src':
                self.enabledDict[child.name] = self.sp.get_comp_child_state(
                    child)[0]
        self.secu_enabled = self.enabledDict['artful-security']
        self.recc_enabled = self.enabledDict['artful-updates']
        self.back_enabled = self.enabledDict['artful-backports']
        self.prop_enabled = self.enabledDict['artful-proposed']
        return 0

    def get_line(self, enabled, rtype, archs, uri, version, component):
        """Collect all values from the entries and create an apt line"""
        if enabled == True:
            line = ""
        else:
            line = "#"

        line = "%s %s %s %s %s %s" % (line, rtype, archs, uri, version,
                                      component)
        return line

    # Turn an added deb line into an apt source
    def deb_line_to_source(self, line):
        print(line)
        source = self.sp._find_source_from_string(line)
        return source

    # Modify an existing PPA
    def modify_ppa(self, old_source, rtype, archs, uri, version, component):
        print("Old source: %s\n" % old_source)
        print("New source: %s %s %s %s %s" %
              (rtype, archs, uri, version, component))
        line = self.get_line(True, rtype, archs, uri, version, component)
        self.parent.parent.parent.hbar.spinner.start()
        self.parent.parent.parent.stack.list_all.view.set_sensitive(False)
        ModifyThread(self.parent, old_source, line, self.sp).start()

    # Starts a new thread to add a repository
    def add(self, url):
        self.parent.parent.parent.hbar.spinner.start()
        self.parent.parent.parent.stack.list_all.view.set_sensitive(False)
        AddThread(self.parent, url, self.sp).start()

    # Starts a new thread to remove a repository
    def remove(self, ppa):
        self.parent.parent.hbar.spinner.start()
        self.parent.parent.stack.list_all.view.set_sensitive(False)
        RemoveThread(self.parent, self.sources_path, ppa, self.sp).start()

    def list_all(self):
        sp = SoftwareProperties()
        isv_sources = sp.get_isv_sources()
        source_list = []
        for source in isv_sources:
            if not str(source).startswith("#"):
                source_list.append(str(source))
        return source_list
예제 #8
0
파일: list.py 프로젝트: isantop/Repoman_old
    def __init__(self, parent):
        self.sp = SoftwareProperties()
        Gtk.Box.__init__(self, False, 0)
        self.parent = parent
        self.ppa = PPA(self)

        self.settings = Gtk.Settings()

        self.log = logging.getLogger("repoman.List")
        handler = logging.StreamHandler()
        formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
        handler.setFormatter(formatter)
        self.log.addHandler(handler)
        self.log.setLevel(logging.WARNING)

        self.content_grid = Gtk.Grid()
        self.content_grid.set_margin_top(24)
        self.content_grid.set_margin_left(12)
        self.content_grid.set_margin_right(12)
        self.content_grid.set_margin_bottom(12)
        self.content_grid.set_row_spacing(6)
        self.content_grid.set_hexpand(True)
        self.content_grid.set_vexpand(True)
        self.add(self.content_grid)

        sources_title = Gtk.Label(_("Extra Sources"))
        Gtk.StyleContext.add_class(sources_title.get_style_context(), "h2")
        sources_title.set_halign(Gtk.Align.START)
        self.content_grid.attach(sources_title, 0, 0, 1, 1)

        sources_label = Gtk.Label(_("These sources are for software provided by a third party. They may present a security risk or can cause system instability. Only add sources that you trust."))
        sources_label.set_line_wrap(True)
        sources_label.set_halign(Gtk.Align.START)
        sources_label.set_justify(Gtk.Justification.FILL)
        sources_label.set_hexpand(True)
        self.content_grid.attach(sources_label, 0, 1, 1, 1)

        list_grid = Gtk.Grid()
        self.content_grid.attach(list_grid, 0, 2, 1, 1)
        list_window = Gtk.ScrolledWindow()
        list_grid.attach(list_window, 0, 0, 1, 1)

        self.ppa_liststore = Gtk.ListStore(str, str)
        self.view = Gtk.TreeView(self.ppa_liststore)
        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn(_("Source"), renderer, markup=0)
        self.view.append_column(column)
        self.view.set_hexpand(True)
        self.view.set_vexpand(True)
        self.view.connect("row-activated", self.on_row_activated)
        tree_selection = self.view.get_selection()
        tree_selection.connect('changed', self.on_row_change)
        list_window.add(self.view)

        # add button
        add_button = Gtk.ToolButton()
        add_button.set_icon_name("list-add-symbolic")
        Gtk.StyleContext.add_class(add_button.get_style_context(),
                                   "image-button")
        add_button.set_tooltip_text(_("Add New Source"))
        add_button.connect("clicked", self.on_add_button_clicked)

        # edit button
        edit_button = Gtk.ToolButton()
        edit_button.set_icon_name("edit-symbolic")
        Gtk.StyleContext.add_class(edit_button.get_style_context(),
                                   "image-button")
        edit_button.set_tooltip_text(_("Modify Selected Source"))
        edit_button.connect("clicked", self.on_edit_button_clicked)

        action_bar = Gtk.Toolbar()
        action_bar.set_icon_size(Gtk.IconSize.SMALL_TOOLBAR)
        Gtk.StyleContext.add_class(action_bar.get_style_context(),
                                   "inline-toolbar")
        action_bar.insert(edit_button, 0)
        action_bar.insert(add_button, 0)
        list_grid.attach(action_bar, 0, 1, 1, 1)

        self.generate_entries(self.ppa.get_isv())
예제 #9
0
class PPA:
    waiting = "Waiting for PPA"
    invalid = "Not a valid PPA"
    valid = "Valid PPA found"
    sources_path = "/etc/apt/sources.list.d/"
    cache = apt.Cache()
    sp = SoftwareProperties()

    def __init__(self, parent=None):
        self.parent = parent

        self.log = logging.getLogger("repoman.Updates")
        handler = logging.StreamHandler()
        formatter = logging.Formatter(
            '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
        handler.setFormatter(formatter)
        self.log.addHandler(handler)
        self.log.setLevel(logging.WARNING)

    # Returns a list of all 3rd-party software sources.
    def get_isv(self):
        self.sp.reload_sourceslist()
        list = self.sp.get_isv_sources()
        return list

    # Returns the current distro Components.
    def get_distro_sources(self):
        components = self.sp.distro.source_template.components
        return components

    # Returns the current child repos (updates)
    def get_distro_child_repos(self):
        repos = self.sp.distro.source_template.children
        return repos

    # Get whether a component is enabled or not
    def get_comp_download_state(self, comp):
        (active, inconsistent) = self.sp.get_comp_download_state(comp)
        return (active, inconsistent)

    # Get whether a child repo is enabled or not
    def get_child_download_state(self, child):
        (active, inconsistent) = self.sp.get_comp_child_state(child)
        self.log.debug(child.name + " (" + str(active) + ", " +
                       str(inconsistent) + ")")
        return (active, inconsistent)

    # Get Source Code State
    def get_source_code_enabled(self):
        enabled = self.sp.get_source_code_state()
        if enabled == None:
            return (False, True)
        else:
            return (enabled, False)

    # Enable/Disable a component
    def set_comp_enabled(self, comp, enabled):
        self.log.info('Component: %s\nEnabled: %s' % (comp, enabled))
        try:
            remote_object.SetCompEnabled(comp, enabled)
        except:
            self.exc = sys.exc_info()
            self.throw_error(self.exc[1])
        return 0

    # Enable/Disable a child repo
    def set_child_enabled(self, child, enabled):
        self.log.info('Child: %s\nEnabled: %s' % (child, enabled))
        try:
            remote_object.SetChildEnabled(child.name, enabled)
        except:
            self.exc = sys.exc_info()
            self.throw_error(self.exc[1])
        return 0

    # Enable/Disable source code
    def set_source_code_enabled(self, enabled):
        self.log.info('Source enabled: %s' % enabled)
        try:
            remote_object.SetSourceCodeEnabled(enabled)
        except:
            self.exc = sys.exc_info()
            self.throw_error(self.exc[1])
        return 0

    def get_line(self, isdisabled, rtype, archs, uri, version, component):
        """Collect all values from the entries and create an apt line"""
        if isdisabled == True:
            disstr = "#"
        else:
            disstr = ""

        if archs == "[arch]":
            archs = ""

        line = "%s%s %s %s %s %s" % (disstr, rtype, archs, uri, version,
                                     component)
        return line

    # Turn an added deb line into an apt source
    def deb_line_to_source(self, line):
        self.log.info(line)
        source = self.sp._find_source_from_string(line)
        return source

    # Modify an existing PPA
    def modify_ppa(self, old_source, disabled, rtype, archs, uri, version,
                   component):
        self.log.info("Old source: %s" % old_source)
        line = self.get_line(disabled, rtype, archs, uri, version, component)
        self.log.info("New source: %s" % line)
        self.parent.parent.parent.hbar.spinner.start()
        self.parent.parent.parent.stack.list_all.view.set_sensitive(False)
        ModifyThread(self.parent, old_source, line, self.sp).start()

    # Starts a new thread to add a repository
    def add(self, url):
        self.log.info("Adding source: %s" % url)
        print(type(url))
        self.parent.parent.parent.hbar.spinner.start()
        self.parent.parent.parent.stack.list_all.view.set_sensitive(False)
        t = AddThread(self.parent, url, self.sp)
        t.start()

    # Starts a new thread to remove a repository
    def remove(self, ppa):
        self.log.info("Removing source: %s" % ppa)
        self.parent.parent.hbar.spinner.start()
        self.parent.parent.stack.list_all.view.set_sensitive(False)
        RemoveThread(self.parent, self.sources_path, ppa, self.sp).start()

    # Validate if a line appears to be a valid apt line or ppa.
    def validate(self, line):

        if line.startswith("deb"):
            if "http" in line:
                return True

        elif line.startswith("ppa:"):
            if "/" in line:
                return True

        elif line.startswith("http"):
            if "://" in line:
                return True

        else:
            return False

    # Get the current OS name, or fallback if not available
    def get_os_name(self):
        try:
            with open("/etc/os-release") as os_release_file:
                os_release = os_release_file.readlines()
                for line in os_release:
                    parse = line.split('=')
                    if parse[0] == "NAME":
                        if parse[1].startswith('"'):
                            return parse[1][1:-2]
                        else:
                            return parse[1][:-1]
                    else:
                        continue
        except FileNotFoundError:
            return "your OS"

        return "your OS"

    def throw_error(self, message):
        GObject.idle_add(
            self.parent.parent.parent.stack.list_all.throw_error_dialog,
            message, "error")
예제 #10
0
    # Import softwareproperties
    try:
        from softwareproperties.SoftwareProperties import SoftwareProperties
    except ImportError:
        pkg = apt_cache['python-software-properties']
        if pkg.is_installed:
            logger.error('Package:  python-software-propertiesis already installed but python cannot import library.')
        else:
            pkg.mark_install()

        try:
            apt_cache.commit()
            from softwareproperties.SoftwareProperties import SoftwareProperties
        except Exception, err:
            logger.error('Package installation has failed: %s', str(err))
            sys.exit(1)

    # Add ppa
    logger.debug('Add Openvswitch PPA')
    sp = SoftwareProperties()
    sp.add_source_from_line('ppa:sgran/openvswitch-precise')
    sp.sourceslist.save()
    logger.debug(subprocess.check_output('apt-get update',shell=True))
    new_apt_cache = apt.cache.Cache()
    apt_cache = new_apt_cache

    main(args)

    logger.info('Finished!')
    sys.exit(0)
 def setUp(self):
     self.temp_dir = tempfile.mkdtemp()
     self.sp = SoftwareProperties()
     self.mock_key = os.path.join(self.temp_dir, u"määäp.asc")
     with open(self.mock_key, "wb") as fp:
         fp.write(u"bäää".encode("utf-8"))