|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import { InjectModel } from '@nestjs/mongoose'; |
| 3 | +import { Cron, CronExpression } from '@nestjs/schedule'; |
| 4 | +import { TypesenseService } from '@server/typesense/typesense.service'; |
| 5 | +import { Model } from 'mongoose'; |
| 6 | + |
| 7 | +import { Song as SongEntity, SongPreviewDto } from '@nbw/database'; |
| 8 | +import type { SongWithUser } from '@nbw/database'; |
| 9 | + |
| 10 | +@Injectable() |
| 11 | +export class SongIndexingService { |
| 12 | + private readonly logger = new Logger(SongIndexingService.name); |
| 13 | + private readonly batchSize = 50; |
| 14 | + |
| 15 | + constructor( |
| 16 | + @InjectModel(SongEntity.name) |
| 17 | + private songModel: Model<SongEntity>, |
| 18 | + private typesenseService: TypesenseService, |
| 19 | + ) {} |
| 20 | + |
| 21 | + @Cron(CronExpression.EVERY_5_MINUTES) |
| 22 | + async indexUnindexedSongs() { |
| 23 | + try { |
| 24 | + this.logger.log('Starting batch indexing of unindexed songs...'); |
| 25 | + |
| 26 | + // Find songs that are not indexed and are public |
| 27 | + const unindexedSongs = await this.songModel |
| 28 | + .find({ |
| 29 | + $or: [ |
| 30 | + { searchIndexed: false }, |
| 31 | + { searchIndexed: { $exists: false } }, |
| 32 | + { searchIndexed: null }, |
| 33 | + ], |
| 34 | + visibility: 'public', // Exclude private songs |
| 35 | + }) |
| 36 | + .limit(this.batchSize) |
| 37 | + .populate('uploader', 'username displayName profileImage -_id') |
| 38 | + .lean() // Use lean() to get plain JavaScript objects |
| 39 | + .exec(); |
| 40 | + |
| 41 | + if (unindexedSongs.length === 0) { |
| 42 | + this.logger.log('No unindexed songs found'); |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + this.logger.log(`Found ${unindexedSongs.length} unindexed songs`); |
| 47 | + |
| 48 | + // Debug: Log first song to see what fields are present |
| 49 | + if (unindexedSongs.length > 0) { |
| 50 | + const firstSong = unindexedSongs[0]; |
| 51 | + this.logger.debug( |
| 52 | + `First song sample - Has stats: ${!!firstSong.stats}, Has uploader: ${!!firstSong.uploader}`, |
| 53 | + ); |
| 54 | + if (firstSong.stats) { |
| 55 | + this.logger.debug( |
| 56 | + `Stats sample - duration: ${firstSong.stats.duration}, noteCount: ${firstSong.stats.noteCount}`, |
| 57 | + ); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // Convert to SongPreviewDto format, filtering out songs with missing data |
| 62 | + const songPreviews = unindexedSongs |
| 63 | + .filter((song) => { |
| 64 | + if (!song.stats) { |
| 65 | + this.logger.warn( |
| 66 | + `Song ${song.publicId} has no stats field, skipping indexing`, |
| 67 | + ); |
| 68 | + return false; |
| 69 | + } |
| 70 | + if (!song.stats.duration || !song.stats.noteCount) { |
| 71 | + this.logger.warn( |
| 72 | + `Song ${song.publicId} has incomplete stats, skipping indexing`, |
| 73 | + ); |
| 74 | + return false; |
| 75 | + } |
| 76 | + return true; |
| 77 | + }) |
| 78 | + .map((song) => { |
| 79 | + const songWithUser = song as unknown as SongWithUser; |
| 80 | + return SongPreviewDto.fromSongDocumentWithUser(songWithUser); |
| 81 | + }); |
| 82 | + |
| 83 | + if (songPreviews.length === 0) { |
| 84 | + this.logger.warn('No valid songs to index after filtering'); |
| 85 | + return; |
| 86 | + } |
| 87 | + |
| 88 | + // Index songs in Typesense |
| 89 | + await this.typesenseService.indexSongs(songPreviews); |
| 90 | + |
| 91 | + // Mark only the successfully indexed songs |
| 92 | + const indexedSongIds = unindexedSongs |
| 93 | + .filter( |
| 94 | + (song) => song.stats && song.stats.duration && song.stats.noteCount, |
| 95 | + ) |
| 96 | + .map((song) => song._id); |
| 97 | + |
| 98 | + await this.songModel.updateMany( |
| 99 | + { _id: { $in: indexedSongIds } }, |
| 100 | + { $set: { searchIndexed: true } }, |
| 101 | + ); |
| 102 | + |
| 103 | + this.logger.log(`Successfully indexed ${songPreviews.length} songs`); |
| 104 | + } catch (error) { |
| 105 | + this.logger.error('Error during batch indexing:', error); |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + /** |
| 110 | + * Manually trigger indexing of all songs |
| 111 | + * This is useful for initial setup or reindexing |
| 112 | + */ |
| 113 | + async reindexAllSongs() { |
| 114 | + this.logger.log('Starting full reindex of all songs...'); |
| 115 | + |
| 116 | + try { |
| 117 | + // Reset searchIndexed flag for all public songs |
| 118 | + await this.songModel.updateMany( |
| 119 | + { visibility: 'public' }, |
| 120 | + { $set: { searchIndexed: false } }, |
| 121 | + ); |
| 122 | + |
| 123 | + this.logger.log('Reset searchIndexed flag for all public songs'); |
| 124 | + |
| 125 | + // Recreate the collection in Typesense |
| 126 | + await this.typesenseService.recreateCollection(); |
| 127 | + |
| 128 | + this.logger.log('Recreated Typesense collection'); |
| 129 | + |
| 130 | + // Index songs in batches |
| 131 | + let processedCount = 0; |
| 132 | + let hasMore = true; |
| 133 | + |
| 134 | + while (hasMore) { |
| 135 | + const songs = await this.songModel |
| 136 | + .find({ |
| 137 | + visibility: 'public', |
| 138 | + searchIndexed: false, |
| 139 | + }) |
| 140 | + .limit(this.batchSize) |
| 141 | + .populate('uploader', 'username displayName profileImage -_id') |
| 142 | + .lean() |
| 143 | + .exec(); |
| 144 | + |
| 145 | + if (songs.length === 0) { |
| 146 | + hasMore = false; |
| 147 | + break; |
| 148 | + } |
| 149 | + |
| 150 | + const songPreviews = songs |
| 151 | + .filter((song) => { |
| 152 | + if (!song.stats) { |
| 153 | + this.logger.warn( |
| 154 | + `Song ${song.publicId} has no stats field, skipping indexing`, |
| 155 | + ); |
| 156 | + return false; |
| 157 | + } |
| 158 | + if (!song.stats.duration || !song.stats.noteCount) { |
| 159 | + this.logger.warn( |
| 160 | + `Song ${song.publicId} has incomplete stats, skipping indexing`, |
| 161 | + ); |
| 162 | + return false; |
| 163 | + } |
| 164 | + return true; |
| 165 | + }) |
| 166 | + .map((song) => { |
| 167 | + const songWithUser = song as unknown as SongWithUser; |
| 168 | + return SongPreviewDto.fromSongDocumentWithUser(songWithUser); |
| 169 | + }); |
| 170 | + |
| 171 | + if (songPreviews.length === 0) { |
| 172 | + this.logger.warn('No valid songs to index in this batch'); |
| 173 | + continue; |
| 174 | + } |
| 175 | + |
| 176 | + await this.typesenseService.indexSongs(songPreviews); |
| 177 | + |
| 178 | + // Mark only the successfully indexed songs |
| 179 | + const indexedSongIds = songs |
| 180 | + .filter( |
| 181 | + (song) => song.stats && song.stats.duration && song.stats.noteCount, |
| 182 | + ) |
| 183 | + .map((song) => song._id); |
| 184 | + |
| 185 | + await this.songModel.updateMany( |
| 186 | + { _id: { $in: indexedSongIds } }, |
| 187 | + { $set: { searchIndexed: true } }, |
| 188 | + ); |
| 189 | + |
| 190 | + processedCount += songPreviews.length; |
| 191 | + this.logger.log(`Indexed ${processedCount} songs so far...`); |
| 192 | + } |
| 193 | + |
| 194 | + this.logger.log( |
| 195 | + `Full reindex complete. Total songs indexed: ${processedCount}`, |
| 196 | + ); |
| 197 | + } catch (error) { |
| 198 | + this.logger.error('Error during full reindex:', error); |
| 199 | + throw error; |
| 200 | + } |
| 201 | + } |
| 202 | +} |
0 commit comments