-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathspotify_monitor.py
1570 lines (1309 loc) · 81.9 KB
/
spotify_monitor.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 python3
"""
Author: Michal Szymanski <[email protected]>
v1.7
Tool implementing real-time tracking of Spotify friends music activity:
https://github.com/misiektoja/spotify_monitor/
Python pip3 requirements:
python-dateutil
requests
urllib3
"""
VERSION = 1.7
# ---------------------------
# CONFIGURATION SECTION START
# ---------------------------
# Log in to Spotify web client (https://open.spotify.com/) and put the value of sp_dc cookie below (or use -u parameter)
# Newly generated Spotify's sp_dc cookie should be valid for 1 year
# You can use Cookie-Editor by cgagnier to get it easily (available for all major web browsers): https://cookie-editor.com/
SP_DC_COOKIE = "your_sp_dc_cookie_value"
# SMTP settings for sending email notifications, you can leave it as it is below and no notifications will be sent
SMTP_HOST = "your_smtp_server_ssl"
SMTP_PORT = 587
SMTP_USER = "your_smtp_user"
SMTP_PASSWORD = "your_smtp_password"
SMTP_SSL = True
SENDER_EMAIL = "your_sender_email"
# SMTP_HOST = "your_smtp_server_plaintext"
# SMTP_PORT = 25
# SMTP_USER = "your_smtp_user"
# SMTP_PASSWORD = "your_smtp_password"
# SMTP_SSL = False
# SENDER_EMAIL = "your_sender_email"
RECEIVER_EMAIL = "your_receiver_email"
# How often do we perform checks for user activity, you can also use -c parameter; in seconds
SPOTIFY_CHECK_INTERVAL = 30 # 30 seconds
# After which time do we consider user as inactive (after last activity), you can also use -o parameter; in seconds
# Keep in mind if the user listens to songs longer than below timer then the tool will mark the user as inactive
SPOTIFY_INACTIVITY_CHECK = 660 # 11 mins
# What method should we use to play the song listened by the tracked user in local Spotify client under macOS
# (i.e. when -g / --track_songs functionality is enabled)
# Methods:
# "apple-script" (recommended)
# "trigger-url"
SPOTIFY_MACOS_PLAYING_METHOD = "apple-script"
# What method should we use to play the song listened by the tracked user in local Spotify client under Linux OS
# (i.e. when -g / --track_songs functionality is enabled)
# Methods:
# "dbus-send" (most common one)
# "qdbus"
# "trigger-url"
SPOTIFY_LINUX_PLAYING_METHOD = "dbus-send"
# What method should we use to play the song listened by the tracked user in local Spotify client under Windows OS
# (if -g / --track_songs functionality is enabled)
# Methods:
# "start-uri" (recommended)
# "spotify-cmd"
# "trigger-url"
SPOTIFY_WINDOWS_PLAYING_METHOD = "start-uri"
# How many consecutive plays of the same song is considered as being on loop
SONG_ON_LOOP_VALUE = 3
# When do we consider the song as being skipped; fraction
SKIPPED_SONG_THRESHOLD = 0.55 # song is treated as skipped if played for <=55% of track duration
# Sometimes the monitored Spotify user disappears from the list of recently active friends/buddies; it happens on few occasions:
# - you unfollowed the monitored user
# - issue with Spotify services
# - Spotify user listens on private mode and sometimes the Spotify client messes some things up
# - Spotify user was inactive for more than a week
# In such case we will continuously check for the user to reappear using the time interval below; in seconds
# You can also use -m parameter
SPOTIFY_DISAPPEARED_CHECK_INTERVAL = 120 # 2 mins
# Type Spotify ID of the "finishing" track to play when user gets offline, only needed for track_songs functionality;
# leave empty to simply pause
#SP_USER_GOT_OFFLINE_TRACK_ID = "5wCjNjnugSUqGDBrmQhn0e"
SP_USER_GOT_OFFLINE_TRACK_ID = ""
# Delay after which the above track gets paused, type 0 to play infinitely until user pauses manually; in seconds
SP_USER_GOT_OFFLINE_DELAY_BEFORE_PAUSE = 5 # 5 seconds
# How often do we perform alive check by printing "alive check" message in the output; in seconds
TOOL_ALIVE_INTERVAL = 21600 # 6 hours
# URL we check in the beginning to make sure we have internet connectivity
CHECK_INTERNET_URL = 'http://www.google.com/'
# Default value for initial checking of internet connectivity; in seconds
CHECK_INTERNET_TIMEOUT = 5
# The name of the .log file; the tool by default will output its messages to spotify_monitor_userid.log file
SP_LOGFILE = "spotify_monitor"
# Value used by signal handlers increasing/decreasing the inactivity check (SPOTIFY_INACTIVITY_CHECK); in seconds
SPOTIFY_INACTIVITY_CHECK_SIGNAL_VALUE = 30 # 30 seconds
# How many 50x errors need to show up in the defined time to display error message in the console - it is to suppress sporadic issues with Spotify API endpoint; adjust the parameters according to the SPOTIFY_CHECK_INTERVAL timer
# If more than 6 Spotify API related issues in 4 mins - we will show the error message
ERROR_500_NUMBER_LIMIT = 6
ERROR_500_TIME_LIMIT = 240 # 4 min
# How many network related errors need to show up in the defined time to display error message in the console - it is to suppress sporadic issues with internet connectivity; adjust the parameters according to the SPOTIFY_CHECK_INTERVAL timer
# If more than 6 network related issues in 4 mins - we will show the error message
ERROR_NETWORK_ISSUES_NUMBER_LIMIT = 6
ERROR_NETWORK_ISSUES_TIME_LIMIT = 240 # 4 min
# -------------------------
# CONFIGURATION SECTION END
# -------------------------
# Strings removed from track names for generating proper Genius search URLs
re_search_str = r'remaster|extended|original mix|remix|original soundtrack|radio( |-)edit|\(feat\.|( \(.*version\))|( - .*version)'
re_replace_str = r'( - (\d*)( )*remaster$)|( - (\d*)( )*remastered( version)*( \d*)*.*$)|( \((\d*)( )*remaster\)$)|( - (\d+) - remaster$)|( - extended$)|( - extended mix$)|( - (.*); extended mix$)|( - extended version$)|( - (.*) remix$)|( - remix$)|( - remixed by .*$)|( - original mix$)|( - .*original soundtrack$)|( - .*radio( |-)edit$)|( \(feat\. .*\)$)|( \(\d+.*Remaster.*\)$)|( \(.*Version\))|( - .*version)'
# Default value for network-related timeouts in functions + alarm signal handler; in seconds
FUNCTION_TIMEOUT = 15
TOOL_ALIVE_COUNTER = TOOL_ALIVE_INTERVAL / SPOTIFY_CHECK_INTERVAL
stdout_bck = None
csvfieldnames = ['Date', 'Artist', 'Track', 'Playlist', 'Album', 'Last activity']
active_notification = False
inactive_notification = False
song_notification = False
track_notification = False
song_on_loop_notification = False
# to solve the issue: 'SyntaxError: f-string expression part cannot include a backslash'
nl_ch = "\n"
import sys
import time
import string
import json
import os
from datetime import datetime
from dateutil import relativedelta
import calendar
import requests as req
import signal
import smtplib
import ssl
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import argparse
import csv
import urllib
import subprocess
import platform
import re
import ipaddress
from html import escape
# Logger class to output messages to stdout and log file
class Logger(object):
def __init__(self, filename):
self.terminal = sys.stdout
self.logfile = open(filename, "a", buffering=1, encoding="utf-8")
def write(self, message):
self.terminal.write(message)
self.logfile.write(message)
self.terminal.flush()
self.logfile.flush()
def flush(self):
pass
# Class used to generate timeout exceptions
class TimeoutException(Exception):
pass
# Signal handler for SIGALRM when the operation times out
def timeout_handler(sig, frame):
raise TimeoutException
# Signal handler when user presses Ctrl+C
def signal_handler(sig, frame):
sys.stdout = stdout_bck
print('\n* You pressed Ctrl+C, tool is terminated.')
sys.exit(0)
# Function to check internet connectivity
def check_internet():
url = CHECK_INTERNET_URL
try:
_ = req.get(url, timeout=CHECK_INTERNET_TIMEOUT)
print("OK")
return True
except Exception as e:
print(f"No connectivity, please check your network - {e}")
sys.exit(1)
return False
# Function to convert absolute value of seconds to human readable format
def display_time(seconds, granularity=2):
intervals = (
('years', 31556952), # approximation
('months', 2629746), # approximation
('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60
('minutes', 60),
('seconds', 1),
)
result = []
if seconds > 0:
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append(f"{value} {name}")
return ', '.join(result[:granularity])
else:
return '0 seconds'
# Function to calculate time span between two timestamps in seconds
def calculate_timespan(timestamp1, timestamp2, show_weeks=True, show_hours=True, show_minutes=True, show_seconds=True, granularity=3):
result = []
intervals = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds']
ts1 = timestamp1
ts2 = timestamp2
if type(timestamp1) is int:
dt1 = datetime.fromtimestamp(int(ts1))
elif type(timestamp1) is float:
ts1 = int(round(ts1))
dt1 = datetime.fromtimestamp(ts1)
elif type(timestamp1) is datetime:
dt1 = timestamp1
ts1 = int(round(dt1.timestamp()))
else:
return ""
if type(timestamp2) is int:
dt2 = datetime.fromtimestamp(int(ts2))
elif type(timestamp2) is float:
ts2 = int(round(ts2))
dt2 = datetime.fromtimestamp(ts2)
elif type(timestamp2) is datetime:
dt2 = timestamp2
ts2 = int(round(dt2.timestamp()))
else:
return ""
if ts1 >= ts2:
ts_diff = ts1 - ts2
else:
ts_diff = ts2 - ts1
dt1, dt2 = dt2, dt1
if ts_diff > 0:
date_diff = relativedelta.relativedelta(dt1, dt2)
years = date_diff.years
months = date_diff.months
weeks = date_diff.weeks
if not show_weeks:
weeks = 0
days = date_diff.days
if weeks > 0:
days = days - (weeks * 7)
hours = date_diff.hours
if (not show_hours and ts_diff > 86400):
hours = 0
minutes = date_diff.minutes
if (not show_minutes and ts_diff > 3600):
minutes = 0
seconds = date_diff.seconds
if (not show_seconds and ts_diff > 60):
seconds = 0
date_list = [years, months, weeks, days, hours, minutes, seconds]
for index, interval in enumerate(date_list):
if interval > 0:
name = intervals[index]
if interval == 1:
name = name.rstrip('s')
result.append(f"{interval} {name}")
return ', '.join(result[:granularity])
else:
return '0 seconds'
# Function to send email notification
def send_email(subject, body, body_html, use_ssl, smtp_timeout=15):
fqdn_re = re.compile(r'(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}\.?$)')
email_re = re.compile(r'[^@]+@[^@]+\.[^@]+')
try:
is_ip = ipaddress.ip_address(str(SMTP_HOST))
except ValueError:
if not fqdn_re.search(str(SMTP_HOST)):
print("Error sending email - SMTP settings are incorrect (invalid IP address/FQDN in SMTP_HOST)")
return 1
try:
port = int(SMTP_PORT)
if not (1 <= port <= 65535):
raise ValueError
except ValueError:
print("Error sending email - SMTP settings are incorrect (invalid port number in SMTP_PORT)")
return 1
if not email_re.search(str(SENDER_EMAIL)) or not email_re.search(str(RECEIVER_EMAIL)):
print("Error sending email - SMTP settings are incorrect (invalid email in SENDER_EMAIL or RECEIVER_EMAIL)")
return 1
if not SMTP_USER or not isinstance(SMTP_USER, str) or SMTP_USER == "your_smtp_user" or not SMTP_PASSWORD or not isinstance(SMTP_PASSWORD, str) or SMTP_PASSWORD == "your_smtp_password":
print("Error sending email - SMTP settings are incorrect (check SMTP_USER & SMTP_PASSWORD variables)")
return 1
if not subject or not isinstance(subject, str):
print("Error sending email - SMTP settings are incorrect (subject is not a string or is empty)")
return 1
if not body and not body_html:
print("Error sending email - SMTP settings are incorrect (body and body_html cannot be empty at the same time)")
return 1
try:
if use_ssl:
ssl_context = ssl.create_default_context()
smtpObj = smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=smtp_timeout)
smtpObj.starttls(context=ssl_context)
else:
smtpObj = smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=smtp_timeout)
smtpObj.login(SMTP_USER, SMTP_PASSWORD)
email_msg = MIMEMultipart('alternative')
email_msg["From"] = SENDER_EMAIL
email_msg["To"] = RECEIVER_EMAIL
email_msg["Subject"] = Header(subject, 'utf-8')
if body:
part1 = MIMEText(body, 'plain')
part1 = MIMEText(body.encode('utf-8'), 'plain', _charset='utf-8')
email_msg.attach(part1)
if body_html:
part2 = MIMEText(body_html, 'html')
part2 = MIMEText(body_html.encode('utf-8'), 'html', _charset='utf-8')
email_msg.attach(part2)
smtpObj.sendmail(SENDER_EMAIL, RECEIVER_EMAIL, email_msg.as_string())
smtpObj.quit()
except Exception as e:
print(f"Error sending email - {e}")
return 1
return 0
# Function to write CSV entry
def write_csv_entry(csv_file_name, timestamp, artist, track, playlist, album, last_activity_ts):
try:
csv_file = open(csv_file_name, 'a', newline='', buffering=1, encoding="utf-8")
csvwriter = csv.DictWriter(csv_file, fieldnames=csvfieldnames, quoting=csv.QUOTE_NONNUMERIC)
csvwriter.writerow({'Date': timestamp, 'Artist': artist, 'Track': track, 'Playlist': playlist, 'Album': album, 'Last activity': last_activity_ts})
csv_file.close()
except Exception as e:
raise
# Function to return the timestamp in human readable format; eg. Sun, 21 Apr 2024, 15:08:45
def get_cur_ts(ts_str=""):
return (f'{ts_str}{calendar.day_abbr[(datetime.fromtimestamp(int(time.time()))).weekday()]}, {datetime.fromtimestamp(int(time.time())).strftime("%d %b %Y, %H:%M:%S")}')
# Function to print the current timestamp in human readable format; eg. Sun, 21 Apr 2024, 15:08:45
def print_cur_ts(ts_str=""):
print(get_cur_ts(str(ts_str)))
print("---------------------------------------------------------------------------------------------------------")
# Function to return the timestamp/datetime object in human readable format (long version); eg. Sun, 21 Apr 2024, 15:08:45
def get_date_from_ts(ts):
if type(ts) is datetime:
ts_new = int(round(ts.timestamp()))
elif type(ts) is int:
ts_new = ts
elif type(ts) is float:
ts_new = int(round(ts))
else:
return ""
return (f'{calendar.day_abbr[(datetime.fromtimestamp(ts_new)).weekday()]} {datetime.fromtimestamp(ts_new).strftime("%d %b %Y, %H:%M:%S")}')
# Function to return the timestamp/datetime object in human readable format (short version); eg.
# Sun 21 Apr 15:08
# Sun 21 Apr 24, 15:08 (if show_year == True and current year is different)
# Sun 21 Apr (if show_hour == False)
def get_short_date_from_ts(ts, show_year=False, show_hour=True):
if type(ts) is datetime:
ts_new = int(round(ts.timestamp()))
elif type(ts) is int:
ts_new = ts
elif type(ts) is float:
ts_new = int(round(ts))
else:
return ""
if show_hour:
hour_strftime = " %H:%M"
else:
hour_strftime = ""
if show_year and int(datetime.fromtimestamp(ts_new).strftime("%Y")) != int(datetime.now().strftime("%Y")):
if show_hour:
hour_prefix = ","
else:
hour_prefix = ""
return (f'{calendar.day_abbr[(datetime.fromtimestamp(ts_new)).weekday()]} {datetime.fromtimestamp(ts_new).strftime(f"%d %b %y{hour_prefix}{hour_strftime}")}')
else:
return (f'{calendar.day_abbr[(datetime.fromtimestamp(ts_new)).weekday()]} {datetime.fromtimestamp(ts_new).strftime(f"%d %b{hour_strftime}")}')
# Function to return the timestamp/datetime object in human readable format (only hour, minutes and optionally seconds): eg. 15:08:12
def get_hour_min_from_ts(ts, show_seconds=False):
if type(ts) is datetime:
ts_new = int(round(ts.timestamp()))
elif type(ts) is int:
ts_new = ts
elif type(ts) is float:
ts_new = int(round(ts))
else:
return ""
if show_seconds:
out_strf = "%H:%M:%S"
else:
out_strf = "%H:%M"
return (str(datetime.fromtimestamp(ts_new).strftime(out_strf)))
# Function to return the range between two timestamps/datetime objects; eg. Sun 21 Apr 14:09 - 14:15
def get_range_of_dates_from_tss(ts1, ts2, between_sep=" - ", short=False):
if type(ts1) is datetime:
ts1_new = int(round(ts1.timestamp()))
elif type(ts1) is int:
ts1_new = ts1
elif type(ts1) is float:
ts1_new = int(round(ts1))
else:
return ""
if type(ts2) is datetime:
ts2_new = int(round(ts2.timestamp()))
elif type(ts2) is int:
ts2_new = ts2
elif type(ts2) is float:
ts2_new = int(round(ts2))
else:
return ""
ts1_strf = datetime.fromtimestamp(ts1_new).strftime("%Y%m%d")
ts2_strf = datetime.fromtimestamp(ts2_new).strftime("%Y%m%d")
if ts1_strf == ts2_strf:
if short:
out_str = f"{get_short_date_from_ts(ts1_new)}{between_sep}{get_hour_min_from_ts(ts2_new)}"
else:
out_str = f"{get_date_from_ts(ts1_new)}{between_sep}{get_hour_min_from_ts(ts2_new, show_seconds=True)}"
else:
if short:
out_str = f"{get_short_date_from_ts(ts1_new)}{between_sep}{get_short_date_from_ts(ts2_new)}"
else:
out_str = f"{get_date_from_ts(ts1_new)}{between_sep}{get_date_from_ts(ts2_new)}"
return (str(out_str))
# Signal handler for SIGUSR1 allowing to switch active/inactive email notifications
def toggle_active_inactive_notifications_signal_handler(sig, frame):
global active_notification
global inactive_notification
active_notification = not active_notification
inactive_notification = not inactive_notification
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Email notifications: [active = {active_notification}] [inactive = {inactive_notification}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGUSR2 allowing to switch every song email notifications
def toggle_song_notifications_signal_handler(sig, frame):
global song_notification
song_notification = not song_notification
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Email notifications: [every song = {song_notification}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGCONT allowing to switch tracked songs email notifications
def toggle_track_notifications_signal_handler(sig, frame):
global track_notification
track_notification = not track_notification
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Email notifications: [tracked = {track_notification}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGPIPE allowing to switch songs on loop email notifications
def toggle_songs_on_loop_notifications_signal_handler(sig, frame):
global song_on_loop_notification
song_on_loop_notification = not song_on_loop_notification
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Email notifications: [songs on loop = {song_on_loop_notification}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGTRAP allowing to increase inactivity check timer by SPOTIFY_INACTIVITY_CHECK_SIGNAL_VALUE seconds
def increase_inactivity_check_signal_handler(sig, frame):
global SPOTIFY_INACTIVITY_CHECK
SPOTIFY_INACTIVITY_CHECK = SPOTIFY_INACTIVITY_CHECK + SPOTIFY_INACTIVITY_CHECK_SIGNAL_VALUE
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Spotify timers: [inactivity: {display_time(SPOTIFY_INACTIVITY_CHECK)}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGABRT allowing to decrease inactivity check timer by SPOTIFY_INACTIVITY_CHECK_SIGNAL_VALUE seconds
def decrease_inactivity_check_signal_handler(sig, frame):
global SPOTIFY_INACTIVITY_CHECK
if SPOTIFY_INACTIVITY_CHECK - SPOTIFY_INACTIVITY_CHECK_SIGNAL_VALUE > 0:
SPOTIFY_INACTIVITY_CHECK = SPOTIFY_INACTIVITY_CHECK - SPOTIFY_INACTIVITY_CHECK_SIGNAL_VALUE
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Spotify timers: [inactivity: {display_time(SPOTIFY_INACTIVITY_CHECK)}]")
print_cur_ts("Timestamp:\t\t\t")
# Function preparing Apple & Genius search URLs for specified track
def get_apple_genius_search_urls(artist, track):
genius_search_string = f"{artist} {track}"
youtube_music_search_string = urllib.parse.quote_plus(f"{artist} {track}")
if re.search(re_search_str, genius_search_string, re.IGNORECASE):
genius_search_string = re.sub(re_replace_str, '', genius_search_string, flags=re.IGNORECASE)
apple_search_string = urllib.parse.quote(f"{artist} {track}")
apple_search_url = f"https://music.apple.com/pl/search?term={apple_search_string}"
genius_search_url = f"https://genius.com/search?q={urllib.parse.quote_plus(genius_search_string)}"
youtube_music_search_url = f"https://music.youtube.com/search?q={youtube_music_search_string}"
return apple_search_url, genius_search_url, youtube_music_search_url
# Function getting Spotify access token based on provided sp_dc cookie value
def spotify_get_access_token(sp_dc):
url = "https://open.spotify.com/get_access_token?reason=transport&productType=web_player"
cookies = {"sp_dc": sp_dc}
try:
response = req.get(url, cookies=cookies, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
return response.json().get("accessToken", "")
except Exception as e:
raise
# Function getting list of Spotify friends
def spotify_get_friends_json(access_token):
url = "https://guc-spclient.spotify.com/presence-view/v1/buddylist"
headers = {"Authorization": "Bearer " + access_token}
try:
response = req.get(url, headers=headers, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
friends_json = response.json()
error_str = friends_json.get("error")
if error_str:
raise ValueError(error_str)
return friends_json
except Exception as e:
raise
# Function converting Spotify URI (e.g. spotify:user:username) to URL (e.g. https://open.spotify.com/user/username)
def spotify_convert_uri_to_url(uri):
# add si parameter so link opens in native Spotify app after clicking
si = "?si=1"
# si=""
url = ""
if "spotify:user:" in uri:
s_id = uri.split(':', 2)[2]
url = f"https://open.spotify.com/user/{s_id}{si}"
elif "spotify:artist:" in uri:
s_id = uri.split(':', 2)[2]
url = f"https://open.spotify.com/artist/{s_id}{si}"
elif "spotify:track:" in uri:
s_id = uri.split(':', 2)[2]
url = f"https://open.spotify.com/track/{s_id}{si}"
elif "spotify:album:" in uri:
s_id = uri.split(':', 2)[2]
url = f"https://open.spotify.com/album/{s_id}{si}"
elif "spotify:playlist:" in uri:
s_id = uri.split(':', 2)[2]
url = f"https://open.spotify.com/playlist/{s_id}{si}"
return url
# Function printing the list of Spotify friends with the last listened track
def spotify_list_friends(friend_activity):
for friend in friend_activity["friends"]:
sp_uri = friend["user"].get("uri").split("spotify:user:", 1)[1]
sp_username = friend["user"].get("name")
sp_artist = friend["track"]["artist"].get("name")
sp_album = friend["track"]["album"].get("name")
sp_playlist = friend["track"]["context"].get("name")
sp_track = friend["track"].get("name")
sp_ts = friend.get("timestamp")
sp_album_uri = friend["track"]["album"].get("uri")
sp_playlist_uri = friend["track"]["context"].get("uri")
sp_track_uri = friend["track"].get("uri")
print("---------------------------------------------------------------------------------------------------------")
print(f"Username:\t\t\t{sp_username}")
print(f"User URI ID:\t\t\t{sp_uri}")
print(f"\nLast played:\t\t\t{sp_artist} - {sp_track}\n")
if 'spotify:playlist:' in sp_playlist_uri:
print(f"Playlist:\t\t\t{sp_playlist}")
print(f"Album:\t\t\t\t{sp_album}")
if 'spotify:album:' in sp_playlist_uri and sp_playlist != sp_album:
print(f"\nContext (Album):\t\t{sp_playlist}")
if 'spotify:artist:' in sp_playlist_uri:
print(f"\nContext (Artist):\t\t{sp_playlist}")
print(f"\nTrack URL:\t\t\t{spotify_convert_uri_to_url(sp_track_uri)}")
if 'spotify:playlist:' in sp_playlist_uri:
print(f"Playlist URL:\t\t\t{spotify_convert_uri_to_url(sp_playlist_uri)}")
print(f"Album URL:\t\t\t{spotify_convert_uri_to_url(sp_album_uri)}")
if 'spotify:album:' in sp_playlist_uri and sp_playlist != sp_album:
print(f"Context (Album) URL:\t\t{spotify_convert_uri_to_url(sp_playlist_uri)}")
if 'spotify:artist:' in sp_playlist_uri:
print(f"Context (Artist) URL:\t\t{spotify_convert_uri_to_url(sp_playlist_uri)}")
apple_search_url, genius_search_url, youtube_music_search_url = get_apple_genius_search_urls(str(sp_artist), str(sp_track))
print(f"Apple search URL:\t\t{apple_search_url}")
print(f"YouTube Music search URL:\t{youtube_music_search_url}")
print(f"Genius lyrics URL:\t\t{genius_search_url}")
print(f"\nLast activity:\t\t\t{get_date_from_ts(float(str(sp_ts)[0:-3]))} ({calculate_timespan(int(time.time()), datetime.fromtimestamp(float(str(sp_ts)[0:-3])))} ago)")
# Function returning information for specific Spotify friend's user URI id
def spotify_get_friend_info(friend_activity, uri):
for friend in friend_activity["friends"]:
sp_uri = friend["user"]["uri"].split("spotify:user:", 1)[1]
if sp_uri == uri:
sp_username = friend["user"].get("name")
sp_artist = friend["track"]["artist"].get("name")
sp_album = friend["track"]["album"].get("name")
sp_album_uri = friend["track"]["album"].get("uri")
sp_playlist = friend["track"]["context"].get("name")
sp_playlist_uri = friend["track"]["context"].get("uri")
sp_track = friend["track"].get("name")
sp_track_uri = str(friend["track"].get("uri"))
if "spotify:track:" in sp_track_uri:
sp_track_uri_id = sp_track_uri.split(':', 2)[2]
else:
sp_track_uri_id = ""
sp_ts = int(str(friend.get("timestamp"))[0:-3])
return True, {"sp_uri": sp_uri, "sp_username": sp_username, "sp_artist": sp_artist, "sp_track": sp_track, "sp_track_uri": sp_track_uri, "sp_track_uri_id": sp_track_uri_id, "sp_album": sp_album, "sp_album_uri": sp_album_uri, "sp_playlist": sp_playlist, "sp_playlist_uri": sp_playlist_uri, "sp_ts": sp_ts}
return False, {}
# Function returning information for specific Spotify track URI
def spotify_get_track_info(access_token, track_uri):
track_id = track_uri.split(':', 2)[2]
url = "https://api.spotify.com/v1/tracks/" + track_id
headers = {"Authorization": "Bearer " + access_token}
# add si parameter so link opens in native Spotify app after clicking
si = "?si=1"
try:
response = req.get(url, headers=headers, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
json_response = response.json()
sp_track_duration = int(json_response.get("duration_ms") / 1000)
sp_track_url = json_response["external_urls"].get("spotify") + si
sp_track_name = json_response.get("name")
sp_artist_url = json_response["artists"][0]["external_urls"].get("spotify") + si
sp_artist_name = json_response["artists"][0].get("name")
sp_album_url = json_response["album"]["external_urls"].get("spotify") + si
sp_album_name = json_response["album"].get("name")
return {"sp_track_duration": sp_track_duration, "sp_track_url": sp_track_url, "sp_artist_url": sp_artist_url, "sp_album_url": sp_album_url, "sp_track_name": sp_track_name, "sp_artist_name": sp_artist_name, "sp_album_name": sp_album_name}
except Exception as e:
raise
# Function returning information for specific Spotify playlist URI
def spotify_get_playlist_info(access_token, playlist_uri):
playlist_id = playlist_uri.split(':', 2)[2]
url = f"https://api.spotify.com/v1/playlists/{playlist_id}?fields=name,owner,followers,external_urls"
headers = {"Authorization": "Bearer " + access_token}
# add si parameter so link opens in native Spotify app after clicking
si = "?si=1"
try:
response = req.get(url, headers=headers, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
json_response = response.json()
sp_playlist_name = json_response.get("name")
sp_playlist_owner = json_response["owner"].get("display_name")
sp_playlist_owner_url = json_response["owner"]["external_urls"].get("spotify")
sp_playlist_followers = int(json_response["followers"].get("total"))
sp_playlist_url = json_response["external_urls"].get("spotify") + si
return {"sp_playlist_name": sp_playlist_name, "sp_playlist_owner": sp_playlist_owner, "sp_playlist_owner_url": sp_playlist_owner_url, "sp_playlist_followers": sp_playlist_followers, "sp_playlist_url": sp_playlist_url}
except Exception as e:
raise
def spotify_macos_play_song(sp_track_uri_id, method=SPOTIFY_MACOS_PLAYING_METHOD):
if method == "apple-script": # apple-script
script = f'tell app "Spotify" to play track "spotify:track:{sp_track_uri_id}"'
proc = subprocess.Popen(['osascript', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = proc.communicate(script)
else: # trigger-url - just trigger track URL in the client
subprocess.call(('open', spotify_convert_uri_to_url(f"spotify:track:{sp_track_uri_id}")))
def spotify_macos_play_pause(action, method=SPOTIFY_MACOS_PLAYING_METHOD):
if method == "apple-script": # apple-script
if str(action).lower() == "pause":
script = 'tell app "Spotify" to pause'
proc = subprocess.Popen(['osascript', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = proc.communicate(script)
elif str(action).lower() == "play":
script = 'tell app "Spotify" to play'
proc = subprocess.Popen(['osascript', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = proc.communicate(script)
def spotify_linux_play_song(sp_track_uri_id, method=SPOTIFY_LINUX_PLAYING_METHOD):
if method == "dbus-send": # dbus-send
subprocess.call((f"dbus-send --type=method_call --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.OpenUri string:'spotify:track:{sp_track_uri_id}'"), shell=True)
elif method == "qdbus": # qdbus
subprocess.call((f"qdbus org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.OpenUri spotify:track:{sp_track_uri_id}"), shell=True)
else: # trigger-url - just trigger track URL in the client
subprocess.call(('xdg-open', spotify_convert_uri_to_url(f"spotify:track:{sp_track_uri_id}")), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
def spotify_linux_play_pause(action, method=SPOTIFY_LINUX_PLAYING_METHOD):
if method == "dbus-send": # dbus-send
if str(action).lower() == "pause":
subprocess.call((f"dbus-send --type=method_call --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Pause"), shell=True)
elif str(action).lower() == "play":
subprocess.call((f"dbus-send --type=method_call --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Play"), shell=True)
elif method == "qdbus": # qdbus
if str(action).lower() == "pause":
subprocess.call((f"qdbus org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Pause"), shell=True)
elif str(action).lower() == "play":
subprocess.call((f"qdbus org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Play"), shell=True)
def spotify_win_play_song(sp_track_uri_id, method=SPOTIFY_WINDOWS_PLAYING_METHOD):
WIN_SPOTIFY_APP_PATH = r'%APPDATA%\Spotify\Spotify.exe'
if method == "start-uri": # start-uri
subprocess.call((f"start spotify:track:{sp_track_uri_id}"), shell=True)
elif method == "spotify-cmd": # spotify-cmd
subprocess.call((f"{WIN_SPOTIFY_APP_PATH} --uri=spotify:track:{sp_track_uri_id}"), shell=True)
else: # trigger-url - just trigger track URL in the client
os.startfile(spotify_convert_uri_to_url(f"spotify:track:{sp_track_uri_id}"))
# Main function monitoring activity of the specified Spotify friend's user URI ID
def spotify_monitor_friend_uri(user_uri_id, tracks, error_notification, csv_file_name, csv_exists):
sp_active_ts_start = 0
sp_active_ts_stop = 0
sp_active_ts_start_old = 0
user_not_found = False
listened_songs = 0
listened_songs_old = 0
looped_songs = 0
looped_songs_old = 0
skipped_songs = 0
skipped_songs_old = 0
sp_artist_old = ""
sp_track_old = ""
song_on_loop = 0
error_500_counter = 0
error_500_start_ts = 0
error_network_issue_counter = 0
error_network_issue_start_ts = 0
try:
if csv_file_name:
csv_file = open(csv_file_name, 'a', newline='', buffering=1, encoding="utf-8")
csvwriter = csv.DictWriter(csv_file, fieldnames=csvfieldnames, quoting=csv.QUOTE_NONNUMERIC)
if not csv_exists:
csvwriter.writeheader()
csv_file.close()
except Exception as e:
print(f"* Error - {e}")
email_sent = False
# Main loop
while True:
# Sometimes Spotify network functions halt even though we specified the timeout
# To overcome this we use alarm signal functionality to kill it inevitably, not available on Windows
if platform.system() != 'Windows':
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(FUNCTION_TIMEOUT)
try:
sp_accessToken = spotify_get_access_token(SP_DC_COOKIE)
sp_friends = spotify_get_friends_json(sp_accessToken)
sp_found, sp_data = spotify_get_friend_info(sp_friends, user_uri_id)
email_sent = False
if platform.system() != 'Windows':
signal.alarm(0)
except TimeoutException:
if platform.system() != 'Windows':
signal.alarm(0)
print(f"spotify_*() function timeout, retrying in {display_time(FUNCTION_TIMEOUT)}")
print_cur_ts("Timestamp:\t\t\t")
time.sleep(FUNCTION_TIMEOUT)
continue
except Exception as e:
if platform.system() != 'Windows':
signal.alarm(0)
print(f"Error, retrying in {display_time(SPOTIFY_CHECK_INTERVAL)} - {e}")
if ('access token' in str(e)) or ('Unauthorized' in str(e)):
print("* sp_dc might have expired!")
if error_notification and not email_sent:
m_subject = f"spotify_monitor: sp_dc might have expired! (uri: {user_uri_id})"
m_body = f"sp_dc might have expired: {e}{get_cur_ts(nl_ch + nl_ch + 'Timestamp: ')}"
m_body_html = f"<html><head></head><body>sp_dc might have expired: {escape(str(e))}{get_cur_ts('<br><br>Timestamp: ')}</body></html>"
print(f"Sending email notification to {RECEIVER_EMAIL}")
send_email(m_subject, m_body, m_body_html, SMTP_SSL)
email_sent = True
print_cur_ts("Timestamp:\t\t\t")
time.sleep(SPOTIFY_CHECK_INTERVAL)
continue
playlist_m_body = ""
playlist_m_body_html = ""
played_for_m_body = ""
played_for_m_body_html = ""
is_playlist = False
# User is found in the Spotify's friend list just after starting the tool
if sp_found:
user_not_found = False
print("* User found, starting monitoring ....")
sp_track_uri = sp_data["sp_track_uri"]
sp_track_uri_id = sp_data["sp_track_uri_id"]
sp_album_uri = sp_data["sp_album_uri"]
sp_playlist_uri = sp_data["sp_playlist_uri"]
sp_playlist_data = {}
try:
sp_track_data = spotify_get_track_info(sp_accessToken, sp_track_uri)
if 'spotify:playlist:' in sp_playlist_uri:
is_playlist = True
sp_playlist_data = spotify_get_playlist_info(sp_accessToken, sp_playlist_uri)
if not sp_playlist_data:
is_playlist = False
else:
is_playlist = False
except Exception as e:
print(f"Error, retrying in {display_time(SPOTIFY_CHECK_INTERVAL)} - {e}")
print_cur_ts("Timestamp:\t\t\t")
time.sleep(SPOTIFY_CHECK_INTERVAL)
continue
sp_username = sp_data["sp_username"]
sp_artist = sp_data["sp_artist"]
if not sp_artist:
sp_artist = sp_track_data["sp_artist_name"]
sp_track = sp_data["sp_track"]
if not sp_track:
sp_track = sp_track_data["sp_track_name"]
sp_playlist = sp_data["sp_playlist"]
sp_album = sp_data["sp_album"]
if not sp_album:
sp_album = sp_track_data["sp_album_name"]
sp_ts = sp_data["sp_ts"]
cur_ts = int(time.time())
sp_track_duration = sp_track_data["sp_track_duration"]
sp_track_url = sp_track_data["sp_track_url"]
sp_artist_url = sp_track_data["sp_artist_url"]
sp_album_url = sp_track_data["sp_album_url"]
sp_playlist_url = ""
if is_playlist:
sp_playlist_url = sp_playlist_data.get("sp_playlist_url")
playlist_m_body = f"\nPlaylist: {sp_playlist}"
playlist_m_body_html = f"<br>Playlist: <a href=\"{sp_playlist_url}\">{escape(sp_playlist)}</a>"
print(f"\nUsername:\t\t\t{sp_username}")
print(f"User URI ID:\t\t\t{sp_data['sp_uri']}")
print(f"\nLast played:\t\t\t{sp_artist} - {sp_track}")
print(f"Duration:\t\t\t{display_time(sp_track_duration)}\n")
if is_playlist:
print(f"Playlist:\t\t\t{sp_playlist}")
print(f"Album:\t\t\t\t{sp_album}")
context_m_body = ""
context_m_body_html = ""
if 'spotify:album:' in sp_playlist_uri and sp_playlist != sp_album:
print(f"\nContext (Album):\t\t{sp_playlist}")
context_m_body += f"\nContext (Album): {sp_playlist}"
context_m_body_html += f"<br>Context (Album): <a href=\"{spotify_convert_uri_to_url(sp_playlist_uri)}\">{escape(sp_playlist)}</a>"
if 'spotify:artist:' in sp_playlist_uri:
print(f"\nContext (Artist):\t\t{sp_playlist}")
context_m_body += f"\nContext (Artist): {sp_playlist}"
context_m_body_html += f"<br>Context (Artist): <a href=\"{spotify_convert_uri_to_url(sp_playlist_uri)}\">{escape(sp_playlist)}</a>"
print(f"\nTrack URL:\t\t\t{sp_track_url}")
if is_playlist:
print(f"Playlist URL:\t\t\t{sp_playlist_url}")
print(f"Album URL:\t\t\t{sp_album_url}")
if 'spotify:album:' in sp_playlist_uri and sp_playlist != sp_album:
print(f"Context (Album) URL:\t\t{spotify_convert_uri_to_url(sp_playlist_uri)}")
if 'spotify:artist:' in sp_playlist_uri:
print(f"Context (Artist) URL:\t\t{spotify_convert_uri_to_url(sp_playlist_uri)}")
apple_search_url, genius_search_url, youtube_music_search_url = get_apple_genius_search_urls(str(sp_artist), str(sp_track))
print(f"Apple search URL:\t\t{apple_search_url}")
print(f"YouTube Music search URL:\t{youtube_music_search_url}")
print(f"Genius lyrics URL:\t\t{genius_search_url}")
if not is_playlist:
sp_playlist = ""
print(f"\nLast activity:\t\t\t{get_date_from_ts(sp_ts)}")
# Friend is currently active (listens to music)
if (cur_ts - sp_ts) <= SPOTIFY_INACTIVITY_CHECK:
sp_active_ts_start = sp_ts - sp_track_duration
sp_active_ts_stop = 0
listened_songs = 1
song_on_loop = 1
print("\n*** Friend is currently ACTIVE !")
if sp_track.upper() in map(str.upper, tracks) or sp_playlist.upper() in map(str.upper, tracks) or sp_album.upper() in map(str.upper, tracks):
print("*** Track/playlist/album matched with the list!")
try:
if csv_file_name:
write_csv_entry(csv_file_name, datetime.fromtimestamp(int(cur_ts)), sp_artist, sp_track, sp_playlist, sp_album, datetime.fromtimestamp(int(sp_ts)))
except Exception as e:
print(f"* Cannot write CSV entry - {e}")
if active_notification:
m_subject = f"Spotify user {sp_username} is active: '{sp_artist} - {sp_track}'"
m_body = f"Last played: {sp_artist} - {sp_track}\nDuration: {display_time(sp_track_duration)}{playlist_m_body}\nAlbum: {sp_album}{context_m_body}\n\nApple search URL: {apple_search_url}\nYouTube Music search URL:{youtube_music_search_url}\nGenius lyrics URL: {genius_search_url}\n\nLast activity: {get_date_from_ts(sp_ts)}{get_cur_ts(nl_ch + 'Timestamp: ')}"
m_body_html = f"<html><head></head><body>Last played: <b><a href=\"{sp_artist_url}\">{escape(sp_artist)}</a> - <a href=\"{sp_track_url}\">{escape(sp_track)}</a></b><br>Duration: {display_time(sp_track_duration)}{playlist_m_body_html}<br>Album: <a href=\"{sp_album_url}\">{escape(sp_album)}</a>{context_m_body_html}<br><br>Apple search URL: <a href=\"{apple_search_url}\">{escape(sp_artist)} - {escape(sp_track)}</a><br>YouTube Music search URL: <a href=\"{youtube_music_search_url}\">{escape(sp_artist)} - {escape(sp_track)}</a><br>Genius lyrics URL: <a href=\"{genius_search_url}\">{escape(sp_artist)} - {escape(sp_track)}</a><br><br>Last activity: {get_date_from_ts(sp_ts)}{get_cur_ts('<br>Timestamp: ')}</body></html>"
print(f"Sending email notification to {RECEIVER_EMAIL}")
send_email(m_subject, m_body, m_body_html, SMTP_SSL)
if track_songs and sp_track_uri_id:
if platform.system() == 'Darwin': # macOS
spotify_macos_play_song(sp_track_uri_id)
elif platform.system() == 'Windows': # Windows
spotify_win_play_song(sp_track_uri_id)