background.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // Background script for the extension
  2. browser.storage.local.get("playlists").then(function (data) {
  3. if (!data.playlists) {
  4. console.log("pre-populating playlists");
  5. browser.storage.local.set({
  6. playlists: {
  7. "listening-long": [],
  8. "listening-short": [],
  9. "listening-misc": [],
  10. "watching-short": [],
  11. "watching-long": [],
  12. "slow-tv": [],
  13. },
  14. });
  15. } else {
  16. console.log("no need to pre-populate playlists");
  17. }
  18. });
  19. browser.storage.local.get("history").then(function (data) {
  20. if (!data.history) {
  21. console.log("pre-populating history");
  22. browser.storage.local.set({
  23. history: {},
  24. });
  25. } else {
  26. console.log("no need to pre-populate history");
  27. }
  28. });
  29. // Create context menu items when the extension is installed
  30. browser.runtime.onInstalled.addListener(() => {
  31. // Parent menu item
  32. browser.contextMenus.create({
  33. id: "my-playlist-menu",
  34. title: "Add to Playlist",
  35. contexts: ["link"],
  36. targetUrlPatterns: ["https://*.youtube.com/watch*"],
  37. });
  38. // Sub-menu items
  39. browser.contextMenus.create({
  40. id: "listening-long",
  41. parentId: "my-playlist-menu",
  42. title: "Listening - Long",
  43. contexts: ["link"],
  44. });
  45. browser.contextMenus.create({
  46. id: "listening-short",
  47. parentId: "my-playlist-menu",
  48. title: "Listening - Short",
  49. contexts: ["link"],
  50. });
  51. browser.contextMenus.create({
  52. id: "listening-misc",
  53. parentId: "my-playlist-menu",
  54. title: "Listening - Misc",
  55. contexts: ["link"],
  56. });
  57. // Separator
  58. browser.contextMenus.create({
  59. id: "separator-1",
  60. parentId: "my-playlist-menu",
  61. type: "separator",
  62. contexts: ["link"],
  63. });
  64. browser.contextMenus.create({
  65. id: "watching-short",
  66. parentId: "my-playlist-menu",
  67. title: "Watching - Short",
  68. contexts: ["link"],
  69. });
  70. browser.contextMenus.create({
  71. id: "watching-long",
  72. parentId: "my-playlist-menu",
  73. title: "Watching - Long",
  74. contexts: ["link"],
  75. });
  76. browser.contextMenus.create({
  77. id: "slow-tv",
  78. parentId: "my-playlist-menu",
  79. title: "Slow TV",
  80. contexts: ["link"],
  81. });
  82. });
  83. // Context menu click handler
  84. browser.contextMenus.onClicked.addListener(async (item, _tab) => {
  85. PlaylistUtils.addLinkToPlaylist(item.menuItemId, item);
  86. });
  87. // Function to navigate a tab to a new URL
  88. function navigateTab(tabId, url) {
  89. return browser.tabs.update(tabId, { url: url });
  90. }
  91. async function updateTracking(message) {
  92. // Get current playlists from storage
  93. const { playlists } = await browser.storage.local.get("playlists");
  94. // Find the video in playlists using shared utils
  95. const result = PlaylistUtils.findVideoInPlaylists(playlists, message.url);
  96. // If the video is not present in any playlist, do nothing
  97. if (!result) {
  98. return;
  99. }
  100. const [playlistName, videoIndex, _] = result;
  101. // Only update for pause and ended events
  102. if (message.type === "pause" || message.type === "ended") {
  103. // Create a copy of the playlist for immutability
  104. const updatedPlaylists = { ...playlists };
  105. const targetPlaylist = [...updatedPlaylists[playlistName]];
  106. // Get the current video object
  107. const video = { ...targetPlaylist[videoIndex] };
  108. // Update the video's status based on message type
  109. if (message.type === "pause") {
  110. video.status = message.timestamp; // Set status to current timestamp
  111. } else if (message.type === "ended") {
  112. video.status = "done"; // Set status to "done"
  113. }
  114. // Update the video in the playlist
  115. targetPlaylist[videoIndex] = video;
  116. updatedPlaylists[playlistName] = targetPlaylist;
  117. // Save the updated playlists back to storage
  118. await browser.storage.local.set({ playlists: updatedPlaylists });
  119. }
  120. }
  121. async function updateHistory(message) {
  122. const { history: currentHistory } =
  123. await browser.storage.local.get("history");
  124. const q = new URL(message.url);
  125. const v = q.searchParams.get("v");
  126. if (currentHistory[v]) {
  127. const { [v]: existing, ...rest } = currentHistory;
  128. const shouldIgnore =
  129. message.type === "playing" &&
  130. existing?.history?.length > 0 &&
  131. (existing.history[existing.history.length - 1].action === "play" ||
  132. existing.history[existing.history.length - 1].action === "playing") &&
  133. message.timestamp ===
  134. existing.history[existing.history.length - 1].position;
  135. if (!shouldIgnore) {
  136. await browser.storage.local.set({
  137. history: {
  138. [v]: {
  139. ...existing,
  140. title: message.title,
  141. duration:
  142. !isNaN(existing.duration) && isFinite(existing.duration)
  143. ? Math.max(message.duration, existing.duration)
  144. : message.duration,
  145. history: [
  146. ...existing.history,
  147. {
  148. action: message.type,
  149. position: message.timestamp,
  150. timestamp: Date.now(),
  151. },
  152. ],
  153. },
  154. ...rest,
  155. },
  156. });
  157. }
  158. } else {
  159. await browser.storage.local.set({
  160. history: {
  161. [v]: {
  162. url: message.url,
  163. title: message.title,
  164. duration: message.duration,
  165. history: [
  166. {
  167. action: message.type,
  168. position: message.timestamp,
  169. timestamp: Date.now(),
  170. },
  171. ],
  172. },
  173. ...currentHistory,
  174. },
  175. });
  176. }
  177. }
  178. function findNext(playlists, url) {
  179. const result = PlaylistUtils.findVideoInPlaylists(playlists, url);
  180. if (!result) {
  181. return false; // Not found in any playlist
  182. }
  183. const [playlistName, videoIndex, isLastVideo] = result;
  184. if (isLastVideo) {
  185. return false; // Last video, no next video available
  186. } else {
  187. // Get next video in the playlist
  188. const nextVideo = playlists[playlistName][videoIndex + 1];
  189. console.log("FOUND VIDEO", playlists[playlistName][videoIndex]);
  190. return nextVideo;
  191. }
  192. }
  193. async function navigateAndWait(tabId, url) {
  194. return new Promise((resolve) => {
  195. const listener = (details) => {
  196. if (details.tabId === tabId && details.frameId === 0) {
  197. browser.webNavigation.onCompleted.removeListener(listener);
  198. setTimeout(resolve, 500);
  199. }
  200. };
  201. browser.webNavigation.onCompleted.addListener(listener);
  202. browser.tabs.update(tabId, { url });
  203. });
  204. }
  205. async function advance(tabId, url) {
  206. const { playlists } = await browser.storage.local.get("playlists");
  207. const nextVideo = await findNext(playlists, url);
  208. if (nextVideo) {
  209. await navigateAndWait(tabId, nextVideo.url);
  210. await browser.tabs.sendMessage(tabId, { type: "autoplay" });
  211. }
  212. }
  213. // Listen for messages from popup or content scripts
  214. browser.runtime.onMessage.addListener((message, sender, _sendResponse) => {
  215. console.log("MESSAGE", message, sender);
  216. switch (message.type) {
  217. case "play":
  218. case "playing":
  219. case "pause":
  220. updateTracking(message);
  221. updateHistory(message);
  222. break;
  223. case "ended":
  224. updateTracking(message);
  225. updateHistory(message);
  226. advance(sender.tab.id, message.url);
  227. break;
  228. }
  229. });