Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added timeout and loading animation when new judges are added #116

Merged
merged 5 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions client/src/components/admin/add-judges/AddJudgeStatsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import { errorAlert } from '../../../util';

interface JudgeStats {
num: number;
avg_votes: number;
avg_seen: number;
num_active: number;
}

const AddJudgeStatsPanel = () => {
const [stats, setStats] = useState<JudgeStats>({ num: 0, avg_votes: 0, num_active: 0 });
const [stats, setStats] = useState<JudgeStats>({ num: 0, avg_seen: 0, num_active: 0 });
useEffect(() => {
const fetchStats = async () => {
const res = await getRequest('/judge/stats', 'admin');
Expand All @@ -31,7 +31,7 @@ const AddJudgeStatsPanel = () => {
<div className="flex flex-col justify-evenly w-full mt-8">
<div className="flex justify-evenly basis-2/5">
<StatBlock name="Total Judges" value={stats.num} />
<StatBlock name="Average Votes" value={stats.avg_votes} />
<StatBlock name="Average Seen" value={stats.avg_seen} />
<StatBlock name="Active Judges" value={stats.num_active} />
</div>
</div>
Expand Down
5 changes: 4 additions & 1 deletion client/src/components/admin/add-judges/NewJudgeForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import TextArea from '../../TextArea';
import { postRequest } from '../../../api';
import { errorAlert } from '../../../util';
import Checkbox from '../../Checkbox';
import Loading from '../../Loading';

interface NewJudgeData {
name: string;
Expand All @@ -22,11 +23,12 @@ const NewJudgeForm = () => {
const onSubmit: SubmitHandler<NewJudgeData> = async (data) => {
setIsSubmitting(true);

const newdata = { ...data, no_send: noSend }
const newdata: NewJudgeDataFull = { ...data, no_send: noSend };

const res = await postRequest('/judge/new', 'admin', newdata);
if (res.status !== 200) {
errorAlert(res);
setIsSubmitting(false);
return;
}

Expand Down Expand Up @@ -56,6 +58,7 @@ const NewJudgeForm = () => {
</button>
</form>
</div>
<Loading disabled={!isSubmitting} />
</div>
);
};
Expand Down
2 changes: 2 additions & 0 deletions client/src/components/admin/add-judges/UploadCSVForm.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState } from 'react';
import { createHeaders } from '../../../api';
import Loading from '../../Loading';

interface UploadCSVFormProps {
/* The format of the CSV file */
Expand Down Expand Up @@ -180,6 +181,7 @@ const UploadCSVForm = (props: UploadCSVFormProps) => {
</div>
</form>
</div>
<Loading disabled={!isUploading} />
</div>
</>
);
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ services:
- MONGODB_URI=${MONGODB_URI}
- JURY_ADMIN_PASSWORD=${JURY_ADMIN_PASSWORD}
- EMAIL_HOST=${EMAIL_HOST}
- EMAIL_PORT=${EMAIL_PORT}
- EMAIL_PORT=${EMAIL_PORT:587}
- EMAIL_FROM=${EMAIL_FROM}
- EMAIL_FROM_NAME=${EMAIL_FROM_NAME}
- EMAIL_USERNAME=${EMAIL_USERNAME}
Expand Down
13 changes: 10 additions & 3 deletions server/database/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,13 @@ func AggregateStats(db *mongo.Database) (*models.Stats, error) {
// Get the first document from the cursor
var projAvgSeen AvgSeenAgg
projCursor.Next(context.Background())
projCursor.Decode(&projAvgSeen)
err = projCursor.Decode(&projAvgSeen)
if err != nil {
return nil, err
}

// Get the average judge seen using an aggregation pipeline
judgeCursor, err := db.Collection("judge").Aggregate(context.Background(), []gin.H{
judgeCursor, err := db.Collection("judges").Aggregate(context.Background(), []gin.H{
{"$match": gin.H{"active": true}},
{"$group": gin.H{
"_id": nil,
Expand All @@ -60,7 +63,11 @@ func AggregateStats(db *mongo.Database) (*models.Stats, error) {
// Get the first document from the cursor
var judgeAvgSeen AvgSeenAgg
judgeCursor.Next(context.Background())
judgeCursor.Decode(&judgeAvgSeen)
err = judgeCursor.Decode(&judgeAvgSeen)
println(judgeAvgSeen.AvgSeen)
if err != nil {
return nil, err
}

// Create the stats object
var stats models.Stats
Expand Down
65 changes: 62 additions & 3 deletions server/funcs/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ package funcs

import (
"bytes"
"crypto/tls"
"fmt"
"html/template"
"net"
"net/smtp"
"server/config"
"server/models"
"time"

"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
Expand All @@ -23,7 +26,7 @@ func SendJudgeEmail(judge *models.Judge, hostname string) error {
// If sendgrid API key exists, send email with sendgrid
sendgridApiKey := config.GetOptEnv("SENDGRID_API_KEY", "")
if sendgridApiKey != "" {
return SendgridEmail(sendgridApiKey, judge, hostname)
return sendgridEmail(sendgridApiKey, judge, hostname)
}

// Sender info
Expand Down Expand Up @@ -59,7 +62,7 @@ func SendJudgeEmail(judge *models.Judge, hostname string) error {
body.Write(html)

// Send email!
err = smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, body.Bytes())
err = sendEmailWithTimeout(smtpHost, smtpPort, auth, from, to, body.Bytes())
return err
}

Expand Down Expand Up @@ -88,7 +91,7 @@ func FillTemplate(name string, baseUrl string, code string, appName string) ([]b
}

// Send email with Sendgrid
func SendgridEmail(sendgridApiKey string, judge *models.Judge, hostname string) error {
func sendgridEmail(sendgridApiKey string, judge *models.Judge, hostname string) error {
appName := config.GetEnv("VITE_JURY_NAME")

from := mail.NewEmail(config.GetEnv("EMAIL_FROM_NAME"), config.GetEnv("EMAIL_FROM"))
Expand All @@ -105,3 +108,59 @@ func SendgridEmail(sendgridApiKey string, judge *models.Judge, hostname string)
_, err = client.Send(message)
return err
}

func sendEmailWithTimeout(host string, port string, auth smtp.Auth, from string, to []string, body []byte) error {
// Dial SMTP with 5 second timeout
conn, err := net.DialTimeout("tcp", host+":"+port, 5*time.Second)
if err != nil {
return fmt.Errorf("failed to connect to email server: %v", err)
}
defer conn.Close()

// Create SMTP client
client, err := smtp.NewClient(conn, host)
if err != nil {
return fmt.Errorf("failed to create SMTP client: %v", err)
}
defer client.Quit()

// Initiate TLS connection
tlsConfig := &tls.Config{
InsecureSkipVerify: true, // Set to true for self-signed certificates, but ideally use false and verify the server's certificate
ServerName: host,
}
if err := client.StartTLS(tlsConfig); err != nil {
return fmt.Errorf("failed to start email TLS client: %v", err)
}

// Authenticate
if err := client.Auth(auth); err != nil {
return fmt.Errorf("failed to authenticate SMTP client: %v", err)
}

// Set the sender and recipient
if err := client.Mail(from); err != nil {
return fmt.Errorf("failed to set email sender: %v", err)
}
for _, addr := range to {
if err := client.Rcpt(addr); err != nil {
return fmt.Errorf("failed to set email recipient: %v", err)
}
}

// Send the email body
writer, err := client.Data()
if err != nil {
return fmt.Errorf("failed to get email writer: %v", err)
}
_, err = writer.Write(body)
if err != nil {
return fmt.Errorf("failed to write email body: %v", err)
}
err = writer.Close()
if err != nil {
return fmt.Errorf("failed to close email writer: %v", err)
}

return nil
}