예제 #1
0
def main(config):
    try:
        base_request_header = {
            "User-Agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/39.0.2171.95 Safari/537.36",
        }

        collected_details = get_saved_user_info(config)
        display_info_dict(collected_details)

        while True:
            info = SimpleNamespace(**get_saved_user_info(config))
            request_header = copy.deepcopy(base_request_header)
            request_header["Authorization"] = info.auth

            # call function to check and book slots
            if not check_and_book(
                    request_header,
                    info.beneficiary_dtls,
                    info.location_dtls,
                    preferred_slot=info.preferred_slot,
                    min_slots=info.minimum_slots,
                    api_key=info.api_key,
                    appointment_id=info.appointment_id,
            ):
                print("Reauthorizing...")
                reauthorize(config=config)

    except Exception as e:
        print(str(e))
        print("Exiting Script")
예제 #2
0
def book_slot(mobile, token, state_name, district_name):
    base_request_header = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
        }

    request_header = copy.deepcopy(base_request_header)
    request_header["Authorization"] = f"Bearer {token}"

    collected_details, error = collect_user_details(request_header, state_name, district_name)
    if error:
        return False, error
    info = SimpleNamespace(**collected_details)

    retry_count = 1
    while retry_count < 5:
        # call function to check and book slots
        try:
            token_valid, error = check_and_book(request_header, info.beneficiary_dtls, info.location_dtls, info.search_option,
                                            min_slots=info.minimum_slots,
                                            ref_freq=info.refresh_freq,
                                            auto_book=info.auto_book,
                                            start_date=info.start_date,
                                            vaccine_type=info.vaccine_type,
                                            fee_type=info.fee_type,
                                            mobile=mobile,
                                            captcha_automation=info.captcha_automation,
                                            captcha_automation_api_key=info.captcha_automation_api_key)

            if error:
                return False, error
            # check if token is still valid
            beneficiaries_list = requests.get(BENEFICIARIES_URL, headers=request_header)
            if beneficiaries_list.status_code == 200:
                token_valid = True
                return True, "Slot has been booked. You will get notification on your registered mobile number."
            else:
                # if token invalid, retry 5 times
                logger.info('Token is INVALID.')
                retry_count = retry_count + 1

                logger.info('Retryin in 5 seconds')
                time.sleep(5)    
        except Exception as e:
            logger.error(e)
            logger.info('Retryin in 5 seconds')
            retry_count = retry_count + 1
            time.sleep(5)
    return False, "Slot Booking Failed. Please Try again in Sometime."
예제 #3
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--token", help="Pass token directly")
    parser.add_argument("--mobile", help="Pass mobile directly")
    parser.add_argument("--kvdb-bucket", help="Pass kvdb.io bucket directly")
    parser.add_argument("--config", help="Config file name")
    parser.add_argument(
        "--no-tty",
        help="Do not ask any terminal inputs. Proceed with smart choices",
        action="store_false",
    )

    args = parser.parse_args()

    if args.config:
        filename = args.config
    else:
        filename = "vaccine-booking-details-"

    if args.mobile:
        mobile = args.mobile
    else:
        mobile = None

    if args.kvdb_bucket:
        kvdb_bucket = args.kvdb_bucket
    else:
        kvdb_bucket = KVDB_BUCKET

    print("Running Script")
    beep(500, 150)

    try:
        base_request_header = {
            "User-Agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
            "origin": "https://selfregistration.cowin.gov.in/",
            "referer": "https://selfregistration.cowin.gov.in/",
        }

        token = None
        otp_pref = "n"
        if args.token:
            token = args.token
        else:
            if mobile is None:
                mobile = input("Enter the registered mobile number: ")
            if not args.config:
                filename = filename + mobile + ".json"
            if not kvdb_bucket:
                otp_pref = (input(
                    "\nDo you want to enter OTP manually, instead of auto-read? \nRemember selecting n would require some setup described in README (y/n Default n): "
                ) if args.no_tty else "n")
                otp_pref = otp_pref if otp_pref else "n"
                if otp_pref == "n":
                    kvdb_bucket = (input(
                        "Please refer KVDB setup in ReadMe to setup your own KVDB bucket. Please enter your KVDB bucket value here: "
                    ) if args.no_tty and kvdb_bucket is None else kvdb_bucket)
                    if not kvdb_bucket:
                        print(
                            "Sorry, having your private KVDB bucket is mandatory. Please refer ReadMe and create your own private KVBD bucket."
                        )
                        sys.exit()
            if kvdb_bucket:
                print(
                    "\n### Note ### Please make sure the URL configured in the IFTTT/Shortcuts app on your phone is: "
                    + "https://kvdb.io/" + kvdb_bucket + "/" + mobile + "\n")

            while token is None:
                if otp_pref == "n":
                    try:
                        token = generate_token_OTP(mobile, base_request_header,
                                                   kvdb_bucket)
                    except Exception as e:
                        print(str(e))
                        print("OTP Retrying in 5 seconds")
                        time.sleep(5)
                elif otp_pref == "y":
                    token = generate_token_OTP_manual(mobile,
                                                      base_request_header)

        request_header = copy.deepcopy(base_request_header)
        request_header["Authorization"] = f"Bearer {token}"

        if os.path.exists(filename):
            print(
                "\n=================================== Note ===================================\n"
            )
            print(
                f"Info from perhaps a previous run already exists in {filename} in this directory."
            )
            print(
                f"IMPORTANT: If this is your first time running this version of the application, DO NOT USE THE FILE!"
            )
            try_file = (input(
                "Would you like to see the details and confirm to proceed? (y/n Default y): "
            ) if args.no_tty else "y")
            try_file = try_file if try_file else "y"

            if try_file == "y":
                collected_details = get_saved_user_info(filename)
                print(
                    "\n================================= Info =================================\n"
                )
                display_info_dict(collected_details)

                file_acceptable = (
                    input("\nProceed with above info? (y/n Default y): ")
                    if args.no_tty else "y")
                file_acceptable = file_acceptable if file_acceptable else "y"

                if file_acceptable != "y":
                    collected_details = collect_user_details(request_header)
                    save_user_info(filename, collected_details)

            else:
                collected_details = collect_user_details(request_header)
                save_user_info(filename, collected_details)

        else:
            collected_details = collect_user_details(request_header)
            save_user_info(filename, collected_details)
            confirm_and_proceed(collected_details, args.no_tty)

        # HACK: Temporary workaround for not supporting reschedule appointments
        beneficiary_ref_ids = [
            beneficiary["bref_id"]
            for beneficiary in collected_details["beneficiary_dtls"]
        ]
        beneficiary_dtls = fetch_beneficiaries(request_header)
        if beneficiary_dtls.status_code == 200:
            beneficiary_dtls = [
                beneficiary
                for beneficiary in beneficiary_dtls.json()["beneficiaries"] if
                beneficiary["beneficiary_reference_id"] in beneficiary_ref_ids
            ]
            active_appointments = []
            for beneficiary in beneficiary_dtls:
                expected_appointments = (1 if beneficiary["vaccination_status"]
                                         == "Partially Vaccinated" else 0)
                if len(beneficiary["appointments"]) > expected_appointments:
                    data = beneficiary["appointments"][expected_appointments]
                    beneficiary_data = {
                        "name": data["name"],
                        "state_name": data["state_name"],
                        "dose": data["dose"],
                        "date": data["date"],
                        "slot": data["slot"],
                    }
                    active_appointments.append({
                        "beneficiary":
                        beneficiary["name"],
                        **beneficiary_data
                    })

            if active_appointments:
                print(
                    "The following appointments are active! Please cancel them manually first to continue"
                )
                display_table(active_appointments)
                beep(WARNING_BEEP_DURATION[0], WARNING_BEEP_DURATION[1])
                return
        else:
            print(
                "WARNING: Failed to check if any beneficiary has active appointments. Please cancel before using this script"
            )
            if args.no_tty:
                input("Press any key to continue execution...")

        info = SimpleNamespace(**collected_details)

        if info.find_option == 1:
            disable_re_assignment_feature()

        while True:  # infinite-loop
            # create new request_header
            request_header = copy.deepcopy(base_request_header)
            request_header["Authorization"] = f"Bearer {token}"

            # call function to check and book slots
            try:
                token_valid = is_token_valid(token)

                # token is invalid ?
                # If yes, generate new one
                if not token_valid:
                    print("Token is INVALID.")
                    token = None
                    while token is None:
                        if otp_pref == "n":
                            try:
                                token = generate_token_OTP(
                                    mobile, base_request_header, kvdb_bucket)
                            except Exception as e:
                                print(str(e))
                                print("OTP Retrying in 5 seconds")
                                time.sleep(5)
                        elif otp_pref == "y":
                            token = generate_token_OTP_manual(
                                mobile, base_request_header)

                check_and_book(
                    request_header,
                    info.beneficiary_dtls,
                    info.location_dtls,
                    info.pin_code_location_dtls,
                    info.find_option,
                    info.search_option,
                    min_slots=info.minimum_slots,
                    ref_freq=info.refresh_freq,
                    # auto_book=info.auto_book,
                    start_date=info.start_date,
                    vaccine_type=info.vaccine_type,
                    fee_type=info.fee_type,
                    mobile=mobile,
                    # captcha_automation=info.captcha_automation,
                    dose_num=get_dose_num(collected_details),
                )
            except Exception as e:
                print(str(e))
                print("Retryin in 5 seconds")
                time.sleep(5)

    except Exception as e:
        print(str(e))
        print("Exiting Script")
        os.system("pause")
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--token', help='Pass token directly')
    args = parser.parse_args()

    filename = 'vaccine-booking-details.json'
    mobile = None

    print('Running Script')
    beep(500, 150)

    try:
        base_request_header = {
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
        }

        if args.token:
            token = args.token
        else:
            mobile = input("Enter the registered mobile number: ")
            token = generate_token_OTP(mobile, base_request_header)

        request_header = copy.deepcopy(base_request_header)
        request_header["Authorization"] = f"Bearer {token}"

        if os.path.exists(filename):
            print(
                "\n=================================== Note ===================================\n"
            )
            print(
                f"Info from perhaps a previous run already exists in {filename} in this directory."
            )
            print(
                f"IMPORTANT: If this is your first time running this version of the application, DO NOT USE THE FILE!"
            )
            try_file = input(
                "Would you like to see the details and confirm to proceed? (y/n Default y): "
            )
            try_file = try_file if try_file else 'y'

            if try_file == 'y':
                collected_details = get_saved_user_info(filename)
                print(
                    "\n================================= Info =================================\n"
                )
                display_info_dict(collected_details)

                file_acceptable = input(
                    "\nProceed with above info? (y/n Default n): ")
                file_acceptable = file_acceptable if file_acceptable else 'n'

                if file_acceptable != 'y':
                    collected_details = collect_user_details(request_header)
                    save_user_info(filename, collected_details)

            else:
                collected_details = collect_user_details(request_header)
                save_user_info(filename, collected_details)

        else:
            collected_details = collect_user_details(request_header)
            save_user_info(filename, collected_details)
            confirm_and_proceed(collected_details)

        info = SimpleNamespace(**collected_details)

        token_valid = True
        while token_valid:
            request_header = copy.deepcopy(base_request_header)
            request_header["Authorization"] = f"Bearer {token}"

            # call function to check and book slots
            token_valid = check_and_book(request_header,
                                         info.beneficiary_dtls,
                                         info.location_dtls,
                                         info.search_option,
                                         min_slots=info.minimum_slots,
                                         ref_freq=info.refresh_freq,
                                         auto_book=info.auto_book,
                                         start_date=info.start_date,
                                         vaccine_type=info.vaccine_type,
                                         fee_type=info.fee_type)

            # check if token is still valid
            beneficiaries_list = requests.get(BENEFICIARIES_URL,
                                              headers=request_header)
            if beneficiaries_list.status_code == 200:
                token_valid = True

            else:
                # if token invalid, regenerate OTP and new token
                beep(WARNING_BEEP_DURATION[0], WARNING_BEEP_DURATION[1])
                print('Token is INVALID.')
                token_valid = False

                tryOTP = input('Try for a new Token? (y/n Default y): ')
                if tryOTP.lower() == 'y' or not tryOTP:
                    if not mobile:
                        mobile = input("Enter the registered mobile number: ")
                    token = generate_token_OTP(mobile, base_request_header)
                    token_valid = True
                else:
                    print("Exiting")
                    os.system("pause")

    except Exception as e:
        print(str(e))
        print('Exiting Script')
        os.system("pause")
예제 #5
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--token', help='Pass token directly')
    args = parser.parse_args()

    mobile = None
    try:
        if args.token:
            token = args.token
        else:
            mobile = input("Enter the registered mobile number: ")
            token = generate_token_OTP_pin(mobile)

        request_header = {"Authorization": f"Bearer {token}"}

        # Get Beneficiaries
        print("Fetching registered beneficiaries.. ")
        beneficiary_dtls = get_beneficiaries_pin(request_header)

        if len(beneficiary_dtls) == 0:
            print("There should be at least one beneficiary. Exiting.")
            os.system("pause")
            sys.exit(1)

        # Make sure all beneficiaries have the same type of vaccine
        vaccine_types = [
            beneficiary['vaccine'] for beneficiary in beneficiary_dtls
        ]
        vaccines = Counter(vaccine_types)

        if len(vaccines.keys()) != 1:
            print(
                f"All beneficiaries in one attempt should have the same vaccine type. Found {len(vaccines.keys())}"
            )
            os.system("pause")
            sys.exit(1)

        # Collect vaccination center preferance
        mode = int(
            input("""
        ##########################################

                SELECT MODE OF BOOKING
                
        1. Enter 0 for District wise search
        2. Enter 1 for Pincode wise search
        
        ##########################################
        """))
        if mode == 0:
            district_dtls = get_districts()
            # Set filter condition
            minimum_slots = int(
                input('Filter out centers with availability less than: '))
            minimum_slots = minimum_slots if minimum_slots > len(
                beneficiary_dtls) else len(beneficiary_dtls)

            token_valid = True
            while token_valid:
                request_header = {"Authorization": f"Bearer {token}"}

                # call function to check and book slots
                token_valid = check_and_book(request_header, beneficiary_dtls,
                                             district_dtls, minimum_slots)

                # check if token is still valid
                beneficiaries_list = requests.get(BENEFICIARIES_URL,
                                                  headers=request_header)
                if beneficiaries_list.status_code == 200:
                    token_valid = True

                else:
                    # if token invalid, regenerate OTP and new token
                    beep(WARNING_BEEP_DURATION[0], WARNING_BEEP_DURATION[1])
                    print('Token is INVALID.')
                    token_valid = False

                    tryOTP = input('Try for a new Token? (y/n): ')
                    if tryOTP.lower() == 'y':
                        if mobile:
                            tryOTP = input(
                                f"Try for OTP with mobile number {mobile}? (y/n) : "
                            )
                            if tryOTP.lower() == 'y':
                                token = generate_token_OTP(mobile)
                                token_valid = True
                            else:
                                token_valid = False
                                print("Exiting")
                        else:
                            mobile = input(
                                f"Enter 10 digit mobile number for new OTP generation? : "
                            )
                            token = generate_token_OTP(mobile)
                            token_valid = True
                    else:
                        print("Exiting")
                        os.system("pause")

        else:
            pincode = int(input("Enter Pincode: "))

            # Set filter condition
            minimum_slots = int(
                input('Filter out centers with availability less than: '))
            minimum_slots = minimum_slots if minimum_slots > len(
                beneficiary_dtls) else len(beneficiary_dtls)

            token_valid = True
            while token_valid:
                request_header = {"Authorization": f"Bearer {token}"}

                # call function to check and book slots
                token_valid = check_and_book_pin(request_header,
                                                 beneficiary_dtls, pincode,
                                                 minimum_slots)

                # check if token is still valid
                beneficiaries_list = requests.get(BENEFICIARIES_URL,
                                                  headers=request_header)
                if beneficiaries_list.status_code == 200:
                    token_valid = True

                else:
                    # if token invalid, regenerate OTP and new token
                    beep_pin(WARNING_BEEP_DURATION[0],
                             WARNING_BEEP_DURATION[1])
                    print('Token is INVALID.')
                    token_valid = False

                    tryOTP = input('Try for a new Token? (y/n): ')
                    if tryOTP.lower() == 'y':
                        if mobile:
                            tryOTP = input(
                                f"Try for OTP with mobile number {mobile}? (y/n) : "
                            )
                            if tryOTP.lower() == 'y':
                                token = generate_token_OTP_pin(mobile)
                                token_valid = True
                            else:
                                token_valid = False
                                print("Exiting")
                        else:
                            mobile = input(
                                f"Enter 10 digit mobile number for new OTP generation? : "
                            )
                            token = generate_token_OTP_pin(mobile)
                            token_valid = True
                    else:
                        print("Exiting")
                        os.system("pause")

    except Exception as e:
        print(str(e))
        print('Exiting Script')
        os.system("pause")
예제 #6
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--token', help='Pass token directly')
    args = parser.parse_args()

    mobile = None
    try:
        base_request_header = {
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
        }

        if args.token:
            token = args.token
        else:
            mobile = input("Enter the registered mobile number: ")
            token = generate_token_OTP(mobile, base_request_header)

        request_header = copy.deepcopy(base_request_header)
        request_header["Authorization"] = f"Bearer {token}"

        # Get Beneficiaries
        print("Fetching registered beneficiaries.. ")
        beneficiary_dtls = get_beneficiaries(request_header)

        if len(beneficiary_dtls) == 0:
            print("There should be at least one beneficiary. Exiting.")
            os.system("pause")
            sys.exit(1)

        # Make sure all beneficiaries have the same type of vaccine
        vaccine_types = [
            beneficiary['vaccine'] for beneficiary in beneficiary_dtls
        ]
        vaccines = Counter(vaccine_types)

        if len(vaccines.keys()) != 1:
            print(
                f"All beneficiaries in one attempt should have the same vaccine type. Found {len(vaccines.keys())}"
            )
            os.system("pause")
            sys.exit(1)

        print(
            "\n================================= Location Info =================================\n"
        )
        # get search method to use
        search_option = input(
            """Search by Pincode? Or by State/District? \nEnter 1 for Pincode or 2 for State/District. (Default 2) : """
        )
        search_option = int(search_option) if int(search_option) in [1, 2
                                                                     ] else 2

        if search_option == 2:
            # Collect vaccination center preferance
            location_dtls = get_districts(request_header)

        else:
            # Collect vaccination center preferance
            location_dtls = get_pincodes()

        print(
            "\n================================= Additional Info =================================\n"
        )

        # Set filter condition
        minimum_slots = input(
            f'Filter out centers with availability less than ? Minimum {len(beneficiary_dtls)} : '
        )
        if minimum_slots:
            minimum_slots = int(minimum_slots) if int(minimum_slots) >= len(
                beneficiary_dtls) else len(beneficiary_dtls)
        else:
            minimum_slots = len(beneficiary_dtls)

        # Get refresh frequency
        refresh_freq = input(
            'How often do you want to refresh the calendar (in seconds)? Default 15. Minimum 5. : '
        )
        refresh_freq = int(
            refresh_freq) if refresh_freq and int(refresh_freq) >= 5 else 15

        # Get search start date
        start_date = input(
            'Search for next seven day starting from when?\nUse 1 for today, 2 for tomorrow, or provide a date in the format yyyy-mm-dd. Default 2: '
        )
        if not start_date:
            start_date = 2
        elif start_date in ['1', '2']:
            start_date = int(start_date)
        else:
            try:
                datetime.datetime.strptime(start_date, '%Y-%m-%d')
            except ValueError:
                start_date = 2

        print(
            "\n=========== CAUTION! =========== CAUTION! CAUTION! =============== CAUTION! =======\n"
        )
        print(
            " ==== BE CAREFUL WITH THIS OPTION! AUTO-BOOKING WILL BOOK THE FIRST AVAILABLE CENTRE, DATE, AND SLOT! ==== "
        )
        auto_book = input(
            "Do you want to enable auto-booking? (yes-please or no): ")

        token_valid = True
        while token_valid:
            request_header = copy.deepcopy(base_request_header)
            request_header["Authorization"] = f"Bearer {token}"

            # call function to check and book slots
            token_valid = check_and_book(request_header,
                                         beneficiary_dtls,
                                         location_dtls,
                                         search_option,
                                         min_slots=minimum_slots,
                                         ref_freq=refresh_freq,
                                         auto_book=auto_book,
                                         start_date=start_date)

            # check if token is still valid
            beneficiaries_list = requests.get(BENEFICIARIES_URL,
                                              headers=request_header)
            if beneficiaries_list.status_code == 200:
                token_valid = True

            else:
                # if token invalid, regenerate OTP and new token
                beep(WARNING_BEEP_DURATION[0], WARNING_BEEP_DURATION[1])
                print('Token is INVALID.')
                token_valid = False

                tryOTP = input('Try for a new Token? (y/n): ')
                if tryOTP.lower() == 'y':
                    if mobile:
                        tryOTP = input(
                            f"Try for OTP with mobile number {mobile}? (y/n) : "
                        )
                        if tryOTP.lower() == 'y':
                            token = generate_token_OTP(mobile,
                                                       base_request_header)
                            token_valid = True
                        else:
                            token_valid = False
                            print("Exiting")
                    else:
                        mobile = input(
                            f"Enter 10 digit mobile number for new OTP generation? : "
                        )
                        token = generate_token_OTP(mobile, base_request_header)
                        token_valid = True
                else:
                    print("Exiting")
                    os.system("pause")

    except Exception as e:
        print(str(e))
        print('Exiting Script')
        os.system("pause")
예제 #7
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--token', help='Pass token directly')
    args = parser.parse_args()

    mobile = None
    try:
        if args.token:
            token = args.token
        else:
            mobile = input("Enter the registered mobile number: ")
            token = generate_token_OTP(mobile)

        request_header = {"Authorization": f"Bearer {token}"}

        # Get Beneficiaries
        print("Fetching registered beneficiaries.. ")
        beneficiary_dtls = get_beneficiaries(request_header)

        if len(beneficiary_dtls) == 0:
            print("There should be at least one beneficiary. Exiting.")
            os.system("pause")
            sys.exit(1)

        # Make sure all beneficiaries have the same type of vaccine
        vaccine_types = [
            beneficiary['vaccine'] for beneficiary in beneficiary_dtls
        ]
        vaccines = Counter(vaccine_types)

        if len(vaccines.keys()) != 1:
            print(
                f"All beneficiaries in one attempt should have the same vaccine type. Found {len(vaccines.keys())}"
            )
            os.system("pause")
            sys.exit(1)

        # Collect vaccination center preferance
        district_dtls = get_districts()

        print(
            "================================= Additional Info ================================="
        )

        # Set filter condition
        minimum_slots = int(
            input(
                f'Filter out centers with availability less than ? Minimum {len(beneficiary_dtls)} : '
            ))
        minimum_slots = minimum_slots if minimum_slots >= len(
            beneficiary_dtls) else len(beneficiary_dtls)

        # Get refresh frequency
        refresh_freq = input(
            'How often do you want to refresh the calendar (in seconds)? Default 15. Minimum 5. : '
        )
        refresh_freq = int(
            refresh_freq) if refresh_freq and int(refresh_freq) >= 5 else 15

        token_valid = True
        while token_valid:
            request_header = {"Authorization": f"Bearer {token}"}

            # call function to check and book slots
            token_valid = check_and_book(request_header,
                                         beneficiary_dtls,
                                         district_dtls,
                                         min_slots=minimum_slots,
                                         ref_freq=refresh_freq)

            # check if token is still valid
            beneficiaries_list = requests.get(BENEFICIARIES_URL,
                                              headers=request_header)
            if beneficiaries_list.status_code == 200:
                token_valid = True

            else:
                # if token invalid, regenerate OTP and new token
                beep(WARNING_BEEP_DURATION[0], WARNING_BEEP_DURATION[1])
                print('Token is INVALID.')
                token_valid = False

                tryOTP = input('Try for a new Token? (y/n): ')
                if tryOTP.lower() == 'y':
                    if mobile:
                        tryOTP = input(
                            f"Try for OTP with mobile number {mobile}? (y/n) : "
                        )
                        if tryOTP.lower() == 'y':
                            token = generate_token_OTP(mobile)
                            token_valid = True
                        else:
                            token_valid = False
                            print("Exiting")
                    else:
                        mobile = input(
                            f"Enter 10 digit mobile number for new OTP generation? : "
                        )
                        token = generate_token_OTP(mobile)
                        token_valid = True
                else:
                    print("Exiting")
                    os.system("pause")

    except Exception as e:
        print(str(e))
        print('Exiting Script')
        os.system("pause")
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--token', help='Pass token directly')
    args = parser.parse_args()

    filename = 'vaccine-booking-details-'
    mobile = None

    print('Running Script')
    beep(500, 150)

    try:
        base_request_header = {
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
        }

        token = None
        if args.token:
            token = args.token
        else:
            mobile = input("Enter the registered mobile number: ")
            filename = filename + mobile + ".json"
            otp_pref = input(
                "\nDo you want to enter OTP manually, instead of auto-read? \nRemember selecting n would require some setup described in README (y/n Default n): "
            )
            otp_pref = otp_pref if otp_pref else "n"
            while token is None:
                if otp_pref == "n":
                    try:
                        token = generate_token_OTP(mobile, base_request_header)
                    except Exception as e:
                        print(str(e))
                        print('OTP Retrying in 5 seconds')
                        time.sleep(5)
                elif otp_pref == "y":
                    token = generate_token_OTP_manual(mobile,
                                                      base_request_header)

        request_header = copy.deepcopy(base_request_header)
        request_header["Authorization"] = f"Bearer {token}"

        if os.path.exists(filename):
            print(
                "\n=================================== Note ===================================\n"
            )
            print(
                f"Info from perhaps a previous run already exists in {filename} in this directory."
            )
            print(
                f"IMPORTANT: If this is your first time running this version of the application, DO NOT USE THE FILE!"
            )
            try_file = input(
                "Would you like to see the details and confirm to proceed? (y/n Default y): "
            )
            try_file = try_file if try_file else 'y'

            if try_file == 'y':
                collected_details = get_saved_user_info(filename)
                print(
                    "\n================================= Info =================================\n"
                )
                display_info_dict(collected_details)

                file_acceptable = input(
                    "\nProceed with above info? (y/n Default n): ")
                file_acceptable = file_acceptable if file_acceptable else 'n'
                if file_acceptable != 'y':
                    collected_details = collect_user_details(request_header)
                    save_user_info(filename, collected_details)

            else:
                collected_details = collect_user_details(request_header)
                save_user_info(filename, collected_details)

        else:
            collected_details = collect_user_details(request_header)
            save_user_info(filename, collected_details)
            confirm_and_proceed(collected_details)

        # HACK: Temporary workaround for not supporting reschedule appointments
        beneficiary_ref_ids = [
            beneficiary["bref_id"]
            for beneficiary in collected_details["beneficiary_dtls"]
        ]
        beneficiary_dtls = fetch_beneficiaries(request_header)
        if beneficiary_dtls.status_code == 200:
            beneficiary_dtls = [
                beneficiary
                for beneficiary in beneficiary_dtls.json()['beneficiaries'] if
                beneficiary['beneficiary_reference_id'] in beneficiary_ref_ids
            ]
            active_appointments = []
            for beneficiary in beneficiary_dtls:
                expected_appointments = (1 if beneficiary['vaccination_status']
                                         == "Partially Vaccinated" else 0)
                if len(beneficiary['appointments']) > expected_appointments:
                    data = beneficiary['appointments'][expected_appointments]
                    beneficiary_data = {
                        'name': data['name'],
                        'state_name': data['state_name'],
                        'dose': data['dose'],
                        'date': data['date'],
                        'slot': data['slot']
                    }
                    active_appointments.append({
                        "beneficiary":
                        beneficiary['name'],
                        **beneficiary_data
                    })

            if active_appointments:
                print(
                    "The following appointments are active! Please cancel them manually first to continue"
                )
                display_table(active_appointments)
                beep(WARNING_BEEP_DURATION[0], WARNING_BEEP_DURATION[1])
                return
        else:
            print(
                "WARNING: Failed to check if any beneficiary has active appointments. Please cancel before using this script"
            )
            input("Press any key to continue execution...")

        info = SimpleNamespace(**collected_details)

        token_valid = True
        while token_valid:
            request_header = copy.deepcopy(base_request_header)
            request_header["Authorization"] = f"Bearer {token}"

            # call function to check and book slots
            try:
                token_valid = check_and_book(
                    request_header,
                    info.beneficiary_dtls,
                    info.location_dtls,
                    info.search_option,
                    min_slots=info.minimum_slots,
                    ref_freq=info.refresh_freq,
                    auto_book=info.auto_book,
                    start_date=info.start_date,
                    vaccine_type=info.vaccine_type,
                    fee_type=info.fee_type,
                    mobile=mobile,
                    captcha_automation=info.captcha_automation,
                    captcha_automation_api_key=info.captcha_automation_api_key,
                    dose_num=get_dose_num(collected_details))

                # check if token is still valid
                beneficiaries_list = requests.get(BENEFICIARIES_URL,
                                                  headers=request_header)
                if beneficiaries_list.status_code == 200:
                    token_valid = True

                else:
                    # if token invalid, regenerate OTP and new token
                    # beep(WARNING_BEEP_DURATION[0], WARNING_BEEP_DURATION[1])
                    print('Token is INVALID.')
                    token_valid = False
                    token = None

                    while token is None:
                        if otp_pref == "n":
                            try:
                                token = generate_token_OTP(
                                    mobile, base_request_header)
                            except Exception as e:
                                print(str(e))
                                print('OTP Retrying in 5 seconds')
                                time.sleep(5)
                        elif otp_pref == "y":
                            token = generate_token_OTP_manual(
                                mobile, base_request_header)
                    token_valid = True
            except Exception as e:
                print(str(e))
                print('Retryin in 5 seconds')
                time.sleep(5)

    except Exception as e:
        print(str(e))
        print('Exiting Script')
        os.system("pause")
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--token', help='Pass token directly')
    args = parser.parse_args()

    filename = 'details.json'
    mobile = None

    print('Running Script')

    try:
        base_request_header = {
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
        }

        if args.token:
            token = args.token
        else:
            mobile = input("Enter the registered mobile number: ")
            token = generate_token_OTP(mobile, base_request_header)

        request_header = copy.deepcopy(base_request_header)
        request_header["Authorization"] = f"Bearer {token}"

        if os.path.exists(filename):
            print(
                "\n=================================== Note ===================================\n"
            )
            print(f"Fetching details from {filename} in this directory.")

            collected_details = get_saved_user_info(filename)
            display_info_dict(collected_details)

        else:
            raise "No Details Available"

        info = SimpleNamespace(**collected_details)

        token_valid = True
        while token_valid:
            request_header = copy.deepcopy(base_request_header)
            request_header["Authorization"] = f"Bearer {token}"

            # call function to check and book slots
            token_valid = check_and_book(
                request_header,
                info.beneficiary_dtls,
                info.location_dtls,
                info.search_option,
                min_slots=info.minimum_slots,
                ref_freq=info.refresh_freq,
                auto_book=info.auto_book,
                start_date=info.start_date,
                vaccine_type=info.vaccine_type,
                fee_type=info.fee_type,
                preferred_centres=info.preferred_centres)

            # check if token is still valid
            beneficiaries_list = requests.get(BENEFICIARIES_URL,
                                              headers=request_header)
            if beneficiaries_list.status_code == 200:
                token_valid = True

            else:
                # if token invalid, regenerate OTP and new token
                print('Token is INVALID.')
                token_valid = False

                tryOTP = input('Try for a new Token? (y/n Default y): ')
                if tryOTP.lower() == 'y' or not tryOTP:
                    if not mobile:
                        mobile = input("Enter the registered mobile number: ")
                    token = generate_token_OTP(mobile, base_request_header)
                    token_valid = True
                else:
                    print("Exiting")
                    os.system("pause")

    except Exception as e:
        print(str(e))
        print('Exiting Script')
        os.system("pause")