popup.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. document.addEventListener("alpine:init", () => {
  2. //TODO
  3. // - preserve playlist order (sort)
  4. // - "play/resume playlist" button (pick up where you left off)
  5. // X track timestamp to truly resume where you left off
  6. // - periodically remove watched videos
  7. // - or move to an "old" category, and add a screen to see the list
  8. // - consider separating context menu items (rather than having a sub-menu)
  9. // - view playback history (?)
  10. // - include currently open tabs in export
  11. // - support playlist management (add, remove, rename playlists)
  12. // - support input text box for adding to playlist (how to handle title?)
  13. // - option (probably a button) to add current page (url, title) to playlist
  14. // - button to add channel to youtube page (copy gql mutation to clipboard) (like the automa version)
  15. // - long-term: replace youtube page? rss feeds? need server?
  16. // - add personal rating feature ("enjoyed", "this was important", etc)
  17. Alpine.data("playlistManager", () => ({
  18. playlists: {},
  19. currentIndices: {},
  20. history: {},
  21. sortedHistory: [],
  22. openMenus: new Set(), // Track which menus are open
  23. currentView: 'playlists', // Track current view: 'playlists', 'history', or 'playlist'
  24. currentPlaylistName: '', // Track which playlist is being viewed
  25. playlistsForDisplay: [], // Computed array for display
  26. currentPlaylistVideos: [], // Videos for current playlist view
  27. init() {
  28. this.loadPlaylists();
  29. this.loadHistory();
  30. // Add document click handler to close menus
  31. document.addEventListener('click', (e) => {
  32. // If click is not on a more button or menu, close all menus
  33. if (!e.target.closest('.more-menu-container')) {
  34. this.closeAllMenus();
  35. }
  36. });
  37. },
  38. async loadPlaylists() {
  39. try {
  40. const result = await browser.storage.local.get("playlists");
  41. console.log("LOAD RESULT", result.playlists);
  42. this.playlists = result.playlists || {};
  43. if (result.playlists) {
  44. this.currentIndices = Object.keys(result.playlists).reduce(
  45. (acc, pln) => {
  46. const ind = result.playlists[pln].findIndex(
  47. (v) => v.status !== "done",
  48. );
  49. if (ind === -1) {
  50. acc[pln] = result.playlists[pln].length;
  51. } else {
  52. acc[pln] = ind;
  53. }
  54. return acc;
  55. },
  56. {},
  57. );
  58. } else {
  59. this.currentIndices = {};
  60. }
  61. } catch (error) {
  62. console.error("Error loading playlists:", error);
  63. }
  64. this.updatePlaylistsForDisplay();
  65. },
  66. updatePlaylistsForDisplay() {
  67. this.playlistsForDisplay = Object.entries(this.playlists).map(([playlistName, videos]) => {
  68. const currentIndex = this.currentIndices[playlistName] || 0;
  69. const shouldShowTruncation = currentIndex > 0;
  70. const truncationText = shouldShowTruncation
  71. ? `(${currentIndex} previous video${currentIndex === 1 ? '' : 's'})`
  72. : '';
  73. // Get visible videos from current index onwards with original indices
  74. const visibleVideos = videos.slice(currentIndex).map((video, index) => ({
  75. ...video,
  76. originalIndex: currentIndex + index
  77. }));
  78. return {
  79. name: playlistName,
  80. videos: videos,
  81. visibleVideos: visibleVideos,
  82. shouldShowTruncation: shouldShowTruncation,
  83. truncationText: truncationText
  84. };
  85. });
  86. },
  87. updateCurrentPlaylistVideos() {
  88. if (!this.currentPlaylistName || !this.playlists[this.currentPlaylistName]) {
  89. this.currentPlaylistVideos = [];
  90. } else {
  91. this.currentPlaylistVideos = this.playlists[this.currentPlaylistName];
  92. }
  93. },
  94. async loadHistory() {
  95. try {
  96. const result = await browser.storage.local.get("history");
  97. console.log("LOAD HISTORY RESULT", result.history);
  98. this.history = result.history || {};
  99. this.sortHistoryByRecentInteraction();
  100. } catch (error) {
  101. console.error("Error loading history:", error);
  102. }
  103. },
  104. sortHistoryByRecentInteraction() {
  105. // Convert history object to array with video ID and sort by most recent interaction
  106. this.sortedHistory = Object.entries(this.history)
  107. .map(([videoId, videoData]) => {
  108. const lastInteraction = videoData.history.length > 0
  109. ? Math.max(...videoData.history.map(event => event.timestamp))
  110. : 0;
  111. // Pre-process events with formatted data for CSP compliance
  112. const processedEvents = videoData.history
  113. .slice()
  114. .reverse()
  115. .map((event, index) => ({
  116. ...event,
  117. formattedAction: this.formatActionName(event.action),
  118. formattedPosition: `at ${this.formatVideoPosition(event.position)}`,
  119. formattedTimestamp: this.formatTimestamp(event.timestamp),
  120. uniqueKey: `${videoId}-${event.timestamp}-${index}`
  121. }));
  122. return {
  123. videoId,
  124. formattedVideoId: `(${videoId})`,
  125. ...videoData,
  126. lastInteraction,
  127. processedEvents
  128. };
  129. })
  130. .sort((a, b) => b.lastInteraction - a.lastInteraction);
  131. },
  132. formatTimestamp(timestamp) {
  133. const date = new Date(timestamp);
  134. const now = new Date();
  135. const diffMs = now - date;
  136. const diffMins = Math.floor(diffMs / (1000 * 60));
  137. const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  138. const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  139. if (diffMins < 1) return 'Just now';
  140. if (diffMins < 60) return `${diffMins} minute${diffMins > 1 ? 's' : ''} ago`;
  141. if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
  142. if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
  143. return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
  144. },
  145. formatVideoPosition(seconds) {
  146. const minutes = Math.floor(seconds / 60);
  147. const remainingSeconds = Math.floor(seconds % 60);
  148. return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  149. },
  150. formatActionName(action) {
  151. const actionMap = {
  152. 'play': 'Started',
  153. 'playing': 'Playing',
  154. 'pause': 'Paused',
  155. 'ended': 'Finished'
  156. };
  157. return actionMap[action] || action;
  158. },
  159. formatPlaylistName(name) {
  160. // Convert "listening-1" to "Listening - 1"
  161. return name
  162. .split("-")
  163. .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
  164. .join(" - ");
  165. },
  166. openVideo(url) {
  167. browser.tabs.create({ url });
  168. },
  169. async removeVideo(playlistName, index) {
  170. const playlists = JSON.parse(JSON.stringify(this.playlists));
  171. // Make a copy of the current playlist
  172. const playlist = [...playlists[playlistName]];
  173. // Remove the video at the specified index
  174. playlist.splice(index, 1);
  175. // Create an updated playlists object with the remaining playlists unchanged
  176. const updatedPlaylists = {
  177. ...playlists,
  178. [playlistName]: playlist,
  179. };
  180. // Update the playlists in storage
  181. try {
  182. await browser.storage.local.set({ playlists: updatedPlaylists });
  183. this.playlists = updatedPlaylists;
  184. this.updatePlaylistsForDisplay();
  185. this.updateCurrentPlaylistVideos();
  186. } catch (error) {
  187. console.error("Error removing video:", error);
  188. }
  189. },
  190. async moveVideoUp(playlistName, index) {
  191. // Can't move the first item up
  192. if (index <= 0) return;
  193. const playlists = JSON.parse(JSON.stringify(this.playlists));
  194. // Make a copy of the current playlist
  195. const playlist = [...playlists[playlistName]];
  196. // Swap the video with the one above it
  197. [playlist[index], playlist[index - 1]] = [
  198. playlist[index - 1],
  199. playlist[index],
  200. ];
  201. // Create an updated playlists object
  202. const updatedPlaylists = {
  203. ...playlists,
  204. [playlistName]: playlist,
  205. };
  206. // Update the playlists in storage
  207. try {
  208. await browser.storage.local.set({ playlists: updatedPlaylists });
  209. this.playlists = updatedPlaylists;
  210. this.updatePlaylistsForDisplay();
  211. this.updateCurrentPlaylistVideos();
  212. } catch (error) {
  213. console.error("Error moving video up:", error);
  214. }
  215. },
  216. async moveVideoDown(playlistName, index) {
  217. const playlists = JSON.parse(JSON.stringify(this.playlists));
  218. const playlist = [...playlists[playlistName]];
  219. // Can't move the last item down
  220. if (index >= playlist.length - 1) return;
  221. // Swap the video with the one below it
  222. [playlist[index], playlist[index + 1]] = [
  223. playlist[index + 1],
  224. playlist[index],
  225. ];
  226. // Create an updated playlists object
  227. const updatedPlaylists = {
  228. ...playlists,
  229. [playlistName]: playlist,
  230. };
  231. // Update the playlists in storage
  232. try {
  233. await browser.storage.local.set({ playlists: updatedPlaylists });
  234. this.playlists = updatedPlaylists;
  235. this.updatePlaylistsForDisplay();
  236. this.updateCurrentPlaylistVideos();
  237. } catch (error) {
  238. console.error("Error moving video down:", error);
  239. }
  240. },
  241. async exportPlaylists() {
  242. try {
  243. // Get current playlists
  244. const playlistResult = await browser.storage.local.get("playlists");
  245. const playlists = playlistResult.playlists || {};
  246. // Get playback history
  247. const historyResult = await browser.storage.local.get("history");
  248. const playbackHistory = historyResult.history || {};
  249. // Create export data object
  250. const exportData = {
  251. playlists,
  252. playbackHistory,
  253. exportDate: new Date().toISOString(),
  254. };
  255. // Convert to JSON
  256. const jsonString = JSON.stringify(exportData, null, 2);
  257. // Create download
  258. const blob = new Blob([jsonString], { type: "application/json" });
  259. const url = URL.createObjectURL(blob);
  260. // Trigger download
  261. const a = document.createElement("a");
  262. a.href = url;
  263. a.download = `playlists-export-${new Date().toISOString().split("T")[0]}.json`;
  264. document.body.appendChild(a);
  265. a.click();
  266. // Clean up
  267. setTimeout(() => {
  268. document.body.removeChild(a);
  269. URL.revokeObjectURL(url);
  270. }, 100);
  271. } catch (error) {
  272. console.error("Error exporting playlists:", error);
  273. }
  274. },
  275. videotitle: {
  276. ["@click"]() {
  277. console.log("TITLE CLICK", this.$el);
  278. },
  279. },
  280. videoPlayLink: {
  281. ["@click.prevent"]() {
  282. browser.tabs.update({ url: this.$el.href });
  283. },
  284. },
  285. isCurrentVideo(playlistName, index) {
  286. const currentIndex = this.currentIndices[playlistName];
  287. return currentIndex === index;
  288. },
  289. isDoneVideo(playlistName, index) {
  290. const currentIndex = this.currentIndices[playlistName];
  291. return index < currentIndex;
  292. },
  293. videoItemClass: {
  294. [":class"]() {
  295. const playlistName = this.$el.dataset.playlistName;
  296. const index = parseInt(this.$el.dataset.playlistIndex);
  297. const video = this.playlists[playlistName][index];
  298. return {
  299. "current-video": this.isCurrentVideo(playlistName, index),
  300. "done-video":
  301. this.isDoneVideo(playlistName, index) && video.status === "done",
  302. };
  303. },
  304. },
  305. removeVideoButton: {
  306. ["@click"]() {
  307. this.removeVideo(
  308. this.$el.dataset.playlistName,
  309. this.$el.dataset.playlistIndex,
  310. );
  311. this.closeAllMenus();
  312. },
  313. },
  314. moveUpButton: {
  315. ["@click"]() {
  316. this.moveVideoUp(
  317. this.$el.dataset.playlistName,
  318. parseInt(this.$el.dataset.playlistIndex),
  319. );
  320. },
  321. [":disabled"]() {
  322. return parseInt(this.$el.dataset.playlistIndex) === 0;
  323. },
  324. },
  325. moveDownButton: {
  326. ["@click"]() {
  327. this.moveVideoDown(
  328. this.$el.dataset.playlistName,
  329. parseInt(this.$el.dataset.playlistIndex),
  330. );
  331. },
  332. [":disabled"]() {
  333. return (
  334. parseInt(this.$el.dataset.playlistIndex) ===
  335. this.playlists[this.$el.dataset.playlistName].length - 1
  336. );
  337. },
  338. },
  339. exportButton: {
  340. ["@click"]() {
  341. this.exportPlaylists();
  342. },
  343. },
  344. importButton: {
  345. ["@click"]() {
  346. document.getElementById("import-file-input").click();
  347. },
  348. },
  349. importFile(event) {
  350. const file = event.target.files[0];
  351. if (!file) return;
  352. const reader = new FileReader();
  353. reader.onload = (e) => {
  354. try {
  355. const importedData = JSON.parse(e.target.result);
  356. this.validateAndImportPlaylists(importedData);
  357. } catch (error) {
  358. console.error("Error parsing JSON file:", error);
  359. alert(
  360. "Invalid JSON file. Please select a valid playlist export file.",
  361. );
  362. } finally {
  363. // Reset the file input so the same file can be selected again
  364. event.target.value = "";
  365. }
  366. };
  367. reader.readAsText(file);
  368. },
  369. validateAndImportPlaylists(data) {
  370. // Validate the playlists structure
  371. if (!data.playlists || typeof data.playlists !== "object") {
  372. alert("Invalid file format: Missing or invalid 'playlists' property");
  373. return;
  374. }
  375. // Validate each playlist
  376. const validPlaylists = {};
  377. let hasErrors = false;
  378. for (const [playlistName, videos] of Object.entries(data.playlists)) {
  379. // Check if videos is an array
  380. if (!Array.isArray(videos)) {
  381. console.error(
  382. `Playlist '${playlistName}' does not contain a valid array of videos`,
  383. );
  384. hasErrors = true;
  385. continue;
  386. }
  387. // Validate each video in the playlist
  388. const validVideos = videos.filter((video) => {
  389. if (!video || typeof video !== "object") {
  390. console.error(`Invalid video object in '${playlistName}'`);
  391. return false;
  392. }
  393. if (
  394. !video.url ||
  395. typeof video.url !== "string" ||
  396. !video.title ||
  397. typeof video.title !== "string"
  398. ) {
  399. console.error(
  400. `Video in '${playlistName}' missing required properties (url, title)`,
  401. );
  402. return false;
  403. }
  404. return true;
  405. });
  406. // Add the validated playlist if it has valid videos
  407. if (validVideos.length > 0) {
  408. validPlaylists[playlistName] = validVideos;
  409. }
  410. }
  411. if (Object.keys(validPlaylists).length === 0) {
  412. alert("No valid playlists found in the import file");
  413. return;
  414. }
  415. if (hasErrors) {
  416. const confirmImport = confirm(
  417. "Some playlists or videos were invalid and will be skipped. Do you want to continue with the import?",
  418. );
  419. if (!confirmImport) return;
  420. }
  421. // Update storage and state
  422. this.updatePlaylists(validPlaylists);
  423. },
  424. async updatePlaylists(playlists) {
  425. try {
  426. await browser.storage.local.set({ playlists });
  427. this.playlists = playlists;
  428. this.updatePlaylistsForDisplay();
  429. this.updateCurrentPlaylistVideos();
  430. alert("Playlists imported successfully!");
  431. } catch (error) {
  432. console.error("Error updating playlists:", error);
  433. alert("Error importing playlists: " + error.message);
  434. }
  435. },
  436. getMenuId(playlistName, index) {
  437. return `${playlistName}-${index}`;
  438. },
  439. isMenuOpen(playlistName, index) {
  440. return this.openMenus.has(this.getMenuId(playlistName, index));
  441. },
  442. toggleMenu(playlistName, index) {
  443. const menuId = this.getMenuId(playlistName, index);
  444. if (this.openMenus.has(menuId)) {
  445. this.openMenus.delete(menuId);
  446. } else {
  447. // Close all other menus first
  448. this.openMenus.clear();
  449. this.openMenus.add(menuId);
  450. }
  451. },
  452. closeAllMenus() {
  453. this.openMenus.clear();
  454. },
  455. moreMenuButton: {
  456. ["@click.stop"]() {
  457. this.toggleMenu(
  458. this.$el.dataset.playlistName,
  459. parseInt(this.$el.dataset.playlistIndex)
  460. );
  461. },
  462. },
  463. moreMenu: {
  464. ["x-show"]() {
  465. return this.isMenuOpen(
  466. this.$el.dataset.playlistName,
  467. parseInt(this.$el.dataset.playlistIndex)
  468. );
  469. },
  470. },
  471. // View navigation methods
  472. showHistory() {
  473. this.currentView = 'history';
  474. this.loadHistory(); // Refresh history data when switching to history view
  475. },
  476. showPlaylists() {
  477. this.currentView = 'playlists';
  478. },
  479. showPlaylist(playlistName) {
  480. this.currentView = 'playlist';
  481. this.currentPlaylistName = playlistName;
  482. this.updateCurrentPlaylistVideos();
  483. },
  484. // Methods for truncated display
  485. shouldShowTruncation(playlistName) {
  486. const currentIndex = this.currentIndices[playlistName] || 0;
  487. return currentIndex > 0;
  488. },
  489. getTruncationText(playlistName) {
  490. const currentIndex = this.currentIndices[playlistName] || 0;
  491. const count = currentIndex;
  492. return `(${count} previous video${count === 1 ? '' : 's'})`;
  493. },
  494. getVisibleVideos(playlistName, videos) {
  495. const currentIndex = this.currentIndices[playlistName] || 0;
  496. // Show from current video onwards, but keep original indices
  497. return videos.slice(currentIndex).map((video, index) => ({
  498. ...video,
  499. originalIndex: currentIndex + index
  500. }));
  501. },
  502. getCurrentPlaylistVideos() {
  503. if (!this.currentPlaylistName || !this.playlists[this.currentPlaylistName]) {
  504. return [];
  505. }
  506. return this.playlists[this.currentPlaylistName];
  507. },
  508. // Button bindings for navigation
  509. historyButton: {
  510. ["@click"]() {
  511. this.showHistory();
  512. },
  513. },
  514. backButton: {
  515. ["@click"]() {
  516. this.showPlaylists();
  517. },
  518. },
  519. // Event handlers for playlist navigation
  520. playlistNameClick: {
  521. ["@click"]() {
  522. const playlistName = this.$el.dataset.playlistName;
  523. this.showPlaylist(playlistName);
  524. },
  525. },
  526. truncatedVideosClick: {
  527. ["@click"]() {
  528. const playlistName = this.$el.dataset.playlistName;
  529. this.showPlaylist(playlistName);
  530. },
  531. },
  532. truncatedVideosClick: {
  533. ["@click"]() {
  534. const playlistName = this.$el.dataset.playlistName;
  535. this.showPlaylist(playlistName);
  536. },
  537. },
  538. truncatedVideosDisplay: {
  539. ["x-show"]() {
  540. const playlistName = this.$el.dataset.playlistName;
  541. const playlistData = this.playlistsForDisplay.find(p => p.name === playlistName);
  542. return playlistData ? playlistData.shouldShowTruncation : false;
  543. },
  544. ["@click"]() {
  545. const playlistName = this.$el.dataset.playlistName;
  546. this.showPlaylist(playlistName);
  547. },
  548. },
  549. // CSP-compliant view bindings
  550. playlistsHeader: {
  551. ["x-show"]() {
  552. return this.currentView === 'playlists';
  553. },
  554. },
  555. historyHeader: {
  556. ["x-show"]() {
  557. return this.currentView === 'history';
  558. },
  559. },
  560. playlistViewHeader: {
  561. ["x-show"]() {
  562. return this.currentView === 'playlist';
  563. },
  564. },
  565. playlistsContainer: {
  566. ["x-show"]() {
  567. return this.currentView === 'playlists';
  568. },
  569. },
  570. historyContainer: {
  571. ["x-show"]() {
  572. return this.currentView === 'history';
  573. },
  574. },
  575. playlistViewContainer: {
  576. ["x-show"]() {
  577. return this.currentView === 'playlist';
  578. },
  579. },
  580. exportContainer: {
  581. ["x-show"]() {
  582. return this.currentView === 'playlists';
  583. },
  584. },
  585. // History-specific bindings for CSP compliance
  586. historyEmptyState: {
  587. ["x-show"]() {
  588. return this.sortedHistory.length === 0;
  589. },
  590. },
  591. // Playlist view-specific bindings for CSP compliance
  592. playlistViewEmptyState: {
  593. ["x-show"]() {
  594. return this.currentPlaylistVideos.length === 0;
  595. },
  596. },
  597. }));
  598. });