A decentralized music tracking and discovery platform built on AT Protocol 馃幍
listenbrainz spotify atproto lastfm musicbrainz scrobbling
at main 101 lines 2.7 kB view raw
1import chalk from "chalk"; 2import { consola } from "consola"; 3import { ctx } from "context"; 4import { and, count, eq } from "drizzle-orm"; 5import tables from "schema"; 6import type { InsertArtistAlbum } from "schema/artist-albums"; 7 8const size = 100; 9const total = await ctx.db 10 .select({ value: count() }) 11 .from(tables.tracks) 12 .execute() 13 .then(([row]) => row.value); 14 15consola.info(`Total tracks to process: ${chalk.magentaBright(total)}`); 16 17for (let i = 0; i < total; i += size) { 18 const skip = i; 19 consola.info( 20 `Processing ${chalk.magentaBright("tracks")}: ${chalk.magentaBright(skip)} to ${chalk.magentaBright(skip + size)}`, 21 ); 22 const results = await ctx.db 23 .select() 24 .from(tables.tracks) 25 .limit(size) 26 .offset(skip) 27 .execute(); 28 29 for (const track of results) { 30 if (!track.artistUri || !track.albumUri) { 31 consola.info( 32 `Deleting album-track relationship for track: ${chalk.redBright(track.uri)}`, 33 ); 34 consola.info("artistUri", track.artistUri); 35 consola.info("albumUri", track.albumUri); 36 continue; 37 } 38 39 const found = await ctx.db 40 .select() 41 .from(tables.artistAlbums) 42 .leftJoin( 43 tables.artists, 44 eq(tables.artistAlbums.artistId, tables.artists.id), 45 ) 46 .leftJoin( 47 tables.albums, 48 eq(tables.artistAlbums.albumId, tables.albums.id), 49 ) 50 .where( 51 and( 52 eq(tables.artists.uri, track.artistUri), 53 eq(tables.albums.uri, track.albumUri), 54 ), 55 ) 56 .limit(1) 57 .execute() 58 .then((rows) => rows.length > 0); 59 60 if (!found) { 61 consola.info( 62 `Creating artist-album relationship for track: ${track.uri}`, 63 ); 64 const [artist, album] = await Promise.all([ 65 ctx.db 66 .select() 67 .from(tables.artists) 68 .where(eq(tables.artists.uri, track.artistUri)) 69 .limit(1) 70 .execute() 71 .then((rows) => rows[0]), 72 ctx.db 73 .select() 74 .from(tables.albums) 75 .where(eq(tables.albums.uri, track.albumUri)) 76 .limit(1) 77 .execute() 78 .then((rows) => rows[0]), 79 ]); 80 81 if (!artist || !album) { 82 consola.error( 83 `Artist-album relationship already exists for track: ${chalk.redBright(track.uri)}`, 84 ); 85 consola.info("artist", artist); 86 consola.info("album", album); 87 continue; 88 } 89 90 await ctx.db 91 .insert(tables.artistAlbums) 92 .values({ 93 artistId: artist.id, 94 albumId: album.id, 95 } as InsertArtistAlbum) 96 .execute(); 97 } 98 } 99} 100 101process.exit(0);