musicify.js 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  1. /*
  2. Musicify - Alpine.js Application Component
  3. Modern music player for ArozOS
  4. */
  5. // ─── Default cover art SVG (music note) ──────────────────────────────────────
  6. const DEFAULT_COVER = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' fill='%231e1e26'/%3E%3Ctext x='50' y='62' font-size='48' text-anchor='middle' fill='%23a855f7'%3E%F0%9F%8E%B5%3C/text%3E%3C/svg%3E";
  7. function musicifyApp() {
  8. return {
  9. // ── Navigation ──────────────────────────────────────────────────────
  10. view: 'home', // 'home' | 'folders' | 'artists' | 'recent' | 'playlist'
  11. sidebarOpen: false,
  12. loading: false,
  13. loadingMsg: '',
  14. // ── Folder Browser ──────────────────────────────────────────────────
  15. folderRoot: 'user:/Music',
  16. folderPath: 'user:/Music',
  17. folderStack: [], // stack of previous paths for back navigation
  18. folderContents: { folders: [], songs: [] },
  19. musicLibraries: [], // [ { label, root } ] from listRoots.js
  20. // ── Artists ─────────────────────────────────────────────────────────
  21. artists: [],
  22. selectedArtist: null, // full artist object for dedicated artist songs view
  23. artistDetailOpen: false,
  24. artistsFromCache: false,
  25. artistsRefreshing: false,
  26. artistsCacheUpdatedAt: 0,
  27. _artistsFetchInFlight: false,
  28. _artistsUpdateFlash: false,
  29. _artistsUpdateFlashTimer: null,
  30. _artistsWorker: null,
  31. _artistsWorkerReqId: 0,
  32. _artistsActiveReqId: 0,
  33. _artistsWatchdogTimer: null,
  34. // Artist virtual scrolling
  35. artistRowHeight: 65, // must match CSS .artist-row height
  36. artistOverscan: 120, //artistRowHeight * artistOverscan = overscan px, Should be large enough for playlist expansion
  37. artistScrollTop: 0,
  38. artistListScrollTop: 0,
  39. selectedArtistListScrollTop: 0,
  40. // ── Recent ──────────────────────────────────────────────────────────
  41. recentSongs: [],
  42. // ── Playlists ────────────────────────────────────────────────────────
  43. playlists: [],
  44. currentPlaylistName: null,
  45. currentPlaylistSongs: [],
  46. showNewPlaylistModal: false,
  47. newPlaylistName: '',
  48. showAddToPlaylistModal: false,
  49. addToPlaylistSong: null,
  50. // ── Search ───────────────────────────────────────────────────────────
  51. searchQuery: '',
  52. searchResults: [],
  53. // ── Player ───────────────────────────────────────────────────────────
  54. queue: [], // current ordered play queue
  55. shuffledQueue: [], // shuffled copy used when shuffle is on
  56. queueIndex: -1,
  57. currentTrack: null,
  58. isPlaying: false,
  59. currentTime: 0,
  60. duration: 0,
  61. isSeeking: false,
  62. volume: 80,
  63. isMuted: false,
  64. shuffle: false,
  65. repeat: 'none', // 'none' | 'all' | 'one'
  66. showQueue: false,
  67. coverError: false,
  68. // ── Sleep Timer ──────────────────────────────────────────────────────
  69. showSleepModal: false,
  70. sleepActive: false,
  71. sleepMinutes: 30,
  72. sleepCountdown: '',
  73. _sleepTimer: null,
  74. _sleepEnd: 0,
  75. // ── Recently Played (localStorage) ───────────────────────────────────
  76. recentlyPlayed: [], // last 12 tracks
  77. // ── Track Info Panel ─────────────────────────────────────────────────
  78. showTrackInfo: false,
  79. trackInfoSong: null,
  80. // ── Internal playback guard ──────────────────────────────────────────
  81. _suppressEnded: false, // true while a new track is loading (prevents double-skip)
  82. // ── Helpers (accessible from Alpine template expressions) ─────────────
  83. isSidebarDesktop() { return window.innerWidth > 768; },
  84. // ── Transcode ────────────────────────────────────────────────────────
  85. transcodeMode: '48', // 'disabled' | '16' | '24' | '48' (kHz)
  86. _transcodeSeekOffset: 0, // seconds already seeked past in current transcode stream
  87. _currentTrackTranscoded: false,// true when current track is served via transcode endpoint
  88. // ── Arozcast ─────────────────────────────────────────────────────────
  89. castMode: false,
  90. castConnected: false,
  91. castConnecting: false,
  92. showCastModal: false,
  93. castCode: '',
  94. castCodeInput: '',
  95. castError: '',
  96. _castWs: null,
  97. _castPingTimer: null,
  98. _castWatchTimer: null,
  99. _castLastSeen: 0,
  100. _castReconnectTimer: null,
  101. _castReconnectCount: 0,
  102. _castPendingCode: null,
  103. // ── Internal refs ────────────────────────────────────────────────────
  104. _audio: null,
  105. // ════════════════════════════════════════════════════════════════════
  106. // INIT
  107. // ════════════════════════════════════════════════════════════════════
  108. init() {
  109. this._audio = document.getElementById('musicPlayer');
  110. const self = this;
  111. this._audio.addEventListener('timeupdate', () => {
  112. if (!self.isSeeking) {
  113. self.currentTime = self._audio.currentTime + self._transcodeSeekOffset;
  114. }
  115. });
  116. this._audio.addEventListener('loadedmetadata', () => {
  117. var d = self._audio.duration;
  118. if (self._currentTrackTranscoded) {
  119. // Don't override the pre-fetched duration for transcoded streams
  120. if (!self.duration && d && isFinite(d) && d > 0) self.duration = d;
  121. } else {
  122. self.duration = (d && isFinite(d)) ? d : 0;
  123. }
  124. });
  125. this._audio.addEventListener('ended', () => { self._onEnded(); });
  126. this._audio.addEventListener('error', () => { self._onError(); });
  127. this._audio.addEventListener('play', () => { self.isPlaying = true; self._suppressEnded = false; self._updateMediaSession(); });
  128. this._audio.addEventListener('pause', () => { self.isPlaying = false; self._updateMediaSession(); });
  129. // Restore volume
  130. var savedVol = localStorage.getItem('musicify_volume');
  131. if (savedVol !== null) {
  132. this.volume = parseInt(savedVol);
  133. this._audio.volume = this.volume / 100;
  134. } else {
  135. this._audio.volume = this.volume / 100;
  136. }
  137. // Restore shuffle / repeat / recently-played from server-side prefs
  138. // (cross-device: stored per user, not per browser)
  139. ao_module_storage.loadStorage("Musicify", "shuffle", function(val) {
  140. if (val !== null && val !== undefined) self.shuffle = (val === 'true');
  141. });
  142. ao_module_storage.loadStorage("Musicify", "repeat", function(val) {
  143. if (val === 'all' || val === 'one' || val === 'none') self.repeat = val;
  144. });
  145. ao_module_storage.loadStorage("Musicify", "recent", function(val) {
  146. if (val) {
  147. try { self.recentlyPlayed = JSON.parse(val).slice(0, 12); } catch(e) {}
  148. }
  149. });
  150. var _savedTranscode = localStorage.getItem('musicify_transcodeMode');
  151. if (_savedTranscode === 'disabled' || _savedTranscode === '16' || _savedTranscode === '24' || _savedTranscode === '48') {
  152. this.transcodeMode = _savedTranscode;
  153. }
  154. // MediaSession
  155. this._setupMediaSession();
  156. // Load playlists for sidebar
  157. this._loadPlaylists();
  158. // Pre-load available music library roots for the folder-view switcher
  159. this._loadMusicLibraries();
  160. window.addEventListener('beforeunload', () => {
  161. if (this._artistsWorker) {
  162. this._artistsWorker.terminate();
  163. this._artistsWorker = null;
  164. }
  165. });
  166. // Handle #folder=<path> hash from embedded player's "Open in Musicify" button
  167. var _hash = window.location.hash;
  168. if (_hash.startsWith('#folder=')) {
  169. var _folder = decodeURIComponent(_hash.substring(8));
  170. window.history.replaceState(null, '', window.location.pathname);
  171. this.view = 'folders';
  172. this.folderStack = [];
  173. this.loadFolder(_folder);
  174. }
  175. // Listen for other apps taking over the Arozcast session
  176. try {
  177. var _acCh = new BroadcastChannel('arozcast');
  178. _acCh.onmessage = (evt) => {
  179. if (evt.data && evt.data.type === 'arozcast.takeover' && self.castMode) {
  180. self.disconnectCast();
  181. }
  182. };
  183. } catch(e) {}
  184. // When the user returns to this tab after the phone was asleep, reconnect immediately
  185. document.addEventListener('visibilitychange', function() {
  186. if (document.visibilityState === 'visible' && self._castPendingCode) {
  187. clearTimeout(self._castReconnectTimer);
  188. self._castReconnectTimer = null;
  189. self._attemptCastReconnect();
  190. }
  191. });
  192. // Responsive sidebar
  193. this.sidebarOpen = window.innerWidth > 768;
  194. var resizeT;
  195. window.addEventListener('resize', () => {
  196. clearTimeout(resizeT);
  197. resizeT = setTimeout(() => {
  198. if (window.innerWidth <= 768) this.sidebarOpen = false;
  199. }, 150);
  200. });
  201. },
  202. // ════════════════════════════════════════════════════════════════════
  203. // NAVIGATION
  204. // ════════════════════════════════════════════════════════════════════
  205. navigateTo(v) {
  206. this.view = v;
  207. this.searchQuery = '';
  208. if (window.innerWidth <= 768) this.sidebarOpen = false;
  209. if (v === 'folders') {
  210. if (this.musicLibraries.length === 0) this._loadMusicLibraries();
  211. if (this.folderContents.songs.length === 0 && this.folderContents.folders.length === 0) {
  212. this.loadFolder(this.folderRoot);
  213. }
  214. } else if (v === 'artists') {
  215. this._loadArtists();
  216. } else if (v === 'recent' && this.recentSongs.length === 0) {
  217. this._loadRecent();
  218. }
  219. },
  220. openPlaylistView(name) {
  221. this.currentPlaylistName = name;
  222. this.view = 'playlist';
  223. if (window.innerWidth <= 768) this.sidebarOpen = false;
  224. this._loadPlaylistSongs(name);
  225. },
  226. // ════════════════════════════════════════════════════════════════════
  227. // LIBRARY ROOTS
  228. // ════════════════════════════════════════════════════════════════════
  229. _loadMusicLibraries() {
  230. const self = this;
  231. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/listRoots.js', {
  232. method: 'POST', cache: 'no-cache',
  233. headers: { 'Content-Type': 'application/json' },
  234. body: JSON.stringify({})
  235. }).then(r => r.json()).then(data => {
  236. // Remove tmp:/ and trash:/ from the array
  237. data = Array.isArray(data) ? data.map(d => {
  238. if (d.root.startsWith('tmp:/') || d.root.startsWith('trash:/')) {
  239. return null;
  240. }
  241. return d;
  242. }) : [];
  243. self.musicLibraries = Array.isArray(data) ? data : [];
  244. }).catch(() => {});
  245. },
  246. switchLibrary(root) {
  247. this.folderRoot = root;
  248. this.folderStack = [];
  249. this.folderContents = { folders: [], songs: [] };
  250. this.loadFolder(root, false);
  251. },
  252. // ════════════════════════════════════════════════════════════════════
  253. // FOLDER BROWSER
  254. // ════════════════════════════════════════════════════════════════════
  255. loadFolder(path, showLoading = true) {
  256. if (showLoading) {
  257. this.loadingMsg = 'Loading folder…';
  258. this.loading = true;
  259. }
  260. const self = this;
  261. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/listFolder.js', {
  262. method: 'POST', cache: 'no-cache',
  263. headers: { 'Content-Type': 'application/json' },
  264. body: JSON.stringify({ folder: path })
  265. }).then(r => r.json()).then(data => {
  266. if (data.error) { self._showToast(data.error, 'error'); if (showLoading) self.loading = false; return; }
  267. self.folderContents = data;
  268. self.folderPath = path;
  269. if (showLoading) {
  270. setTimeout(() => { self.loading = false; }, 100); // slight delay for smoother UX
  271. };
  272. }).catch(() => { if (showLoading){
  273. setTimeout(() => { self.loading = false; }, 100); // slight delay for smoother UX
  274. } });
  275. },
  276. folderNavigate(path) {
  277. this.folderStack.push(this.folderPath);
  278. this.artistDetailOpen = false;
  279. this.selectedArtist = null;
  280. this.loadFolder(path);
  281. },
  282. folderBack() {
  283. if (this.folderStack.length === 0) return;
  284. var prev = this.folderStack.pop();
  285. this.loadFolder(prev);
  286. },
  287. getFolderBreadcrumbs() {
  288. var parts = this.folderPath.split('/');
  289. var crumbs = [];
  290. var acc = '';
  291. for (var i = 0; i < parts.length; i++) {
  292. acc = i === 0 ? parts[0] : acc + '/' + parts[i];
  293. crumbs.push({ name: parts[i], path: acc });
  294. }
  295. return crumbs;
  296. },
  297. // ════════════════════════════════════════════════════════════════════
  298. // ARTISTS
  299. // ════════════════════════════════════════════════════════════════════
  300. _loadArtists(opts) {
  301. opts = opts || {};
  302. var forceNetwork = !!opts.forceNetwork;
  303. var self = this;
  304. // Artists refresh should never block the entire content panel.
  305. this.loading = false;
  306. // ── Start the network scan immediately — never wait for cache ─────
  307. if (this._artistsFetchInFlight) return;
  308. this._artistsFetchInFlight = true;
  309. this.artistsRefreshing = true;
  310. var reqId = ++this._artistsWorkerReqId;
  311. this._artistsActiveReqId = reqId;
  312. this._startArtistsWatchdog(reqId);
  313. // Use worker first to keep fetch + JSON parsing off the UI thread.
  314. var startedInWorker = this._dispatchArtistsFetchToWorker(reqId);
  315. if (!startedInWorker) {
  316. this._dispatchArtistsFetchFallback(reqId);
  317. }
  318. // ── In parallel: read server-side cache to pre-populate the UI ────
  319. // Only applies the cache if the network scan has not yet returned.
  320. if (!forceNetwork) {
  321. this._readArtistsCache(function(cache) {
  322. if (self.artistsRefreshing && cache && Array.isArray(cache.items)) {
  323. self.artists = cache.items;
  324. self.artistsFromCache = true;
  325. self.artistsCacheUpdatedAt = cache.ts || 0;
  326. }
  327. });
  328. }
  329. },
  330. _dispatchArtistsFetchToWorker(reqId) {
  331. if (!('Worker' in window)) return false;
  332. const self = this;
  333. if (!this._artistsWorker) {
  334. try {
  335. this._artistsWorker = new Worker('artistsWorker.js');
  336. } catch (e) {
  337. this._artistsWorker = null;
  338. return false;
  339. }
  340. this._artistsWorker.onmessage = function(evt) {
  341. var msg = evt && evt.data ? evt.data : {};
  342. if (msg.type === 'artistsResult') {
  343. self._applyArtistsResult(msg.items, msg.reqId);
  344. } else if (msg.type === 'artistsError') {
  345. self._handleArtistsError(msg.reqId);
  346. }
  347. };
  348. this._artistsWorker.onerror = function() {
  349. self._handleArtistsError(self._artistsActiveReqId);
  350. if (self._artistsWorker) {
  351. self._artistsWorker.terminate();
  352. self._artistsWorker = null;
  353. }
  354. };
  355. }
  356. try {
  357. this._artistsWorker.postMessage({
  358. type: 'fetchArtists',
  359. reqId: reqId,
  360. endpoint: ao_root + 'system/ajgi/interface?script=Musicify/backend/listArtists.js'
  361. });
  362. return true;
  363. } catch (e) {
  364. return false;
  365. }
  366. },
  367. _dispatchArtistsFetchFallback(reqId) {
  368. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/listArtists.js', {
  369. method: 'POST', cache: 'no-cache',
  370. headers: { 'Content-Type': 'application/json' },
  371. body: JSON.stringify({})
  372. }).then(r => r.json()).then(data => {
  373. this._applyArtistsResult(data, reqId);
  374. }).catch(() => {
  375. this._handleArtistsError(reqId);
  376. });
  377. },
  378. _applyArtistsResult(data, reqId) {
  379. if (reqId !== this._artistsActiveReqId) return;
  380. data = Array.isArray(data) ? data : [];
  381. var selectedPath = this.selectedArtist ? this.selectedArtist.path : null;
  382. this.artists = data;
  383. this.artistsFromCache = false;
  384. this.artistsCacheUpdatedAt = Date.now();
  385. this._writeArtistsCache(data, this.artistsCacheUpdatedAt);
  386. this._flashArtistsUpdated();
  387. if (selectedPath) {
  388. var matched = null;
  389. for (var i = 0; i < data.length; i++) {
  390. if (data[i].path === selectedPath) {
  391. matched = data[i];
  392. break;
  393. }
  394. }
  395. this.selectedArtist = matched;
  396. }
  397. this._finalizeArtistsFetch(reqId);
  398. },
  399. _handleArtistsError(reqId) {
  400. if (reqId !== this._artistsActiveReqId) return;
  401. this._finalizeArtistsFetch(reqId);
  402. },
  403. _startArtistsWatchdog(reqId) {
  404. if (this._artistsWatchdogTimer) clearTimeout(this._artistsWatchdogTimer);
  405. const self = this;
  406. this._artistsWatchdogTimer = setTimeout(() => {
  407. if (reqId !== self._artistsActiveReqId) return;
  408. self._finalizeArtistsFetch(reqId);
  409. if (self._artistsWorker) {
  410. self._artistsWorker.terminate();
  411. self._artistsWorker = null;
  412. }
  413. }, 25000);
  414. },
  415. _finalizeArtistsFetch(reqId) {
  416. if (reqId !== this._artistsActiveReqId) return;
  417. if (this._artistsWatchdogTimer) {
  418. clearTimeout(this._artistsWatchdogTimer);
  419. this._artistsWatchdogTimer = null;
  420. }
  421. this.artistsRefreshing = false;
  422. this._artistsFetchInFlight = false;
  423. },
  424. // Reads the server-side artists cache (user:/.appdata/Musicify/).
  425. // Async — calls callback(cache) where cache is { ts, items } or null.
  426. _readArtistsCache(callback) {
  427. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/getArtistsCache.js', {
  428. method: 'POST', cache: 'no-cache',
  429. headers: { 'Content-Type': 'application/json' },
  430. body: JSON.stringify({})
  431. }).then(function(r) { return r.json(); })
  432. .then(function(data) {
  433. if (data && !data.error && Array.isArray(data.items)) {
  434. callback({ ts: data.ts || 0, items: data.items });
  435. } else {
  436. callback(null);
  437. }
  438. }).catch(function() { callback(null); });
  439. },
  440. // Cache is now written server-side by listArtists.js before it sends its
  441. // response — no client-side write needed.
  442. _writeArtistsCache(items, updatedAt) {},
  443. _flashArtistsUpdated() {
  444. this._artistsUpdateFlash = true;
  445. if (this._artistsUpdateFlashTimer) clearTimeout(this._artistsUpdateFlashTimer);
  446. const self = this;
  447. this._artistsUpdateFlashTimer = setTimeout(() => {
  448. self._artistsUpdateFlash = false;
  449. }, 3000);
  450. },
  451. artistsStatusText() {
  452. if (this.artistsRefreshing && this.artistsFromCache) {
  453. return 'Showing cached artists while refreshing in background';
  454. }
  455. if (this.artistsFromCache) {
  456. return 'Showing cached artists';
  457. }
  458. if (this.artistsRefreshing) {
  459. return 'Refreshing artist list';
  460. }
  461. if (this._artistsUpdateFlash) {
  462. return 'Artist list updated';
  463. }
  464. return 'Live artist list';
  465. },
  466. artistsUpdatedTimeText() {
  467. if (!this.artistsCacheUpdatedAt) return '';
  468. var d = new Date(this.artistsCacheUpdatedAt);
  469. return 'Updated at ' + d.toLocaleTimeString([], {
  470. hour: '2-digit',
  471. minute: '2-digit',
  472. timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
  473. timeZoneName: 'short'
  474. });
  475. },
  476. _getSelectedArtistListContainer() {
  477. return document.getElementById('artist-selected-content-body');
  478. },
  479. _getArtistListContainer() {
  480. return document.getElementById('artist-content-body');
  481. },
  482. _getMainContentContainer() {
  483. return document.getElementById('mainContent');
  484. },
  485. _getArtistViewportHeight() {
  486. var artistListContainer = this._getArtistListContainer();
  487. if (artistListContainer && artistListContainer.clientHeight) {
  488. return artistListContainer.clientHeight;
  489. }
  490. var mainContainer = this._getMainContentContainer();
  491. if (mainContainer && mainContainer.clientHeight) {
  492. return mainContainer.clientHeight;
  493. }
  494. return window.innerHeight;
  495. },
  496. selectArtist(artist) {
  497. var mainContainer = this._getMainContentContainer();
  498. if (mainContainer) {
  499. this.artistListScrollTop = mainContainer.scrollTop;
  500. this.artistScrollTop = mainContainer.scrollTop;
  501. }
  502. this.selectedArtist = artist;
  503. this.artistDetailOpen = true;
  504. this.$nextTick(() => {
  505. this.$nextTick(() => {
  506. var mainContainer = this._getMainContentContainer();
  507. if (mainContainer) {
  508. mainContainer.scrollTop = 0;
  509. };
  510. });
  511. });
  512. },
  513. backToArtistList() {
  514. this.artistDetailOpen = false;
  515. var targetScrollTop = this.artistListScrollTop || 0;
  516. this.artistScrollTop = targetScrollTop;
  517. this.$nextTick(() => {
  518. this.$nextTick(() => {
  519. var mainContainer = this._getMainContentContainer();
  520. if (mainContainer) {
  521. mainContainer.scrollTop = targetScrollTop;
  522. }
  523. });
  524. });
  525. },
  526. visibleArtists() {
  527. const viewportHeight = this._getArtistViewportHeight();
  528. const start =
  529. Math.max(
  530. 0,
  531. Math.floor(this.artistScrollTop / this.artistRowHeight)
  532. - this.artistOverscan
  533. );
  534. const count =
  535. Math.ceil(viewportHeight / this.artistRowHeight)
  536. + (this.artistOverscan * 2);
  537. return this.artists.slice(start, start + count);
  538. },
  539. artistStartIndex() {
  540. return Math.max(
  541. 0,
  542. Math.floor(this.artistScrollTop / this.artistRowHeight)
  543. - this.artistOverscan
  544. );
  545. },
  546. artistTopSpacerHeight() {
  547. return this.artistStartIndex() * this.artistRowHeight;
  548. },
  549. artistBottomSpacerHeight() {
  550. const rendered =
  551. this.visibleArtists().length;
  552. return Math.max(
  553. 0,
  554. (this.artists.length -
  555. this.artistStartIndex() -
  556. rendered) * this.artistRowHeight
  557. );
  558. },
  559. onArtistScroll(e) {
  560. var eventScrollTop = e && e.target ? e.target.scrollTop : 0;
  561. var artistListContainer = this._getArtistListContainer();
  562. var mainContainer = this._getMainContentContainer();
  563. var scrollTop = Math.max(
  564. eventScrollTop,
  565. artistListContainer ? artistListContainer.scrollTop : 0,
  566. mainContainer ? mainContainer.scrollTop : 0
  567. );
  568. this.artistScrollTop = scrollTop;
  569. this.artistListScrollTop = scrollTop;
  570. },
  571. onMainContentScroll(e) {
  572. if (this.view !== 'artists' || this.artistDetailOpen) return;
  573. this.onArtistScroll(e);
  574. },
  575. onSelectedArtistListScroll(e) {
  576. this.selectedArtistListScrollTop = e.target.scrollTop;
  577. },
  578. // ════════════════════════════════════════════════════════════════════
  579. // RECENT
  580. // ════════════════════════════════════════════════════════════════════
  581. _loadRecent() {
  582. this.loading = true;
  583. this.loadingMsg = 'Loading recent tracks…';
  584. const self = this;
  585. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/listRecent.js', {
  586. method: 'POST', cache: 'no-cache',
  587. headers: { 'Content-Type': 'application/json' },
  588. body: JSON.stringify({})
  589. }).then(r => r.json()).then(data => {
  590. self.recentSongs = data;
  591. self.loading = false;
  592. }).catch(() => { self.loading = false; });
  593. },
  594. // ════════════════════════════════════════════════════════════════════
  595. // PLAYLISTS
  596. // ════════════════════════════════════════════════════════════════════
  597. _loadPlaylists() {
  598. const self = this;
  599. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/playlist.js', {
  600. method: 'POST', cache: 'no-cache',
  601. headers: { 'Content-Type': 'application/json' },
  602. body: JSON.stringify({ opr: 'list_all' })
  603. }).then(r => r.json()).then(data => {
  604. self.playlists = Array.isArray(data) ? data : [];
  605. }).catch(() => {});
  606. },
  607. _loadPlaylistSongs(name) {
  608. this.loading = true;
  609. this.loadingMsg = 'Loading playlist…';
  610. const self = this;
  611. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/playlist.js', {
  612. method: 'POST', cache: 'no-cache',
  613. headers: { 'Content-Type': 'application/json' },
  614. body: JSON.stringify({ opr: 'get', name: name })
  615. }).then(r => r.json()).then(data => {
  616. self.currentPlaylistSongs = Array.isArray(data) ? data : [];
  617. self.loading = false;
  618. }).catch(() => { self.loading = false; });
  619. },
  620. createPlaylist() {
  621. var n = this.newPlaylistName.trim();
  622. if (!n) return;
  623. const self = this;
  624. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/playlist.js', {
  625. method: 'POST', cache: 'no-cache',
  626. headers: { 'Content-Type': 'application/json' },
  627. body: JSON.stringify({ opr: 'create', name: n })
  628. }).then(r => r.json()).then(data => {
  629. if (data.error) { self._showToast(data.error, 'error'); return; }
  630. self.newPlaylistName = '';
  631. self.showNewPlaylistModal = false;
  632. self._loadPlaylists();
  633. self._showToast('Playlist "' + n + '" created');
  634. });
  635. },
  636. deletePlaylist(name) {
  637. if (!confirm('Delete playlist "' + name + '"?')) return;
  638. const self = this;
  639. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/playlist.js', {
  640. method: 'POST', cache: 'no-cache',
  641. headers: { 'Content-Type': 'application/json' },
  642. body: JSON.stringify({ opr: 'delete', name: name })
  643. }).then(() => {
  644. if (self.currentPlaylistName === name) { self.currentPlaylistName = null; self.view = 'home'; }
  645. self._loadPlaylists();
  646. self._showToast('Playlist deleted');
  647. });
  648. },
  649. promptAddToPlaylist(song, event) {
  650. if (event) event.stopPropagation();
  651. this.addToPlaylistSong = song;
  652. this.showAddToPlaylistModal = true;
  653. },
  654. addSongToPlaylist(playlistName) {
  655. if (!this.addToPlaylistSong) return;
  656. const self = this;
  657. const song = this.addToPlaylistSong;
  658. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/playlist.js', {
  659. method: 'POST', cache: 'no-cache',
  660. headers: { 'Content-Type': 'application/json' },
  661. body: JSON.stringify({ opr: 'add', name: playlistName, song: encodeURIComponent(song.filepath) })
  662. }).then(r => r.json()).then(data => {
  663. self.showAddToPlaylistModal = false;
  664. self.addToPlaylistSong = null;
  665. if (data.error) { self._showToast(data.error, 'error'); return; }
  666. if (data.duplicate) { self._showToast('Already in playlist'); return; }
  667. self._showToast('Added to "' + playlistName + '"');
  668. self._loadPlaylists();
  669. if (self.currentPlaylistName === playlistName) self._loadPlaylistSongs(playlistName);
  670. });
  671. },
  672. removeFromCurrentPlaylist(index, event) {
  673. if (event) event.stopPropagation();
  674. const self = this;
  675. fetch(ao_root + 'system/ajgi/interface?script=Musicify/backend/playlist.js', {
  676. method: 'POST', cache: 'no-cache',
  677. headers: { 'Content-Type': 'application/json' },
  678. body: JSON.stringify({ opr: 'remove', name: self.currentPlaylistName, index: index })
  679. }).then(() => {
  680. self._loadPlaylistSongs(self.currentPlaylistName);
  681. self._loadPlaylists();
  682. });
  683. },
  684. // ════════════════════════════════════════════════════════════════════
  685. // SEARCH
  686. // ════════════════════════════════════════════════════════════════════
  687. doSearch() {
  688. var q = this.searchQuery.toLowerCase().trim();
  689. if (!q) { this.searchResults = []; return; }
  690. // Search across already-loaded data pools
  691. var results = [];
  692. var seen = {};
  693. function addIfNew(song) {
  694. if (!seen[song.filepath]) {
  695. seen[song.filepath] = true;
  696. results.push(song);
  697. }
  698. }
  699. // Folder contents
  700. (this.folderContents.songs || []).forEach(s => { if (s.name.toLowerCase().includes(q)) addIfNew(s); });
  701. // Recent
  702. (this.recentSongs || []).forEach(s => { if (s.name.toLowerCase().includes(q)) addIfNew(s); });
  703. // Artists
  704. (this.artists || []).forEach(a => {
  705. (a.songs || []).forEach(s => { if (s.name.toLowerCase().includes(q) || a.name.toLowerCase().includes(q)) addIfNew(s); });
  706. });
  707. // Current playlist
  708. (this.currentPlaylistSongs || []).forEach(s => { if (s.name.toLowerCase().includes(q)) addIfNew(s); });
  709. // Recently played
  710. (this.recentlyPlayed || []).forEach(s => { if (s.name.toLowerCase().includes(q)) addIfNew(s); });
  711. this.searchResults = results.slice(0, 100);
  712. },
  713. // ════════════════════════════════════════════════════════════════════
  714. // PLAYER – Queue management
  715. // ════════════════════════════════════════════════════════════════════
  716. playList(songs, startIndex) {
  717. if (!songs || songs.length === 0) return;
  718. startIndex = startIndex || 0;
  719. this.queue = songs.slice();
  720. this.queueIndex = startIndex;
  721. if (this.shuffle) this._buildShuffledQueue(startIndex);
  722. this._loadTrack(this._effectiveQueue()[this._effectiveIndex(startIndex)]);
  723. },
  724. playSong(song, sourceList, event) {
  725. if (event) event.stopPropagation();
  726. if (!sourceList || sourceList.length === 0) sourceList = [song];
  727. var idx = 0;
  728. for (var i = 0; i < sourceList.length; i++) {
  729. if (sourceList[i].filepath === song.filepath) { idx = i; break; }
  730. }
  731. this.playList(sourceList, idx);
  732. },
  733. addToQueue(song, event) {
  734. if (event) event.stopPropagation();
  735. this.queue.push(song);
  736. if (this.shuffle) this.shuffledQueue.push(song);
  737. this._showToast('Added to queue');
  738. },
  739. playNext(song, event) {
  740. if (event) event.stopPropagation();
  741. var insertAt = this.queueIndex + 1;
  742. this.queue.splice(insertAt, 0, song);
  743. if (this.shuffle) this.shuffledQueue.splice(this._effectiveIndex(this.queueIndex) + 1, 0, song);
  744. this._showToast('Playing next');
  745. },
  746. removeFromQueue(index, event) {
  747. if (event) event.stopPropagation();
  748. if (index === this.queueIndex) return; // can't remove currently playing
  749. this.queue.splice(index, 1);
  750. if (index < this.queueIndex) this.queueIndex--;
  751. },
  752. _effectiveQueue() { return this.shuffle ? this.shuffledQueue : this.queue; },
  753. _effectiveIndex(rawIndex) {
  754. if (!this.shuffle) return rawIndex;
  755. var track = this.queue[rawIndex];
  756. if (!track) return 0;
  757. for (var i = 0; i < this.shuffledQueue.length; i++) {
  758. if (this.shuffledQueue[i].filepath === track.filepath) return i;
  759. }
  760. return 0;
  761. },
  762. _buildShuffledQueue(currentIndex) {
  763. var arr = this.queue.slice();
  764. var current = arr.splice(currentIndex, 1)[0];
  765. for (var i = arr.length - 1; i > 0; i--) {
  766. var j = Math.floor(Math.random() * (i + 1));
  767. var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
  768. }
  769. this.shuffledQueue = current ? [current].concat(arr) : arr;
  770. },
  771. // ════════════════════════════════════════════════════════════════════
  772. // PLAYER – Playback control
  773. // ════════════════════════════════════════════════════════════════════
  774. _loadTrack(song) {
  775. if (!song) return;
  776. this._suppressEnded = true;
  777. this.currentTrack = song;
  778. this.coverError = false;
  779. this.currentTime = 0;
  780. this.duration = 0;
  781. this._transcodeSeekOffset = 0;
  782. this._currentTrackTranscoded = false;
  783. if (this.castMode) {
  784. this._castSend('media.load', {
  785. filepath: song.filepath,
  786. name: song.name,
  787. artist: this.getArtistLabel(song),
  788. cover: song.cover || '',
  789. type: 'audio'
  790. });
  791. this._audio.pause();
  792. this.isPlaying = true;
  793. } else {
  794. this._currentTrackTranscoded = (this.transcodeMode !== 'disabled' && this._needsTranscode(song));
  795. this._audio.src = this._getAudioSrc(song);
  796. this._audio.load();
  797. this._audio.play().catch(() => {});
  798. if (this._currentTrackTranscoded) {
  799. var _prefetchSong = song;
  800. fetch(ao_root + 'media/duration/?file=' + encodeURIComponent(song.filepath))
  801. .then(r => r.json())
  802. .then(data => {
  803. if (data.duration > 0 && this.currentTrack && this.currentTrack.filepath === _prefetchSong.filepath) {
  804. this.duration = data.duration;
  805. }
  806. }).catch(() => {});
  807. }
  808. }
  809. this._saveRecentlyPlayed(song);
  810. this._setupMediaSession();
  811. document.title = song.name + ' – Musicify';
  812. if (ao_module_virtualDesktop){
  813. ao_module_setWindowTitle('Musicify - ' + song.name);
  814. }
  815. this.trackInfoSong = song;
  816. },
  817. togglePlay() {
  818. if (!this.currentTrack) return;
  819. if (this.castMode) {
  820. if (this.isPlaying) {
  821. this._castSend('media.pause', {});
  822. this.isPlaying = false;
  823. } else {
  824. this._castSend('media.play', {});
  825. this.isPlaying = true;
  826. }
  827. return;
  828. }
  829. if (this._audio.paused) { this._audio.play().catch(() => {}); }
  830. else { this._audio.pause(); }
  831. },
  832. nextTrack() {
  833. var eq = this._effectiveQueue();
  834. var ei = this._effectiveIndex(this.queueIndex);
  835. if (eq.length === 0) return;
  836. var next = ei + 1;
  837. if (next >= eq.length) {
  838. if (this.repeat === 'all') next = 0;
  839. else { this._audio.pause(); this.isPlaying = false; return; }
  840. }
  841. // Map back to queue index for shuffle mode
  842. if (this.shuffle) {
  843. var nextSong = this.shuffledQueue[next];
  844. for (var i = 0; i < this.queue.length; i++) {
  845. if (this.queue[i].filepath === nextSong.filepath) { this.queueIndex = i; break; }
  846. }
  847. } else {
  848. this.queueIndex = next;
  849. }
  850. this._loadTrack(eq[next]);
  851. },
  852. prevTrack() {
  853. if (this.currentTime > 3) { this._audio.currentTime = 0; return; }
  854. var eq = this._effectiveQueue();
  855. var ei = this._effectiveIndex(this.queueIndex);
  856. var prev = ei - 1;
  857. if (prev < 0) { prev = this.repeat === 'all' ? eq.length - 1 : 0; }
  858. if (this.shuffle) {
  859. var prevSong = this.shuffledQueue[prev];
  860. for (var i = 0; i < this.queue.length; i++) {
  861. if (this.queue[i].filepath === prevSong.filepath) { this.queueIndex = i; break; }
  862. }
  863. } else {
  864. this.queueIndex = prev;
  865. }
  866. this._loadTrack(eq[prev]);
  867. },
  868. seekTo(val) {
  869. val = parseFloat(val);
  870. if (this.castMode) {
  871. this._castSend('media.seek', { time: val });
  872. this.currentTime = val;
  873. return;
  874. }
  875. if (this._currentTrackTranscoded && this.currentTrack) {
  876. // Seek by reloading the transcode stream from the new position
  877. this._transcodeSeekOffset = val;
  878. this.currentTime = val;
  879. this._audio.src = this._getAudioSrc(this.currentTrack, val);
  880. this._audio.load();
  881. this._audio.play().catch(() => {});
  882. return;
  883. }
  884. this._audio.currentTime = val;
  885. this.currentTime = this._audio.currentTime;
  886. },
  887. beginSeek() { this.isSeeking = true; },
  888. endSeek(val) { this.isSeeking = false; this.seekTo(val); },
  889. setVolume(val) {
  890. this.volume = parseInt(val);
  891. this.isMuted = this.volume === 0;
  892. localStorage.setItem('musicify_volume', this.volume);
  893. if (this.castMode) {
  894. this._castSend('media.volume', { volume: this.volume, muted: this.isMuted });
  895. return;
  896. }
  897. this._audio.volume = this.volume / 100;
  898. },
  899. toggleMute() {
  900. this.isMuted = !this.isMuted;
  901. if (this.castMode) {
  902. this._castSend('media.volume', { volume: this.volume, muted: this.isMuted });
  903. return;
  904. }
  905. this._audio.muted = this.isMuted;
  906. },
  907. toggleShuffle() {
  908. this.shuffle = !this.shuffle;
  909. ao_module_storage.setStorage("Musicify", "shuffle", String(this.shuffle));
  910. if (this.shuffle) this._buildShuffledQueue(this.queueIndex);
  911. },
  912. cycleRepeat() {
  913. var modes = ['none', 'all', 'one'];
  914. var idx = modes.indexOf(this.repeat);
  915. this.repeat = modes[(idx + 1) % modes.length];
  916. ao_module_storage.setStorage("Musicify", "repeat", this.repeat);
  917. if (this.castMode) {
  918. this._castSend('media.repeat', { mode: this.repeat });
  919. }
  920. },
  921. // ════════════════════════════════════════════════════════════════════
  922. // TRANSCODE HELPERS
  923. // ════════════════════════════════════════════════════════════════════
  924. _needsTranscode(song) {
  925. if (!song || !song.ext) return false;
  926. var nonNative = ['flac', 'ogg', 'wma', 'webm', 'opus'];
  927. return nonNative.indexOf(song.ext.toLowerCase()) !== -1;
  928. },
  929. // Returns the playback URL for a song, using the transcode endpoint when needed.
  930. // startTime (seconds) is only appended when seeking a transcoded stream.
  931. _getAudioSrc(song, startTime) {
  932. if (!song) return '';
  933. if (this.transcodeMode !== 'disabled' && this._needsTranscode(song)) {
  934. var url = ao_root + 'media/transcode/audio/?file=' + encodeURIComponent(song.filepath) +
  935. '&samplerate=' + this.transcodeMode + '000';
  936. if (startTime && startTime > 0.001) url += '&start=' + parseFloat(startTime).toFixed(3);
  937. return url;
  938. }
  939. return ao_root + 'media?file=' + encodeURIComponent(song.filepath);
  940. },
  941. saveTranscodeMode() {
  942. localStorage.setItem('musicify_transcodeMode', this.transcodeMode);
  943. // If a non-native track is currently loaded, reload it immediately at the
  944. // current position so seeks work correctly under the new mode.
  945. if (this.currentTrack && this._needsTranscode(this.currentTrack) && !this.castMode) {
  946. var resumeAt = this.currentTime; // already includes _transcodeSeekOffset
  947. var wasPlaying = this.isPlaying;
  948. var willTranscode = (this.transcodeMode !== 'disabled');
  949. this._suppressEnded = true;
  950. this._transcodeSeekOffset = 0;
  951. this._currentTrackTranscoded = willTranscode;
  952. this.duration = 0;
  953. if (willTranscode && resumeAt > 0.001) {
  954. // Transcoded seek: bake the position into the stream URL
  955. this._transcodeSeekOffset = resumeAt;
  956. this._audio.src = this._getAudioSrc(this.currentTrack, resumeAt);
  957. } else {
  958. this._audio.src = this._getAudioSrc(this.currentTrack);
  959. }
  960. this._audio.load();
  961. if (willTranscode) {
  962. // Re-fetch duration for the transcoded stream
  963. var _song = this.currentTrack;
  964. fetch(ao_root + 'media/duration/?file=' + encodeURIComponent(_song.filepath))
  965. .then(r => r.json())
  966. .then(data => {
  967. if (data.duration > 0 && this.currentTrack && this.currentTrack.filepath === _song.filepath) {
  968. this.duration = data.duration;
  969. }
  970. }).catch(() => {});
  971. } else if (resumeAt > 0) {
  972. // Native audio: seek to position after metadata is ready
  973. var self = this;
  974. this._audio.addEventListener('loadedmetadata', function() {
  975. self._audio.currentTime = resumeAt;
  976. }, { once: true });
  977. }
  978. if (wasPlaying) {
  979. this._audio.play().catch(() => {});
  980. }
  981. }
  982. this._showToast('Transcode: ' + (this.transcodeMode === 'disabled' ? 'disabled' : this.transcodeMode + ' kHz'));
  983. },
  984. _onEnded() {
  985. if (this._suppressEnded) return;
  986. if (this.repeat === 'one') {
  987. if (this.castMode) {
  988. this._castSend('media.seek', { time: 0 });
  989. this._castSend('media.play', {});
  990. } else {
  991. this._audio.currentTime = 0;
  992. this._audio.play().catch(() => {});
  993. }
  994. return;
  995. }
  996. this.nextTrack();
  997. },
  998. _onError() {
  999. this._showToast('Playback error – skipping', 'error');
  1000. setTimeout(() => { this.nextTrack(); }, 1500);
  1001. },
  1002. isCurrentTrack(song) {
  1003. return this.currentTrack && this.currentTrack.filepath === song.filepath;
  1004. },
  1005. isCurrentQueueItem(index) {
  1006. if (!this.shuffle) return index === this.queueIndex;
  1007. var eq = this._effectiveQueue();
  1008. var current = eq[this._effectiveIndex(this.queueIndex)];
  1009. return current && this.queue[index].filepath === current.filepath;
  1010. },
  1011. // ════════════════════════════════════════════════════════════════════
  1012. // SLEEP TIMER
  1013. // ════════════════════════════════════════════════════════════════════
  1014. startSleepTimer() {
  1015. this.cancelSleepTimer();
  1016. this._sleepEnd = Date.now() + this.sleepMinutes * 60000;
  1017. this.sleepActive = true;
  1018. this.showSleepModal = false;
  1019. const self = this;
  1020. this._sleepTimer = setInterval(() => {
  1021. var rem = self._sleepEnd - Date.now();
  1022. if (rem <= 0) {
  1023. self._fadeOutAndPause();
  1024. self.cancelSleepTimer();
  1025. } else {
  1026. var m = Math.floor(rem / 60000);
  1027. var s = Math.floor((rem % 60000) / 1000);
  1028. self.sleepCountdown = m + ':' + String(s).padStart(2, '0');
  1029. }
  1030. }, 1000);
  1031. this._showToast('Sleep timer set for ' + this.sleepMinutes + ' min');
  1032. },
  1033. cancelSleepTimer() {
  1034. if (this._sleepTimer) clearInterval(this._sleepTimer);
  1035. this._sleepTimer = null;
  1036. this.sleepActive = false;
  1037. this.sleepCountdown = '';
  1038. },
  1039. _fadeOutAndPause() {
  1040. const audio = this._audio;
  1041. const originalVol = audio.volume;
  1042. const self = this;
  1043. var fadeInterval = setInterval(() => {
  1044. if (audio.volume > 0.05) {
  1045. audio.volume = Math.max(0, audio.volume - 0.04);
  1046. } else {
  1047. audio.volume = 0;
  1048. audio.pause();
  1049. audio.volume = originalVol;
  1050. self.isPlaying = false;
  1051. clearInterval(fadeInterval);
  1052. self._showToast('Sleep timer: music stopped');
  1053. }
  1054. }, 150);
  1055. },
  1056. // ════════════════════════════════════════════════════════════════════
  1057. // MEDIA SESSION API
  1058. // ════════════════════════════════════════════════════════════════════
  1059. _setupMediaSession() {
  1060. if (!('mediaSession' in navigator) || !this.currentTrack) return;
  1061. const self = this;
  1062. navigator.mediaSession.metadata = new MediaMetadata({
  1063. title: this.currentTrack.name,
  1064. artist: this._getArtistName(this.currentTrack),
  1065. album: '',
  1066. artwork: [{ src: this.getCoverUrl(this.currentTrack), sizes: '512x512', type: 'image/jpeg' }]
  1067. });
  1068. navigator.mediaSession.setActionHandler('play', () => self._audio.play());
  1069. navigator.mediaSession.setActionHandler('pause', () => self._audio.pause());
  1070. navigator.mediaSession.setActionHandler('previoustrack', () => self.prevTrack());
  1071. navigator.mediaSession.setActionHandler('nexttrack', () => self.nextTrack());
  1072. navigator.mediaSession.setActionHandler('seekto', details => {
  1073. self._audio.currentTime = details.seekTime;
  1074. });
  1075. },
  1076. _updateMediaSession() {
  1077. if (!('mediaSession' in navigator)) return;
  1078. navigator.mediaSession.playbackState = this.isPlaying ? 'playing' : 'paused';
  1079. if (this.duration > 0) {
  1080. try {
  1081. navigator.mediaSession.setPositionState({
  1082. duration: this.duration,
  1083. playbackRate: 1,
  1084. position: Math.min(this.currentTime, this.duration)
  1085. });
  1086. } catch(e) {}
  1087. }
  1088. },
  1089. // ════════════════════════════════════════════════════════════════════
  1090. // RECENTLY PLAYED (server-side, cross-device)
  1091. // ════════════════════════════════════════════════════════════════════
  1092. _saveRecentlyPlayed(song) {
  1093. var list = this.recentlyPlayed.filter(s => s.filepath !== song.filepath);
  1094. list.unshift(song);
  1095. list = list.slice(0, 12);
  1096. this.recentlyPlayed = list;
  1097. ao_module_storage.setStorage("Musicify", "recent", JSON.stringify(list));
  1098. },
  1099. // ════════════════════════════════════════════════════════════════════
  1100. // HELPERS
  1101. // ════════════════════════════════════════════════════════════════════
  1102. formatTime(s) {
  1103. if (!s || isNaN(s)) return '0:00';
  1104. s = Math.floor(s);
  1105. return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
  1106. },
  1107. getCoverUrl(song) {
  1108. if (!song) return 'img/placeholder.png';
  1109. return ao_root + 'system/file_system/loadThumbnail?bytes=true&vpath=' + encodeURIComponent(song.filepath);
  1110. },
  1111. handleCoverError(event) {
  1112. event.target.src = 'img/placeholder.png';
  1113. event.target.onerror = null;
  1114. },
  1115. _getArtistName(song) {
  1116. if (!song) return '';
  1117. var parts = song.filepath.split('/');
  1118. // /user:/Music/ArtistName/... → index 2
  1119. if (parts.length >= 3) return parts[parts.length - 2];
  1120. return '';
  1121. },
  1122. getArtistLabel(song) {
  1123. return this._getArtistName(song) || '';
  1124. },
  1125. progressPercent() {
  1126. if (!this.duration) return 0;
  1127. return (this.currentTime / this.duration) * 100;
  1128. },
  1129. volumeIcon() {
  1130. if (this.isMuted || this.volume === 0) return 'volume off';
  1131. if (this.volume < 40) return 'volume down';
  1132. return 'volume up';
  1133. },
  1134. repeatIcon() {
  1135. if (this.repeat === 'one') return 'repeat';
  1136. return 'redo alternate';
  1137. },
  1138. repeatTitle() {
  1139. if (this.repeat === 'none') return 'Repeat: off';
  1140. if (this.repeat === 'all') return 'Repeat: all';
  1141. return 'Repeat: one';
  1142. },
  1143. // ════════════════════════════════════════════════════════════════════
  1144. // TRACK INFO PANEL
  1145. // ════════════════════════════════════════════════════════════════════
  1146. openTrackInfo(song, event) {
  1147. if (event) event.stopPropagation();
  1148. if (!song) return;
  1149. var mc = document.getElementById('mainContent');
  1150. // Pin overlay to the current visible top before Alpine shows it
  1151. var overlay = mc ? mc.querySelector('.track-info-overlay') : null;
  1152. if (overlay) overlay.style.top = (mc.scrollTop) + 'px';
  1153. if (mc) mc.style.overflow = 'hidden';
  1154. this.trackInfoSong = song;
  1155. this.showTrackInfo = true;
  1156. if (!ao_module_virtualDesktop){
  1157. // Not in webdesktop mode, so "Open in Embedded Player" option doesn't make sense – hide it
  1158. $("#open-in-embedded").hide();
  1159. }else{
  1160. $("#open-in-embedded").show();
  1161. }
  1162. },
  1163. closeTrackInfo() {
  1164. this.showTrackInfo = false;
  1165. this.trackInfoSong = null;
  1166. var mc = document.getElementById('mainContent');
  1167. if (mc) mc.style.overflow = '';
  1168. },
  1169. copyTrackTitle(song) {
  1170. if (!song) return;
  1171. var text = song.name;
  1172. if (navigator.clipboard) {
  1173. navigator.clipboard.writeText(text)
  1174. .then(() => { this._showToast('Title copied!'); })
  1175. .catch(() => { this._showToast('Failed to copy', 'error'); });
  1176. } else {
  1177. var el = document.createElement('textarea');
  1178. el.value = text;
  1179. document.body.appendChild(el);
  1180. el.select();
  1181. document.execCommand('copy');
  1182. document.body.removeChild(el);
  1183. this._showToast('Title copied!');
  1184. }
  1185. },
  1186. openInFileManager(song) {
  1187. if (!song) return;
  1188. var parts = song.filepath.split('/');
  1189. var filename = parts.pop();
  1190. var folder = parts.join('/');
  1191. ao_module_openPath(folder, filename);
  1192. },
  1193. openInEmbedded(song) {
  1194. if (!song) return;
  1195. var fileList = [{
  1196. filename: song.name + (song.ext ? '.' + song.ext : ''),
  1197. filepath: song.filepath
  1198. }];
  1199. ao_module_newfw({
  1200. url: 'Musicify/embedded.html#' + encodeURIComponent(JSON.stringify(fileList)),
  1201. title: song.name,
  1202. appicon: 'Musicify/img/module_icon.png',
  1203. width: 360,
  1204. height: 254
  1205. });
  1206. },
  1207. searchOnYoutube(song) {
  1208. if (!song) return;
  1209. var q = encodeURIComponent(song.name + ' ' + this.getArtistLabel(song));
  1210. window.open('https://www.youtube.com/results?search_query=' + q, '_blank');
  1211. },
  1212. downloadSong(song) {
  1213. if (!song) return;
  1214. var a = document.createElement('a');
  1215. a.href = ao_root + 'media?file=' + encodeURIComponent(song.filepath);
  1216. a.download = song.name + (song.ext ? '.' + song.ext : '');
  1217. document.body.appendChild(a);
  1218. a.click();
  1219. document.body.removeChild(a);
  1220. },
  1221. getTrackFolder(song) {
  1222. if (!song) return '';
  1223. var parts = song.filepath.split('/');
  1224. parts.pop();
  1225. return parts.join('/');
  1226. },
  1227. // ════════════════════════════════════════════════════════════════════
  1228. // AROZCAST
  1229. // ════════════════════════════════════════════════════════════════════
  1230. connectToCast() {
  1231. var code = this.castCodeInput.trim();
  1232. if (!/^\d{4}$/.test(code)) {
  1233. this.castError = 'Enter a valid 4-digit code.';
  1234. return;
  1235. }
  1236. this.castError = '';
  1237. this.castConnecting = true;
  1238. var self = this;
  1239. fetch(ao_root + 'api/arozcast/ping?code=' + code)
  1240. .then(function(r) { return r.json(); })
  1241. .then(function(data) {
  1242. if (!data.exists) {
  1243. self.castConnecting = false;
  1244. self.castError = 'Room not found. Check the code and try again.';
  1245. return;
  1246. }
  1247. self._castOpen(code);
  1248. })
  1249. .catch(function() {
  1250. self.castConnecting = false;
  1251. self.castError = 'Connection failed. Is Arozcast running?';
  1252. });
  1253. },
  1254. _castOpen(code) {
  1255. var self = this;
  1256. // Cancel any pending auto-reconnect to the old room — user is opening a new session
  1257. clearTimeout(this._castReconnectTimer); this._castReconnectTimer = null;
  1258. this._castReconnectCount = 0; this._castPendingCode = null;
  1259. var wsUrl = new URL(ao_root + 'api/arozcast/ws?code=' + code, window.location.href);
  1260. wsUrl.protocol = (location.protocol === 'https:') ? 'wss:' : 'ws:';
  1261. var ws = new WebSocket(wsUrl.toString());
  1262. ws.onopen = function() {
  1263. self.castConnecting = false;
  1264. self.castConnected = true;
  1265. self.castMode = true;
  1266. self.castCode = code;
  1267. self._castWs = ws;
  1268. self.showCastModal = false;
  1269. self.castCodeInput = '';
  1270. self._castLastSeen = Date.now();
  1271. // Pause local audio; remote screen takes over
  1272. self._audio.pause();
  1273. // Announce presence; sync volume first so _loadMedia reads the right level
  1274. ws.send(JSON.stringify({ topic: 'peer.hello', payload: {} }));
  1275. self._castSend('media.volume', { volume: self.volume, muted: self.isMuted });
  1276. if (self.currentTrack) {
  1277. self._castSend('media.load', {
  1278. filepath: self.currentTrack.filepath,
  1279. name: self.currentTrack.name,
  1280. artist: self.getArtistLabel(self.currentTrack),
  1281. cover: self.currentTrack.cover || '',
  1282. type: 'audio',
  1283. startTime: self.currentTime // sync mid-playback position
  1284. });
  1285. // Explicitly mirror play/pause state rather than relying on autoplay
  1286. if (self.isPlaying) {
  1287. self._castSend('media.play', {});
  1288. } else {
  1289. self._castSend('media.pause', {});
  1290. }
  1291. self._castSend('media.repeat', { mode: self.repeat });
  1292. }
  1293. // Heartbeat: tell Arozcast we are still here every 5 s
  1294. self._castPingTimer = setInterval(function() {
  1295. self._castSend('peer.heartbeat', {});
  1296. }, 5000);
  1297. // Watchdog: if Arozcast stops sending for 12 s, force-close the WS
  1298. self._castWatchTimer = setInterval(function() {
  1299. if (Date.now() - self._castLastSeen > 12000) {
  1300. if (self._castWs) self._castWs.close();
  1301. }
  1302. }, 4000);
  1303. self._showToast('Connected to Arozcast');
  1304. };
  1305. ws.onclose = function() {
  1306. clearInterval(self._castPingTimer);
  1307. clearInterval(self._castWatchTimer);
  1308. self._castPingTimer = null;
  1309. self._castWatchTimer = null;
  1310. var wasActive = self.castMode;
  1311. var savedCode = self.castCode;
  1312. self.castConnected = false;
  1313. self.castMode = false;
  1314. self._castWs = null;
  1315. if (wasActive) { self._startCastReconnect(savedCode); }
  1316. };
  1317. ws.onerror = function() {
  1318. self.castConnecting = false;
  1319. self.castError = 'WebSocket error. Check your connection.';
  1320. };
  1321. ws.onmessage = function(evt) {
  1322. self._castLastSeen = Date.now();
  1323. try {
  1324. var msg = JSON.parse(evt.data);
  1325. if (msg.topic === 'status.update') {
  1326. if (!self.isSeeking) self.currentTime = msg.payload.currentTime || 0;
  1327. self.duration = msg.payload.duration || 0;
  1328. self.isPlaying = msg.payload.isPlaying || false;
  1329. }
  1330. } catch(e) {}
  1331. };
  1332. },
  1333. // ── Auto-reconnect helpers ────────────────────────────────────────────
  1334. _startCastReconnect(code) {
  1335. var self = this;
  1336. var DELAYS = [2000, 5000, 12000];
  1337. if (!code || this._castReconnectCount >= DELAYS.length) {
  1338. if (this._castReconnectCount > 0) {
  1339. // All retries exhausted — fall back to local playback
  1340. if (this.currentTrack) {
  1341. var resumeAt = this.currentTime;
  1342. var self = this;
  1343. this._currentTrackTranscoded = (this.transcodeMode !== 'disabled' && this._needsTranscode(this.currentTrack));
  1344. this._transcodeSeekOffset = 0;
  1345. if (this._currentTrackTranscoded && resumeAt > 0.001) {
  1346. this._transcodeSeekOffset = resumeAt;
  1347. this._audio.src = this._getAudioSrc(this.currentTrack, resumeAt);
  1348. } else {
  1349. this._audio.src = this._getAudioSrc(this.currentTrack);
  1350. }
  1351. this._audio.volume = this.volume / 100;
  1352. this._audio.muted = this.isMuted;
  1353. this._audio.load();
  1354. if (!this._currentTrackTranscoded && resumeAt > 0) {
  1355. this._audio.addEventListener('loadedmetadata', function() {
  1356. self._audio.currentTime = resumeAt;
  1357. }, { once: true });
  1358. }
  1359. this.isPlaying = false;
  1360. this._showToast('Arozcast: reconnect failed — resuming locally', 'error');
  1361. }
  1362. }
  1363. this._castReconnectCount = 0; this._castPendingCode = null;
  1364. return;
  1365. }
  1366. this._castPendingCode = code;
  1367. var delay = DELAYS[this._castReconnectCount++];
  1368. clearTimeout(this._castReconnectTimer);
  1369. this._castReconnectTimer = setTimeout(function() {
  1370. self._castReconnectTimer = null;
  1371. self._attemptCastReconnect();
  1372. }, delay);
  1373. this._showToast('Arozcast disconnected — reconnecting…');
  1374. },
  1375. _attemptCastReconnect() {
  1376. var self = this;
  1377. if (!this._castPendingCode) return;
  1378. var code = this._castPendingCode;
  1379. var wsUrl = new URL(ao_root + 'api/arozcast/ws?code=' + code, window.location.href);
  1380. wsUrl.protocol = (location.protocol === 'https:') ? 'wss:' : 'ws:';
  1381. var ws = new WebSocket(wsUrl.toString());
  1382. var openTimer = setTimeout(function() {
  1383. ws.onopen = ws.onclose = ws.onerror = null; ws.close();
  1384. self._startCastReconnect(code);
  1385. }, 8000);
  1386. ws.onopen = function() { clearTimeout(openTimer); self._castPendingCode = null; self._castDidReconnect(ws, code); };
  1387. ws.onerror = function() {};
  1388. ws.onclose = function() { clearTimeout(openTimer); self._startCastReconnect(code); };
  1389. },
  1390. _castDidReconnect(ws, code) {
  1391. var self = this;
  1392. this._castWs = ws;
  1393. this.castCode = code;
  1394. this.castMode = true;
  1395. this.castConnected = true;
  1396. this._castLastSeen = Date.now();
  1397. ws.onmessage = function(evt) {
  1398. self._castLastSeen = Date.now();
  1399. try {
  1400. var msg = JSON.parse(evt.data);
  1401. if (msg.topic === 'status.update') {
  1402. self._castReconnectCount = 0; // receiver confirmed alive — reset retry counter
  1403. if (!self.isSeeking) self.currentTime = msg.payload.currentTime || 0;
  1404. self.duration = msg.payload.duration || 0;
  1405. self.isPlaying = msg.payload.isPlaying || false;
  1406. } else if (msg.topic === 'media.ended') {
  1407. self._onEnded();
  1408. }
  1409. } catch(e) {}
  1410. };
  1411. ws.onclose = function() {
  1412. clearInterval(self._castPingTimer); clearInterval(self._castWatchTimer);
  1413. self._castPingTimer = null; self._castWatchTimer = null;
  1414. var wasActive = self.castMode;
  1415. var savedCode = self.castCode;
  1416. self.castConnected = false; self.castMode = false; self._castWs = null;
  1417. if (wasActive) { self._startCastReconnect(savedCode); }
  1418. };
  1419. // Re-announce presence and sync volume only — do NOT resend media.load.
  1420. // Arozcast kept playing while the phone was asleep; its next status.update
  1421. // will immediately sync currentTime to the live remote position.
  1422. ws.send(JSON.stringify({ topic: 'peer.hello', payload: {} }));
  1423. this._castSend('media.volume', { volume: this.volume, muted: this.isMuted });
  1424. this._castSend('media.repeat', { mode: this.repeat });
  1425. clearInterval(this._castPingTimer); clearInterval(this._castWatchTimer);
  1426. this._castPingTimer = setInterval(function() { self._castSend('peer.heartbeat', {}); }, 5000);
  1427. this._castWatchTimer = setInterval(function() {
  1428. if (Date.now() - self._castLastSeen > 12000 && self._castWs) self._castWs.close();
  1429. }, 4000);
  1430. this._showToast('Arozcast reconnected');
  1431. },
  1432. disconnectCast() {
  1433. // Capture play state before we tear anything down
  1434. var wasPlaying = this.isPlaying;
  1435. // Cancel any pending auto-reconnect before tearing down
  1436. clearTimeout(this._castReconnectTimer); this._castReconnectTimer = null;
  1437. this._castReconnectCount = 0; this._castPendingCode = null;
  1438. clearInterval(this._castPingTimer);
  1439. clearInterval(this._castWatchTimer);
  1440. this._castPingTimer = null;
  1441. this._castWatchTimer = null;
  1442. this.castMode = false;
  1443. this.castConnected = false;
  1444. this.showCastModal = false;
  1445. if (this._castWs) {
  1446. // Send stop so Arozcast halts — this is an explicit user disconnect,
  1447. // not a sleep/drop (those suppress onclose and never reach here).
  1448. this._castSend('media.stop', {});
  1449. this._castWs.onclose = null; // suppress reconnect trigger
  1450. this._castWs.close();
  1451. this._castWs = null;
  1452. }
  1453. this.castCode = '';
  1454. this.castCodeInput = '';
  1455. this.castError = '';
  1456. this.isPlaying = false;
  1457. // Resume local playback at the last known remote position,
  1458. // but only auto-start if the remote was actually playing.
  1459. if (this.currentTrack) {
  1460. var resumeAt = this.currentTime;
  1461. var self = this;
  1462. this._currentTrackTranscoded = (this.transcodeMode !== 'disabled' && this._needsTranscode(this.currentTrack));
  1463. this._transcodeSeekOffset = 0;
  1464. if (this._currentTrackTranscoded && resumeAt > 0.001) {
  1465. this._transcodeSeekOffset = resumeAt;
  1466. this._audio.src = this._getAudioSrc(this.currentTrack, resumeAt);
  1467. } else {
  1468. this._audio.src = this._getAudioSrc(this.currentTrack);
  1469. }
  1470. this._audio.volume = this.volume / 100;
  1471. this._audio.muted = this.isMuted;
  1472. this._audio.load();
  1473. if (!this._currentTrackTranscoded && resumeAt > 0) {
  1474. this._audio.addEventListener('loadedmetadata', function() {
  1475. self._audio.currentTime = resumeAt;
  1476. }, { once: true });
  1477. }
  1478. if (wasPlaying) {
  1479. this._audio.play().catch(function() {});
  1480. }
  1481. }
  1482. this._showToast('Disconnected from Arozcast');
  1483. },
  1484. _castSend(topic, payload) {
  1485. if (!this._castWs || this._castWs.readyState !== WebSocket.OPEN) return;
  1486. this._castWs.send(JSON.stringify({ topic: topic, payload: payload }));
  1487. },
  1488. // Toast notification (simple, injected into DOM)
  1489. _toastTimer: null,
  1490. toastMsg: '',
  1491. toastType: 'info',
  1492. showToast: false,
  1493. _showToast(msg, type) {
  1494. this.toastMsg = msg;
  1495. this.toastType = type || 'info';
  1496. this.showToast = true;
  1497. if (this._toastTimer) clearTimeout(this._toastTimer);
  1498. const self = this;
  1499. this._toastTimer = setTimeout(() => { self.showToast = false; }, 2500);
  1500. }
  1501. };
  1502. }