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 Oct 3, 2023
1 parent 5899865 commit a1f1e48
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 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;
}
Expand Down

0 comments on commit a1f1e48

Please sign in to comment.