Beispiel #1
0
def clean(dry_run=False):
    status = UpdaterStatus.get_instance()

    old_status = status.state
    msg = "The status of the updater at boot was: {}".format(status.state)
    logger.debug(msg)

    if status.state == UpdaterStatus.DOWNLOADING_UPDATES:
        # The download was interrupted, go back one state
        status.state = UpdaterStatus.UPDATES_AVAILABLE
    elif status.state == UpdaterStatus.INSTALLING_UPDATES:
        # The installation was interrupted, go back one state
        status.state = UpdaterStatus.UPDATES_DOWNLOADED
    elif status.state == UpdaterStatus.INSTALLING_INDEPENDENT:
        # The installation was interrupted, go back one state
        status.state = UpdaterStatus.NO_UPDATES
    elif status.state == UpdaterStatus.UPDATES_INSTALLED:
        # Show a dialog and change the state back to no updates
        status.state = UpdaterStatus.NO_UPDATES
        status.is_urgent = False

    if status.state != old_status:
        msg = "The status was changed to: {}".format(status.state)
        logger.debug(msg)

    status.notifications_muted = False

    if not dry_run:
        status.save()

    return old_status
Beispiel #2
0
def compare_and_set_full_range(edid, status, model, dry_run=False, force=False):
    """
    Returns True if full range is changed

    TODO: What is this for?
    """
    if status['full_range'] == edid['target_full_range'] and not force:
        logger.debug('Config full range change not needed.')
        return False

    hdmi_pixel_encoding = 2 if edid['target_full_range'] else 0

    logger.info(
        'Config full range change needed. Setting hdmi_pixel_encoding to {}'
        .format(hdmi_pixel_encoding)
    )
    if dry_run and not force:
        return True

    set_config_value(
        'hdmi_pixel_encoding',
        hdmi_pixel_encoding,
        config_filter=Filter.get_edid_filter(model)
    )
    return True
Beispiel #3
0
    def last_check(self, value):
        if not isinstance(value, int):
            msg = "'last_check' must be an Unix timestamp (int)."
            raise UpdaterStatusError(msg)

        logger.debug("Setting the status' last_check to: {}".format(value))
        self._last_check = value
def set_parental_level(level_setting):
    # NB, we pass -1 to disable all
    feature_levels = [
        # Low
        ['blacklist', 'cookies'],
        # Medium
        ['dns'],
        # High
        ['chromium', 'search_engines'],
        # Ultimate
        ['ultimate']
    ]

    enabled = []

    for level, features in enumerate(feature_levels):
        if level <= level_setting:
            enabled = enabled + features

    logger.debug('Setting parental control to level {}'.format(level_setting))

    if 'ultimate' in enabled:
        set_ultimate_parental('ultimate' in enabled)
    else:
        set_ultimate_parental(False)
        set_chromium_parental('chromium' in enabled)
        set_dns_parental('dns' in enabled)
        set_everyone_cookies('cookies' in enabled)

    # Blacklist setup
    blacklist, whitelist = read_listed_sites()

    set_hosts_blacklist('blacklist' in enabled, 'search_engines' in enabled,
                        blocked_sites=blacklist, allowed_sites=whitelist)
Beispiel #5
0
    def last_check(self, value):
        if not isinstance(value, int):
            msg = "'last_check' must be an Unix timestamp (int)."
            raise UpdaterStatusError(msg)

        logger.debug("Setting the status' last_check to: {}".format(value))
        self._last_check = value
Beispiel #6
0
    def save(self):
        logger.debug("Saving status instance")
        data = {
            'state': self._state,
            'last_update': self._last_update,
            'last_check': self._last_check,
            'ind_pkg': self._updatable_independent_packages,
            'last_check_urgent': self._last_check_urgent,
            'first_boot_countdown': self._first_boot_countdown,
            'is_urgent': 1 if self._is_urgent else 0,
            'is_scheduled': 1 if self._is_scheduled else 0,
            'is_shutdown': 1 if self._is_shutdown else 0,
            'notifications_muted': 1 if self._notifications_muted else 0
        }

        with open(self._status_file, 'w') as status_file:
            json.dump(data, status_file, indent=4)

        # When installing updates, configure the recovery stategy for the next
        # boot in case of power failure. This sets a different splash screen
        # during bootup and configures the system to autologin as the user in
        # order to start the Updater immediately. See kano-ui-autostart.
        if self.is_recovery_needed():
            enable_system_recovery_flow()
        else:
            cancel_system_recovery_flow()
Beispiel #7
0
    def is_shutdown(self, value):
        if not isinstance(value, bool):
            msg = "'is_shutdown' must be a boolean value."
            raise UpdaterStatusError(msg)

        logger.debug("Setting the status' is_shutdown to: {}".format(value))
        self._is_shutdown = value
Beispiel #8
0
    def validate(self, *dummy):
        day = self._str_to_int(self._day_dropdown.get_selected_item_text())
        month = self._month_dropdown.get_selected_item_index() + 1
        year = self._str_to_int(self._year_dropdown.get_selected_item_text())

        logger.debug("validate function")
        logger.debug("day = {}".format(day))
        logger.debug("month = {}".format(month))
        logger.debug("year = {}".format(year))

        if self.FIELD_INCOMPLETE in [day, year] or month == 0:
            return self._set_validation_msg("", False)

        try:
            birthday = datetime.date(year, month, day)
        except Exception as e:
            logger.debug("Exception raised when validating = {}".format(str(e)))
            return

        today = datetime.date.today()
        if birthday > today:
            return self._set_validation_msg(_(" date is in the future"), False)

        oldest_date = today.replace(year=(today.year - 100))
        if birthday < oldest_date and (birthday.year < 0 or birthday.year > 99):
            return self._set_validation_msg(_(" year out of range"), False)

        return self._set_validation_msg(_(" is valid"), True)
    def check_command(self, line):
        separate_words = line.split(" ")
        all_items = []

        if separate_words[0] == 'mv' and (separate_words[-1] == 'basket' or
                                          separate_words[-1] == 'basket/'):
            for item in separate_words[1:-1]:
                all_items.append(item)

            items_moved = 0
            hint = ''

            for item in all_items:
                try:
                    self.passable_items.remove(item)
                    items_moved += 1
                except ValueError as e:
                    logger.debug("Tried removing item {} from list. User might have"
                                 " made a typo - [{}]".format(item, e))

            if items_moved:
                hint = _("{{gb:Well done! Keep going.}}")

        else:
            hint = _("{{rb:Try using}} {{yb:mv %s basket/}}") % self.passable_items[0]

        self.send_hint(hint)
Beispiel #10
0
 def abort(self, msg):
     """
         Akin a an exception
     """
     phase = self._phases[self._current_phase_idx]
     logger.debug("Aborting {}, {}".format(phase.label, msg))
     self._abort(phase, msg)
Beispiel #11
0
    def load(self):
        logger.debug("Loading status instance from file")
        with open(self._status_file, 'r') as status_file:
            try:
                data = json.load(status_file)

                # File format sanity check: Try to access the expected keys
                data['state']
                data['last_update']
                data['last_check']
                data['last_check_urgent']
                data['first_boot_countdown']
                data['is_urgent']
                data['is_scheduled']
                data['is_shutdown']
            except Exception:
                # Initialise the file again if it is corrupted
                logger.warn("The status file was corrupted.")
                self.save()
                return

            self._state = data['state']
            self._last_update = data['last_update']
            self._last_check = data['last_check']
            self._updatable_independent_packages = data.get('ind_pkg',[])
            self._last_check_urgent = data['last_check_urgent']
            self._first_boot_countdown = data['first_boot_countdown']
            self._is_urgent = (data['is_urgent'] == 1)
            self._is_scheduled = (data['is_scheduled'] == 1)
            self._is_shutdown = (data['is_shutdown'] == 1)

            if 'notifications_muted' in data:
                self._notifications_muted = (data['notifications_muted'] == 1)
Beispiel #12
0
def make_safesearch_config_file(config_file, opendns):
    new_config = {"port": 53, "host": "127.0.0.1", "rules": []}
    if opendns:
        servers = ', '.join(opendns_servers)
    else:
        # use google servers
        servers = ', '.join(google_servers)

    import pycountry
    import json

    rule_google = "cname ^(?:www.google.)(?:{}) to forcesafesearch.google.com using " + servers
    rule_youtube = "cname ^(?:www.youtube.|m.youtube.|youtubei.googleapis.|youtube.googleapis.|www.youtube-nocookie.)(?:{}) " \
        "to restrict.youtube.com using " + servers

    country_names = [country.alpha2.lower() for country in pycountry.countries]
    country_names.extend(second_level_domains)
    country_names_re = '|'.join(country_names)
    new_config['rules'].append(rule_google.format(country_names_re))
    new_config['rules'].append(rule_youtube.format(country_names_re))
    new_config['rules'].append("resolve ^(.*) using " + servers)

    logger.debug("new safesearch parental control config: {}".format(new_config))
    g = open(config_file, 'w+')
    json.dump(new_config, g)
    g.close()
    logger.debug("finished writing new safesearch parental control to {}".format(config_file))
Beispiel #13
0
def load_badge_rules():
    if not os.path.exists(rules_dir):
        logger.error("rules dir missing")
        return

    merged_rules = dict()
    subfolders = ['badges', 'environments']
    for folder in subfolders:
        folder_fullpath = os.path.join(rules_dir, folder)
        if not os.path.exists(folder_fullpath):
            logger.error("rules subfolder missing: {}".format(folder_fullpath))
            return

        rule_files = os.listdir(folder_fullpath)
        if not rule_files:
            logger.error(
                "no rule files in subfolder: {}".format(folder_fullpath))
            return

        for rule_file in rule_files:
            rule_file_fullpath = os.path.join(folder_fullpath, rule_file)
            if os.path.splitext(rule_file_fullpath)[1] != '.json':
                logger.debug(
                    "Skipping over non json {}".format(rule_file_fullpath))
                continue
            rule_data = read_json(rule_file_fullpath)
            if not rule_data:
                logger.error("rule file empty: {}".format(rule_file_fullpath))
                continue

            category = folder
            subcategory = rule_file.split('.')[0]

            merged_rules.setdefault(category, dict())[subcategory] = rule_data
    return merged_rules
Beispiel #14
0
    def _create_progress_dots(self, index):
        '''Index is a number from1 to 3, and represents which is
        the selected dot (i.e selected page number)
        '''

        logger.debug("Creating dots")

        for child in self.dot_box.get_children():
            self.dot_box.remove(child)

        for i in range(self.num_of_pages):
            if i + 1 == index:
                dot = self.selected_dot()
                dot.set_margin_left(3)
                dot.set_margin_right(3)
                dot.set_margin_top(9)
                dot.set_margin_bottom(9)
            else:
                dot = self.unselected_dot()
                dot.set_margin_left(5)
                dot.set_margin_right(5)
                dot.set_margin_top(11)
                dot.set_margin_bottom(11)

            self.dot_box.pack_start(dot, False, False, 0)

        self.dot_box.show_all()
Beispiel #15
0
def _connect_thread_(wiface, network_name, passphrase, encryption,
                     thread_finish_cb):
    '''
    This function runs in a thread so we can run a spinner alongside.

    :param wiface: wifi card id
    :param network_name: network id
    :param passphrase: password entered by user
    :param encryption: type of encryption
    :param disable_widget_cb: the callback for any widgets that need to be
                              disabled
    :param thread_finish_cb: the callback to be run when the thread is finished
    '''

    success = connect(wiface, network_name, encryption, passphrase)

    # save the connection in cache so it reconnects on next system boot
    wificache = KwifiCache()
    if success:
        wificache.save(network_name, encryption, passphrase)
    else:
        wificache.empty()

    logger.debug(
        "Connecting to {} {} {}. Successful: {}".format(
            network_name, encryption, passphrase, success
        )
    )

    GObject.idle_add(thread_finish_cb, success)
Beispiel #16
0
def _apply_co_packages(dest_dir):
    import tarfile

    co_index = _get_co_assets()

    for order in sorted(co_index.iterkeys()):
        tar_file = co_index[order]
        # First try to open the file
        try:
            tarball = tarfile.open(tar_file)
        except (IOError, OSError) as exc:
            err_msg = "Couldn't open file '{}', [{}]".format(tar_file, exc)
            logger.error(err_msg)
            continue
        except tarfile.ReadError as exc:
            err_msg = 'Error parsing tarfile "{}", [{}]'.format(tar_file, exc)
            logger.error(err_msg)
            continue
        else:
            # Now try to extract the files one by one
            with tarball:
                for tarred_file in tarball:
                    try:
                        tarball.extract(tarred_file, path=dest_dir)
                    except IOError as exc:
                        # This is to guard against weird tar behaviour when
                        # trying to ovewrite symlinks
                        bad_filename = os.path.join(dest_dir, tarred_file.name)
                        if os.path.islink(bad_filename):
                            logger.debug(
                                'Remove link and ovewrite "{}"'.format(
                                    bad_filename)
                            )
                            os.remove(os.path.join(dest_dir, tarred_file.name))
                            tarball.extract(tarred_file, path=dest_dir)
Beispiel #17
0
def clean(dry_run=False):
    status = UpdaterStatus.get_instance()

    old_status = status.state
    msg = "The status of the updater at boot was: {}".format(status.state)
    logger.debug(msg)

    if status.state == UpdaterStatus.DOWNLOADING_UPDATES:
        # The download was interrupted, go back one state
        status.state = UpdaterStatus.UPDATES_AVAILABLE

    elif status.state == UpdaterStatus.UPDATES_INSTALLED:
        # Show a dialog and change the state back to no updates
        status.state = UpdaterStatus.NO_UPDATES
        status.is_urgent = False

    if status.state != old_status:
        msg = "The status was changed to: {}".format(status.state)
        logger.debug(msg)

    status.notifications_muted = False

    if not dry_run:
        status.save()

    return old_status
Beispiel #18
0
def get_window_class(plug=False):
    if plug:
        logger.debug("Launching as a Gtk.Plug")
        return application_window_wrapper(Gtk.Plug)
    else:
        logger.debug("Launching as a Gtk.Window")
        return application_window_wrapper(Gtk.Window)
Beispiel #19
0
def play_sound(audio_file, background=False):
    from kano.logging import logger

    # Check if file exists
    if not os.path.isfile(audio_file):
        logger.error('audio file not found: {}'.format(audio_file))
        return False

    _, extension = os.path.splitext(audio_file)

    if extension in ['wav', 'voc', 'raw', 'au']:
        cmd = 'aplay -q {}'.format(audio_file)
    else:
        volume_percent, _ = get_volume()
        volume_str = '--vol {}'.format(
            percent_to_millibel(volume_percent, raspberry_mod=True))
        cmd = 'omxplayer -o both {volume} {link}'.format(
            volume=volume_str, link=audio_file)

    logger.debug('cmd: {}'.format(cmd))

    if background:
        run_bg(cmd)
        rc = 0
    else:
        _, _, rc = run_cmd_log(cmd)

    return rc == 0
Beispiel #20
0
    def load(self):
        logger.debug("Loading status instance from file")
        with open(self._status_file, 'r') as status_file:
            try:
                data = json.load(status_file)

                # File format sanity check: Try to access the expected keys
                data['state']
                data['last_update']
                data['last_check']
                data['last_check_urgent']
                data['first_boot_countdown']
                data['is_urgent']
                data['is_scheduled']
                data['is_shutdown']
            except Exception:
                # Initialise the file again if it is corrupted
                logger.warn("The status file was corrupted.")
                self.save()
                return

            self._state = data['state']
            self._last_update = data['last_update']
            self._last_check = data['last_check']
            self._updatable_independent_packages = data.get('ind_pkg', [])
            self._last_check_urgent = data['last_check_urgent']
            self._first_boot_countdown = data['first_boot_countdown']
            self._is_urgent = (data['is_urgent'] == 1)
            self._is_scheduled = (data['is_scheduled'] == 1)
            self._is_shutdown = (data['is_shutdown'] == 1)

            if 'notifications_muted' in data:
                self._notifications_muted = (data['notifications_muted'] == 1)
Beispiel #21
0
    def is_shutdown(self, value):
        if not isinstance(value, bool):
            msg = "'is_shutdown' must be a boolean value."
            raise UpdaterStatusError(msg)

        logger.debug("Setting the status' is_shutdown to: {}".format(value))
        self._is_shutdown = value
Beispiel #22
0
 def _create_dropdown_input(self, values):
     logger.debug("dropdown being created with values {}".format(values))
     widget = DropdownInput(values)
     widget.connect("dropdown-changed", self._set_send_sensitive)
     widget.connect("popup", self._set_anti_shrink_flag, True)
     widget.connect("dropdown-changed", self._set_anti_shrink_flag, False)
     return widget
Beispiel #23
0
    def check_command(self):
        separate_words = self.last_user_input.split()
        all_items = []

        if self.get_command_blocked():
            hint = _("{{rb:Try using}} {{yb:mv %s basket/}}"
                     ) % self.passable_items[0]

        elif separate_words[0] == 'mv' and (separate_words[-1] == 'basket' or
                                            separate_words[-1] == 'basket/'):
            for item in separate_words[1:-1]:
                all_items.append(item)

            items_moved = 0
            hint = ''

            for item in all_items:
                try:
                    self.passable_items.remove(item)
                    items_moved += 1
                except ValueError as e:
                    logger.debug(
                        "Tried removing item {} from list. User might have"
                        " made a typo - [{}]".format(item, e))

            if items_moved:
                hint = _("\n{{gb:Well done! Keep going.}}")

        else:
            hint = _("{{rb:Try using}} {{yb:mv %s basket/}}") \
                   % self.passable_items[0]

        self.send_hint(hint)
Beispiel #24
0
 def abort(self, msg):
     """
         Akin a an exception
     """
     phase = self._phases[self._current_phase_idx]
     logger.debug("Aborting {}, {}".format(phase.label, msg))
     self._abort(phase, msg)
Beispiel #25
0
def track_data_and_sync(event_name, event_data):
    """Create a tracking event with data and upload it to the servers.

    This function also appends a uuid to the event data such that these
    immediate events can be grouped more easily.
    See :func:`kano_profile.tracker.tracking_uuids.get_tracking_uuid`.

    Note:
        This is a slow function, requires a network connection and the user
        being logged into Kano World.

    Args:
        event_name (str): See :func:`kano_profile.tracker.track_data`
        event_data (dict): See :func:`kano_profile.tracker.track_data`
    """

    try:
        from kano_profile.tracker import track_data
        from kano_profile.tracker.tracking_uuids import get_tracking_uuid

        event_data['uuid'] = get_tracking_uuid(TRACKING_UUID_KEY)
        track_data(event_name, event_data)
        rc = os.system('kano-sync --skip-kdesk --upload-tracking-data --silent')
        logger.debug(
            'track_data_and_sync: {} {} and sync rc {}'
            .format(event_name, event_data, rc)
        )
    except:
        logger.error('Unexpected error:\n{}'.format(traceback.format_exc()))
Beispiel #26
0
 def widgets_full(self, widget=None, event=None):
     if self.username_entry.validated and self.password_entry.validated and self._is_birthday_valid:
         logger.debug("emiting widgets-full")
         self.emit("widgets-filled")
     else:
         logger.debug("emiting widgets-empty")
         self.emit("widgets-empty")
 def _create_dropdown_input(self, values):
     logger.debug("dropdown being created with values {}".format(values))
     widget = DropdownInput(values)
     widget.connect("dropdown-changed", self._set_send_sensitive)
     widget.connect("popup", self._set_anti_shrink_flag, True)
     widget.connect("dropdown-changed", self._set_anti_shrink_flag, False)
     return widget
    def _cache_get_all(self, offline=False):
        '''
        Loads the complete cache of prompts and answers, answered and postponed
        '''
        cached_prompts = []
        try:
            with open(self.cache_file) as csvfile:
                reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC)
                for row in reader:
                    if row[0]:
                        row[0] = row[0].decode('utf-8')
                    if row[1]:
                        row[1] = row[1].decode('utf-8')
                    if row[2]:
                        row[2] = row[2].decode('utf-8')

                    if offline:
                        if row[1] != 'yes':
                            # this is an offline answer
                            cached_prompts.append([row[0], row[1], row[2]])
                    else:
                        cached_prompts.append([row[0], row[1], row[2]])
        except Exception as e:
            logger.debug("Exception in _cache_get_all: {}".format(str(e)))

        return cached_prompts
Beispiel #29
0
def make_safesearch_config_file(config_file, opendns):
    new_config = {"port": 53, "host": "127.0.0.1", "rules": []}
    if opendns:
        servers = ', '.join(opendns_servers)
    else:
        # use google servers
        servers = ', '.join(google_servers)

    import pycountry
    import json

    rule_google = "cname ^(?:www.google.)(?:{}) to forcesafesearch.google.com using " + servers
    rule_youtube = "cname ^(?:www.youtube.|m.youtube.|youtubei.googleapis.|youtube.googleapis.|www.youtube-nocookie.)(?:{}) " \
        "to restrict.youtube.com using " + servers

    country_names = [country.alpha2.lower() for country in pycountry.countries]
    country_names.extend(second_level_domains)
    country_names_re = '|'.join(country_names)
    new_config['rules'].append(rule_google.format(country_names_re))
    new_config['rules'].append(rule_youtube.format(country_names_re))
    new_config['rules'].append("resolve ^(.*) using " + servers)

    logger.debug(
        "new safesearch parental control config: {}".format(new_config))
    g = open(config_file, 'w+')
    json.dump(new_config, g)
    g.close()
    logger.debug(
        "finished writing new safesearch parental control to {}".format(
            config_file))
Beispiel #30
0
def set_parental_level(level_setting):
    set_setting('Parental-level', max(level_setting, 0))

    # NB, we pass -1 to disable all
    feature_levels = [
        # Low
        ['blacklist', 'forcesafe'],
        # Medium
        ['dns'],
        # High
        ['chromium', 'search_engines'],
        # Ultimate
        ['ultimate']
    ]

    enabled = []

    for level, features in enumerate(feature_levels):
        if level <= level_setting:
            enabled = enabled + features

    logger.debug("Setting parental control to level {}".format(level_setting))

    set_dns_parental('ultimate' in enabled, 'forcesafe' in enabled, 'dns' in enabled)

    if 'ultimate' not in enabled:
        set_chromium_parental('chromium' in enabled)

    # Blacklist setup
    blacklist, whitelist = read_listed_sites()

    set_hosts_blacklist('blacklist' in enabled, 'search_engines' in enabled,
                        blocked_sites=blacklist, allowed_sites=whitelist)
Beispiel #31
0
 def _mark_all_for_update(self, priority=Priority.NONE):
     for pkg in self._cache:
         if self._is_package_upgradable(pkg, priority=priority):
             logger.debug("Marking {} ({}) for upgrade".format(
                 pkg.shortname, pkg.candidate.version
             ))
             pkg.mark_upgrade()
Beispiel #32
0
def save_app_state_variable_with_dialog(app_name, variable, value):
    logger.debug('save_app_state_variable_with_dialog {} {} {}'.format(app_name, variable, value))

    data = load_app_state(app_name)
    data[variable] = value

    save_app_state_with_dialog(app_name, data)
    def validate(self, *dummy):
        day = self._str_to_int(self._day_dropdown.get_selected_item_text())
        month = self._month_dropdown.get_selected_item_index() + 1
        year = self._str_to_int(self._year_dropdown.get_selected_item_text())

        logger.debug("validate function")
        logger.debug("day = {}".format(day))
        logger.debug("month = {}".format(month))
        logger.debug("year = {}".format(year))

        if self.FIELD_INCOMPLETE in [day, year] or month == 0:
            return self._set_validation_msg('', False)

        try:
            birthday = datetime.date(year, month, day)
        except Exception as e:
            logger.debug("Exception raised when validating = {}".format(str(e)))
            return

        today = datetime.date.today()
        if birthday > today:
            return self._set_validation_msg(_('date is in the future'), False)

        oldest_date = today.replace(year=(today.year - 100))
        if birthday < oldest_date and (birthday.year < 0 or birthday.year > 99):
            return self._set_validation_msg(_('year out of range'), False)

        return self._set_validation_msg(_('is valid'), True)
Beispiel #34
0
def set_parental_level(level_setting):
    set_setting('Parental-level', max(level_setting, 0))

    # NB, we pass -1 to disable all
    feature_levels = [
        # Low
        ['blacklist', 'forcesafe'],
        # Medium
        ['dns'],
        # High
        ['chromium', 'search_engines'],
        # Ultimate
        ['ultimate']
    ]

    enabled = []

    for level, features in enumerate(feature_levels):
        if level <= level_setting:
            enabled = enabled + features

    logger.debug("Setting parental control to level {}".format(level_setting))

    set_dns_parental('ultimate' in enabled, 'forcesafe' in enabled, 'dns' in enabled)

    if 'ultimate' not in enabled:
        set_chromium_parental('chromium' in enabled)

    # Blacklist setup
    blacklist, whitelist = read_listed_sites()

    set_hosts_blacklist('blacklist' in enabled, 'search_engines' in enabled,
                        blocked_sites=blacklist, allowed_sites=whitelist)
Beispiel #35
0
def get_window_class(plug=False):
    if plug:
        logger.debug("Launching as a Gtk.Plug")
        return application_window_wrapper(Gtk.Plug)
    else:
        logger.debug("Launching as a Gtk.Window")
        return application_window_wrapper(Gtk.Window)
Beispiel #36
0
    def _cache_get_all(self, offline=False):
        '''
        Loads the complete cache of prompts and answers, answered and postponed
        '''
        cached_prompts = []
        try:
            with open(self.cache_file) as csvfile:
                reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC)
                for row in reader:
                    if row[0]:
                        row[0] = row[0].decode('utf-8')
                    if row[1]:
                        row[1] = row[1].decode('utf-8')
                    if row[2]:
                        row[2] = row[2].decode('utf-8')

                    if offline:
                        if row[1] != 'yes':
                            # this is an offline answer
                            cached_prompts.append([row[0], row[1], row[2]])
                    else:
                        cached_prompts.append([row[0], row[1], row[2]])
        except Exception as e:
            logger.debug("Exception in _cache_get_all: {}".format(str(e)))

        return cached_prompts
Beispiel #37
0
    def save(self):
        logger.debug("Saving status instance")
        data = {
            'state': self._state,
            'last_update': self._last_update,
            'last_check': self._last_check,
            'ind_pkg': self._updatable_independent_packages,
            'last_check_urgent': self._last_check_urgent,
            'first_boot_countdown': self._first_boot_countdown,
            'is_urgent': 1 if self._is_urgent else 0,
            'is_scheduled': 1 if self._is_scheduled else 0,
            'is_shutdown': 1 if self._is_shutdown else 0,
            'notifications_muted': 1 if self._notifications_muted else 0
        }

        with open(self._status_file, 'w') as status_file:
            json.dump(data, status_file, indent=4)

        # When installing updates, configure the recovery stategy for the next
        # boot in case of power failure. This sets a different splash screen
        # during bootup and configures the system to autologin as the user in
        # order to start the Updater immediately. See kano-ui-autostart.
        if self.is_recovery_needed():
            enable_system_recovery_flow()
        else:
            cancel_system_recovery_flow()
Beispiel #38
0
    def start(self, phase_name):
        """
            Starts a certain phase of the progress.

            This doesn't need to be called for steps.

            :param phase_name: A string that identifies the current phase.
            :type phase_name: str
        """
        phase = self._get_phase_by_name(phase_name)

        self._current_phase_idx = self._phases.index(phase)

        log = "global({}%) local({}%): " \
              "Starting '{}' ({}) [main phase '{}' ({})]".format(
                  phase.global_percent,
                  phase.percent,
                  phase.label.encode('utf-8'),
                  phase.name,
                  phase.get_main_phase().label.encode('utf-8'),
                  phase.get_main_phase().name
              )
        logger.debug(log)

        # Calculate current progres and emitt an event
        self._change(phase, phase.label)
    def _get_next_prompt(self):
        '''
        Jump to the next available question that has not been answered yet
        '''

        next_prompt = None
        iterations = 0
        try:
            while iterations < len(self.prompts):
                # Jump to the next prompt in the circular queue
                self.current_prompt_idx += 1
                if self.current_prompt_idx == len(self.prompts):
                    self.current_prompt_idx = 0

                next_prompt = self.prompts[self.current_prompt_idx]['text']

                # prompt has not been answered yet, take it!
                if not self._cache_is_prompt_responded(next_prompt):
                    return next_prompt

                iterations += 1

            # No more questions to answer
            next_prompt = None
        except Exception as e:
            logger.debug("Exception in _get_next_prompt: {}".format(str(e)))

        return next_prompt
Beispiel #40
0
    def start(self, phase_name):
        """
            Starts a certain phase of the progress.

            This doesn't need to be called for steps.

            :param phase_name: A string that identifies the current phase.
            :type phase_name: str
        """
        phase = self._get_phase_by_name(phase_name)

        self._current_phase_idx = self._phases.index(phase)

        log = "global({}%) local({}%): " \
              "Starting '{}' ({}) [main phase '{}' ({})]".format(
                  phase.global_percent,
                  phase.percent,
                  phase.label.encode('utf-8'),
                  phase.name,
                  phase.get_main_phase().label.encode('utf-8'),
                  phase.get_main_phase().name
              )
        logger.debug(log)

        # Calculate current progres and emitt an event
        self._change(phase, phase.label)
Beispiel #41
0
def _connect_thread_(wiface, network_name, passphrase, encryption,
                     thread_finish_cb):
    '''
    This function runs in a thread so we can run a spinner alongside.

    :param wiface: wifi card id
    :param network_name: network id
    :param passphrase: password entered by user
    :param encryption: type of encryption
    :param disable_widget_cb: the callback for any widgets that need to be
                              disabled
    :param thread_finish_cb: the callback to be run when the thread is finished
    '''

    rc = connect(wiface, network_name, encryption, passphrase)

    # save the connection in cache so it reconnects on next system boot
    wificache = KwifiCache()
    if not rc:
        wificache.save(network_name, encryption, passphrase)
    else:
        wificache.empty()

    logger.debug("Connecting to {} {} {}. Return code: {}".format(
        network_name, encryption, passphrase, rc))

    GObject.idle_add(thread_finish_cb, rc)
Beispiel #42
0
def _apply_co_packages(dest_dir):
    import tarfile

    co_index = _get_co_assets()

    for order in sorted(co_index.iterkeys()):
        tar_file = co_index[order]
        # First try to open the file
        try:
            tarball = tarfile.open(tar_file)
        except (IOError, OSError) as exc:
            err_msg = "Couldn't open file '{}', [{}]".format(tar_file, exc)
            logger.error(err_msg)
            continue
        except tarfile.ReadError as exc:
            err_msg = 'Error parsing tarfile "{}", [{}]'.format(tar_file, exc)
            logger.error(err_msg)
            continue
        else:
            # Now try to extract the files one by one
            with tarball:
                for tarred_file in tarball:
                    try:
                        tarball.extract(tarred_file, path=dest_dir)
                    except IOError as exc:
                        # This is to guard against weird tar behaviour when
                        # trying to ovewrite symlinks
                        bad_filename = os.path.join(dest_dir, tarred_file.name)
                        if os.path.islink(bad_filename):
                            logger.debug(
                                'Remove link and ovewrite "{}"'.format(
                                    bad_filename)
                            )
                            os.remove(os.path.join(dest_dir, tarred_file.name))
                            tarball.extract(tarred_file, path=dest_dir)
Beispiel #43
0
def add_safesearch_blacklist(hosts):
    '''
    Prevents surfing to generic search engine sites by adding them to the blacklist
    '''

    # import pycountry here as it takes a long time to import. 
    import pycountry
    logger.debug("Applying safesearch settings")
    # Block search sites
    search_sites = [
        'google.com',
        'bing.com',
        'search.yahoo.com',
        'uk.search.yahoo.com',
        'ask.com',
        'uk.ask.com',  # pycountry does not return "uk", but "gb"
        'search.aol.com',
        'aolsearch.com',
        'search.com',
        'uk.search.com',
        'wow.com',
        'webcrawler.com',
        'zoo.com',  # Webcrawler sometimes redirects to zoo.com
        'mywebsearch.com',
        'home.mywebsearch.com',
        'infospace.com',
        'info.com',
        'duckduckgo.com',
        'blekko.com',
        'contenko.com',
        'dogpile.com',
        'alhea.com',
        'uk.alhea.com']

    # Blacklist major search engines
    for site in search_sites:
        add_blacklist_host(hosts, site)

    # Add subdomains only to those search engines that need it
    for country in pycountry.countries:

        add_blacklist_host(hosts, 'google.{}'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.ask.com'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.search.yahoo.com'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, 'search.yahoo.{}'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.search.com'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.wow.com'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.webcrawler.com'.format(country.alpha2.lower()))

        # Some search engines are redirecting to zoo.com and possibly [country]
        add_blacklist_host(hosts, 'zoo.{}'.format(country.alpha2.lower()))

        add_blacklist_host(hosts, '{}.info.com'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.alhea.com'.format(country.alpha2.lower()))


    for subdomain in second_level_domains:
        add_blacklist_host(hosts, 'google.{}'.format(subdomain))

    return hosts
Beispiel #44
0
def enable_system_recovery_flow():
    """Configure the system to start in recovery mode on next bootup.

    This sets up a few things:

    1. Replaces the normal bootup splash animation with another for recovery.
    2. Configures LightDM autologin for multi-user systems since the Updater
       runs under the user.

    Returns:
        bool - Whether the operation was successful
    """
    logger.debug('Configuring recovery stategy for next boot')
    successful = True

    # Set the recovery bootup splash and replace normal bootup one.
    set_splash_interrupted()

    # Configure the system to autologin for multi-user systems. This is due
    # to the Updater process running under the user.
    try:
        user = get_user_unsudoed()
        if user:
            # TODO: Create a single function for these in kano_init.
            enable_console_autologin(user)
            set_ldm_autologin(user)
            enable_ldm_autostart()
        else:
            successful = False
    except:
        logger.error('Could not configure autologin for update recovery!')
        successful = False

    return successful
Beispiel #45
0
 def env_select(self, env_name):
     """ Set an environment for the background. If the environment given is
     not unlocked a different unlocked one is selected in random
     :param env_name: Environment name
     :returns: True iff the environment exists (is available)
     :rtype: Boolean
     """
     env_inst = self._sel_char_layer().item(env_name)
     if env_inst.category().get_id() == self.env_label:
         if not env_inst.is_unlocked():
             logger.warn(
                 "Environment {} is locked, replacing with random".format(
                     env_name))
             # Select randomly among the unlocked environments
             self._sel_env = random.choice(
                 [env for env in env_inst.category().items()
                     if env.is_unlocked()])
         else:
             self._sel_env = env_inst
         logger.debug(
             "Selected Environment: {}".format(self._sel_env.get_id()))
         return True
     else:
         logger.error(
             "Environment {} is not in the available env list".format(
                 env_name))
         return False
Beispiel #46
0
def compare_and_set_full_range(edid,
                               status,
                               model,
                               dry_run=False,
                               force=False):
    """
    Returns True if full range is changed

    TODO: What is this for?
    """
    if status['full_range'] == edid['target_full_range'] and not force:
        logger.debug('Config full range change not needed.')
        return False

    hdmi_pixel_encoding = 2 if edid['target_full_range'] else 0

    logger.info(
        'Config full range change needed. Setting hdmi_pixel_encoding to {}'.
        format(hdmi_pixel_encoding))
    if dry_run and not force:
        return True

    set_config_value('hdmi_pixel_encoding',
                     hdmi_pixel_encoding,
                     config_filter=Filter.get_edid_filter(model))
    return True
Beispiel #47
0
def install_urgent(progress, status):
    progress.split(
        Phase(
            'installing-urgent',
            _("Installing Hotfix"),
            100,
            is_main=True
        )
    )
    logger.debug("Installing urgent hotfix")
    packages_to_update = apt_handle.packages_to_be_upgraded()
    progress.start('installing-urgent')
    install_deb_packages(progress, priority=Priority.URGENT)
    status.is_urgent = False
    try:
        from kano_profile.tracker import track_data
        track_data('updated_hotfix', {
            'packages': packages_to_update
        })
        logger.debug("Tracking Data: '{}'".format(packages_to_update))
    except ImportError as imp_exc:
        logger.error("Couldn't track hotfix installation, failed to import " \
                     "tracking module: [{}]".format(imp_exc))
    except Exception:
        pass
Beispiel #48
0
def add_safesearch_blacklist(hosts):
    '''
    Prevents surfing to generic search engine sites by adding them to the blacklist
    '''

    # import pycountry here as it takes a long time to import.
    import pycountry
    logger.debug("Applying safesearch settings")
    # Block search sites
    search_sites = [
        'google.com',
        'bing.com',
        'search.yahoo.com',
        'uk.search.yahoo.com',
        'ask.com',
        'uk.ask.com',  # pycountry does not return "uk", but "gb"
        'search.aol.com',
        'aolsearch.com',
        'search.com',
        'uk.search.com',
        'wow.com',
        'webcrawler.com',
        'zoo.com',  # Webcrawler sometimes redirects to zoo.com
        'mywebsearch.com',
        'home.mywebsearch.com',
        'infospace.com',
        'info.com',
        'duckduckgo.com',
        'blekko.com',
        'contenko.com',
        'dogpile.com',
        'alhea.com',
        'uk.alhea.com']

    # Blacklist major search engines
    for site in search_sites:
        add_blacklist_host(hosts, site)

    # Add subdomains only to those search engines that need it
    for country in pycountry.countries:

        add_blacklist_host(hosts, 'google.{}'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.ask.com'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.search.yahoo.com'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, 'search.yahoo.{}'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.search.com'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.wow.com'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.webcrawler.com'.format(country.alpha2.lower()))

        # Some search engines are redirecting to zoo.com and possibly [country]
        add_blacklist_host(hosts, 'zoo.{}'.format(country.alpha2.lower()))

        add_blacklist_host(hosts, '{}.info.com'.format(country.alpha2.lower()))
        add_blacklist_host(hosts, '{}.alhea.com'.format(country.alpha2.lower()))

    for subdomain in second_level_domains:
        add_blacklist_host(hosts, 'google.{}'.format(subdomain))

    return hosts
Beispiel #49
0
 def _create_checkbutton_input(self, values, maximum, minimum):
     logger.debug(
         "checkbuttons being created with values {}, minimum {}, maximum".
         format(values, minimum, maximum))
     widget = CheckInput(values, maximum, minimum)
     widget.connect('min-not-selected', self._set_send_insensitive)
     widget.connect('min-selected', self._set_send_sensitive)
     return widget
Beispiel #50
0
    def first_boot_countdown(self, value):
        if not isinstance(value, int):
            msg = "'first_boot_countdown' must be an Unix timestamp (int)."
            raise UpdaterStatusError(msg)

        logger.debug(
            "Setting the status' first_boot_countdown to: {}".format(value))
        self._first_boot_countdown = value
Beispiel #51
0
    def notifications_muted(self, value):
        if not isinstance(value, bool):
            msg = "'notifications_muted' must be a boolean value."
            raise UpdaterStatusError(msg)

        logger.debug("Setting the status' notifications_muted to: {}"
                     .format(value))
        self._notifications_muted = value
Beispiel #52
0
    def launch_registration(self):
        try:
            p = subprocess.Popen(['/usr/bin/kano-login', '-r'])
            p.wait()
        except Exception:
            logger.debug("kano-login failed to launch")

        GLib.idle_add(self.next_stage)
Beispiel #53
0
    def notifications_muted(self, value):
        if not isinstance(value, bool):
            msg = "'notifications_muted' must be a boolean value."
            raise UpdaterStatusError(msg)

        logger.debug(
            "Setting the status' notifications_muted to: {}".format(value))
        self._notifications_muted = value
Beispiel #54
0
    def _launch_login_process(self):
        try:
            p = subprocess.Popen(['/usr/bin/kano-login', '-r'])
            p.wait()
        except Exception:
            logger.debug("kano-login failed to launch")

        GLib.idle_add(self._finish_login_thread)
    def get_instance():
        """Get an instance to the singleton class."""

        logger.debug("Getting RCState instance")
        if not RCState._singleton_instance:
            RCState()

        return RCState._singleton_instance
    def get_instance():
        """Get an instance to the singleton class."""

        logger.debug("Getting RCState instance")
        if not RCState._singleton_instance:
            RCState()

        return RCState._singleton_instance
Beispiel #57
0
def save_app_state_variable_with_dialog(app_name, variable, value):
    logger.debug('save_app_state_variable_with_dialog {} {} {}'.format(
        app_name, variable, value))

    data = load_app_state(app_name)
    data[variable] = value

    save_app_state_with_dialog(app_name, data)