-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmpdart.py
1866 lines (1698 loc) · 87.3 KB
/
mpdart.py
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# encoding:utf-8
# Author: cumulus13
# email: cumulus13@gmail.com
from __future__ import print_function
#from netifaces import interfaces, ifaddresses, AF_INET
from make_colors import make_colors
from pydebugger.debug import debug
from multiprocessing import Pool
from progressbar import ProgressBar
import re
import shutil
#import socket
import os
import io
from PIL import Image
import sys
import signal
import time
#import base64
import http.server as SimpleHTTPServer
import socketserver as SocketServer
try:
from mutagen.id3 import ID3
from mutagen.flac import FLAC
MUTAGEN = True
except ImportError:
MUTAGEN = False
import requests
from datetime import datetime, timedelta
if sys.version_info.major == 3:
raw_input = input
import traceback
import argparse
import qdarkstyle
import qtmodern.styles
import qtmodern.windows
from qt_material import apply_stylesheet
try:
from pause import pause
except:
def pause(*args, **kwargs):
return None
NOTIFY2 = False
if not sys.platform == 'win32':
try:
import notify2 as pynotify
NOTIFY2 = True
if not pynotify.init("MPD status"):
logger.error("warning: Unable to initialize dbus Notifications")
except:
NOTIFY2 = False
from PyQt5 import Qt
from PyQt5.Qt import QStandardItemModel, QStandardItem, QKeySequence
from PyQt5.QtGui import QPixmap, QImage, QIcon, QFont, QColor
from PyQt5.QtWidgets import QDialog, QApplication, QLabel, QTableWidgetItem, QAbstractScrollArea, QAbstractItemView, QTableWidget, QHeaderView, QPushButton, QScrollArea, QWidget, QShortcut, QGraphicsPixmapItem, QGraphicsScene
from PyQt5.QtCore import *
#from PyQt5.QtWebEngineWidgets import QWebEnginePage
try:
from .gui import *
except:
from gui import *
import ast, json
#from jsoncolor import jprint
from configset import configset
from mpd import MPDClient
import mpd
try:
from xnotify import notify
XNOTIFY = True
except:
XNOTIFY = False
try:
from . import mimelist
except:
import mimelist
import logging
class CustomFormatter(logging.Formatter):
info = "\x1b[32;20m"
debug = "\x1b[33;20m"
fatal = "\x1b[44;97m"
error = "\x1b[41;97m"
warning = "\x1b[43;30m"
critical = "\x1b[45;97m"
reset = "\x1b[0m"
format = "%(asctime)s - %(name)s - %(process)d - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
FORMATS = {
logging.DEBUG: debug + format + reset,
logging.INFO: info + format + reset,
logging.WARNING: warning + format + reset,
logging.ERROR: error + format + reset,
logging.CRITICAL: critical + format + reset,
logging.FATAL: fatal + format + reset
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)
#log_format = '%(name)s %(asctime)s %(process)d - %(levelname)s - %(message)s'
#logging.basicConfig(format = log_format)
logger = logging.getLogger('MPD-Art')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(CustomFormatter())
logger.addHandler(ch)
MPD_HOST = ''
MPD_PORT = 6600
MPD_MUSIC_DIR = ''
MPD_SLEEP = 1
APP = 'MPD-Art'
CONFIGFILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mpdart.ini')
CONFIG = configset(CONFIGFILE)
MOD_MASK = (Qt.CTRL | Qt.ALT | Qt.SHIFT | Qt.META)
class MPD(object):
cover = ''
CONFIG = CONFIG
host = CONFIG.get_config('mpd', 'host') or MPD_HOST or os.getenv('MPD_HOST') or '127.0.0.1'
port = CONFIG.get_config('mpd', 'port') or MPD_PORT or os.getenv('MPD_PORT') or 6600
debug(host = host)
debug(port = port)
music_dir = CONFIG.get_config('mpd', 'music_dir')
jump_from = None
jump_to = None
sleep = CONFIG.get_config('sleep', 'time') or 1000
icon = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'icon.png')
timeout = CONFIG.get_config('mpd', 'timeout')
CONN = MPDClient()
debug(host = host)
debug(port = port)
#try:
#CONN.connect(host, port)
#except:
#pass
DEFAULT_COVER = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'no-cover.png')
current_song = {}
COVER_TEMP_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'covers')
FAIL_LAST_FM = False
current_state = {}
first = False
process = None
process1 = None
first_current_song = False
first_state = False
@classmethod
def conn(self, func, args = (), host = None, port = None, refresh = False, repeat = False):
if host and not host == self.host or port and not port == self.port:
debug(host = host)
debug(port = port)
self.CONN.connect(host, port, self.timeout)
self.host = host
self.port = port
else:
host = host or self.host or '127.0.0.1'
port = port or self.port or 6600
try:
self.CONN.connect(host, port, self.timeout)
except:
pass
timeout = self.timeout or self.CONFIG.get_config('mpd', 'timeout') or None
debug(host = host)
debug(port = port)
debug(timeout = timeout)
debug(refresh = refresh)
debug(func = func)
#logger.debug("func: {}".format(func))
if refresh:
if (func == 'currentsong' and not self.first_current_song and not self.command == func) or (func == 'status' and not self.first_state and not self.command == func):
#print("GET:", func)
c = MPDClient()
c.connect(host, port, timeout)
self.first = True
self.command = func
return getattr(c, func)(*args)
try:
if str(repeat).isdigit():
for i in range(0, repeat + int(repeat)):
result = getattr(self.CONN, func)(*args)
if result:
break
self.command = func
return getattr(self.CONN, func)(*args)
except Exception as e:
#if not self.first:
#print(traceback.format_exc())
if os.getenv('TRACEBACK') == '1' or os.getenv('TRACEBACK') == 1:
logger.error(e)
#time.sleep(1)
try:
c = MPDClient()
c.connect(host, port, timeout)
#if str(repeat).isdigit():
#for i in range(0, repeat + int(repeat)):
#result = getattr(c, func)(*args)
#if result:
#break
self.command = func
return getattr(c, func)(*args)
except Exception as e:
logger.error("MPD:conn: {}".format(e))
if not self.first:
#print(traceback.format_exc())
if os.getenv('TRACEBACK') == 1:
logger.error(traceback.format_exc())
self.first = True
#self.first = True
time.sleep(1)
self.command = func
return {}
@classmethod
def format_number(self, number, length = 10):
number = str(number).strip()
if not str(number).isdigit():
return number
zeros = len(str(length)) - len(number)
r = ("0" * zeros) + str(number)
if len(r) == 1:
return "0" + r
return r
@classmethod
def send_notify(self, current_song = None, current_state = None, event = 'stop', cover_art = None, app = 'MPD-Art'):
label = ''
track = '0'
title = '~ no title / unknown ~'
album = '~ no album / unknown ~'
albumartist = '~ no albumartist / unknown ~'
date = '~ no date / unknown ~'
label = ''
bitrate = ''
genres = ''
artist = ''
disc = "0"
duration = ''
state = 'stop'
debug(current_song = current_song)
debug(current_state = current_state)
logger.debug("current_song: {}".format(current_song))
logger.debug("current_state: {}".format(current_state))
debug(self_current_song = self.current_song)
debug(self_current_state = self.current_state)
logger.debug("self.current_song: {}".format(self.current_song))
logger.debug("self.current_state: {}".format(self.current_state))
current_song = current_song or self.current_song
current_state = current_state or self.current_state
debug(current_song = current_song)
debug(current_state = current_state)
logger.debug("current_song: {}".format(current_song))
logger.debug("current_state: {}".format(current_state))
if current_song and current_state:
track = current_song.get('track') or track or ''
title = current_song.get('title') or title or ''
album = current_song.get('album') or album or ''
albumartist = current_song.get('albumartist') or albumartist or ''
date = current_song.get('date') or date or ''
artist = current_song.get('artist') or artist or ''
disc = current_song.get('disc') or disc or '0'
label = current_song.get('label') or label or ''
duration = current_song.get('duration') or duration or ''
genres = current_song.get('genre') or genres or ''
state = current_state.get('state') or event or ''
bitrate = current_state.get('bitrate') or bitrate or ''
event = state or event or 'stop'
message = track + "/" +\
self.format_number(disc) + ". " +\
title + "\n" + \
duration + "[" + bitrate + "] " + "\n" +\
"Artist : " + artist + "\n" + \
"Album : " + album + "\n" + \
"Genres : " + genres + "\n\n" + \
state
cover_art = cover_art or self.DEFAULT_COVER
debug(cover_art = cover_art)
debug(NOTIFY2 = NOTIFY2)
debug(XNOTIFY = XNOTIFY)
if NOTIFY2 and self.CONFIG.get_config('notification', 'notify2') == 1:
logger.debug("send notify [LINUX]: {}".format(message))
try:
pnotify = pynotify.Notification("MPD-Art " + title + " " + event, message, "file://" + cover_art)
pnotify.show()
except:
traceback.format_exc()
if XNOTIFY and self.CONFIG.get_config('notification', 'xnotify') == 1:
growl = self.CONFIG.get_config('xnotify', 'growl') or False
growl_host = list(filter(None, [i.strip() for i in re.split(",|\n", self.CONFIG.get_config('xnotify', 'grow_host'))]))
nmd = self.CONFIG.get_config('xnotify', 'nmd') or False
nmd_api = self.CONFIG.get_config('xnotify', 'nmd_api')
pushbullet = self.CONFIG.get_config('xnotify', 'pushbullet') or False
pushbullet_api = self.CONFIG.get_config('xnotify', 'pushbullet_api')
ntfy = self.CONFIG.get_config('xnotify', 'ntfy') or False
ntfy_server = list(filter(None, [i.strip() for i in re.split(",|\n", self.CONFIG.get_config('xnotify', 'ntfy_server'))]))
notify.active_growl = growl
notify.active_nmd = nmd
notify.active_pushbullet = pushbullet
notify.active_ntfy = ntfy
notify.host = growl_host
notify.nmd_api = nmd_api
notify.pushbullet_api = pushbullet_api
notify.ntfy_server = ntfy_server
logger.debug("send notify: {}".format(message))
try:
notify.send('MPD-Art:' + " " + (event or 'play'), message, app, event, growl_host, icon = cover_art, iconpath = cover_art, ntfy = ntfy, nfty_sever = ntfy_server, pushbullet_api = pushbullet_api, nmd_api = nmd_api, pushbullet = pushbullet, nmd = nmd, growl = growl)
except:
traceback.format_exc()
logger.warning("send notification done ...")
@classmethod
def get_cover_tag(self, music_file, save_dir = None):
debug(music_file = music_file)
save_dir = save_dir or (os.getenv('TEMP') or '/tmp')
if not os.path.isdir(save_dir):
save_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'covers')
if not os.path.isdir(save_dir):
try:
os.makedirs(save_dir)
except:
pass
#if not os.path.isfile(music_file):
#if not self.first:
#print(make_colors("Invalid Music file !", 'lw', 'lr'))
#if not sys.platform == 'win32':
#pnotify = pynotify.Notification("Error", "Invalid Music file !", "file://" + os.path.join(os.path.dirname(os.path.realpath(__file__)), "error.png"))
#pnotify.show()
#if not self.first:
#notify.send("Error", "Invalid Music file !", "MPDNotify", "error", iconpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "error.png"), sticky = True)
#return ''
data_cover = None
debug(music_file = music_file)
if music_file.lower().endswith('.mp3'):
f = ID3(music_file)
debug(meta_keys = f.keys())
for i in f.keys():
if "APIC" in i:
data_cover = f.get(i)
debug(len_data_cover = len(data_cover.data))
break
if data_cover: debug(len_data_cover = len(data_cover.data))
elif music_file.lower().endswith('.flac'):
if MUTAGEN:
f = FLAC(music_file)
if f.picture:
data_cover = f.picture[0]
else:
print('"mutagen" module is not installed !')
if not data_cover:
if not self.first:
logger.warn(make_colors("Music file don't containt tag Cover !", 'lw', 'r'))
if not sys.platform == 'win32':
if not self.first:
pnotify = pynotify.Notification("Error", "Music file don't containt tag Cover !", "file://" + os.path.join(os.path.dirname(os.path.realpath(__file__)), "error.png"))
pnotify.show()
if not self.first:
notify.send("Error", "Music file don't containt tag Cover !", "MPDNotify", "error", iconpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "error.png"), sticky = True)
# return self.DEFAULT_COVER
return ''
debug(data_cover_mime = data_cover.mime)
ext = mimelist.get(data_cover.mime) or data_cover.mime.split("/")[-1]
debug(ext = ext)
save_dir = save_dir or os.path.dirname(music_file)
if os.path.isfile(os.path.join(os.path.realpath(save_dir), 'cover2.' + ext)):
return os.path.join(os.path.realpath(save_dir), 'cover2.' + ext)
if isinstance(data_cover.data, bytes):
with open(os.path.join(save_dir, 'cover2.' + ext), 'wb') as c:
c.write(data_cover.data)
elif isinstance(data_cover.data, str):
with open(os.path.join(save_dir, 'cover2.' + ext), 'w') as c:
c.write(data_cover.data)
if not os.path.isfile(os.path.join(save_dir, 'cover2.' + ext)):
if not self.first:
logger.error(make_colors("Invalid Cover !", 'lw', 'r'))
if not sys.platform == 'win32':
if not self.first:
pnotify = pynotify.Notification("Error", "Invalid Cover !", "file://" + os.path.join(os.path.dirname(os.path.realpath(__file__)), "error.png"))
pnotify.show()
if not self.first:
notify.send("Error", "Invalid Cover !", "MPDNotify", "error", iconpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "error.png"), sticky = True)
return self.DEFAULT_COVER
return os.path.join(save_dir, 'cover2.' + ext)
@classmethod
def get_cover_lastfm(self, current_song = None, timeout = 5, retries = 5, size = 'medium'):
file_path = ''
img_url = ''
thumb = ''
current_song = current_song or self.current_song or self.conn('currentsong')
if not current_song or not isinstance(current_song, dict):
return '', '', ''
api_key = self.CONFIG.get_config('lastfm', 'api')
if not api_key:
try:
import mpd_album_art
grab = mpd_album_art.Grabber(self.COVER_TEMP_DIR)
debug(current_song = current_song)
file_path = grab.get_art(current_song)
if file_path:
if os.path.isfile(file_path):
return file_path, '', ''
except ImportError:
logger.fatal(make_colors("Please install 'mpd_album_art' before: 'pip install git+http://jameh.github.io/mpd-album-art' or input lastfm api key in config file, '{}'".format(self.CONFIG.configname), 'lw', 'r'))
file_path = ''
if not file_path and api_key:
url_artist = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist={}&api_key=" + api_key + "&format=json"
url_album = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=" + api_key + "&artist={}&album={}&format=json"
IS_ARTIST = False
IS_ALBUM = False
debug(artist = current_song.get('artist'))
debug(album = current_song.get('album'))
n = 1
a = None
while 1:
try:
a = requests.get(url_album.format(current_song.get('artist'), current_song.get('album'))).json()
debug(a = a)
if isinstance(a, dict):
if a.get('error') == 6 or a.get('message') == 'Album not found':
IS_ALBUM = False
a = requests.get(url_artist.format(current_song.get('artist'))).json()
debug(a = a)
else:
IS_ALBUM = True
else:
IS_ARTIST = True
break
except:
if not n == retries:
n += 1
time.sleep(1)
else:
break
debug(a = a)
if a:
debug(IS_ARTIST = IS_ARTIST)
debug(IS_ALBUM = IS_ALBUM)
#pause()
try:
if IS_ARTIST:
images = a.get('album').get('image')
debug(images = images)
elif IS_ALBUM:
images = a.get('album').get('image')
debug(images = images)
else:
logger.warn(make_colors("Not Artist or Album from LaST.fm [1] !", 'lw', 'r'))
file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'no-cover.png')
if not os.path.isfile(file_path): file_path = ''
return file_path, '', thumb
except AttributeError:
#print(traceback.format_exc())
logger.error(traceback.format_exc())
logger.warn(make_colors("Not Artist or Album from LaST.fm [2] !", 'lw', 'r'))
file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'no-cover.png')
if not os.path.isfile(file_path): file_path = ''
return file_path, '', thumb
debug(images = images)
if images:
for i in images:
if i.get('size') == size:
img_url = i.get('#text')
debug(i = i)
debug(img_url = img_url)
if i.get('size') == 'small':
thumb = i.get('#text')
debug(i = i)
debug(img_url = img_url)
if img_url:
break
if not img_url:
img_url = images[0].get('#text')
debug(img_url = img_url)
if not os.path.isdir(self.COVER_TEMP_DIR):
os.makedirs(self.COVER_TEMP_DIR)
#try:
## Download the image
#urlretrieve(img_url, file_path)
#self.remove_current_link()
#except:
#sys.stderr.write(traceback.format_exc() + "\n")
#self.remove_current_link()
#return None
if img_url:
n = 1
data_img = None
while 1:
try:
data_img = requests.get(img_url, stream = True).content
debug(len_data_img = len(data_img))
file_path = os.path.join(self.COVER_TEMP_DIR, '{}_{}{}'.format(current_song.get('artist'), current_song.get('album').replace(" ", "_"), os.path.splitext(img_url)[-1]))
debug(file_path = file_path)
with open(file_path, 'wb') as img:
img.write(data_img)
break
except:
if not n == retries:
n += 1
else:
#print(make_colors("ERROR:", 'lw', 'r') + traceback.format_exc())
logger.error(traceback.format_exc())
break
debug(file_path = file_path)
if file_path:
if not os.path.isfile(file_path): file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'no-cover.png')
return file_path, img_url, thumb
@classmethod
def get_cover_from_cover_server(self, current_song, ext):
try:
chost = self.CONFIG.get_config('cover_server', 'host')
debug(chost = chost)
if chost == '0.0.0.0': chost = '127.0.0.1'
#if self.process:
#try:
#self.process.terminate()
#except:
#pass
#self.process = Pool(processes = 1)
r = None
nt = 0
while 1:
try:
#r = self.process.apply_async(requests.get, args = ('http://' + chost + ":" + str(self.CONFIG.get_config('cover_server', 'port')),), kwds = {'timeout': (self.CONFIG.get_config('requests', 'timeout') or 6)})
logger.warning("Get cover from cover server 'http://{}:{}'".format(chost, str(self.CONFIG.get_config('cover_server', 'port'))))
r = requests.get(
'http://' + chost + ":" + str(self.CONFIG.get_config('cover_server', 'port')),
timeout = (self.CONFIG.get_config('requests', 'timeout') or 6)
)
except Exception as e:
if os.getenv('TRACEBACK') == '1' or os.getenv('TRACEBACK') == 1:
logger.warning("get cover from cover server [ERROR]: {}".format(e))
else:
logger.warning("get cover from cover server [ERROR]")
try:
logger.warning("get cover from cover server")
#if r.get():
if r:
logger.warning("get cover from cover server [FINISH]")
break
except Exception as e:
if os.getenv('TRACEBACK') == '1' or os.getenv('TRACEBACK') == 1:
logger.warning("get cover from cover server [ERROR]: {}".format(e))
else:
logger.warning("get cover from cover server [ERROR]")
debug(nt = nt)
if not nt > (self.CONFIG.get_config('cover_server', 'tries', '3') or 3):
nt += 1
else:
r = None
break
#r = requests.get('http://' + chost + ":" + str(self.CONFIG.get_config('cover_server', 'port')), timeout = (self.CONFIG.get_config('requests', 'timeout') or 5))
if r:
#ext = r.get().headers.get('Content-type') or r.get().headers.get('content-type')
ext = r.headers.get('Content-type') or r.headers.get('content-type')
logger.debug("ext: {}".format(ext))
if ext:
if "image" in ext: logger.warning("get cover from cover server [SUCCESS]")
if ext: ext = mimelist.get(ext) or "jpg"
logger.debug("ext: {}".format(ext))
try:
if not os.path.isdir(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'))):
os.makedirs(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown')))
with open(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover.' + ext), 'wb') as fc:
try:
logger.warning("get cover from cover server, write file")
#fc.write(r.get().content)
fc.write(r.content)
logger.warning("get cover from cover server, write file [FINISH]")
logger.info("get cover from cover server: cover: '{}'".format(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover.' + ext)))
except Exception as e:
logger.error("Failed to make file, get cover from cover server [FAILED 0]")
if os.getenv('TRACEBACK') == '1' or os.getenv('TRACEBACK') == 1:
logger.error(e)
except Exception as e:
logger.error("Failed to make file, get cover from cover server [FAILED 1]")
if os.getenv('TRACEBACK') == '1' or os.getenv('TRACEBACK') == 1:
logger.error(e)
else:
logger.error("Failed to get cover from cover server [FAILED]")
logger.warning("get cover from cover server, check is file")
if MPD.check_is_image(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover.' + ext)):
self.cover = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover.' + ext)
debug(self_cover = self.cover)
logger.warning("cover is file [7]")
return self.cover
else:
logger.error("Failed to make file, get cover from cover server [FAILED 2]")
except Exception as e:
logger.error(e)
if os.getenv('TRACEBACK') == '1' or os.getenv('TRACEBACK') == 1: logger.error(traceback.format_exc())
return False
@classmethod
def get_cover(self, current_song, music_dir = None, get_lastfm_cover = True, refresh = False):
if refresh: self.cover = ''
current_song = current_song or self.conn('currentsong')
if current_song.get('file') == self.current_song.get('file'): self.current_song = current_song
logger.info("self.current_song: {}".format(self.current_song))
debug(music_dir = music_dir)
music_dir = music_dir or MPD_MUSIC_DIR or self.music_dir
debug(music_dir = music_dir)
debug(current_song = current_song)
if sys.platform == 'win32':
sep = "\\"
else:
sep = "/"
############################ [start] get cover from mpd tag #############################################
logger.debug("get cover from mpd tag")
debug(file = current_song.get('file'))
img_data = self.conn('albumart', (current_song.get('file'), ))
ext = 'jpg'
if img_data: img_data = img_data.get('binary')
debug(img_data = len(img_data))
if img_data and current_song:
logger.debug("get cover from mpd tag, img_data is exists")
img = Image.open(io.BytesIO(img_data))
debug(check_ext = mimelist.get2(img.format))
ext = mimelist.get2(img.format)[1]
if not os.path.isdir(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'))):
os.makedirs(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown')))
try:
img.save(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover' + "." + ext))
except Exception as e:
logger.error("get cover from mpd tag, Error save imgdata")
if os.getenv('TRACEBACK') == '1' or os.getenv('TRACEBACK') == 1: logger.error("get cover from mpd tag, Error save imgdata: {}".format(str(traceback.format_exc())))
if os.path.isfile(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover' + "." + ext)):
if MPD.check_is_image(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover' + "." + ext)):
self.cover = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover' + "." + ext)
debug(self_cover_X = self.cover)
logger.warning("get cover from mpd tag, cover is file [2]")
logger.debug("self.cover: {}".format(self.cover))
return os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover' + "." + ext)
debug(refresh = refresh)
debug(self_cover = self.cover)
debug(check_cover = MPD.check_is_image(self.cover))
############################ [end] get cover from mpd tag #############################################
############################# [start] get cover by name [.jpg|.png] #####################################
logger.debug("get cover by name [.jpg|.png]")
if os.path.isfile(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover' + ".jpg")):
self.cover = self.cover = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover' + ".jpg")
elif os.path.isfile(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover' + ".png")):
self.cover = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'cover' + ".png")
elif os.path.isfile(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'Cover' + ".jpg")):
self.cover = self.cover = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'Cover' + ".jpg")
elif os.path.isfile(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'Cover' + ".png")):
self.cover = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'Cover' + ".png")
elif os.path.isfile(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'folder' + ".jpg")):
self.cover = self.cover = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'folder' + ".jpg")
elif os.path.isfile(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'folder' + ".png")):
self.cover = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'folder' + ".png")
elif os.path.isfile(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'Folder' + ".jpg")):
self.cover = self.cover = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'Folder' + ".jpg")
elif os.path.isfile(os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'Folder' + ".png")):
self.cover = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'), 'Folder' + ".png")
debug(self_cover = self.cover)
if MPD.check_is_image(self.cover):
debug(self_cover = self.cover)
logger.warning("cover is file [1]")
logger.debug("[SUCCESS] get cover by name [.jpg|.png]")
logger.debug("self.cover: {}".format(self.cover))
return self.cover
debug('No cover')
if not MPD.check_is_image(self.cover) and current_song.get('file'):
#if not os.path.isfile(self.cover):
if sys.platform == 'win32':
self.cover = os.path.join(music_dir, sep.join(os.path.splitext(current_song.get('file'))[0].split("/")[1:])) + '.jpg'
else:
self.cover = os.path.join(music_dir, os.path.splitext(current_song.get('file'))[0]) + '.jpg'
debug(self_cover = self.cover)
if MPD.check_is_image(self.cover):
logger.warning("get cover by name [.jpg|.png], cover is file [2]")
logger.debug("self.cover: {}".format(self.cover))
return self.cover
if not MPD.check_is_image(self.cover) and current_song.get('file'):
if sys.platform == 'win32':
self.cover = os.path.join(music_dir, sep.join(os.path.splitext(current_song.get('file'))[0].split("/")[1:])) + '.png'
else:
self.cover = os.path.join(music_dir, os.path.splitext(current_song.get('file'))[0]) + '.png'
debug(self_cover = self.cover)
if MPD.check_is_image(self.cover):
logger.warning("get cover by name [.jpg|.png], cover is file [3]")
logger.debug("self.cover: {}".format(self.cover))
return self.cover
if not MPD.check_is_image(self.cover) and current_song.get('file'):
cover_file = os.path.join(music_dir, sep.join(current_song.get('file').split("/")[1:]))
debug(cover_file = cover_file)
try:
if MUTAGEN:
self.cover = MPD.get_cover_tag(cover_file)
if MPD.check_is_image(cover_file):
logger.warning("get cover by name [.jpg|.png], cover is file [4]")
logger.debug("self.cover: {}".format(self.cover))
return self.cover
else:
print('"mutagen" module is not installed !')
except:
pass
#if MPD.check_is_image(self.cover):
#logger.warning("cover is file [4]")
#return self.cover
debug(self_cover = self.cover)
valid_cover = list(filter(None, [i.strip() for i in re.split(",|\n|\t", self.CONFIG.get_config('cover', 'valid'))])) or ['cover.jpg', 'cover2.jpg', 'cover.png', 'cover2.png', 'folder.jpg', 'folder.png', 'front.jpg', 'front.png', 'albumart.jpg', 'albumart.png', 'folder1.jpg', 'folder1.png', 'back.jpg', 'back.png']
debug(cover_check_1 = (current_song.get('file') or 'unknown').split("/")[1:])
#debug(file = file)
for i in valid_cover:
#if sys.platform == 'win32':
debug(split_drive = os.path.join(music_dir, sep.join(os.path.dirname((current_song.get('file') or 'unknown')).split("/")[1:]), i), sep = sep)
if sys.platform == 'win32':
split_drive = os.path.join(music_dir, sep.join(os.path.dirname((current_song.get('file') or 'unknown')).split("/")[1:]))
else:
split_drive = os.path.join(music_dir, sep.join(os.path.dirname((current_song.get('file') or 'unknown')).split("/")))
self.cover = list(filter(lambda k: os.path.isfile(k),
[
os.path.join(split_drive, i),
os.path.join(split_drive, i.title()),
os.path.join(split_drive, i.upper())
]
))
debug(self_cover = self.cover)
if self.cover:
self.cover = self.cover[0]
else:
self.cover = ''
#else:
#self.cover = os.path.join(music_dir, os.path.dirname(current_song.get('file')), i)
debug(self_cover = self.cover)
#if self.cover:
debug(self_cover = self.cover)
if MPD.check_is_image(self.cover):
#print('return 3.....')
debug(self_cover = self.cover)
logger.debug("self.cover: {}".format(self.cover))
return self.cover
#cover_dir = os.path.join(self.COVER_TEMP_DIR, (current_song.get('artist') or 'unknown'), (current_song.get('album') or 'unknown'))
#debug(cover_dir = cover_dir)
#if not os.path.isdir(cover_dir):
#try:
#os.makedirs(cover_dir)
#except NotADirectoryError:
#logger.error("NotADirectoryError: '{}'".format(cover_dir))
#cover_dir = self.COVER_TEMP_DIR
#if not os.path.isdir(cover_dir):
#os.makedirs(cover_dir)
#try:
#shutil.copy2(self.cover, cover_dir)
#self.cover = os.path.join(cover_dir, os.path.basename(self.cover))
#debug(self_cover = self.cover)
#except Exception as e:
# #print(make_colors("shutil:", 'lw', 'r') + " " + make_colors(str(e), 'lw', 'bl'))
#logger.error(e)
#if os.getenv('TRACEBACK'):
# #print(traceback.format_exc())
#logger.error(traceback.format_exc())
#logger.warning("cover is file [5]")
#return self.cover
else:
self.cover: self.cover = ''
#if self.cover and MPD.check_is_image(self.cover):
#debug(self_cover = self.cover)
#logger.warning("cover is file [6]")
#return self.cover
############################# [end] get cover by name [.jpg|.png] #####################################
########################### get cover from cover server ##########################
self.cover = self.get_cover_from_cover_server(current_song, ext)
if self.cover:
if not MPD.check_is_image(self.cover): self.cover = False
############################ get cover from lastfm ######################################
if get_lastfm_cover and not self.cover:
logger.warning("get cover from LAST.FM")
debug(self_FAIL_LAST_FM = self.FAIL_LAST_FM)
if not self.FAIL_LAST_FM:
if self.process1:
try:
self.process1.terminate()
except:
pass
r1 = None
self.process1 = Pool(processes = 1)
#self.cover = MPD.get_cover_lastfm()[0]
nt1 = 0
while 1:
try:
r1 = self.process1.apply_async(MPD.get_cover_lastfm, args = ())
except Exception as e:
logger.warning("get cover from LAST.FM [ERROR]: {}".format(e))
try:
logger.warning("get cover from LAST.FM")
if r1.get():
logger.warning("get cover from LAST.FM [FINISH]")
break
except Exception as e:
logger.warning("get cover from LAST.FM [ERROR]: {}".format(e))
debug(nt1 = nt1)
if not nt1 > (self.CONFIG.get_config('lastfm', 'tries', '3') or 3):
nt1 += 1
else:
r1 = None
break
if r1: self.cover = r1.get()[0]
if self.cover:
debug(self_cover = self.cover)
debug(cover_split = self.cover.split(os.path.sep)[-1])
if not self.cover or self.cover.split(os.path.sep)[-1] == 'no-cover.png': self.FAIL_LAST_FM = True
debug(self_FAIL_LAST_FM = self.FAIL_LAST_FM)
debug(self_cover = self.cover)
if not MPD.check_is_image(self.cover):
logger.warning("cover is self.DEFAULT_COVER")
return self.DEFAULT_COVER
logger.warning("cover is file [8]")
return self.cover
@classmethod
def check_is_image(self, file):
try:
im = Image.open(file)
im.verify()
im.close()
return True
except:
return False
@classmethod
def cover_server(self, host = None, port = None):
try:
from . cover_server import CoverServer
except:
from cover_server import CoverServer
host = host or self.CONFIG.get_config('cover_server', 'host') or '0.0.0.0'
port = port or self.CONFIG.get_config('cover_server', 'port') or 8800
if host: self.CONFIG.write_config('cover_server', 'host', host)
if port: self.CONFIG.write_config('cover_server', 'port', port)
Handler = CoverServer
logger.warning('Server Run on: {}:{}'.format(host, port))
debug(host = host)
debug(port = port)
#server = SocketServer.TCPServer((host, port), Handler)
try:
server = SocketServer.TCPServer((host, port), Handler)
server.serve_forever()
except KeyboardInterrupt:
logging.error("Exception occurred", exc_info=True)
os.kill(os.getpid(), signal.SIGTERM)
except:
logging.error(traceback.format_exc())
class Art(QDialog):
keyPressed = pyqtSignal(str)
CONFIG = MPD.CONFIG
sleep = CONFIG.get_config('sleep', 'time') or 1000
icon = CONFIG.get_config('icon', 'path')
music_dir = CONFIG.get_config('mpd', 'music_dir')
configfile = CONFIG.get_config('config', 'file')
timeout = CONFIG.get_config('mpd', 'timeout')
command = None
last_dir = None
cover = ''
DEFAULT_COVER = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'no-cover.png')
current_song = {}
COVER_TEMP_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'covers')
FAIL_LAST_FM = False
current_state = {}
first = False
process = None
last_state = 'stop'
last_song = ''
current = 1
total = 1
host = '127.0.0.1'
port = 6600
PREFIX = '{variables.task} >> {variables.subtask} '
VARIABLES = {'task': '--', 'subtask': '--',}
BAR = ProgressBar(max_value = 100, max_error = False, prefix = PREFIX, variables = VARIABLES)
def __init__(self, host = None, port = None, sleep = None, configfile = None, icon = None, music_dir = None):
if sys.version_info.major == 3:
super().__init__()
else:
super(MPDArt(), self).__init__()
#QDialog.__init__(self, None, QtCore.Qt.WindowStaysOnTopHint)
self.ui = Ui_mpdart()
self.ui.setupUi(self)
self.setMouseTracking(True)
self.setShortcut()
self.installEventFilter(self)
try:
self.dark_view.installEventFilter(self)
except:
pass
self.music_dir = music_dir or self.music_dir or self.CONFIG.get_config('mpd', 'music_dir')
debug(music_dir = music_dir)
if not self.music_dir:
logger.warn(make_colors("No Music Directory 'music_dir' setup !", 'lw', 'r'))
#return False
if self.music_dir:
if not os.path.isdir(self.music_dir) and self.music_dir[1:3] == ":\\":
logger.warn(make_colors("Invalid Music Directory 'music_dir'!, please setup before", 'lw', 'r'))
#return False
host0 = host
debug(host0 = host0)
self.host = host or self.host or '127.0.0.1'
self.port = port or self.port or 6600
debug(self_host = self.host)
if host and not host0 == self.host: self.CONN.connect(self.host, self.port)
self.sleep = sleep or self.sleep or 1000
self.configfile = configfile or self.configfile
if self.configfile:
if os.path.isfile(self.configfile): self.CONFIG = configset(self.configfile)
self.icon = icon or self.CONFIG.get_config('icon', 'path')
if not os.path.isfile(self.icon): self.icon = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'icon.png')
debug(self_icon = self.icon)
if os.path.isfile(self.icon): self.setWindowIcon(QIcon(self.icon))
if os.path.isfile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'no-cover.png')):
self.setPixmap(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'no-cover.png'))
#self.setToolTip()
self.ui.cb_top.stateChanged.connect(self.setOnTop)
if sys.platform == "win32":
self.change_font(self.CONFIG.get_config('font', 'all'))
else:
self.change_font(6)
self.change_color()
self.change_opacity()
self.change_title_bar()
self.setPositionbylast()
#fi = self.ui.artist.fontInfo()
#print("font artist:", fi.pointSize())
self.timer = QTimer(self)
self.timer_bar = QTimer(self)
#self.showData()
def quit(self):
logger.debug("list position [1]: {}, {}".format(self.pos().x(), self.pos().y()))
try: