Beispiel #1
0
 def showConfirmationDlg(self, title, message):
     head = "<html><head><style>body { font-family: Arial, Helvetica, Verdana, Sans-serif; font-size: 12px; color: #555555; background: #ffffff; }</style></head><body>"
     end = "</body></html>"
     html = "%s%s%s" % (head, message, end)
     sw = Gtk.ScrolledWindow()
     sw.add(SimpleBrowser(html))
     return CustomQuestionDialog(title, sw, 550, 300, self.window).show()
Beispiel #2
0
def create_browser():
    name = os.getenv('BROWSER', 'chrome')
    width = 1920
    height = 1080
    logger.debug('creating browser %s, width %s, height %s', name, width,
                 height)
    browser = SimpleBrowser(browser=name, width=width, height=height)
    return browser
Beispiel #3
0
 def loadHtml(self, page):
     page = "{}/{}.html".format(self.languageDir, page)
     if exists(page):
         url = "file://{}".format(page)
         children = self.swWelcome.get_children()
         if children:
             children[0].openUrl(url)
         else:
             self.swWelcome.add(SimpleBrowser(url))
    def loadInfo(self):
        url = join("file://%s" % self.scriptDir,
                   self.umglobal.settings['not-found'])
        self.btnInfo.set_icon_name("help-about")
        if self.umglobal.umfilesUrl is not None:
            url = "%s/%s" % (self.umglobal.umfilesUrl,
                             self.umglobal.settings['upd-info'])

        self.log.write("Load info url: %s" % url, "UM.loadInfo", "debug")

        children = self.swInfo.get_children()
        if children:
            children[0].openUrl(url)
        else:
            self.swInfo.add(SimpleBrowser(url))
Beispiel #5
0
def module_browser(base_url):
   browser = os.getenv('BROWSER', 'chrome')
   width = int(os.getenv('WIDTH', '1920'))
   height = int(os.getenv('HEIGHT', '1080'))
   logger.debug('creating browser %s, width %s, height %s', browser, width, height)
   sb = SimpleBrowser(browser=browser, width=width, height=height)
   sb.get(base_url)
   sb.click(xpath="//span[contains(@class, 'banner-close')]")
   yield sb
   logger.debug('shutting down browser')
   del sb
Beispiel #6
0
    def loadInfo(self):
        languageDir = self.get_language_dir()
        url = join("file://%s" % languageDir,
                   self.umglobal.settings['up-to-date'])
        self.btnInfo.set_icon_name("help-about")
        if self.upgradables:
            url = join("file://%s" % languageDir,
                       self.umglobal.settings['updates'])
            if self.umglobal.newUpd:
                url = "%s/%s/%s" % (self.umglobal.settings['solydxk'],
                                    self.umglobal.settings["umfilesdir"],
                                    self.umglobal.settings['upd-info'])
        elif self.umglobal.serverUpdVersion is None:
            url = join("file://%s" % languageDir,
                       self.umglobal.settings['not-found'])

        self.log.write("Load info url: %s" % url, "UM.loadInfo", "debug")

        children = self.swInfo.get_children()
        if children:
            children[0].openUrl(url)
        else:
            self.swInfo.add(SimpleBrowser(url))
Beispiel #7
0
    def __init__(self):

        # Check the system's architecture
        self.architecture = get_architecture()

        # Check for backports
        self.isBackportsEnabled = False
        output = getoutput("grep backports /etc/apt/sources.list | grep -v ^#")
        if output:
            self.isBackportsEnabled = True
        else:
            output = getoutput("grep backports /etc/apt/sources.list.d/*.list | grep -v ^#")
            if output:
                self.isBackportsEnabled = True

        # ================================
        # Define html page array
        # 0 = no action (just show)
        # 1 = apt install
        # 2 = open external application
        self.pages = []
        self.pages.append([0, 'welcome'])
        if not 'arm' in self.architecture:
            if self.need_drivers():
                self.pages.append([2, 'drivers'])
            self.pages.append([1, 'multimedia'])
        if self.isBackportsEnabled:
            self.pages.append([1, 'libreoffice'])
        self.pages.append([1, 'business'])
        self.pages.append([1, 'home'])
        self.pages.append([1, 'system'])
        self.pages.append([1, 'games'])
        if not 'arm' in self.architecture:
            self.pages.append([1, 'wine'])
        # ================================

        # Load window and widgets
        self.scriptName = basename(__file__)
        self.scriptDir = abspath(dirname(__file__))
        self.mediaDir = abspath(join(self.scriptDir, '../../../share/solydxk/welcome'))
        self.htmlDir = join(self.mediaDir, "html")
        self.builder = Gtk.Builder()
        self.builder.add_from_file(join(self.mediaDir, 'welcome.glade'))

        # Main window objects
        go = self.builder.get_object
        self.window = go("welcomeWindow")
        self.swWelcome = go("swWelcome")
        self.btnInstall = go("btnInstall")
        self.btnQuit = go("btnQuit")
        self.btnNext = go("btnNext")
        self.btnPrevious = go("btnPrevious")
        self.pbWelcome = go("pbWelcome")

        self.window.set_title(_("SolydXK Welcome"))
        self.btnInstall.set_label(_("Install"))
        self.btnQuit.set_label(_("Quit"))
        self.btnNext.set_label(_("Next"))
        self.btnPrevious.set_label(_("Previous"))

        self.btnInstall.set_sensitive(False)
        self.btnPrevious.set_sensitive(False)

        # Resize the window to 75% of the screen size in the primary monitor
        display = Gdk.Display.get_default()
        pm = display.get_primary_monitor()
        geo = pm.get_geometry()
        w = geo.width
        h = geo.height
        if w > 640:
            self.window.set_default_size(w * 0.75, h * 0.75)
        else:
            self.window.fullscreen()

        # Initiate variables
        self.browser = SimpleBrowser()
        self.browser.connect("js-finished", self.install_packages)
        self.langDir = self.get_language_dir()
        self.selected_packages = []
        self.queue = Queue(-1)
        self.threads = {}
        self.currentPage = 0
        self.flagPath = os.path.join(os.environ.get('HOME'), '.sws.flag')
        self.lastPage = len(self.pages) - 1
        self.pbSavedState = 0
        self.nextSavedState = True
        self.prevSavedState = False

        # Load first HTML page and show in window
        self.loadHtml(self.pages[0][1])
        self.swWelcome.add(self.browser)

        # Connect builder signals and show window
        self.builder.connect_signals(self)
        self.window.show_all()
Beispiel #8
0
class SolydXKWelcome(object):

    def __init__(self):

        # Check the system's architecture
        self.architecture = get_architecture()

        # Check for backports
        self.isBackportsEnabled = False
        output = getoutput("grep backports /etc/apt/sources.list | grep -v ^#")
        if output:
            self.isBackportsEnabled = True
        else:
            output = getoutput("grep backports /etc/apt/sources.list.d/*.list | grep -v ^#")
            if output:
                self.isBackportsEnabled = True

        # ================================
        # Define html page array
        # 0 = no action (just show)
        # 1 = apt install
        # 2 = open external application
        self.pages = []
        self.pages.append([0, 'welcome'])
        if not 'arm' in self.architecture:
            if self.need_drivers():
                self.pages.append([2, 'drivers'])
            self.pages.append([1, 'multimedia'])
        if self.isBackportsEnabled:
            self.pages.append([1, 'libreoffice'])
        self.pages.append([1, 'business'])
        self.pages.append([1, 'home'])
        self.pages.append([1, 'system'])
        self.pages.append([1, 'games'])
        if not 'arm' in self.architecture:
            self.pages.append([1, 'wine'])
        # ================================

        # Load window and widgets
        self.scriptName = basename(__file__)
        self.scriptDir = abspath(dirname(__file__))
        self.mediaDir = abspath(join(self.scriptDir, '../../../share/solydxk/welcome'))
        self.htmlDir = join(self.mediaDir, "html")
        self.builder = Gtk.Builder()
        self.builder.add_from_file(join(self.mediaDir, 'welcome.glade'))

        # Main window objects
        go = self.builder.get_object
        self.window = go("welcomeWindow")
        self.swWelcome = go("swWelcome")
        self.btnInstall = go("btnInstall")
        self.btnQuit = go("btnQuit")
        self.btnNext = go("btnNext")
        self.btnPrevious = go("btnPrevious")
        self.pbWelcome = go("pbWelcome")

        self.window.set_title(_("SolydXK Welcome"))
        self.btnInstall.set_label(_("Install"))
        self.btnQuit.set_label(_("Quit"))
        self.btnNext.set_label(_("Next"))
        self.btnPrevious.set_label(_("Previous"))

        self.btnInstall.set_sensitive(False)
        self.btnPrevious.set_sensitive(False)

        # Resize the window to 75% of the screen size in the primary monitor
        display = Gdk.Display.get_default()
        pm = display.get_primary_monitor()
        geo = pm.get_geometry()
        w = geo.width
        h = geo.height
        if w > 640:
            self.window.set_default_size(w * 0.75, h * 0.75)
        else:
            self.window.fullscreen()

        # Initiate variables
        self.browser = SimpleBrowser()
        self.browser.connect("js-finished", self.install_packages)
        self.langDir = self.get_language_dir()
        self.selected_packages = []
        self.queue = Queue(-1)
        self.threads = {}
        self.currentPage = 0
        self.flagPath = os.path.join(os.environ.get('HOME'), '.sws.flag')
        self.lastPage = len(self.pages) - 1
        self.pbSavedState = 0
        self.nextSavedState = True
        self.prevSavedState = False

        # Load first HTML page and show in window
        self.loadHtml(self.pages[0][1])
        self.swWelcome.add(self.browser)

        # Connect builder signals and show window
        self.builder.connect_signals(self)
        self.window.show_all()

    # ===============================================
    # Main window functions
    # ===============================================
    
    def install_packages(self, browser):
        values = browser.js_values
        # Do not install VirtualBox in VirtualBox client
        if in_virtualbox() and 'virtualbox' in values:
            msg = _("VirtualBox cannot be installed in a VirtualBox client.\n"
                    "This package is skipped.")
            MessageDialog(self.btnInstall.get_label(), msg)
            values.remove('virtualbox')
                
        # Install selected packages
        if values:
            page = self.pages[self.currentPage][1]
            script = join(self.scriptDir, "scripts/{}".format(page))
            print(("Install packages: {}".format(' '.join(values))))
            self.exec_command("pkexec env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY {} {}".format(script, ' '.join(values)))
        else:
            msg = _("Nothing to do:\n"
                    "No packages were selected.")
            MessageDialog(self.btnInstall.get_label(), msg)
        
        # Enable the buttons
        self.set_buttons_state(True)

    def on_btnInstall_clicked(self, widget):
        actionNr = self.pages[self.currentPage][0]
        if actionNr > 0:
            # Check if there is an internet connection
            if not has_internet_connection():
                title = _("No internet connection")
                msg = _("You need an internet connection to install the additional software.\n"
                        "Please, connect to the internet and try again.")
                WarningDialog(title, msg)
                return

            # Disable buttons
            self.set_buttons_state(False)

            # Check for installation script
            page = self.pages[self.currentPage][1]
            script = join(self.scriptDir, "scripts/{}".format(page))
            if exists(script):
                if actionNr == 1:
                    # Get the values of the selected checkboxes
                    self.browser.get_element_values('package')
                    # Asynchronous handling: installation by callback function install_packages
                elif actionNr == 2:
                    os.system("/bin/sh -c \"{}\" &".format(script))
                    self.set_buttons_state(True)
            else:
                msg = _("Cannot install the requested software:\n"
                        "Script not found: {}".format(script))
                ErrorDialog(self.btnInstall.get_label(), msg)
                self.set_buttons_state(True)

    def on_btnQuit_clicked(self, widget):
        self.on_welcomeWindow_destroy(widget)

    def on_btnPrevious_clicked(self, widget):
        self.switchPage(-1)

    def on_btnNext_clicked(self, widget):
        self.switchPage(1)

    def switchPage(self, count):
        self.currentPage += count
        self.btnInstall.set_sensitive(self.pages[self.currentPage][0])
        self.btnPrevious.set_sensitive(self.currentPage)
        self.btnNext.set_sensitive(self.currentPage - self.lastPage)
        self.loadHtml(self.pages[self.currentPage][1])
        if self.currentPage > 0:
            self.pbWelcome.set_fraction(1 / (self.lastPage / self.currentPage))
        else:
            self.pbWelcome.set_fraction(0)
        if not self.btnNext.get_sensitive():
            self.btnPrevious.grab_focus()
        elif not self.btnPrevious.get_sensitive():
            self.btnNext.grab_focus()

    def loadHtml(self, page):
        page_path = '{0}/{1}.html'.format(self.langDir, page)
        if exists(page_path):
            self.browser.show_html(page_path)

    def get_language_dir(self):
        # First test if full locale directory exists, e.g. html/pt_BR,
        # otherwise perhaps at least the language is there, e.g. html/pt
        # and if that doesn't work, try html/pt_PT
        lang = self.get_current_language()
        path = join(self.htmlDir, lang)
        if not isdir(path):
            base_lang = lang.split('_')[0].lower()
            path = join(self.htmlDir, base_lang)
            if not isdir(path):
                path = join(self.htmlDir, "{}_{}".format(base_lang, base_lang.upper()))
                if not isdir(path):
                    path = join(self.htmlDir, 'en')
        return path

    def get_current_language(self):
        lang = os.environ.get('LANG', 'US').split('.')[0]
        if lang == '':
            lang = 'en'
        return lang

    def show_message(self, cmdOutput, onlyOnError=False):
        try:
            msg = _("There was an error during the installation.\n"
                    "Please, run 'sudo apt-get -f install' in a terminal.\n"
                    "Visit our forum for support: https://forums.solydxk.com")
            if int(cmdOutput) != 255:
                if int(cmdOutput) > 0:
                    # There was an error
                    ErrorDialog(self.btnInstall.get_label(), msg)
                elif not onlyOnError:
                    msg = _("The software has been successfully installed.")
                    MessageDialog(self.btnInstall.get_label(), msg)
        except:
            MessageDialog(self.btnInstall.get_label(), cmdOutput)

    def exec_command(self, command):
        try:
            # Run the command in a separate thread
            print(("Run command: {}".format(command)))
            name = 'aptcmd'
            t = ExecuteThreadedCommands([command], self.queue)
            self.threads[name] = t
            t.daemon = True
            t.start()
            self.queue.join()
            GObject.timeout_add(250, self.check_thread, name)

        except Exception as detail:
            ErrorDialog(self.btnInstall.get_label(), detail)

    def set_buttons_state(self, enable):
        if not enable:
            # Get widgets current state
            self.nextSavedState = self.btnNext.get_sensitive()
            self.prevSavedState = self.btnPrevious.get_sensitive()
            self.pbSavedState = self.pbWelcome.get_fraction()

            # Disable buttons and pulse the progressbar
            self.btnInstall.set_sensitive(False)
            self.btnNext.set_sensitive(False)
            self.btnPrevious.set_sensitive(False)
        else:
            # Set widgets back to old state
            self.pbWelcome.set_fraction(self.pbSavedState)
            self.btnNext.set_sensitive(self.nextSavedState)
            self.btnPrevious.set_sensitive(self.prevSavedState)
            self.btnInstall.set_sensitive(True)

    def check_thread(self, name):
        if self.threads[name].is_alive():
            self.pbWelcome.pulse()
            if not self.queue.empty():
                ret = self.queue.get()
                print(("Queue returns: {}".format(ret)))
                self.queue.task_done()
                self.show_message(ret, True)
            return True

        # Thread is done
        #print(("++ Thread is done"))
        if not self.queue.empty():
            ret = self.queue.get()
            self.queue.task_done()
            self.show_message(ret)
        del self.threads[name]

        self.set_buttons_state(True)

        return False

    # Check with ddm if we can install proprietary drivers
    def need_drivers(self):
        if exists('/usr/bin/ddm'):
            hw_list = ['amd', 'nvidia', 'broadcom', 'pae']
            for hw in hw_list:
                drivers = getoutput("ddm -i %s -s" % hw)
                if drivers[0]:
                    return True
        return False

    # Close the gui
    def on_welcomeWindow_destroy(self, widget):
        # Create flag file
        print(('touch {}'.format(self.flagPath)))
        os.system('touch {}'.format(self.flagPath))
        # Close the app
        Gtk.main_quit()
Beispiel #9
0
 def __init__(self):
     self.sb = SimpleBrowser(browser='chrome', width=1920, height=1080)
Beispiel #10
0
class LinkedIn:
    def __init__(self):
        self.sb = SimpleBrowser(browser='chrome', width=1920, height=1080)

    def login(self, username: str, password: str):
        self.sb.get(
            'https://www.linkedin.com/login?fromSignIn=true&trk=guest_homepage-basic_nav-header-signin'
        )
        self.sb.input(xpath='//input[@id="username"]', keys=username)
        self.sb.input(xpath='//input[@id="password"]', keys=password)
        pause()
        self.sb.click(xpath='//button[contains(text(), "Sign in")]')
        pause()

    def __salesnav_search_page(self):
        pause()
        self.sb.scroll_down_page()
        res = parse_salesnav_search(self.sb.driver.page_source)
        return res

    def salesnav_search(self, url: str, start_page: int, num_pages: int):
        assert num_pages > 0
        current_page: int = start_page
        self.sb.get(f'{url}&page={current_page}')
        while True:
            logger.info('processing page %s', current_page)
            pause()
            self.sb.scroll_down_page()
            res = parse_salesnav_search(self.sb.driver.page_source)
            for sr in res:
                yield sr
            current_page = current_page + 1
            if current_page >= start_page + num_pages:
                break
            n = self.sb.find(
                xpath=
                '//button[@class="search-results__pagination-next-button"]',
                scroll=True)
            disabled = n.get_attribute('disabled')
            if disabled:
                break
            else:
                n.click()

    def __salesnav_goto_profile(self):
        self.sb.click(
            xpath=
            '//button[contains(@class, "right-actions-overflow-menu-trigger")]'
        )
        pause(min=200, max=300)
        self.sb.click(xpath='//div[@data-control-name="view_linkedin"]')
        pause(min=500, max=1000)
        # this is one weird thing.. linkedin.com opens in new tab so we need to switch to it
        # TODO: move this functionality to simplebrowser
        self.sb.driver.switch_to.window(self.sb.driver.window_handles[1])

    def __profile_connect(self, note: str):
        # TODO: assert that we are in a profile page
        self.sb.scroll_down_page()
        self.sb.scroll_up_page()
        connected = False
        try:
            self.sb.click(
                xpath='//button[contains(@aria-label, "Connect with")]')
            connected = True
        except Exception as e:
            pass
#            logger.error('did not find connect button will try more..')

        if not connected:
            self.sb.click(xpath='//button/span[contains(text(), "More")]')
            pause(min=200, max=400)
            self.sb.click(
                xpath=
                '//div[contains(@class, "pv-s-profile-actions--connect")]//span[contains(text(),"Connect")]'
            )
            connected = True

        assert connected
        if note and len(note) > 10:
            self.sb.click(
                xpath='//button[contains(@aria-label, "Add a note")]')
            self.sb.input(xpath='//textarea[@name="message"]', keys=note)
            self.sb.click(xpath='//button[contains(@aria-label, "Done")]')
        else:
            self.sb.click(xpath='//button[contains(@aria-label, "Send now")]')
        pause(min=500, max=1000)

    def __profile_follow(self):
        # TODO: assert that we are in a profile page
        followed = False
        try:
            self.sb.click(xpath='//button[contains(@aria-label, "Follow")]')
            followed = True
        except Exception as e:
            pass
#            logger.error('did not find follow button will try more..')

        if not followed:
            self.sb.click(xpath='//button/span[contains(text(), "More")]')
            pause(min=200, max=400)
            self.sb.click(
                xpath=
                '//div[contains(@class, "pv-s-profile-actions--follow")]//span[contains(text(),"Follow")]'
            )

    def salesnav_connect(self, salesnav_url: str, note: str):
        self.sb.get(salesnav_url)
        pause(min=2000, max=3000)
        res = parse_salesnav_details(page_source=self.sb.driver.page_source)
        self.__salesnav_goto_profile()
        res['profile_url'] = self.sb.get_current_url()
        res2 = parse_profile_details(page_source=self.sb.driver.page_source)
        res = {**res, **res2}
        try:
            if res['connect_status'] == 'not_requested':
                logger.info('trying to connect %s', res['profile_url'])
                self.__profile_connect(note=note)
                logger.info('successfully requested')
            else:
                logger.info('already connected.. skipping')
        except Exception as e:
            logger.exception('connect %s failed', res['profile_url'])
            raise e
        finally:
            self.sb.close_windows()
        return res

    def salesnav_follow(self, salesnav_url: str):
        self.sb.get(salesnav_url)
        pause(min=1000, max=3000)
        res = parse_salesnav_details(page_source=self.sb.driver.page_source)
        self.__salesnav_goto_profile()
        res['profile_url'] = self.sb.get_current_url()
        res2 = parse_profile_details(page_source=self.sb.driver.page_source)
        res = {**res, **res2}
        try:
            if res['follow_status'] == 'not_followed':
                logger.info('trying to follow %s', res['profile_url'])
                self.__profile_follow()
                logger.info('followed successfully')
            else:
                logger.info('already followed.. skipping')
        except Exception as e:
            logger.exception('following %s failed', res['profile_url'])
            raise e
        finally:
            self.sb.close_windows()
        return res

    def invitations_withdraw(self, page: int):
        self.sb.get(
            f'https://www.linkedin.com/mynetwork/invitation-manager/sent/?invitationType=&page={page}'
        )
        self.sb.scroll_down_page()
        lis = self.sb.find_many(
            xpath='//li[contains(@class, "invitation-card")]')
        liws = reversed(lis)

        # for li in reversed(lis):
        #     t = li.find_element_by_xpath('.//time').text
        #     if 'week' in t and li.is_displayed():
        #         liws.append(li)

        for liw in liws:
            self.sb.scroll_down_page()
            logger.info('withdrawing invitation %s', liw.text)
            b = liw.find_element_by_xpath(
                './/button[contains(@data-control-name, "withdraw_single")]')
            b.click()
            pause(min=500, max=1000)
            self.sb.click(
                xpath='//button[contains(@class, "artdeco-button--primary")]')
            pause(min=1000, max=2000)