コード例 #1
0
def mark_attendance(target_url, session, headers) -> None:
    """Function that marks the attendance for every calender event."""
    payload_instance = dict(payload)

    with RequestURL(target_url, session, headers) as soup:
        title = soup.title.string
        try:
            target = soup.find("a", text="Submit attendance")["href"]

        except TypeError:
            print(title)
            print("NO Submission Link")
            print("-" * 20)

        else:
            for key, value in parse_qs(urlparse(target).query).items():
                payload_instance[key] = "".join(value)

            with RequestURL(target, session, headers) as soup2:
                present_value = soup2.find("input", {
                    "name": "status",
                    "type": "radio"
                })["value"]

                payload_instance.setdefault("status", present_value)

                with PostToURL(MARKATTENDANCEURL, session, headers,
                               payload_instance) as responce:
                    print(title)

                    if responce.status_code == codes["ok"]:
                        print("Submitted Attendance successfully")
                    else:
                        print("Error happend : " + responce.status_code)
                    print("-" * 20)
コード例 #2
0
    def get_file_title(url):
        """Returns the file_title from google drive link"""
        with RequestURL(url=url) as soup:
            file_title = soup.find("meta", attrs={
                "property": "og:title"
            }).attrs["content"]

            return file_title
コード例 #3
0
def submit_attendance(session, headers) -> None:
    """Submits the attendance for every calender event
    if submit attendance link is found."""
    clear_screen()
    print("Submitting attendance if any in calender")
    print("-" * 20)
    with RequestURL(CLNDRURL, session, headers) as soup:
        for link in links(soup):
            threading.Thread(target=mark_attendance,
                             args=(link, session, headers)).start()
コード例 #4
0
def calender_events(session, headers) -> None:
    """Shows the calender events"""
    clear_screen()
    print("Showing upcoming events")
    print("-" * 20)
    with RequestURL(CLNDRURL, session, headers) as soup:
        for event in current_events(soup):
            for row in event.find_all("div", class_=re.compile("^row$")):
                print(row.get_text().strip())
            print("-" * 20)
            sys.stdout.flush()
コード例 #5
0
    def test_login(self):
        """tests login with RequestURL and PostToURL"""

        load_config()

        with requests.Session() as session:
            with RequestURL(URL, session, headers) as soup:
                config['logintoken'] = soup.find(
                    'input', {'name': 'logintoken'})['value']

            with PostToURL(URL, session, headers, config) as response:
                self.assertEqual(response.url, MAINURL)
コード例 #6
0
    def test_requesturl(self):
        """tests RequestURL context manager"""

        with requests.Session() as session:
            urllib3.disable_warnings(
                urllib3.exceptions.InsecureRequestWarning)
            with RequestURL('https://en.wikipedia.org/wiki/Netscape_Navigator',
                            session, headers) as soup:
                response = soup.find(
                    "meta", attrs={"property": "og:image"}).attrs["content"]

        self.assertEqual(
            response, 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Netscape_icon.svg/1200px-Netscape_icon.svg.png')
コード例 #7
0
ファイル: cli.py プロジェクト: ashish-patwal/MoodleAutomate
def login(cur_session):
    """logins to moodle"""
    with RequestURL(URL, cur_session, headers) as soup:
        config["logintoken"] = soup.find("input",
                                         {"name": "logintoken"})["value"]

    print("\nAuthenticating with Moodle...")

    with PostToURL(URL, cur_session, headers, config) as response:
        if response.url == URL:
            """Since on failed authentication page redirects to the login page we get status[200] in place of authentication failed status code .
            Therefore need to compare redirected URLS to check if we were authenticated against the platform or not"""
            raise FalseCredentialsError

        headers.update(cur_session.cookies.get_dict())
        print("\nupdated cookies for moodle session...")

    return cur_session
コード例 #8
0
ファイル: cli.py プロジェクト: ashish-patwal/MoodleAutomate
def get_sesskey(cur_session):
    """gets sesskey for current session"""
    with RequestURL(MAINURL, cur_session, headers) as soup:
        sesskey = soup.find("input", {"name": "sesskey"})["value"]

        return sesskey
コード例 #9
0
def subject_material(
    session,
    headers,
    selected_subject_info,
    sesskey,
    flagkey,
) -> None:
    """Prints the resources for a particular subject."""

    with RequestURL(f"{SUBURL}{selected_subject_info[3]}", session,
                    headers) as soup:
        links_data = soup.find_all(
            "a",
            href=re.compile(VIDEOURL_REG + "|" + ATTENDANCEURL_REG + "|" +
                            RESOURCEURL_REG),
        )

        datalist = [[
            counter,
            title_string_solver(link.get_text()), link.attrs["href"]
        ] for counter, link in enumerate(links_data, 1)]

        datalist = type_parser(datalist)

        clear_screen()

        print(
            tabulate(
                [[data[0], data[1], data[3]] for data in datalist],
                headers=["S.No", "Title", "url", "type"],
                tablefmt="pretty",
            ))

        try:

            if flagkey == "list_subjects":
                choice = input("Enter choice [ q/Q to quit ] : ")

                if choice.lower() == "q":
                    sys.exit(1)

                if (int(choice) not in range(1,
                                             len(datalist) + 1)
                        or not choice.isdigit()):
                    print(choice)
                    raise UserChoiceError

                baseurl = datalist[int(choice) - 1][2]
                module_completion["sesskey"] = sesskey
                module_completion["id"] = baseurl.split("=")[1]
                mark_module_completion(session, headers, module_completion)

                if datalist[int(choice) - 1][3] == "resource":
                    download_resource(baseurl, session, headers,
                                      selected_subject_info[1])
                elif datalist[int(choice) - 1][3] == "video":
                    play_video(baseurl, session, headers)
                elif datalist[int(choice) - 1][3] == "attendance":
                    pass
                else:
                    print("Something new just emerged . Contact the dev .")

            elif flagkey == "download_modules":
                range_list = input(
                    "Enter modules to download [ q/Q to quit ]: ")

                if range_list.lower() == "q":
                    clear_screen()
                    sys.exit(0)

                range_list = modules_download_range_resolver(range_list)

                if range_list[-1] > len(datalist):
                    raise UserChoiceError

                download_modules(session, headers, range_list, datalist,
                                 selected_subject_info[1])

        except (UserChoiceError, ValueError):
            print("\nInvalid input. Check your responce.")

        except IndexError:
            print("value out of index")

        input("Press any key to continue...")
        # TODO: Addition of Quit statement and backspace for previous page
        subject_material(session, headers, selected_subject_info, sesskey,
                         flagkey)