Пример #1
0
    def maybe_sync_appstream(self, executor, source):
        """ Check if appstream data needs updating """

        # Do we need appstream data update?
        fremote = source.get_remote()
        modtime = 0
        try:
            updatefile = fremote.get_appstream_timestamp()
            finfo = updatefile.query_info("*", 0, None)
            modtime = finfo.get_modification_time().tv_sec
            print(modtime)
        except Exception as e:
            print(e)

        time_now = GLib.get_current_time()

        if time_now - modtime < APPSTREAM_THRESHOLD_SECS:
            print("AppStream data for {} is up to date".format(source.name))
            print(time_now - modtime)
            return

        self.executor.set_progress_string(_("Updating AppStream data"))
        self.client.update_appstream_sync(
            source.name,
            Flatpak.get_default_arch(),  # Use local architecture
            None)

        self.executor = None
        print("flatpak appstream synced")
Пример #2
0
def process_full_flatpak_installation(cache):
    fp_time = time.time()

    arch = Flatpak.get_default_arch()
    fp_sys = get_fp_sys()

    flatpak_remote_infos = {}

    try:
        for remote in fp_sys.list_remotes():
            _process_remote(cache, fp_sys, remote, arch)

            remote_name = remote.get_name()

            try:
                for ref in fp_sys.list_installed_refs_by_kind(
                        Flatpak.RefKind.APP, None):
                    # All remotes will see installed refs, but the installed refs will always
                    # report their correct origin, so only add installed refs when they match the remote.
                    if ref.get_origin() == remote_name:
                        _add_package_to_cache(cache, ref, remote.get_url(),
                                              True)
            except GLib.Error as e:
                print(e.message)

            flatpak_remote_infos[remote_name] = FlatpakRemoteInfo(remote)

    except GLib.Error as e:
        print("Installer: flatpak - could not get remote list", e.message)
        cache = {}

    print('Installer: Processing Flatpaks for cache took %0.3f ms' %
          ((time.time() - fp_time) * 1000.0))

    return cache, flatpak_remote_infos
Пример #3
0
def _find_remote_ref_from_list(fp_sys, remote_name, basic_ref, nofail=False):
    remote_ref = None

    all_refs = fp_sys.list_remote_refs_sync(remote_name, None)

    ref_str = basic_ref.format_ref()

    for ref in all_refs:
        if ref_str == ref.format_ref():
            remote_ref = ref
            break

    if remote_ref == None:
        try:
            remote_ref = fp_sys.fetch_remote_ref_sync(remote_name,
                                                      basic_ref.get_kind(),
                                                      basic_ref.get_name(),
                                                      basic_ref.get_arch(),
                                                      basic_ref.get_branch(),
                                                      None)
        except GLib.Error as e:
            if nofail:
                remote_ref = Flatpak.RemoteRef(
                    remote_name=remote_name,
                    kind=basic_ref.get_kind(),
                    arch=basic_ref.get_arch(),
                    branch=basic_ref.get_branch(),
                    name=basic_ref.get_name(),
                    commit=basic_ref.get_commit(),
                    collection_id=basic_ref.get_collection_id())
    return remote_ref
Пример #4
0
	def _install(self,app_info):
		#self._debug("Installing %s"%app_info['name'])
		action="install"
		flInst=Flatpak.get_system_installations()
		for installer in flInst:
			flRemote=installer.list_remotes()
			remoteInst=installer
			for remote in flRemote:
				remoteName=remote.get_name()
				break
			transaction=Flatpak.Transaction.new_for_installation(installer)
			break
#		ref=remoteInst.install(remoteName,Flatpak.RefKind.APP,app_info['id'],None,'stable',None,None,None)
#		for relRef in remoteInst.list_remote_related_refs_sync(remoteName,ref.format_ref()):
#			if relRef.should_download():
#				self._debug("Installing related ref %s"%relRef.get_name())
#				remoteInst.install(remoteName,Flatpak.RefKind.APP,relRef.format_ref(),None,'stable',None,None,None)

		if transaction:
	   	#Get remote ref
			self._debug(remoteName)
			remoteRef=remoteInst.fetch_remote_ref_sync(remoteName,Flatpak.RefKind.APP,app_info['id'],None,'stable',None)
			self._debug(remoteRef)
			self._debug(app_info['id'])
			#transaction.add_install(remoteName,remoteRef.get_remote_name(),None)
			transaction.add_install(remoteName,remoteRef.format_ref(),None)
			self._debug(transaction)
			transaction.run()
	   #self._debug("Installed %s"%app_info)
#		self.resultQ[action].put(str(json.dumps([result])))
#		self.progress[action] = 100
#		self.progressQ[action].put(int(self.progress[action]))
		app_info['state']='installed'
		self._set_status(0)
		return app_info
Пример #5
0
    def maybe_sync_appstream(self, executor, source):
        """ Check if appstream data needs updating """

        # Do we need appstream data update?
        fremote = source.get_remote()
        modtime = 0
        try:
            updatefile = fremote.get_appstream_timestamp()
            finfo = updatefile.query_info("*", 0, None)
            modtime = finfo.get_modification_time().tv_sec
            print(modtime)
        except Exception as e:
            print(e)

        time_now = GLib.get_current_time()

        if time_now - modtime < APPSTREAM_THRESHOLD_SECS:
            print("AppStream data for {} is up to date".format(source.name))
            print(time_now - modtime)
            return

        self.executor.set_progress_string(_("Updating AppStream data"))
        self.client.update_appstream_sync(
            source.name,
            Flatpak.get_default_arch(),  # Use local architecture
            None)

        self.executor = None
        print("flatpak appstream synced")
Пример #6
0
    def __init__(self, installation, config=None, is_cache_repo=False):
        self.installation = installation
        self.installation_path = self.installation.get_path().get_path()

        self.config = config
        if self.config is None:
            self.config = eib.get_config()

        self.is_cache_repo = is_cache_repo

        self.install_refs = None

        # Get architecture from generic flatpak section, falling back to
        # default arch for host. The config default is an empty string,
        # so the direct fallback mechanism doesn't work.
        self.arch = self.config.get('flatpak', 'arch', fallback=None)
        if not self.arch:
            self.arch = Flatpak.get_default_arch()
        logger.info('Using flatpak arch %s', self.arch)

        # Get locales configuration from generic flatpak section
        self.locales = self.config.get('flatpak', 'locales',
                                       fallback=()).split()
        if self.locales:
            logger.info('Using flatpak locales %s', ' '.join(self.locales))

        # See if collection IDs should be set
        self.enable_p2p_updates = self.config.getboolean('flatpak',
                                                         'enable_p2p_updates',
                                                         fallback=False)

        # See if extra-languages should be set
        self.set_extra_languages = self.config.getboolean(
            'flatpak', 'set_extra_languages', fallback=False)

        self.remotes = OrderedDict()
        for sect in self.config.sections():
            head, sep, name = sect.partition(self.REMOTE_PREFIX)
            if sep == '' or head != '':
                # Not a section beginning with the prefix
                continue
            if name == '':
                # No name after the prefix
                raise FlatpakError('No remote name suffix in config section',
                                   sect)

            # Skip if the remote is disabled
            remote_enabled = self.config.getboolean(sect,
                                                    'enable',
                                                    fallback=True)
            if not remote_enabled:
                logger.info('Remote %s disabled, skipping', name)
                continue

            # Pass the remote options as keyword arguments to
            # FlatpakRemote after removing unrecognized options
            remote_options = dict(self.config.items(sect))
            remote_options.pop('enable', None)
            logger.debug('Remote %s options: %s', name, remote_options)
            self.remotes[name] = FlatpakRemote(self, name, **remote_options)
Пример #7
0
def _pick_refs_for_installation(task):
    fp_sys = get_fp_sys()

    pkginfo = task.pkginfo
    refid = pkginfo.refid

    ref = Flatpak.Ref.parse(refid)
    remote_name = pkginfo.remote

    try:
        remote_ref = Flatpak.RemoteRef(remote_name=remote_name,
                                       kind=ref.get_kind(),
                                       arch=ref.get_arch(),
                                       branch=ref.get_branch(),
                                       name=ref.get_name(),
                                       commit=ref.get_commit(),
                                       collection_id=ref.get_collection_id())

        _add_ref_to_task(fp_sys, task, remote_ref)

        update_list = fp_sys.list_installed_refs_for_update(None)

        runtime_ref = _get_runtime_ref(fp_sys, remote_name, remote_ref)

        if not _is_ref_installed(fp_sys, runtime_ref):
            _add_ref_to_task(fp_sys, task, runtime_ref)
        else:
            if runtime_ref in update_list:
                _add_ref_to_task(fp_sys, task, runtime_ref, needs_update=True)

        all_related_refs = _get_remote_related_refs(fp_sys, remote_ref.get_remote_name(), remote_ref)
        all_related_refs += _get_remote_related_refs(fp_sys, runtime_ref.get_remote_name(), runtime_ref)
        all_related_refs += _get_theme_refs(fp_sys, runtime_ref.get_remote_name(), runtime_ref)

        for related_ref in all_related_refs:
            if not _is_ref_installed(fp_sys, related_ref):
                _add_ref_to_task(fp_sys, task, related_ref)
            else:
                if related_ref in update_list:
                    _add_ref_to_task(fp_sys, task, related_ref, needs_update=True)

    except Exception as e:
        # Something went wrong, bail out
        task.info_ready_status = task.STATUS_BROKEN
        task.error_message = str(e)
        dialogs.show_flatpak_error(task.error_message)
        if task.info_ready_callback:
            GObject.idle_add(task.info_ready_callback, task)
        return

    print("For installation:")
    for ref in task.to_install:
        print(ref.format_ref())

    task.info_ready_status = task.STATUS_OK
    task.execute = execute_transaction

    if task.info_ready_callback:
        GObject.idle_add(task.info_ready_callback, task)
Пример #8
0
	def _get_info(self,app_info):
		flInst=Flatpak.get_system_installations()
		for installer in flInst:
			flRemote=installer.list_remotes()
			remoteInst=installer
			break
		try:
			installer.get_installed_ref(Flatpak.RefKind.APP,app_info['id'],None,'stable',None)
			app_info['state']='installed'
		except Exception as e:
			app_info['state']='available'
		self._set_status(0)
		return app_info
Пример #9
0
    def populate_category(self, storage, category):
        """ Populate the storage with refs from the given category """
        if not category.get_id().startswith("flatpak:"):
            return
        remote_apps = self.client.list_remote_refs_sync(
            category.source.name, None)

        for remote_app in remote_apps:
            # Only want apps
            if not remote_app.get_kind() == Flatpak.RefKind.APP:
                continue
            # Only support native arch
            if remote_app.get_arch() != Flatpak.get_default_arch():
                continue
            item = self.build_item(remote_app)
            storage.add_item(item.get_id(), item, PopulationFilter.CATEGORY)
Пример #10
0
        def __init__(self):
            #determine if Superuser or not to determine install target
            if getpass.getuser() == "root":
                self.superuser = True
            else:
                self.superuser = False

            self.arch = Flatpak.get_default_arch()

            self.item_count = 0
            self.current_count = 0

            self.taskstbinstalled = {}
            self.taskstbupdated = {}
            self.taskstbremoved = {}

            self.flatpakoverridesiceaccess = ["org.mozilla.firefox"]
            self.flatpakoverridesonlyadwaita = ["org.mozilla.firefox"]
            
            if self.superuser == True:
                self.flatpakclassthing = Flatpak.Installation.new_system()
                self.flatpakclassthingalt = self.flatpakclassthing
            else:
                self.flatpakclassthing = Flatpak.Installation.new_user()
                self.flatpakclassthingalt = Flatpak.Installation.new_system()
            self.transaction = Flatpak.Transaction.new_for_installation(self.flatpakclassthing)

            self.flatpakremotes = self.flatpakclassthing.list_remotes()
            if self.flatpakclassthing != self.flatpakclassthingalt:
                for flatpakremote in self.flatpakclassthingalt.list_remotes():
                    if flatpakremote not in self.flatpakremotes:
                        self.flatpakremotes.append(flatpakremote)

            self.all_refs = []
            for remote_name in self.flatpakremotes:
                try:
                    self.all_refs.extend(self.flatpakclassthing.list_remote_refs_sync(remote_name.get_name(), None))
                    if self.flatpakclassthing != self.flatpakclassthingalt:
                        for i in self.flatpakclassthingalt.list_remote_refs_sync(remote_name.get_name(), None):
                            if i not in self.all_refs:
                                self.all_refs.append(i)
                except:
                    try:
                        self.all_refs.extend(self.flatpakclassthingalt.list_remote_refs_sync(remote_name.get_name(), None))
                    except:
                        pass
Пример #11
0
    def populate_category(self, storage, category):
        """ Populate the storage with refs from the given category """
        if not category.get_id().startswith("flatpak:"):
            return
        remote_apps = self.client.list_remote_refs_sync(
            category.source.name,
            None)

        for remote_app in remote_apps:
            # Only want apps
            if not remote_app.get_kind() == Flatpak.RefKind.APP:
                continue
            # Only support native arch
            if remote_app.get_arch() != Flatpak.get_default_arch():
                continue
            item = self.build_item(remote_app)
            storage.add_item(item.get_id(), item, PopulationFilter.CATEGORY)
def main():
    # Send logging messages both to the console and the journal
    logging.basicConfig(level=logging.INFO)
    logging.root.addHandler(journal.JournalHandler())

    parser = argparse.ArgumentParser()
    parser.add_argument('--debug', dest='debug', action='store_true')
    parser.add_argument('--app-id',
                        dest='app_id',
                        help='Flatpak App ID',
                        type=str,
                        required=True)
    parser.add_argument('--remote',
                        dest='remote',
                        help='Flatpak Remote',
                        type=str,
                        required=True)
    parser.add_argument('--branch',
                        dest='branch',
                        help='Flatpak Branch',
                        type=str,
                        default='',
                        required=False)
    parser.add_argument('--required-archs',
                        dest='required_archs',
                        default=[],
                        nargs='*',
                        type=str)

    parsed_args = parser.parse_args()

    if parsed_args.debug:
        logging.root.setLevel(logging.DEBUG)

    if parsed_args.required_archs and Flatpak.get_default_arch(
    ) not in parsed_args.required_archs:
        exit_with_error(
            "Found installation of unsupported architecture: {}".format(
                parsed_args.required_archs))

    InstallAppHelperInstaller(parsed_args.app_id, parsed_args.remote,
                              parsed_args.branch)
    sys.exit(0)
def main():
    # Send logging messages both to the console and the journal
    logging.basicConfig(level=logging.INFO)
    logging.root.addHandler(journal.JournalHandler())

    parser = argparse.ArgumentParser()
    parser.add_argument('--debug', dest='debug', action='store_true')

    parsed_args = parser.parse_args()

    if parsed_args.debug:
        logging.root.setLevel(logging.DEBUG)

    app_arch = Flatpak.get_default_arch()
    if app_arch != 'x86_64':
        exit_with_error("Found installation of unsupported architecture: %s",
                        app_arch)

    GoogleChromeInstaller()
    sys.exit(0)
Пример #14
0
    def checkinstalled(ref, userland):
        if userland == False:
            flatpakclassthing = Flatpak.Installation.new_system()
        else:
            flatpakclassthing = Flatpak.Installation.new_user()
        flatpakremotes = flatpakclassthing.list_remotes()
        all_refs = []
        for remote_name in flatpakremotes:
            try:
                for i in flatpakclassthing.list_remote_refs_sync(
                        remote_name.get_name(), None):
                    if i not in all_refs:
                        all_refs.append(i)
            except:
                pass
        ref2 = ""
        arch = Flatpak.get_default_arch()
        for i in all_refs:
            if i.get_name() == ref and i.get_arch() == arch:
                ref2 = i

        try:
            iref = flatpakclassthing.get_installed_ref(ref2.get_kind(),
                                                       ref2.get_name(),
                                                       ref2.get_arch(),
                                                       ref2.get_branch(), None)

            if iref:
                if ref2 in flatpakclassthing.list_installed_refs_for_update(
                        None):
                    return (3)
                else:
                    return (1)
        except GLib.Error:
            pass
        except AttributeError:  # bad/null ref
            pass
        return (2)
Пример #15
0
	def _remove(self,app_info):
		action='remove'
		flInst=Flatpak.get_system_installations()
		for installer in flInst:
			flRemote=installer.list_remotes()
			remoteInst=installer
			for remote in flRemote:
				remoteName=remote.get_name()
				break
			transaction=Flatpak.Transaction.new_for_installation(installer)
			break
		if transaction:
	   	#Get remote ref
			self._debug(remoteName)
			remoteRef=remoteInst.fetch_remote_ref_sync(remoteName,Flatpak.RefKind.APP,app_info['id'],None,'stable',None)
			self._debug(remoteRef)
			self._debug(app_info['id'])
			#transaction.add_install(remoteName,remoteRef.get_remote_name(),None)
			transaction.add_uninstall(remoteRef.format_ref())
			self._debug(transaction)
			transaction.run()
		app_info['state']='available'
		self._set_status(0)
		return app_info
                        help='Flatpak Remote',
                        type=str,
                        required=True)
    parser.add_argument('--branch',
                        dest='branch',
                        help='Flatpak Branch',
                        type=str,
                        default='',
                        required=False)
    parser.add_argument('--required-archs',
                        dest='required_archs',
                        default=[],
                        nargs='*',
                        type=str)

    parsed_args, otherargs = parser.parse_known_args()

    if parsed_args.debug:
        logging.root.setLevel(logging.DEBUG)

    # Some apps are only available for certain architectures
    if parsed_args.required_archs and Flatpak.get_default_arch(
    ) not in parsed_args.required_archs:
        exit_with_error(
            "Found installation of unsupported architecture: {}".format(
                parsed_args.required_archs))

    InstallAppHelperLauncher(parsed_args.app_id, parsed_args.remote,
                             parsed_args.branch, otherargs)
    sys.exit(0)
Пример #17
0
    def __init__(self, application, flatpak_installation, tree_model, show_button):
        self.Application = application

        self.FlatpakInstallation = flatpak_installation
        self.RefsToUpdate = flatpak_installation.list_installed_refs_for_update(Gio.Cancellable.new())
        self.InstalledRefsList = self.FlatpakInstallation.list_installed_refs()
        self.FlatHubRefsList = self.FlatpakInstallation.list_remote_refs_sync(
            "flathub", Gio.Cancellable.new())
        self.NonInstalledRefsList = []

        for item in self.FlatHubRefsList:
            self.NonInstalledRefsList.append(item)
            for item_2 in self.InstalledRefsList:
                if item.get_name() == item_2.get_name() and \
                        item.get_arch() == item_2.get_arch() and \
                        item.get_branch() == item_2.get_branch():
                    if len(self.NonInstalledRefsList) != 0:
                        self.NonInstalledRefsList.pop(len(self.NonInstalledRefsList) - 1)
                    else:
                        self.NonInstalledRefsList = []

        self.FlatpakTransaction = \
            Flatpak.Transaction.new_for_installation(
                self.FlatpakInstallation,
                Gio.Cancellable.new())
        self.FlatpakTransaction.set_default_arch(Flatpak.get_default_arch())
        self.FlatpakTransaction.set_disable_dependencies(False)
        self.FlatpakTransaction.set_disable_prune(False)
        self.FlatpakTransaction.set_disable_related(False)
        self.FlatpakTransaction.set_disable_static_deltas(False)
        self.FlatpakTransaction.set_no_deploy(False)
        self.FlatpakTransaction.set_no_pull(False)
        for ref_to_update in self.RefsToUpdate:
            ref_str = ref_to_update.format_ref()
            self.FlatpakTransaction.add_update(ref_str, None, None)

        self.TreeModel = tree_model
        self.HeaderBarShowButton = show_button

        try:
            update_all_gui_file = "/usr/share/pardus/pardus-flatpak-gui/ui/actionwindow.glade"
            update_all_builder = Gtk.Builder.new_from_file(update_all_gui_file)
            update_all_builder.connect_signals(self)
        except GLib.GError:
            print(_("Error reading GUI file: ") + update_all_gui_file)
            raise

        self.UpdateAllCancellation = Gio.Cancellable.new()

        self.UpdateAllWindow = update_all_builder.get_object("ActionWindow")
        self.UpdateAllWindow.set_application(application)
        self.UpdateAllWindow.set_title(_("Updating All"))
        self.UpdateAllWindow.show()

        self.UpdateAllButtonCancel = update_all_builder.get_object("ActionButtonCancel")
        self.UpdateAllButtonCancel.set_sensitive(True)

        self.UpdateAllProgressBar = update_all_builder.get_object(
                                        "ActionProgressBar")
        self.ProgressBarValue = int(
            self.UpdateAllProgressBar.get_fraction() * 100)

        self.UpdateAllLabel = update_all_builder.get_object("ActionLabel")
        self.UpdateAllTextBuffer = update_all_builder.get_object(
                                       "ActionTextBuffer")

        self.UpdateAllTextBuffer.set_text("\0", -1)
        self.StatusText = _("Updating...")
        self.UpdateAllLabel.set_text(self.StatusText)
        self.UpdateAllTextBuffer.set_text(self.StatusText)

        self.handler_id = self.FlatpakTransaction.connect(
            "new-operation",
            self.update_all_progress_callback)
        self.handler_id_2 = self.FlatpakTransaction.connect(
            "operation-done",
            self.update_all_progress_callback_done)
        self.handler_id_error = self.FlatpakTransaction.connect(
            "operation-error",
            self.update_all_progress_callback_error)

        self.UpdateAllThread = threading.Thread(
                           target=self.update_all,
                           args=())
        self.UpdateAllThread.start()
        GLib.threads_init()
Пример #18
0
def _get_remote_related_refs(fp_sys, remote, ref):
    return_refs = []

    try:
        related_refs = fp_sys.list_remote_related_refs_sync(remote,
                                                            ref.format_ref(),
                                                            None)

        for related_ref in related_refs:
            real_ref = None

            if not related_ref.should_download():
                continue

            print("Looking for related ref %s in remote %s" % (related_ref.get_name(), remote))

            try:
                real_ref = fp_sys.fetch_remote_ref_sync(remote,
                                                        related_ref.get_kind(),
                                                        related_ref.get_name(),
                                                        related_ref.get_arch(),
                                                        related_ref.get_branch(),
                                                        None)
            except GLib.Error:
                pass

            if real_ref == None:
                for other_remote in fp_sys.list_remotes():
                    other_remote_name = other_remote.get_name()

                    if other_remote_name == remote:
                        continue

                    print("Looking for related ref %s in alternate remote %s" % (related_ref.get_name(), other_remote_name))

                    try:
                        real_ref = fp_sys.fetch_remote_ref_sync(other_remote_name,
                                                                related_ref.get_kind(),
                                                                related_ref.get_name(),
                                                                related_ref.get_arch(),
                                                                related_ref.get_branch(),
                                                                None)
                    except GLib.Error:
                        continue

                    if real_ref:
                        break
            if real_ref == None:
                real_ref = Flatpak.RemoteRef(remote_name=remote,
                                             kind=related_ref.get_kind(),
                                             arch=related_ref.get_arch(),
                                             branch=related_ref.get_branch(),
                                             name=related_ref.get_name(),
                                             commit=related_ref.get_commit(),
                                             collection_id=related_ref.get_collection_id())

            return_refs.append(real_ref)
    except GLib.Error as e:
        raise Exception("Could not determine remote related refs for app: %s" % e.message)

    return return_refs
Пример #19
0
	def _get_flatpak_catalogue(self):
		action="load"
		rebostPkgList=[]
		sections=[]
		progress=0
		inc=0
		flInst=''
		store=appstream.Store()
		store2=appstream.Store()
		#metadata=appstream.Metadata()
		try:
			#Get all the remotes, copy appstream to wrkdir
			flInst=Flatpak.get_system_installations()
			for installer in flInst:
				flRemote=installer.list_remotes()
				for remote in flRemote:
					srcDir=remote.get_appstream_dir().get_path()
					installer.update_appstream_sync(remote.get_name())
			#sections=self.snap_client.get_sections_sync()
		except Exception as e:
			print(e)
			#self._on_error("load",e)

		try:
			store.from_file(Gio.File.parse_name(os.path.join(srcDir,"appstream.xml")))
		except Exception as e:
			print(e)
			pass
		added=[]
		for pkg in store.get_apps():
			idx=pkg.get_id()
			idxList=idx.split(".")
			if len(idxList)>2:
				idxList[0]="org"
				idxList[1]="flathub"
				newId=".".join(idxList).lower()
			else:
				newId="org.flathub.{}".format(idx[-1])
			#pkg.set_id(newId)
			state="available"
			for installer in flInst:
				installed=False
				try:
					installed=installer.get_installed_ref(0,pkg.get_name())
				except:
					try:
						installed=installer.get_installed_ref(1,pkg.get_name())
					except:
						pass
				if installed:
					state="installed"
					break
			#flatpak has his own cache dir for icons so if present use it
			iconPath=''
			icon64=os.path.join(srcDir,"icons/64x64")
			icon128=os.path.join(srcDir,"icons/128x128")
			idx=idx.replace(".desktop","")
			if os.path.isfile(os.path.join(icon128,"{}.png".format(idx))):
				iconPath=os.path.join(icon128,"{}.png".format(idx))
			elif os.path.isfile(os.path.join(icon64,"{}.png".format(idx))):
				iconPath=os.path.join(icon64,"{}.png".format(idx))
			if iconPath!='':
				icon=appstream.Icon()
				icon.set_kind(appstream.IconKind.LOCAL)
				icon.set_filename(iconPath)
				pkg.add_icon(icon)
			add=False
			if not pkg.get_bundles():
				bundle=appstream.Bundle()
				bundle.set_id("{};amd64;{}".format(pkg.get_id(),state))
				bundle.set_kind(appstream.BundleKind.FLATPAK)
				pkg.add_bundle(bundle)
				add=True
			else:
				for bundle in pkg.get_bundles():
					bundle.set_id("{};amd64;{}".format(pkg.get_id(),state))
					bundle.set_kind(appstream.BundleKind.FLATPAK)
					add=True
			if add and pkg.get_id() not in added:
				try:
						#	if not (app.validate()):
					pkg.set_name("C",pkg.get_name().lower().replace(" ","_")+'.flatpak')
					pkg.add_pkgname(pkg.get_name())
					store2.add_app(pkg)
				#	else:
				#		pass
				#		print(app.validate())
				except:
					pass
				added.append(pkg.get_id())
		self._debug("Loaded flatpak metadata")
		return(store2)
        installation.install(test_remote,
                             Flatpak.RefKind.APP,
                             test_app_id, None, test_branch,
                             _progress_callback,
                             None,
                             None)
        print("\n{} successfully installed".format(test_app_id))
    except GLib.Error as e:
        print("Could not install {}: {}".format(test_app_id, e.message))

    # Backup the app now.
    print("\n2. Backing up app {} to {}...".format(test_app_id, test_backup_dir))
    backup_app(test_app_id, test_remote, test_backup_dir, parsed_args.interactive)

    # Can't restore and app if it's installed!
    try:
        print("\n3. Making sure {} is NOT installed before restoring...".format(test_app_id))
        installation.uninstall(Flatpak.RefKind.APP,
                               test_app_id, Flatpak.get_default_arch(), test_branch,
                               _progress_callback,
                               None,
                               None)
        print("\n{} successfully uninstalled".format(test_app_id))
    except GLib.Error as e:
        print("Could not uninstall {}: {}".format(test_app_id, e.message))

    # Finally, restore the app.
    print("\n4. Restoring app {} from {}...".format(test_app_id, test_backup_dir))
    restore_app(test_app_id, test_remote, test_backup_dir, parsed_args.interactive)
    sys.exit(0)
Пример #21
0
def _pkginfo_from_file_thread(cache, file, callback):
    fp_sys = get_fp_sys()

    path = file.get_path()

    if path == None:
        print("Installer: flatpak - no valid .flatpakref path provided")
        return None

    ref = None
    pkginfo = None
    remote_name = None

    with open(path) as f:
        contents = f.read()

        b = contents.encode("utf-8")
        gb = GLib.Bytes(b)

        try:
            kf = GLib.KeyFile()
            if kf.load_from_file(path, GLib.KeyFileFlags.NONE):
                name = kf.get_string("Flatpak Ref", "Name")
                url = kf.get_string("Flatpak Ref", "Url")

                try:
                    branch = kf.get_string("Flatpak Ref", "Branch")
                except GLib.Error as e:
                    if e.code == GLib.KeyFileError.KEY_NOT_FOUND:
                        print(
                            "Installer: flatpak - flatpakref file doesn't have a Branch key, maybe nightly or testing."
                        )
                        branch = None

                remote_name = _get_remote_name_by_url(fp_sys, url)

                if name and remote_name:
                    ref = Flatpak.RemoteRef(remote_name=remote_name,
                                            kind=Flatpak.RefKind.APP,
                                            arch=Flatpak.get_default_arch(),
                                            branch=branch,
                                            name=name)
                    print(
                        "Installer: flatpak - using existing remote '%s' for flatpakref file install"
                        % remote_name)
                else:  #If Flatpakref is not installed already
                    try:
                        print(
                            "Installer: flatpak - trying to install new remote for flatpakref file"
                        )
                        ref = fp_sys.install_ref_file(gb, None)
                        fp_sys.drop_caches(None)

                        remote_name = ref.get_remote_name()
                        print("Installer: flatpak - added remote '%s'" %
                              remote_name)
                    except GLib.Error as e:
                        if e.code != Gio.DBusError.ACCESS_DENIED:  # user cancelling auth prompt for adding a remote
                            print(
                                "Installer: could not add new remote to system: %s"
                                % e.message)
                            dialogs.show_flatpak_error(e.message)
        except GLib.Error as e:
            print("Installer: flatpak - could not parse flatpakref file: %s" %
                  e.message)
            dialogs.show_flatpak_error(e.message)

        if ref:
            try:
                remote = fp_sys.get_remote_by_name(remote_name, None)

                # Add the ref's remote if it doesn't already exist
                _process_remote(cache, fp_sys, remote,
                                Flatpak.get_default_arch())

                # Add the ref to the cache, so we can work with it like any other in mintinstall
                pkginfo = _add_package_to_cache(cache, ref, remote.get_url(),
                                                False)

                # Fetch the appstream info for the ref
                global _as_pools

                with _as_pool_lock:
                    if remote_name not in _as_pools.keys():
                        _load_appstream_pool(_as_pools, remote)

                # Some flatpakref files will have a pointer to a runtime .flatpakrepo file
                # We need to process and possibly add that remote as well.

                kf = GLib.KeyFile()
                if kf.load_from_file(path, GLib.KeyFileFlags.NONE):
                    try:
                        url = kf.get_string("Flatpak Ref", "RuntimeRepo")
                    except GLib.Error:
                        url = None

                    if url:
                        # Fetch the .flatpakrepo file
                        r = requests.get(url, stream=True)

                        file = tempfile.NamedTemporaryFile(delete=False)

                        with file as fd:
                            for chunk in r.iter_content(chunk_size=128):
                                fd.write(chunk)

                        # Get the true runtime url from the repo file
                        runtime_repo_url = _get_repofile_repo_url(file.name)

                        if runtime_repo_url:
                            existing = False

                            path = Path(file.name)
                            runtime_remote_name = Path(url).stem

                            # Check if the remote is already installed
                            for remote in fp_sys.list_remotes(None):
                                # See comments below in _remote_from_repo_file_thread about get_noenumerate() use.
                                if remote.get_url(
                                ) == runtime_repo_url and not remote.get_noenumerate(
                                ):
                                    print(
                                        "Installer: flatpak - runtime remote '%s' already in system, skipping"
                                        % runtime_remote_name)
                                    existing = True
                                    break

                            if not existing:
                                print(
                                    "Installer: Adding additional runtime remote named '%s' at '%s'"
                                    % (runtime_remote_name, runtime_repo_url))

                                cmd_v = [
                                    'flatpak', 'remote-add', '--from',
                                    runtime_remote_name, file.name
                                ]

                                add_repo_proc = subprocess.Popen(cmd_v)
                                retcode = add_repo_proc.wait()

                                fp_sys.drop_caches(None)
                        os.unlink(file.name)
            except GLib.Error as e:
                print("Installer: could not process .flatpakref file: %s" %
                      e.message)
                dialogs.show_flatpak_error(e.message)

    GLib.idle_add(callback, pkginfo, priority=GLib.PRIORITY_DEFAULT)
Пример #22
0
def _get_theme_refs(fp_sys, remote_name, ref=None):
    if ref:
        arch = ref.get_arch()
    else:
        arch = Flatpak.get_default_arch()

    theme_refs = []

    gtksettings = Gtk.Settings.get_default()

    icon_theme = "org.freedesktop.Platform.Icontheme.%s" % gtksettings.props.gtk_icon_theme_name
    gtk_theme = "org.gtk.Gtk3theme.%s" % gtksettings.props.gtk_theme_name

    def sortref(ref):
        try:
            val = float(ref.get_branch())
        except ValueError:
            val = 9.9

        return val

    for name in (icon_theme, gtk_theme):
        theme_ref = None

        try:
            print("Looking for theme %s in %s" % (name, remote_name))

            all_refs = fp_sys.list_remote_refs_sync(remote_name, None)

            matching_refs = []

            for listed_ref in all_refs:
                if listed_ref.get_name() == name:
                    matching_refs.append(listed_ref)

            if not matching_refs:
                continue

            # Sort highest version first.
            matching_refs = sorted(matching_refs, key=sortref, reverse=True)

            for matching_ref in matching_refs:
                if matching_ref.get_arch() != arch:
                    continue

                theme_ref = matching_ref
                print("Found theme ref '%s' in remote %s" %
                      (theme_ref.format_ref(), remote_name))
                break

            # if nothing is found, check other remotes
            if theme_ref == None:
                for other_remote in fp_sys.list_remotes():
                    other_remote_name = other_remote.get_name()

                    if other_remote_name == remote_name:
                        continue

                    print("Looking for theme %s in alternate remote %s" %
                          (name, other_remote_name))

                    all_refs = fp_sys.list_remote_refs_sync(
                        other_remote_name, None)

                    matching_refs = []

                    for listed_ref in all_refs:
                        if listed_ref.get_name() == name:
                            matching_refs.append(listed_ref)

                    if not matching_refs:
                        continue

                    # Sort highest version first.
                    matching_refs = sorted(matching_refs,
                                           key=sortref,
                                           reverse=True)

                    for matching_ref in matching_refs:
                        if matching_ref.get_arch() != arch:
                            continue

                        theme_ref = matching_ref
                        print("Found theme ref '%s' in alternate remote %s" %
                              (theme_ref.format_ref(), other_remote_name))
                        break

                    if theme_ref:
                        break
                if theme_ref == None:
                    debug(
                        "Could not locate theme '%s' in any registered remotes"
                        % name)
        except GLib.Error as e:
            theme_ref = None
            debug("Error finding themes for flatpak: %s" % e.message)

        if theme_ref:
            theme_refs.append(theme_ref)

    return theme_refs
Пример #23
0
        app_launcher_path = os.path.join(app_path, 'files', 'bin', 'eos-google-chrome-app')
        if not os.path.exists(app_launcher_path):
            exit_with_error("Could not find flatpak launcher for Google Chrome")

        logging.info("Found flatpak launcher for Google Chrome: %s", repr(app_launcher_path))
        return app_launcher_path


if __name__ == '__main__':
    # Send logging messages both to the console and the journal
    logging.basicConfig(level=logging.INFO)
    logging.root.addHandler(journal.JournalHandler())

    parser = argparse.ArgumentParser()
    parser.add_argument('--debug', dest='debug', action='store_true')

    parsed_args, otherargs = parser.parse_known_args()

    if parsed_args.debug:
        logging.root.setLevel(logging.DEBUG)

    # Google Chrome is only available for Intel 64-bit
    app_arch = Flatpak.get_default_arch()
    if app_arch != 'x86_64':
        exit_with_error("Found installation of unsupported architecture: {}".format(app_arch))


    GoogleChromeLauncher(otherargs)
    sys.exit(0)
Пример #24
0
    def __init__(self, application):
        self.Application = application

        try:
            main_gui_file = "/usr/share/pardus/pardus-flatpak-gui/ui/mainwindow.glade"
            main_builder = Gtk.Builder.new_from_file(main_gui_file)
            main_builder.connect_signals(self)
        except GLib.GError:
            print(_("Error reading GUI file: ") + main_gui_file)
            raise

        try:
            about_gui_file = "/usr/share/pardus/pardus-flatpak-gui/ui/aboutdialog.glade"
            about_builder = Gtk.Builder.new_from_file(about_gui_file)
            about_builder.connect_signals(self)
        except GLib.GError:
            print(_("Error reading About dialog GUI file: ") + about_gui_file)
            raise

        try:
            messages_gui_file = "/usr/share/pardus/pardus-flatpak-gui/ui/messagedialogs.glade"
            messages_builder = Gtk.Builder.new_from_file(messages_gui_file)
            messages_builder.connect_signals(self)
        except GLib.GError:
            print(
                _("Error reading message dialogs GUI file: ") +
                messages_gui_file)
            raise

        self.FlatpakInstallation = Flatpak.Installation.new_system()
        self.InstalledRefsList = self.FlatpakInstallation.list_installed_refs()
        self.FlatHubRefsList = self.FlatpakInstallation.list_remote_refs_sync(
            "flathub", Gio.Cancellable.new())
        self.NonInstalledRefsList = []

        for item in self.FlatHubRefsList:
            self.NonInstalledRefsList.append(item)
            for item_2 in self.InstalledRefsList:
                if item.get_name() == item_2.get_name() and \
                        item.get_arch() == item_2.get_arch() and \
                        item.get_branch() == item_2.get_branch():
                    if len(self.NonInstalledRefsList) != 0:
                        self.NonInstalledRefsList.pop(
                            len(self.NonInstalledRefsList) - 1)
                    else:
                        self.NonInstalledRefsList = []

        self.AllRefsList = self.InstalledRefsList + self.NonInstalledRefsList

        self.ListStoreMain = main_builder.get_object("ListStoreMain")

        self.MessageDialogError = messages_builder.get_object(
            "MessageDialogError")
        self.MessageDialogError.set_title(_("Pardus Flatpak GUI Error Dialog"))

        self.MessageDialogQuestion = messages_builder.get_object(
            "MessageDialogQuestion")
        self.MessageDialogQuestion.set_title(
            _("Pardus Flatpak GUI Question Dialog"))

        # Debug print()'s:
        # print("self.FlatHubRefsList:", len(self.FlatHubRefsList))
        # print("self.InstalledRefsList:", len(self.InstalledRefsList))
        # print("self.NonInstalledRefsList:", len(self.NonInstalledRefsList))
        # print("self.AllRefsList:", len(self.AllRefsList))

        for item in self.AllRefsList:
            if item.get_kind() == Flatpak.RefKind.APP and \
                    item.get_arch() == Flatpak.get_default_arch():
                if isinstance(item, Flatpak.RemoteRef):
                    item_is_installed = False
                elif isinstance(item, Flatpak.InstalledRef):
                    item_is_installed = True
                else:
                    item_is_installed = None

                real_name = item.get_name()
                arch = item.get_arch()
                branch = item.get_branch()
                installed_size = item.get_installed_size()
                installed_size_mib = installed_size / 1048576
                installed_size_mib_str = f"{installed_size_mib:.2f}" + " MiB"

                if not item_is_installed:
                    if item in self.FlatHubRefsList:
                        remote_name = "FlatHub"
                    else:
                        remote_name = ""
                    download_size = item.get_download_size()
                    download_size_mib = download_size / 1048576
                    download_size_mib_str = f"{download_size_mib:.2f}" + " MiB"
                    name = ""
                elif item_is_installed:
                    remote_name = item.get_origin()
                    if remote_name == "flathub":
                        remote_name = "FlatHub"
                    download_size_mib_str = ""
                    name = item.get_appdata_name()
                else:
                    remote_name = ""
                    download_size_mib_str = ""
                    name = ""

                    self.MessageDialogError.set_markup(
                        _("<big><b>Invalid Flatpak Reference Error</b></big>"))
                    self.MessageDialogError.format_secondary_text(
                        _("Invalid Flatpak reference is: ") + "app/" +
                        real_name + "/" + arch + "/" + branch)
                    self.MessageDialogError.run()
                    self.MessageDialogError.hide()

                if item_is_installed is not None:
                    self.ListStoreMain.append([
                        real_name, arch, branch, remote_name,
                        installed_size_mib_str, download_size_mib_str, name
                    ])
            else:
                continue

        self.HeaderBarMain = main_builder.get_object("HeaderBarMain")
        self.HeaderBarMain.set_title(_("Pardus Flatpak GUI"))
        self.HeaderBarMain.set_subtitle(
            _("Manage Flatpak softwares via GUI on Pardus"))

        self.RunMenuItem = main_builder.get_object("RunMenuItem")
        self.RunMenuItem.set_label(_("_Run"))

        self.InfoMenuItem = main_builder.get_object("InfoMenuItem")
        self.InfoMenuItem.set_label(_("_Info"))

        self.UninstallMenuItem = main_builder.get_object("UninstallMenuItem")
        self.UninstallMenuItem.set_label(_("_Uninstall"))

        self.InstallMenuItem = main_builder.get_object("InstallMenuItem")
        self.InstallMenuItem.set_label(_("I_nstall"))

        self.ActionsMenu = main_builder.get_object("ActionsMenu")

        self.UpdateAllMenuItem = main_builder.get_object("UpdateAllMenuItem")
        self.UpdateAllMenuItem.set_label(_("_Update All"))

        self.AboutMenuItem = main_builder.get_object("AboutMenuItem")
        self.AboutMenuItem.set_label(_("_About"))

        self.TreeViewColumnRealName = main_builder.get_object(
            "TreeViewColumnRealName")
        self.TreeViewColumnRealName.set_title(_("Real Name"))

        self.TreeViewColumnArch = main_builder.get_object("TreeViewColumnArch")
        self.TreeViewColumnArch.set_title(_("Arch"))

        self.TreeViewColumnBranch = main_builder.get_object(
            "TreeViewColumnBranch")
        self.TreeViewColumnBranch.set_title(_("Branch"))

        self.TreeViewColumnRemoteName = main_builder.get_object(
            "TreeViewColumnRemoteName")
        self.TreeViewColumnRemoteName.set_title(_("Remote Name"))

        self.TreeViewColumnInstalledSize = main_builder.get_object(
            "TreeViewColumnInstalledSize")
        self.TreeViewColumnInstalledSize.set_title(_("Installed Size"))

        self.TreeViewColumnDownloadSize = main_builder.get_object(
            "TreeViewColumnDownloadSize")
        self.TreeViewColumnDownloadSize.set_title(_("Download Size"))

        self.TreeViewColumnName = main_builder.get_object("TreeViewColumnName")
        self.TreeViewColumnName.set_title(_("Name"))

        self.TreeViewMain = main_builder.get_object("TreeViewMain")

        self.TreeSelectionMain = main_builder.get_object("TreeSelectionMain")

        self.SearchEntryMain = main_builder.get_object("SearchEntryMain")
        self.SearchEntryMain.set_placeholder_text(_("Click here for search"))

        self.SearchFilter = main_builder.get_object("SearchFilter")
        self.SearchFilter.set_visible_func(self.search_filter_function)

        self.SortModel = main_builder.get_object("SortModel")
        self.SortModel.set_sort_func(0, self.sorting_compare_function,
                                     (self.TreeViewColumnRealName, 0))
        self.SortModel.set_sort_func(1, self.sorting_compare_function,
                                     (self.TreeViewColumnArch, 1))
        self.SortModel.set_sort_func(2, self.sorting_compare_function,
                                     (self.TreeViewColumnBranch, 2))
        self.SortModel.set_sort_func(3, self.sorting_compare_function,
                                     (self.TreeViewColumnRemoteName, 3))
        self.SortModel.set_sort_func(4, self.sorting_float_compare_function,
                                     (self.TreeViewColumnInstalledSize, 4))
        self.SortModel.set_sort_func(5, self.sorting_float_compare_function,
                                     (self.TreeViewColumnDownloadSize, 5))
        self.SortModel.set_sort_func(6, self.sorting_compare_function,
                                     (self.TreeViewColumnName, 6))

        self.HeaderBarShowButton = main_builder.get_object(
            "HeaderBarShowButton")
        self.HeaderBarShowButton.set_label(_("Show Installed Apps"))

        self.AboutDialog = about_builder.get_object("AboutDialog")
        self.AboutDialog.set_comments(_("Flatpak GUI for Pardus"))
        self.AboutDialog.set_copyright(_("Copyright (C) 2020 Erdem Ersoy"))
        self.AboutDialog.set_program_name(_("Pardus Flatpak GUI"))
        self.AboutDialog.set_version(Version.getVersion())
        self.AboutDialog.set_website_label(_("Pardus Flatpak GUI Web Site"))

        self.MainWindow = main_builder.get_object("MainWindow")
        self.MainWindow.set_application(application)
        self.MainWindow.show()