background.js 1.2 KiB

12345678910111213141516171819202122232425262728293031323334
  1. import { makeRemotelyCallable } from 'webextension-rpc';
  2. // Format time as S, or M:SS, or H:MM:SS, depending on which would be needed to express maxSeconds.
  3. // E.g. secondsToString(12) === '12', but secondsToString(12, 3600) === '0:00:12'.
  4. function secondsToString(seconds, maxSeconds) {
  5. let s = `${Math.round(seconds % 60)}`;
  6. let m = '';
  7. let h = '';
  8. const minutes = Math.floor(seconds / 60);
  9. if (minutes || maxSeconds >= 60) {
  10. m = `${minutes % 60}:`;
  11. if (!/^\d\d/.test(s)) s = '0' + s;
  12. }
  13. if (seconds >= 60 * 60 || maxSeconds >= 60 * 60) {
  14. h = `${Math.floor(minutes / 60)}:`;
  15. if (m.length <= 2) m = '0' + m;
  16. }
  17. return `${h}${m}${s}`;
  18. }
  19. async function createBookmark({ url, start, end, trackDuration }) {
  20. // Create a (hopefully) meaningful title; e.g. 'filename.mp3 0:30–1:10'
  21. const filenameMatch = url.match(/.*\/([^\/#?]+)(?:\?.*)?(?:#.*)?/);
  22. const filename = filenameMatch ? filenameMatch[1] : 'Audio fragment';
  23. const startString = secondsToString(start, trackDuration);
  24. const endString = (end !== undefined)
  25. ? '–' + secondsToString(end, trackDuration)
  26. : '';
  27. const title = `${filename} ${startString}${endString}`;
  28. await browser.bookmarks.create({ url, title });
  29. }
  30. makeRemotelyCallable({ createBookmark });