| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237 |
- document.addEventListener("alpine:init", () => {
- //TODO
- // - reorder videos in playlist
- // - remove videos from playlist
- // - preserve playlist order (sort)
- // - "play/resume playlist" button (pick up where you left off)
- // - track timestamp to truly resume where you left off
- // - periodically remove watched videos
- // - consider separating context menu items (rather than having a sub-menu)
- Alpine.data("playlistManager", () => ({
- playlists: {},
- init() {
- this.loadPlaylists();
- },
- async loadPlaylists() {
- try {
- const result = await browser.storage.local.get("playlists");
- console.log("LOAD RESULT", result.playlists);
- this.playlists = result.playlists || {};
- } catch (error) {
- console.error("Error loading playlists:", error);
- }
- },
- formatPlaylistName(name) {
- // Convert "listening-1" to "Listening - 1"
- return name
- .split("-")
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
- .join(" - ");
- },
- openVideo(url) {
- browser.tabs.create({ url });
- },
- async removeVideo(playlistName, index) {
- const playlists = JSON.parse(JSON.stringify(this.playlists));
- // Make a copy of the current playlist
- const playlist = [...playlists[playlistName]];
- // Remove the video at the specified index
- playlist.splice(index, 1);
- // Create an updated playlists object with the remaining playlists unchanged
- const updatedPlaylists = {
- ...playlists,
- [playlistName]: playlist,
- };
- // Update the playlists in storage
- try {
- await browser.storage.local.set({ playlists: updatedPlaylists });
- this.playlists = updatedPlaylists;
- } catch (error) {
- console.error("Error removing video:", error);
- }
- },
- async exportPlaylists() {
- try {
- // Get current playlists
- const playlistResult = await browser.storage.local.get("playlists");
- const playlists = playlistResult.playlists || {};
- // Get playback history
- const historyResult = await browser.storage.local.get("history");
- const playbackHistory = historyResult.history || {};
- // Create export data object
- const exportData = {
- playlists,
- playbackHistory,
- exportDate: new Date().toISOString(),
- };
- // Convert to JSON
- const jsonString = JSON.stringify(exportData, null, 2);
- // Create download
- const blob = new Blob([jsonString], { type: "application/json" });
- const url = URL.createObjectURL(blob);
- // Trigger download
- const a = document.createElement("a");
- a.href = url;
- a.download = `playlists-export-${new Date().toISOString().split("T")[0]}.json`;
- document.body.appendChild(a);
- a.click();
- // Clean up
- setTimeout(() => {
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- }, 100);
- } catch (error) {
- console.error("Error exporting playlists:", error);
- }
- },
- videotitle: {
- ["@click"]() {
- console.log("TITLE CLICK", this.$el);
- },
- },
- videoPlayLink: {
- ["@click.prevent"]() {
- browser.tabs.update({ url: this.$el.href });
- },
- },
- removeVideoButton: {
- ["@click"]() {
- this.removeVideo(
- this.$el.dataset.playlistName,
- this.$el.dataset.playlistIndex,
- );
- },
- },
- exportButton: {
- ["@click"]() {
- this.exportPlaylists();
- },
- },
- importButton: {
- ["@click"]() {
- document.getElementById("import-file-input").click();
- },
- },
- importFile(event) {
- const file = event.target.files[0];
- if (!file) return;
- const reader = new FileReader();
- reader.onload = (e) => {
- try {
- const importedData = JSON.parse(e.target.result);
- this.validateAndImportPlaylists(importedData);
- } catch (error) {
- console.error("Error parsing JSON file:", error);
- alert(
- "Invalid JSON file. Please select a valid playlist export file.",
- );
- } finally {
- // Reset the file input so the same file can be selected again
- event.target.value = "";
- }
- };
- reader.readAsText(file);
- },
- validateAndImportPlaylists(data) {
- // Validate the playlists structure
- if (!data.playlists || typeof data.playlists !== "object") {
- alert("Invalid file format: Missing or invalid 'playlists' property");
- return;
- }
- // Validate each playlist
- const validPlaylists = {};
- let hasErrors = false;
- for (const [playlistName, videos] of Object.entries(data.playlists)) {
- // Check if videos is an array
- if (!Array.isArray(videos)) {
- console.error(
- `Playlist '${playlistName}' does not contain a valid array of videos`,
- );
- hasErrors = true;
- continue;
- }
- // Validate each video in the playlist
- const validVideos = videos.filter((video) => {
- if (!video || typeof video !== "object") {
- console.error(`Invalid video object in '${playlistName}'`);
- return false;
- }
- if (
- !video.url ||
- typeof video.url !== "string" ||
- !video.title ||
- typeof video.title !== "string"
- ) {
- console.error(
- `Video in '${playlistName}' missing required properties (url, title)`,
- );
- return false;
- }
- return true;
- });
- // Add the validated playlist if it has valid videos
- if (validVideos.length > 0) {
- validPlaylists[playlistName] = validVideos;
- }
- }
- if (Object.keys(validPlaylists).length === 0) {
- alert("No valid playlists found in the import file");
- return;
- }
- if (hasErrors) {
- const confirmImport = confirm(
- "Some playlists or videos were invalid and will be skipped. Do you want to continue with the import?",
- );
- if (!confirmImport) return;
- }
- // Update storage and state
- this.updatePlaylists(validPlaylists);
- },
- async updatePlaylists(playlists) {
- try {
- await browser.storage.local.set({ playlists });
- this.playlists = playlists;
- alert("Playlists imported successfully!");
- } catch (error) {
- console.error("Error updating playlists:", error);
- alert("Error importing playlists: " + error.message);
- }
- },
- }));
- });
|