-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy path__init__.py
More file actions
856 lines (727 loc) · 35.4 KB
/
Copy path__init__.py
File metadata and controls
856 lines (727 loc) · 35.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
# -*- coding: utf-8 -*-
"""
Package for interfacing with the MPD Music Player Daemon
Status information in three topics
1) Player Status: published only on change
This is a subset of the MPD status (and not the full MPD status) ??
- folder
- song
- volume (volume is published only via player status, and not separatly to avoid too many Threads)
- ...
2) Elapsed time: published every 250 ms, unless constant
- elapsed
3) Folder Config: published only on change
This belongs to the folder being played
Publish:
- random, resume, single, loop
On save store this information:
Contains the information for resume functionality of each folder
- random, resume, single, loop
- if resume:
- current song, elapsed
- what is PLAYSTATUS for?
When to save
- on stop
Angstsave:
- on pause (only if box get turned off without proper shutdown - else stop gets implicitly called)
- on status change of random, resume, single, loop (for resume omit current status if currently playing- this has now meaning)
Load checks:
- if resume, but no song, elapsed -> log error and start from the beginning
Status storing:
- Folder config for each folder (see above)
- Information to restart last folder playback, which is:
- last_folder -> folder_on_close
- song, elapsed
- random, resume, single, loop
- if resume is enabled, after start we need to set last_played_folder, such that card swipe is detected as second swipe?!
on the other hand: if resume is enabled, this is also saved to folder.config -> and that is checked by play card
Internal status
- last played folder: Needed to detect second swipe
Saving {'player_status': {'last_played_folder': 'TraumfaengerStarkeLieder', 'CURRENTSONGPOS': '0', 'CURRENTFILENAME': 'TraumfaengerStarkeLieder/01.mp3'},
'audio_folder_status':
{'TraumfaengerStarkeLieder': {'ELAPSED': '1.0', 'CURRENTFILENAME': 'TraumfaengerStarkeLieder/01.mp3', 'CURRENTSONGPOS': '0', 'PLAYSTATUS': 'stop', 'RESUME': 'OFF', 'SHUFFLE': 'OFF', 'LOOP': 'OFF', 'SINGLE': 'OFF'},
'Giraffenaffen': {'ELAPSED': '1.0', 'CURRENTFILENAME': 'TraumfaengerStarkeLieder/01.mp3', 'CURRENTSONGPOS': '0', 'PLAYSTATUS': 'play', 'RESUME': 'OFF', 'SHUFFLE': 'OFF', 'LOOP': 'OFF', 'SINGLE': 'OFF'}}}
References:
https://github.com/Mic92/python-mpd2
https://python-mpd2.readthedocs.io/en/latest/topics/commands.html
https://mpd.readthedocs.io/en/latest/protocol.html
sudo -u mpd speaker-test -t wav -c 2
""" # noqa: E501
# Warum ist "Second Swipe" im Player und nicht im RFID Reader?
# Second swipe ist abhängig vom Player State - nicht vom RFID state.
# Beispiel: RFID triggered Folder1, Web App triggered Folder2, RFID Folder1:
# Dann muss das 2. Mal Folder1 auch als "first swipe" gewertet werden.
# Wenn der RFID das basierend auf IDs macht, kann der nicht unterscheiden und glaubt es ist 2. Swipe.
# Beispiel 2: Jemand hat RFID Reader (oder 1x RFID und 1x Barcode Scanner oder so) angeschlossen. Liest zuerst Karte mit
# Reader 1 und dann mit Reader 2: Reader 2 weiß nicht, was bei Reader 1 passiert ist und denkt es ist 1. swipe.
# Beispiel 3: RFID trigered Folder1, Playlist läuft durch und hat schon gestoppt, dann wird die Karte wieder vorgehalten.
# Dann muss das als 1. Swipe gewertet werden
# Beispiel 4: RFID triggered "Folder1", dann wird Karte "Volume Up" aufgelegt, dann wieder Karte "Folder1": Auch das ist
# aus Sicht ders Playbacks 2nd Swipe
# 2nd Swipe ist keine im Reader festgelegte Funktion extra fur den Player.
#
# In der aktuellen Implementierung weiß der Player (der second "swipe" dekodiert) überhaupt nichts vom RFID.
# Im Prinzip gibt es zwei "Play" Funktionen: (1) play always from start und (2) play with toggle action.
# Die Web App ruft immer (1) auf und die RFID immer (2). Jetzt kann man sogar für einige Karten sagen
# immer (1) - also kein Second Swipe und für andere (2).
# Sollte der Reader das Swcond swipe dekodieren, muss aber der Reader den Status des Player kennen.
# Das ist allerdings ein Problem. In Version 2 ist das nicht aufgefallen,
# weil alles uber File I/Os lief - Thread safe ist das nicht!
#
# Beispiel: Second swipe bei anderen Funktionen, hier: WiFi on/off.
# Was die Karte Action tut ist ein Toggle. Der Toggle hängt vom Wifi State ab, den der RFID Kartenleser nicht kennt.
# Den kann der Leser auch nicht tracken. Der State kann ja auch über die Web App oder Kommandozeile geändert werden.
# Toggle (und 2nd Swipe generell) ist immer vom Status des Zielsystems abhängig und kann damit nur vom Zielsystem geändert
# werden. Bei Wifi also braucht man 3 Funktionen: on / off / toggle. Toggle ist dann first swipe / second swipe
import os
import mpd
import threading
import logging
import time
import functools
from pathlib import Path
from typing import Union, Dict, Any, Optional
import components.player
import jukebox.cfghandler
import jukebox.utils as utils
import jukebox.plugs as plugs
import jukebox.multitimer as multitimer
import jukebox.publishing as publishing
import jukebox.playlistgenerator as playlistgenerator
import misc
from jukebox.NvManager import nv_manager
from .play_content_callback import PlayContentCallbacks, PlayCardState
from .coverart_cache_manager import CoverartCacheManager
from .play_content_handler import PlayContentHandler, PlayContent, PlayContentType
logger = logging.getLogger('jb.PlayerMPD')
cfg = jukebox.cfghandler.get_handler('jukebox')
class MpdLock:
def __init__(self, client: mpd.MPDClient, host: str, port: int):
self._lock = threading.RLock()
self.client = client
self.host = host
self.port = port
def _try_connect(self):
try:
self.client.connect(self.host, self.port)
except mpd.base.ConnectionError:
pass
def __enter__(self):
self._lock.acquire()
self._try_connect()
return self
def __exit__(self, exc_type, exc_value, traceback):
self._lock.release()
def acquire(self, blocking: bool = True, timeout: float = -1) -> bool:
locked = self._lock.acquire(blocking, timeout)
if locked:
self._try_connect()
return locked
def release(self):
self._lock.release()
def locked(self):
return self._lock.locked()
class PlayerMPD:
"""Interface to MPD Music Player Daemon"""
def __init__(self):
self.nvm = nv_manager()
self.mpd_host = cfg.getn('playermpd', 'host')
self.music_player_status = self.nvm.load(cfg.getn('playermpd', 'status_file'))
self.second_swipe_action_dict = {'toggle': self.toggle,
'play': self.play,
'skip': self.next,
'rewind': self.rewind,
'replay': self.replay,
'replay_if_stopped': self.replay_if_stopped}
self.second_swipe_action = None
self.decode_2nd_swipe_option()
self.end_of_playlist_next_action = utils.get_config_action(cfg,
'playermpd',
'end_of_playlist_next_action',
'none',
{'rewind': self.rewind,
'stop': self.stop,
'none': lambda: None},
logger)
self.stopped_prev_action = utils.get_config_action(cfg,
'playermpd',
'stopped_prev_action',
'prev',
{'rewind': self.rewind,
'prev': self._prev_in_stopped_state,
'none': lambda: None},
logger)
self.stopped_next_action = utils.get_config_action(cfg,
'playermpd',
'stopped_next_action',
'next',
{'rewind': self.rewind,
'next': self._next_in_stopped_state,
'none': lambda: None},
logger)
self.mpd_client = mpd.MPDClient()
self.coverart_cache_manager = CoverartCacheManager()
# The timeout refer to the low-level socket time-out
# If these are too short and the response is not fast enough (due to the PI being busy),
# the current MPC command times out. Leave these at blocking calls, since we do not react on a timed out socket
# in any relevant matter anyway
self.mpd_client.timeout = None # network timeout in seconds (floats allowed), default: None
self.mpd_client.idletimeout = None # timeout for fetching the result of the idle command
self.connect()
logger.info(f"Connected to MPD Version: {self.mpd_client.mpd_version}")
self.current_folder_status = {}
if not self.music_player_status:
self.music_player_status['player_status'] = {}
self.music_player_status['audio_folder_status'] = {}
self.music_player_status.save_to_json()
self.current_folder_status = {}
self.music_player_status['player_status']['last_played_folder'] = ''
else:
last_played_folder = self.music_player_status['player_status'].get('last_played_folder')
if last_played_folder:
# current_folder_status is a dict, but last_played_folder a str
self.current_folder_status = self.music_player_status['audio_folder_status'][last_played_folder]
# Restore the playlist status in mpd
# But what about playback position?
self.mpd_client.clear()
# This could fail and cause load fail of entire package:
# self.mpd_client.add(last_played_folder)
logger.info(f"Last Played Folder: {last_played_folder}")
# Clear last folder played, as we actually did not play any folder yet
# Needed for second swipe detection
# TODO: This will loose the last_played_folder information is the box is started and closed with playing anything...
# Change this to last_played_folder and shutdown_state (for restoring)
self.music_player_status['player_status']['last_played_folder'] = ''
self.old_song = None
self.mpd_status = {}
self.mpd_status_poll_interval = 0.25
self.mpd_lock = MpdLock(self.mpd_client, self.mpd_host, 6600)
global play_card_callbacks
play_card_callbacks = PlayContentCallbacks[PlayCardState]('play_card_callbacks', logger, context=self.mpd_lock)
self.play_card_callbacks = play_card_callbacks
self.play_content_handler = PlayContentHandler(self)
self.play_content_handler.set_second_swipe_action(self.second_swipe_action)
self.status_is_closing = False
# self.status_thread = threading.Timer(self.mpd_status_poll_interval, self._mpd_status_poll).start()
self.status_thread = multitimer.GenericEndlessTimerClass('mpd.timer_status',
self.mpd_status_poll_interval, self._mpd_status_poll)
self.status_thread.start()
def exit(self):
logger.debug("Exit routine of playermpd started")
self.status_is_closing = True
self.status_thread.cancel()
self.mpd_client.disconnect()
self.nvm.save_all()
return self.status_thread.timer_thread
def connect(self):
self.mpd_client.connect(self.mpd_host, 6600)
def decode_2nd_swipe_option(self):
cfg_2nd_swipe_action = cfg.setndefault('playermpd', 'second_swipe_action', 'alias', value='none').lower()
if cfg_2nd_swipe_action not in [*self.second_swipe_action_dict.keys(), 'none', 'custom']:
logger.error(f"Config mpd.second_swipe_action must be one of "
f"{[*self.second_swipe_action_dict.keys(), 'none', 'custom']}. Ignore setting.")
if cfg_2nd_swipe_action in self.second_swipe_action_dict.keys():
self.second_swipe_action = self.second_swipe_action_dict[cfg_2nd_swipe_action]
if cfg_2nd_swipe_action == 'custom':
custom_action = utils.decode_rpc_call(cfg.getn('playermpd', 'second_swipe_action', default=None))
self.second_swipe_action = functools.partial(plugs.call_ignore_errors,
custom_action['package'],
custom_action['plugin'],
custom_action['method'],
custom_action['args'],
custom_action['kwargs'])
def mpd_retry_with_mutex(self, mpd_cmd, *args):
"""
This method adds thread saftey for acceses to mpd via a mutex lock,
it shall be used for each access to mpd to ensure thread safety
In case of a communication error the connection will be reestablished and the pending command will be repeated 2 times
I think this should be refactored to a decorator
"""
with self.mpd_lock:
try:
value = mpd_cmd(*args)
except Exception as e:
logger.error(f"{e.__class__.__qualname__}: {e}")
value = None
return value
def _mpd_status_poll(self):
"""
this method polls the status from mpd and stores the important inforamtion in the music_player_status,
it will repeat itself in the intervall specified by self.mpd_status_poll_interval
"""
self.mpd_status.update(self.mpd_retry_with_mutex(self.mpd_client.status))
self.mpd_status.update(self.mpd_retry_with_mutex(self.mpd_client.currentsong))
if self.mpd_status.get('elapsed') is not None:
self.current_folder_status["ELAPSED"] = self.mpd_status['elapsed']
self.music_player_status['player_status']["CURRENTSONGPOS"] = self.mpd_status['song']
self.music_player_status['player_status']["CURRENTFILENAME"] = self.mpd_status['file']
if self.mpd_status.get('file') is not None:
self.current_folder_status["CURRENTFILENAME"] = self.mpd_status['file']
self.current_folder_status["CURRENTSONGPOS"] = self.mpd_status['song']
self.current_folder_status["ELAPSED"] = self.mpd_status.get('elapsed', '0.0')
self.current_folder_status["PLAYSTATUS"] = self.mpd_status['state']
self.current_folder_status["RESUME"] = "OFF"
self.current_folder_status["SHUFFLE"] = "OFF"
self.current_folder_status["LOOP"] = "OFF"
self.current_folder_status["SINGLE"] = "OFF"
# Delete the volume key to avoid confusion
# Volume is published via the 'volume' component!
try:
del self.mpd_status['volume']
except KeyError:
pass
publishing.get_publisher().send('playerstatus', self.mpd_status)
# MPD can play absolute paths but can find songs in its database only by relative path
# This function aims to prepare the song_url accordingly
def harmonize_mpd_url(self, song_url):
_music_library_path_absolute = os.path.expanduser(components.player.get_music_library_path())
song_url = song_url.replace(f'{_music_library_path_absolute}/', '')
return song_url
@plugs.tag
def get_player_type_and_version(self):
with self.mpd_lock:
value = self.mpd_client.mpd_version()
return value
@plugs.tag
def update(self):
with self.mpd_lock:
state = self.mpd_client.update()
return state
@plugs.tag
def update_wait(self):
state = self.update()
self._db_wait_for_update(state)
return state
@plugs.tag
def play(self):
with self.mpd_lock:
self.mpd_client.play()
@plugs.tag
def stop(self):
with self.mpd_lock:
self.mpd_client.stop()
@plugs.tag
def pause(self, state: int = 1):
"""Enforce pause to state (1: pause, 0: resume)
This is what you want as card removal action: pause the playback, so it can be resumed when card is placed
on the reader again. What happens on re-placement depends on configured second swipe option
"""
with self.mpd_lock:
self.mpd_client.pause(state)
@plugs.tag
def prev(self):
logger.debug("Prev")
if self.mpd_status['state'] == 'stop':
logger.debug('Player is stopped, calling stopped_prev_action')
return self.stopped_prev_action()
try:
with self.mpd_lock:
self.mpd_client.previous()
except mpd.base.CommandError:
# This shouldn't happen in reality, but we still catch
# this error to avoid crashing the player thread:
logger.warning('Failed to go to previous song, ignoring')
def _prev_in_stopped_state(self):
with self.mpd_lock:
self.mpd_client.play(max(0, int(self.mpd_status['pos']) - 1))
@plugs.tag
def next(self):
"""Play next track in current playlist"""
logger.debug("Next")
if self.mpd_status['state'] == 'stop':
logger.debug('Player is stopped, calling stopped_next_action')
return self.stopped_next_action()
playlist_len = int(self.mpd_status.get('playlistlength', -1))
current_pos = int(self.mpd_status.get('pos', 0))
if current_pos == playlist_len - 1:
logger.debug(f'next() called during last song ({current_pos}) of '
f'playlist (len={playlist_len}), running end_of_playlist_next_action.')
return self.end_of_playlist_next_action()
try:
with self.mpd_lock:
self.mpd_client.next()
except mpd.base.CommandError:
# This shouldn't happen in reality, but we still catch
# this error to avoid crashing the player thread:
logger.warning('Failed to go to next song, ignoring')
def _next_in_stopped_state(self):
pos = int(self.mpd_status['pos']) + 1
if pos > int(self.mpd_status['playlistlength']) - 1:
return self.end_of_playlist_next_action()
with self.mpd_lock:
self.mpd_client.play(pos)
@plugs.tag
def seek(self, new_time):
with self.mpd_lock:
self.mpd_client.seekcur(new_time)
@plugs.tag
def rewind(self):
"""
Re-start current playlist from first track
Note: Will not re-read folder config, but leave settings untouched"""
logger.debug("Rewind")
with self.mpd_lock:
self.mpd_client.play(0)
@plugs.tag
def replay(self):
"""
Re-start playing the last-played folder
Will reset settings to folder config"""
logger.debug("Replay")
with self.mpd_lock:
self.play_folder(self.music_player_status['player_status']['last_played_folder'])
@plugs.tag
def toggle(self):
"""Toggle pause state, i.e. do a pause / resume depending on current state"""
with self.mpd_lock:
self.mpd_client.pause()
@plugs.tag
def replay_if_stopped(self):
"""
Re-start playing the last-played folder unless playlist is still playing
> [!NOTE]
> To me this seems much like the behaviour of play,
> but we keep it as it is specifically implemented in box 2.X"""
with self.mpd_lock:
if self.mpd_status['state'] == 'stop':
self.play_folder(self.music_player_status['player_status']['last_played_folder'])
# Shuffle
def _shuffle(self, random):
# As long as we don't work with waiting lists (aka playlist), this implementation is ok!
self.mpd_retry_with_mutex(self.mpd_client.random, 1 if random else 0)
@plugs.tag
def shuffle(self, option='toggle'):
if option == 'toggle':
if self.mpd_status['random'] == '0':
self._shuffle(1)
else:
self._shuffle(0)
elif option == 'enable':
self._shuffle(1)
elif option == 'disable':
self._shuffle(0)
else:
logger.error(f"'{option}' does not exist for 'shuffle'")
# Repeat
def _repeatmode(self, mode):
if mode == 'repeat':
repeat = 1
single = 0
elif mode == 'single':
repeat = 1
single = 1
else:
repeat = 0
single = 0
with self.mpd_lock:
self.mpd_client.repeat(repeat)
self.mpd_client.single(single)
@plugs.tag
def repeat(self, option='toggle'):
if option == 'toggle':
if self.mpd_status['repeat'] == '0':
self._repeatmode('repeat')
elif self.mpd_status['repeat'] == '1' and self.mpd_status['single'] == '0':
self._repeatmode('single')
else:
self._repeatmode(None)
elif option == 'toggle_repeat':
if self.mpd_status['repeat'] == '0':
self._repeatmode('repeat')
else:
self._repeatmode(None)
elif option == 'toggle_repeat_single':
if self.mpd_status['single'] == '0':
self._repeatmode('single')
else:
self._repeatmode(None)
elif option == 'enable_repeat':
self._repeatmode('repeat')
elif option == 'enable_repeat_single':
self._repeatmode('single')
elif option == 'disable':
self._repeatmode(None)
else:
logger.error(f"'{option}' does not exist for 'repeat'")
@plugs.tag
def get_current_song(self, param):
return self.mpd_status
@plugs.tag
def map_filename_to_playlist_pos(self, filename):
# self.mpd_client.playlistfind()
raise NotImplementedError
@plugs.tag
def remove(self):
raise NotImplementedError
@plugs.tag
def move(self):
# song_id = param.get("song_id")
# step = param.get("step")
# MPDClient.playlistmove(name, from, to)
# MPDClient.swapid(song1, song2)
raise NotImplementedError
def _play_single_internal(self, song_url: str) -> None:
with self.mpd_lock:
self.mpd_client.clear()
self.mpd_client.addid(song_url)
self.mpd_client.play()
def _play_album_internal(self, artist: str, album: str) -> None:
with self.mpd_lock:
logger.info(f"Play album: '{album}' by '{artist}")
self.mpd_client.clear()
self.mpd_retry_with_mutex(self.mpd_client.findadd, 'albumartist', artist, 'album', album)
self.mpd_client.play()
def _play_folder_internal(self, folder: str, recursive: bool) -> None:
with self.mpd_lock:
logger.info(f"Play folder: '{folder}'")
self.mpd_client.clear()
plc = playlistgenerator.PlaylistCollector(components.player.get_music_library_path())
plc.parse(folder, recursive)
uri = '--unset--'
try:
for uri in plc:
self.mpd_client.addid(uri)
except mpd.base.CommandError as e:
logger.error(f"{e.__class__.__qualname__}: {e} at uri {uri}")
except Exception as e:
logger.error(f"{e.__class__.__qualname__}: {e} at uri {uri}")
self.music_player_status['player_status']['last_played_folder'] = folder
self.current_folder_status = self.music_player_status['audio_folder_status'].get(folder)
if self.current_folder_status is None:
self.current_folder_status = self.music_player_status['audio_folder_status'][folder] = {}
self.mpd_client.play()
@plugs.tag
def play_content(self, content: Union[str, Dict[str, Any]], content_type: str = 'folder', recursive: bool = False):
"""
Main entry point for trigger music playing from any source (RFID reader, web UI, etc.).
Does NOT support second swipe - use play_from_reader() for that.
:param content: Content identifier:
- For singles/folders: file/folder path as string
- For albums: dict with 'albumartist' and 'album' keys
:param content_type: Type of content ('single', 'album', 'folder')
:param recursive: Add folder recursively (only used for folder type)
"""
try:
content_type = content_type.lower()
if content_type == 'album':
if isinstance(content, dict):
albumartist = content.get('albumartist')
album = content.get('album')
if not albumartist or not album:
raise ValueError("Album content must contain both 'albumartist' and 'album' keys")
else:
raise ValueError("Album content must be a dictionary with 'albumartist' and 'album' keys")
play_content = PlayContent(
type=PlayContentType.ALBUM,
content=(albumartist, album)
)
elif content_type == 'single':
if isinstance(content, dict):
raise ValueError("Single track content should be a direct file path, not a dictionary")
play_content = PlayContent(
type=PlayContentType.SINGLE,
content=content
)
else: # folder is default
if isinstance(content, dict):
raise ValueError("Folder content should be a direct folder path, not a dictionary")
play_content = PlayContent(
type=PlayContentType.FOLDER,
content=content,
recursive=recursive
)
# Ensure no second swipe for regular content playback
old_action = self.play_content_handler._second_swipe_action
self.play_content_handler._second_swipe_action = None
try:
self.play_content_handler.play_content(play_content)
finally:
# Restore previous second swipe action
self.play_content_handler._second_swipe_action = old_action
except Exception as e:
logger.error(f"Error playing content: {e}")
raise
@plugs.tag
def play_from_reader(self, content: Union[str, Dict[str, str]], content_type: str = 'folder',
recursive: bool = False, second_swipe: Optional[str] = None):
"""
Special entry point for reader-triggered playback with second swipe support.
Used when content is identified via RFID, barcode, or other physical readers.
:param content: Content identifier, either:
- string path for single/folder types
- dict with 'albumartist' and 'album' keys for album type
:param content_type: Type of content ('single', 'album', 'folder')
:param recursive: Add folder recursively (only used for folder type)
:param second_swipe: Override default second swipe action for this reader:
- None/not specified: use default from config
- 'none': disable second swipe
- One of: 'toggle', 'play', 'skip', 'rewind', 'replay', 'replay_if_stopped'
"""
# Determine second swipe action
if second_swipe is None:
action = self.second_swipe_action
elif second_swipe.lower() == 'none':
action = None
else:
action = self.second_swipe_action_dict.get(second_swipe.lower())
if action is None:
logger.error(f"Unknown second swipe action '{second_swipe}', using default")
action = self.second_swipe_action
# Temporarily set the chosen second swipe action
old_action = self.play_content_handler._second_swipe_action
self.play_content_handler.set_second_swipe_action(action)
try:
self.play_content(content, content_type, recursive)
finally:
# Restore previous second swipe action
self.play_content_handler.set_second_swipe_action(old_action)
# The following methods are kept for backward compatibility but now use play_content internally
@plugs.tag
def play_single(self, song_url):
"""Deprecated: Use play_content with content_type='single' instead"""
self.play_content(song_url, content_type='single')
@plugs.tag
def play_album(self, albumartist: str, album: str):
"""Deprecated: Use play_content with content_type='album' instead"""
content = {'artist': albumartist, 'album': album}
self.play_content(content, content_type='album')
@plugs.tag
def play_folder(self, folder: str, recursive: bool = False):
"""Deprecated: Use play_content with content_type='folder' instead"""
self.play_content(folder, content_type='folder', recursive=recursive)
@plugs.tag
def resume(self):
with self.mpd_lock:
songpos = self.current_folder_status["CURRENTSONGPOS"]
elapsed = self.current_folder_status["ELAPSED"]
self.mpd_client.seek(songpos, elapsed)
self.mpd_client.play()
@plugs.tag
def get_single_coverart(self, song_url):
mp3_file_path = Path(components.player.get_music_library_path(), song_url).expanduser()
cache_filename = self.coverart_cache_manager.get_cache_filename(mp3_file_path)
return cache_filename
@plugs.tag
def get_album_coverart(self, albumartist: str, album: str):
song_list = self.list_songs_by_artist_and_album(albumartist, album)
return self.get_single_coverart(song_list[0]['file'])
@plugs.tag
def flush_coverart_cache(self):
"""
Deletes the Cover Art Cache
"""
return self.coverart_cache_manager.flush_cache()
@plugs.tag
def get_folder_content(self, folder: str):
"""
Get the folder content as content list with meta-information. Depth is always 1.
Call repeatedly to descend in hierarchy
:param folder: Folder path relative to music library path
"""
plc = playlistgenerator.PlaylistCollector(components.player.get_music_library_path())
plc.get_directory_content(folder)
return plc.playlist
@plugs.tag
def queue_load(self, folder):
# There was something playing before -> stop and save state
# Clear the queue
# Check / Create the playlist
# - not needed if same folder is played again? Buf what if files have been added a mpc update has been run?
# - and this a re-trigger to start the new playlist
# If we must update the playlists everytime anyway why write them to file and not just keep them in the queue?
# Load the playlist
# Get folder config and apply settings
pass
@plugs.tag
def playerstatus(self):
return self.mpd_status
@plugs.tag
def playlistinfo(self):
with self.mpd_lock:
value = self.mpd_client.playlistinfo()
return value
# Attention: MPD.listal will consume a lot of memory with large libs.. should be refactored at some point
@plugs.tag
def list_all_dirs(self):
with self.mpd_lock:
result = self.mpd_client.listall()
# list = [entry for entry in list if 'directory' in entry]
return result
@plugs.tag
def list_albums(self):
with self.mpd_lock:
album_list = self.mpd_retry_with_mutex(self.mpd_client.list, 'album', 'group', 'albumartist')
return album_list
@plugs.tag
def list_songs_by_artist_and_album(self, albumartist, album):
with self.mpd_lock:
song_list = self.mpd_retry_with_mutex(self.mpd_client.find, 'albumartist', albumartist, 'album', album)
return song_list
@plugs.tag
def get_song_by_url(self, song_url):
song_url = self.harmonize_mpd_url(song_url)
with self.mpd_lock:
song = self.mpd_retry_with_mutex(self.mpd_client.find, 'file', song_url)
return song
def get_volume(self):
"""
Get the current volume
For volume control do not use directly, but use through the plugin 'volume',
as the user may have configured a volume control manager other than MPD"""
with self.mpd_lock:
volume = self.mpd_client.status().get('volume')
return int(volume)
def set_volume(self, volume):
"""
Set the volume
For volume control do not use directly, but use through the plugin 'volume',
as the user may have configured a volume control manager other than MPD"""
with self.mpd_lock:
self.mpd_client.setvol(volume)
return self.get_volume()
def _db_wait_for_update(self, update_id: int):
logger.debug("Waiting for update to finish")
while self._db_is_updating(update_id):
# a little throttling
time.sleep(0.1)
def _db_is_updating(self, update_id: int):
with self.mpd_lock:
_status = self.mpd_client.status()
_cur_update_id = _status.get('updating_db')
if _cur_update_id is not None and int(_cur_update_id) <= int(update_id):
return True
else:
return False
# ---------------------------------------------------------------------------
# Plugin Initializer / Finalizer
# ---------------------------------------------------------------------------
player_ctrl: PlayerMPD
#: Callback handler instance for play_card events.
#: - is executed when play_card function is called
#: States:
#: - See :class:`PlayCardState`
#: See :class:`PlayContentCallbacks`
player_ctrl: PlayerMPD
play_card_callbacks: PlayContentCallbacks[PlayCardState]
@plugs.initialize
def initialize():
global player_ctrl
player_ctrl = PlayerMPD()
plugs.register(player_ctrl, name='ctrl')
global play_card_callbacks
play_card_callbacks = PlayContentCallbacks[PlayCardState]('play_card_callbacks', logger, context=player_ctrl.mpd_lock)
# Update mpc library
library_update = cfg.setndefault('playermpd', 'library', 'update_on_startup', value=True)
if library_update:
player_ctrl.update()
# Check user rights on music library
library_check_user_rights = cfg.setndefault('playermpd', 'library', 'check_user_rights', value=True)
if library_check_user_rights is True:
music_library_path = components.player.get_music_library_path()
if music_library_path is not None:
logger.info(f"Change user rights for {music_library_path}")
misc.recursive_chmod(music_library_path, mode_files=0o666, mode_dirs=0o777)
@plugs.atexit
def atexit(**ignored_kwargs):
global player_ctrl
return player_ctrl.exit()