Skip to content

Commit

Permalink
youtube: Normalize timestamps to seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
leungbk committed Sep 21, 2023
1 parent 5899865 commit 4f54b51
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/features/clips/providers/youtube/youtube.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
Expand Down
25 changes: 24 additions & 1 deletion src/features/clips/providers/youtube/youtubeProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 TIME_UNITS = ['h', 'm', 's'];
const seen_units = chunks.filter(chunk => TIME_UNITS.includes(chunk));

if (chunks.length === 1) {
return `${id};${chunks[0]}`;
} else {
const normalizedStartTime = magnitudes.reduce((accum, magnitude, index) => {
let conversion_factor = 0;

if (seen_units[index] === 'h') {
conversion_factor = 3600;
} else if (seen_units[index] === 'm') {
conversion_factor = 60;
} else if (seen_units[index] === 's') {
conversion_factor = 1;
}

return accum + magnitude * conversion_factor;
}, 0);

return `${id};${normalizedStartTime}`;
}
} else {
return id;
}
Expand Down

0 comments on commit 4f54b51

Please sign in to comment.