From a1f1e485a8cb97c19d7fa8d75a38dea6d156891e Mon Sep 17 00:00:00 2001 From: Brian Leung Date: Wed, 20 Sep 2023 21:33:03 -0700 Subject: [PATCH] youtube: Normalize timestamps to seconds --- .../clips/providers/youtube/youtube.test.ts | 4 +++ .../providers/youtube/youtubeProvider.ts | 25 ++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/features/clips/providers/youtube/youtube.test.ts b/src/features/clips/providers/youtube/youtube.test.ts index 5316b62..3bd617b 100644 --- a/src/features/clips/providers/youtube/youtube.test.ts +++ b/src/features/clips/providers/youtube/youtube.test.ts @@ -17,6 +17,10 @@ describe('youtubeProvider', () => { expect(youtubeProvider.getIdFromUrl('https://www.youtube.com/watch?v=1TewCPi92ro&t=30')).toEqual('1TewCPi92ro;30'); }); + it('gets clip info from www.youtube.com url with timestamp in hours/minutes/seconds', () => { + expect(youtubeProvider.getIdFromUrl('https://www.youtube.com/watch?v=1TewCPi92ro&t=1m42s1h')).toEqual('1TewCPi92ro;3702'); + }); + it('gets clip info from youtu.be url', () => { expect(youtubeProvider.getIdFromUrl('https://youtu.be/1TewCPi92ro')).toEqual('1TewCPi92ro'); }); diff --git a/src/features/clips/providers/youtube/youtubeProvider.ts b/src/features/clips/providers/youtube/youtubeProvider.ts index c771686..6af6048 100644 --- a/src/features/clips/providers/youtube/youtubeProvider.ts +++ b/src/features/clips/providers/youtube/youtubeProvider.ts @@ -28,7 +28,30 @@ class YoutubeProvider implements ClipProvider { const startTime = uri.searchParams.get('t') ?? undefined; if (startTime) { - return `${id};${startTime}`; + const chunks = startTime.split(/([hms])/).filter(chunk => chunk !== ''); + const magnitudes = chunks.filter(chunk => chunk.match(/[0-9]+/)).map(chunk => parseInt(chunk)); + const UNITS = ['h', 'm', 's']; + const seenUnits = chunks.filter(chunk => UNITS.includes(chunk)); + + if (chunks.length === 1) { + return `${id};${chunks[0]}`; + } else { + const normalizedStartTime = magnitudes.reduce((accum, magnitude, index) => { + let conversionFactor = 0; + + if (seenUnits[index] === 'h') { + conversionFactor = 3600; + } else if (seenUnits[index] === 'm') { + conversionFactor = 60; + } else if (seenUnits[index] === 's') { + conversionFactor = 1; + } + + return accum + magnitude * conversionFactor; + }, 0); + + return `${id};${normalizedStartTime}`; + } } else { return id; }