2025-12-03 19:29:37 +00:00
package handlers
import (
2025-12-28 21:18:33 +00:00
"context"
2025-12-06 16:21:59 +00:00
"errors"
2025-12-03 19:29:37 +00:00
"net/http"
"strconv"
2025-12-24 10:19:05 +00:00
apperrors "veza-backend-api/internal/errors"
2025-12-28 21:18:33 +00:00
"veza-backend-api/internal/models"
2025-12-16 16:23:49 +00:00
"veza-backend-api/internal/services"
2025-12-24 11:15:25 +00:00
"veza-backend-api/internal/utils"
2025-12-16 16:23:49 +00:00
2025-12-03 19:29:37 +00:00
"github.com/gin-gonic/gin"
P0: stabilisation backend/chat/stream + nouvelle base migrations v1
Backend Go:
- Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN.
- Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError).
- Sécurisation de config.go, CORS, statuts de santé et monitoring.
- Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles).
- Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés.
- Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*.
Chat server (Rust):
- Refonte du pipeline JWT + sécurité, audit et rate limiting avancé.
- Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing).
- Nettoyage des panics, gestion d’erreurs robuste, logs structurés.
- Migrations chat alignées sur le schéma UUID et nouvelles features.
Stream server (Rust):
- Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core.
- Transactions P0 pour les jobs et segments, garanties d’atomicité.
- Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION).
Documentation & audits:
- TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services.
- Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3).
- Scripts de reset et de cleanup pour la lab DB et la V1.
Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
"github.com/google/uuid"
"go.uber.org/zap"
2025-12-03 19:29:37 +00:00
)
2025-12-28 21:18:33 +00:00
// CommentServiceInterface defines the interface for comment operations
// This allows for easier testing with mocks
type CommentServiceInterface interface {
CreateComment ( ctx context . Context , trackID uuid . UUID , userID uuid . UUID , content string , timestamp float64 , parentID * uuid . UUID ) ( * models . TrackComment , error )
GetComments ( ctx context . Context , trackID uuid . UUID , page , limit int ) ( [ ] models . TrackComment , int64 , error )
UpdateComment ( ctx context . Context , commentID uuid . UUID , userID uuid . UUID , content string ) ( * models . TrackComment , error )
DeleteComment ( ctx context . Context , commentID uuid . UUID , userID uuid . UUID , isAdmin bool ) error
GetReplies ( ctx context . Context , parentID uuid . UUID , page , limit int ) ( [ ] models . TrackComment , int64 , error )
chore: consolidate CI, E2E, backend and frontend updates
- CI: workflows updates (cd, ci), remove playwright.yml
- E2E: global-setup, auth/playlists/profile specs
- Remove playwright-report and test-results artifacts from tracking
- Backend: auth, handlers, services, workers, migrations
- Frontend: components, features, vite config
- Add e2e-results.json to gitignore
- Docs: REMEDIATION_PROGRESS, audit archive
- Rust: chat-server, stream-server updates
2026-02-17 15:43:21 +00:00
GetTrackCreatorID ( ctx context . Context , trackID uuid . UUID ) ( uuid . UUID , error )
2025-12-28 21:18:33 +00:00
}
2025-12-03 19:29:37 +00:00
// CommentHandler gère les opérations sur les commentaires de tracks
type CommentHandler struct {
2026-03-05 22:03:43 +00:00
commentService CommentServiceInterface
chore: consolidate CI, E2E, backend and frontend updates
- CI: workflows updates (cd, ci), remove playwright.yml
- E2E: global-setup, auth/playlists/profile specs
- Remove playwright-report and test-results artifacts from tracking
- Backend: auth, handlers, services, workers, migrations
- Frontend: components, features, vite config
- Add e2e-results.json to gitignore
- Docs: REMEDIATION_PROGRESS, audit archive
- Rust: chat-server, stream-server updates
2026-02-17 15:43:21 +00:00
notificationService * services . NotificationService // Phase 2.2: Optional, for comment notifications
2026-03-05 22:03:43 +00:00
commonHandler * CommonHandler
2025-12-03 19:29:37 +00:00
}
// NewCommentHandler crée un nouveau handler de commentaires
P0: stabilisation backend/chat/stream + nouvelle base migrations v1
Backend Go:
- Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN.
- Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError).
- Sécurisation de config.go, CORS, statuts de santé et monitoring.
- Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles).
- Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés.
- Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*.
Chat server (Rust):
- Refonte du pipeline JWT + sécurité, audit et rate limiting avancé.
- Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing).
- Nettoyage des panics, gestion d’erreurs robuste, logs structurés.
- Migrations chat alignées sur le schéma UUID et nouvelles features.
Stream server (Rust):
- Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core.
- Transactions P0 pour les jobs et segments, garanties d’atomicité.
- Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION).
Documentation & audits:
- TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services.
- Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3).
- Scripts de reset et de cleanup pour la lab DB et la V1.
Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
func NewCommentHandler ( commentService * services . CommentService , logger * zap . Logger ) * CommentHandler {
return & CommentHandler {
commentService : commentService ,
commonHandler : NewCommonHandler ( logger ) ,
}
2025-12-03 19:29:37 +00:00
}
2025-12-28 21:18:33 +00:00
// NewCommentHandlerWithInterface crée un nouveau handler avec une interface (pour les tests)
func NewCommentHandlerWithInterface ( commentService CommentServiceInterface , logger * zap . Logger ) * CommentHandler {
return & CommentHandler {
commentService : commentService ,
commonHandler : NewCommonHandler ( logger ) ,
}
}
chore: consolidate CI, E2E, backend and frontend updates
- CI: workflows updates (cd, ci), remove playwright.yml
- E2E: global-setup, auth/playlists/profile specs
- Remove playwright-report and test-results artifacts from tracking
- Backend: auth, handlers, services, workers, migrations
- Frontend: components, features, vite config
- Add e2e-results.json to gitignore
- Docs: REMEDIATION_PROGRESS, audit archive
- Rust: chat-server, stream-server updates
2026-02-17 15:43:21 +00:00
// SetNotificationService sets the notification service for comment notifications (Phase 2.2)
func ( h * CommentHandler ) SetNotificationService ( notificationService * services . NotificationService ) {
h . notificationService = notificationService
}
2025-12-03 19:29:37 +00:00
// CreateCommentRequest représente la requête pour créer un commentaire
2025-12-16 18:34:08 +00:00
// MOD-P1-001: Ajout tags validate pour validation systématique
feat(v0.10.3): Commentaires & Interactions Sociales - F201-F215
- F201: Commentaires avec timestamp cliquable, modération mots-clés
- F202: Likes privés (compteur visible créateur uniquement)
- F203: Reposts de tracks sur le profil, bouton Repost, onglet Reposts
- F204: Notifications (commentaire, repost), pas de gamification
Backend: migrations 127/128, comment_moderation_service, track_repost_service,
GetTrackLikes/GetTrack masquent like_count pour non-créateurs
Frontend: LikeButton isCreator, RepostButton, Reposts tab profil, timestamp seek
2026-03-09 09:30:47 +00:00
// v0.10.3 F201: Timestamp (position in track in seconds) for seekable comments
2025-12-03 19:29:37 +00:00
type CreateCommentRequest struct {
feat(v0.10.3): Commentaires & Interactions Sociales - F201-F215
- F201: Commentaires avec timestamp cliquable, modération mots-clés
- F202: Likes privés (compteur visible créateur uniquement)
- F203: Reposts de tracks sur le profil, bouton Repost, onglet Reposts
- F204: Notifications (commentaire, repost), pas de gamification
Backend: migrations 127/128, comment_moderation_service, track_repost_service,
GetTrackLikes/GetTrack masquent like_count pour non-créateurs
Frontend: LikeButton isCreator, RepostButton, Reposts tab profil, timestamp seek
2026-03-09 09:30:47 +00:00
Content string ` json:"content" binding:"required,min=1,max=5000" validate:"required,min=1,max=5000" `
ParentID * uuid . UUID ` json:"parent_id,omitempty" validate:"omitempty" `
Timestamp * float64 ` json:"timestamp,omitempty" ` // Position in seconds (0 = top-level, no specific time)
2025-12-03 19:29:37 +00:00
}
// UpdateCommentRequest représente la requête pour mettre à jour un commentaire
2025-12-16 18:34:08 +00:00
// MOD-P1-001: Ajout tags validate pour validation systématique
2025-12-03 19:29:37 +00:00
type UpdateCommentRequest struct {
2025-12-16 18:34:08 +00:00
Content string ` json:"content" binding:"required,min=1,max=5000" validate:"required,min=1,max=5000" `
2025-12-03 19:29:37 +00:00
}
// CreateComment gère la création d'un commentaire sur un track
2025-12-25 14:23:19 +00:00
// @Summary Create comment
2026-01-07 18:39:21 +00:00
// @Description Create a new comment on a track. Can be a top-level comment or a reply to another comment (using parent_id).
2025-12-25 14:23:19 +00:00
// @Tags Comment
// @Accept json
// @Produce json
// @Security BearerAuth
2026-01-07 18:39:21 +00:00
// @Param id path string true "Track ID (UUID)"
// @Param comment body handlers.CreateCommentRequest true "Comment data"
2025-12-25 14:23:19 +00:00
// @Success 201 {object} handlers.APIResponse{data=object{comment=object}}
// @Failure 400 {object} handlers.APIResponse "Validation error"
// @Failure 401 {object} handlers.APIResponse "Unauthorized"
// @Failure 404 {object} handlers.APIResponse "Track not found"
2026-01-07 18:39:21 +00:00
// @Failure 500 {object} handlers.APIResponse "Internal server error"
2025-12-25 14:23:19 +00:00
// @Router /tracks/{id}/comments [post]
2025-12-03 19:29:37 +00:00
func ( h * CommentHandler ) CreateComment ( c * gin . Context ) {
2025-12-16 16:23:49 +00:00
userID , ok := GetUserIDUUID ( c )
if ! ok {
return // Erreur déjà envoyée par GetUserIDUUID
}
2025-12-03 19:29:37 +00:00
if userID == uuid . Nil {
2026-01-15 16:32:02 +00:00
// Action 1.3.2.1: Use wrapped format helper for errors
RespondWithError ( c , int ( apperrors . ErrCodeUnauthorized ) , "unauthorized" )
2025-12-03 19:29:37 +00:00
return
}
trackIDStr := c . Param ( "id" )
if trackIDStr == "" {
2026-01-15 16:32:02 +00:00
// Action 1.3.2.1: Use wrapped format helper for errors
RespondWithError ( c , int ( apperrors . ErrCodeValidation ) , "track id is required" )
2025-12-03 19:29:37 +00:00
return
}
trackID , err := uuid . Parse ( trackIDStr ) // Changed to uuid.Parse
if err != nil {
2026-01-15 16:32:02 +00:00
// Action 1.3.2.1: Use wrapped format helper for errors
RespondWithError ( c , int ( apperrors . ErrCodeValidation ) , "invalid track id" )
2025-12-03 19:29:37 +00:00
return
}
var req CreateCommentRequest
P0: stabilisation backend/chat/stream + nouvelle base migrations v1
Backend Go:
- Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN.
- Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError).
- Sécurisation de config.go, CORS, statuts de santé et monitoring.
- Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles).
- Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés.
- Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*.
Chat server (Rust):
- Refonte du pipeline JWT + sécurité, audit et rate limiting avancé.
- Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing).
- Nettoyage des panics, gestion d’erreurs robuste, logs structurés.
- Migrations chat alignées sur le schéma UUID et nouvelles features.
Stream server (Rust):
- Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core.
- Transactions P0 pour les jobs et segments, garanties d’atomicité.
- Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION).
Documentation & audits:
- TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services.
- Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3).
- Scripts de reset et de cleanup pour la lab DB et la V1.
Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
if appErr := h . commonHandler . BindAndValidateJSON ( c , & req ) ; appErr != nil {
RespondWithAppError ( c , appErr )
2025-12-03 19:29:37 +00:00
return
}
2025-12-24 11:15:25 +00:00
// BE-SEC-009: Sanitize user inputs to prevent XSS and injection attacks
req . Content = utils . SanitizeText ( req . Content , 5000 )
feat(v0.10.3): Commentaires & Interactions Sociales - F201-F215
- F201: Commentaires avec timestamp cliquable, modération mots-clés
- F202: Likes privés (compteur visible créateur uniquement)
- F203: Reposts de tracks sur le profil, bouton Repost, onglet Reposts
- F204: Notifications (commentaire, repost), pas de gamification
Backend: migrations 127/128, comment_moderation_service, track_repost_service,
GetTrackLikes/GetTrack masquent like_count pour non-créateurs
Frontend: LikeButton isCreator, RepostButton, Reposts tab profil, timestamp seek
2026-03-09 09:30:47 +00:00
timestamp := 0.0
if req . Timestamp != nil && * req . Timestamp >= 0 {
timestamp = * req . Timestamp
}
comment , err := h . commentService . CreateComment ( c . Request . Context ( ) , trackID , userID , req . Content , timestamp , req . ParentID )
2025-12-03 19:29:37 +00:00
if err != nil {
feat(v0.10.3): Commentaires & Interactions Sociales - F201-F215
- F201: Commentaires avec timestamp cliquable, modération mots-clés
- F202: Likes privés (compteur visible créateur uniquement)
- F203: Reposts de tracks sur le profil, bouton Repost, onglet Reposts
- F204: Notifications (commentaire, repost), pas de gamification
Backend: migrations 127/128, comment_moderation_service, track_repost_service,
GetTrackLikes/GetTrack masquent like_count pour non-créateurs
Frontend: LikeButton isCreator, RepostButton, Reposts tab profil, timestamp seek
2026-03-09 09:30:47 +00:00
if errors . Is ( err , services . ErrModerationRejected ) {
RespondWithAppError ( c , apperrors . NewValidationError ( "content does not comply with moderation rules" ) )
return
}
2025-12-06 16:21:59 +00:00
if errors . Is ( err , services . ErrTrackNotFound ) {
2025-12-24 10:19:05 +00:00
RespondWithAppError ( c , apperrors . NewNotFoundError ( "track" ) )
2025-12-03 19:29:37 +00:00
return
}
2025-12-06 16:21:59 +00:00
if errors . Is ( err , services . ErrParentCommentNotFound ) {
2025-12-24 10:19:05 +00:00
RespondWithAppError ( c , apperrors . NewNotFoundError ( "parent comment" ) )
2025-12-03 19:29:37 +00:00
return
}
2025-12-06 16:21:59 +00:00
if errors . Is ( err , services . ErrParentTrackMismatch ) {
2025-12-24 10:19:05 +00:00
RespondWithAppError ( c , apperrors . NewValidationError ( "parent comment does not belong to the same track" ) )
2025-12-03 19:29:37 +00:00
return
}
2025-12-24 10:19:05 +00:00
h . commonHandler . logger . Error ( "failed to create comment" , zap . Error ( err ) )
RespondWithAppError ( c , apperrors . Wrap ( apperrors . ErrCodeInternal , "Failed to create comment" , err ) )
2025-12-03 19:29:37 +00:00
return
}
feat(v0.10.5): Notifications complètes — F551-F555
F555: Backend pagination/filter GetNotifications (type, page, limit) + frontend pagination
F551: WebSocket real-time — backend inject chat hub, send on CreateNotification; frontend useChat invalidates
F553: Quiet hours — migration 132, CreateNotification skips push/WS, UI in PushPreferencesSection
F554: Notification grouping — migration 133, group_key/actor_count for like/comment, UI format
F552: Weekly digest — migration 134, NotificationDigestWorker, email template, prefs UI
Acceptance: no gamification notif; defaults unchanged; individual toggles for marketing
2026-03-10 09:02:21 +00:00
// Phase 2.2: Create notification for track creator (skip if user comments on own track). F554: grouping by track
chore: consolidate CI, E2E, backend and frontend updates
- CI: workflows updates (cd, ci), remove playwright.yml
- E2E: global-setup, auth/playlists/profile specs
- Remove playwright-report and test-results artifacts from tracking
- Backend: auth, handlers, services, workers, migrations
- Frontend: components, features, vite config
- Add e2e-results.json to gitignore
- Docs: REMEDIATION_PROGRESS, audit archive
- Rust: chat-server, stream-server updates
2026-02-17 15:43:21 +00:00
if h . notificationService != nil {
creatorID , err := h . commentService . GetTrackCreatorID ( c . Request . Context ( ) , trackID )
if err == nil && creatorID != userID {
link := "/tracks/" + trackID . String ( )
feat(v0.10.5): Notifications complètes — F551-F555
F555: Backend pagination/filter GetNotifications (type, page, limit) + frontend pagination
F551: WebSocket real-time — backend inject chat hub, send on CreateNotification; frontend useChat invalidates
F553: Quiet hours — migration 132, CreateNotification skips push/WS, UI in PushPreferencesSection
F554: Notification grouping — migration 133, group_key/actor_count for like/comment, UI format
F552: Weekly digest — migration 134, NotificationDigestWorker, email template, prefs UI
Acceptance: no gamification notif; defaults unchanged; individual toggles for marketing
2026-03-10 09:02:21 +00:00
if err := h . notificationService . CreateNotificationWithGroup ( creatorID , "comment" , "New comment" , "Someone commented on your track" , link , "comment:track:" + trackID . String ( ) , userID ) ; err != nil {
chore: consolidate CI, E2E, backend and frontend updates
- CI: workflows updates (cd, ci), remove playwright.yml
- E2E: global-setup, auth/playlists/profile specs
- Remove playwright-report and test-results artifacts from tracking
- Backend: auth, handlers, services, workers, migrations
- Frontend: components, features, vite config
- Add e2e-results.json to gitignore
- Docs: REMEDIATION_PROGRESS, audit archive
- Rust: chat-server, stream-server updates
2026-02-17 15:43:21 +00:00
h . commonHandler . logger . Warn ( "failed to create comment notification" , zap . Error ( err ) )
}
}
}
2025-12-24 10:19:05 +00:00
RespondSuccess ( c , http . StatusCreated , comment )
2025-12-03 19:29:37 +00:00
}
// GetComments gère la récupération des commentaires d'un track
2025-12-25 14:23:19 +00:00
// @Summary Get track comments
// @Description Get paginated list of comments for a track
// @Tags Comment
// @Accept json
// @Produce json
// @Param id path string true "Track ID"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(20)
// @Success 200 {object} handlers.APIResponse{data=object{comments=array,pagination=object}}
// @Failure 400 {object} handlers.APIResponse "Validation error"
// @Failure 404 {object} handlers.APIResponse "Track not found"
// @Failure 500 {object} handlers.APIResponse "Internal server error"
// @Router /tracks/{id}/comments [get]
2025-12-03 19:29:37 +00:00
func ( h * CommentHandler ) GetComments ( c * gin . Context ) {
trackIDStr := c . Param ( "id" )
if trackIDStr == "" {
2025-12-24 10:19:05 +00:00
RespondWithAppError ( c , apperrors . NewValidationError ( "track id is required" ) )
2025-12-03 19:29:37 +00:00
return
}
trackID , err := uuid . Parse ( trackIDStr ) // Changed to uuid.Parse
if err != nil {
2025-12-24 10:19:05 +00:00
RespondWithAppError ( c , apperrors . NewValidationError ( "invalid track id" ) )
2025-12-03 19:29:37 +00:00
return
}
page , _ := strconv . Atoi ( c . DefaultQuery ( "page" , "1" ) )
limit , _ := strconv . Atoi ( c . DefaultQuery ( "limit" , "20" ) )
2026-03-12 05:13:38 +00:00
limit = clampLimit ( limit ) // SECURITY(MEDIUM-004)
2025-12-03 19:29:37 +00:00
if page < 1 {
page = 1
}
if limit < 1 {
limit = 20
}
if limit > 100 {
limit = 100
}
comments , total , err := h . commentService . GetComments ( c . Request . Context ( ) , trackID , page , limit )
if err != nil {
2025-12-24 10:19:05 +00:00
h . commonHandler . logger . Error ( "failed to get comments" , zap . Error ( err ) )
RespondWithAppError ( c , apperrors . Wrap ( apperrors . ErrCodeInternal , "Failed to get comments" , err ) )
2025-12-03 19:29:37 +00:00
return
}
2025-12-25 14:14:26 +00:00
// INT-007: Standardize pagination format
pagination := BuildPaginationData ( page , limit , total )
2025-12-24 10:19:05 +00:00
RespondSuccess ( c , http . StatusOK , gin . H {
2025-12-25 14:14:26 +00:00
"comments" : comments ,
"pagination" : pagination ,
2025-12-03 19:29:37 +00:00
} )
}
// UpdateComment gère la mise à jour d'un commentaire
2026-01-07 18:39:21 +00:00
// @Summary Update comment
// @Description Update a comment (only by owner)
// @Tags Comment
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path string true "Comment ID (UUID)"
// @Param comment body handlers.UpdateCommentRequest true "Updated comment content"
// @Success 200 {object} handlers.APIResponse{data=object{comment=object}}
// @Failure 400 {object} handlers.APIResponse "Validation error"
// @Failure 401 {object} handlers.APIResponse "Unauthorized"
// @Failure 403 {object} handlers.APIResponse "Forbidden - can only edit own comments"
// @Failure 404 {object} handlers.APIResponse "Comment not found"
// @Failure 500 {object} handlers.APIResponse "Internal server error"
// @Router /comments/{id} [put]
2025-12-03 19:29:37 +00:00
func ( h * CommentHandler ) UpdateComment ( c * gin . Context ) {
2025-12-16 16:23:49 +00:00
userID , ok := GetUserIDUUID ( c )
if ! ok {
return // Erreur déjà envoyée par GetUserIDUUID
}
2025-12-03 19:29:37 +00:00
if userID == uuid . Nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError ( c , apperrors . NewUnauthorizedError ( "unauthorized" ) )
2025-12-03 19:29:37 +00:00
return
}
commentIDStr := c . Param ( "id" )
if commentIDStr == "" {
2026-03-06 23:54:35 +00:00
RespondWithAppError ( c , apperrors . NewValidationError ( "comment id is required" ) )
2025-12-03 19:29:37 +00:00
return
}
commentID , err := uuid . Parse ( commentIDStr ) // Changed to uuid.Parse
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError ( c , apperrors . NewValidationError ( "invalid comment id" ) )
2025-12-03 19:29:37 +00:00
return
}
var req UpdateCommentRequest
P0: stabilisation backend/chat/stream + nouvelle base migrations v1
Backend Go:
- Remplacement complet des anciennes migrations par la base V1 alignée sur ORIGIN.
- Durcissement global du parsing JSON (BindAndValidateJSON + RespondWithAppError).
- Sécurisation de config.go, CORS, statuts de santé et monitoring.
- Implémentation des transactions P0 (RBAC, duplication de playlists, social toggles).
- Ajout d’un job worker structuré (emails, analytics, thumbnails) + tests associés.
- Nouvelle doc backend : AUDIT_CONFIG, BACKEND_CONFIG, AUTH_PASSWORD_RESET, JOB_WORKER_*.
Chat server (Rust):
- Refonte du pipeline JWT + sécurité, audit et rate limiting avancé.
- Implémentation complète du cycle de message (read receipts, delivered, edit/delete, typing).
- Nettoyage des panics, gestion d’erreurs robuste, logs structurés.
- Migrations chat alignées sur le schéma UUID et nouvelles features.
Stream server (Rust):
- Refonte du moteur de streaming (encoding pipeline + HLS) et des modules core.
- Transactions P0 pour les jobs et segments, garanties d’atomicité.
- Documentation détaillée de la pipeline (AUDIT_STREAM_*, DESIGN_STREAM_PIPELINE, TRANSACTIONS_P0_IMPLEMENTATION).
Documentation & audits:
- TRIAGE.md et AUDIT_STABILITY.md à jour avec l’état réel des 3 services.
- Cartographie complète des migrations et des transactions (DB_MIGRATIONS_*, DB_TRANSACTION_PLAN, AUDIT_DB_TRANSACTIONS, TRANSACTION_TESTS_PHASE3).
- Scripts de reset et de cleanup pour la lab DB et la V1.
Ce commit fige l’ensemble du travail de stabilisation P0 (UUID, backend, chat et stream) avant les phases suivantes (Coherence Guardian, WS hardening, etc.).
2025-12-06 10:14:38 +00:00
if appErr := h . commonHandler . BindAndValidateJSON ( c , & req ) ; appErr != nil {
RespondWithAppError ( c , appErr )
2025-12-03 19:29:37 +00:00
return
}
2025-12-24 11:15:25 +00:00
// BE-SEC-009: Sanitize user inputs to prevent XSS and injection attacks
req . Content = utils . SanitizeText ( req . Content , 5000 )
2025-12-03 19:29:37 +00:00
comment , err := h . commentService . UpdateComment ( c . Request . Context ( ) , commentID , userID , req . Content )
if err != nil {
2025-12-06 16:21:59 +00:00
if errors . Is ( err , services . ErrCommentNotFound ) {
2026-03-06 23:54:35 +00:00
RespondWithAppError ( c , apperrors . NewNotFoundError ( "comment" ) )
2025-12-03 19:29:37 +00:00
return
}
2025-12-06 16:21:59 +00:00
if errors . Is ( err , services . ErrForbidden ) {
2026-03-06 23:54:35 +00:00
RespondWithAppError ( c , apperrors . NewForbiddenError ( "unauthorized: you can only edit your own comments" ) )
2025-12-03 19:29:37 +00:00
return
}
2026-03-06 23:54:35 +00:00
RespondWithAppError ( c , apperrors . NewInternalErrorWrap ( "Failed to update comment" , err ) )
2025-12-03 19:29:37 +00:00
return
}
2026-03-06 23:54:35 +00:00
RespondSuccess ( c , http . StatusOK , gin . H { "comment" : comment } )
2025-12-03 19:29:37 +00:00
}
// DeleteComment gère la suppression d'un commentaire
2025-12-25 14:23:19 +00:00
// @Summary Delete comment
// @Description Delete a comment (only by owner or admin)
// @Tags Comment
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path string true "Track ID"
// @Param comment_id path string true "Comment ID"
// @Success 200 {object} handlers.APIResponse{data=object{message=string}}
// @Failure 400 {object} handlers.APIResponse "Validation error"
// @Failure 401 {object} handlers.APIResponse "Unauthorized"
// @Failure 403 {object} handlers.APIResponse "Forbidden - not comment owner"
// @Failure 404 {object} handlers.APIResponse "Comment not found"
// @Router /tracks/{id}/comments/{comment_id} [delete]
2025-12-03 19:29:37 +00:00
func ( h * CommentHandler ) DeleteComment ( c * gin . Context ) {
2025-12-16 16:23:49 +00:00
userID , ok := GetUserIDUUID ( c )
if ! ok {
return // Erreur déjà envoyée par GetUserIDUUID
}
2025-12-03 19:29:37 +00:00
if userID == uuid . Nil {
2025-12-24 10:19:05 +00:00
RespondWithAppError ( c , apperrors . NewUnauthorizedError ( "unauthorized" ) )
2025-12-03 19:29:37 +00:00
return
}
commentIDStr := c . Param ( "id" )
if commentIDStr == "" {
2025-12-24 10:19:05 +00:00
RespondWithAppError ( c , apperrors . NewValidationError ( "comment id is required" ) )
2025-12-03 19:29:37 +00:00
return
}
commentID , err := uuid . Parse ( commentIDStr ) // Changed to uuid.Parse
if err != nil {
2025-12-24 10:19:05 +00:00
RespondWithAppError ( c , apperrors . NewValidationError ( "invalid comment id" ) )
2025-12-03 19:29:37 +00:00
return
}
err = h . commentService . DeleteComment ( c . Request . Context ( ) , commentID , userID , false ) // Added false for isAdmin
if err != nil {
2025-12-06 16:21:59 +00:00
if errors . Is ( err , services . ErrCommentNotFound ) {
2025-12-24 10:19:05 +00:00
RespondWithAppError ( c , apperrors . NewNotFoundError ( "comment" ) )
2025-12-03 19:29:37 +00:00
return
}
2025-12-06 16:21:59 +00:00
if errors . Is ( err , services . ErrForbidden ) {
2025-12-24 10:19:05 +00:00
RespondWithAppError ( c , apperrors . NewForbiddenError ( "you can only delete your own comments" ) )
2025-12-03 19:29:37 +00:00
return
}
2025-12-24 10:19:05 +00:00
h . commonHandler . logger . Error ( "failed to delete comment" , zap . Error ( err ) )
RespondWithAppError ( c , apperrors . Wrap ( apperrors . ErrCodeInternal , "Failed to delete comment" , err ) )
2025-12-03 19:29:37 +00:00
return
}
2025-12-24 10:19:05 +00:00
RespondSuccess ( c , http . StatusOK , gin . H { "message" : "Comment deleted successfully" } )
2025-12-03 19:29:37 +00:00
}
// GetReplies gère la récupération des réponses d'un commentaire
2026-01-07 18:39:21 +00:00
// @Summary Get comment replies
// @Description Get paginated list of replies to a comment
// @Tags Comment
// @Accept json
// @Produce json
// @Param id path string true "Parent Comment ID (UUID)"
// @Param page query int false "Page number" default(1) minimum(1)
// @Param limit query int false "Items per page" default(20) minimum(1) maximum(100)
// @Success 200 {object} handlers.APIResponse{data=object{replies=array,pagination=object}}
// @Failure 400 {object} handlers.APIResponse "Validation error"
// @Failure 404 {object} handlers.APIResponse "Parent comment not found"
// @Failure 500 {object} handlers.APIResponse "Internal server error"
// @Router /comments/{id}/replies [get]
2025-12-03 19:29:37 +00:00
func ( h * CommentHandler ) GetReplies ( c * gin . Context ) {
parentIDStr := c . Param ( "id" )
if parentIDStr == "" {
2026-03-06 23:54:35 +00:00
RespondWithAppError ( c , apperrors . NewValidationError ( "parent comment id is required" ) )
2025-12-03 19:29:37 +00:00
return
}
parentID , err := uuid . Parse ( parentIDStr ) // Changed to uuid.Parse
if err != nil {
2026-03-06 23:54:35 +00:00
RespondWithAppError ( c , apperrors . NewValidationError ( "invalid parent comment id" ) )
2025-12-03 19:29:37 +00:00
return
}
page , _ := strconv . Atoi ( c . DefaultQuery ( "page" , "1" ) )
limit , _ := strconv . Atoi ( c . DefaultQuery ( "limit" , "20" ) )
2026-03-12 05:13:38 +00:00
limit = clampLimit ( limit ) // SECURITY(MEDIUM-004)
2025-12-03 19:29:37 +00:00
if page < 1 {
page = 1
}
if limit < 1 {
limit = 20
}
if limit > 100 {
limit = 100
}
replies , total , err := h . commentService . GetReplies ( c . Request . Context ( ) , parentID , page , limit )
if err != nil {
2025-12-06 16:21:59 +00:00
if errors . Is ( err , services . ErrParentCommentNotFound ) {
2026-03-06 23:54:35 +00:00
RespondWithAppError ( c , apperrors . NewNotFoundError ( "parent comment" ) )
2025-12-03 19:29:37 +00:00
return
}
2026-03-06 23:54:35 +00:00
RespondWithAppError ( c , apperrors . NewInternalErrorWrap ( "Failed to get replies" , err ) )
2025-12-03 19:29:37 +00:00
return
}
2026-03-06 23:54:35 +00:00
RespondSuccess ( c , http . StatusOK , gin . H {
2025-12-03 19:29:37 +00:00
"replies" : replies ,
"total" : total ,
"page" : page ,
"limit" : limit ,
} )
}