def main():
    module = AnsibleModule(
        argument_spec = dict(
            state = dict(default='present', choices=['installed', 'latest', 'removed', 'absent', 'present', 'build-dep']),
            update_cache = dict(default=False, aliases=['update-cache'], type='bool'),
            cache_valid_time = dict(type='int'),
            purge = dict(default=False, type='bool'),
            package = dict(default=None, aliases=['pkg', 'name'], type='list'),
            deb = dict(default=None),
            default_release = dict(default=None, aliases=['default-release']),
            install_recommends = dict(default=None, aliases=['install-recommends'], type='bool'),
            force = dict(default='no', type='bool'),
            upgrade = dict(choices=['no', 'yes', 'safe', 'full', 'dist']),
            dpkg_options = dict(default=DPKG_OPTIONS),
            autoremove = dict(type='bool', default=False, aliases=['autoclean'])
        ),
        mutually_exclusive = [['package', 'upgrade', 'deb']],
        required_one_of = [['package', 'upgrade', 'update_cache', 'deb']],
        supports_check_mode = True
    )

    module.run_command_environ_update = APT_ENV_VARS

    if not HAS_PYTHON_APT:
        try:
            module.run_command('apt-get update && apt-get install python-apt -y -q --force-yes', use_unsafe_shell=True, check_rc=True)
            global apt, apt_pkg
            import apt
            import apt.debfile
            import apt_pkg
        except ImportError:
            module.fail_json(msg="Could not import python modules: apt, apt_pkg. Please install python-apt package.")

    global APTITUDE_CMD
    APTITUDE_CMD = module.get_bin_path("aptitude", False)
    global APT_GET_CMD
    APT_GET_CMD = module.get_bin_path("apt-get")

    p = module.params

    if p['upgrade'] == 'no':
        p['upgrade'] = None

    if not APTITUDE_CMD and p.get('upgrade', None) in [ 'full', 'safe', 'yes' ]:
        module.fail_json(msg="Could not find aptitude. Please ensure it is installed.")

    updated_cache = False
    updated_cache_time = 0
    install_recommends = p['install_recommends']
    dpkg_options = expand_dpkg_options(p['dpkg_options'])
    autoremove = p['autoremove']

    # Deal with deprecated aliases
    if p['state'] == 'installed':
        p['state'] = 'present'
    if p['state'] == 'removed':
        p['state'] = 'absent'

    try:
        cache = apt.Cache()
        if p['default_release']:
            try:
                apt_pkg.config['APT::Default-Release'] = p['default_release']
            except AttributeError:
                apt_pkg.Config['APT::Default-Release'] = p['default_release']
            # reopen cache w/ modified config
            cache.open(progress=None)

        if p['update_cache']:
            # Default is: always update the cache
            cache_valid = False
            now = datetime.datetime.now()
            if p.get('cache_valid_time', False):
                try:
                    mtime = os.stat(APT_UPDATE_SUCCESS_STAMP_PATH).st_mtime
                except:
                    # Looks like the update-success-stamp is not available
                    # Fallback: Checking the mtime of the lists
                    try:
                        mtime = os.stat(APT_LISTS_PATH).st_mtime
                    except:
                        # No mtime could be read. We update the cache to be safe
                        mtime = False

                if mtime:
                    tdelta = datetime.timedelta(seconds=p['cache_valid_time'])
                    mtimestamp = datetime.datetime.fromtimestamp(mtime)
                    if mtimestamp + tdelta >= now:
                        cache_valid = True
                        updated_cache_time = int(time.mktime(mtimestamp.timetuple()))

            if cache_valid is not True:
                cache.update()
                cache.open(progress=None)
                updated_cache = True
                updated_cache_time = int(time.mktime(now.timetuple()))
            if not p['package'] and not p['upgrade'] and not p['deb']:
                module.exit_json(changed=False, cache_updated=updated_cache, cache_update_time=updated_cache_time)
        else:
            updated_cache = False
            updated_cache_time = 0

        force_yes = p['force']

        if p['upgrade']:
            upgrade(module, p['upgrade'], force_yes, p['default_release'], dpkg_options)

        if p['deb']:
            if p['state'] != 'present':
                module.fail_json(msg="deb only supports state=present")
            install_deb(module, p['deb'], cache,
                        install_recommends=install_recommends,
                        force=force_yes, dpkg_options=p['dpkg_options'])

        packages = p['package']
        latest = p['state'] == 'latest'
        for package in packages:
            if package.count('=') > 1:
                module.fail_json(msg="invalid package spec: %s" % package)
            if latest and '=' in package:
                module.fail_json(msg='version number inconsistent with state=latest: %s' % package)

        if p['state'] in ('latest', 'present', 'build-dep'):
            state_upgrade = False
            state_builddep = False
            if p['state'] == 'latest':
                state_upgrade = True
            if p['state'] == 'build-dep':
                state_builddep = True
            result = install(module, packages, cache, upgrade=state_upgrade,
                    default_release=p['default_release'],
                    install_recommends=install_recommends,
                    force=force_yes, dpkg_options=dpkg_options,
                    build_dep=state_builddep, autoremove=autoremove)
            (success, retvals) = result
            retvals['cache_updated']=updated_cache
            retvals['cache_update_time']=updated_cache_time
            if success:
                module.exit_json(**retvals)
            else:
                module.fail_json(**retvals)
        elif p['state'] == 'absent':
            remove(module, packages, cache, p['purge'], dpkg_options, autoremove)

    except apt.cache.LockFailedException:
        module.fail_json(msg="Failed to lock apt for exclusive operation")
    except apt.cache.FetchFailedException:
        module.fail_json(msg="Could not fetch updated apt files")
Example #2
0
    def __init__(self):

        # Determine path to system locale-config
        self.locale_path=''

        if os.path.exists('/etc/default/locale'):
            self.locale_path='/etc/default/locale'
        else:
            self.locale_path='/etc/locale.conf'

        # Prepare the APT cache
        if IS_DEBIAN:
            self.cache = apt.Cache()
        self.cache_updated = False

        # load our glade ui file in
        self.builder = Gtk.Builder()
        self.builder.set_translation_domain("mintlocale")
        self.builder.add_from_file('/usr/share/linuxmint/mintlocale/mintlocale.ui')

        self.window = self.builder.get_object("main_window")
        self.window.set_title(_("Language Settings"))
        self.window.connect("destroy", Gtk.main_quit)
        XApp.set_window_icon_name(self.window, "preferences-desktop-locale")

        self.toolbar = Gtk.Toolbar()
        self.toolbar.get_style_context().add_class("primary-toolbar")
        self.builder.get_object("box1").pack_start(self.toolbar, False, False, 0)


        size_group = Gtk.SizeGroup.new(Gtk.SizeGroupMode.HORIZONTAL)

        self.locale_button = PictureChooserButton(num_cols=2, button_picture_size=BUTTON_FLAG_SIZE, has_button_label=True)
        size_group.add_widget(self.locale_button)
        self.region_button = PictureChooserButton(num_cols=2, button_picture_size=BUTTON_FLAG_SIZE, has_button_label=True)
        size_group.add_widget(self.region_button)

        self.locale_system_wide_button = Gtk.Button()
        self.locale_system_wide_button.set_label(_("Apply System-Wide"))
        self.locale_system_wide_button.connect("clicked", self.button_system_language_clicked)
        size_group.add_widget(self.locale_system_wide_button)

        self.locale_install_button = Gtk.Button()
        self.locale_install_button.set_label(_("Install / Remove Languages..."))
        self.locale_install_button.connect("clicked", self.button_install_remove_clicked)
        size_group.add_widget(self.locale_install_button)

        self.system_label = Gtk.Label()
        self.install_label = Gtk.Label()

        page = SettingsPage()
        self.builder.get_object("box1").pack_start(page, True, True, 0)

        language_settings = page.add_section()

        label = Gtk.Label.new()
        label.set_markup("<b>%s</b>\n<small>%s</small>" % (_("Language"), _("Language, interface, date and time...")))
        row = SettingsRow(label, self.locale_button)
        language_settings.add_row(row)

        label = Gtk.Label.new()
        label.set_markup("<b>%s</b>\n<small>%s</small>" % (_("Region"), _("Numbers, currency, addresses, measurement...")))
        row = SettingsRow(label, self.region_button)
        language_settings.add_row(row)

        self.system_row = SettingsRow(self.system_label, self.locale_system_wide_button)
        self.system_row.set_no_show_all(True)
        language_settings.add_row(self.system_row)

        self.install_row = SettingsRow(self.install_label, self.locale_install_button)
        self.install_row.set_no_show_all(True)
        if IS_DEBIAN:
            language_settings.add_row(self.install_row)

        self.pam_environment_path = os.path.join(GLib.get_home_dir(), ".pam_environment")
        self.dmrc_path = os.path.join(GLib.get_home_dir(), ".dmrc")
        self.dmrc = configparser.ConfigParser()
        self.dmrc.optionxform = str  # force case sensitivity on ConfigParser
        self.dmrc.read(self.dmrc_path)
        if not self.dmrc.has_section('Desktop'):
            self.dmrc.add_section('Desktop')

        current_user = GLib.get_user_name()

        self.current_language = None
        dmrc_language = None
        env_language = os.environ['LANG']

        if self.dmrc.has_option('Desktop', 'Language'):
            dmrc_language = self.dmrc.get('Desktop', 'Language')

        if dmrc_language is not None:
            self.current_language = dmrc_language
        else:
            self.current_language = env_language

        print("User language in .dmrc: %s" % dmrc_language)
        print("User language in $LANG: %s" % env_language)
        print("Current language: %s" % self.current_language)

        if 'LC_NUMERIC' in os.environ:
            self.current_region = os.environ['LC_NUMERIC']
        else:
            self.current_region = self.current_language

        if os.path.exists(self.pam_environment_path):
            with codecs.open(self.pam_environment_path, 'r', encoding='UTF-8') as pam_file:
                for line in pam_file:
                    line = line.strip()
                    if line.startswith("LC_NUMERIC="):
                        self.current_region = line.split("=")[1].replace("\"", "").replace("'", "").strip()

        print("Current region: %s" % self.current_region)

        # Replace utf8 with UTF-8 (lightDM GTK greeter messes that up)
        self.current_language = self.current_language.replace(".utf8", ".UTF-8")
        self.current_region = self.current_region.replace(".utf8", ".UTF-8")

        self.build_lang_list()
        self.set_system_locale()
        self.set_num_installed()

        self.accountService = AccountsService.UserManager.get_default().get_user(current_user)
        self.accountService.connect('notify::is-loaded', self.accountservice_ready)
        self.accountService.connect('changed::', self.accountservice_changed)

        groups = grp.getgrall()
        for group in groups:
            (name, pw, gid, mem) = group
            if name in ("adm", "sudo", "wheel", "root"):
                for user in mem:
                    if current_user == user:
                        self.system_row.set_no_show_all(False)
                        self.install_row.set_no_show_all(False)
                        language_settings.show_all()
                        break

        self.window.show_all()
Example #3
0
def _setupVNC():
  libjpeg_ver = "2.0.3"
  virtualGL_ver = "2.6.2"
  turboVNC_ver = "2.2.3"

  libjpeg_url = "https://svwh.dl.sourceforge.net/project/libjpeg-turbo/{0}/libjpeg-turbo-official_{0}_amd64.deb".format(libjpeg_ver)
  virtualGL_url = "https://svwh.dl.sourceforge.net/project/virtualgl/{0}/virtualgl_{0}_amd64.deb".format(virtualGL_ver)
  turboVNC_url = "https://svwh.dl.sourceforge.net/project/turbovnc/{0}/turbovnc_{0}_amd64.deb".format(turboVNC_ver)

  _download(libjpeg_url, "libjpeg-turbo.deb")
  _download(virtualGL_url, "virtualgl.deb")
  _download(turboVNC_url, "turbovnc.deb")
  cache = apt.Cache()
  apt.debfile.DebPackage("libjpeg-turbo.deb", cache).install()
  apt.debfile.DebPackage("virtualgl.deb", cache).install()
  apt.debfile.DebPackage("turbovnc.deb", cache).install()

  _installPkgs(cache, "xfce4", "xfce4-terminal")
  cache.commit()

  vnc_sec_conf_p = pathlib.Path("/etc/turbovncserver-security.conf")
  vnc_sec_conf_p.write_text("""\
no-remote-connections
no-httpd
no-x11-tcp-connections
""")

  # Install TESLA DRIVER FOR LINUX X64 ver418.67.
  # Kernel module in this driver is already loaded and cannot be neither removed nor updated.
  # (nvidia, nvidia_uvm, nvidia_drm. See dmesg)
  # Existing nvidia driver for Xorg is newer than these kernel module and cannot be used with Xorg.
  # So overwrite them with the nvidia driver that is same version to loaded kernel module.
  _download("http://us.download.nvidia.com/tesla/418.67/NVIDIA-Linux-x86_64-418.67.run", "nvidia.run")
  pathlib.Path("nvidia.run").chmod(stat.S_IXUSR)
  subprocess.run(["./nvidia.run", "--no-kernel-module", "--ui=none"], input = "1\n", check = True, universal_newlines = True)

  #https://virtualgl.org/Documentation/HeadlessNV
  subprocess.run(["nvidia-xconfig",
                  "-a",
                  "--allow-empty-initial-configuration",
                  "--virtual=1920x1200",
                  "--busid", "PCI:0:4:0"],
                 check = True
                )

  with open("/etc/X11/xorg.conf", "r") as f:
    conf = f.read()
    conf = re.sub('(Section "Device".*?)(EndSection)',
                  '\\1    MatchSeat      "seat-1"\n\\2',
                  conf,
                  1,
                  re.DOTALL)
  #  conf = conf + """
  #Section "Files"
  #    ModulePath "/usr/lib/xorg/modules"
  #    ModulePath "/usr/lib/x86_64-linux-gnu/nvidia-418/xorg/"
  #EndSection
  #"""

  with open("/etc/X11/xorg.conf", "w") as f:
    f.write(conf)

  #!service lightdm stop
  subprocess.run(["/opt/VirtualGL/bin/vglserver_config", "-config", "+s", "+f"], check = True)
  #user_name = "colab"
  #!usermod -a -G vglusers $user_name
  #!service lightdm start

  # Run Xorg server
  # VirtualGL and OpenGL application require Xorg running with nvidia driver to get Hardware 3D Acceleration.
  #
  # Without "-seat seat-1" option, Xorg try to open /dev/tty0 but it doesn't exists.
  # You can create /dev/tty0 with "mknod /dev/tty0 c 4 0" but you will get permision denied error.
  subprocess.Popen(["Xorg", "-seat", "seat-1", "-allowMouseOpenFail", "-novtswitch", "-nolisten", "tcp"])

  vncrun_py = pathlib.Path("vncrun.py")
  vncrun_py.write_text("""\
import subprocess, secrets, pathlib

vnc_passwd = secrets.token_urlsafe()[:8]
vnc_viewonly_passwd = secrets.token_urlsafe()[:8]
print("✂️"*24)
print("VNC password: {}".format(vnc_passwd))
print("VNC view only password: {}".format(vnc_viewonly_passwd))
print("✂️"*24)
vncpasswd_input = "{0}\\n{1}".format(vnc_passwd, vnc_viewonly_passwd)
vnc_user_dir = pathlib.Path.home().joinpath(".vnc")
vnc_user_dir.mkdir(exist_ok=True)
vnc_user_passwd = vnc_user_dir.joinpath("passwd")
with vnc_user_passwd.open('wb') as f:
  subprocess.run(
    ["/opt/TurboVNC/bin/vncpasswd", "-f"],
    stdout=f,
    input=vncpasswd_input,
    universal_newlines=True)
vnc_user_passwd.chmod(0o600)
subprocess.run(
  ["/opt/TurboVNC/bin/vncserver"]
)

#Disable screensaver because no one would want it.
(pathlib.Path.home() / ".xscreensaver").write_text("mode: off\\n")
""")
  r = subprocess.run(
                    ["su", "-c", "python3 vncrun.py", "colab"],
                    check = True,
                    stdout = subprocess.PIPE,
                    universal_newlines = True)
  print(r.stdout)
    def __init__(self):
        builder = Gtk.Builder()
        builder.set_translation_domain("mintwelcome")
        builder.add_from_file(
            '/usr/share/linuxmint/mintwelcome/mintwelcome.ui')

        window = builder.get_object("main_window")
        window.set_icon_name("mintwelcome")
        window.set_position(Gtk.WindowPosition.CENTER)
        window.connect("destroy", Gtk.main_quit)

        with open("/etc/hamonikr/info") as f:
            config = dict([line.strip().split("=") for line in f])
        codename = config['CODENAME'].capitalize()
        edition = config['EDITION'].replace('"', '')
        release = config['RELEASE']
        desktop = config['DESKTOP']
        release_notes = config['RELEASE_NOTES_URL']
        new_features = config['NEW_FEATURES_URL']
        architecture = "64-bit"
        if platform.machine() != "x86_64":
            architecture = "32-bit"

        # distro-specific
        with open("/etc/lsb-release") as f:
            config = dict([line.strip().split("=") for line in f])
        dist_name = config['DISTRIB_ID']

        if os.path.exists(
                "/usr/share/doc/debian-system-adjustments/copyright"):
            dist_name = "LMDE"

        # Setup the labels in the Mint badge
        builder.get_object("label_version").set_text("%s %s" %
                                                     (dist_name, release))
        builder.get_object("label_edition").set_text("%s %s" %
                                                     (edition, architecture))

        # Setup the main stack
        self.stack = Gtk.Stack()
        builder.get_object("center_box").pack_start(self.stack, True, True, 0)
        self.stack.set_transition_type(Gtk.StackTransitionType.CROSSFADE)
        self.stack.set_transition_duration(150)

        # Action buttons
        builder.get_object("button_forums").connect("clicked", self.visit,
                                                    "https://hamonikr.org")
        # builder.get_object("button_documentation").connect("clicked", self.visit, "https://hamonikr.org/board_manual")
        builder.get_object("button_contribute").connect(
            "clicked", self.visit, "https://github.com/hamonikr")
        builder.get_object("button_irc").connect(
            "clicked", self.visit, "https://hamonikr.org/how_join")
        builder.get_object("button_codecs").connect(
            "clicked", self.visit, "apt://mint-meta-codecs?refresh=yes")
        builder.get_object("button_new_features").connect(
            "clicked", self.visit, "https://docs.hamonikr.org/new-features/")
        builder.get_object("button_release_notes").connect(
            "clicked", self.visit, "https://docs.hamonikr.org/release-note/")
        builder.get_object("button_mintupdate").connect(
            "clicked", self.launch, "mintupdate")
        builder.get_object("button_mintinstall").connect(
            "clicked", self.launch, "mintinstall")
        builder.get_object("button_timeshift").connect("clicked", self.pkexec,
                                                       "timeshift-gtk")
        builder.get_object("button_mintdrivers").connect(
            "clicked", self.pkexec, "driver-manager")
        builder.get_object("button_gufw").connect("clicked", self.launch,
                                                  "gufw")
        builder.get_object("button_layout_legacy").connect(
            "clicked", self.on_button_layout_clicked, LAYOUT_STYLE_LEGACY)
        builder.get_object("button_layout_new").connect(
            "clicked", self.on_button_layout_clicked, LAYOUT_STYLE_NEW)

        # custom new features
        builder.get_object("button_license").connect(
            "clicked", self.visit, "http://pms.invesume.com:8090/hl/os/5-0")

        # custom recommended software
        builder.get_object("button_hancom").connect("clicked", self.launch,
                                                    "hoffice-support")
        builder.get_object("button_site_compatibility_support").connect(
            "clicked", self.launch, "site-compatibility-support")
        builder.get_object("button_kakaotalk").connect("clicked", self.launch,
                                                       "kakaotalk-install")
        builder.get_object("button_hamonikr_drive").connect(
            "clicked", self.visit, "https://drive.hamonikr.org/")
        builder.get_object("button_lutris").connect(
            "clicked", self.on_button_lutris_clicked)
        builder.get_object("button_kodi").connect("clicked",
                                                  self.on_button_kodi_clicked)
        builder.get_object("button_korean_language").connect(
            "clicked", self.on_button_korean_language)

        ### ---------- development software start ---------- ###

        # Editor
        # builder.get_object("button_vscode").connect("clicked", self.visit, "apt://code?refresh=yes")
        builder.get_object("button_vscode").connect(
            "clicked", self.on_button_vscode_clicked)

        # DBMS
        builder.get_object("button_mysql_server").connect(
            "clicked", self.visit, "apt://mysql-server?refresh=yes")
        builder.get_object("button_postgresql").connect(
            "clicked", self.visit, "apt://postgresql?refresh=yes")

        # WEB/WAS
        builder.get_object("button_apache").connect(
            "clicked", self.visit, "apt://apache2?refresh=yes")
        builder.get_object("button_tomcat").connect(
            "clicked", self.visit, "apt://tomcat9?refresh=yes")

        # Development Language
        builder.get_object("button_default_jdk").connect(
            "clicked", self.visit, "apt://default-jdk?refresh=yes")
        builder.get_object("button_python_pip").connect(
            "clicked", self.visit, "apt://python3-pip?refresh=yes")

        # Etc...
        builder.get_object("button_asbru").connect(
            "clicked", self.visit, "apt://asbru-cm?refresh=yes")
        builder.get_object("button_git").connect("clicked", self.visit,
                                                 "apt://git?refresh=yes")
        builder.get_object("button_rabbitvcs").connect(
            "clicked", self.visit, "apt://hamonikr-nemo-rabbitvcs?refresh=yes")
        builder.get_object("button_avahi").connect(
            "clicked", self.visit, "apt://hamonikr-avahi-service?refresh=yes")

        ### ---------- development software end ---------- ###

        # custom help
        builder.get_object("button_help").connect(
            "clicked", self.visit, "https://docs.hamonikr.org/hamonikr-5.0")
        builder.get_object("button_shortcut").connect("clicked", self.launch,
                                                      "conky-shortcut-on-off")

        # builder.get_object("button_ventoy").connect("clicked", self.visit, "apt://ventoy?refresh=yes")
        # builder.get_object("button_systemback").connect("clicked", self.visit, "apt://systemback?refresh=yes")
        # builder.get_object("button_live_usb_creator").connect("clicked", self.visit, "apt://live-usb-creator?refresh=yes")
        # builder.get_object("button_hamonikr_cli_tools").connect("clicked", self.visit, "apt://hamonikr-cli-tools?refresh=yes")

        # Settings button depends on DE
        de_is_cinnamon = False
        self.theme = None
        if os.getenv("XDG_CURRENT_DESKTOP") in ["Cinnamon", "X-Cinnamon"]:
            builder.get_object("button_settings").connect(
                "clicked", self.launch, "cinnamon-settings")
            de_is_cinnamon = True
            self.theme = Gio.Settings(schema="org.cinnamon.desktop.interface"
                                      ).get_string("gtk-theme")
        elif os.getenv("XDG_CURRENT_DESKTOP") == "MATE":
            builder.get_object("button_settings").connect(
                "clicked", self.launch, "mate-control-center")
        elif os.getenv("XDG_CURRENT_DESKTOP") == "XFCE":
            builder.get_object("button_settings").connect(
                "clicked", self.launch, "xfce4-settings-manager")
        else:
            # Hide settings
            builder.get_object("box_first_steps").remove(
                builder.get_object("box_settings"))

        # Hide Desktop colors
        builder.get_object("box_first_steps").remove(
            builder.get_object("box_colors"))

        # Hide Cinnamon layout settings in other DEs
        if not de_is_cinnamon:
            builder.get_object("box_first_steps").remove(
                builder.get_object("box_cinnamon"))

        # Hide codecs box if they're already installed
        add_codecs = False
        cache = apt.Cache()
        if "mint-meta-codecs" in cache:
            pkg = cache["mint-meta-codecs"]
            if not pkg.is_installed:
                add_codecs = True
        if not add_codecs:
            builder.get_object("box_first_steps").remove(
                builder.get_object("box_codecs"))

        # Hide drivers if mintdrivers is absent (LMDE)
        if not os.path.exists("/usr/bin/mintdrivers"):
            builder.get_object("box_first_steps").remove(
                builder.get_object("box_drivers"))

        # Hide new features page for LMDE
        if dist_name == "LMDE":
            builder.get_object("box_documentation").remove(
                builder.get_object("box_new_features"))

        # Construct the stack switcher
        list_box = builder.get_object("list_navigation")

        page = builder.get_object("page_home")
        self.stack.add_named(page, "page_home")
        list_box.add(SidebarRow(page, _("Welcome"), "go-home-symbolic"))
        self.stack.set_visible_child(page)

        page = builder.get_object("page_first_steps")
        self.stack.add_named(page, "page_first_steps")
        list_box.add(
            SidebarRow(page, _("HamoniKR Settings"),
                       "dialog-information-symbolic"))

        page = builder.get_object("page_second_steps")
        self.stack.add_named(page, "page_second_steps")
        list_box.add(
            SidebarRow(page, _("Recommended Program"),
                       "dialog-information-symbolic"))

        page = builder.get_object("page_third_steps")
        self.stack.add_named(page, "page_third_steps")
        list_box.add(
            SidebarRow(page, _("Development Program"),
                       "dialog-information-symbolic"))

        page = builder.get_object("page_help")
        self.stack.add_named(page, "page_help")
        list_box.add(SidebarRow(page, _("Help"), "help-browser-symbolic"))

        page = builder.get_object("page_new_feature")
        self.stack.add_named(page, "page_new_feature")
        list_box.add(
            SidebarRow(page, _("HamoniKR Information"),
                       "accessories-dictionary-symbolic"))

        list_box.connect("row-activated", self.sidebar_row_selected_cb)

        # Construct the bottom toolbar
        box = builder.get_object("toolbar_bottom")
        checkbox = Gtk.CheckButton()
        checkbox.set_label(_("Show this dialog at startup"))
        if not os.path.exists(NORUN_FLAG):
            checkbox.set_active(True)
        checkbox.connect("toggled", self.on_button_toggled)
        box.pack_end(checkbox)

        scale = window.get_scale_factor()

        self.color = "green"
        self.dark_mode = False

        # Use HIDPI pictures if appropriate
        if scale == 1:
            surface = self.surface_for_path(
                "/usr/share/linuxmint/mintwelcome/hamonikr_legacy.png", scale)
            builder.get_object("img_legacy").set_from_surface(surface)
            surface = self.surface_for_path(
                "/usr/share/linuxmint/mintwelcome/hamonikr_modern.png", scale)
            builder.get_object("img_modern").set_from_surface(surface)
        else:
            surface = self.surface_for_path(
                "/usr/share/linuxmint/mintwelcome/hamonikr_legacy.png", scale)
            builder.get_object("img_legacy").set_from_surface(surface)
            surface = self.surface_for_path(
                "/usr/share/linuxmint/mintwelcome/hamonikr_modern.png", scale)
            builder.get_object("img_modern").set_from_surface(surface)

        path = "/usr/share/linuxmint/mintwelcome/colors/"
        if scale == 2:
            path = "/usr/share/linuxmint/mintwelcome/colors/hidpi/"
        for color in [
                "green", "aqua", "blue", "brown", "grey", "orange", "pink",
                "purple", "red", "sand", "teal"
        ]:
            builder.get_object("img_" + color).set_from_surface(
                self.surface_for_path("%s/%s.png" % (path, color), scale))
            builder.get_object("button_" + color).connect(
                "clicked", self.on_color_button_clicked, color)

        builder.get_object("switch_dark").connect("state-set",
                                                  self.on_dark_mode_changed)

        window.set_default_size(800, 500)
        window.show_all()
Example #5
0
import gi
import subprocess
import sys
import threading
import getpass
import time

if len(sys.argv) == 1 or len(sys.argv) > 4:
    print("Invalid number of arguments")
    exit()

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Pango, Gdk, GdkPixbuf

import apt
cache = apt.Cache()


class init():
    stepsdone = ""

    def __init__(self):
        self.builder = Gtk.Builder()
        self.builder.add_from_file('/usr/lib/feren-majorupdate/gui.glade')
        self.win = self.builder.get_object('mainwind')
        self.win.connect('delete-event', Gtk.main_quit)

        self.pagestack = self.builder.get_object('stack1')

        #PangoFont = Pango.FontDescription("Tahoma 12")
        #self.win.modify_font(PangoFont)
Example #6
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            repo=dict(required=True),
            state=dict(choices=['present', 'absent'], default='present'),
            mode=dict(required=False, type='raw'),
            update_cache = dict(aliases=['update-cache'], type='bool', default='yes'),
            filename=dict(required=False, default=None),
            # this should not be needed, but exists as a failsafe
            install_python_apt=dict(required=False, default="yes", type='bool'),
            validate_certs = dict(default='yes', type='bool'),
            codename = dict(required=False),
        ),
        supports_check_mode=True,
    )

    params = module.params
    repo = module.params['repo']
    state = module.params['state']
    update_cache = module.params['update_cache']
    # Note: mode is referenced in SourcesList class via the passed in module (self here)

    sourceslist = None

    if not HAVE_PYTHON_APT:
        if params['install_python_apt']:
            install_python_apt(module)
        else:
            module.fail_json(msg='%s is not installed, and install_python_apt is False' % PYTHON_APT)

    if isinstance(distro, aptsources_distro.Distribution):
        sourceslist = UbuntuSourcesList(module,
            add_ppa_signing_keys_callback=get_add_ppa_signing_key_callback(module))
    else:
        module.fail_json(msg='Module apt_repository is not supported on target.')

    sources_before = sourceslist.dump()

    try:
        if state == 'present':
            sourceslist.add_source(repo)
        elif state == 'absent':
            sourceslist.remove_source(repo)
    except InvalidSource:
        err = get_exception()
        module.fail_json(msg='Invalid repository string: %s' % unicode(err))

    sources_after = sourceslist.dump()
    changed = sources_before != sources_after

    if changed and module._diff:
        diff = []
        for filename in set(sources_before.keys()).union(sources_after.keys()):
            diff.append({'before': sources_before.get(filename, ''),
                         'after': sources_after.get(filename, ''),
                         'before_header': (filename, '/dev/null')[filename not in sources_before],
                         'after_header': (filename, '/dev/null')[filename not in sources_after]})
    else:
        diff = {}

    if changed and not module.check_mode:
        try:
            sourceslist.save()
            if update_cache:
                cache = apt.Cache()
                cache.update()
        except OSError:
            err = get_exception()
            module.fail_json(msg=unicode(err))

    module.exit_json(changed=changed, repo=repo, state=state, diff=diff)
Example #7
0
import apt
import apt_pkg
import os.path

if __name__ == "__main__":
    apt_pkg.Config.Set("APT::Update::Pre-Invoke::",
                       "touch /tmp/update-about-to-run")
    apt_pkg.Config.Set("APT::Update::Post-Invoke::",
                       "touch /tmp/update-was-run")
    c = apt.Cache()
    res = c.update(apt.progress.TextFetchProgress())
    print "res: ", res
    assert (os.path.exists("/tmp/update-about-to-run"))
Example #8
0
 def __init__(self, dbus_service):
     self.dbus_service = dbus_service
     locale.setlocale(locale.LC_ALL, "zh_CN.UTF-8")
     self.cache = apt.Cache()
Example #9
0
def package_versions():
    def kernelDict():
        ret = os.uname()
        try:
            ver, rel = ret[2].split('-', 1)
        except ValueError:
            logging.error('kernel release not found', exc_info=True)
            ver, rel = '0', '0'
        try:
            t = ret[3].split()[2:]
            del t[4]  # Delete timezone
            t = time.mktime(time.strptime(' '.join(t)))
        except ValueError:
            logging.error('kernel build time not found', exc_info=True)
            t = '0'
        return dict(version=ver, release=rel, buildtime=t)

    pkgs = {'kernel': kernelDict()}

    if _release_name() in (OSName.RHEVH, OSName.OVIRT, OSName.FEDORA,
                           OSName.RHEL, OSName.POWERKVM):
        KEY_PACKAGES = {
            'glusterfs-cli': ('glusterfs-cli', ),
            'librbd1': ('librbd1', ),
            'libvirt': ('libvirt', 'libvirt-daemon-kvm'),
            'mom': ('mom', ),
            'qemu-img': ('qemu-img', 'qemu-img-rhev', 'qemu-img-ev'),
            'qemu-kvm': ('qemu-kvm', 'qemu-kvm-rhev', 'qemu-kvm-ev'),
            'spice-server': ('spice-server', ),
            'vdsm': ('vdsm', ),
        }

        if glusterEnabled:
            KEY_PACKAGES.update(GLUSTER_RPM_PACKAGES)

        try:
            ts = rpm.TransactionSet()

            for pkg, names in KEY_PACKAGES.iteritems():
                try:
                    mi = itertools.chain(
                        *[ts.dbMatch('name', name) for name in names]).next()
                except StopIteration:
                    logging.debug("rpm package %s not found",
                                  KEY_PACKAGES[pkg])
                else:
                    pkgs[pkg] = {
                        'version': mi['version'],
                        'release': mi['release'],
                        'buildtime': mi['buildtime'],
                    }
        except Exception:
            logging.error('', exc_info=True)

    elif _release_name() == OSName.DEBIAN and python_apt:
        KEY_PACKAGES = {
            'glusterfs-cli': 'glusterfs-cli',
            'librbd1': 'librbd1',
            'libvirt': 'libvirt0',
            'mom': 'mom',
            'qemu-img': 'qemu-utils',
            'qemu-kvm': 'qemu-kvm',
            'spice-server': 'libspice-server1',
            'vdsm': 'vdsmd',
        }

        if glusterEnabled:
            KEY_PACKAGES.update(GLUSTER_DEB_PACKAGES)

        cache = apt.Cache()

        for pkg in KEY_PACKAGES:
            try:
                deb_pkg = KEY_PACKAGES[pkg]
                ver = cache[deb_pkg].installed.version
                # Debian just offers a version
                pkgs[pkg] = dict(version=ver, release="", buildtime="")
            except Exception:
                logging.error('', exc_info=True)

    return pkgs
Example #10
0
#!/usr/bin/env python3

import apt
import re

best_golang = None
for p in apt.Cache():
    if re.match(r"golang-([0-9.]+)$", p.name):
        if (
            best_golang is None
            or apt.apt_pkg.version_compare(
                best_golang.candidate.version, p.candidate.version
            )
            < 0
        ):
            best_golang = p

print(best_golang.name)
Example #11
0
    def install(self, name):
        session = Prompt(
            placeholder=Text("<grey>(please type something</grey>"))
        package_name = self.data[name]["package_name"]
        package_manager = self.data[name]["package_manager"]
        url = self.data[name]["url"]
        req = list(self.data[name]["dependency"])
        system = sys()

        if system.connection():
            if len(req) != 0 and req[0] != None:
                for dep in req:
                    if os.path.exists(system.bin + "/" + dep):
                        pass
                    else:
                        if system.sudo != None:
                            os.system(system.sudo + " " + system.pac +
                                      " install " + dep + " -y")
                        else:
                            os.system(system.pac + " install " + dep + " -y")

            if package_manager == "package_manager":
                if os.path.exists(system.bin + "/" + package_name):
                    clear()
                    logo.already_installed(name)
                    tmp = session.prompt("$» ")
                else:
                    if system.sudo != None:
                        os.system(system.sudo + " " + system.pac +
                                  " install " + package_name + " -y")
                    else:
                        os.system(system.pac + " install " + package_name +
                                  " -y")
                    # check tool is installed or not
                    if os.path.exists(system.bin + "/" + package_name):
                        clear()
                        logo.installed(name)
                        tmp = session.prompt("$» ")
                    else:
                        clear()
                        logo.not_installed(name)
                        tmp = session.prompt("$» ")

            elif package_manager == "git":
                if os.path.exists(system.home + "/" + package_name):
                    clear()
                    logo.already_installed(name)
                    tmp = session.prompt("$» ")
                else:
                    if system.sudo != None:
                        os.system(system.sudo + " git clone " + url + " " +
                                  system.home + "/" + package_name)
                    else:
                        os.system("git clone " + url + " " + system.home +
                                  "/" + package_name)
                    # check tool is installed or not
                    if os.path.exists(system.home + "/" + package_name):
                        clear()
                        logo.installed(name)
                        tmp = session.prompt("$» ")
                    else:
                        clear()
                        logo.not_installed(name)
                        tmp = session.prompt("$» ")

            elif package_manager == "wget":
                if os.path.exists(system.home + "/" + package_name):
                    clear()
                    logo.already_installed(name)
                    tmp = session.prompt("$» ")
                else:
                    if system.sudo != None:
                        os.system(system.sudo + " wget " + url + " -o " +
                                  system.home + "/" + package_name)
                    else:
                        os.system("wget " + url + " -o " + system.home + "/" +
                                  package_name)
                    # check tool is installed or not
                    if os.path.exists(system.home + "/" + package_name):
                        clear()
                        logo.installed(name)
                        tmp = session.prompt("$» ")
                    else:
                        clear()
                        logo.not_installed(name)
                        tmp = session.prompt("$» ")

            elif package_manager == "curl":
                if os.path.exists(system.home + "/" + package_name):
                    clear()
                    logo.already_installed(name)
                    tmp = session.prompt("$» ")
                else:
                    if system.sudo != None:
                        os.system(system.sudo + " curl " + url + " -o " +
                                  system.home + "/" + package_name)
                    else:
                        os.system("curl " + url + " -o " + system.home + "/" +
                                  package_name)
                    # check tool is installed or not
                    if os.path.exists(system.home + "/" + package_name):
                        clear()
                        logo.installed(name)
                        tmp = session.prompt("$» ")
                    else:
                        clear()
                        logo.not_installed(name)
                        tmp = session.prompt("$» ")
        if package_manager == "apt":
            import apt
            cache = apt.Cache()
            if cache[package_name].is_installed:
                clear()
                logo.already_installed(name)
                tmp = session.prompt("$» ")
            else:
                os.system("sudo apt install " + package_name)

        # if os.path.exists(system.home+"/"+package_name):
        # clear()
        #   logo.already_installed(name)
        #      tmp=session.prompt("$» ")
        #   else:
        #     if system.sudo != None:
        #       print("dddd")
        #    os.system(system.sudo+" apt " + package_name)
        else:
            clear()
            logo.nonet()
            tmp = session.prompt("$» ")
Example #12
0
    def run(self):
        global steps
        global progressbar
        global wTree
        global packages
        global user
        global home

        wTree.get_widget("main_button").hide()
        wTree.get_widget("cancel_button").set_label("gtk-cancel")
        wTree.get_widget("cancel_button").set_use_stock(True)

        totalSteps = steps
        if (self.rightRepositories != "local"):
            progressbar.set_text(_("Backing up your APT sources"))
            self.execute(
                "mv /etc/apt/sources.list /etc/apt/sources.list.swmbackup")
            self.execute(
                "cp /usr/share/solydxk/softwaremanager/sources.list /etc/apt/sources.list"
            )
            cache = apt.Cache()
            os.system("apt-get update")
            totalSteps = steps + 2

        fraction = 0
        progressbar.set_fraction(fraction)

        for i in range(steps + 1):
            if (i > 0):
                openfile = open(
                    "/usr/lib/solydxk/softwaremanager/tmp/steps/" + str(i),
                    'r')
                datalist = openfile.readlines()
                for j in range(len(datalist)):
                    if (str.find(datalist[j], "TITLE") > -1):
                        title = datalist[j][6:]
                        progressbar.set_text(str.strip(title))
                    if (str.find(datalist[j], "INSTALL") > -1):
                        install = datalist[j][8:]
                        install = str.strip(install)
                        installPackages = string.split(install)
                        cmd = [
                            "sudo", "/usr/sbin/synaptic", "--hide-main-window",
                            "--non-interactive", "--parent-window-id",
                            self.window_id
                        ]
                        cmd.append("--progress-str")
                        cmd.append("\"" +
                                   _("Please wait, this can take some time") +
                                   "\"")
                        cmd.append("--finish-str")
                        cmd.append("\"" + _("Installation is complete") + "\"")
                        f = tempfile.NamedTemporaryFile()
                        for pkg in installPackages:
                            f.write("%s\tinstall\n" % pkg)
                            cmd.append("--set-selections-file")
                            cmd.append("%s" % f.name)
                            f.flush()
                            comnd = Popen(' '.join(cmd), shell=True)
                        returnCode = comnd.wait()
                        f.close()

                    if (str.find(datalist[j], "SOURCE") > -1):
                        source = datalist[j][7:]
                        source = source.rstrip()
                        self.execute("echo \"" + source +
                                     "\" >> /etc/apt/sources.list")
                        os.system("apt-get update")
                    if (str.find(datalist[j], "EXECUTE") > -1):
                        execution = datalist[j][8:]
                        execution = execution.rstrip()
                        execution = execution.replace("<<USER>>", user)
                        execution = execution.replace("<<HOME>>", home)
                        self.execute(execution)

                fraction = float(i) / float(totalSteps)
                progressbar.set_fraction(fraction)

        if (self.rightRepositories != "local"):
            progressbar.set_text(_("Restoring your APT sources"))
            self.execute(
                "mv /etc/apt/sources.list.swmbackup /etc/apt/sources.list")
            os.system("apt-get update")
        progressbar.set_fraction(1)
        progressbar.set_text(_("Finished"))
        wTree.get_widget("main_button").hide()
        wTree.get_widget("cancel_button").set_label(_("Close"))
        #Everything is done, exit quietly
        gtk.main_quit()
        sys.exit(0)
Example #13
0
    def __init__(self, solydxkFile, user, home):
        global steps
        global progressbar
        global wTree
        global installation_terminal
        global installation_progressbar
        global download_progressbar
        global packages

        self.swmFile = solydxkFile
        self.user = user
        self.home = home

        #Make tmp folder
        os.system("mkdir -p /usr/lib/solydxk/softwaremanager/tmp")

        #Clean tmp files
        os.system("rm -rf /usr/lib/solydxk/softwaremanager/tmp/*")

        #Decompress file
        os.system("cp " + solydxkFile +
                  " /usr/lib/solydxk/softwaremanager/tmp/file.swm")
        os.system(
            "tar xf /usr/lib/solydxk/softwaremanager/tmp/file.swm -C /usr/lib/solydxk/softwaremanager/tmp/"
        )  #Try without gzip
        os.system(
            "tar zxf /usr/lib/solydxk/softwaremanager/tmp/file.swm -C /usr/lib/solydxk/softwaremanager/tmp/"
        )  #Try with gzip

        #Extract the name
        self.name = commands.getoutput(
            "cat /usr/lib/solydxk/softwaremanager/tmp/name")
        self.name = str.strip(self.name)

        #Extract the number of steps
        steps = int(
            commands.getoutput(
                "ls -l /usr/lib/solydxk/softwaremanager/tmp/steps/ | wc -l"))
        steps = steps - 1
        self.pulse = 1 / steps

        #Initialize APT
        cache = apt.Cache()

        #Extract repositories and packages
        self.repositories = []
        packages = []
        for i in range(steps + 1):
            if (i > 0):
                openfile = open(
                    "/usr/lib/solydxk/softwaremanager/tmp/steps/" + str(i),
                    'r')
                datalist = openfile.readlines()
                for j in range(len(datalist)):
                    if (str.find(datalist[j], "INSTALL") > -1):
                        install = datalist[j][8:]
                        install = str.strip(install)
                        packages.append(install)
                    if (str.find(datalist[j], "SOURCE") > -1):
                        source = datalist[j][7:]
                        source = source.rstrip()
                        self.repositories.append(source)
                #openfile.close()

        #Set the Glade file
        self.gladefile = "/usr/share/solydxk/softwaremanager/softwaremanager-args.glade"
        wTree = gtk.glade.XML(self.gladefile, "main_window")
        wTree.get_widget("main_window").set_icon_from_file(
            "/usr/share/solydxk/softwaremanager/icon.svg")
        wTree.get_widget("main_window").set_title("")

        wTree.get_widget("main_window").connect("destroy", self.giveUp)

        # Get the window socket (needed for synaptic later on)
        vbox = wTree.get_widget("vbox1")
        socket = gtk.Socket()
        vbox.pack_start(socket)
        socket.show()
        window_id = repr(socket.get_id())

        wTree.get_widget("label_repositories").set_text(
            _("Using the following repositories:"))

        #Fill in the GUI with information from the solydxkFile
        wTree.get_widget("main_button_label").set_text(_("Install"))

        wTree.get_widget("txt_name").set_text("<big><b>" + _("Install %s?") %
                                              (self.name) + "</b></big>")
        wTree.get_widget("txt_name").set_use_markup(True)

        wTree.get_widget("txt_guidance").set_text(
            _("The following packages will be installed:"))

        if (len(self.repositories) == 0):
            treeview = wTree.get_widget("tree_repositories")
            column1 = gtk.TreeViewColumn()
            renderer = gtk.CellRendererText()
            column1.pack_start(renderer, False)
            column1.set_attributes(renderer, text=0)
            treeview.append_column(column1)
            treeview.set_headers_visible(False)
            model = gtk.ListStore(str)
            model.append([_("Default repositories")])
            treeview.set_model(model)
            wTree.get_widget("label_repositories").hide()
            wTree.get_widget("scrolledwindow_repositories").hide()

            treeview = wTree.get_widget("tree_packages")
            column1 = gtk.TreeViewColumn()
            renderer = gtk.CellRendererText()
            column1.pack_start(renderer, False)
            column1.set_attributes(renderer, text=0)
            treeview.append_column(column1)
            treeview.set_headers_visible(False)
            model = gtk.ListStore(str)

            for package in packages:
                strPackage = package
                try:
                    pkg = cache[package]
                    strPackage = str(
                        package) + " [" + pkg.candidateVersion + "]"
                    for dep in pkg.candidateDependencies:
                        for o in dep.or_dependencies:
                            dependency = cache[o.name]
                            if not dependency.is_installed:
                                strDependency = dependency.name + " [" + dependency.candidateVersion + "]"
                                model.append([strDependency])
                except Exception, detail:
                    print detail
                    pass
                model.append([strPackage])
            treeview.set_model(model)
            treeview.show()
Example #14
0
def main():
    """
    Run the BYOB setup script

    """
    import os
    import sys
    import logging
    import subprocess

    # debugging
    logging.basicConfig(level=logging.DEBUG, handlers=[logging.StreamHandler()])
    logger = logging.getLogger(__name__)

    #urllib vomit
    if sys.version_info[0] > 2:
        from urllib.request import urlopen
        # for mainstream linux kernel we need to get opencv from the repo, else it must be compiled from source;
        # this, to prevent a segfault at runtime for resources loading cv2 package in python3
        if os.name != "nt":
            try:
                import apt
                aptcache = apt.Cache()
                if not aptcache['python3-opencv'].is_installed:
                    logger.error('Install python3-opencv before continuing:\n\n        sudo apt install python3-opencv\n')
                    sys.exit()
            except:
                #assuming then we're rhel based
                try:
                    import yum
                    yumapp = yum.YumBase()
                    rpmdb = yumapp.doPackageLists(patterns="python3-opencv")
                    if not rpmdb.installed:
                        logger.error('Install python3-opencv before continuing:\n\n        sudo yum install python3-opencv\n')
                        sys.exit()
                except:
                    logger.error('Unable to determine if python3-opencv is installed; continuing anyway.\n        If you get a cv2 import error, install python3-opencv')
    else:
        from urllib import urlopen

    # find pip
    try:
        pip_path = subprocess.check_output('where pip' if os.name == 'nt' else 'which pip', shell=True).strip().rstrip()
    except Exception as e:
        logger.debug("Error in pip package installer: {}".format(str(e)))

    # install pip if missing
    try:
        import pip
    except:
        if not bool('pip_path' in locals() and os.path.exists(pip_path)) and os.name != "nt":
            try:
                # NOTE: intrct -- I think this is a bad practice (instituting execution of arbitrary remote code we don't control).
                if os.getuid() != 0:
                    # intrct: added this exit because otherwise this just runs in an infinite loop; I still think it's a bad idea.
                    logger.error("pip is not installed or a module, so setup must run elevated (sudo)")
                    sys.exit()
                # intrct: added check for version for proper callout materials, and 
                # running as subprocess rather than internal due to potential early exits in remote code.
                if sys.version_info[0] > 2:
                    subprocess.check_call("""{} -c 'from urllib.request import urlopen; exec(urlopen("https://bootstrap.pypa.io/get-pip.py").read())'""".format(sys.executable), shell=True)
                else:
                    subprocess.check_call("""{} -c 'from urllib import urlopen; exec(urlopen("https://bootstrap.pypa.io/get-pip.py").read())'""".format(sys.executable), shell=True)
            except Exception as e:
                logger.debug("Error installing pip: {}".format(str(e)))

            # restart
            # intrct: I would like to point out a limitation that this only installs packages for the linked "python"
            #           and not the called version of python in the original runtime.
            os.execv(sys.executable, ['python'] + [os.path.abspath(sys.argv[0])] + sys.argv[1:])

    # find requirements
    for tree in os.walk('..'):
        if 'byob' not in tree[0]:
            continue
        elif 'requirements.txt' in tree[2]:
            requirements = os.path.join(tree[0], 'requirements.txt')
            break

    # install requirements
    try:
        print("Installing requirements.txt")
        if os.name != "nt":
            locals()['pip_install_1'] = subprocess.Popen('sudo --prompt=" Please enter sudo password (to install python dependencies): " {} -m pip install -r {}'.format(sys.executable, requirements), 0, None, subprocess.PIPE, subprocess.PIPE, subprocess.PIPE, shell=True)
        else:
            locals()['pip_install_1'] = subprocess.Popen('{} -m pip install -r {}'.format(sys.executable, requirements), 0, None, subprocess.PIPE, subprocess.PIPE, subprocess.PIPE, shell=True)           
        for line in locals()['pip_install_1'].stdout:
            print(line.decode())
            sys.stdout.flush()
    except Exception as e:
        logger.error("Error installing requirements: {}".format(e))
Example #15
0
 def setUp(self):
     self.ml_data = MachineLearningData()
     self.cache = apt.Cache()
Example #16
0
 def updateSources(self):
     self.buttonRefresh.setEnabled(False)
     cache = apt.Cache()
     cache.update(self.aprogress)
     self.buttonRefresh.setEnabled(True)
Example #17
0
    def apt_update_complete(self):

        self.cache = apt.Cache()

        self.REBOOT_REQUIRED = 0

        log('apt_update_complete called')

        self.cache.open(None)
        self.cache.upgrade()

        available_updates = self.cache.get_changes()

        del self.cache

        # if 'osmc' isnt in the name of any available updates, then return without doing anything
        # SUPPRESSED FOR TESTING
        # if not any(['osmc' in x.shortname.lower() for x in available_updates]):
        # 	log('There are no osmc packages')
        # 	return
        if not available_updates:
            return  # dont bother doing anything else if there are no updates FOR TESTING ONLY

        log('The following packages have newer versions and are upgradable: ')

        for pkg in available_updates:
            if pkg.is_upgradable:

                log('is upgradeable', pkg.shortname)

                if "mediacenter" in pkg.shortname:
                    self.REBOOT_REQUIRED = 1

        # display update available notification
        if not self.s['suppress_icon']:
            self.window.setProperty('OSMC_notification', 'true')

        # The following section implements the procedure that the user has chosen to take place when updates are detected

        if self.s['on_upd_detected'] == 1:
            # Display icon on home screen only
            return

        elif (self.s['on_upd_detected'] in [
                2, 3
        ]) or (self.s['on_upd_detected'] == 4 and self.REBOOT_REQUIRED):
            # Download updates, then prompt
            # Download and display icon
            # Download, install, prompt if restart needed (restart is needed)
            self.call_child_script('fetch')
            return

        elif (self.s['on_upd_detected'] == 4
              and not self.REBOOT_REQUIRED) or self.s['on_upd_detected'] == 5:
            # Download, install, prompt if restart needed (restart is not needed)
            # Download, install, auto-restart if needed
            self.call_child_script('commit')
            return

        elif self.s['on_upd_detected'] == 0:
            # show all prompts (default)

            if self.REBOOT_REQUIRED == 1:

                log("We can't upgrade from within Kodi as it needs updating itself"
                    )

                # Downloading all the debs at once require su access. So we call an external script to download the updates
                # to the default apt_cache. That other script provides a progress update to this parent script,
                # which is displayed as a background progress bar
                self.call_child_script('fetch')

            else:

                log("Updates are available, no reboot is required")

                install = DIALOG.yesno(
                    'OSMC Update Available',
                    'There are updates that are available for install.',
                    'Would you like to install them now?')

                if install:

                    self.call_child_script('commit')  # Actually installs

                    self.window.setProperty('OSMC_notification', 'false')

                else:

                    okey_dokey = DIALOG.ok(
                        'OSMC Update Available', 'Fair enough, then.',
                        'You can install them from within the OSMC settings later.'
                    )

                    # create the file that will prevent further update checks until the updates have been installed
                    with open(self.block_update_file, 'w') as f:
                        f.write('d')

                    # trigger the flag to skip update checks
                    self.skip_update_check = True
Example #18
0
def get_packages():
    return apt.Cache()
Example #19
0
def package_versions():
    pkgs = {'kernel': runtime_kernel_flags().version}

    if _release_name() in (OSName.RHEVH, OSName.OVIRT, OSName.FEDORA,
                           OSName.RHEL, OSName.POWERKVM):
        KEY_PACKAGES = {
            'glusterfs-cli': ('glusterfs-cli', ),
            'librbd1': ('librbd1', ),
            'libvirt': ('libvirt', 'libvirt-daemon-kvm'),
            'mom': ('mom', ),
            'ovirt-hosted-engine-ha': ('ovirt-hosted-engine-ha', ),
            'qemu-img': ('qemu-img', 'qemu-img-rhev', 'qemu-img-ev'),
            'qemu-kvm': ('qemu-kvm', 'qemu-kvm-rhev', 'qemu-kvm-ev'),
            'spice-server': ('spice-server', ),
            'vdsm': ('vdsm', ),
        }

        if glusterEnabled:
            KEY_PACKAGES.update(GLUSTER_RPM_PACKAGES)

        try:
            ts = rpm.TransactionSet()

            for pkg, names in KEY_PACKAGES.iteritems():
                try:
                    mi = itertools.chain(
                        *[ts.dbMatch('name', name) for name in names]).next()
                except StopIteration:
                    logging.debug("rpm package %s not found",
                                  KEY_PACKAGES[pkg])
                else:
                    pkgs[pkg] = {
                        'version': mi['version'],
                        'release': mi['release'],
                    }
        except Exception:
            logging.error('', exc_info=True)

    elif _release_name() == OSName.DEBIAN and python_apt:
        KEY_PACKAGES = {
            'glusterfs-cli': 'glusterfs-cli',
            'librbd1': 'librbd1',
            'libvirt': 'libvirt0',
            'mom': 'mom',
            'qemu-img': 'qemu-utils',
            'qemu-kvm': 'qemu-kvm',
            'spice-server': 'libspice-server1',
            'vdsm': 'vdsmd',
        }

        if glusterEnabled:
            KEY_PACKAGES.update(GLUSTER_DEB_PACKAGES)

        cache = apt.Cache()

        for pkg in KEY_PACKAGES:
            try:
                deb_pkg = KEY_PACKAGES[pkg]
                ver = cache[deb_pkg].installed.version
                # Debian just offers a version
                pkgs[pkg] = dict(version=ver, release="")
            except Exception:
                logging.error('', exc_info=True)

    return pkgs
Example #20
0
def system_driver_packages(apt_cache=None, sys_path=None, freeonly=False, include_oem=True):
    '''Get driver packages that are available for the system.

    This calls system_modaliases() to determine the system's hardware and then
    queries apt about which packages provide drivers for those. It also adds
    available packages from detect_plugin_packages().

    If you already have an apt.Cache() object, you should pass it as an
    argument for efficiency. If not given, this function creates a temporary
    one by itself.

    If freeonly is set to True, only free packages (from main and universe) are
    considered

    Return a dictionary which maps package names to information about them:

      driver_package → {'modalias': 'pci:...', ...}

    Available information keys are:
      'modalias':    Modalias for the device that needs this driver (not for
                     drivers from detect plugins)
      'syspath':     sysfs directory for the device that needs this driver
                     (not for drivers from detect plugins)
      'plugin':      Name of plugin that detected this package (only for
                     drivers from detect plugins)
      'free':        Boolean flag whether driver is free, i. e. in the "main"
                     or "universe" component.
      'from_distro': Boolean flag whether the driver is shipped by the distro;
                     if not, it comes from a (potentially less tested/trusted)
                     third party source.
      'vendor':      Human readable vendor name, if available.
      'model':       Human readable product name, if available.
      'recommended': Some drivers (nvidia, fglrx) come in multiple variants and
                     versions; these have this flag, where exactly one has
                     recommended == True, and all others False.
    '''
    modaliases = system_modaliases(sys_path)

    if not apt_cache:
        apt_cache = apt.Cache()

    packages = {}
    for alias, syspath in modaliases.items():
        for p in packages_for_modalias(apt_cache, alias):
            if freeonly and not _is_package_free(p):
                continue
            if not include_oem and fnmatch.fnmatch(p.name, 'oem-*-meta'):
                continue
            packages[p.name] = {
                    'modalias': alias,
                    'syspath': syspath,
                    'free': _is_package_free(p),
                    'from_distro': _is_package_from_distro(p),
                }
            (vendor, model) = _get_db_name(syspath, alias)
            if vendor is not None:
                packages[p.name]['vendor'] = vendor
            if model is not None:
                packages[p.name]['model'] = model

    # Add "recommended" flags for NVidia alternatives
    nvidia_packages = [p for p in packages if p.startswith('nvidia-')]
    if nvidia_packages:
        nvidia_packages.sort(key=functools.cmp_to_key(_cmp_gfx_alternatives))
        recommended = nvidia_packages[-1]
        for p in nvidia_packages:
            packages[p]['recommended'] = (p == recommended)

    # Add "recommended" flags for fglrx alternatives
    fglrx_packages = [p for p in packages if p.startswith('fglrx-')]
    if fglrx_packages:
        fglrx_packages.sort(key=functools.cmp_to_key(_cmp_gfx_alternatives))
        recommended = fglrx_packages[-1]
        for p in fglrx_packages:
            packages[p]['recommended'] = (p == recommended)

    # add available packages which need custom detection code
    for plugin, pkgs in detect_plugin_packages(apt_cache).items():
        for p in pkgs:
            apt_p = apt_cache[p]
            packages[p] = {
                    'free': _is_package_free(apt_p),
                    'from_distro': _is_package_from_distro(apt_p),
                    'plugin': plugin,
                }

    return packages
Example #21
0
 def __init__(self):
     self.apt_cache = apt.Cache()
     self.pool = AppStream.Pool()
     self.pool.load()
     self.transacted = []
Example #22
0
def system_gpgpu_driver_packages(apt_cache=None, sys_path=None):
    '''Get driver packages, for gpgpu purposes, that are available for the system.

    This calls system_modaliases() to determine the system's hardware and then
    queries apt about which packages provide drivers for those. Finally, it looks
    for the correct metapackage, by calling _get_headless_no_dkms_metapackage().

    If you already have an apt.Cache() object, you should pass it as an
    argument for efficiency. If not given, this function creates a temporary
    one by itself.

    Return a dictionary which maps package names to information about them:

      driver_package → {'modalias': 'pci:...', ...}

    Available information keys are:
      'modalias':    Modalias for the device that needs this driver (not for
                     drivers from detect plugins)
      'syspath':     sysfs directory for the device that needs this driver
                     (not for drivers from detect plugins)
      'plugin':      Name of plugin that detected this package (only for
                     drivers from detect plugins)
      'free':        Boolean flag whether driver is free, i. e. in the "main"
                     or "universe" component.
      'from_distro': Boolean flag whether the driver is shipped by the distro;
                     if not, it comes from a (potentially less tested/trusted)
                     third party source.
      'vendor':      Human readable vendor name, if available.
      'model':       Human readable product name, if available.
      'recommended': Some drivers (nvidia, fglrx) come in multiple variants and
                     versions; these have this flag, where exactly one has
                     recommended == True, and all others False.
    '''
    vendors_whitelist = ['10de']
    modaliases = system_modaliases(sys_path)

    if not apt_cache:
        apt_cache = apt.Cache()

    packages = {}
    for alias, syspath in modaliases.items():
        for p in packages_for_modalias(apt_cache, alias):
            (vendor, model) = _get_db_name(syspath, alias)
            vendor_id, model_id = _get_vendor_model_from_alias(alias)
            if (vendor_id is not None) and (vendor_id.lower() in vendors_whitelist):
                packages[p.name] = {
                        'modalias': alias,
                        'syspath': syspath,
                        'free': _is_package_free(p),
                        'from_distro': _is_package_from_distro(p),
                    }
                if vendor is not None:
                    packages[p.name]['vendor'] = vendor
                if model is not None:
                    packages[p.name]['model'] = model
                metapackage = _get_headless_no_dkms_metapackage(p, apt_cache)

                if metapackage is not None:
                    packages[p.name]['metapackage'] = metapackage

    # Add "recommended" flags for NVidia alternatives
    nvidia_packages = [p for p in packages if p.startswith('nvidia-')]
    if nvidia_packages:
        nvidia_packages.sort(key=functools.cmp_to_key(_cmp_gfx_alternatives))
        recommended = nvidia_packages[-1]
        for p in nvidia_packages:
            packages[p]['recommended'] = (p == recommended)

    return packages
Example #23
0
 def __init__(self):
     self._progress = _NoteProgress()
     self._cache = apt.Cache(self._progress)
Example #24
0
def system_device_drivers(apt_cache=None, sys_path=None, freeonly=False):
    '''Get by-device driver packages that are available for the system.

    This calls system_modaliases() to determine the system's hardware and then
    queries apt about which packages provide drivers for each of those. It also
    adds available packages from detect_plugin_packages(), using the name of
    the detction plugin as device name.

    If you already have an apt.Cache() object, you should pass it as an
    argument for efficiency. If not given, this function creates a temporary
    one by itself.

    If freeonly is set to True, only free packages (from main and universe) are
    considered

    Return a dictionary which maps devices to available drivers:

      device_name →  {'modalias': 'pci:...', <device info>,
                      'drivers': {'pkgname': {<driver package info>}}

    A key (device name) is either the sysfs path (for drivers detected through
    modaliases) or the detect plugin name (without the full path).

    Available keys in <device info>:
      'modalias':    Modalias for the device that needs this driver (not for
                     drivers from detect plugins)
      'vendor':      Human readable vendor name, if available.
      'model':       Human readable product name, if available.
      'drivers':     Driver package map for this device, see below. Installing any
                     of the drivers in that map will make this particular
                     device work. The keys are the package names of the driver
                     packages; note that this can be an already installed
                     default package such as xserver-xorg-video-nouveau which
                     provides a free alternative to the proprietary NVidia
                     driver; these will have the 'builtin' flag set.
      'manual_install':
                     None of the driver packages are installed, but the kernel
                     module that it provides is available; this usually means
                     that the user manually installed the driver from upstream.

    Aavailable keys in <driver package info>:
      'builtin':     The package is shipped by default in Ubuntu and MUST
                     NOT be uninstalled. This usually applies to free
                     drivers like xserver-xorg-video-nouveau.
      'free':        Boolean flag whether driver is free, i. e. in the "main"
                     or "universe" component.
      'from_distro': Boolean flag whether the driver is shipped by the distro;
                     if not, it comes from a (potentially less tested/trusted)
                     third party source.
      'recommended': Some drivers (nvidia, fglrx) come in multiple variants and
                     versions; these have this flag, where exactly one has
                     recommended == True, and all others False.
    '''
    result = {}
    if not apt_cache:
        apt_cache = apt.Cache()

    # copy the system_driver_packages() structure into the by-device structure
    for pkg, pkginfo in system_driver_packages(apt_cache, sys_path,
                                               freeonly=freeonly).items():
        if 'syspath' in pkginfo:
            device_name = pkginfo['syspath']
        else:
            device_name = pkginfo['plugin']
        result.setdefault(device_name, {})
        for opt_key in ('modalias', 'vendor', 'model'):
            if opt_key in pkginfo:
                result[device_name][opt_key] = pkginfo[opt_key]
        drivers = result[device_name].setdefault('drivers', {})
        drivers[pkg] = {'free': pkginfo['free'], 'from_distro': pkginfo['from_distro']}
        if 'recommended' in pkginfo:
            drivers[pkg]['recommended'] = pkginfo['recommended']

    # now determine the manual_install device flag: this is true iff all driver
    # packages are "manually installed"
    for driver, info in result.items():
        for pkg in info['drivers']:
            if not _is_manual_install(apt_cache[pkg]):
                break
        else:
            info['manual_install'] = True

    # add OS builtin free alternatives to proprietary drivers
    _add_builtins(result)

    return result
Example #25
0
def install_deb(m, debs, cache, force, install_recommends,
                allow_unauthenticated, dpkg_options):
    changed = False
    deps_to_install = []
    pkgs_to_install = []
    for deb_file in debs.split(','):
        try:
            pkg = apt.debfile.DebPackage(deb_file)
            pkg_name = get_field_of_deb(m, deb_file, "Package")
            pkg_version = get_field_of_deb(m, deb_file, "Version")
            if len(apt_pkg.get_architectures()) > 1:
                pkg_arch = get_field_of_deb(m, deb_file, "Architecture")
                pkg_key = "%s:%s" % (pkg_name, pkg_arch)
            else:
                pkg_key = pkg_name
            try:
                installed_pkg = apt.Cache()[pkg_key]
                installed_version = installed_pkg.installed.version
                if package_version_compare(pkg_version,
                                           installed_version) == 0:
                    # Does not need to down-/upgrade, move on to next package
                    continue
            except Exception:
                # Must not be installed, continue with installation
                pass
            # Check if package is installable
            if not pkg.check() and not force:
                m.fail_json(msg=pkg._failure_string)

            # add any missing deps to the list of deps we need
            # to install so they're all done in one shot
            deps_to_install.extend(pkg.missing_deps)

        except Exception as e:
            m.fail_json(msg="Unable to install package: %s" % to_native(e))

        # and add this deb to the list of packages to install
        pkgs_to_install.append(deb_file)

    # install the deps through apt
    retvals = {}
    if deps_to_install:
        (success,
         retvals) = install(m=m,
                            pkgspec=deps_to_install,
                            cache=cache,
                            install_recommends=install_recommends,
                            allow_unauthenticated=allow_unauthenticated,
                            dpkg_options=expand_dpkg_options(dpkg_options))
        if not success:
            m.fail_json(**retvals)
        changed = retvals.get('changed', False)

    if pkgs_to_install:
        options = ' '.join(["--%s" % x for x in dpkg_options.split(",")])
        if m.check_mode:
            options += " --simulate"
        if force:
            options += " --force-all"

        cmd = "dpkg %s -i %s" % (options, " ".join(pkgs_to_install))

        with PolicyRcD(m):
            rc, out, err = m.run_command(cmd)

        if "stdout" in retvals:
            stdout = retvals["stdout"] + out
        else:
            stdout = out
        if "diff" in retvals:
            diff = retvals["diff"]
            if 'prepared' in diff:
                diff['prepared'] += '\n\n' + out
        else:
            diff = parse_diff(out)
        if "stderr" in retvals:
            stderr = retvals["stderr"] + err
        else:
            stderr = err

        if rc == 0:
            m.exit_json(changed=True, stdout=stdout, stderr=stderr, diff=diff)
        else:
            m.fail_json(msg="%s failed" % cmd, stdout=stdout, stderr=stderr)
    else:
        m.exit_json(changed=changed,
                    stdout=retvals.get('stdout', ''),
                    stderr=retvals.get('stderr', ''),
                    diff=retvals.get('diff', ''))
Example #26
0
 def update_apt_cache(self, init=False):
     '''if init is true, force to update, or it will update only once'''
     if init or not getattr(self, 'cache'):
         apt_pkg.init()
         self.cache = apt.Cache()
    def __init__(self):
        builder = Gtk.Builder()
        builder.set_translation_domain("mintwelcome")
        builder.add_from_file(
            '/usr/share/linuxmint/mintwelcome/mintwelcome.ui')

        window = builder.get_object("main_window")
        window.set_icon_name("mintwelcome")
        window.set_position(Gtk.WindowPosition.CENTER)
        window.connect("destroy", Gtk.main_quit)

        with open("/etc/linuxmint/info") as f:
            config = dict([line.strip().split("=") for line in f])
        codename = config['CODENAME'].capitalize()
        edition = config['EDITION'].replace('"', '')
        release = config['RELEASE']
        desktop = config['DESKTOP']
        release_notes = config['RELEASE_NOTES_URL']
        new_features = config['NEW_FEATURES_URL']
        architecture = "64-bit"
        if platform.machine() != "x86_64":
            architecture = "32-bit"

        # distro-specific
        dist_name = "Linux Mint"
        if os.path.exists(
                "/usr/share/doc/debian-system-adjustments/copyright"):
            dist_name = "LMDE"

        # Setup the labels in the Mint badge
        builder.get_object("label_version").set_text("%s %s" %
                                                     (dist_name, release))
        builder.get_object("label_edition").set_text("%s %s" %
                                                     (edition, architecture))

        # Setup the main stack
        self.stack = Gtk.Stack()
        builder.get_object("center_box").pack_start(self.stack, True, True, 0)
        self.stack.set_transition_type(Gtk.StackTransitionType.CROSSFADE)
        self.stack.set_transition_duration(150)

        # Action buttons
        builder.get_object("button_forums").connect(
            "clicked", self.visit, "https://forums.linuxmint.com")
        builder.get_object("button_documentation").connect(
            "clicked", self.visit, "https://linuxmint.com/documentation.php")
        builder.get_object("button_contribute").connect(
            "clicked", self.visit, "https://linuxmint.com/getinvolved.php")
        builder.get_object("button_irc").connect(
            "clicked", self.visit, "irc://irc.spotchat.org/linuxmint-help")
        builder.get_object("button_codecs").connect(
            "clicked", self.visit, "apt://mint-meta-codecs?refresh=yes")
        builder.get_object("button_new_features").connect(
            "clicked", self.visit, new_features)
        builder.get_object("button_release_notes").connect(
            "clicked", self.visit, release_notes)
        builder.get_object("button_mintupdate").connect(
            "clicked", self.launch, "mintupdate")
        builder.get_object("button_mintinstall").connect(
            "clicked", self.launch, "mintinstall")
        builder.get_object("button_timeshift").connect("clicked", self.pkexec,
                                                       "timeshift-gtk")
        builder.get_object("button_mintdrivers").connect(
            "clicked", self.launch, "driver-manager")
        builder.get_object("button_gufw").connect("clicked", self.launch,
                                                  "gufw")
        builder.get_object("button_layout_legacy").connect(
            "clicked", self.on_button_layout_clicked, LAYOUT_STYLE_LEGACY)
        builder.get_object("button_layout_new").connect(
            "clicked", self.on_button_layout_clicked, LAYOUT_STYLE_NEW)

        # Settings button depends on DE
        de_is_cinnamon = False
        self.theme = None
        if os.getenv("XDG_CURRENT_DESKTOP") in ["Cinnamon", "X-Cinnamon"]:
            builder.get_object("button_settings").connect(
                "clicked", self.launch, "cinnamon-settings")
            de_is_cinnamon = True
            self.theme = Gio.Settings(schema="org.cinnamon.desktop.interface"
                                      ).get_string("gtk-theme")
        elif os.getenv("XDG_CURRENT_DESKTOP") == "MATE":
            builder.get_object("button_settings").connect(
                "clicked", self.launch, "mate-control-center")
        elif os.getenv("XDG_CURRENT_DESKTOP") == "XFCE":
            builder.get_object("button_settings").connect(
                "clicked", self.launch, "xfce4-settings-manager")
        else:
            # Hide settings
            builder.get_object("box_first_steps").remove(
                builder.get_object("box_settings"))

        # Hide Cinnamon layout settings in other DEs
        if not de_is_cinnamon:
            builder.get_object("box_first_steps").remove(
                builder.get_object("box_cinnamon"))

        # Hide codecs box if they're already installed
        add_codecs = False
        cache = apt.Cache()
        if "mint-meta-codecs" in cache:
            pkg = cache["mint-meta-codecs"]
            if not pkg.is_installed:
                add_codecs = True
        if not add_codecs:
            builder.get_object("box_first_steps").remove(
                builder.get_object("box_codecs"))

        # Hide drivers if mintdrivers is absent (LMDE)
        if not os.path.exists("/usr/bin/mintdrivers"):
            builder.get_object("box_first_steps").remove(
                builder.get_object("box_drivers"))

        # Hide new features page for LMDE
        if dist_name == "LMDE":
            builder.get_object("box_documentation").remove(
                builder.get_object("box_new_features"))

        # Construct the stack switcher
        list_box = builder.get_object("list_navigation")

        page = builder.get_object("page_home")
        self.stack.add_named(page, "page_home")
        list_box.add(SidebarRow(page, _("Welcome"), "go-home-symbolic"))
        self.stack.set_visible_child(page)

        page = builder.get_object("page_first_steps")
        self.stack.add_named(page, "page_first_steps")
        list_box.add(
            SidebarRow(page, _("First Steps"), "dialog-information-symbolic"))

        page = builder.get_object("page_documentation")
        self.stack.add_named(page, "page_documentation")
        list_box.add(
            SidebarRow(page, _("Documentation"),
                       "accessories-dictionary-symbolic"))

        page = builder.get_object("page_help")
        self.stack.add_named(page, "page_help")
        list_box.add(SidebarRow(page, _("Help"), "help-browser-symbolic"))

        page = builder.get_object("page_contribute")
        self.stack.add_named(page, "page_contribute")
        list_box.add(SidebarRow(page, _("Contribute"), "starred-symbolic"))

        list_box.connect("row-activated", self.sidebar_row_selected_cb)

        # Construct the bottom toolbar
        box = builder.get_object("toolbar_bottom")
        checkbox = Gtk.CheckButton()
        checkbox.set_label(_("Show this dialog at startup"))
        if not os.path.exists(NORUN_FLAG):
            checkbox.set_active(True)
        checkbox.connect("toggled", self.on_button_toggled)
        box.pack_end(checkbox)

        scale = window.get_scale_factor()

        self.color = "green"
        self.dark_mode = False

        # Use HIDPI pictures if appropriate
        if scale == 1:
            surface = self.surface_for_path(
                "/usr/share/linuxmint/mintwelcome/legacy.png", scale)
            builder.get_object("img_legacy").set_from_surface(surface)
            surface = self.surface_for_path(
                "/usr/share/linuxmint/mintwelcome/modern.png", scale)
            builder.get_object("img_modern").set_from_surface(surface)
        else:
            surface = self.surface_for_path(
                "/usr/share/linuxmint/mintwelcome/legacy-hidpi.png", scale)
            builder.get_object("img_legacy").set_from_surface(surface)
            surface = self.surface_for_path(
                "/usr/share/linuxmint/mintwelcome/modern-hidpi.png", scale)
            builder.get_object("img_modern").set_from_surface(surface)

        path = "/usr/share/linuxmint/mintwelcome/colors/"
        if scale == 2:
            path = "/usr/share/linuxmint/mintwelcome/colors/hidpi/"
        for color in [
                "green", "aqua", "blue", "brown", "grey", "orange", "pink",
                "purple", "red", "sand", "teal"
        ]:
            builder.get_object("img_" + color).set_from_surface(
                self.surface_for_path("%s/%s.png" % (path, color), scale))
            builder.get_object("button_" + color).connect(
                "clicked", self.on_color_button_clicked, color)

        builder.get_object("switch_dark").connect("state-set",
                                                  self.on_dark_mode_changed)

        window.set_default_size(800, 500)
        window.show_all()
Example #28
0
    def __init__(self):

        self.downgrade_mode = (sys.argv[1] == "downgrade"
                               )  # whether to downgrade or remove packages

        glade_file = "/usr/lib/linuxmint/mintSources/mintsources.glade"

        self.builder = Gtk.Builder()
        self.builder.set_translation_domain("mintsources")
        self.builder.add_from_file(glade_file)

        self.window = self.builder.get_object("foreign_window")
        self.window.set_title(_("Foreign packages"))
        self.window.set_icon_name("software-sources")
        self.window.connect("destroy", Gtk.main_quit)
        self.builder.get_object("button_foreign_cancel").connect(
            "clicked", Gtk.main_quit)
        self.action_button = self.builder.get_object("button_foreign_action")
        self.action_button.connect("clicked", self.install)
        if self.downgrade_mode:
            self.action_button.set_label(_("Downgrade"))
            self.builder.get_object(
                "label_foreign_explanation"
            ).set_markup("%s" % _(
                "The version of the following packages doesn't match the one from the repositories:"
            ))
        else:
            self.action_button.set_label(_("Remove"))
            self.builder.get_object(
                "label_foreign_explanation"
            ).set_markup("%s" % _(
                "The packages below are installed on your computer but not present in the repositories:"
            ))
        self.action_button.set_sensitive(False)

        self.select_button = self.builder.get_object("button_foreign_select")
        self.select_button.connect("clicked", self.select_all)
        self.select_button.set_label(_("Select All"))
        self.select_button_selects_all = True

        self.model = Gtk.ListStore(str, bool, str, str, str, str)
        # PKG_ID, PKG_CHECKED, PKG_NAME, PKG_INSTALLED_VERSION, PKG_REPO_VERSION, PKG_SORT_NAME

        treeview = self.builder.get_object("treeview_foreign_pkgs")
        treeview.set_model(self.model)
        self.model.set_sort_column_id(PKG_SORT_NAME, Gtk.SortType.ASCENDING)

        cr = Gtk.CellRendererToggle()
        cr.connect("toggled", self.toggled)
        col = Gtk.TreeViewColumn("", cr)
        col.set_cell_data_func(cr, self.datafunction_checkbox)
        treeview.append_column(col)
        col.set_sort_column_id(PKG_CHECKED)

        r = Gtk.CellRendererText()
        col = Gtk.TreeViewColumn(_("Package"), r, markup=PKG_NAME)
        treeview.append_column(col)
        col.set_sort_column_id(PKG_NAME)

        r = Gtk.CellRendererText()
        col = Gtk.TreeViewColumn(_("Installed version"),
                                 r,
                                 markup=PKG_INSTALLED_VERSION)
        treeview.append_column(col)
        col.set_sort_column_id(PKG_INSTALLED_VERSION)

        if self.downgrade_mode:
            r = Gtk.CellRendererText()
            col = Gtk.TreeViewColumn(_("Repository version"),
                                     r,
                                     markup=PKG_REPO_VERSION)
            treeview.append_column(col)
            col.set_sort_column_id(PKG_REPO_VERSION)

        self.apt = mintcommon.APT(self.window)

        cache = apt.Cache()
        for key in cache.keys():
            pkg = cache[key]
            if (pkg.is_installed):
                candidate_version = pkg.candidate.version
                installed_version = pkg.installed.version

                if not pkg.candidate.downloadable:
                    # The candidate is not downloadable...
                    # See if there's a version that is...
                    best_version = None
                    for version in pkg.versions:
                        if version.downloadable:
                            if best_version is None:
                                best_version = version
                            else:
                                if version.policy_priority > best_version.policy_priority:
                                    best_version = version
                                elif version.policy_priority == best_version.policy_priority:
                                    # same priorities, compare version
                                    return_code = subprocess.call([
                                        "dpkg", "--compare-versions",
                                        version.version, "gt",
                                        best_version.version
                                    ])
                                    if return_code == 0:
                                        best_version = version

                    if self.downgrade_mode:
                        if best_version is not None:
                            for origin in best_version.origins:
                                iter = self.model.insert_before(None, None)
                                self.model.set_value(
                                    iter, PKG_ID,
                                    "%s=%s" % (pkg.name, best_version.version))
                                self.model.set_value(iter, PKG_CHECKED, False)
                                self.model.set_value(iter, PKG_NAME,
                                                     "<b>%s</b>" % pkg.name)
                                self.model.set_value(iter,
                                                     PKG_INSTALLED_VERSION,
                                                     installed_version)
                                self.model.set_value(
                                    iter, PKG_REPO_VERSION, "%s (%s)" %
                                    (best_version.version, origin.archive))
                                self.model.set_value(
                                    iter, PKG_SORT_NAME, "%s %s" %
                                    (best_version.source_name, pkg.name))
                                break
                    else:
                        if best_version is None:
                            iter = self.model.insert_before(None, None)
                            self.model.set_value(iter, PKG_ID,
                                                 "%s" % (pkg.name))
                            self.model.set_value(iter, PKG_CHECKED, False)
                            self.model.set_value(iter, PKG_NAME,
                                                 "<b>%s</b>" % pkg.name)
                            self.model.set_value(iter, PKG_INSTALLED_VERSION,
                                                 installed_version)
                            self.model.set_value(iter, PKG_REPO_VERSION, "")
                            self.model.set_value(iter, PKG_SORT_NAME,
                                                 "%s" % (pkg.name))

        treeview.show()
        treeview.connect("row-activated", self.treeview_row_activated)
        self.window.show_all()
Example #29
0
def _setupSSHDImpl(ngrok_token, ngrok_region):
  #apt-get update
  #apt-get upgrade
  cache = apt.Cache()
  cache.update()
  cache.open(None)
  cache.upgrade()
  cache.commit()

  subprocess.run(["unminimize"], input = "y\n", check = True, universal_newlines = True)

  _installPkg(cache, "openssh-server")
  cache.commit()

  #Reset host keys
  for i in pathlib.Path("/etc/ssh").glob("ssh_host_*_key"):
    i.unlink()
  subprocess.run(
                  ["ssh-keygen", "-A"],
                  check = True)

  #Prevent ssh session disconnection.
  with open("/etc/ssh/sshd_config", "a") as f:
    f.write("\n\nClientAliveInterval 120\n")

  print("ECDSA key fingerprint of host:")
  ret = subprocess.run(
                ["ssh-keygen", "-lvf", "/etc/ssh/ssh_host_ecdsa_key.pub"],
                stdout = subprocess.PIPE,
                check = True,
                universal_newlines = True)
  print(ret.stdout)

  _download("https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip", "ngrok.zip")
  shutil.unpack_archive("ngrok.zip")
  pathlib.Path("ngrok").chmod(stat.S_IXUSR)

  root_password = secrets.token_urlsafe()
  user_password = secrets.token_urlsafe()
  user_name = "colab"
  print("✂️"*24)
  print(f"root password: {root_password}")
  print(f"{user_name} password: {user_password}")
  print("✂️"*24)
  subprocess.run(["useradd", "-s", "/bin/bash", "-m", user_name])
  subprocess.run(["chpasswd"], input = f"root:{root_password}", universal_newlines = True)
  subprocess.run(["chpasswd"], input = f"{user_name}:{user_password}", universal_newlines = True)
  subprocess.run(["service", "ssh", "restart"])

  if not pathlib.Path('/root/.ngrok2/ngrok.yml').exists():
    subprocess.run(["./ngrok", "authtoken", ngrok_token])

  subprocess.Popen(["./ngrok", "tcp", "-region", ngrok_region, "22"])
  time.sleep(2)

  with urllib.request.urlopen("http://*****:*****@{hostname}")
  print("✂️"*24)
  print("---")
  print("If you use VNC:")
  print("✂️"*24)
  print(f"ssh {ssh_common_options} -L 5901:localhost:5901 -p {port} {user_name}@{hostname}")
  print("✂️"*24)
Example #30
0
    def __init__(self):

        architecture = commands.getoutput("dpkg --print-architecture")

        self.downgrade_mode = (sys.argv[1] == "downgrade"
                               )  # whether to downgrade or remove packages

        self.foreign_packages = []

        glade_file = "/usr/lib/linuxmint/mintSources/mintSources.glade"

        self.builder = gtk.Builder()
        self.builder.add_from_file(glade_file)

        self.window = self.builder.get_object("foreign_window")
        self.window.set_title(_("Foreign packages"))
        self.window.set_icon_from_file(
            "/usr/share/icons/hicolor/scalable/apps/software-sources.svg")
        self.window.connect("destroy", gtk.main_quit)
        self.builder.get_object("button_foreign_cancel").connect(
            "clicked", gtk.main_quit)
        self.action_button = self.builder.get_object("button_foreign_action")
        self.action_button.connect("clicked", self.install)
        if self.downgrade_mode:
            self.action_button.set_label(_("Downgrade"))
            self.builder.get_object(
                "label_foreign_explanation"
            ).set_markup("<i>%s</i>" % _(
                "The version of the following packages doesn't match the one from the repositories:"
            ))
        else:
            self.action_button.set_label(_("Remove"))
            self.builder.get_object(
                "label_foreign_explanation"
            ).set_markup("<i>%s</i>" % _(
                "The packages below are installed on your computer but not present in the repositories:"
            ))
        self.action_button.set_sensitive(False)
        self.builder.get_object("button_foreign_cancel").set_label(_("Cancel"))
        self.builder.get_object("label_foreign_warning").set_markup(
            "<b>%s</b>" % _("WARNING"))
        self.builder.get_object(
            "label_foreign_review"
        ).set_markup("<i>%s</i>" % _(
            "Review the information below very carefully before validating the command:"
        ))

        self.model = gtk.ListStore(str, bool, str, str, str, str)
        treeview = self.builder.get_object("treeview_foreign_pkgs")
        treeview.set_model(self.model)
        self.model.set_sort_column_id(5, gtk.SORT_ASCENDING)

        r = gtk.CellRendererToggle()
        r.connect("toggled", self.toggled)
        col = gtk.TreeViewColumn("", r)
        col.set_cell_data_func(r, self.datafunction_checkbox)
        treeview.append_column(col)
        col.set_sort_column_id(1)

        r = gtk.CellRendererText()
        col = gtk.TreeViewColumn(_("Package"), r, markup=2)
        treeview.append_column(col)
        col.set_sort_column_id(2)

        r = gtk.CellRendererText()
        col = gtk.TreeViewColumn(_("Installed version"), r, markup=3)
        treeview.append_column(col)
        col.set_sort_column_id(3)

        if self.downgrade_mode:
            r = gtk.CellRendererText()
            col = gtk.TreeViewColumn(_("Repository version"), r, markup=4)
            treeview.append_column(col)
            col.set_sort_column_id(4)

        cache = apt.Cache()
        for key in cache.keys():
            pkg = cache[key]
            if (pkg.is_installed):
                candidate_version = pkg.candidate.version
                installed_version = pkg.installed.version

                if not pkg.candidate.downloadable:
                    # The candidate is not downloadable...
                    # See if there's a version that is...
                    best_version = None
                    for version in pkg.versions:
                        if version.downloadable:
                            if best_version is None:
                                best_version = version
                            else:
                                if version.policy_priority > best_version.policy_priority:
                                    best_version = version
                                elif version.policy_priority == best_version.policy_priority:
                                    # same priorities, compare version
                                    if commands.getoutput(
                                            "dpkg --compare-versions %s gt %s && echo 'OK'"
                                            % (version.version,
                                               best_version.version)) == "OK":
                                        best_version = version

                    if self.downgrade_mode:
                        if best_version is not None:
                            for origin in best_version.origins:
                                self.model.append(
                                    ("%s=%s" %
                                     (pkg.name, best_version.version), False,
                                     "<b>%s</b>" % pkg.name, installed_version,
                                     "%s (%s)" %
                                     (best_version.version, origin.archive),
                                     "%s %s" %
                                     (best_version.source_name, pkg.name)))
                                break
                    else:
                        if best_version is None:
                            self.model.append(
                                ("%s" % (pkg.name), False,
                                 "<b>%s</b>" % pkg.name, installed_version, "",
                                 "%s" % (pkg.name)))

        treeview.show()
        self.window.show_all()

        parent_window_xid = int(sys.argv[2])
        try:
            parent = gtk.gdk.window_foreign_new(parent_window_xid)
            self.window.realize()
            self.window.window.set_transient_for(parent)
        except:
            pass