コード例 #1
0
ファイル: session.py プロジェクト: rcocetta/kano-profile
    def download_online_badges(self):
        profile = load_profile()
        if "kanoworld_id" in profile:
            user_id = profile["kanoworld_id"]
        else:
            return False, "Profile not registered!"

        success, text, data = request_wrapper("get", "/users/{}".format(user_id), session=self.session)

        if not success:
            return False, text

        if "user" not in data:
            return False, "Corrupt response (the 'user' key not found)"

        if "profile" not in data["user"]:
            return False, "Corrupt response (the 'user.profile' key not found)"

        if "badges" not in data["user"]["profile"]:
            msg = "Corrupt response (the 'user.profile.badges' key not found)"
            return False, msg

        online_badges_data = {}

        ensure_dir(online_badges_dir)

        badges = data["user"]["profile"]["badges"]
        for badge in badges:
            if "assigned" not in badge or not badge["assigned"]:
                continue

            if "image_url" not in badge:
                return False, "Couldn't find an image for the badge"

            image_loc = os.path.join(online_badges_dir, "{}.png".format(badge["id"]))
            download_url(badge["image_url"], image_loc)

            online_badges_data[badge["id"]] = {
                "achieved": True,
                "bg_color": badge["bg_color"].replace("#", ""),
                "desc_locked": badge["desc_locked"],
                "desc_unlocked": badge["desc_unlocked"],
                "title": badge["title"],
            }

        try:
            may_write = True
            txt = None
            f = open(online_badges_file, "w")
        except IOError as e:
            may_write = False
            txt = "Error opening badges file {}".format(str(e))
        else:
            with f:
                f.write(json.dumps(online_badges_data))
            if "SUDO_USER" in os.environ:
                chown_path(online_badges_dir)
                chown_path(online_badges_file)

        return may_write, txt
コード例 #2
0
ファイル: session.py プロジェクト: rcocetta/kano-profile
    def refresh_notifications(self):
        rv = True
        error = None

        next_page = 0
        notifications = []
        while next_page is not None:
            success, text, data = request_wrapper(
                "get", "/notifications?read=false&page={}".format(next_page), session=self.session
            )

            if not success:
                rv = False
                error = text
                break

            for entry in data["entries"]:
                if entry["read"] is False:
                    n = self._process_notification(entry)
                    notifications.append(n)

            try:
                next_page = data["next"]
            except:
                break

        if rv:
            profile = load_profile()
            profile["notifications"] = notifications
            save_profile(profile)

        return rv, error
コード例 #3
0
ファイル: session.py プロジェクト: KanoComputing/kano-profile
    def download_profile_stats(self, data=None):
        if not data:
            profile = load_profile()
            if 'kanoworld_id' in profile:
                user_id = profile['kanoworld_id']
            else:
                return False, 'Profile not registered!'

            success, text, data = request_wrapper('get', '/users/' + user_id,
                                                  headers=content_type_json,
                                                  session=self.session)
            if not success:
                return False, text

        try:
            version_no = data['user']['avatar']['generator']['version']
            save_profile_variable(
                'version',
                version_no,
                skip_kdesk_refresh=True
            )
        except Exception:
            pass

        updated_locally = False
        try:
            # Only update locally if version is 2. otherwise we will generate
            # a default
            if data['user']['avatar']['generator']['version'] == 2:
                gen = data['user']['avatar']['generator']
                avatar_subcat, avatar_item = gen['character']
                updated_locally = set_avatar(
                    avatar_subcat,
                    avatar_item,
                    sync=False
                )

                environment = gen['environment'][1]
                updated_locally |= set_environment(environment, sync=False)

        except Exception:
            pass

        # app states
        try:
            app_data = data['user']['profile']['stats']
        except Exception:
            return False, "Data missing from payload!"

        for app, values in app_data.iteritems():
            if not values or type(values) != dict or \
                    (len(values.keys()) == 1 and 'save_date' in values):
                continue
            if not is_private(app):
                save_app_state(app, values)

        if updated_locally:
            recreate_char(block=True)

        return True, None
コード例 #4
0
    def refresh_notifications(self):
        rv = True
        error = None

        next_page = 0
        notifications = []
        while next_page is not None:
            success, text, data = request_wrapper(
                'get',
                '/notifications?read=false&page={}'.format(next_page),
                session=self.session)

            if not success:
                rv = False
                error = text
                break

            for entry in data['entries']:
                if entry['read'] is False:
                    n = self._process_notification(entry)
                    if n:
                        notifications.append(n)

            try:
                next_page = data['next']
            except:
                break

        if rv:
            profile = load_profile()
            profile['notifications'] = notifications
            save_profile(profile)

        return rv, error
コード例 #5
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def get_mixed_username():
    if is_registered():
        profile = load_profile()
        username = profile['kanoworld_username']
    else:
        username = get_user_unsudoed()
    return username
コード例 #6
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def get_mixed_username():
    if is_registered():
        profile = load_profile()
        username = profile['kanoworld_username']
    else:
        username = get_user_unsudoed()
    return username
コード例 #7
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def login_register_data(data):
    global glob_session

    profile = load_profile()
    profile['token'] = data['session']['token']
    profile['kanoworld_username'] = data['session']['user']['username']
    profile['kanoworld_id'] = data['session']['user']['id']
    profile['email'] = data['session']['user']['email']

    # We know this field will be returned from the API even if it is empty
    # However we only need to store it if it has a meaningful value
    try:
        if data['session']['user']['secondary_email']:
            profile['secondary_email'] = data['session']['user'][
                'secondary_email']
    except:
        profile.pop('secondary_email', None)

    save_profile(profile)
    try:
        glob_session = KanoWorldSession(profile['token'])
        return True, None
    except Exception as e:
        return False, _(
            "We cannot reach the Kano server. Try again in a few minutes. Error = {}"
        ).format(str(e))
コード例 #8
0
ファイル: session.py プロジェクト: KanoComputing/kano-profile
    def refresh_notifications(self):
        rv = True
        error = None

        next_page = 0
        notifications = []
        while next_page is not None:
            success, text, data = request_wrapper(
                'get',
                '/notifications?read=false&page={}'.format(next_page),
                session=self.session
            )

            if not success:
                rv = False
                error = text
                break

            for entry in data['entries']:
                if entry['read'] is False:
                    n = self._process_notification(entry)
                    if n:
                        notifications.append(n)

            try:
                next_page = data['next']
            except:
                break

        if rv:
            profile = load_profile()
            profile['notifications'] = notifications
            save_profile(profile)

        return rv, error
コード例 #9
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def remove_registration():
    profile = load_profile()
    profile.pop('token', None)
    profile.pop('kanoworld_username', None)
    profile.pop('kanoworld_id', None)
    profile.pop('email', None)
    profile.pop('secondary_email', None)
    save_profile(profile)
コード例 #10
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def remove_registration():
    profile = load_profile()
    profile.pop('token', None)
    profile.pop('kanoworld_username', None)
    profile.pop('kanoworld_id', None)
    profile.pop('email', None)
    profile.pop('secondary_email', None)
    save_profile(profile)
コード例 #11
0
    def download_profile_stats(self, data=None):
        if not data:
            profile = load_profile()
            if 'kanoworld_id' in profile:
                user_id = profile['kanoworld_id']
            else:
                return False, 'Profile not registered!'

            success, text, data = request_wrapper('get',
                                                  '/users/' + user_id,
                                                  headers=content_type_json,
                                                  session=self.session)
            if not success:
                return False, text

        try:
            version_no = data['user']['avatar']['generator']['version']
            save_profile_variable('version',
                                  version_no,
                                  skip_kdesk_refresh=True)
        except Exception:
            pass

        updated_locally = False
        try:
            # Only update locally if version is 2. otherwise we will generate
            # a default
            if data['user']['avatar']['generator']['version'] == 2:
                gen = data['user']['avatar']['generator']
                avatar_subcat, avatar_item = gen['character']
                updated_locally = set_avatar(avatar_subcat,
                                             avatar_item,
                                             sync=False)

                environment = gen['environment'][1]
                updated_locally |= set_environment(environment, sync=False)

        except Exception:
            pass

        # app states
        try:
            app_data = data['user']['profile']['stats']
        except Exception:
            return False, "Data missing from payload!"

        for app, values in app_data.iteritems():
            if not values or type(values) != dict or \
                    (len(values.keys()) == 1 and 'save_date' in values):
                continue
            if not is_private(app):
                save_app_state(app, values)

        if updated_locally:
            recreate_char(block=True)

        return True, None
コード例 #12
0
ファイル: session.py プロジェクト: rcocetta/kano-profile
    def download_profile_stats(self, data=None):
        if not data:
            profile = load_profile()
            if "kanoworld_id" in profile:
                user_id = profile["kanoworld_id"]
            else:
                return False, "Profile not registered!"

            success, text, data = request_wrapper(
                "get", "/users/" + user_id, headers=content_type_json, session=self.session
            )
            if not success:
                return False, text

        try:
            version_no = data["user"]["avatar"]["generator"]["version"]
            save_profile_variable("version", version_no)
        except Exception:
            pass

        updated_locally = False
        try:
            # Only update locally if version is 2. otherwise we will generate
            # a default
            if data["user"]["avatar"]["generator"]["version"] == 2:
                gen = data["user"]["avatar"]["generator"]
                avatar_subcat, avatar_item = gen["character"]
                updated_locally = set_avatar(avatar_subcat, avatar_item)

                environment = gen["environment"][1]
                updated_locally |= set_environment(environment)

        except Exception:
            pass

        # app states
        try:
            app_data = data["user"]["profile"]["stats"]
        except Exception:
            return False, "Data missing from payload!"

        for app, values in app_data.iteritems():
            if not values or (len(values.keys()) == 1 and "save_date" in values):
                continue
            if not is_private(app):
                save_app_state(app, values)

        if updated_locally:
            recreate_char(block=True)

        return True, None
コード例 #13
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def login_using_token():
    global glob_session

    if not is_registered():
        return False, 'Not registered!'
    if not has_token():
        return False, 'No token!'

    try:
        profile = load_profile()
        glob_session = KanoWorldSession(profile['token'])
        return True, None
    except Exception as e:
        return False, str(e)
コード例 #14
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def login_using_token():
    global glob_session

    if not is_registered():
        return False, _("Not registered!")
    if not has_token():
        return False, _("No token!")

    try:
        profile = load_profile()
        glob_session = KanoWorldSession(profile['token'])
        return True, None
    except Exception as e:
        return False, str(e)
コード例 #15
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def login_register_data(data):
    global glob_session

    profile = load_profile()
    profile['token'] = data['session']['token']
    profile['kanoworld_username'] = data['session']['user']['username']
    profile['kanoworld_id'] = data['session']['user']['id']
    profile['email'] = data['session']['user']['email']

    # We know this field will be returned from the API even if it is empty
    # However we only need to store it if it has a meaningful value
    try:
        if data['session']['user']['secondary_email']:
            profile['secondary_email'] = data['session']['user']['secondary_email']
    except:
        profile.pop('secondary_email', None)

    save_profile(profile)
    try:
        glob_session = KanoWorldSession(profile['token'])
        return True, None
    except Exception as e:
        return False, 'We cannot reach the Kano server. Try again in a few minutes. Error = {}'.format(str(e))
コード例 #16
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def get_kano_world_id():
    try:
        kw_id = load_profile()['kanoworld_id']
    except Exception:
        kw_id = ''
    return kw_id
コード例 #17
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def get_secondary_email():
    try:
        sec_email = load_profile()['secondary_email']
    except Exception:
        sec_email = ''
    return sec_email
コード例 #18
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def get_email():
    try:
        email = load_profile()['email']
    except Exception:
        email = ''
    return email
コード例 #19
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def get_token():
    try:
        return load_profile()['token']
    except Exception:
        return ''
コード例 #20
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def get_token():
    try:
        return load_profile()['token']
    except Exception:
        return ''
コード例 #21
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def has_token():
    return 'token' in load_profile()
コード例 #22
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def has_token():
    return 'token' in load_profile()
コード例 #23
0
ファイル: session.py プロジェクト: KanoComputing/kano-profile
    def upload_profile_stats(self):
        profile = load_profile()

        data = dict()

        # xp
        data['xp'] = calculate_xp()

        # version
        try:
            data['version'] = profile['version']
        except KeyError:
            logger.debug("Version field not in the data to be synced")

        # age
        try:
            data['birthdate'] = profile['birthdate']
        except Exception:
            pass

        # gender
        try:
            gender = profile['gender']
            if gender == "Boy":
                gender = 'm'
            elif gender == "Girl":
                gender = 'f'
            elif gender == "Wizard":
                gender = 'x'
            data['gender'] = gender
        except Exception:
            pass

        # avatar_generator
        data, files = self._prepare_avatar_gen(profile, data)
        # app states
        stats = dict()
        for app in get_app_list():
            if not is_private(app):
                stats[app] = load_app_state(app)

        # append stats
        data['stats'] = stats

        # Uploading profile stats
        success, text, response_data = request_wrapper(
            'put',
            '/users/profile',
            data=json.dumps(data),
            headers=content_type_json,
            session=self.session)

        if not success:
            logger.error("Uploading of the profile data failed")
            return False, text

        if files:
            # Uploading avatar assets
            success, text, response_data = request_wrapper(
                'put',
                '/users/profile',
                session=self.session,
                files=files)

            # requests doesn't close the file objects after sending them, so
            # we need to tidy up
            self._tidy_up_avatar_files(files)

            if not success:
                logger.error("Uploading of the avatar assets failed")
                return False, text

        return self.download_profile_stats(response_data)
コード例 #24
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def get_secondary_email():
    try:
        sec_email = load_profile()['secondary_email']
    except Exception:
        sec_email = ''
    return sec_email
コード例 #25
0
    def download_online_badges(self):
        profile = load_profile()
        if 'kanoworld_id' in profile:
            user_id = profile['kanoworld_id']
        else:
            return False, 'Profile not registered!'

        success, text, data = request_wrapper('get',
                                              '/users/{}'.format(user_id),
                                              session=self.session)

        if not success:
            return False, text

        if 'user' not in data:
            return False, _("Corrupt response (the 'user' key not found)")

        if 'profile' not in data['user']:
            return False, _(
                "Corrupt response (the 'user.profile' key not found)")

        if 'badges' not in data['user']['profile']:
            return False, _(
                "Corrupt response (the 'user.profile.badges' key not found)")

        online_badges_data = {}

        ensure_dir(online_badges_dir)

        badges = data['user']['profile']['badges']
        for badge in badges:
            if 'assigned' not in badge or not badge['assigned']:
                continue

            if 'image_url' not in badge:
                return False, _("Couldn't find an image for the badge")

            image_loc = os.path.join(online_badges_dir,
                                     "{}.png".format(badge['id']))
            download_url(badge['image_url'], image_loc)

            online_badges_data[badge['id']] = {
                'achieved': True,
                'bg_color': badge['bg_color'].replace("#", ""),
                'desc_locked': badge['desc_locked'],
                'desc_unlocked': badge['desc_unlocked'],
                'title': badge['title']
            }

        try:
            may_write = True
            txt = None
            f = open(online_badges_file, 'w')
        except IOError as e:
            may_write = False
            txt = 'Error opening badges file {}'.format(str(e))
        else:
            with f:
                f.write(json.dumps(online_badges_data))
            if 'SUDO_USER' in os.environ:
                chown_path(online_badges_dir)
                chown_path(online_badges_file)

        return may_write, txt
コード例 #26
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def get_kano_world_id():
    try:
        kw_id = load_profile()['kanoworld_id']
    except Exception:
        kw_id = ''
    return kw_id
コード例 #27
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def remove_token():
    profile = load_profile()
    profile.pop('token', None)
    save_profile(profile)
コード例 #28
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def is_registered():
    return 'kanoworld_id' in load_profile()
コード例 #29
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def get_email():
    try:
        email = load_profile()['email']
    except Exception:
        email = ''
    return email
コード例 #30
0
ファイル: functions.py プロジェクト: japonophile/kano-profile
def remove_token():
    profile = load_profile()
    profile.pop('token', None)
    save_profile(profile)
コード例 #31
0
ファイル: functions.py プロジェクト: fantomid/kano-profile
def is_registered():
    return 'kanoworld_id' in load_profile()
コード例 #32
0
ファイル: session.py プロジェクト: KanoComputing/kano-profile
    def download_online_badges(self):
        profile = load_profile()
        if 'kanoworld_id' in profile:
            user_id = profile['kanoworld_id']
        else:
            return False, 'Profile not registered!'

        success, text, data = request_wrapper(
            'get', '/users/{}'.format(user_id),
            session=self.session
        )

        if not success:
            return False, text

        if 'user' not in data:
            return False, _("Corrupt response (the 'user' key not found)")

        if 'profile' not in data['user']:
            return False, _("Corrupt response (the 'user.profile' key not found)")

        if 'badges' not in data['user']['profile']:
            return False, _("Corrupt response (the 'user.profile.badges' key not found)")

        online_badges_data = {}

        ensure_dir(online_badges_dir)

        badges = data['user']['profile']['badges']
        for badge in badges:
            if 'assigned' not in badge or not badge['assigned']:
                continue

            if 'image_url' not in badge:
                return False, _("Couldn't find an image for the badge")

            image_loc = os.path.join(online_badges_dir,
                                     "{}.png".format(badge['id']))
            download_url(badge['image_url'], image_loc)

            online_badges_data[badge['id']] = {
                'achieved': True,
                'bg_color': badge['bg_color'].replace("#", ""),
                'desc_locked': badge['desc_locked'],
                'desc_unlocked': badge['desc_unlocked'],
                'title': badge['title']
            }

        try:
            may_write = True
            txt = None
            f = open(online_badges_file, 'w')
        except IOError as e:
            may_write = False
            txt = 'Error opening badges file {}'.format(str(e))
        else:
            with f:
                f.write(json.dumps(online_badges_data))
            if 'SUDO_USER' in os.environ:
                chown_path(online_badges_dir)
                chown_path(online_badges_file)

        return may_write, txt
コード例 #33
0
ファイル: login.py プロジェクト: japonophile/kano-profile
from kano.gtk3.heading import Heading
from kano.gtk3.labelled_entries import LabelledEntries

from kano_profile.paths import bin_dir
from kano_profile.profile import load_profile, save_profile_variable
from kano_profile.tracker import save_hardware_info, save_kano_version
from kano_world.functions import (login as login_, is_registered,
                                  reset_password, get_email,
                                  get_mixed_username)

from kano_login.templates.kano_button_box import KanoButtonBox
from kano_login.swag_screen import SwagScreen

from kano_registration_gui.RegistrationScreen1 import RegistrationScreen1

profile = load_profile()
force_login = is_registered() and 'kanoworld_username' in profile


class Login(Gtk.Box):
    width = 550

    def __init__(self, win, prev_screen=None, first_boot=False):

        Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL)
        self.win = win
        self.win.set_main_widget(self)
        self.win.set_decorated(True)
        self.win.set_size_request(self.width, -1)
        self.first_boot = first_boot
コード例 #34
0
    def upload_profile_stats(self):
        profile = load_profile()

        data = dict()

        # xp
        data['xp'] = calculate_xp()

        # version
        try:
            data['version'] = profile['version']
        except KeyError:
            logger.debug("Version field not in the data to be synced")

        # age
        try:
            data['birthdate'] = profile['birthdate']
        except Exception:
            pass

        # gender
        try:
            gender = profile['gender']
            if gender == "Boy":
                gender = 'm'
            elif gender == "Girl":
                gender = 'f'
            elif gender == "Wizard":
                gender = 'x'
            data['gender'] = gender
        except Exception:
            pass

        # avatar_generator
        data, files = self._prepare_avatar_gen(profile, data)
        # app states
        stats = dict()
        for app in get_app_list():
            if not is_private(app):
                stats[app] = load_app_state(app)

        # append stats
        data['stats'] = stats

        # Uploading profile stats
        success, text, response_data = request_wrapper(
            'put',
            '/users/profile',
            data=json.dumps(data),
            headers=content_type_json,
            session=self.session)

        if not success:
            logger.error("Uploading of the profile data failed")
            return False, text

        if files:
            # Uploading avatar assets
            success, text, response_data = request_wrapper(
                'put', '/users/profile', session=self.session, files=files)

            # requests doesn't close the file objects after sending them, so
            # we need to tidy up
            self._tidy_up_avatar_files(files)

            if not success:
                logger.error("Uploading of the avatar assets failed")
                return False, text

        return self.download_profile_stats(response_data)
コード例 #35
0
ファイル: login.py プロジェクト: isabella232/kano-profile
from kano.utils import run_bg

from kano_login.swag_screen import SwagScreen
from kano_login.templates.kano_button_box import KanoButtonBox

from kano_profile.paths import bin_dir
from kano_profile.profile import load_profile, save_profile_variable
from kano_profile.tracker import save_hardware_info, save_kano_version

from kano_registration_gui.RegistrationScreen import RegistrationScreen

from kano_world.functions import get_email, get_mixed_username, is_registered, \
    reset_password, recover_username
from kano_world.functions import login as login_

profile = load_profile()
force_login = is_registered() and 'kanoworld_username' in profile


class Login(Gtk.Box):
    width = 550

    def __init__(self, win, prev_screen=None, first_boot=False):

        Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL)
        self.win = win
        self.win.set_main_widget(self)
        self.win.set_decorated(True)
        self.win.set_size_request(self.width, -1)
        self.first_boot = first_boot