background.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 v = PlaylistUtils.extractVideoId(message.url);
  125. if (currentHistory[v]) {
  126. const { [v]: existing, ...rest } = currentHistory;
  127. const shouldIgnore =
  128. message.type === "playing" &&
  129. existing?.history?.length > 0 &&
  130. (existing.history[existing.history.length - 1].action === "play" ||
  131. existing.history[existing.history.length - 1].action === "playing") &&
  132. message.timestamp ===
  133. existing.history[existing.history.length - 1].position;
  134. if (!shouldIgnore) {
  135. await browser.storage.local.set({
  136. history: {
  137. [v]: {
  138. ...existing,
  139. title: message.title,
  140. duration:
  141. !isNaN(existing.duration) && isFinite(existing.duration)
  142. ? Math.max(message.duration, existing.duration)
  143. : message.duration,
  144. history: [
  145. ...existing.history,
  146. {
  147. action: message.type,
  148. position: message.timestamp,
  149. timestamp: Date.now(),
  150. },
  151. ],
  152. },
  153. ...rest,
  154. },
  155. });
  156. }
  157. } else {
  158. await browser.storage.local.set({
  159. history: {
  160. [v]: {
  161. url: message.url,
  162. title: message.title,
  163. duration: message.duration,
  164. history: [
  165. {
  166. action: message.type,
  167. position: message.timestamp,
  168. timestamp: Date.now(),
  169. },
  170. ],
  171. },
  172. ...currentHistory,
  173. },
  174. });
  175. }
  176. }
  177. function findNext(playlists, url) {
  178. const result = PlaylistUtils.findVideoInPlaylists(playlists, url);
  179. if (!result) {
  180. return false; // Not found in any playlist
  181. }
  182. const [playlistName, videoIndex, isLastVideo] = result;
  183. if (isLastVideo) {
  184. return false; // Last video, no next video available
  185. } else {
  186. // Get next video in the playlist
  187. const nextVideo = playlists[playlistName][videoIndex + 1];
  188. console.log("FOUND VIDEO", playlists[playlistName][videoIndex]);
  189. return nextVideo;
  190. }
  191. }
  192. async function navigateAndWait(tabId, url) {
  193. return new Promise((resolve) => {
  194. const listener = (details) => {
  195. if (details.tabId === tabId && details.frameId === 0) {
  196. browser.webNavigation.onCompleted.removeListener(listener);
  197. setTimeout(resolve, 500);
  198. }
  199. };
  200. browser.webNavigation.onCompleted.addListener(listener);
  201. browser.tabs.update(tabId, { url });
  202. });
  203. }
  204. async function advance(tabId, url) {
  205. const { playlists } = await browser.storage.local.get("playlists");
  206. const nextVideo = await findNext(playlists, url);
  207. if (nextVideo) {
  208. await navigateAndWait(tabId, nextVideo.url);
  209. await browser.tabs.sendMessage(tabId, { type: "autoplay" });
  210. }
  211. }
  212. // Listen for messages from popup or content scripts
  213. browser.runtime.onMessage.addListener((message, sender, _sendResponse) => {
  214. console.log("MESSAGE", message, sender);
  215. switch (message.type) {
  216. case "play":
  217. case "playing":
  218. case "pause":
  219. updateTracking(message);
  220. updateHistory(message);
  221. break;
  222. case "ended":
  223. updateTracking(message);
  224. updateHistory(message);
  225. advance(sender.tab.id, message.url);
  226. break;
  227. }
  228. });