AI Resource Pro / website / scripts / remove-duplicates.ts
| 1 | import { createClient } from '@supabase/supabase-js'; |
| 2 | import * as path from 'path'; |
| 3 | import * as dotenv from 'dotenv'; |
| 4 | import * as fs from 'fs'; |
| 5 | |
| 6 | // Load environment variables from .env.local |
| 7 | const envLocalPath = path.resolve(process.cwd(), '.env.local'); |
| 8 | if (fs.existsSync(envLocalPath)) { |
| 9 | console.log(`Loading environment from: ${envLocalPath}`); |
| 10 | dotenv.config({ path: envLocalPath }); |
| 11 | } else { |
| 12 | console.log(`No .env.local file found at: ${envLocalPath}`); |
| 13 | dotenv.config(); // Try loading from default .env |
| 14 | } |
| 15 | |
| 16 | // Helper function to normalize URLs for comparison |
| 17 | function normalizeUrl(url: string): string { |
| 18 | return url.trim() |
| 19 | .toLowerCase() |
| 20 | .replace(/^https?:\/\/(www\.)?/, '') // Remove protocol and www |
| 21 | .replace(/\/+$/, '') // Remove trailing slashes |
| 22 | .replace(/\?.*$/, ''); // Remove query parameters |
| 23 | } |
| 24 | |
| 25 | async function main() { |
| 26 | // Check for required environment variables |
| 27 | const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 28 | const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; |
| 29 | |
| 30 | if (!supabaseUrl || !supabaseServiceKey) { |
| 31 | console.error('Error: Missing required environment variables NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY'); |
| 32 | process.exit(1); |
| 33 | } |
| 34 | |
| 35 | // Initialize Supabase client |
| 36 | const supabase = createClient(supabaseUrl, supabaseServiceKey, { |
| 37 | auth: { |
| 38 | autoRefreshToken: false, |
| 39 | persistSession: false |
| 40 | } |
| 41 | }); |
| 42 | |
| 43 | try { |
| 44 | console.log('Fetching all news items...'); |
| 45 | |
| 46 | // Fetch all news items |
| 47 | const { data: allNews, error: fetchError } = await supabase |
| 48 | .from('news') |
| 49 | .select('id, title, url, source, article_date, created_at') |
| 50 | .order('article_date', { ascending: false }); |
| 51 | |
| 52 | if (fetchError) { |
| 53 | console.error('Error fetching news items:', fetchError); |
| 54 | return; |
| 55 | } |
| 56 | |
| 57 | if (!allNews || allNews.length === 0) { |
| 58 | console.log('No news items found.'); |
| 59 | return; |
| 60 | } |
| 61 | |
| 62 | console.log(`Found ${allNews.length} news items.`); |
| 63 | |
| 64 | // Create maps to track duplicates |
| 65 | const normalizedUrlMap = new Map(); |
| 66 | const titleSourceMap = new Map(); |
| 67 | const duplicateIds = new Set<number>(); |
| 68 | |
| 69 | // First pass: identify duplicates |
| 70 | for (const news of allNews) { |
| 71 | const normalizedUrl = normalizeUrl(news.url); |
| 72 | const titleSourceKey = `${news.title.toLowerCase().trim()}|${news.source.toLowerCase().trim()}`; |
| 73 | |
| 74 | // Check for URL duplicates |
| 75 | if (normalizedUrlMap.has(normalizedUrl)) { |
| 76 | const existing = normalizedUrlMap.get(normalizedUrl); |
| 77 | |
| 78 | // Keep the newer item (based on article_date, then created_at) |
| 79 | const existingDate = new Date(existing.article_date || existing.created_at); |
| 80 | const currentDate = new Date(news.article_date || news.created_at); |
| 81 | |
| 82 | if (existingDate >= currentDate) { |
| 83 | duplicateIds.add(news.id); |
| 84 | console.log(`Duplicate URL found: "${news.title}" (ID: ${news.id}) is a duplicate of ID: ${existing.id}`); |
| 85 | } else { |
| 86 | duplicateIds.add(existing.id); |
| 87 | normalizedUrlMap.set(normalizedUrl, news); |
| 88 | console.log(`Duplicate URL found: "${existing.title}" (ID: ${existing.id}) is a duplicate of ID: ${news.id}`); |
| 89 | } |
| 90 | } else { |
| 91 | normalizedUrlMap.set(normalizedUrl, news); |
| 92 | } |
| 93 | |
| 94 | // Check for title+source duplicates (if not already marked as duplicate) |
| 95 | if (!duplicateIds.has(news.id) && titleSourceMap.has(titleSourceKey)) { |
| 96 | const existing = titleSourceMap.get(titleSourceKey); |
| 97 | |
| 98 | // Skip if this is the same item we already processed by URL |
| 99 | if (existing.id === news.id) continue; |
| 100 | |
| 101 | // Keep the newer item (based on article_date, then created_at) |
| 102 | const existingDate = new Date(existing.article_date || existing.created_at); |
| 103 | const currentDate = new Date(news.article_date || news.created_at); |
| 104 | |
| 105 | if (existingDate >= currentDate) { |
| 106 | duplicateIds.add(news.id); |
| 107 | console.log(`Duplicate title+source found: "${news.title}" (ID: ${news.id}) is a duplicate of ID: ${existing.id}`); |
| 108 | } else { |
| 109 | duplicateIds.add(existing.id); |
| 110 | titleSourceMap.set(titleSourceKey, news); |
| 111 | console.log(`Duplicate title+source found: "${existing.title}" (ID: ${existing.id}) is a duplicate of ID: ${news.id}`); |
| 112 | } |
| 113 | } else if (!duplicateIds.has(news.id)) { |
| 114 | titleSourceMap.set(titleSourceKey, news); |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | // Second pass: check for similar URLs |
| 119 | for (const news of allNews) { |
| 120 | // Skip if already marked as duplicate |
| 121 | if (duplicateIds.has(news.id)) continue; |
| 122 | |
| 123 | const normalizedUrl = normalizeUrl(news.url); |
| 124 | |
| 125 | // Check for similar URLs |
| 126 | for (const [existingNormalized, existing] of normalizedUrlMap.entries()) { |
| 127 | // Skip if it's the same news item or if existing is already a duplicate |
| 128 | if (existing.id === news.id || duplicateIds.has(existing.id)) continue; |
| 129 | |
| 130 | // Skip if it's an exact match (already handled) |
| 131 | if (existingNormalized === normalizedUrl) continue; |
| 132 | |
| 133 | // Check for partial matches |
| 134 | if (existingNormalized.includes(normalizedUrl) || normalizedUrl.includes(existingNormalized)) { |
| 135 | // Keep the newer item (based on article_date, then created_at) |
| 136 | const existingDate = new Date(existing.article_date || existing.created_at); |
| 137 | const currentDate = new Date(news.article_date || news.created_at); |
| 138 | |
| 139 | if (existingDate >= currentDate) { |
| 140 | duplicateIds.add(news.id); |
| 141 | console.log(`Similar URL found: "${news.title}" (ID: ${news.id}) is similar to ID: ${existing.id}`); |
| 142 | console.log(` URL 1: ${news.url}`); |
| 143 | console.log(` URL 2: ${existing.url}`); |
| 144 | break; |
| 145 | } else { |
| 146 | duplicateIds.add(existing.id); |
| 147 | console.log(`Similar URL found: "${existing.title}" (ID: ${existing.id}) is similar to ID: ${news.id}`); |
| 148 | console.log(` URL 1: ${existing.url}`); |
| 149 | console.log(` URL 2: ${news.url}`); |
| 150 | // Update the map with the newer item |
| 151 | normalizedUrlMap.set(existingNormalized, news); |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | console.log(`Found ${duplicateIds.size} duplicate news items.`); |
| 158 | |
| 159 | if (duplicateIds.size === 0) { |
| 160 | console.log('No duplicates to remove.'); |
| 161 | return; |
| 162 | } |
| 163 | |
| 164 | // Confirm before deleting |
| 165 | console.log('Deleting duplicate news items...'); |
| 166 | |
| 167 | // Delete news_categories entries for duplicates |
| 168 | const { error: deleteJunctionError } = await supabase |
| 169 | .from('news_categories') |
| 170 | .delete() |
| 171 | .in('news_id', Array.from(duplicateIds)); |
| 172 | |
| 173 | if (deleteJunctionError) { |
| 174 | console.error('Error deleting news_categories entries:', deleteJunctionError); |
| 175 | } else { |
| 176 | console.log('Deleted news_categories entries for duplicates.'); |
| 177 | } |
| 178 | |
| 179 | // Delete duplicate news items |
| 180 | const { error: deleteNewsError } = await supabase |
| 181 | .from('news') |
| 182 | .delete() |
| 183 | .in('id', Array.from(duplicateIds)); |
| 184 | |
| 185 | if (deleteNewsError) { |
| 186 | console.error('Error deleting duplicate news items:', deleteNewsError); |
| 187 | } else { |
| 188 | console.log(`Successfully deleted ${duplicateIds.size} duplicate news items.`); |
| 189 | } |
| 190 | |
| 191 | // Get final count |
| 192 | const { count, error: countError } = await supabase |
| 193 | .from('news') |
| 194 | .select('*', { count: 'exact', head: true }); |
| 195 | |
| 196 | if (countError) { |
| 197 | console.error('Error getting final count:', countError); |
| 198 | } else { |
| 199 | console.log(`Final news item count: ${count}`); |
| 200 | } |
| 201 | |
| 202 | console.log('Duplicate removal completed successfully!'); |
| 203 | } catch (error) { |
| 204 | console.error('Error removing duplicates:', error); |
| 205 | throw error; |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | // Run the function |
| 210 | main() |
| 211 | .then(() => { |
| 212 | console.log('Process completed successfully'); |
| 213 | process.exit(0); |
| 214 | }) |
| 215 | .catch((error) => { |
| 216 | console.error('Process failed:', error); |
| 217 | process.exit(1); |
| 218 | }); |