background.js 1.2 KiB

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