def obtain_login_token(username: str, password: str, moodle_domain: str,
                       moodle_path: str = "/",
                       skip_cert_verify: bool = False) -> str:
    """
    Sends the login credentials to the Moodle-System and extracts the
    resulting Login-Token.
    @params: The necessary parameters to create a Toekn.
    @return: The received token.
    """
    login_data = {
        'username': username,
        'password': password,
        'service': 'moodle_mobile_app'
    }

    response = RequestHelper(moodle_domain, moodle_path,
                             skip_cert_verify).get_login(login_data)

    if "token" not in response:
        # = we didn't get an error page (checked by the RequestHelper) but
        # somehow we don't have the needed token
        raise RuntimeError('Invalid response received from the Moodle' +
                           ' System!  No token was received.')

    return response.get("token", "")
    def interactively_acquire_config(self):
        """
        Guides the user through the process of configuring the downloader
        for the courses to be downloaded and in what way
        """

        token = self.get_token()
        moodle_domain = self.get_moodle_domain()
        moodle_path = self.get_moodle_path()

        request_helper = RequestHelper(moodle_domain, moodle_path, token)
        results_handler = ResultsHandler(request_helper)

        courses = []
        try:

            userid, version = results_handler.fetch_userid_and_version()
            results_handler.setVersion(version)

            courses = results_handler.fetch_courses(userid)

        except (RequestRejectedError, ValueError, RuntimeError) as error:
            raise RuntimeError(
                'Error while communicating with the Moodle System! (%s)' %
                (error))

        self._select_courses_to_download(courses)
        self._select_should_download_submissions()
    def interactively_acquire_sso_token(self) -> str:
        """
        Walks the user through the receiving of a SSO token for the
        Moodle-System and saves it.
        @return: The Token for Moodle.
        """

        moodle_url = input('URL of Moodle:   ')

        moodle_uri = urlparse(moodle_url)

        moodle_domain, moodle_path = self._split_moodle_uri(moodle_uri)

        version = RequestHelper(moodle_domain, moodle_path, '',
                                self.skip_cert_verify
                                ).get_simple_moodle_version()

        if (version > 3.8):
            print('Between version 3.81 and 3.82 a change was added to' +
                  ' Moodle so that automatic copying of the SSO token' +
                  ' might not work. You can still try it, your version is: ' +
                  str(version))

        print(' If you want to copy the login-token manual,' +
              ' you will be guided through the manual copy process.')
        do_automatic = cutie.prompt_yes_or_no(
            'Do you want to try to receive the SSO token automatically?')

        print('Please log into Moodle on this computer and then visit' +
              ' the following address in your web browser: ')

        print('https://' + moodle_domain + moodle_path +
              'admin/tool/mobile/launch.php?service=' +
              'moodle_mobile_app&passport=12345&' +
              'urlscheme=http%3A%2F%2Flocalhost')

        if do_automatic:
            moodle_token = sso_token_receiver.receive_token()
        else:
            print('If you open the link in the browser, no web page should' +
                  ' load, instead an error will occur. Open the' +
                  ' developer console (press F12) and go to the Network Tab,' +
                  ' if there is no error, reload the web page.')

            print('Copy the link address of the website that could not be' +
                  ' loaded (right click, then click on Copy, then click' +
                  ' on copy link address).')

            token_address = input('Then insert the address here:   ')

            moodle_token = sso_token_receiver.extract_token(token_address)
            if(moodle_token is None):
                raise ValueError('Invalid URL!')

        # Saves the created token and the successful Moodle parameters.
        self.config_helper.set_property('token', moodle_token)
        self.config_helper.set_property('moodle_domain', moodle_domain)
        self.config_helper.set_property('moodle_path', moodle_path)

        return moodle_token
Beispiel #4
0
    def interactively_acquire_config(self):
        """
        Guides the user through the process of configuring the downloader
        for the courses to be downloaded and in what way
        """

        token = self.config_helper.get_token()
        moodle_domain = self.config_helper.get_moodle_domain()
        moodle_path = self.config_helper.get_moodle_path()

        request_helper = RequestHelper(moodle_domain, moodle_path, token,
                                       self.skip_cert_verify)
        first_contact_handler = FirstContactHandler(request_helper)

        courses = []
        try:

            userid, version = first_contact_handler.fetch_userid_and_version()

            courses = first_contact_handler.fetch_courses(userid)

        except (RequestRejectedError, ValueError, RuntimeError) as error:
            raise RuntimeError(
                'Error while communicating with the Moodle System! (%s)' %
                (error))

        self._select_courses_to_download(courses)
        self._set_options_of_courses(courses)
        self._select_should_download_submissions()
        self._select_should_download_descriptions()
        self._select_should_download_databases()
        self._select_should_download_linked_files()
    def fetch_state(self) -> [Course]:
        """
        Gets the current status of the configured Moodle account and compares
        it with the last known status for changes. It does not change the
        known state, nor does it download the files.
        @return: List with detected changes
        """
        logging.debug('Fetching current Moodle State...')

        token = self.config_helper.get_token()
        moodle_domain = self.config_helper.get_moodle_domain()
        moodle_path = self.config_helper.get_moodle_path()

        request_helper = RequestHelper(moodle_domain, moodle_path, token,
                                       self.skip_cert_verify)
        results_handler = ResultsHandler(request_helper)

        download_course_ids = self.config_helper.get_download_course_ids()
        dont_download_course_ids = self.config_helper\
            .get_dont_download_course_ids()
        download_submissions = self.config_helper.get_download_submissions()
        download_descriptions = self.config_helper.get_download_descriptions()

        courses = []
        filtered_courses = []
        try:

            sys.stdout.write('\rDownload account information')
            sys.stdout.flush()

            userid, version = results_handler.fetch_userid_and_version()
            results_handler.setVersion(version)

            courses_list = results_handler.fetch_courses(userid)
            courses = []
            # Filter unselected courses
            for course in courses_list:
                if (ResultsHandler._should_download_course(
                    course.id, download_course_ids,
                        dont_download_course_ids)):
                    courses.append(course)

            assignments = results_handler.fetch_assignments(courses)

            if(download_submissions):
                assignments = results_handler.fetch_submissions(
                    userid, assignments, download_course_ids,
                    dont_download_course_ids)

            index = 0
            for course in courses:
                index += 1

                # to limit the output to one line
                limits = shutil.get_terminal_size()

                shorted_course_name = course.fullname
                if (len(course.fullname) > 17):
                    shorted_course_name = course.fullname[:15] + '..'

                into = '\rDownload course information'

                status_message = (into + ' %3d/%3d [%17s|%6s]'
                                  % (index, len(courses),
                                      shorted_course_name,
                                      course.id))

                if (len(status_message) > limits.columns):
                    status_message = status_message[0:limits.columns]

                sys.stdout.write(status_message)
                sys.stdout.flush()

                course_assignments = assignments.get(course.id, [])
                course.files = results_handler.fetch_files(
                    course.id, course_assignments, download_descriptions)

                filtered_courses.append(course)
            print("")

        except (RequestRejectedError, ValueError, RuntimeError) as error:
            raise RuntimeError(
                'Error while communicating with the Moodle System! (%s)' % (
                    error))

        logging.debug('Checking for changes...')
        changes = self.recorder.changes_of_new_version(filtered_courses)

        # Filter changes
        changes = self._filter_courses(changes, download_course_ids,
                                       dont_download_course_ids,
                                       download_submissions,
                                       download_descriptions)

        changes = self.add_options_to_courses(changes)

        return changes