示例#1
0
class ConfigCreator(object):
    """Create a new config file interactively"""

    def __init__(self):
        super(ConfigCreator, self).__init__()
        self._session = Session()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self._session.__exit__(exc_type, exc_value, traceback)

    def new_config(self):
        base_url = input("URL of StudIP (leave empty for default server): ")
        username = input("Username: "******"Save password (in clear text)? [y/N]: ").lower() in ("y", "yes")
        files_destination = input("Sync files to directory (leave empty to disable): ")
        media_destination = input("Sync media to directory (leave empty to disable): ")

        self._session.login(username, password)
        #courses = list(self._session.get_courses())

        config = {}
        #config["courses"] = courses
        config["user"] = {"login": username}

        if base_url:
            config["base_url"] = base_url

        if save_password:
            config["user"]["password"] = password

        if files_destination:
            config["files_destination"] = files_destination

        if media_destination:
            config["media_destination"] = media_destination

        path = CONFIG_PATH
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w") as config_file:
            print("Writing new config to '{}'".format(path))
            json.dump(config, config_file, ensure_ascii=False, indent=4)

    @staticmethod
    def replace_config(config):
        path = CONFIG_PATH
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w") as config_file:
            print("Replacing config at '{}'".format(path))
            json.dump(config, config_file, ensure_ascii=False, indent=4)
示例#2
0
    def sync(self):
        extractor = Extractor(self.extract_dir)
        rsync = RsyncWrapper()

        with Session() as session:
            print("Logging in...")
            try:
                session.login(CONFIG.username, CONFIG.password)
            except (LoginError, ParserError):
                print("Login failed!")
                return 1

            status_code = 0
            for course in CONFIG.courses:
                print("Downloading '{}'...".format(course["save_as"]),
                      end="",
                      flush=True)
                try:
                    zip_location = session.download(course["course_id"],
                                                    self.download_dir,
                                                    course.get("sync_only"))
                    extractor.extract(zip_location, course["save_as"])
                except DownloadError:
                    print(" Download FAILED!", end="")
                    status_code = 2
                except ExtractionError:
                    print(" Extracting FAILED!", end="")
                    status_code = 2
                finally:
                    print()

        print("Synchronizing with existing files...")
        rsync.sync(self.extract_dir + "/", self.destination_dir)
        return status_code
示例#3
0
def create_session():
    with Session(base_url=STUDIP_SYNC_CONFIG.base_url) as studip_sync_session:
        print("Logging in...")
        try:
            studip_sync_session.login(STUDIP_SYNC_CONFIG.auth_type, STUDIP_SYNC_CONFIG.auth_type_data,
                                      STUDIP_SYNC_CONFIG.username,
                                      STUDIP_SYNC_CONFIG.password)
        except (LoginError, ParserError) as e:
            print("Login failed!")
            print(e)
            return 1

    return studip_sync_session.session
示例#4
0
class ConfigCreator(object):
    """Create a new config file interactively"""
    def __init__(self):
        super(ConfigCreator, self).__init__()
        self._session = Session()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self._session.__exit__(exc_type, exc_value, traceback)

    def new_config(self):
        username = input("Username: "******"Save password (in clear text)? [y/N]: ").lower() in ("y", "yes")
        destination = input("Sync to directory: ")

        self._session.login(username, password)
        courses = list(self._session.get_couses())

        config = {}
        config["courses"] = courses
        config["user"] = {"login": username}

        if save_password:
            config["user"]["password"] = password

        if destination:
            config["destination"] = destination

        path = CONFIG_PATH
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w") as config_file:
            print("Writing new config to '{}'".format(path))
            json.dump(config, config_file, ensure_ascii=False, indent=4)
示例#5
0
 def __init__(self):
     super(ConfigCreator, self).__init__()
     self._session = Session()
示例#6
0
    def sync(self, sync_fully=False, sync_recent=False, use_api=False):
        PLUGINS.hook("hook_start")

        with Session(base_url=CONFIG.base_url, plugins=PLUGINS) as session:
            print("Logging in...")
            try:
                session.login(CONFIG.auth_type, CONFIG.auth_type_data,
                              CONFIG.username, CONFIG.password)
            except (LoginError, ParserError) as e:
                print("Login failed!")
                print(e)
                return 1

            print("Downloading course list...")

            try:
                courses = list(session.get_courses(sync_recent))
            except (LoginError, ParserError) as e:
                print("Downloading course list failed!")
                print(e)
                return 1

            if sync_recent:
                print("Syncing only the most recent semester!")

            status_code = 0
            for i in range(0, len(courses)):
                course = courses[i]
                print("{}) {}: {}".format(i + 1, course["semester"],
                                          course["save_as"]))

                course_save_as = get_course_save_as(course)

                if self.files_destination_dir:
                    try:
                        files_root_dir = os.path.join(
                            self.files_destination_dir, course_save_as)

                        CourseRSync(session, self.workdir, files_root_dir,
                                    course, sync_fully, use_api).download()
                    except MissingFeatureError:
                        # Ignore if there are no files
                        pass
                    except DownloadError as e:
                        print("\tDownload of files failed: " + str(e))
                        status_code = 2
                        raise e

                if self.media_destination_dir:
                    try:
                        print("\tSyncing media files...")

                        media_root_dir = os.path.join(
                            self.media_destination_dir, course_save_as)

                        session.download_media(course["course_id"],
                                               media_root_dir,
                                               course["save_as"])
                    except MissingFeatureError:
                        # Ignore if there is no media
                        pass
                    except DownloadError as e:
                        print("\tDownload of media failed: " + str(e))
                        status_code = 2
                        raise e
                    except ParserError as e:
                        print("\tDownload of media failed: " + str(e))
                        if status_code != 0:
                            raise e
                        else:
                            status_code = 2

        if self.files_destination_dir and status_code == 0:
            CONFIG.update_last_sync(int(time.time()))

        return status_code
示例#7
0
    def sync(self, sync_fully=False, sync_recent=False):
        extractor = Extractor(self.extract_dir)
        rsync = RsyncWrapper()

        with Session(CONFIG.base_url) as session:
            print("Logging in...")
            try:
                session.login(CONFIG.username, CONFIG.password)
            except (LoginError, ParserError) as e:
                print("Login failed!")
                print(e)
                return 1

            print("Downloading course list...")

            courses = []
            try:
                courses = list(session.get_courses(sync_recent))
            except (LoginError, ParserError) as e:
                print("Downloading course list failed!")
                print(e)
                return 1

            if sync_recent:
                print("Syncing only the most recent semester!")

            status_code = 0
            for i in range(0, len(courses)):
                course = courses[i]
                print("{}) {}: {}".format(i + 1, course["semester"],
                                          course["save_as"]))

                if self.files_destination_dir:
                    try:
                        if sync_fully or session.check_course_new_files(
                                course["course_id"], CONFIG.last_sync):
                            print("\tDownloading files...")
                            zip_location = session.download(
                                course["course_id"], self.download_dir,
                                course.get("sync_only"))
                            extractor.extract(zip_location, course["save_as"])
                        else:
                            print("\tSkipping this course...")
                    except MissingFeatureError as e:
                        # Ignore if there are no files
                        pass
                    except DownloadError as e:
                        print("\tDownload of files failed: " + str(e))
                        status_code = 2
                    except ExtractionError as e:
                        print("\tExtracting files failed: " + str(e))
                        status_code = 2

                if self.media_destination_dir:
                    try:
                        print("\tSyncing media files...")

                        media_course_dir = os.path.join(
                            self.media_destination_dir, course["save_as"])

                        session.download_media(course["course_id"],
                                               media_course_dir)
                    except MissingFeatureError as e:
                        # Ignore if there is no media
                        pass
                    except DownloadError as e:
                        print("\tDownload of media failed: " + str(e))
                        status_code = 2

        if self.files_destination_dir:
            print("Synchronizing with existing files...")
            rsync.sync(self.extract_dir + "/", self.files_destination_dir)

            if status_code == 0:
                CONFIG.update_last_sync(int(time.time()))

        return status_code
示例#8
0
class ConfigCreator(object):
    """Create a new config file interactively"""

    def __init__(self):
        super(ConfigCreator, self).__init__()
        self._session = Session()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self._session.__exit__(exc_type, exc_value, traceback)

    def new_config(self):
        base_url, auth_key, auth_data = get_url_and_auth_type()
        username = input("Username: "******"Logging in...")
        self._session.login(auth_key, auth_data, username, password)

        save_password = input("Save password (in clear text)? [y/N]: ").lower() in ("y", "yes")
        files_destination = input("Sync files to directory (leave empty to disable): ")
        media_destination = input("Sync media to directory (leave empty to disable): ")

        config = {
            "user": {
                "login": username
            }
        }

        if base_url:
            config["base_url"] = base_url

        if auth_key:
            config["auth_type"] = auth_key

        if auth_data:
            config["auth_type_data"] = auth_data

        if save_password:
            config["user"]["password"] = password

        if files_destination:
            config["files_destination"] = files_destination

        if media_destination:
            config["media_destination"] = media_destination

        path = get_config_file()

        JSONConfig.save_config(path, config)

    @staticmethod
    def replace_config(config):
        path = get_config_file()

        JSONConfig.save_config(path, config)