|
1 | 1 | from django import forms |
2 | 2 | from django.contrib.auth.models import User |
| 3 | +from django.core.validators import URLValidator |
| 4 | +from django.core.exceptions import ValidationError |
3 | 5 |
|
4 | 6 | from dal import autocomplete |
5 | 7 |
|
6 | | -from hknweb.candidate.models import BitByteActivity, OffChallenge |
| 8 | +import csv |
| 9 | +import re |
| 10 | + |
| 11 | +from hknweb.candidate.models import BitByteActivity, OffChallenge, ShortLink |
7 | 12 |
|
8 | 13 |
|
9 | 14 | TEXT_AREA_STYLE = ( |
@@ -38,3 +43,137 @@ class Meta: |
38 | 43 | def __init__(self, *args, **kwargs): |
39 | 44 | super(BitByteRequestForm, self).__init__(*args, **kwargs) |
40 | 45 | self.fields["participants"].queryset = User.objects.order_by("username") |
| 46 | + |
| 47 | + |
| 48 | +class CreateShortLinkForm(forms.ModelForm): |
| 49 | + """ |
| 50 | + Form for creating a single shortlink. |
| 51 | + """ |
| 52 | + |
| 53 | + class Meta: |
| 54 | + model = ShortLink |
| 55 | + fields = ["slug", "destination_url", "description"] |
| 56 | + widgets = { |
| 57 | + "slug": forms.TextInput(attrs={"placeholder": "e.g., discord, apply"}), |
| 58 | + "destination_url": forms.URLInput( |
| 59 | + attrs={"placeholder": "https://example.com"} |
| 60 | + ), |
| 61 | + "description": forms.TextInput( |
| 62 | + attrs={"placeholder": "Optional description"} |
| 63 | + ), |
| 64 | + } |
| 65 | + help_texts = { |
| 66 | + "slug": "Short code (letters, numbers, hyphens, underscores only)", |
| 67 | + "destination_url": "Full URL to redirect to", |
| 68 | + "description": "Optional description for reference", |
| 69 | + } |
| 70 | + |
| 71 | + def clean_slug(self): |
| 72 | + slug = self.cleaned_data.get("slug") |
| 73 | + if slug and not re.match(r"^[a-zA-Z0-9-_]+$", slug): |
| 74 | + raise ValidationError( |
| 75 | + "Slug can only contain letters, numbers, hyphens, and underscores" |
| 76 | + ) |
| 77 | + return slug |
| 78 | + |
| 79 | + |
| 80 | +class ImportShortLinksForm(forms.Form): |
| 81 | + """ |
| 82 | + Form for importing shortlinks from CSV. |
| 83 | + Expected CSV format: "In url,Out url,Creator,..." (additional columns ignored) |
| 84 | + """ |
| 85 | + |
| 86 | + file = forms.FileField( |
| 87 | + help_text='Upload a CSV file with columns: "In url", "Out url", "Creator"' |
| 88 | + ) |
| 89 | + |
| 90 | + REQUIRED_CSV_FIELDNAMES = {"In url", "Out url", "Creator"} |
| 91 | + SLUG_PATTERN = re.compile(r"^[a-zA-Z0-9-_]+$") |
| 92 | + |
| 93 | + def clean_file(self): |
| 94 | + file_wrapper = self.cleaned_data["file"] |
| 95 | + |
| 96 | + # Check file extension |
| 97 | + if not file_wrapper.name.endswith(".csv"): |
| 98 | + raise ValidationError("File must be a CSV file") |
| 99 | + |
| 100 | + return file_wrapper |
| 101 | + |
| 102 | + def save(self, user): |
| 103 | + """ |
| 104 | + Process the CSV and create/update shortlinks. |
| 105 | + Returns tuple: (created_count, updated_count, errors) |
| 106 | + """ |
| 107 | + file_wrapper = self.cleaned_data["file"] |
| 108 | + |
| 109 | + # Decode file and parse CSV |
| 110 | + decoded_file = file_wrapper.read().decode("utf-8").splitlines() |
| 111 | + reader = csv.DictReader(decoded_file) |
| 112 | + rows = list(reader) |
| 113 | + |
| 114 | + # Validate fieldnames |
| 115 | + uploaded_fieldnames = set(reader.fieldnames) |
| 116 | + if not self.REQUIRED_CSV_FIELDNAMES.issubset(uploaded_fieldnames): |
| 117 | + missing = self.REQUIRED_CSV_FIELDNAMES.difference(uploaded_fieldnames) |
| 118 | + raise forms.ValidationError( |
| 119 | + f"CSV is missing required columns: {', '.join(missing)}" |
| 120 | + ) |
| 121 | + |
| 122 | + # Process rows |
| 123 | + url_validator = URLValidator() |
| 124 | + created_count = 0 |
| 125 | + updated_count = 0 |
| 126 | + errors = [] |
| 127 | + |
| 128 | + for i, row in enumerate(rows, start=2): # Start at 2 (header is row 1) |
| 129 | + slug = row["In url"].strip() |
| 130 | + destination_url = row["Out url"].strip() |
| 131 | + creator_name = row["Creator"].strip() |
| 132 | + |
| 133 | + # Skip empty rows |
| 134 | + if not slug and not destination_url: |
| 135 | + continue |
| 136 | + |
| 137 | + # Validate slug |
| 138 | + if not slug: |
| 139 | + errors.append(f"Row {i}: Missing slug") |
| 140 | + continue |
| 141 | + |
| 142 | + if not self.SLUG_PATTERN.match(slug): |
| 143 | + errors.append( |
| 144 | + f"Row {i}: Invalid slug '{slug}' (only letters, numbers, hyphens, underscores allowed)" |
| 145 | + ) |
| 146 | + continue |
| 147 | + |
| 148 | + # Validate destination URL |
| 149 | + if not destination_url: |
| 150 | + errors.append(f"Row {i}: Missing destination URL for slug '{slug}'") |
| 151 | + continue |
| 152 | + |
| 153 | + try: |
| 154 | + url_validator(destination_url) |
| 155 | + except ValidationError: |
| 156 | + errors.append(f"Row {i}: Invalid URL '{destination_url}' for slug '{slug}'") |
| 157 | + continue |
| 158 | + |
| 159 | + # Create or update shortlink |
| 160 | + try: |
| 161 | + shortlink, created = ShortLink.objects.update_or_create( |
| 162 | + slug=slug, |
| 163 | + defaults={ |
| 164 | + "destination_url": destination_url, |
| 165 | + "description": f"Created by {creator_name}", |
| 166 | + "created_by": user, |
| 167 | + "active": True, |
| 168 | + }, |
| 169 | + ) |
| 170 | + |
| 171 | + if created: |
| 172 | + created_count += 1 |
| 173 | + else: |
| 174 | + updated_count += 1 |
| 175 | + |
| 176 | + except Exception as e: |
| 177 | + errors.append(f"Row {i}: Error processing slug '{slug}': {str(e)}") |
| 178 | + |
| 179 | + return created_count, updated_count, errors |
0 commit comments