Example #1
0
def compare_and_set_optimal_resolution(edid, status, supported_modes, dry_run=False, force=False):
    """
    Check the current resolution and set an optimal one if needed.

    Args:
        edid - dict as returned by the function get_edid()
        status - dict as returned by the function get_status()
        supported_modes - list as returned by the function list_supported_modes()
        dry_run - bool run the function, but do not apply any changes
        force - bool reconfigure settings even when the status says it's not needed

    Returns:
        changes - bool whether or not changes were applied
    """
    optimal_mode = get_optimal_resolution_mode(edid, supported_modes)

    if status['group'] == optimal_mode['group'] and \
       status['mode'] == optimal_mode['mode'] and \
       not force:
        logger.info('Resolution mode/group change not needed.')
        return False

    logger.info(
        'Resolution change needed. Setting hdmi_group to {} and hdmi_mode to {}.'
        .format(optimal_mode['group'], optimal_mode['mode'])
    )
    if dry_run and not force:
        return True

    # Apply the hdmi_group and hdmi_mode config options for this screen (with filter).
    set_hdmi_mode(optimal_mode['group'], optimal_mode['mode'])
    return True
    def on_drag_delete(self, *_):
        """ Triggered when the drag action is completed successfully """

        logger.info("Drag deleted")
        self.eventbox.destroy()
        self.label1.destroy()
        self.instruction.destroy()
Example #3
0
    def run(self, progress):
        log = "Running the {}-update scripts...".format(self._type)
        logger.info(log)

        current_version = self._old_version
        target_version = get_target_version()

        while current_version < target_version:
            step_found = False
            for (from_version, to_version), func in self._scenarios.iteritems():
                if current_version == from_version:
                    msg = "Running {}-update from {} to {}.".format(
                        self._type,
                        from_version,
                        to_version
                    )
                    logger.info(msg)
                    func(progress)
                    current_version = to_version
                    step_found = True
                    break

            if not step_found:
                msg = "{}-update step missing".format(self._type)
                update_failed(msg)
                raise Exception(msg)

        self._finalise()
Example #4
0
    def last_check(self, value):
        if not isinstance(value, int):
            msg = "'last_check' must be an Unix timestamp (int)."
            raise UpdaterStatusError(msg)

        logger.info("Setting the status' last_check to: {}".format(value))
        self._last_check = value
Example #5
0
    def run(self):
        log = "Running the {}-update scripts...".format(self._type)
        logger.info(log)

        current_v = str(self._old)
        while current_v < str(TARGET_VERSION):
            step_found = False
            for (from_v, to_v), func in self._scenarios.iteritems():
                if current_v == from_v:
                    msg = "Running {}-update from {} to {}.".format(
                        self._type,
                        from_v,
                        to_v
                    )
                    logger.info(msg)
                    func()
                    current_v = to_v
                    step_found = True
                    break

            if not step_found:
                msg = "{}-update step missing".format(self._type)
                update_failed(msg)
                raise Exception(msg)

        self._finalise()
Example #6
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.info(log)

        # Calculate current progress and emit an event
        monitor_heartbeat.heartbeat()
        self._change(phase, phase.label)
Example #7
0
def block_and_sync():
    """ Sync the local profile data with kano_world and block until finished
    """
    logger.info("block and sync profile")
    cmd = '{bin_dir}/kano-sync --sync -s --skip-kdesk'.format(bin_dir=bin_dir)
    pr = run_bg(cmd)
    pr.wait()
Example #8
0
def launch(data):
    (title, attachment_path, app, attachment_name, folder, item_id) = data
    msg = 'Downloaded share: {}'.format(title)
    logger.info(msg)

    launch_project(app, attachment_name, folder)
    _report_share_opened(item_id)
Example #9
0
def _copy_package_assets():
    # Use abs paths for both src and dest for subsequent replacements to work
    src_dir = os.path.abspath(_get_package_static_dir())
    dest_dir = os.path.abspath(STATIC_ASSET_DIR)

    # First Clear this cache
    for existing_file in os.listdir(dest_dir):
        cur_file = os.path.abspath(os.path.join(dest_dir, existing_file))
        if os.path.islink(cur_file):
            os.unlink(cur_file)
        else:
            if os.path.isdir(cur_file):
                shutil.rmtree(cur_file)
            else:
                os.remove(cur_file)

    # Now copy the static assets
    for root_d, dirs, files in os.walk(src_dir):
        # Firstly create the dirs
        dest_root = root_d.replace(src_dir, dest_dir)
        for dir_n in dirs:
            new_dir = os.path.join(dest_root, dir_n)
            os.mkdir(new_dir)
        # Now deal with the files
        for file_n in files:
            src_file = os.path.join(root_d, file_n)
            new_file = os.path.join(dest_root, file_n)
            shutil.copy(src_file, new_file)
    logger.info('Successfully copied over static assets')
Example #10
0
    def run(self):
        log = "Running the {}-update scripts...".format(self._type)
        logger.info(log)

        current_version = self._old_version
        target_version = TARGET_VERSION

        while current_version < target_version:
            step_found = False
            for (from_version,
                 to_version), func in self._scenarios.iteritems():
                if current_version == from_version:
                    msg = "Running {}-update from {} to {}.".format(
                        self._type, from_version, to_version)
                    logger.info(msg)
                    func()
                    current_version = to_version
                    step_found = True
                    break

            if not step_found:
                msg = "{}-update step missing".format(self._type)
                update_failed(msg)
                raise Exception(msg)

        self._finalise()
Example #11
0
def set_ssh_enabled(enabled, with_logging=True):
    """
    Sets the Dropbear SSH client between disabled and enabled.
    Requires sudo.

    Args:
        enabled - bool to enable & start or disabled & stop the SSH service
        with_logging - bool to control whether or not the operation logs messages
    Returns:
        successful - bool whether the operation succeeded or not
    """
    if enabled:
        rc = os.system("systemctl enable dropbear.service")
        rc = rc or os.system("systemctl start dropbear.service")

        if rc == 0 and with_logging:
            logger.info('set_ssh_enabled: Enabled and started Dropbear SSH')
        elif rc != 0 and with_logging:
            logger.error('set_ssh_enabled: Failed to enable and start Dropbear SSH')

    else:
        rc = os.system("systemctl disable dropbear.service")
        rc = rc or os.system("systemctl stop dropbear.service")

        if rc == 0 and with_logging:
            logger.info('set_ssh_enabled: Disabled and stopped Dropbear SSH')
        elif rc != 0 and with_logging:
            logger.error('set_ssh_enabled: Failed to disable and stop Dropbear SSH')

    return (rc == 0)
Example #12
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.info(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.info(msg)

    status.notifications_muted = False

    if not dry_run:
        status.save()

    return old_status
Example #13
0
def compare_and_set_optimal_resolution(edid, status, supported_modes, dry_run=False, force=False):
    """
    Check the current resolution and set an optimal one if needed.

    Args:
        edid - dict as returned by the function get_edid()
        status - dict as returned by the function get_status()
        supported_modes - list as returned by the function list_supported_modes()
        dry_run - bool run the function, but do not apply any changes
        force - bool reconfigure settings even when the status says it's not needed

    Returns:
        changes - bool whether or not changes were applied
    """
    optimal_mode = get_optimal_resolution_mode(edid, supported_modes)

    if status['group'] == optimal_mode['group'] and \
       status['mode'] == optimal_mode['mode'] and \
       not force:
        logger.info('Resolution mode/group change not needed.')
        return False

    logger.info(
        'Resolution change needed. Setting hdmi_group to {} and hdmi_mode to {}.'
        .format(optimal_mode['group'], optimal_mode['mode'])
    )
    if dry_run and not force:
        return True

    # Apply the hdmi_group and hdmi_mode config options for this screen (with filter).
    set_hdmi_mode(optimal_mode['group'], optimal_mode['mode'])
    return True
Example #14
0
def _copy_package_assets():
    # Use abs paths for both src and dest for subsequent replacements to work
    src_dir = os.path.abspath(_get_package_static_dir())
    dest_dir = os.path.abspath(STATIC_ASSET_DIR)

    # First Clear this cache
    for existing_file in os.listdir(dest_dir):
        cur_file = os.path.abspath(os.path.join(dest_dir, existing_file))
        if os.path.islink(cur_file):
            os.unlink(cur_file)
        else:
            if os.path.isdir(cur_file):
                shutil.rmtree(cur_file)
            else:
                os.remove(cur_file)

    # Now copy the static assets
    for root_d, dirs, files in os.walk(src_dir):
        # Firstly create the dirs
        dest_root = root_d.replace(src_dir, dest_dir)
        for dir_n in dirs:
            new_dir = os.path.join(dest_root, dir_n)
            os.mkdir(new_dir)
        # Now deal with the files
        for file_n in files:
            src_file = os.path.join(root_d, file_n)
            new_file = os.path.join(dest_root, file_n)
            shutil.copy(src_file, new_file)
    logger.info('Successfully copied over static assets')
Example #15
0
def install_urgent(progress, status):
    progress.split(
        Phase(
            'installing-urgent',
            _("Installing Hotfix"),
            100,
            is_main=True
        )
    )
    logger.info("Installing urgent hotfix")
    apt_handle = AptWrapper.get_instance()
    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.info("Tracking Data: '{}'".format(packages_to_update))
    except ImportError as imp_exc:
        logger.error("Couldn't track hotfix installation, failed to import "
                     "tracking module", exception=imp_exc)
    except Exception:
        pass

    return True
Example #16
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
Example #17
0
def change_overclock_value(config, board_name=None):
    board = get_board_props(board_name=board_name)

    if not board:
        logger.error("Could not get overclocking settings for board")
        return

    try:
        values = board.CLOCKING['values'][config]
    except KeyError:
        logger.error(
            "kano-settings: set_overclock: SetOverclock: set_overclock(): " \
            "was called with an invalid overclock setting={}"
            .format(config)
        )
        return

    logger.info(
        u"set_overclock / apply_changes: " \
        "config:{} arm_freq:{arm_freq} " \
        "core_freq:{core_freq} " \
        "sdram_freq:{sdram_freq} " \
        "over_voltage:{over_voltage}"
        .format(config, **values)
    )

    # Apply changes
    for val in values:
        set_config_value(val, values[val])

    # Update config
    set_setting('Overclocking', config)
Example #18
0
    def fix_broken(self, progress):
        progress.split(
            Phase('dpkg-clean',
                  _("Cleaning dpkg journal")),
            Phase('fix-broken',
                  _("Fixing broken packages"))
        )
        if self._cache.dpkg_journal_dirty:
            progress.start('dpkg-clean')
            logger.info("Cleaning dpkg journal")
            run_cmd_log("dpkg --configure -a")

            self._cache.clear()
            self._cache.open()

        progress.start('fix-broken')

        # Naughty but don't want to re-initialise
        if self._cache._depcache.broken_count:
            try:
                self._cache._depcache.fix_broken()
            except SystemError as e:
                logger.error('Error attempting to fix broken pkgs', exception=e)

            self._cache.clear()
            self._cache.open()
Example #19
0
    def set_state_writable(self):
        if self.state == 0:
            self.raise_state_to_locked()

        if self.state == 1:

            temp = tempfile.NamedTemporaryFile(mode='w',
                                               delete=False,
                                               prefix="config_tmp_",
                                               dir=self.dir)
            self.temp_path = temp.name
            logger.info(
                "Enable modifications in config transaction: {}".format(
                    self.temp_path))
            temp.close()
            if os.path.exists(self.path):
                shutil.copy2(self.path, self.temp_path)
            else:
                logger.warn(
                    "Could not make a copy of config.txt, using default")
                shutil.copy2(default_config_path, self.temp_path)

            # create temporary
            self.temp_config = BootConfig(self.temp_path)

        self.state = 2
Example #20
0
    def set_comment(self, name, value, config_filter=Filter.ALL):
        '''
        Adds a custom Kano comment key to the config file
        in the form: ### my_comment_name: value
        '''
        lines = read_file_contents_as_lines(self.path)
        if not lines:
            return

        logger.info("writing comment to {} {} {}".format(
            self.path, name, value))

        comment_str_full = '### {}: {}'.format(name, value)
        comment_str_name = '### {}'.format(name)

        with open_locked(self.path, 'w') as boot_config_file:
            boot_config_file.write(comment_str_full + '\n')

            for line in lines:
                if comment_str_name in line:
                    continue

                boot_config_file.write(line + '\n')

            # make sure changes go to disk
            boot_config_file.flush()
            os.fsync(boot_config_file.fileno())
def change_overclock_value(config, is_pi2):
    try:
        values = CLOCK_MODES[is_pi2]['values'][config]
    except KeyError:
        logger.error(
            'kano-settings: set_overclock: SetOverclock: set_overclock(): '
            'was called with an invalid overclock setting={}'
            .format(config)
        )
        return

    logger.info(
        'set_overclock / apply_changes: '
        'config:{} arm_freq:{arm_freq} '
        'core_freq:{core_freq} '
        'sdram_freq:{sdram_freq} '
        'over_voltage:{over_voltage}'
        .format(config, **values)
    )

    # Apply changes
    for val in values:
        set_config_value(val, values[val])

    # Update config
    set_setting("Overclocking", config)
Example #22
0
 def beta_134_to_beta_200(self):
     if not is_installed('kano-character-cli'):
         logger.info("kano-character-cli not installed,"
                     " attempt to install kano-profile")
         install('kano-profile')
     run_cmd_log(
         'kano-character-cli -c "judoka" "Hair_Black" "Skin_Orange" -s')
Example #23
0
def get_avatar(sync=True):
    """ Returns the information about the avatar for the specific profile. If
    the optional variable is set, there will be an attempt to sync with kano
    world to ensure that the profile is up to date.
    If no info is available about the avatar, a default set is being returned
    :param sync: (Optional) Set to True to sync before providing the values
                 for the avatar
    :type sync: Boolean
    :returns: tuple of the form (char, items) or None in case of version error
    :rtype: tuple with two items
    """
    profile = load_profile()
    if 'version' in profile and profile['version'] == 2 and \
            'avatar' in profile:
        subcat, item = profile['avatar']

        if subcat == 'Judoka_Base':
            subcat = 'judoka'
        for cat in category_conversion:
            if cat in item:
                item[category_conversion[cat]] = item.pop(cat)
    else:
        # Attempt to sync to retrieve the avatar from world
        if sync:
            block_and_sync()
            recreate_char(block=True)
            subcat, item = get_avatar(sync=False)
        else:
            # Provide a default set
            logger.info("Avatar not found in profile, returning default")
            subcat, item = get_default_avatar()
    return subcat, item
Example #24
0
def get_avatar(sync=True):
    """ Returns the information about the avatar for the specific profile. If
    the optional variable is set, there will be an attempt to sync with kano
    world to ensure that the profile is up to date.
    If no info is available about the avatar, a default set is being returned
    :param sync: (Optional) Set to True to sync before providing the values
                 for the avatar
    :type sync: Boolean
    :returns: tuple of the form (char, items) or None in case of version error
    :rtype: tuple with two items
    """
    profile = load_profile()
    if 'version' in profile and profile['version'] == 2 and \
            'avatar' in profile:
        subcat, item = profile['avatar']

        if subcat == 'Judoka_Base':
            subcat = 'judoka'
        for cat in category_conversion:
            if cat in item:
                item[category_conversion[cat]] = item.pop(cat)
    else:
        # Attempt to sync to retrieve the avatar from world
        if sync:
            block_and_sync()
            recreate_char(block=True)
            subcat, item = get_avatar(sync=False)
        else:
            # Provide a default set
            logger.info('Avatar not found in profile, returning default')
            subcat, item = get_default_avatar()
    return subcat, item
Example #25
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.info(log)

        # Calculate current progress and emit an event
        monitor_heartbeat.heartbeat()
        self._change(phase, phase.label)
Example #26
0
    def last_check(self, value):
        if not isinstance(value, int):
            msg = "'last_check' must be an Unix timestamp (int)."
            raise UpdaterStatusError(msg)

        logger.info("Setting the status' last_check to: {}".format(value))
        self._last_check = value
Example #27
0
    def is_shutdown(self, value):
        if not isinstance(value, bool):
            msg = "'is_shutdown' must be a boolean value."
            raise UpdaterStatusError(msg)

        logger.info("Setting the status' is_shutdown to: {}".format(value))
        self._is_shutdown = value
Example #28
0
    def pair(self, *dummy_args, **dummy_kwargs):
        def done_pairing():
            self._set_paired_button_state()
            self.emit('done-pairing')

        @queue_cb(callback=done_pairing, gtk=True)
        def do_pair():
            if not self.device.fuse():
                GObject.idle_add(self.error, _("Pairing failed"))

        @queue_cb(callback=done_pairing, gtk=True)
        def do_unpair():
            if not self.device.unfuse():
                GObject.idle_add(self.error, _("Unpairing failed"))

        self.emit('pairing')

        if self.device.connected:
            pair_fn = do_unpair
            logger.info("Unpairing {}".format(self.device))
        else:
            pair_fn = do_pair
            logger.info("Pairing {}".format(self.device))

        pair_thr = threading.Thread(target=pair_fn)
        pair_thr.start()
Example #29
0
def block_and_sync():
    """ Sync the local profile data with kano_world and block until finished
    """
    logger.info('block and sync profile')
    cmd = '{bin_dir}/kano-sync --sync -s --skip-kdesk'.format(bin_dir=bin_dir)
    pr = run_bg(cmd)
    pr.wait()
Example #30
0
    def is_shutdown(self, value):
        if not isinstance(value, bool):
            msg = "'is_shutdown' must be a boolean value."
            raise UpdaterStatusError(msg)

        logger.info("Setting the status' is_shutdown to: {}".format(value))
        self._is_shutdown = value
Example #31
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
    def on_drag_end(self, *_):
        """ Triggered when the drag action is terminated """

        logger.info("Drag ended")
        self.eventbox.remove(self.bg_image)
        self.eventbox.add(self.image)
        self.eventbox.show_all()
    def pair(self, *dummy_args, **dummy_kwargs):
        def done_pairing():
            self._set_paired_button_state()
            self.emit('done-pairing')

        @queue_cb(callback=done_pairing, gtk=True)
        def do_pair():
            if not self.device.fuse():
                GObject.idle_add(self.error, _("Pairing failed"))

        @queue_cb(callback=done_pairing, gtk=True)
        def do_unpair():
            if not self.device.unfuse():
                GObject.idle_add(self.error, _("Unpairing failed"))

        self.emit('pairing')

        if self.device.connected:
            pair_fn = do_unpair
            logger.info("Unpairing {}".format(self.device))
        else:
            pair_fn = do_pair
            logger.info("Pairing {}".format(self.device))

        pair_thr = threading.Thread(target=pair_fn)
        pair_thr.start()
Example #34
0
def set_ssh_enabled(enabled, with_logging=True):
    """
    Sets the Dropbear SSH client between disabled and enabled.
    Requires sudo.

    Args:
        enabled - bool to enable & start or disabled & stop the SSH service
        with_logging - bool to control whether or not the operation logs messages
    Returns:
        successful - bool whether the operation succeeded or not
    """
    if enabled:
        rc = os.system("systemctl enable dropbear.service")
        rc = rc or os.system("systemctl start dropbear.service")

        if rc == 0 and with_logging:
            logger.info('set_ssh_enabled: Enabled and started Dropbear SSH')
        elif rc != 0 and with_logging:
            logger.error('set_ssh_enabled: Failed to enable and start Dropbear SSH')

    else:
        rc = os.system("systemctl disable dropbear.service")
        rc = rc or os.system("systemctl stop dropbear.service")

        if rc == 0 and with_logging:
            logger.info('set_ssh_enabled: Disabled and stopped Dropbear SSH')
        elif rc != 0 and with_logging:
            logger.error('set_ssh_enabled: Failed to disable and stop Dropbear SSH')

    return (rc == 0)
    def set_comment(self, name, value, config_filter=Filter.ALL):
        '''
        Adds a custom Kano comment key to the config file
        in the form: ### my_comment_name: value
        '''
        lines = read_file_contents_as_lines(self.path)
        if not lines:
            return

        logger.info("writing comment to {} {} {}".format(self.path, name, value))

        comment_str_full = '### {}: {}'.format(name, value)
        comment_str_name = '### {}'.format(name)

        with open_locked(self.path, 'w') as boot_config_file:
            boot_config_file.write(comment_str_full + '\n')

            for line in lines:
                if comment_str_name in line:
                    continue

                boot_config_file.write(line + '\n')

            # make sure changes go to disk
            boot_config_file.flush()
            os.fsync(boot_config_file.fileno())
Example #36
0
    def state(self, value):
        if value not in self._valid_states:
            msg = "'{}' is not a valid state".format(value)
            logger.warn(msg)
            raise UpdaterStatusError(msg)

        logger.info("Setting the status' state to: {}".format(value))
        self._state = value
        def _do_populate(devices):
            if not devices:
                logger.info("No devices")
                GObject.idle_add(self.set_no_devices_nearby)

            for idx, device in enumerate(devices):
                logger.info("Adding device {}".format(device))
                GObject.idle_add(self.add_device, device, idx)
Example #38
0
    def state(self, value):
        if value not in self._valid_states:
            msg = "'{}' is not a valid state".format(value)
            logger.warn(msg)
            raise UpdaterStatusError(msg)

        logger.info("Setting the status' state to: {}".format(value))
        self._state = value
Example #39
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.info("Setting the status' first_boot_countdown to: {}"
                     .format(value))
        self._first_boot_countdown = value
Example #40
0
    def notifications_muted(self, value):
        if not isinstance(value, bool):
            msg = "'notifications_muted' must be a boolean value."
            raise UpdaterStatusError(msg)

        logger.info("Setting the status' notifications_muted to: {}"
                     .format(value))
        self._notifications_muted = value
Example #41
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.info(
            "Setting the status' first_boot_countdown to: {}".format(value))
        self._first_boot_countdown = value
Example #42
0
    def notifications_muted(self, value):
        if not isinstance(value, bool):
            msg = "'notifications_muted' must be a boolean value."
            raise UpdaterStatusError(msg)

        logger.info(
            "Setting the status' notifications_muted to: {}".format(value))
        self._notifications_muted = value
Example #43
0
        def _do_populate(devices):
            if not devices:
                logger.info("No devices")
                GObject.idle_add(self.set_no_devices_nearby)

            for idx, device in enumerate(devices):
                logger.info("Adding device {}".format(device))
                GObject.idle_add(self.add_device, device, idx)
Example #44
0
 def updatable_independent_packages(self, value):
     if not isinstance(value, list) and all(
         [isinstance(p, str) for p in value]):
         msg = "'ind_pkg' must be a list of package names"
         raise UpdaterStatusError(msg)
     logger.info(
         "Setting the status' updatable_independent_packages to: {}".format(
             value))
     self._updatable_independent_packages = value
Example #45
0
 def _mark_all_for_update(self, priority=Priority.NONE):
     if priority < Priority.URGENT:
         self._cache.upgrade(dist_upgrade=True)
     else:
         for pkg in self.upgradable_packages(priority=priority):
             logger.info("Marking {} ({}) for upgrade".format(
                 pkg.shortname, pkg.candidate.version
             ))
             pkg.mark_upgrade()
def get_setting(variable):

    try:
        value = read_json(settings_file)[variable]
    except Exception:
        if variable not in DEFAULTS:
            logger.info("Defaults not found for variable: {}".format(variable))
        value = DEFAULTS[variable]
    return value
Example #47
0
def get_setting(variable):

    try:
        value = read_json(settings_file)[variable]
    except Exception:
        if variable not in DEFAULTS:
            logger.info("Defaults not found for variable: {}".format(variable))
        value = DEFAULTS[variable]
    return value
Example #48
0
def launch_project(app, filename, data_dir):
    logger.info('launch_project: {} {} {}'.format(app, filename, data_dir))

    app_profiles = read_json(app_profiles_file)

    fullpath = os.path.join(data_dir, filename)
    cmd = app_profiles[app]['cmd'].format(fullpath=fullpath, filename=filename)
    _, _, rc = run_print_output_error(cmd)
    return rc
Example #49
0
def save_app_state_with_dialog(app_name, data):
    logger.debug('save_app_state_with_dialog {}'.format(app_name))

    old_level, _, old_xp = calculate_kano_level()
    old_badges = calculate_badges()

    save_app_state(app_name, data)

    new_level, _, new_xp = calculate_kano_level()
    new_badges = calculate_badges()

    # TODO: This function needs a bit of refactoring in the future
    # The notifications no longer need to be concatenated to a string

    # new level
    new_level_str = ''
    if old_level != new_level:
        new_level_str = 'level:{}'.format(new_level)

        # A new level has been reached, update the desktop profile icon
        if os.path.exists('/usr/bin/kdesk') and not is_running('kano-sync'):
            logger.info('refreshing kdesk due to new experience level')
            run_bg('kdesk -a profile')

    # new items
    new_items_str = ''
    badge_changes = compare_badges_dict(old_badges, new_badges)
    if badge_changes:
        for category, subcats in badge_changes.iteritems():
            for subcat, items in subcats.iteritems():
                for item, rules in items.iteritems():
                    new_items_str += ' {}:{}:{}'.format(category, subcat, item)

    # Check if XP has changed, if so play sound in the backgrond
    if old_xp != new_xp:
        sound_cmd = 'aplay /usr/share/kano-media/sounds/kano_xp.wav > /dev/null 2>&1 &'
        run_bg(sound_cmd)

    if not new_level_str and not new_items_str:
        return

    if is_gui():
        fifo = open(
            os.path.join(os.path.expanduser('~'), '.kano-notifications.fifo'),
            'w'
        )
        with fifo:
            for notification in (new_level_str + ' ' + new_items_str).split(' '):
                if len(notification) > 0:
                    logger.debug(
                        "Showing the {} notification".format(notification)
                    )
                    fifo.write('{}\n'.format(notification))

    cmd = '{bin_dir}/kano-sync --sync -s'.format(bin_dir=bin_dir)
    run_bg(cmd)
Example #50
0
 def beta_134_to_beta_200(self, dummy_progress):
     if not is_installed('kano-character-cli'):
         logger.info(
             "kano-character-cli not installed,"
             " attempt to install kano-profile"
         )
         install('kano-profile')
     run_cmd_log(
         'kano-character-cli -c "judoka" "Hair_Black" "Skin_Orange" -s'
     )
    def on_drag_end(self, *_):
        """ Triggered when the drag action is terminated """

        logger.info("Drag ended")
        self.add(self.image)

        for element in self.hidden_elements:
            element.show()

        self.show_all()
def main():
    """TODO"""

    if os.getuid() != 0:
        return 10

    logger.info('Reverting Safe Mode config.txt configuration')

    config_copy_from(CONFIG_TXT_BACKUP_PATH)
    os.remove(CONFIG_TXT_BACKUP_PATH)
    end_config_transaction()
    def on_drag_data_received(self, widget, drag_context, x, y, data, info,
                              time):
        """
        Triggered whenever new drag data is received. If the Judoka
        has been successfully dragged then move on to the next stage
        """

        logger.info("Drop area has received data")
        if info == 2:
            drag_context.finish(True, True, time)
            self.next_cb()
Example #54
0
def launch(data, background=False):
    if data:
        (title, attachment_path, app, attachment_name, folder, item_id) = data
        msg = "Downloaded share: {}".format(title)
        logger.info(msg)

        if check_installed(app):
            launch_project(app, attachment_name, folder, background=background)
            report_share_opened(item_id)
    else:
        logger.error("Share hook launch failed")
Example #55
0
def recreate_char(block=True):
    """ Recreate the assets for the character from the saved values
    :param block: (Optional) Set to True to block until the operation has
                  finished
    :type block: Boolean
    """
    logger.info("recreating character from profile")
    cmd = '{bin_dir}/kano-character-cli -g'.format(bin_dir=bin_dir)
    pr = run_bg(cmd)
    if block:
        pr.wait()
Example #56
0
def _copy_package_assets():
    # Use abs paths for both src and dest for subsequent replacements to work
    src_dir = os.path.abspath(_get_package_static_dir())
    dest_dir = os.path.abspath(STATIC_ASSET_DIR)

    # First Clear this cache
    empty_directory(dest_dir)

    # Now copy the static assets
    recursively_copy(src_dir, dest_dir)

    logger.info('Successfully copied over static assets')
Example #57
0
    def create_avatar(self, file_name=''):
        """ Create the finished main image and save it to file.
        :param file_name: (Optional) A filename to be used for the asset that
                          is generated
        :returns: None if there was an issue while creating avatar, the
                  location of the created file otherwise
        :rtype: String or None
        """
        logger.debug(
            "About to create character with items: {}".format(
                str(self.selected_items()))
        )
        ret = None
        rc = self._create_base_img()

        if not rc:
            logger.error("Can't create image")
            return None

        for zindex in sorted(self._sel_objs_per_zindex.keys()):
            items = self._sel_objs_per_zindex[zindex]
            for item in items:
                item.paste_over_image(self._sel_char.get_img(),self._sel_char.get_img_overworld())

        # write to specified location
        fname_actual = file_name[:]
        if not fname_actual:
            logger.info(
                "Haven't provided a filename to save asset,using default")

            fname_actual = AVATAR_SCRATCH
            if not os.path.isdir(os.path.dirname(fname_actual)):
                os.makedirs(os.path.dirname(fname_actual))

        # save overworld avatar
        if not os.path.isdir(os.path.dirname(AVATAR_OVERWORLD)):
            os.makedirs(os.path.dirname(AVATAR_OVERWORLD))
        self._sel_char.save_image_overworld(AVATAR_OVERWORLD)
        # save pong avatar
        if not os.path.isdir(os.path.dirname(AVATAR_PONG)):
            os.makedirs(os.path.dirname(AVATAR_PONG))
        self._sel_char.save_image_overworld(AVATAR_PONG)

        if not self._sel_env:
            logger.error("Haven't selected environment, can't save character")
            return None
        else:
            # Save the final image with the background
            file_name_env = append_suffix_to_fname(fname_actual, '_inc_env')
            self.create_avatar_with_background(file_name_env)
            ret = file_name_env

        return ret
Example #58
0
def remove_user_files(files):
    logger.info("utils / remove_user_files files:{}".format(files))
    for d in os.listdir("/home/"):
        if os.path.isdir("/home/{}/".format(d)):
            for f in files:
                file_path = "/home/{}/{}".format(d, f)
                if os.path.exists(file_path):
                    logger.info("trying to delete file: {}".format(file_path))
                    try:
                        os.remove(file_path)
                    except:
                        logger.warn("could not delete file: {}".format(file_path))