|
| 1 | +import { NextRequest, NextResponse } from 'next/server'; |
| 2 | +import { createClient } from '@supabase/supabase-js'; |
| 3 | +import webpush from 'web-push'; |
| 4 | + |
| 5 | +// Configure web-push with your VAPID keys |
| 6 | +webpush.setVapidDetails( |
| 7 | + 'mailto:your-email@example.com', |
| 8 | + process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!, |
| 9 | + process.env.VAPID_PRIVATE_KEY! |
| 10 | +); |
| 11 | + |
| 12 | +export async function POST(request: NextRequest) { |
| 13 | + try { |
| 14 | + console.log('Environment check:'); |
| 15 | + console.log('SUPABASE_URL:', process.env.NEXT_PUBLIC_SUPABASE_URL); |
| 16 | + console.log('SERVICE_ROLE_KEY exists:', !!process.env.SUPABASE_SERVICE_ROLE_KEY); |
| 17 | + console.log('VAPID_PUBLIC_KEY exists:', !!process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY); |
| 18 | + console.log('VAPID_PRIVATE_KEY exists:', !!process.env.VAPID_PRIVATE_KEY); |
| 19 | + |
| 20 | + // Check if we're in Docker environment |
| 21 | + const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.includes('127.0.0.1') |
| 22 | + ? process.env.NEXT_PUBLIC_SUPABASE_URL?.replace('127.0.0.1', 'host.docker.internal') |
| 23 | + : process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 24 | + |
| 25 | + console.log('Using Supabase URL:', supabaseUrl); |
| 26 | + |
| 27 | + if (!supabaseUrl || !process.env.SUPABASE_SERVICE_ROLE_KEY) { |
| 28 | + return NextResponse.json({ |
| 29 | + error: 'Missing required environment variables', |
| 30 | + details: { |
| 31 | + hasUrl: !!supabaseUrl, |
| 32 | + hasServiceKey: !!process.env.SUPABASE_SERVICE_ROLE_KEY |
| 33 | + } |
| 34 | + }, { status: 500 }); |
| 35 | + } |
| 36 | + |
| 37 | + // Create Supabase client with service role for admin access |
| 38 | + const supabase = createClient( |
| 39 | + supabaseUrl, |
| 40 | + process.env.SUPABASE_SERVICE_ROLE_KEY! |
| 41 | + ); |
| 42 | + |
| 43 | + console.log('Attempting to fetch subscriptions...'); |
| 44 | + |
| 45 | + // Get all push subscriptions, but deduplicate by endpoint to avoid sending multiple notifications to the same device |
| 46 | + const { data: allSubscriptions, error } = await supabase |
| 47 | + .from('push_subscriptions') |
| 48 | + .select('*') |
| 49 | + .order('created_at', { ascending: false }); |
| 50 | + |
| 51 | + console.log('Supabase response:', { data: allSubscriptions, error }); |
| 52 | + |
| 53 | + if (error) { |
| 54 | + console.error('Error fetching subscriptions:', error); |
| 55 | + return NextResponse.json({ |
| 56 | + error: 'Failed to fetch subscriptions', |
| 57 | + details: error.message, |
| 58 | + code: error.code, |
| 59 | + hint: error.hint |
| 60 | + }, { status: 500 }); |
| 61 | + } |
| 62 | + |
| 63 | + if (!allSubscriptions || allSubscriptions.length === 0) { |
| 64 | + return NextResponse.json({ message: 'No subscriptions found' }, { status: 200 }); |
| 65 | + } |
| 66 | + |
| 67 | + // Deduplicate by endpoint - keep only the most recent subscription for each unique endpoint |
| 68 | + const uniqueEndpoints = new Map(); |
| 69 | + allSubscriptions.forEach(sub => { |
| 70 | + if (!uniqueEndpoints.has(sub.endpoint)) { |
| 71 | + uniqueEndpoints.set(sub.endpoint, sub); |
| 72 | + } |
| 73 | + }); |
| 74 | + |
| 75 | + const subscriptions = Array.from(uniqueEndpoints.values()); |
| 76 | + console.log(`Deduplicated from ${allSubscriptions.length} to ${subscriptions.length} unique endpoints`); |
| 77 | + |
| 78 | + // Parse request body for custom message |
| 79 | + const body = await request.json().catch(() => ({})); |
| 80 | + const title = body.title || 'Test Notification'; |
| 81 | + const message = body.message || 'This is a test push notification!'; |
| 82 | + const url = body.url || '/'; |
| 83 | + |
| 84 | + const payload = JSON.stringify({ |
| 85 | + title, |
| 86 | + body: message, |
| 87 | + url, |
| 88 | + icon: '/assets/Captn.jpg' |
| 89 | + }); |
| 90 | + |
| 91 | + console.log(`Sending test notification to ${subscriptions.length} subscribers`); |
| 92 | + |
| 93 | + // Send notifications to all subscribers |
| 94 | + const promises = subscriptions.map(async (subscription) => { |
| 95 | + try { |
| 96 | + const pushSubscription = { |
| 97 | + endpoint: subscription.endpoint, |
| 98 | + keys: { |
| 99 | + auth: subscription.auth, |
| 100 | + p256dh: subscription.p256dh |
| 101 | + } |
| 102 | + }; |
| 103 | + |
| 104 | + await webpush.sendNotification(pushSubscription, payload); |
| 105 | + console.log(`Sent notification to user ${subscription.profile_id}`); |
| 106 | + return { success: true, userId: subscription.profile_id }; |
| 107 | + } catch (error) { |
| 108 | + console.error(`Failed to send notification to user ${subscription.profile_id}:`, error); |
| 109 | + return { success: false, userId: subscription.profile_id, error: String(error) }; |
| 110 | + } |
| 111 | + }); |
| 112 | + |
| 113 | + const results = await Promise.all(promises); |
| 114 | + const successful = results.filter(r => r.success).length; |
| 115 | + const failed = results.filter(r => !r.success).length; |
| 116 | + |
| 117 | + return NextResponse.json({ |
| 118 | + message: `Sent ${successful} notifications successfully, ${failed} failed`, |
| 119 | + results |
| 120 | + }); |
| 121 | + |
| 122 | + } catch (error) { |
| 123 | + console.error('Error sending test notifications:', error); |
| 124 | + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); |
| 125 | + } |
| 126 | +} |
0 commit comments