Ejemplo n.º 1
0
def build_pages(id_):
    """Walk user through building multiple new page documents.

    :return a page object
    """
    pages = list()
    logging.info("Getting Page Metadata")

    # Looks through to get the number of pages as a number with error checking
    num_pages = get_number("    How many pages do you need?")

    for page_num in range(int(num_pages)):
        logging.info(f"Building Page {page_num + 1}")
        temp_page = Page()
        auto_forward = yes_no_prompt("    Will this page auto forward?")
        temp_page.capture_credentials = False
        temp_page.capture_passwords = False

        if auto_forward == "yes":
            setattr(temp_page, "name", f"{id_}-{page_num+1}-AutoForward")
            temp_page.html = AUTO_FORWARD
            temp_page.redirect_url = get_input("    URL to Redirect to:")

        else:
            temp_page.name = f"{id_}-{page_num+1}-Landing"
            forward = yes_no_prompt("    Will this page forward after action? (yes/no)")
            if forward == "yes":
                temp_page.redirect_url = get_input("    URL to Redirect to:")

            # Receives the file name and checks if it exists.
            while True:
                try:
                    landing_file_name = get_input("Landing Page File name:")
                    # Drops .html if included so it can always be added as fail safe.
                    landing_file_name = landing_file_name.split(".", 1)[0]

                    with open(landing_file_name + ".html") as landingFile:
                        temp_page.html = landingFile.read()

                    break
                except EnvironmentError:
                    logging.critical(
                        f"ERROR- Landing Page File not found: {landing_file_name}.html"
                    )
                    print("Please try again...")

        # Debug page information
        logging.debug(f"Page Name: {temp_page.name}")
        logging.debug(f"Redirect ULR: {temp_page.redirect_url}")
        logging.debug(f"Capture Credentials: {temp_page.capture_credentials}")
        logging.debug(f"Capture Passwords: {temp_page.capture_passwords}")

        temp_page = review_page(temp_page)
        pages.append(temp_page)

    return pages
Ejemplo n.º 2
0
def review_page(page):
    """Review page."""
    # Loops until not changes are required.
    while True:
        print("\n")
        page_keys = list()
        for key, value in page.as_dict().items():
            if key != "html":
                print("{}: {}".format(key, value))
                page_keys.append(key)
        if yes_no_prompt("Changes Required") == "yes":
            completer = WordCompleter(page_keys, ignore_case=True)

            # Loops to get valid Field name form user.
            while True:
                update_key = prompt(
                    "Which Field: ",
                    completer=completer,
                    validator=BlankInputValidator(),
                ).lower()

                try:
                    update_value = prompt(
                        "{}: ".format(update_key),
                        default=page.as_dict()[update_key],
                        validator=BlankInputValidator(),
                    )
                except KeyError:
                    logging.error("Incorrect Field!")
                else:
                    setattr(page, update_key, update_value)
                    break
        else:
            break
    return page
Ejemplo n.º 3
0
def build_groups(id, target_domains):
    """Build groups."""
    logging.info("Getting Group Metadata")
    groups = list()

    # Looks through to get the number of groups as a number with error checking
    num_groups = get_number("    How many groups do you need?")

    if num_groups > 1:
        logging.warning("NOTE: Please load each group as a different CSV")

    labels = yes_no_prompt("    Are there customer labels?")

    for group_num in range(int(num_groups)):
        logging.info(f"Building Group {group_num + 1}")

        new_group = Group(name=f"{id}-G{str(group_num + 1)}")

        new_group.targets = build_emails(target_domains, labels)

        logging.info(f"Group Ready: {new_group.name}")
        groups.append(new_group)

    return groups
Ejemplo n.º 4
0
def build_emails(domains, labels):
    """Build emails."""
    # Holds list of Users to be added to group.
    targets = list()
    domain_miss_match = list()
    format_error = list()

    # Receives the file name and checks if it exists.
    while True:
        try:
            email_file_name = get_input("    E-mail CSV name:")
            # Drops .csv if included so it can always be added as fail safe.
            email_file_name = email_file_name.split(".", 1)[0]

            with open(email_file_name + ".csv") as csv_file:
                read_csv = csv.reader(csv_file, delimiter=",")
                next(read_csv)

                for row in read_csv:
                    # Checks e-mail format, if false prints message.
                    if not validate_email(row[2]):
                        format_error.append(row)
                    # Checks that the domain matches, if false prints message,
                    elif not validate_domain(row[2], domains):
                        domain_miss_match.append(row)

                    else:
                        target = Target(first_name=row[0],
                                        last_name=row[1],
                                        email=row[2])
                        target = target_add_label(labels, row, target)
                        targets.append(target)

                # Works through emails found to include formatting errors.
                print("\n")
                if len(format_error) < 2:
                    for email in format_error:
                        email[2] = prompt(
                            "Correct Email Formatting: ",
                            default=email[2],
                            validator=EmailValidator(),
                        )
                        if not validate_domain(email[2], domains):
                            domain_miss_match.append(email)
                        else:
                            target = Target(first_name=email[0],
                                            last_name=email[1],
                                            email=email[2])
                            target = target_add_label(labels, email, target)
                            targets.append(target)
                else:
                    logging.error("{} Formatting Errors".format(
                        len(format_error)))
                    if yes_no_prompt(
                            "Would you like to correct each here") == "yes":
                        for email in format_error:
                            email[2] = prompt(
                                "Correct Email Formatting: ",
                                default=email[2],
                                validator=EmailValidator(),
                            )
                            if not validate_domain(email[2], domains):
                                domain_miss_match.append(email)
                            else:
                                target = Target(first_name=row[0],
                                                last_name=row[1],
                                                email=row[2])
                                target = target_add_label(
                                    labels, email, target)
                                targets.append(target)
                    else:
                        logging.warning(
                            "Incorrectly formatted Emails will not be added, continuing..."
                        )

                # Works through emails found to have domain miss match.
                if len(domain_miss_match) < 2:
                    for email in domain_miss_match:
                        email[2] = prompt(
                            "Correct Email Domain: ",
                            default=email[2],
                            validator=EmailValidator(),
                        )
                else:
                    logging.error("{} Domain Miss Match Errors".format(
                        len(format_error)))
                    if yes_no_prompt(
                            "Would you like to correct each here") == "yes":
                        for email in domain_miss_match:
                            while True:
                                email[2] = prompt(
                                    "Correct Email Domain: ",
                                    default=email[2],
                                    validator=EmailValidator(),
                                )
                                if validate_domain(email[2], domains):
                                    target = Target(
                                        first_name=row[0],
                                        last_name=row[1],
                                        email=row[2],
                                    )
                                    target = target_add_label(
                                        labels, email, target)
                                    targets.append(target)
                                    break
                    else:
                        logging.warning(
                            "Incorrectly formatted Emails will not be added, continuing..."
                        )

            if len(targets) == 0:
                raise Exception("No targets loaded")
            break
        except EnvironmentError:
            logging.critical(
                "Email File not found: {}.csv".format(email_file_name))
            print("\t Please try again...")
        except Exception:
            # Logs and indicates the user should correct before clicking ok which will re-run the import.
            logging.critical("No targets loaded")
            message_dialog(
                title="Missing Targets",
                text=
                "No targets loaded from file, please check file before clicking Ok.",
            )
            continue

    return targets
Ejemplo n.º 5
0
def review_campaign(campaign):
    """Review a campaign."""
    # TODO Review group name and page name.
    campaign_dict = campaign.as_dict()
    while True:
        print("\n")

        # Outputs relevent fields except Email Template.
        for field, value in campaign_dict.items():
            if field in [
                    "launch_date",
                    "complete_date",
                    "url",
                    "name",
                    "group_name",
                    "page_name",
            ]:
                print("{}: {}".format(field.replace("_", " ").title(), value))
            elif field == "smtp":
                print("SMTP: ")
                for smtp_key, smtp_value in campaign_dict["smtp"].items():
                    print("\t{}: {}".format(
                        smtp_key.replace("_", " ").title(), smtp_value))

        if yes_no_prompt("\nChanges Required") == "yes":
            completer = WordCompleter(campaign_dict.keys().remove("template"),
                                      ignore_case=True)
            # Loops to get valid Field name form user.
            while True:
                update_key = prompt(
                    "Which Field: ",
                    completer=completer,
                    validator=BlankInputValidator(),
                ).lower()
                if update_key != "smtp":
                    try:
                        update_value = prompt(
                            "{}: ".format(update_key),
                            default=campaign_dict[update_key],
                            validator=BlankInputValidator(),
                        )
                    except KeyError:
                        logging.error("Incorrect Field!")
                    else:
                        setattr(campaign, update_key, update_value)
                        break
                else:
                    # Builds a word completion list with each word of the option being capitalized.
                    sub_completer = WordCompleter(
                        list(
                            map(
                                lambda sub_field: sub_field.replace("_", " ").
                                title(),
                                campaign_dict[update_key].as_dict().keys(),
                            )),
                        ignore_case=True,
                    )
                    update_sub = prompt(
                        "Which Indicator: ",
                        completer=sub_completer,
                        validator=BlankInputValidator(),
                    ).lower()
                    try:
                        update_value = prompt(
                            "{}: ".format(update_sub),
                            default=campaign_dict[update_key].as_dict()
                            [update_sub],
                            validator=BlankInputValidator(),
                        )
                    except KeyError:
                        logging.error("Incorrect Field!")
                    else:
                        setattr(campaign_dict[update_key], update_sub,
                                update_value)
                        break
        else:
            break

    return campaign