This commit is contained in:
2025-08-31 00:29:53 +02:00
parent 191bd84573
commit 29611b15ca
87 changed files with 2451 additions and 0 deletions

0
app/upload/__init__.py Normal file
View File

3
app/upload/admin.py Normal file
View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View File

@@ -0,0 +1,10 @@
from rest_framework import serializers
from upload.models import Upload
class UploadSerializer(serializers.ModelSerializer):
class Meta:
model = Upload
fields = ['id', 'created_at', 'user', 'filename', 'slug']
read_only_fields = ['id', 'created_at', 'slug']

View File

@@ -0,0 +1,19 @@
from rest_framework import viewsets, permissions
from upload.models import Upload
from upload.api.serializers import UploadSerializer
class UploadViewSet(viewsets.ModelViewSet):
queryset = Upload.objects.all()
serializer_class = UploadSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
# Les utilisateurs ne peuvent voir que leurs propres uploads
if not self.request.user.is_staff:
return Upload.objects.filter(user=self.request.user)
# Les administrateurs peuvent voir tous les uploads
return Upload.objects.all()
def perform_create(self, serializer):
serializer.save(user=self.request.user)

6
app/upload/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class UploadConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'upload'

26
app/upload/forms.py Normal file
View File

@@ -0,0 +1,26 @@
from django import forms
from .models import Upload, Image
class UploadImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ['file']
def save(self, commit=True):
image = super().save(commit=False)
if not image.name:
image.name = image.file.name
if not image.content_type:
from utils import get_mimetype
image.content_type = get_mimetype(image.file)
image.size = image.file.size
if commit:
image.save()
return image

View File

@@ -0,0 +1,148 @@
# Generated by Django 5.2 on 2025-05-04 14:43
import django.db.models.deletion
import upload.models
import uuid
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Archive',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=upload.models.upload_to)),
('content_type', models.CharField(max_length=255)),
('size', models.PositiveBigIntegerField()),
('name', models.CharField(max_length=255)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Audio',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=upload.models.upload_to)),
('content_type', models.CharField(max_length=255)),
('size', models.PositiveBigIntegerField()),
('name', models.CharField(max_length=255)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Code',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=upload.models.upload_to)),
('content_type', models.CharField(max_length=255)),
('size', models.PositiveBigIntegerField()),
('name', models.CharField(max_length=255)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Document',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=upload.models.upload_to)),
('content_type', models.CharField(max_length=255)),
('size', models.PositiveBigIntegerField()),
('name', models.CharField(max_length=255)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Image',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=upload.models.upload_to)),
('content_type', models.CharField(max_length=255)),
('size', models.PositiveBigIntegerField()),
('name', models.CharField(max_length=255)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Other',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=upload.models.upload_to)),
('content_type', models.CharField(max_length=255)),
('size', models.PositiveBigIntegerField()),
('name', models.CharField(max_length=255)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='StructuredData',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=upload.models.upload_to)),
('content_type', models.CharField(max_length=255)),
('size', models.PositiveBigIntegerField()),
('name', models.CharField(max_length=255)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Text',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=upload.models.upload_to)),
('content_type', models.CharField(max_length=255)),
('size', models.PositiveBigIntegerField()),
('name', models.CharField(max_length=255)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Video',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to=upload.models.upload_to)),
('content_type', models.CharField(max_length=255)),
('size', models.PositiveBigIntegerField()),
('name', models.CharField(max_length=255)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Upload',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('filename', models.CharField(max_length=255)),
('object_id', models.UUIDField(blank=True, null=True)),
('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.contenttype')),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]

View File

172
app/upload/models.py Normal file
View File

@@ -0,0 +1,172 @@
from django.utils import timezone
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
import uuid
from pathlib import Path
from nanoid import generate
def generate_unique_slug_for_upload(size=10):
while True:
slug = generate(size=size)
if not Upload.objects.filter(slug=slug).exists():
return slug
def upload_to(instance, filename):
today = timezone.now().date()
dest_path = Path(f"uploads/{str(today.year)}/{str(today.month)}/{str(today.day)}")
if not dest_path.exists():
dest_path.mkdir(parents=True)
uid = uuid.uuid4().hex
file_path = Path(filename)
return str(dest_path / f"{uid}{file_path.suffix}")
class Upload(models.Model):
id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey('user.User', on_delete=models.CASCADE, null=True, blank=True)
filename = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True, default=generate_unique_slug_for_upload, editable=False)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True)
object_id = models.UUIDField(null=True, blank=True)
content_object = GenericForeignKey('content_type', 'object_id')
class AbstractFile(models.Model):
file = models.FileField(upload_to=upload_to)
content_type = models.CharField(max_length=255)
size = models.PositiveBigIntegerField()
name = models.CharField(max_length=255)
class Meta:
abstract = True
def save(self, *args, **kwargs):
if self.file:
from utils import get_mimetype
self.size = self.file.size
self.content_type = get_mimetype(self.file)
self.name = self.file.name
class Image(AbstractFile):
allowed_mimetypes = [
"image/jpeg",
"image/png",
"image/gif",
"image/webp",
"image/bmp",
"image/svg+xml",
"image/tiff",
"image/x-icon", # favicon
"image/vnd.microsoft.icon"
]
pass
class Video(AbstractFile):
allowed_mimetypes = [
"video/mp4",
"video/quicktime", # .mov
"video/x-msvideo", # .avi
"video/x-matroska", # .mkv
"video/webm",
"video/mpeg",
"video/ogg"
]
pass
class Audio(AbstractFile):
allowed_mimetypes = [
"audio/mpeg", # .mp3
"audio/wav", # .wav
"audio/x-wav",
"audio/ogg", # .ogg
"audio/webm", # .webm audio
"audio/aac",
"audio/flac",
"audio/x-flac"
]
pass
class Document(AbstractFile):
allowed_mimetypes = [
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document", # .docx
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", # .xlsx
"application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.presentationml.presentation", # .pptx
"application/rtf",
"text/plain",
"text/csv"
]
pass
class Archive(AbstractFile):
allowed_mimetypes = [
"application/zip",
"application/x-tar",
"application/x-gzip",
"application/x-bzip2",
"application/x-7z-compressed",
"application/x-rar-compressed"
]
class Text(AbstractFile):
allowed_mimetypes = [
"text/plain", # .txt, .log
]
pass
class Code(AbstractFile):
allowed_mimetypes = [
"text/x-python", # .py
"text/x-shellscript", # .sh, .bash
"text/x-csrc", # .c
"text/x-c++src", # .cpp, .cc
"text/x-java-source", # .java
"text/x-go", # .go
"text/x-rustsrc", # .rs
"text/x-sql", # .sql
"text/x-markdown", # .md
"text/markdown", # .md (alternative)
"text/x-makefile", # Makefile
"text/x-php", # .php
"application/javascript", # .js (modern)
"text/javascript", # .js (legacy)
"text/css", # .css
"application/x-perl", # .pl
"application/x-ruby", # .rb
"application/x-lua", # .lua
]
class StructuredData(AbstractFile):
allowed_mimetypes = [
"application/json", # .json
"application/xml", # .xml
"text/xml", # .xml alternative
"text/csv", # .csv
"text/tab-separated-values", # .tsv
"application/x-yaml", # .yaml (rare)
"text/x-yaml", # .yaml, .yml (le plus courant)
"application/vnd.ms-excel", # .xls (Excel legacy)
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", # .xlsx
"application/x-hdf", # .hdf, .h5
"application/x-parquet", # .parquet
"application/x-ndjson", # .ndjson (newline-delimited JSON)
"application/x-netcdf", # .nc
]
class Other(AbstractFile):
allowed_extensions = []
pass

View File

@@ -0,0 +1 @@
{% extends "base.html" %}

View File

@@ -0,0 +1,2 @@
{% extends "upload/layout.html" %}

3
app/upload/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

26
app/upload/utils.py Normal file
View File

@@ -0,0 +1,26 @@
import magic
from upload.models import AbstractFile
from functools import lru_cache
@lru_cache(maxsize=128)
def get_mimetype_class_map():
mapping = {}
for cls in AbstractFile.__subclasses__():
for mt in getattr(cls, 'allowed_mimetypes', []):
mapping[mt] = cls
return mapping
def get_mimetype(file_obj):
mimetype = magic.from_buffer(file_obj.read(2048), mime=True)
file_obj.seek(0)
return mimetype
def get_upload_class_for_mimetype(mimetype):
mimetype = mimetype.lower().replace('x-', '') # normalisation légère
return get_mimetype_class_map().get(mimetype)
def create_upload(request, file_obj):
pass

25
app/upload/views.py Normal file
View File

@@ -0,0 +1,25 @@
from django.shortcuts import render, redirect
from .forms import UploadImageForm
from .models import Upload
from django.contrib.contenttypes.models import ContentType
def upload_image_view(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
image = form.save()
upload = Upload.objects.create(
filename=image.file.name,
content_type=ContentType.objects.get_for_model(image),
object_id=image.id,
user=request.user if request.user.is_authenticated else None
)
return redirect('upload_success', slug=upload.slug)
else:
form = UploadImageForm()
return render(request, 'upload/upload_form.html', {'form': form})