playlist.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. let songIndex = 0;
  2. let songsToDelete = [];
  3. let playlistToRemove = "";
  4. let deleteAll = false;
  5. let db;
  6. // Cached DOM elements
  7. const returnToMainFrameButton = document.getElementById('return-to-main-frame');
  8. const addPlaylistButton = document.getElementById('add-new-playlist-button');
  9. const deleteAllButton = document.getElementById('delete-all-button');
  10. const saveButton = document.getElementById('save-button');
  11. const exportButton = document.getElementById('export-button');
  12. const openImportMenuButton = document.getElementById('open-import-menu-button');
  13. const inputPlaylistName = document.getElementById('input-playlist-name');
  14. const playlistsContainer = document.getElementById('playlists');
  15. const songContainer = document.getElementById('songs');
  16. const optionsButton = document.getElementById("options-button");
  17. const playerSelect = document.getElementById("player-select");
  18. const themeSelect = document.getElementById("theme-select");
  19. const fontSelect = document.getElementById("font-select");
  20. const styleSelect = document.getElementById("style-select");
  21. const saveOptionsButton = document.getElementById('save-button-options-panel');
  22. const closeOptionsButton = document.getElementById('close-button-options-panel');
  23. const importButton = document.getElementById("import-button");
  24. const closeImportButton = document.getElementById("close-import-menu");
  25. // Add event listeners
  26. returnToMainFrameButton.addEventListener('click', ReturnToMainFrame);
  27. addPlaylistButton.addEventListener('click', CreateNewPlaylist);
  28. deleteAllButton.addEventListener('click', MarkTotalDeletion);
  29. saveButton.addEventListener('click', SaveChangesToPlaylist);
  30. exportButton.addEventListener('click', ExportDatabaseToFile);
  31. openImportMenuButton.addEventListener('click', OpenImportMenu);
  32. optionsButton.addEventListener('click', OpenOptionMenu);
  33. playerSelect.addEventListener('change', ChangePlayer);
  34. themeSelect.addEventListener('change', ChangeTheme);
  35. fontSelect.addEventListener('change', ChangeFont);
  36. styleSelect.addEventListener('change', ChangeStyle);
  37. saveOptionsButton.addEventListener('click', SaveOptionsPanel);
  38. closeOptionsButton.addEventListener('click', CloseOptionsPanel);
  39. importButton.addEventListener('click', ImportData);
  40. closeImportButton.addEventListener('click', CloseImportPanel);
  41. Initialize();
  42. // Load user preferences
  43. function Initialize() {
  44. ConnectDatabase().then((db) => {
  45. songsToDelete = [];
  46. playlistToRemove = "";
  47. deleteAll = false;
  48. // Load preferred player
  49. RetrieveDataFromDatabase('preferredPlayer').then((preferredPlayer) => {
  50. if (preferredPlayer !== null && preferredPlayer !== undefined) {
  51. // Set player
  52. playerSelect.value = preferredPlayer;
  53. } else {
  54. // Set default player
  55. playerSelect.value = "youtube-player";
  56. }
  57. })
  58. .catch((error) => {
  59. console.error('Error:', error);
  60. });
  61. // Load preferred theme
  62. RetrieveDataFromDatabase('preferredTheme').then((preferredTheme) => {
  63. if (preferredTheme !== null && preferredTheme !== undefined) {
  64. // Set theme
  65. themeSelect.value = preferredTheme;
  66. ChangeTheme();
  67. } else {
  68. // Set default theme
  69. themeSelect.value = "white-theme";
  70. ChangeTheme();
  71. }
  72. })
  73. .catch((error) => {
  74. console.error('Error:', error);
  75. });
  76. // Load preferred font
  77. RetrieveDataFromDatabase('preferredFont').then((preferredFont) => {
  78. if (preferredFont !== null && preferredFont !== undefined) {
  79. // Set font
  80. fontSelect.value = preferredFont;
  81. ChangeFont();
  82. } else {
  83. // Set default font
  84. fontSelect.value = "barlow-font";
  85. ChangeFont();
  86. }
  87. })
  88. .catch((error) => {
  89. console.error('Error:', error);
  90. });
  91. // Load preferred style
  92. RetrieveDataFromDatabase('preferredStyle').then((preferredStyle) => {
  93. if (preferredStyle !== null && preferredStyle !== undefined) {
  94. // Set style
  95. styleSelect.value = preferredStyle;
  96. ChangeStyle();
  97. } else {
  98. // Set default style
  99. styleSelect.value = "sharp-style";
  100. ChangeStyle();
  101. }
  102. })
  103. .catch((error) => {
  104. console.error('Error:', error);
  105. });
  106. LoadPlaylists();
  107. // Remove text from input field
  108. const inputInsertBackup = document.getElementById('input-insert-backup');
  109. inputInsertBackup.value = '';
  110. })
  111. .catch((error) => {
  112. // Connection error
  113. });
  114. }
  115. // Function to load playlists from localStorage
  116. function LoadPlaylists() {
  117. GetPlaylistsFromDatabase().then((savedPlaylists) => {
  118. if (savedPlaylists !== null && savedPlaylists !== undefined) {
  119. savedPlaylists.playlists.forEach(function (playlist) {
  120. AddPlaylist(playlist.playlistId, playlist.name);
  121. });
  122. localStorage.setItem("savedPlaylists", JSON.stringify(savedPlaylists));
  123. }
  124. })
  125. .catch((error) => {
  126. console.error('Error:', error);
  127. });
  128. }
  129. // Function to create a new playlist
  130. function CreateNewPlaylist() {
  131. GetPlaylistsFromDatabase().then((savedPlaylists) => {
  132. if (savedPlaylists !== null && savedPlaylists !== undefined) {
  133. const newRandomId = GenerateRandomId();
  134. const newPlaylist = {
  135. "playlistId": newRandomId,
  136. "name": "New Playlist",
  137. "songs": []
  138. };
  139. savedPlaylists.playlists.push(newPlaylist);
  140. savedPlaylistsString = JSON.stringify(savedPlaylists);
  141. // Save data to localStorage for functions that must be 'user-initiated' and don't work with async (like opening a new tab in the browser)
  142. localStorage.setItem("savedPlaylists", savedPlaylistsString);
  143. // Save to database
  144. AddOrUpdateDataInDatabase('savedPlaylists', savedPlaylistsString).then(() => {
  145. AddPlaylist(newRandomId, "New Playlist");
  146. })
  147. .catch((error) => {
  148. console.error('Error:', error);
  149. });
  150. }
  151. })
  152. .catch((error) => {
  153. console.error('Error:', error);
  154. });
  155. }
  156. // Function to add a playlist to the UI
  157. function AddPlaylist(id, name) {
  158. const playlistContainer = document.createElement('div');
  159. playlistContainer.className = 'playlist';
  160. playlistContainer.classList.add('playlist', 'list-objects-theme', 'borders-theme');
  161. const playlistName = document.createElement('div');
  162. playlistName.classList.add('playlist-name', 'text-theme', 'font-type');
  163. playlistName.textContent = name || 'New Playlist';
  164. const playButton = document.createElement('button');
  165. playButton.classList.add('playlist-play-button', 'borders-theme');
  166. playButton.addEventListener('click', () => {PlaySongs(id);});
  167. const editButton = document.createElement('button');
  168. editButton.classList.add('playlist-edit-button', 'borders-theme');
  169. editButton.addEventListener('click', () => {ToggleEditPlaylist(id);});
  170. playlistContainer.appendChild(playlistName);
  171. playlistContainer.appendChild(playButton);
  172. playlistContainer.appendChild(editButton);
  173. playlistsContainer.appendChild(playlistContainer);
  174. }
  175. // Function to toggle between edit and main frames
  176. function ToggleEditPlaylist(playlistId) {
  177. const playlistMainFrame = document.getElementById('playlist-main-window');
  178. const editMainFrame = document.getElementById('edit-playlist-main-window');
  179. editMainFrame.style.display = 'flex';
  180. playlistMainFrame.style.display = 'none';
  181. LoadSongs(playlistId);
  182. ModifyAddSongButton(playlistId);
  183. ModifyEditPlaylistName(playlistId);
  184. ModifyInputPlaylistName(playlistId);
  185. ModifyDeletePlaylistButton(playlistId);
  186. const inputInsertURL = document.getElementById("input-insert-url");
  187. inputInsertURL.value = "";
  188. inputInsertURL.addEventListener("keyup", function(event) {
  189. if (event.key === "Enter") {
  190. AddSong(playlistId);
  191. inputInsertURL.value = "";
  192. }
  193. });
  194. const inputPlaylistName = document.getElementById('input-playlist-name');
  195. // Load the name of a playlist
  196. GetPlaylistsFromDatabase().then((savedPlaylists) => {
  197. if (savedPlaylists !== null && savedPlaylists !== undefined) {
  198. const playlist = savedPlaylists.playlists.find(playlist => playlist.playlistId === playlistId);
  199. inputPlaylistName.value = playlist ? playlist.name : "";
  200. }
  201. })
  202. .catch((error) => {
  203. console.error('Error:', error);
  204. });
  205. }
  206. function GetPlaylistsFromDatabase() {
  207. return new Promise((resolve, reject) => {
  208. RetrieveDataFromDatabase('savedPlaylists')
  209. .then((value) => {
  210. if (value === null || value === undefined) {
  211. CreateNewLocalStorageStructure();
  212. const newStructure = {"playlists": []};
  213. return newStructure;
  214. } else {
  215. resolve(JSON.parse(value));
  216. }
  217. })
  218. .catch((error) => {
  219. console.error('Error:', error);
  220. reject(error);
  221. });
  222. });
  223. }
  224. // Function to remove all playlists from the UI
  225. function DestroyPlaylists() {
  226. const playlistElements = document.querySelectorAll(".playlist");
  227. playlistElements.forEach(playlist => {
  228. playlist.remove();
  229. });
  230. }
  231. // Function to create a new localStorage structure
  232. function CreateNewLocalStorageStructure() {
  233. const newStructure = {
  234. "playlists": []
  235. };
  236. AddOrUpdateDataInDatabase('savedPlaylists', JSON.stringify(newStructure)).then(() => {
  237. return;
  238. })
  239. .catch((error) => {
  240. console.error('Error:', error);
  241. });
  242. }
  243. // Function to load songs for a playlist
  244. function LoadSongs(playlistId) {
  245. GetPlaylistsFromDatabase().then((savedPlaylists) => {
  246. if (savedPlaylists !== null && savedPlaylists !== undefined) {
  247. const playlist = savedPlaylists.playlists.find(playlist => playlist.playlistId === playlistId);
  248. if (playlist) {
  249. songIndex = 0;
  250. playlist.songs.forEach(function (song) {
  251. songIndex += 1;
  252. AddSongElement(song.songId, song.name, playlistId);
  253. });
  254. }
  255. }
  256. })
  257. .catch((error) => {
  258. console.error('Error:', error);
  259. });
  260. }
  261. // Function to add a song element to the UI
  262. function AddSongElement(songId, name, playlistId) {
  263. const songContainer = document.createElement('div');
  264. songContainer.classList.add('song', 'list-objects-theme', 'borders-theme');
  265. const songNumber = document.createElement('div');
  266. songNumber.classList.add('song-number', 'text-theme', 'borders-theme', 'font-type');
  267. songNumber.textContent = songIndex;
  268. const inputSongName = document.createElement("input");
  269. inputSongName.classList.add('input-song-name', 'text-theme', 'font-type');
  270. inputSongName.setAttribute("type", "text");
  271. inputSongName.setAttribute("value", name);
  272. inputSongName.setAttribute("disabled", "true");
  273. inputSongName.addEventListener("keydown", (event) => {
  274. if (event.key === "Enter") {
  275. event.preventDefault();
  276. inputSongName.setAttribute("disabled", "true");
  277. inputSongName.setSelectionRange(0, 0);
  278. inputSongName.focus();
  279. ChangeSongName(playlistId, songId, inputSongName.value);
  280. }
  281. });
  282. const editSongNameButton = document.createElement('button');
  283. editSongNameButton.classList.add('edit-song-name-button', 'borders-theme');
  284. editSongNameButton.addEventListener('click', function () {
  285. ToggleEditSongName(playlistId, songId, inputSongName);
  286. });
  287. const removeSongButton = document.createElement('button');
  288. removeSongButton.classList.add('remove-song-button', 'borders-theme');
  289. removeSongButton.addEventListener('click', function () {
  290. ToggleSongDeletion(songContainer, playlistId, songId);
  291. });
  292. songContainer.appendChild(songNumber);
  293. songContainer.appendChild(inputSongName);
  294. songContainer.appendChild(editSongNameButton);
  295. songContainer.appendChild(removeSongButton);
  296. const songParent = document.getElementById('songs');
  297. songParent.appendChild(songContainer);
  298. }
  299. // Function to toggle editing of song name
  300. function ToggleEditSongName(playlistId, songId, inputSongName) {
  301. if (inputSongName.disabled) {
  302. inputSongName.removeAttribute("disabled");
  303. } else {
  304. inputSongName.setAttribute("disabled", "true");
  305. inputSongName.setSelectionRange(0, 0);
  306. inputSongName.focus();
  307. ChangeSongName(playlistId, songId, inputSongName.value);
  308. }
  309. }
  310. // Function to toggle song deletion
  311. function ToggleSongDeletion(songContainer, playlistId, songId) {
  312. const updatedArray = songsToDelete.filter(innerArray => !innerArray.includes(songId));
  313. if (updatedArray.length === songsToDelete.length) {
  314. const songToRemove = [playlistId, songId];
  315. songsToDelete.push(songToRemove);
  316. songContainer.classList.add('marked-for-deletion');
  317. } else {
  318. songsToDelete = updatedArray;
  319. songContainer.classList.remove('marked-for-deletion');
  320. }
  321. }
  322. // Function to modify the "add-song-button" button
  323. function ModifyAddSongButton(playlistId) {
  324. const addSongButton = document.getElementById('add-song-button');
  325. addSongButton.addEventListener('click', function () {
  326. AddSong(playlistId);
  327. const inputField = document.getElementById("input-insert-url");
  328. inputField.value = "";
  329. });
  330. }
  331. // Function to modify the "playlist-change-name-button" button
  332. function ModifyEditPlaylistName(playlistId) {
  333. const editPlaylistNameButton = document.getElementById('playlist-change-name-button');
  334. const inputPlaylistName = document.getElementById('input-playlist-name');
  335. editPlaylistNameButton.addEventListener('click', function () {
  336. ToggleEditPlaylistName(playlistId, inputPlaylistName);
  337. });
  338. }
  339. // Function to toggle editing of playlist name
  340. function ToggleEditPlaylistName(playlistId, inputPlaylistName) {
  341. if (inputPlaylistName.disabled) {
  342. inputPlaylistName.removeAttribute("disabled");
  343. } else {
  344. inputPlaylistName.setAttribute("disabled", "true");
  345. inputPlaylistName.setSelectionRange(0, 0);
  346. inputPlaylistName.focus();
  347. RenamePlaylist(playlistId, inputPlaylistName.value);
  348. }
  349. }
  350. // Function to remove all events from the "playlist-change-name-button" button
  351. function RemoveAllEventsFromEditPlaylistNameButton() {
  352. const renamePlaylistButton = document.getElementById("playlist-change-name-button");
  353. const newButton = renamePlaylistButton.cloneNode(true);
  354. renamePlaylistButton.parentNode.replaceChild(newButton, renamePlaylistButton);
  355. }
  356. // Function to remove all events from the input playlist name field
  357. function RemoveAllEventsFromInputPlaylistName() {
  358. const inputPlaylistName = document.getElementById("input-playlist-name");
  359. const newInput = inputPlaylistName.cloneNode(true);
  360. inputPlaylistName.parentNode.replaceChild(newInput, inputPlaylistName);
  361. }
  362. // Function to rename a playlist
  363. function RenamePlaylist(playlistId, newName) {
  364. GetPlaylistsFromDatabase().then((savedPlaylists) => {
  365. if (savedPlaylists !== null && savedPlaylists !== undefined) {
  366. const playlist = savedPlaylists.playlists.find(playlist => playlist.playlistId === playlistId);
  367. if (playlist) {
  368. playlist.name = newName;
  369. }
  370. savedPlaylistsString = JSON.stringify(savedPlaylists);
  371. // Save data to localStorage for functions that must be 'user-initiated' and don't work with async (like opening a new tab in the browser)
  372. localStorage.setItem("savedPlaylists", savedPlaylistsString);
  373. // Save to database
  374. AddOrUpdateDataInDatabase('savedPlaylists', savedPlaylistsString).then(() => {
  375. return;
  376. })
  377. .catch((error) => {
  378. console.error('Error:', error);
  379. });
  380. }
  381. })
  382. .catch((error) => {
  383. console.error('Error:', error);
  384. });
  385. }
  386. // Function to remove all events from the "add-song-button" button
  387. function RemoveAllEventsFromAddSongButton() {
  388. const addSongButton = document.getElementById("add-song-button");
  389. const newButton = addSongButton.cloneNode(true);
  390. addSongButton.parentNode.replaceChild(newButton, addSongButton);
  391. }
  392. // Function to remove all events from the "playlist-delete-button" button
  393. function RemoveAllEventsFromPlaylistDeleteButton() {
  394. const deletePlaylistButton = document.getElementById("playlist-delete-button");
  395. const newButton = deletePlaylistButton.cloneNode(true);
  396. deletePlaylistButton.parentNode.replaceChild(newButton, deletePlaylistButton);
  397. // Remove playlist to be deleted in case there is one and change the field color
  398. playlistToRemove = "";
  399. const parent = document.getElementById('playlist-name-parent');
  400. parent.classList.remove('marked-for-deletion');
  401. }
  402. // Mark all playlists for deletion
  403. function MarkTotalDeletion() {
  404. if(deleteAll) {
  405. deleteAll = false;
  406. // Change button color
  407. deleteAllButton.classList.remove('total-delete');
  408. } else {
  409. deleteAll = true;
  410. // Change button color
  411. deleteAllButton.classList.add('total-delete');
  412. }
  413. }
  414. // Function to add a song to a playlist
  415. function AddSong(playlistId) {
  416. const inputURL = ExtractVideoId(document.getElementById("input-insert-url").value);
  417. if (inputURL) {
  418. GetPlaylistsFromDatabase().then((savedPlaylists) => {
  419. if (savedPlaylists !== null && savedPlaylists !== undefined) {
  420. const newRandomId = GenerateRandomId();
  421. const newSong = {
  422. "songId": newRandomId,
  423. "name": "New Song",
  424. "url": inputURL
  425. };
  426. const playlistToUpdate = savedPlaylists.playlists.find(playlist => playlist.playlistId === playlistId);
  427. playlistToUpdate.songs.push(newSong);
  428. savedPlaylistsString = JSON.stringify(savedPlaylists);
  429. // Save data to localStorage for functions that must be 'user-initiated' and don't work with async (like opening a new tab in the browser)
  430. localStorage.setItem("savedPlaylists", savedPlaylistsString);
  431. // Save to database
  432. AddOrUpdateDataInDatabase('savedPlaylists', savedPlaylistsString).then(() => {
  433. songIndex += 1;
  434. AddSongElement(newRandomId, "New Song", playlistId);
  435. })
  436. .catch((error) => {
  437. console.error('Error:', error);
  438. });
  439. }
  440. })
  441. .catch((error) => {
  442. console.error('Error:', error);
  443. });
  444. }
  445. }
  446. // Function to remove all song elements from the UI
  447. function DestroyAllSongs() {
  448. const songElements = document.querySelectorAll(".song");
  449. songElements.forEach(song => {
  450. song.remove();
  451. });
  452. }
  453. // Function to generate a random ID
  454. function GenerateRandomId() {
  455. const timestamp = new Date().getTime();
  456. const random = Math.random().toString(36).substring(2, 10);
  457. return `${timestamp}_${random}`;
  458. }
  459. // Function to save changes to playlists
  460. function SaveChangesToPlaylist() {
  461. if (playlistToRemove !== "") {
  462. GetPlaylistsFromDatabase().then((savedPlaylists) => {
  463. if (savedPlaylists !== null && savedPlaylists !== undefined) {
  464. // Filter out the playlist with the specified ID
  465. const updatedPlaylists = savedPlaylists.playlists.filter(playlist => playlist.playlistId !== playlistToRemove);
  466. // Update the JSON data with the filtered playlists
  467. savedPlaylists.playlists = updatedPlaylists;
  468. playlistToRemove = "";
  469. savedPlaylistsString = JSON.stringify(savedPlaylists);
  470. // Save data to localStorage for functions that must be 'user-initiated' and don't work with async (like opening a new tab in the browser)
  471. localStorage.setItem("savedPlaylists", savedPlaylistsString);
  472. // Save to database
  473. AddOrUpdateDataInDatabase('savedPlaylists', savedPlaylistsString).then(() => {
  474. ReturnToMainFrame();
  475. })
  476. .catch((error) => {
  477. console.error('Error:', error);
  478. });
  479. }
  480. })
  481. .catch((error) => {
  482. console.error('Error:', error);
  483. });
  484. }
  485. if (songsToDelete.length > 0) {
  486. GetPlaylistsFromDatabase().then((savedPlaylists) => {
  487. if (savedPlaylists !== null && savedPlaylists !== undefined) {
  488. let playlistIdToFind = "";
  489. for (const item of songsToDelete) {
  490. playlistIdToFind = item[0];
  491. const songIdToRemove = item[1];
  492. const playlist = savedPlaylists.playlists.find(playlist => playlist.playlistId === playlistIdToFind);
  493. if (playlist) {
  494. playlist.songs = playlist.songs.filter(song => song.songId !== songIdToRemove);
  495. const index = savedPlaylists.playlists.findIndex(p => p.playlistId === playlistIdToFind);
  496. if (index !== -1) {
  497. savedPlaylists.playlists[index] = playlist;
  498. }
  499. }
  500. }
  501. songsToDelete = [];
  502. savedPlaylistsString = JSON.stringify(savedPlaylists);
  503. // Save data to localStorage for functions that must be 'user-initiated' and don't work with async (like opening a new tab in the browser)
  504. localStorage.setItem("savedPlaylists", savedPlaylistsString);
  505. // Save to database
  506. AddOrUpdateDataInDatabase('savedPlaylists', savedPlaylistsString).then(() => {
  507. DestroyAllSongs();
  508. LoadSongs(playlistIdToFind);
  509. })
  510. .catch((error) => {
  511. console.error('Error:', error);
  512. });
  513. }
  514. })
  515. .catch((error) => {
  516. console.error('Error:', error);
  517. });
  518. }
  519. }
  520. // Function to change the name of a song
  521. function ChangeSongName(playlistId, songId, newName) {
  522. GetPlaylistsFromDatabase().then((savedPlaylists) => {
  523. if (savedPlaylists !== null && savedPlaylists !== undefined) {
  524. const playlist = savedPlaylists.playlists.find(playlist => playlist.playlistId === playlistId);
  525. if (playlist) {
  526. const song = playlist.songs.find(song => song.songId === songId);
  527. if (song) {
  528. song.name = newName;
  529. }
  530. }
  531. savedPlaylistsString = JSON.stringify(savedPlaylists);
  532. // Save data to localStorage for functions that must be 'user-initiated' and don't work with async (like opening a new tab in the browser)
  533. localStorage.setItem("savedPlaylists", savedPlaylistsString);
  534. // Save to database
  535. AddOrUpdateDataInDatabase('savedPlaylists', savedPlaylistsString).then(() => {
  536. return;
  537. })
  538. .catch((error) => {
  539. console.error('Error:', error);
  540. });
  541. }
  542. })
  543. .catch((error) => {
  544. console.error('Error:', error);
  545. });
  546. }
  547. // Function to play songs in a playlist
  548. function PlaySongs(playlistId) {
  549. let savedPlaylists = JSON.parse(localStorage.getItem('savedPlaylists'));
  550. let songUrls = "";
  551. for (const playlist of savedPlaylists.playlists) {
  552. if (playlist.playlistId === playlistId) {
  553. for (const song of playlist.songs) {
  554. songUrls += song.url + ",";
  555. }
  556. break;
  557. }
  558. }
  559. if (songUrls) {
  560. if(playerSelect.value === 'youtube-player')
  561. {
  562. window.open("http://www.youtube.com/watch_videos?video_ids=" + songUrls);
  563. }
  564. else
  565. {
  566. window.open("http://yewtu.be/watch_videos?video_ids=" + songUrls);
  567. }
  568. }
  569. }
  570. // Function to clean up and return to main menu
  571. function ReturnToMainFrame() {
  572. // Get DOM elements
  573. const playlistMainFrame = document.getElementById('playlist-main-window');
  574. const editMainFrame = document.getElementById('edit-playlist-main-window');
  575. const inputPlaylistName = document.getElementById("input-playlist-name");
  576. // Disable input playlist name
  577. inputPlaylistName.setAttribute("disabled", "true");
  578. // Show the main frame and hide the edit frame
  579. playlistMainFrame.style.display = 'grid';
  580. editMainFrame.style.display = 'none';
  581. // Reset and clean up
  582. DestroyAllSongs();
  583. RemoveAllEventsFromAddSongButton();
  584. RemoveAllEventsFromEditPlaylistNameButton();
  585. RemoveAllEventsFromInputPlaylistName();
  586. RemoveAllEventsFromPlaylistDeleteButton();
  587. songsToDelete = [];
  588. DestroyPlaylists();
  589. LoadPlaylists();
  590. }
  591. // Function to close options panel
  592. function CloseOptionsPanel() {
  593. // Unmark delition
  594. deleteAll = false;
  595. // Change button color
  596. deleteAllButton.classList.remove('total-delete');
  597. // Reload playlists
  598. DestroyPlaylists();
  599. LoadPlaylists();
  600. // Show main menu
  601. const playlistMainFrame = document.getElementById('playlist-main-window');
  602. const optionsMenu = document.getElementById("options-main-window");
  603. optionsMenu.style.display = 'none';
  604. playlistMainFrame.style.display = 'grid';
  605. }
  606. // Function to modify input field for playlist name
  607. function ModifyInputPlaylistName(playlistId) {
  608. const inputPlaylistName = document.getElementById('input-playlist-name');
  609. inputPlaylistName.addEventListener("keydown", (event) => {
  610. if (event.key === "Enter") {
  611. event.preventDefault();
  612. ToggleEditPlaylistName(playlistId, inputPlaylistName);
  613. }
  614. });
  615. }
  616. // Function to modify playlist-delete-button
  617. function ModifyDeletePlaylistButton(playlistId) {
  618. // Add listener to delete playlist button
  619. const deletePlaylistButton = document.getElementById('playlist-delete-button');
  620. deletePlaylistButton.addEventListener('click', function () {
  621. const parent = document.getElementById('playlist-name-parent');
  622. if (playlistToRemove !== "") { // There alrady is a playlsit marked for deletion, unmart it
  623. playlistToRemove = "";
  624. parent.classList.remove('marked-for-deletion');
  625. } else { // Mark playlist for deletion
  626. playlistToRemove = playlistId;
  627. parent.classList.add('marked-for-deletion');
  628. }
  629. });
  630. }
  631. // Export the saved playlists to a json file
  632. function ExportDatabaseToFile() {
  633. GetPlaylistsFromDatabase().then((jsonData) => {
  634. if (jsonData !== null && jsonData !== undefined) {
  635. let data = "";
  636. jsonData.playlists.forEach((playlist, index) => {
  637. // Convert the playlistData to a JSON string
  638. data += JSON.stringify(playlist) + ",";
  639. });
  640. data = data.substring(0, data.length -1); // Removes the last extra comma
  641. data = "[" + data + "]"; // Add [] brackets so it can be parsed back into JSON
  642. const blob = new Blob([data], { type: 'text/plain' });
  643. const url = URL.createObjectURL(blob);
  644. const a = document.createElement('a');
  645. a.style.display = 'none';
  646. a.href = url;
  647. a.setAttribute('download', "Playlist");
  648. document.body.appendChild(a);
  649. a.click();
  650. document.body.removeChild(a);
  651. URL.revokeObjectURL(url);
  652. }
  653. })
  654. .catch((error) => {
  655. console.error('Error:', error);
  656. });
  657. }
  658. // Function to assign new playlistId values
  659. function AssignNewPlaylistIds(data) {
  660. data.playlists.forEach((playlist) => {
  661. playlist.playlistId = GenerateRandomId();
  662. });
  663. }
  664. // Change the player
  665. function ChangePlayer() {
  666. playerName = playerSelect.value;
  667. // Update database with preferred player
  668. AddOrUpdateDataInDatabase('preferredPlayer', playerName)
  669. .catch((error) => {
  670. console.error('Error:', error);
  671. });
  672. }
  673. // Change the visual themes
  674. function ChangeTheme() {
  675. themeName = themeSelect.value;
  676. // Remove existing theme classes
  677. const themes = ['white-theme', 'black-theme', 'neon-pink-theme', 'matrix-theme', 'huwhite-theme', 'blue-theme', 'coffee-theme', 'night-theme', 'forest-theme'];
  678. const body = document.body;
  679. body.classList.remove(...themes);
  680. // Add the selected theme class
  681. body.classList.add(themeName);
  682. // Update database with preferred theme
  683. AddOrUpdateDataInDatabase('preferredTheme', themeName)
  684. .catch((error) => {
  685. console.error('Error:', error);
  686. });
  687. }
  688. // Change font
  689. function ChangeFont() {
  690. fontName = fontSelect.value;
  691. // Remove existing font classes
  692. const fonts = ['barlow-font', 'cormorant-unicase-font', 'exo2-font', 'gemunu-libre-font', 'josefin-sans-font', 'oswald-font', 'roboto-condensed-font', 'roboto-font', 'roboto-slab-font', 'space-grotesk-font', 'zilla-slab-font'];
  693. const body = document.body;
  694. body.classList.remove(...fonts);
  695. // Add the selected font class
  696. body.classList.add(fontName);
  697. // Update database with preferred font
  698. AddOrUpdateDataInDatabase('preferredFont', fontName)
  699. .catch((error) => {
  700. console.error('Error:', error);
  701. });
  702. }
  703. // Change style
  704. function ChangeStyle() {
  705. styleName = styleSelect.value;
  706. // Remove existing style classes
  707. const styles = ['sharp-style', 'round-style', 'leviosa-style'];
  708. const body = document.body;
  709. body.classList.remove(...styles);
  710. // Add the selected font class
  711. body.classList.add(styleName);
  712. // Update database with preferred style
  713. AddOrUpdateDataInDatabase('preferredStyle', styleName)
  714. .catch((error) => {
  715. console.error('Error:', error);
  716. });
  717. }
  718. // Function to call the options menu and hide the main frame
  719. function OpenOptionMenu() {
  720. const playlistMainFrame = document.getElementById('playlist-main-window');
  721. const optionsMenu = document.getElementById("options-main-window");
  722. optionsMenu.style.display = 'flex';
  723. playlistMainFrame.style.display = 'none';
  724. }
  725. // Function to destroy all playlists and return to main manu
  726. function SaveOptionsPanel() {
  727. if (deleteAll) {
  728. // Destroy all playlists
  729. CreateNewLocalStorageStructure();
  730. // Unmark delition
  731. deleteAll = false;
  732. // Change button color
  733. deleteAllButton.classList.remove('total-delete');
  734. }
  735. }
  736. // Function that opens a specific menu dedicated to importing new data
  737. function OpenImportMenu() {
  738. const optionsMenu = document.getElementById('options-main-window');
  739. const importMenu = document.getElementById("import-main-window");
  740. importMenu.style.display = 'flex';
  741. optionsMenu.style.display = 'none';
  742. }
  743. // Function to close import panel
  744. function CloseImportPanel() {
  745. // Unmark delition
  746. deleteAll = false;
  747. // Change button color
  748. deleteAllButton.classList.remove('total-delete');
  749. // Remove text from input field
  750. const inputInsertBackup = document.getElementById('input-insert-backup');
  751. inputInsertBackup.value = '';
  752. // Reset status
  753. const statusText = document.getElementById('status-message');
  754. statusText.textContent = 'Status: no data.';
  755. // Reload playlists
  756. DestroyPlaylists();
  757. LoadPlaylists();
  758. // Show main menu
  759. const playlistMainFrame = document.getElementById('playlist-main-window');
  760. const importMenu = document.getElementById("import-main-window");
  761. importMenu.style.display = 'none';
  762. playlistMainFrame.style.display = 'grid';
  763. }
  764. // Function to merge data inserted by the user with already existing data
  765. function ImportData() {
  766. GetPlaylistsFromDatabase().then((existingData) => {
  767. if (existingData !== null && existingData !== undefined) {
  768. try {
  769. const inputInsertBackup = document.getElementById('input-insert-backup');
  770. const newData = JSON.parse(inputInsertBackup.value);
  771. if (typeof newData === 'object' && newData !== null)
  772. {
  773. // Merge the new JSON data into existing data
  774. existingData.playlists = existingData.playlists.concat(newData);
  775. // Assign new IDs to every playlist to avoid conflicts
  776. AssignNewPlaylistIds(existingData);
  777. mergedData = JSON.stringify(existingData);
  778. // Save data to localStorage for functions that must be 'user-initiated' and don't work with async (like opening a new tab in the browser)
  779. localStorage.setItem("savedPlaylists", mergedData);
  780. // Save to database
  781. AddOrUpdateDataInDatabase('savedPlaylists', mergedData)
  782. .catch((error) => {
  783. console.error('Error:', error);
  784. });
  785. // Clean input field
  786. inputInsertBackup.value = '';
  787. // change status to success
  788. const statusText = document.getElementById('status-message');
  789. statusText.textContent = 'Status: Data imported.';
  790. }
  791. } catch (error) {
  792. // change status to error
  793. const statusText = document.getElementById('status-message');
  794. statusText.textContent = 'Status: Data is not valid.';
  795. console.error(error);
  796. }
  797. }
  798. })
  799. .catch((error) => {
  800. console.error('Error:', error);
  801. });
  802. }
  803. // Function to extract video ID from url string
  804. function ExtractVideoId(input) {
  805. // Check if the input is a full YouTube URL
  806. if (input.includes('youtube.com/watch?v=')) {
  807. const match = input.match(/[?&]v=([^&]+)/);
  808. if (match) {
  809. return match[1]; // Extracted video ID
  810. }
  811. } else if (input.includes('youtu.be/')) {
  812. // Handle youtu.be short URLs
  813. const match = input.match(/youtu.be\/([^?]+)/);
  814. if (match) {
  815. return match[1]; // Extracted video ID
  816. }
  817. }
  818. // Check if the input is a full yewtu URL
  819. else if (input.includes('yewtu.be/watch?v=')) {
  820. const match = input.match(/[?&]v=([^&]+)/);
  821. if (match) {
  822. return match[1]; // Extracted video ID
  823. }
  824. }
  825. // If it's not a full URL or the pattern doesn't match, assume it's already a video ID
  826. return input;
  827. }
  828. function ConnectDatabase() {
  829. return new Promise((resolve, reject) => {
  830. // Open database
  831. const DBOpenRequest = window.indexedDB.open('userData', 1);
  832. DBOpenRequest.onerror = (event) => {
  833. reject(new Error('Error loading database.'));
  834. };
  835. DBOpenRequest.onsuccess = (event) => {
  836. db = DBOpenRequest.result;
  837. resolve(db);
  838. };
  839. DBOpenRequest.onupgradeneeded = (event) => {
  840. db = event.target.result;
  841. db.onerror = (event) => {
  842. reject(new Error('Error loading database.'));
  843. };
  844. const objectStore = db.createObjectStore('userData', { keyPath: 'key' });
  845. };
  846. });
  847. }
  848. function AddOrUpdateDataInDatabase(key, value) {
  849. return new Promise((resolve, reject) => {
  850. const data = { key: key, value: value };
  851. // Open a read/write DB transaction, ready for adding or updating the data
  852. const transaction = db.transaction(['userData'], 'readwrite');
  853. // Report on the success of the transaction completing, when everything is done
  854. transaction.oncomplete = () => {
  855. //console.log('Transaction completed: database modification finished.');
  856. resolve(); // Resolve the Promise when the transaction is complete
  857. };
  858. // Handler for any unexpected error
  859. transaction.onerror = (event) => {
  860. //console.log(`Transaction not opened due to error: ${transaction.error}`);
  861. reject(transaction.error); // Reject the Promise with the error
  862. };
  863. // Call an object store that's already been added to the database
  864. const objectStore = transaction.objectStore('userData');
  865. // Use the put method to either add or update data
  866. const objectStoreRequest = objectStore.put(data);
  867. objectStoreRequest.onsuccess = (event) => {
  868. //console.log('Request successful.');
  869. };
  870. });
  871. }
  872. function RetrieveDataFromDatabase(key) {
  873. return new Promise((resolve, reject) => {
  874. // Open our object store and then get a cursor list of all the different data items in the IDB to iterate through
  875. const objectStore = db.transaction('userData').objectStore('userData');
  876. const request = objectStore.get(key); // Get the value associated with the key
  877. request.onsuccess = (event) => {
  878. const storedKey = request.result;
  879. if (storedKey) {
  880. resolve(storedKey.value); // Resolve the Promise with the retrieved value
  881. } else {
  882. //console.log("No data found for the key.");
  883. resolve(null); // Resolve with null if no data is found
  884. }
  885. };
  886. request.onerror = (event) => {
  887. //console.error("Error retrieving 'font' value:", event.target.error);
  888. reject(event.target.error); // Reject the Promise with the error
  889. };
  890. });
  891. }
  892. // In case of data corruption, this function can be used to clear the database
  893. function DeleteFromDatabase(key) {
  894. return new Promise((resolve, reject) => {
  895. // Open a read/write DB transaction for deleting data
  896. const transaction = db.transaction(['userData'], 'readwrite');
  897. const objectStore = transaction.objectStore('userData');
  898. const deleteRequest = objectStore.delete(key);
  899. deleteRequest.onsuccess = (event) => {
  900. console.log('Deleted the preference successfully.');
  901. resolve(); // Resolve the Promise when deletion is successful
  902. };
  903. deleteRequest.onerror = (event) => {
  904. console.error('Error deleting the preference:', event.target.error);
  905. reject(new Error('Error deleting preference')); // Reject the Promise on error
  906. };
  907. });
  908. }