popup.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. getCurrentVideoIndex(playlistName) {
  145. const playlist = this.playlists[playlistName];
  146. if (!playlist || !Array.isArray(playlist)) return -1;
  147. // Find the index of the first video that is not "done"
  148. return playlist.findIndex((video) => {
  149. // Consider a video as not done if:
  150. // 1. It has no status property, or
  151. // 2. The status is not "done" (could be a number for partially watched)
  152. return !video.status || video.status !== "done";
  153. });
  154. },
  155. isCurrentVideo(playlistName, index) {
  156. const currentIndex = this.getCurrentVideoIndex(playlistName);
  157. return currentIndex === index && currentIndex !== -1;
  158. },
  159. isDoneVideo(playlistName, index) {
  160. const currentIndex = this.getCurrentVideoIndex(playlistName);
  161. // If there is no current video, or this video's index is less than current,
  162. // and this video is marked as done, then it's a consecutive done video
  163. return currentIndex === -1 || index < currentIndex;
  164. },
  165. videoItemClass: {
  166. [":class"]() {
  167. const playlistName = this.$el.dataset.playlistName;
  168. const index = parseInt(this.$el.dataset.playlistIndex);
  169. const video = this.playlists[playlistName][index];
  170. return {
  171. "current-video": this.isCurrentVideo(playlistName, index),
  172. "done-video":
  173. this.isDoneVideo(playlistName, index) && video.status === "done",
  174. };
  175. },
  176. },
  177. removeVideoButton: {
  178. ["@click"]() {
  179. this.removeVideo(
  180. this.$el.dataset.playlistName,
  181. this.$el.dataset.playlistIndex,
  182. );
  183. },
  184. },
  185. moveUpButton: {
  186. ["@click"]() {
  187. this.moveVideoUp(
  188. this.$el.dataset.playlistName,
  189. parseInt(this.$el.dataset.playlistIndex),
  190. );
  191. },
  192. [":disabled"]() {
  193. return parseInt(this.$el.dataset.playlistIndex) === 0;
  194. },
  195. },
  196. moveDownButton: {
  197. ["@click"]() {
  198. this.moveVideoDown(
  199. this.$el.dataset.playlistName,
  200. parseInt(this.$el.dataset.playlistIndex),
  201. );
  202. },
  203. [":disabled"]() {
  204. return (
  205. parseInt(this.$el.dataset.playlistIndex) ===
  206. this.playlists[this.$el.dataset.playlistName].length - 1
  207. );
  208. },
  209. },
  210. exportButton: {
  211. ["@click"]() {
  212. this.exportPlaylists();
  213. },
  214. },
  215. importButton: {
  216. ["@click"]() {
  217. document.getElementById("import-file-input").click();
  218. },
  219. },
  220. importFile(event) {
  221. const file = event.target.files[0];
  222. if (!file) return;
  223. const reader = new FileReader();
  224. reader.onload = (e) => {
  225. try {
  226. const importedData = JSON.parse(e.target.result);
  227. this.validateAndImportPlaylists(importedData);
  228. } catch (error) {
  229. console.error("Error parsing JSON file:", error);
  230. alert(
  231. "Invalid JSON file. Please select a valid playlist export file.",
  232. );
  233. } finally {
  234. // Reset the file input so the same file can be selected again
  235. event.target.value = "";
  236. }
  237. };
  238. reader.readAsText(file);
  239. },
  240. validateAndImportPlaylists(data) {
  241. // Validate the playlists structure
  242. if (!data.playlists || typeof data.playlists !== "object") {
  243. alert("Invalid file format: Missing or invalid 'playlists' property");
  244. return;
  245. }
  246. // Validate each playlist
  247. const validPlaylists = {};
  248. let hasErrors = false;
  249. for (const [playlistName, videos] of Object.entries(data.playlists)) {
  250. // Check if videos is an array
  251. if (!Array.isArray(videos)) {
  252. console.error(
  253. `Playlist '${playlistName}' does not contain a valid array of videos`,
  254. );
  255. hasErrors = true;
  256. continue;
  257. }
  258. // Validate each video in the playlist
  259. const validVideos = videos.filter((video) => {
  260. if (!video || typeof video !== "object") {
  261. console.error(`Invalid video object in '${playlistName}'`);
  262. return false;
  263. }
  264. if (
  265. !video.url ||
  266. typeof video.url !== "string" ||
  267. !video.title ||
  268. typeof video.title !== "string"
  269. ) {
  270. console.error(
  271. `Video in '${playlistName}' missing required properties (url, title)`,
  272. );
  273. return false;
  274. }
  275. return true;
  276. });
  277. // Add the validated playlist if it has valid videos
  278. if (validVideos.length > 0) {
  279. validPlaylists[playlistName] = validVideos;
  280. }
  281. }
  282. if (Object.keys(validPlaylists).length === 0) {
  283. alert("No valid playlists found in the import file");
  284. return;
  285. }
  286. if (hasErrors) {
  287. const confirmImport = confirm(
  288. "Some playlists or videos were invalid and will be skipped. Do you want to continue with the import?",
  289. );
  290. if (!confirmImport) return;
  291. }
  292. // Update storage and state
  293. this.updatePlaylists(validPlaylists);
  294. },
  295. async updatePlaylists(playlists) {
  296. try {
  297. await browser.storage.local.set({ playlists });
  298. this.playlists = playlists;
  299. alert("Playlists imported successfully!");
  300. } catch (error) {
  301. console.error("Error updating playlists:", error);
  302. alert("Error importing playlists: " + error.message);
  303. }
  304. },
  305. }));
  306. });