popup.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. document.addEventListener("alpine:init", () => {
  2. //TODO
  3. // - reorder videos in playlist
  4. // - remove videos from playlist
  5. // - preserve playlist order (sort)
  6. // - "play/resume playlist" button (pick up where you left off)
  7. // - track timestamp to truly resume where you left off
  8. // - periodically remove watched videos
  9. // - consider separating context menu items (rather than having a sub-menu)
  10. Alpine.data("playlistManager", () => ({
  11. playlists: {},
  12. init() {
  13. this.loadPlaylists();
  14. },
  15. async loadPlaylists() {
  16. try {
  17. const result = await browser.storage.local.get("playlists");
  18. console.log("LOAD RESULT", result.playlists);
  19. this.playlists = result.playlists || {};
  20. } catch (error) {
  21. console.error("Error loading playlists:", error);
  22. }
  23. },
  24. formatPlaylistName(name) {
  25. // Convert "listening-1" to "Listening - 1"
  26. return name
  27. .split("-")
  28. .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
  29. .join(" - ");
  30. },
  31. openVideo(url) {
  32. browser.tabs.create({ url });
  33. },
  34. async removeVideo(playlistName, index) {
  35. const playlists = JSON.parse(JSON.stringify(this.playlists));
  36. // Make a copy of the current playlist
  37. const playlist = [...playlists[playlistName]];
  38. // Remove the video at the specified index
  39. playlist.splice(index, 1);
  40. // Create an updated playlists object with the remaining playlists unchanged
  41. const updatedPlaylists = {
  42. ...playlists,
  43. [playlistName]: playlist,
  44. };
  45. // Update the playlists in storage
  46. try {
  47. await browser.storage.local.set({ playlists: updatedPlaylists });
  48. this.playlists = updatedPlaylists;
  49. } catch (error) {
  50. console.error("Error removing video:", error);
  51. }
  52. },
  53. async moveVideoUp(playlistName, index) {
  54. // Can't move the first item up
  55. if (index <= 0) return;
  56. const playlists = JSON.parse(JSON.stringify(this.playlists));
  57. // Make a copy of the current playlist
  58. const playlist = [...playlists[playlistName]];
  59. // Swap the video with the one above it
  60. [playlist[index], playlist[index - 1]] = [
  61. playlist[index - 1],
  62. playlist[index],
  63. ];
  64. // Create an updated playlists object
  65. const updatedPlaylists = {
  66. ...playlists,
  67. [playlistName]: playlist,
  68. };
  69. // Update the playlists in storage
  70. try {
  71. await browser.storage.local.set({ playlists: updatedPlaylists });
  72. this.playlists = updatedPlaylists;
  73. } catch (error) {
  74. console.error("Error moving video up:", error);
  75. }
  76. },
  77. async moveVideoDown(playlistName, index) {
  78. const playlists = JSON.parse(JSON.stringify(this.playlists));
  79. const playlist = [...playlists[playlistName]];
  80. // Can't move the last item down
  81. if (index >= playlist.length - 1) return;
  82. // Swap the video with the one below it
  83. [playlist[index], playlist[index + 1]] = [
  84. playlist[index + 1],
  85. playlist[index],
  86. ];
  87. // Create an updated playlists object
  88. const updatedPlaylists = {
  89. ...playlists,
  90. [playlistName]: playlist,
  91. };
  92. // Update the playlists in storage
  93. try {
  94. await browser.storage.local.set({ playlists: updatedPlaylists });
  95. this.playlists = updatedPlaylists;
  96. } catch (error) {
  97. console.error("Error moving video down:", error);
  98. }
  99. },
  100. async exportPlaylists() {
  101. try {
  102. // Get current playlists
  103. const playlistResult = await browser.storage.local.get("playlists");
  104. const playlists = playlistResult.playlists || {};
  105. // Get playback history
  106. const historyResult = await browser.storage.local.get("history");
  107. const playbackHistory = historyResult.history || {};
  108. // Create export data object
  109. const exportData = {
  110. playlists,
  111. playbackHistory,
  112. exportDate: new Date().toISOString(),
  113. };
  114. // Convert to JSON
  115. const jsonString = JSON.stringify(exportData, null, 2);
  116. // Create download
  117. const blob = new Blob([jsonString], { type: "application/json" });
  118. const url = URL.createObjectURL(blob);
  119. // Trigger download
  120. const a = document.createElement("a");
  121. a.href = url;
  122. a.download = `playlists-export-${new Date().toISOString().split("T")[0]}.json`;
  123. document.body.appendChild(a);
  124. a.click();
  125. // Clean up
  126. setTimeout(() => {
  127. document.body.removeChild(a);
  128. URL.revokeObjectURL(url);
  129. }, 100);
  130. } catch (error) {
  131. console.error("Error exporting playlists:", error);
  132. }
  133. },
  134. videotitle: {
  135. ["@click"]() {
  136. console.log("TITLE CLICK", this.$el);
  137. },
  138. },
  139. videoPlayLink: {
  140. ["@click.prevent"]() {
  141. browser.tabs.update({ url: this.$el.href });
  142. },
  143. },
  144. removeVideoButton: {
  145. ["@click"]() {
  146. this.removeVideo(
  147. this.$el.dataset.playlistName,
  148. this.$el.dataset.playlistIndex,
  149. );
  150. },
  151. },
  152. moveUpButton: {
  153. ["@click"]() {
  154. this.moveVideoUp(
  155. this.$el.dataset.playlistName,
  156. parseInt(this.$el.dataset.playlistIndex),
  157. );
  158. },
  159. [":disabled"]() {
  160. return parseInt(this.$el.dataset.playlistIndex) === 0;
  161. },
  162. },
  163. moveDownButton: {
  164. ["@click"]() {
  165. this.moveVideoDown(
  166. this.$el.dataset.playlistName,
  167. parseInt(this.$el.dataset.playlistIndex),
  168. );
  169. },
  170. [":disabled"]() {
  171. return (
  172. parseInt(this.$el.dataset.playlistIndex) ===
  173. this.playlists[this.$el.dataset.playlistName].length - 1
  174. );
  175. },
  176. },
  177. exportButton: {
  178. ["@click"]() {
  179. this.exportPlaylists();
  180. },
  181. },
  182. importButton: {
  183. ["@click"]() {
  184. document.getElementById("import-file-input").click();
  185. },
  186. },
  187. importFile(event) {
  188. const file = event.target.files[0];
  189. if (!file) return;
  190. const reader = new FileReader();
  191. reader.onload = (e) => {
  192. try {
  193. const importedData = JSON.parse(e.target.result);
  194. this.validateAndImportPlaylists(importedData);
  195. } catch (error) {
  196. console.error("Error parsing JSON file:", error);
  197. alert(
  198. "Invalid JSON file. Please select a valid playlist export file.",
  199. );
  200. } finally {
  201. // Reset the file input so the same file can be selected again
  202. event.target.value = "";
  203. }
  204. };
  205. reader.readAsText(file);
  206. },
  207. validateAndImportPlaylists(data) {
  208. // Validate the playlists structure
  209. if (!data.playlists || typeof data.playlists !== "object") {
  210. alert("Invalid file format: Missing or invalid 'playlists' property");
  211. return;
  212. }
  213. // Validate each playlist
  214. const validPlaylists = {};
  215. let hasErrors = false;
  216. for (const [playlistName, videos] of Object.entries(data.playlists)) {
  217. // Check if videos is an array
  218. if (!Array.isArray(videos)) {
  219. console.error(
  220. `Playlist '${playlistName}' does not contain a valid array of videos`,
  221. );
  222. hasErrors = true;
  223. continue;
  224. }
  225. // Validate each video in the playlist
  226. const validVideos = videos.filter((video) => {
  227. if (!video || typeof video !== "object") {
  228. console.error(`Invalid video object in '${playlistName}'`);
  229. return false;
  230. }
  231. if (
  232. !video.url ||
  233. typeof video.url !== "string" ||
  234. !video.title ||
  235. typeof video.title !== "string"
  236. ) {
  237. console.error(
  238. `Video in '${playlistName}' missing required properties (url, title)`,
  239. );
  240. return false;
  241. }
  242. return true;
  243. });
  244. // Add the validated playlist if it has valid videos
  245. if (validVideos.length > 0) {
  246. validPlaylists[playlistName] = validVideos;
  247. }
  248. }
  249. if (Object.keys(validPlaylists).length === 0) {
  250. alert("No valid playlists found in the import file");
  251. return;
  252. }
  253. if (hasErrors) {
  254. const confirmImport = confirm(
  255. "Some playlists or videos were invalid and will be skipped. Do you want to continue with the import?",
  256. );
  257. if (!confirmImport) return;
  258. }
  259. // Update storage and state
  260. this.updatePlaylists(validPlaylists);
  261. },
  262. async updatePlaylists(playlists) {
  263. try {
  264. await browser.storage.local.set({ playlists });
  265. this.playlists = playlists;
  266. alert("Playlists imported successfully!");
  267. } catch (error) {
  268. console.error("Error updating playlists:", error);
  269. alert("Error importing playlists: " + error.message);
  270. }
  271. },
  272. }));
  273. });