refactor(api): improve logging around spotify crawling loop

This commit is contained in:
Julian Tölle 2020-11-21 17:43:04 +01:00
parent 3aa90797c1
commit 9869f0a061

View file

@ -1,6 +1,7 @@
import { Injectable } from "@nestjs/common"; import { Injectable } from "@nestjs/common";
import { Interval } from "@nestjs/schedule"; import { Interval, Timeout } from "@nestjs/schedule";
import { ListensService } from "../../listens/listens.service"; import { ListensService } from "../../listens/listens.service";
import { Logger } from "../../logger/logger.service";
import { Album } from "../../music-library/album.entity"; import { Album } from "../../music-library/album.entity";
import { Artist } from "../../music-library/artist.entity"; import { Artist } from "../../music-library/artist.entity";
import { MusicLibraryService } from "../../music-library/music-library.service"; import { MusicLibraryService } from "../../music-library/music-library.service";
@ -24,11 +25,15 @@ export class SpotifyService {
private readonly listensService: ListensService, private readonly listensService: ListensService,
private readonly musicLibraryService: MusicLibraryService, private readonly musicLibraryService: MusicLibraryService,
private readonly spotifyApi: SpotifyApiService, private readonly spotifyApi: SpotifyApiService,
private readonly spotifyAuth: SpotifyAuthService private readonly spotifyAuth: SpotifyAuthService,
) {} private readonly logger: Logger
) {
this.logger.setContext(this.constructor.name);
}
@Interval(20 * 1000) @Interval(20 * 1000)
async getRecentlyPlayedTracks(): Promise<void> { async getRecentlyPlayedTracks(): Promise<void> {
this.logger.debug("Starting Spotify crawler loop");
const users = await this.usersService.findAll(); const users = await this.usersService.findAll();
for (const user of users) { for (const user of users) {
@ -40,6 +45,8 @@ export class SpotifyService {
user: User, user: User,
retryOnExpiredToken: boolean = true retryOnExpiredToken: boolean = true
): Promise<void> { ): Promise<void> {
this.logger.debug(`Importing recently played track for user "${user.id}"`);
let playHistory: PlayHistoryObject[]; let playHistory: PlayHistoryObject[];
try { try {
playHistory = await this.spotifyApi.getRecentlyPlayedTracks(user.spotify); playHistory = await this.spotifyApi.getRecentlyPlayedTracks(user.spotify);
@ -55,9 +62,8 @@ export class SpotifyService {
await this.processUser(user, false); await this.processUser(user, false);
} else { } else {
// TODO sent to sentry // TODO sent to sentry
console.error( this.logger.error(
"Unexpected error while fetching recently played tracks", `Unexpected error while fetching recently played tracks: ${err}`
err
); );
} }
@ -80,8 +86,12 @@ export class SpotifyService {
playedAt: new Date(history.played_at), playedAt: new Date(history.played_at),
}); });
console.log( this.logger.debug(
`Found Listen!: ${user.displayName} listened to "${track.name}" by "${track.artists}"` `New listen found! ${user.id} listened to "${
track.name
}" by ${track.artists
?.map((artist) => `"${artist.name}"`)
.join(", ")}`
); );
}) })
); );
@ -93,10 +103,11 @@ export class SpotifyService {
.pop() .pop()
); );
console.log("newestPlayTime", { this.logger.debug(
newestPlayTime, `Updating last refresh time for user ${
times: playHistory.map((history) => history.played_at).sort(), user.id
}); }, new time: ${newestPlayTime.toISOString()}`
);
this.usersService.updateSpotifyConnection(user, { this.usersService.updateSpotifyConnection(user, {
...user.spotify, ...user.spotify,
@ -241,22 +252,25 @@ export class SpotifyService {
private async refreshAppAccessToken(): Promise<void> { private async refreshAppAccessToken(): Promise<void> {
if (!this.appAccessTokenInProgress) { if (!this.appAccessTokenInProgress) {
console.log("refreshAppAccessToken"); this.logger.debug("refreshing spotify app access token");
this.appAccessTokenInProgress = new Promise(async (resolve, reject) => { this.appAccessTokenInProgress = new Promise(async (resolve, reject) => {
try { try {
const newAccessToken = await this.spotifyAuth.clientCredentialsGrant(); const newAccessToken = await this.spotifyAuth.clientCredentialsGrant();
this.appAccessToken = newAccessToken; this.appAccessToken = newAccessToken;
this.logger.debug("spotify app access token refreshed");
resolve(); resolve();
} catch (err) { } catch (err) {
this.logger.warn(
`Error while refreshing spotify app access token ${err}`
);
reject(err); reject(err);
} finally { } finally {
this.appAccessTokenInProgress = null; this.appAccessTokenInProgress = null;
} }
}); });
} else {
console.log(
"refreshAppAccessToken already in progress, awaiting its result"
);
} }
return this.appAccessTokenInProgress; return this.appAccessTokenInProgress;