popup.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  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. // X periodically remove watched videos
  7. // X 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. // X view playback history (?)
  10. // X 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. // - or raw json editing
  14. // X option (probably a button) to add current page (url, title) to playlist
  15. // X align with addLinkToPlaylist in background.js (no repeated videos)
  16. // - button to add channel to youtube page (copy gql mutation to clipboard) (like the automa version)
  17. // - long-term: replace youtube page? rss feeds? need server?
  18. // X add personal rating feature ("enjoyed", "this was important", etc)
  19. // - option to move video (including status) to another playlist
  20. Alpine.data("playlistManager", () => ({
  21. playlists: {},
  22. currentIndices: {},
  23. history: {},
  24. sortedHistory: [],
  25. openMenus: new Set(), // Track which menus are open
  26. currentView: "playlists", // Track current view: 'playlists', 'history', 'playlist', or 'saveChannel'
  27. currentPlaylistName: "", // Track which playlist is being viewed
  28. playlistsForDisplay: [], // Computed array for display
  29. currentPlaylistVideos: [], // Videos for current playlist view
  30. currentTab: null, // Current active tab info
  31. isCurrentTabYoutube: false, // Whether current tab is YouTube
  32. isCurrentTabChannelPage: false, // Whether current tab is YouTube videos page
  33. addCurrentPageButtonText: "Add Current Page", // Button text
  34. // Save channel properties
  35. selectedCategory: "FOR BOTH", // Currently selected category
  36. availableCategories: ["FOR BOTH", "CHANNELS", "CREATIVE"], // Available categories
  37. curlCommand: "", // Generated curl command
  38. checkInterval: 14, // Check interval in days
  39. init() {
  40. this.loadPlaylists();
  41. this.loadHistory();
  42. this.getCurrentTab();
  43. // Add document click handler to close menus
  44. document.addEventListener("click", (e) => {
  45. // If click is not on a more button or menu, close all menus
  46. if (!e.target.closest(".more-menu-container")) {
  47. this.closeAllMenus();
  48. }
  49. });
  50. },
  51. async loadPlaylists() {
  52. try {
  53. const result = await browser.storage.local.get("playlists");
  54. console.log("LOAD RESULT", result.playlists);
  55. this.playlists = result.playlists || {};
  56. if (result.playlists) {
  57. this.currentIndices = Object.keys(result.playlists).reduce(
  58. (acc, pln) => {
  59. const ind = result.playlists[pln].findIndex(
  60. (v) => v.status !== "done",
  61. );
  62. if (ind === -1) {
  63. acc[pln] = result.playlists[pln].length;
  64. } else {
  65. acc[pln] = ind;
  66. }
  67. return acc;
  68. },
  69. {},
  70. );
  71. } else {
  72. this.currentIndices = {};
  73. }
  74. } catch (error) {
  75. console.error("Error loading playlists:", error);
  76. }
  77. this.updatePlaylistsForDisplay();
  78. },
  79. updatePlaylistsForDisplay() {
  80. this.playlistsForDisplay = Object.entries(this.playlists).map(
  81. ([playlistName, videos]) => {
  82. const currentIndex = this.currentIndices[playlistName] || 0;
  83. const shouldShowTruncation = currentIndex > 0;
  84. const truncationText = shouldShowTruncation
  85. ? `(${currentIndex} previous video${currentIndex === 1 ? "" : "s"})`
  86. : "";
  87. // Get visible videos from current index onwards with original indices
  88. const visibleVideos = videos
  89. .slice(currentIndex)
  90. .map((video, index) => ({
  91. ...video,
  92. originalIndex: currentIndex + index,
  93. doneButtonText: video.status === "done" ? "Remove Done Status" : "Mark as Done",
  94. isNonContiguousDone: this.isNonContiguousDone(playlistName, currentIndex + index),
  95. }));
  96. return {
  97. name: playlistName,
  98. videos: videos,
  99. visibleVideos: visibleVideos,
  100. shouldShowTruncation: shouldShowTruncation,
  101. truncationText: truncationText,
  102. };
  103. },
  104. );
  105. },
  106. updateCurrentPlaylistVideos() {
  107. if (
  108. !this.currentPlaylistName ||
  109. !this.playlists[this.currentPlaylistName]
  110. ) {
  111. this.currentPlaylistVideos = [];
  112. } else {
  113. this.currentPlaylistVideos = this.playlists[this.currentPlaylistName].map((video, index) => ({
  114. ...video,
  115. doneButtonText: video.status === "done" ? "Remove Done Status" : "Mark as Done",
  116. isNonContiguousDone: this.isNonContiguousDone(this.currentPlaylistName, index),
  117. }));
  118. }
  119. },
  120. async loadHistory() {
  121. try {
  122. const result = await browser.storage.local.get("history");
  123. console.log("LOAD HISTORY RESULT", result.history);
  124. this.history = result.history || {};
  125. this.sortHistoryByRecentInteraction();
  126. } catch (error) {
  127. console.error("Error loading history:", error);
  128. }
  129. },
  130. async getCurrentTab() {
  131. try {
  132. const tabs = await browser.tabs.query({
  133. active: true,
  134. currentWindow: true,
  135. });
  136. if (tabs.length > 0) {
  137. this.currentTab = tabs[0];
  138. const url = new URL(this.currentTab.url);
  139. this.isCurrentTabYoutube = url.hostname === "www.youtube.com";
  140. this.isCurrentTabChannelPage = this.isCurrentTabYoutube && url.pathname.includes("/videos");
  141. this.updateAddCurrentPageButtonText();
  142. this.updateCurlCommand();
  143. }
  144. } catch (error) {
  145. console.error("Error getting current tab:", error);
  146. this.currentTab = null;
  147. this.isCurrentTabYoutube = false;
  148. this.isCurrentTabChannelPage = false;
  149. this.updateAddCurrentPageButtonText();
  150. this.updateCurlCommand();
  151. }
  152. },
  153. updateAddCurrentPageButtonText() {
  154. if (!this.currentTab) {
  155. this.addCurrentPageButtonText = "Unable to get current page";
  156. } else if (!this.isCurrentTabYoutube) {
  157. this.addCurrentPageButtonText = "Add Current Page (YouTube only)";
  158. } else {
  159. this.addCurrentPageButtonText = "Add Current Page to Playlist";
  160. }
  161. },
  162. updateCurlCommand() {
  163. if (!this.currentTab || !this.isCurrentTabChannelPage) {
  164. this.curlCommand = "This feature is only available on YouTube channel pages (/videos).";
  165. return;
  166. }
  167. const title = this.currentTab.title.replace(" - YouTube", "");
  168. const url = this.currentTab.url;
  169. const category = this.selectedCategory;
  170. const interval = this.checkInterval;
  171. this.curlCommand = `curl -X POST -H 'content-type: application/json' -d '{"query": "mutation add{ addChannel(details: {category: \\"${category}\\", checkInterval: ${interval}, name: \\"${title}\\", url: \\"${url}\\"}){name} } "}' localhost:8543/data | jq '.'`;
  172. },
  173. async copyCurlCommand() {
  174. try {
  175. await navigator.clipboard.writeText(this.curlCommand);
  176. console.log("Curl command copied to clipboard");
  177. // Could add visual feedback here
  178. } catch (error) {
  179. console.error("Failed to copy to clipboard:", error);
  180. // Fallback for older browsers
  181. try {
  182. const textArea = document.createElement("textarea");
  183. textArea.value = this.curlCommand;
  184. document.body.appendChild(textArea);
  185. textArea.focus();
  186. textArea.select();
  187. document.execCommand("copy");
  188. document.body.removeChild(textArea);
  189. console.log("Curl command copied to clipboard (fallback)");
  190. } catch (fallbackError) {
  191. console.error("Fallback copy failed:", fallbackError);
  192. }
  193. }
  194. },
  195. selectCategory(category) {
  196. this.selectedCategory = category;
  197. this.updateCurlCommand();
  198. },
  199. updateCheckInterval(interval) {
  200. // Ensure it's a positive integer, default to 14 if invalid
  201. const parsedInterval = parseInt(interval);
  202. this.checkInterval = parsedInterval > 0 ? parsedInterval : 14;
  203. this.updateCurlCommand();
  204. },
  205. showSaveChannel() {
  206. this.currentView = "saveChannel";
  207. this.updateCurlCommand();
  208. },
  209. sortHistoryByRecentInteraction() {
  210. // Convert history object to array with video ID and sort by most recent interaction
  211. this.sortedHistory = Object.entries(this.history)
  212. .map(([videoId, videoData]) => {
  213. const lastInteraction =
  214. videoData.history.length > 0
  215. ? Math.max(...videoData.history.map((event) => event.timestamp))
  216. : 0;
  217. // Pre-process events with formatted data for CSP compliance
  218. const processedEvents = videoData.history
  219. .slice()
  220. .reverse()
  221. .map((event, index) => ({
  222. ...event,
  223. formattedAction: this.formatActionName(event.action),
  224. formattedPosition: `at ${this.formatVideoPosition(event.position)}`,
  225. formattedTimestamp: this.formatTimestamp(event.timestamp),
  226. uniqueKey: `${videoId}-${event.timestamp}-${index}`,
  227. }));
  228. return {
  229. videoId,
  230. formattedVideoId: `(${videoId})`,
  231. ...videoData,
  232. lastInteraction,
  233. processedEvents,
  234. tags: videoData.tags || [], // Ensure tags array exists
  235. };
  236. })
  237. .sort((a, b) => b.lastInteraction - a.lastInteraction);
  238. },
  239. formatTimestamp(timestamp) {
  240. const date = new Date(timestamp);
  241. const now = new Date();
  242. const diffMs = now - date;
  243. const diffMins = Math.floor(diffMs / (1000 * 60));
  244. const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  245. const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  246. if (diffMins < 1) return "Just now";
  247. if (diffMins < 60)
  248. return `${diffMins} minute${diffMins > 1 ? "s" : ""} ago`;
  249. if (diffHours < 24)
  250. return `${diffHours} hour${diffHours > 1 ? "s" : ""} ago`;
  251. if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? "s" : ""} ago`;
  252. return (
  253. date.toLocaleDateString() +
  254. " " +
  255. date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
  256. );
  257. },
  258. formatVideoPosition(seconds) {
  259. const minutes = Math.floor(seconds / 60);
  260. const remainingSeconds = Math.floor(seconds % 60);
  261. return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
  262. },
  263. async toggleTag(videoId, tag) {
  264. // Create a deep copy of history to avoid proxy issues
  265. const history = JSON.parse(JSON.stringify(this.history));
  266. if (!history[videoId]) {
  267. console.error(`Video ${videoId} not found in history`);
  268. return;
  269. }
  270. const videoData = history[videoId];
  271. if (!videoData.tags) {
  272. videoData.tags = [];
  273. }
  274. const tagIndex = videoData.tags.indexOf(tag);
  275. if (tagIndex === -1) {
  276. // Add tag
  277. videoData.tags.push(tag);
  278. } else {
  279. // Remove tag
  280. videoData.tags.splice(tagIndex, 1);
  281. }
  282. // Save to storage and update local state
  283. try {
  284. await browser.storage.local.set({ history: history });
  285. this.history = history;
  286. this.sortHistoryByRecentInteraction(); // Refresh display
  287. } catch (error) {
  288. console.error("Error saving tag changes:", error);
  289. }
  290. },
  291. isTagActive(videoId, tag) {
  292. const videoData = this.history[videoId];
  293. return videoData && videoData.tags && videoData.tags.includes(tag);
  294. },
  295. formatActionName(action) {
  296. const actionMap = {
  297. play: "Started",
  298. playing: "Playing",
  299. pause: "Paused",
  300. ended: "Finished",
  301. };
  302. return actionMap[action] || action;
  303. },
  304. formatPlaylistName(name) {
  305. // Convert "listening-1" to "Listening - 1"
  306. return name
  307. .split("-")
  308. .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
  309. .join(" - ");
  310. },
  311. openVideo(url) {
  312. browser.tabs.create({ url });
  313. },
  314. async removeVideo(playlistName, index) {
  315. const playlists = JSON.parse(JSON.stringify(this.playlists));
  316. // Make a copy of the current playlist
  317. const playlist = [...playlists[playlistName]];
  318. // Remove the video at the specified index
  319. playlist.splice(index, 1);
  320. // Create an updated playlists object with the remaining playlists unchanged
  321. const updatedPlaylists = {
  322. ...playlists,
  323. [playlistName]: playlist,
  324. };
  325. // Update the playlists in storage
  326. try {
  327. await browser.storage.local.set({ playlists: updatedPlaylists });
  328. this.playlists = updatedPlaylists;
  329. this.updatePlaylistsForDisplay();
  330. this.updateCurrentPlaylistVideos();
  331. } catch (error) {
  332. console.error("Error removing video:", error);
  333. }
  334. },
  335. async moveVideoUp(playlistName, index) {
  336. // Can't move the first item up
  337. if (index <= 0) return;
  338. const playlists = JSON.parse(JSON.stringify(this.playlists));
  339. // Make a copy of the current playlist
  340. const playlist = [...playlists[playlistName]];
  341. // Swap the video with the one above it
  342. [playlist[index], playlist[index - 1]] = [
  343. playlist[index - 1],
  344. playlist[index],
  345. ];
  346. // Create an updated playlists object
  347. const updatedPlaylists = {
  348. ...playlists,
  349. [playlistName]: playlist,
  350. };
  351. // Update the playlists in storage
  352. try {
  353. await browser.storage.local.set({ playlists: updatedPlaylists });
  354. this.playlists = updatedPlaylists;
  355. this.updatePlaylistsForDisplay();
  356. this.updateCurrentPlaylistVideos();
  357. } catch (error) {
  358. console.error("Error moving video up:", error);
  359. }
  360. },
  361. async moveVideoDown(playlistName, index) {
  362. const playlists = JSON.parse(JSON.stringify(this.playlists));
  363. const playlist = [...playlists[playlistName]];
  364. // Can't move the last item down
  365. if (index >= playlist.length - 1) return;
  366. // Swap the video with the one below it
  367. [playlist[index], playlist[index + 1]] = [
  368. playlist[index + 1],
  369. playlist[index],
  370. ];
  371. // Create an updated playlists object
  372. const updatedPlaylists = {
  373. ...playlists,
  374. [playlistName]: playlist,
  375. };
  376. // Update the playlists in storage
  377. try {
  378. await browser.storage.local.set({ playlists: updatedPlaylists });
  379. this.playlists = updatedPlaylists;
  380. this.updatePlaylistsForDisplay();
  381. this.updateCurrentPlaylistVideos();
  382. } catch (error) {
  383. console.error("Error moving video down:", error);
  384. }
  385. },
  386. async toggleVideoDoneStatus(playlistName, index) {
  387. const playlists = JSON.parse(JSON.stringify(this.playlists));
  388. const playlist = [...playlists[playlistName]];
  389. const video = {...playlist[index]};
  390. // Toggle the done status
  391. if (video.status === "done") {
  392. // Remove status property (undefined status means not done)
  393. delete video.status;
  394. } else {
  395. // Set status to done
  396. video.status = "done";
  397. }
  398. // Update the video in the playlist
  399. playlist[index] = video;
  400. // Create an updated playlists object
  401. const updatedPlaylists = {
  402. ...playlists,
  403. [playlistName]: playlist,
  404. };
  405. // Update the playlists in storage
  406. try {
  407. await browser.storage.local.set({ playlists: updatedPlaylists });
  408. this.playlists = updatedPlaylists;
  409. this.updatePlaylistsForDisplay();
  410. this.updateCurrentPlaylistVideos();
  411. } catch (error) {
  412. console.error("Error toggling video done status:", error);
  413. }
  414. },
  415. async addCurrentPageToPlaylist() {
  416. if (
  417. !this.currentTab ||
  418. !this.isCurrentTabYoutube ||
  419. !this.currentPlaylistName
  420. ) {
  421. return;
  422. }
  423. // Create video object using current tab info
  424. const video = {
  425. url: this.currentTab.url,
  426. title: this.currentTab.title,
  427. };
  428. // Use shared utility function to add video (handles duplicate checking)
  429. const wasAdded = await PlaylistUtils.addVideoToPlaylist(
  430. this.currentPlaylistName,
  431. video,
  432. );
  433. if (wasAdded) {
  434. // Refresh displays only if video was actually added
  435. this.loadPlaylists(); // This will update both display arrays
  436. } else {
  437. // Could show user feedback that video already exists
  438. console.log("Video already exists in a playlist");
  439. }
  440. },
  441. async exportPlaylists() {
  442. try {
  443. // Get current playlists
  444. const playlistResult = await browser.storage.local.get("playlists");
  445. const playlists = playlistResult.playlists || {};
  446. // Get playback history
  447. const historyResult = await browser.storage.local.get("history");
  448. const playbackHistory = historyResult.history || {};
  449. // Get open tabs
  450. let openTabs = [];
  451. try {
  452. const tabsResult = await browser.tabs.query({});
  453. openTabs = tabsResult
  454. .filter(tab => tab.url &&
  455. !tab.url.startsWith('moz-extension://') &&
  456. !tab.url.startsWith('about:') &&
  457. !tab.url.startsWith('chrome://'))
  458. .map(tab => ({
  459. url: tab.url,
  460. title: tab.title || 'Untitled'
  461. }));
  462. } catch (error) {
  463. console.warn("Could not retrieve open tabs:", error);
  464. openTabs = [];
  465. }
  466. // Create export data object
  467. const exportData = {
  468. playlists,
  469. playbackHistory,
  470. openTabs,
  471. exportDate: new Date().toISOString(),
  472. };
  473. // Convert to JSON
  474. const jsonString = JSON.stringify(exportData, null, 2);
  475. // Create download
  476. const blob = new Blob([jsonString], { type: "application/json" });
  477. const url = URL.createObjectURL(blob);
  478. // Trigger download
  479. const a = document.createElement("a");
  480. a.href = url;
  481. a.download = `playlists-export-${new Date().toISOString().split("T")[0]}.json`;
  482. document.body.appendChild(a);
  483. a.click();
  484. // Clean up
  485. setTimeout(() => {
  486. document.body.removeChild(a);
  487. URL.revokeObjectURL(url);
  488. }, 100);
  489. } catch (error) {
  490. console.error("Error exporting playlists:", error);
  491. }
  492. },
  493. videotitle: {
  494. ["@click"]() {
  495. console.log("TITLE CLICK", this.$el);
  496. },
  497. },
  498. videoPlayLink: {
  499. ["@click.prevent"]() {
  500. browser.tabs.update({ url: this.$el.href });
  501. },
  502. },
  503. isNonContiguousDone(playlistName, videoIndex) {
  504. const playlist = this.playlists[playlistName];
  505. if (!playlist || !playlist[videoIndex] || playlist[videoIndex].status !== "done") {
  506. return false;
  507. }
  508. // Check if there's any non-done video before this done video
  509. for (let i = 0; i < videoIndex; i++) {
  510. if (playlist[i].status !== "done") {
  511. return true;
  512. }
  513. }
  514. return false;
  515. },
  516. isCurrentVideo(playlistName, index) {
  517. const currentIndex = this.currentIndices[playlistName];
  518. return currentIndex === index;
  519. },
  520. isDoneVideo(playlistName, index) {
  521. const currentIndex = this.currentIndices[playlistName];
  522. return index < currentIndex;
  523. },
  524. isVideoDone(playlistName, index) {
  525. const video = this.playlists[playlistName] && this.playlists[playlistName][index];
  526. return video && video.status === "done";
  527. },
  528. videoItemClass: {
  529. [":class"]() {
  530. const playlistName = this.$el.dataset.playlistName;
  531. const index = parseInt(this.$el.dataset.playlistIndex);
  532. const video = this.playlists[playlistName][index];
  533. return {
  534. "current-video": this.isCurrentVideo(playlistName, index),
  535. "done-video":
  536. this.isDoneVideo(playlistName, index) && video.status === "done",
  537. "non-contiguous-done-video": this.isNonContiguousDone(playlistName, index),
  538. };
  539. },
  540. },
  541. removeVideoButton: {
  542. ["@click"]() {
  543. this.removeVideo(
  544. this.$el.dataset.playlistName,
  545. this.$el.dataset.playlistIndex,
  546. );
  547. this.closeAllMenus();
  548. },
  549. },
  550. toggleVideoDoneButton: {
  551. ["@click"]() {
  552. this.toggleVideoDoneStatus(
  553. this.$el.dataset.playlistName,
  554. parseInt(this.$el.dataset.playlistIndex),
  555. );
  556. this.closeAllMenus();
  557. },
  558. },
  559. moveUpButton: {
  560. ["@click"]() {
  561. this.moveVideoUp(
  562. this.$el.dataset.playlistName,
  563. parseInt(this.$el.dataset.playlistIndex),
  564. );
  565. },
  566. [":disabled"]() {
  567. return parseInt(this.$el.dataset.playlistIndex) === 0;
  568. },
  569. },
  570. moveDownButton: {
  571. ["@click"]() {
  572. this.moveVideoDown(
  573. this.$el.dataset.playlistName,
  574. parseInt(this.$el.dataset.playlistIndex),
  575. );
  576. },
  577. [":disabled"]() {
  578. return (
  579. parseInt(this.$el.dataset.playlistIndex) ===
  580. this.playlists[this.$el.dataset.playlistName].length - 1
  581. );
  582. },
  583. },
  584. exportButton: {
  585. ["@click"]() {
  586. this.exportPlaylists();
  587. },
  588. },
  589. importButton: {
  590. ["@click"]() {
  591. document.getElementById("import-file-input").click();
  592. },
  593. },
  594. importFileInput: {
  595. ["@change"]() {
  596. this.importFile(this.$event);
  597. },
  598. },
  599. importFile(event) {
  600. const file = event.target.files[0];
  601. if (!file) return;
  602. const reader = new FileReader();
  603. reader.onload = (e) => {
  604. try {
  605. const importedData = JSON.parse(e.target.result);
  606. this.validateAndImportPlaylists(importedData);
  607. } catch (error) {
  608. console.error("Error parsing JSON file:", error);
  609. alert(
  610. "Invalid JSON file. Please select a valid playlist export file.",
  611. );
  612. } finally {
  613. // Reset the file input so the same file can be selected again
  614. event.target.value = "";
  615. }
  616. };
  617. reader.readAsText(file);
  618. },
  619. validateAndImportPlaylists(data) {
  620. // Validate the playlists structure
  621. if (!data.playlists || typeof data.playlists !== "object") {
  622. alert("Invalid file format: Missing or invalid 'playlists' property");
  623. return;
  624. }
  625. // Validate each playlist
  626. const validPlaylists = {};
  627. let hasErrors = false;
  628. for (const [playlistName, videos] of Object.entries(data.playlists)) {
  629. // Check if videos is an array
  630. if (!Array.isArray(videos)) {
  631. console.error(
  632. `Playlist '${playlistName}' does not contain a valid array of videos`,
  633. );
  634. hasErrors = true;
  635. continue;
  636. }
  637. // Validate each video in the playlist
  638. const validVideos = videos.filter((video) => {
  639. if (!video || typeof video !== "object") {
  640. console.error(`Invalid video object in '${playlistName}'`);
  641. return false;
  642. }
  643. if (
  644. !video.url ||
  645. typeof video.url !== "string" ||
  646. !video.title ||
  647. typeof video.title !== "string"
  648. ) {
  649. console.error(
  650. `Video in '${playlistName}' missing required properties (url, title)`,
  651. );
  652. return false;
  653. }
  654. return true;
  655. });
  656. // Add the validated playlist if it has valid videos
  657. if (validVideos.length > 0) {
  658. validPlaylists[playlistName] = validVideos;
  659. }
  660. }
  661. if (Object.keys(validPlaylists).length === 0) {
  662. alert("No valid playlists found in the import file");
  663. return;
  664. }
  665. if (hasErrors) {
  666. const confirmImport = confirm(
  667. "Some playlists or videos were invalid and will be skipped. Do you want to continue with the import?",
  668. );
  669. if (!confirmImport) return;
  670. }
  671. // Update storage and state
  672. this.updatePlaylists(validPlaylists);
  673. },
  674. async updatePlaylists(playlists) {
  675. try {
  676. await browser.storage.local.set({ playlists });
  677. this.playlists = playlists;
  678. this.updatePlaylistsForDisplay();
  679. this.updateCurrentPlaylistVideos();
  680. alert("Playlists imported successfully!");
  681. } catch (error) {
  682. console.error("Error updating playlists:", error);
  683. alert("Error importing playlists: " + error.message);
  684. }
  685. },
  686. getMenuId(playlistName, index) {
  687. return `${playlistName}-${index}`;
  688. },
  689. isMenuOpen(playlistName, index) {
  690. return this.openMenus.has(this.getMenuId(playlistName, index));
  691. },
  692. toggleMenu(playlistName, index) {
  693. const menuId = this.getMenuId(playlistName, index);
  694. if (this.openMenus.has(menuId)) {
  695. this.openMenus.delete(menuId);
  696. } else {
  697. // Close all other menus first
  698. this.openMenus.clear();
  699. this.openMenus.add(menuId);
  700. }
  701. },
  702. closeAllMenus() {
  703. this.openMenus.clear();
  704. },
  705. moreMenuButton: {
  706. ["@click.stop"]() {
  707. this.toggleMenu(
  708. this.$el.dataset.playlistName,
  709. parseInt(this.$el.dataset.playlistIndex),
  710. );
  711. },
  712. },
  713. moreMenu: {
  714. ["x-show"]() {
  715. return this.isMenuOpen(
  716. this.$el.dataset.playlistName,
  717. parseInt(this.$el.dataset.playlistIndex),
  718. );
  719. },
  720. },
  721. // View navigation methods
  722. showHistory() {
  723. this.currentView = "history";
  724. this.loadHistory(); // Refresh history data when switching to history view
  725. },
  726. showPlaylists() {
  727. this.currentView = "playlists";
  728. },
  729. showPlaylist(playlistName) {
  730. this.currentView = "playlist";
  731. this.currentPlaylistName = playlistName;
  732. this.updateCurrentPlaylistVideos();
  733. },
  734. // Methods for truncated display
  735. shouldShowTruncation(playlistName) {
  736. const currentIndex = this.currentIndices[playlistName] || 0;
  737. return currentIndex > 0;
  738. },
  739. getTruncationText(playlistName) {
  740. const currentIndex = this.currentIndices[playlistName] || 0;
  741. const count = currentIndex;
  742. return `(${count} previous video${count === 1 ? "" : "s"})`;
  743. },
  744. getVisibleVideos(playlistName, videos) {
  745. const currentIndex = this.currentIndices[playlistName] || 0;
  746. // Show from current video onwards, but keep original indices
  747. return videos.slice(currentIndex).map((video, index) => ({
  748. ...video,
  749. originalIndex: currentIndex + index,
  750. }));
  751. },
  752. getCurrentPlaylistVideos() {
  753. if (
  754. !this.currentPlaylistName ||
  755. !this.playlists[this.currentPlaylistName]
  756. ) {
  757. return [];
  758. }
  759. return this.playlists[this.currentPlaylistName];
  760. },
  761. // Button bindings for navigation
  762. historyButton: {
  763. ["@click"]() {
  764. this.showHistory();
  765. },
  766. },
  767. saveChannelButton: {
  768. ["@click"]() {
  769. this.showSaveChannel();
  770. },
  771. },
  772. backButton: {
  773. ["@click"]() {
  774. this.showPlaylists();
  775. },
  776. },
  777. // Event handlers for playlist navigation
  778. playlistNameClick: {
  779. ["@click"]() {
  780. const playlistName = this.$el.dataset.playlistName;
  781. this.showPlaylist(playlistName);
  782. },
  783. },
  784. truncatedVideosClick: {
  785. ["@click"]() {
  786. const playlistName = this.$el.dataset.playlistName;
  787. this.showPlaylist(playlistName);
  788. },
  789. },
  790. truncatedVideosClick: {
  791. ["@click"]() {
  792. const playlistName = this.$el.dataset.playlistName;
  793. this.showPlaylist(playlistName);
  794. },
  795. },
  796. truncatedVideosDisplay: {
  797. ["x-show"]() {
  798. const playlistName = this.$el.dataset.playlistName;
  799. const playlistData = this.playlistsForDisplay.find(
  800. (p) => p.name === playlistName,
  801. );
  802. return playlistData ? playlistData.shouldShowTruncation : false;
  803. },
  804. ["@click"]() {
  805. const playlistName = this.$el.dataset.playlistName;
  806. this.showPlaylist(playlistName);
  807. },
  808. },
  809. // CSP-compliant view bindings
  810. playlistsHeader: {
  811. ["x-show"]() {
  812. return this.currentView === "playlists";
  813. },
  814. },
  815. historyHeader: {
  816. ["x-show"]() {
  817. return this.currentView === "history";
  818. },
  819. },
  820. playlistViewHeader: {
  821. ["x-show"]() {
  822. return this.currentView === "playlist";
  823. },
  824. },
  825. saveChannelHeader: {
  826. ["x-show"]() {
  827. return this.currentView === "saveChannel";
  828. },
  829. },
  830. playlistsContainer: {
  831. ["x-show"]() {
  832. return this.currentView === "playlists";
  833. },
  834. },
  835. historyContainer: {
  836. ["x-show"]() {
  837. return this.currentView === "history";
  838. },
  839. },
  840. playlistViewContainer: {
  841. ["x-show"]() {
  842. return this.currentView === "playlist";
  843. },
  844. },
  845. saveChannelContainer: {
  846. ["x-show"]() {
  847. return this.currentView === "saveChannel";
  848. },
  849. },
  850. exportContainer: {
  851. ["x-show"]() {
  852. return this.currentView === "playlists";
  853. },
  854. },
  855. // History-specific bindings for CSP compliance
  856. historyEmptyState: {
  857. ["x-show"]() {
  858. return this.sortedHistory.length === 0;
  859. },
  860. },
  861. // Playlist view-specific bindings for CSP compliance
  862. playlistViewEmptyState: {
  863. ["x-show"]() {
  864. return this.currentPlaylistVideos.length === 0;
  865. },
  866. },
  867. // Tag chip bindings for CSP compliance
  868. tagChip: {
  869. ["@click"]() {
  870. const videoId = this.$el.dataset.videoId;
  871. const tag = this.$el.dataset.tag;
  872. this.toggleTag(videoId, tag);
  873. },
  874. [":class"]() {
  875. const videoId = this.$el.dataset.videoId;
  876. const tag = this.$el.dataset.tag;
  877. return {
  878. active: this.isTagActive(videoId, tag),
  879. };
  880. },
  881. },
  882. // Save Channel specific bindings
  883. copyCurlButton: {
  884. ["@click"]() {
  885. this.copyCurlCommand();
  886. },
  887. [":disabled"]() {
  888. return !this.isCurrentTabChannelPage;
  889. },
  890. },
  891. categoryButton: {
  892. ["@click"]() {
  893. const category = this.$el.dataset.category;
  894. this.selectCategory(category);
  895. },
  896. [":class"]() {
  897. const category = this.$el.dataset.category;
  898. return {
  899. active: this.selectedCategory === category,
  900. };
  901. },
  902. },
  903. saveChannelNotice: {
  904. ["x-show"]() {
  905. return !this.isCurrentTabChannelPage;
  906. },
  907. },
  908. intervalInput: {
  909. [":value"]() {
  910. return this.checkInterval;
  911. },
  912. ["@input"]() {
  913. this.updateCheckInterval(this.$el.value);
  914. },
  915. },
  916. // Add current page button binding
  917. addCurrentPageButton: {
  918. ["@click"]() {
  919. this.addCurrentPageToPlaylist();
  920. },
  921. [":disabled"]() {
  922. return (
  923. !this.currentTab ||
  924. !this.isCurrentTabYoutube ||
  925. !this.currentPlaylistName
  926. );
  927. },
  928. [":class"]() {
  929. return {
  930. disabled:
  931. !this.currentTab ||
  932. !this.isCurrentTabYoutube ||
  933. !this.currentPlaylistName,
  934. };
  935. },
  936. },
  937. }));
  938. });