sojorn/_legacy/supabase/functions/cleanup-expired-content/index.ts
Patrick Britton 3c4680bdd7 Initial commit: Complete threaded conversation system with inline replies
**Major Features Added:**
- **Inline Reply System**: Replace compose screen with inline reply boxes
- **Thread Navigation**: Parent/child navigation with jump functionality
- **Chain Flow UI**: Reply counts, expand/collapse animations, visual hierarchy
- **Enhanced Animations**: Smooth transitions, hover effects, micro-interactions

 **Frontend Changes:**
- **ThreadedCommentWidget**: Complete rewrite with animations and navigation
- **ThreadNode Model**: Added parent references and descendant counting
- **ThreadedConversationScreen**: Integrated navigation handlers
- **PostDetailScreen**: Replaced with threaded conversation view
- **ComposeScreen**: Added reply indicators and context
- **PostActions**: Fixed visibility checks for chain buttons

 **Backend Changes:**
- **API Route**: Added /posts/:id/thread endpoint
- **Post Repository**: Include allow_chain and visibility fields in feed
- **Thread Handler**: Support for fetching post chains

 **UI/UX Improvements:**
- **Reply Context**: Clear indication when replying to specific posts
- **Character Counting**: 500 character limit with live counter
- **Visual Hierarchy**: Depth-based indentation and styling
- **Smooth Animations**: SizeTransition, FadeTransition, hover states
- **Chain Navigation**: Parent/child buttons with visual feedback

 **Technical Enhancements:**
- **Animation Controllers**: Proper lifecycle management
- **State Management**: Clean separation of concerns
- **Navigation Callbacks**: Reusable navigation system
- **Error Handling**: Graceful fallbacks and user feedback

This creates a Reddit-style threaded conversation experience with smooth
animations, inline replies, and intuitive navigation between posts in a chain.
2026-01-30 07:40:19 -06:00

158 lines
4.9 KiB
TypeScript

import { serve } from 'https://deno.land/std@0.177.0/http/server.ts';
import { S3Client, DeleteObjectCommand } from 'https://esm.sh/@aws-sdk/client-s3@3.470.0';
import { createServiceClient } from '../_shared/supabase-client.ts';
const ALLOWED_ORIGIN = Deno.env.get('ALLOWED_ORIGIN') || 'https://gosojorn.com';
const corsHeaders = {
'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
const R2_ENDPOINT = (Deno.env.get('R2_ENDPOINT') ?? '').trim();
const R2_ACCOUNT_ID = (Deno.env.get('R2_ACCOUNT_ID') ?? '').trim();
const R2_ACCESS_KEY_ID = (Deno.env.get('R2_ACCESS_KEY_ID') ?? Deno.env.get('R2_ACCESS_KEY') ?? '').trim();
const R2_SECRET_ACCESS_KEY = (Deno.env.get('R2_SECRET_ACCESS_KEY') ?? Deno.env.get('R2_SECRET_KEY') ?? '').trim();
const R2_BUCKET_NAME = (Deno.env.get('R2_BUCKET_NAME') ?? '').trim();
const DEFAULT_BUCKET_NAME = 'sojorn-media';
const RESOLVED_ENDPOINT = R2_ENDPOINT || (R2_ACCOUNT_ID ? `https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com` : '');
const RESOLVED_BUCKET = R2_BUCKET_NAME || DEFAULT_BUCKET_NAME;
const supabase = createServiceClient();
function extractObjectKey(imageUrl: string, bucketName: string): string | null {
try {
const url = new URL(imageUrl);
let key = url.pathname.replace(/^\/+/, '');
if (!key) return null;
if (bucketName && key.startsWith(`${bucketName}/`)) {
key = key.slice(bucketName.length + 1);
}
return decodeURIComponent(key);
} catch (_) {
return null;
}
}
serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: { ...corsHeaders, 'Access-Control-Allow-Methods': 'POST OPTIONS' } });
}
if (req.method !== 'POST') {
return new Response(JSON.stringify({ error: 'Method not allowed' }), {
status: 405,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
if (!RESOLVED_ENDPOINT || !R2_ACCESS_KEY_ID || !R2_SECRET_ACCESS_KEY || !RESOLVED_BUCKET) {
return new Response(JSON.stringify({ error: 'Missing R2 configuration' }), {
status: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
const r2 = new S3Client({
region: 'auto',
endpoint: RESOLVED_ENDPOINT,
credentials: {
accessKeyId: R2_ACCESS_KEY_ID,
secretAccessKey: R2_SECRET_ACCESS_KEY,
},
forcePathStyle: true,
});
try {
const maxBatches = 50;
const batchSize = 100;
const maxRuntimeMs = 25000;
const startTime = Date.now();
let processedCount = 0;
let deletedCount = 0;
let skippedCount = 0;
let batches = 0;
while (batches < maxBatches && Date.now() - startTime < maxRuntimeMs) {
const { data: posts, error } = await supabase
.from('posts')
.select('id, image_url, expires_at')
.lt('expires_at', new Date().toISOString())
.order('expires_at', { ascending: true })
.limit(batchSize);
if (error) {
console.error('Error fetching expired posts:', error);
return new Response(JSON.stringify({ error: 'Failed to fetch expired posts' }), {
status: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
const expiredPosts = posts ?? [];
if (expiredPosts.length === 0) break;
processedCount += expiredPosts.length;
batches += 1;
for (const post of expiredPosts) {
if (post.image_url) {
const key = extractObjectKey(post.image_url, RESOLVED_BUCKET);
if (!key) {
console.error('Could not parse image key:', { post_id: post.id, image_url: post.image_url });
skippedCount += 1;
continue;
}
try {
await r2.send(
new DeleteObjectCommand({
Bucket: RESOLVED_BUCKET,
Key: key,
})
);
} catch (error) {
console.error('R2 deletion failed:', { post_id: post.id, error });
skippedCount += 1;
continue;
}
}
const { error: deleteError } = await supabase
.from('posts')
.delete()
.eq('id', post.id);
if (deleteError) {
console.error('Failed to delete post row:', { post_id: post.id, error: deleteError });
skippedCount += 1;
continue;
}
deletedCount += 1;
}
}
return new Response(
JSON.stringify({
processed: processedCount,
deleted: deletedCount,
skipped: skippedCount,
batches,
}),
{
status: 200,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
}
);
} catch (error) {
console.error('Unexpected cleanup error:', error);
return new Response(JSON.stringify({ error: 'Internal server error' }), {
status: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
});