Example #1
0
def add_cands(request):
    if request.method != ATTR.POST:
        raise Http404()
    next_page = request.POST.get(ATTR.NEXT, '/')

    cand_csv_file = request.FILES.get(ATTR.CAND_CSV, None)
    if not cand_csv_file.name.endswith(ATTR.CSV_ENDING):
        messages.error(request, "Please input a csv file!")
    decoded_cand_csv_file = cand_csv_file.read().decode(
        ATTR.UTF8SIG).splitlines()
    cand_csv = csv.DictReader(decoded_cand_csv_file)

    candidate_group = Group.objects.get(name=ATTR.CANDIDATE)

    for row in cand_csv:
        try:
            candidatedto = CandidateDTO(row)
        except AssertionError as e:
            messages.error(request, "Invalid candidate information: " + str(e))
            return redirect(next_page)

        password = BaseUserManager.make_random_password(
            None, length=DEFAULT_RANDOM_PASSWORD_LENGTH)
        new_cand = User.objects.create_user(
            candidatedto.username,
            email=candidatedto.email,
            password=password,
        )
        new_cand.first_name = candidatedto.first_name
        new_cand.last_name = candidatedto.last_name
        new_cand.save()
        candidate_group.user_set.add(new_cand)

        subject = "[HKN] Candidate account"
        html_content = render_to_string(
            "candidate/new_candidate_account_email.html", {
                "subject": subject,
                "first_name": candidatedto.first_name,
                "username": candidatedto.username,
                "password": password,
                "website_link": request.build_absolute_uri("/accounts/login/"),
                "img_link": get_rand_photo(),
            })
        msg = EmailMultiAlternatives(subject, subject,
                                     "*****@*****.**",
                                     [candidatedto.email])
        msg.attach_alternative(html_content, "text/html")
        msg.send()

    messages.success(request, "Successfully added candidates!")

    return redirect(next_page)
Example #2
0
def send_off_waitlist_email(request, user, event):
    subject = '[HKN] You have gotten off the waitlist for your event'

    event_link = request.build_absolute_uri(
        reverse("events:detail", kwargs={'id': event.id}))
    html_content = render_to_string(
        'events/off_waitlist_email.html', {
            'subject': subject,
            'event_name': event.name,
            'event_link': event_link,
            'img_link': get_rand_photo(),
        })
    msg = EmailMultiAlternatives(subject, subject, settings.NO_REPLY_EMAIL,
                                 [user.email])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
Example #3
0
def send_bitbyte_confirm_email(request, bitbyte, confirmed):
    subject = '[HKN] Your bit-byte request was reviewed'
    participant_emails = [part.email for part in bitbyte.participants.all()]

    bitbyte_link = request.build_absolute_uri(reverse("candidate:bitbyte"))
    html_content = render_to_string(
        'candidate/bitbyte_confirm_email.html', {
            'subject': subject,
            'confirmed': confirmed,
            'participants': bitbyte.participants.all(),
            'bitbyte_link': bitbyte_link,
            'img_link': get_rand_photo(),
        })
    msg = EmailMultiAlternatives(subject, subject, settings.NO_REPLY_EMAIL,
                                 participant_emails)
    msg.attach_alternative(html_content, "text/html")
    msg.send()
Example #4
0
def send_challenge_confirm_email(request, challenge, confirmed):
    subject = '[HKN] Your officer challenge was reviewed'
    candidate_email = challenge.requester.email

    challenge_link = request.build_absolute_uri(
        reverse("candidate:detail", kwargs={'pk': challenge.id}))
    html_content = render_to_string(
        'candidate/challenge_confirm_email.html', {
            'subject': subject,
            'confirmed': confirmed,
            'officer_name': challenge.officer.get_full_name(),
            'officer_username': challenge.officer.username,
            'challenge_link': challenge_link,
            'img_link': get_rand_photo(),
        })
    msg = EmailMultiAlternatives(subject, subject, settings.NO_REPLY_EMAIL,
                                 [candidate_email])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
Example #5
0
    def send_request_email(self, form):
        subject = '[HKN] Bit-byte request submitted'
        participant_emails = [
            part.email for part in form.instance.participants.all()
        ]

        bitbyte_link = self.request.build_absolute_uri(
            reverse("candidate:bitbyte"))
        html_content = render_to_string(
            'candidate/bitbyte_request_email.html', {
                'subject': subject,
                'requester': self.request.user,
                'participants': form.instance.participants.all(),
                'bitbyte_link': bitbyte_link,
                'img_link': get_rand_photo(),
            })
        msg = EmailMultiAlternatives(subject, subject, settings.NO_REPLY_EMAIL,
                                     participant_emails)
        msg.attach_alternative(html_content, "text/html")
        msg.send()
Example #6
0
    def send_request_email(self, form):
        subject = '[HKN] Confirm Officer Challenge'
        officer_email = form.instance.officer.email

        confirm_link = self.request.build_absolute_uri(
            reverse("candidate:challengeconfirm",
                    kwargs={'pk': form.instance.id}))
        html_content = render_to_string(
            'candidate/challenge_request_email.html', {
                'subject': subject,
                'candidate_name': form.instance.requester.get_full_name(),
                'candidate_username': form.instance.requester.username,
                'confirm_link': confirm_link,
                'img_link': get_rand_photo(),
            })
        msg = EmailMultiAlternatives(subject, subject,
                                     '*****@*****.**',
                                     [officer_email])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
Example #7
0
    def send_request_email(self, form):
        subject = "[HKN] Confirm Officer Challenge"
        officer_email = form.instance.officer.email

        confirm_link = self.request.build_absolute_uri(
            reverse("candidate:challengeconfirm",
                    kwargs={"pk": form.instance.id}))
        html_content = render_to_string(
            "candidate/challenge_request_email.html",
            {
                "subject": subject,
                "candidate_name": form.instance.requester.get_full_name(),
                "candidate_username": form.instance.requester.username,
                "confirm_link": confirm_link,
                "img_link": get_rand_photo(),
            },
        )
        msg = EmailMultiAlternatives(subject, subject, settings.NO_REPLY_EMAIL,
                                     [officer_email])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
Example #8
0
def add_cands_and_email(cand_csv, num_rows, website_login_link, task=None):
    candidate_group = Group.objects.get(name=ATTR.CANDIDATE)
    progress_float = 0.0  # lgtm [py/multiple-definition]
    CAND_ACC_WEIGHT = 0.75
    EMAIL_WEIGHT = 0.25

    # Sanity check progress
    if task is not None:
        task.progress = 1.0
        task.save()

    # Pre-screen and validate data
    new_cand_list = []
    email_set = set()
    username_set = set()
    current_cand_semester = get_current_cand_semester()
    email_passwords = {}
    if current_cand_semester is None:
        error_msg = "Inform CompServ the following: Please add the current semester in CourseSemester."
        error_msg += " "
        error_msg += NO_ACTION_PLS_FIX
        return False, error_msg

    for i, row in enumerate(cand_csv):
        try:
            candidatedto = CandidateDTO(row)
        except AssertionError as e:
            error_msg = "Invalid CSV format. Check that your columns are correctly labeled, there are NO blank rows, and filled out for each row."
            error_msg += " "
            error_msg += NO_ACTION_PLS_FIX
            error_msg += " "
            error_msg += "Candidate error message: {}.".format(e)
            error_msg += " "
            error_msg += "Row Information at row {}: {}.".format(i + 1, row)
            return False, error_msg

        password = BaseUserManager.make_random_password(
            None, length=DEFAULT_RANDOM_PASSWORD_LENGTH)

        duplicate, error_msg = check_duplicates(candidatedto, row, email_set,
                                                username_set, i)
        if duplicate:
            return False, error_msg

        new_cand = User(
            username=candidatedto.username,
            email=candidatedto.email,
        )
        email_set.add(candidatedto.email)
        username_set.add(candidatedto.username)
        new_cand.first_name = candidatedto.first_name
        new_cand.last_name = candidatedto.last_name
        new_cand.set_password(password)
        new_cand_list.append(new_cand)
        email_passwords[new_cand.email] = password

        progress_float = CAND_ACC_WEIGHT * 100 * (i + 1) / num_rows
        if task is not None:
            task.progress = round(progress_float)
            task.save()

    # Reset to CAND_ACC_WEIGHT in case floating point errors
    progress_float = CAND_ACC_WEIGHT * 100
    if task is not None:
        task.progress = round(progress_float)
        task.save()

    num_of_accounts = len(email_set)

    if num_of_accounts != num_rows:
        error_msg = (
            "Internal Error: number of accounts ({}) != number of rows ({})".
            format(num_of_accounts, num_rows))
        error_msg += " "
        error_msg += NO_ACTION_PLS_FIX
        return False, error_msg

    # Release the memory once done
    del email_set
    del username_set

    email_errors = []
    for i, new_cand in enumerate(new_cand_list):
        if i != 0 and i % 50 == 0:
            time.sleep(10)
        new_cand.save()
        candidate_group.user_set.add(new_cand)

        profile = Profile.objects.get(user=new_cand)
        profile.candidate_semester = current_cand_semester
        profile.save()

        subject = "[HKN] Candidate account"
        html_content = render_to_string(
            "candidate/new_candidate_account_email.html",
            {
                "subject": subject,
                "first_name": new_cand.first_name,
                "username": new_cand.username,
                "password": email_passwords[new_cand.email],
                "website_link": website_login_link,
                "img_link": get_rand_photo(),
            },
        )
        if settings.DEBUG:
            print("\n")
            print(new_cand.first_name, new_cand.username, new_cand.email)
            print(html_content)
            print("\n")
        else:
            msg = EmailMultiAlternatives(subject, subject,
                                         settings.NO_REPLY_EMAIL,
                                         [new_cand.email])
            msg.attach_alternative(html_content, "text/html")
            try:
                msg.send()
            except Exception as e:
                email_errors.append((new_cand_list[i].email, str(e)))

        progress_float = (CAND_ACC_WEIGHT * 100) + (EMAIL_WEIGHT * 100 *
                                                    (i + 1) / num_of_accounts)
        if task is not None:
            task.progress = round(progress_float)
            task.save()

    # If gone through everything and no errors
    if len(email_errors) > 0:
        error_msg = (
            "An error occured during the sending of emails. " +
            "Candidate Email and Error Messages: " + str(email_errors) +
            " --- " +
            "Inform CompServ of the errors, and inform the candidates " +
            "to access their accounts by resetting their password " +
            'using "Forget your password?" in the Login page. ' +
            "All {} candidates added!".format(num_of_accounts))
        return False, error_msg
    else:
        return True, "Successfully added {} candidates!".format(
            num_of_accounts)