-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlastfm_monitor.py
1806 lines (1512 loc) · 95.8 KB
/
lastfm_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 <misiektoja-github@rm-rf.ninja>
v1.9
Tool implementing real-time tracking of Last.fm users music activity:
https://github.com/misiektoja/lastfm_monitor/
Python pip3 requirements:
pylast
python-dateutil
requests
urllib3
"""
VERSION = 1.9
# ---------------------------
# CONFIGURATION SECTION START
# ---------------------------
# Create your Last.fm 'API key' and 'Shared secret' by going to: https://www.last.fm/api/account/create
# Or get your existing one from: https://www.last.fm/api/accounts
# Put the respective values below (or use -u and -w parameters)
LASTFM_API_KEY = "your_lastfm_api_key" # Last.fm API key
LASTFM_API_SECRET = "your_lastfm_api_secret" # Last.fm Shared secret
# This setting is optional and only needed if you want to get track duration from Spotify (-r option, more accurate than Last.fm) or
# if you want to use -g / --track_songs functionality, so we can find Spotify track ID and play it in your Spotify client
#
# Log in to Spotify web client (https://open.spotify.com/) and put the value of sp_dc cookie below (or use -z 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 when considered offline (not playing music right now); in seconds
# You can also use -c parameter
LASTFM_CHECK_INTERVAL = 10 # 10 seconds
# How often do we perform checks for user activity when online (playing music right now); in seconds
# You can also use -k parameter
LASTFM_ACTIVE_CHECK_INTERVAL = 3 # 3 seconds
# After which time do we consider user as inactive (after last activity); in seconds
# You can also use -o parameter
LASTFM_INACTIVITY_CHECK = 180 # 3 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; this parameter is used if track duration is NOT available from Last.fm; in seconds
SKIPPED_SONG_THRESHOLD1 = 35 # song is treated as skipped if played for <=35 seconds
# When do we consider the song as being skipped; this parameter is used if track duration is available from Last.fm; fraction
SKIPPED_SONG_THRESHOLD2 = 0.55 # song is treated as skipped if played for <=55% of track duration
# When do we consider the song as being played for longer than track duration; it will happen either if the play time is longer than 130% of track duration of if more than 30 seconds; fraction and seconds
LONGER_SONG_THRESHOLD1 = 1.30 # song is treated as being played longer than track duration if played longer than >= 130% of track duration
LONGER_SONG_THRESHOLD2 = 30 # song is treated as being played longer than track duration if played longer than >= 30 seconds of track duration
# Set the value of the variable below to True if you want to get the track duration from Spotify
# It is recommended since Last.fm very often does not have it or has inaccurate info
# We will try to get track duration from Spotify only if you have defined proper SP_DC_COOKIE value earlier (or via -z parameter)
# You can also use -r parameter
USE_TRACK_DURATION_FROM_SPOTIFY = False
# 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
# If the value is more than 0 it will show when user stops playing/resumes (while active), play break is assumed to be LASTFM_BREAK_CHECK_MULTIPLIER*LASTFM_ACTIVE_CHECK_INTERVAL;
# So if LASTFM_BREAK_CHECK_MULTIPLIER = 4 and LASTFM_ACTIVE_CHECK_INTERVAL = 3, then music pause will be reported after 4*3=12 seconds of inactivity
# You can also use -m parameter
LASTFM_BREAK_CHECK_MULTIPLIER = 4
# 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 lastfm_monitor_username.log file
LF_LOGFILE = "lastfm_monitor"
# Value used by signal handlers increasing/decreasing the inactivity check (LASTFM_INACTIVITY_CHECK); in seconds
LASTFM_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 Last.fm API endpoint; adjust the parameters according to the LASTFM_CHECK_INTERVAL & LASTFM_ACTIVE_CHECK_INTERVAL timers
# If more than 15 Last.fm API related issues in 2 mins - we will show the error message
ERROR_500_NUMBER_LIMIT = 15
ERROR_500_TIME_LIMIT = 120 # 2 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 LASTFM_CHECK_INTERVAL & LASTFM_ACTIVE_CHECK_INTERVAL timers
# If more than 15 network related issues in 2 mins - we will show the error message
ERROR_NETWORK_ISSUES_NUMBER_LIMIT = 15
ERROR_NETWORK_ISSUES_TIME_LIMIT = 120 # 2 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 Spotify network-related timeouts in functions; in seconds
FUNCTION_TIMEOUT = 5 # 5 seconds
# How many recent tracks we fetch after start and every time user gets online
RECENT_TRACKS_NUMBER = 10
TOOL_ALIVE_COUNTER = TOOL_ALIVE_INTERVAL / LASTFM_CHECK_INTERVAL
stdout_bck = None
csvfieldnames = ['Date', 'Artist', 'Track', 'Album']
active_notification = False
inactive_notification = False
song_notification = False
track_notification = False
offline_entries_notification = False
song_on_loop_notification = False
progress_indicator = False
track_songs = False
do_not_show_duration_marks = False
# to solve the issue: 'SyntaxError: f-string expression part cannot include a backslash'
nl_ch = "\n"
import sys
if sys.version_info < (3, 8):
print("* Error: Python version 3.8 or higher required !")
sys.exit(1)
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 pylast
import urllib
import subprocess
import platform
import re
import ipaddress
from itertools import tee, islice, chain
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
# 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)
# 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, album):
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, 'Album': album})
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/offline entries email notifications
def toggle_active_inactive_notifications_signal_handler(sig, frame):
global active_notification
global inactive_notification
global offline_entries_notification
active_notification = not active_notification
inactive_notification = not inactive_notification
offline_entries_notification = not offline_entries_notification
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Email notifications: [active = {active_notification}] [inactive = {inactive_notification}] [offline entries = {offline_entries_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 SIGHUP allowing to switch progress indicator in the output
def toggle_progress_indicator_signal_handler(sig, frame):
global progress_indicator
progress_indicator = not progress_indicator
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Progress indicator enabled: {progress_indicator}")
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 interval by LASTFM_INACTIVITY_CHECK_SIGNAL_VALUE seconds
def increase_inactivity_check_signal_handler(sig, frame):
global LASTFM_INACTIVITY_CHECK
LASTFM_INACTIVITY_CHECK = LASTFM_INACTIVITY_CHECK + LASTFM_INACTIVITY_CHECK_SIGNAL_VALUE
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Last.fm timers: [inactivity: {display_time(LASTFM_INACTIVITY_CHECK)}]")
print_cur_ts("Timestamp:\t\t\t")
# Signal handler for SIGABRT allowing to decrease inactivity check interval by LASTFM_INACTIVITY_CHECK_SIGNAL_VALUE seconds
def decrease_inactivity_check_signal_handler(sig, frame):
global LASTFM_INACTIVITY_CHECK
if LASTFM_INACTIVITY_CHECK - LASTFM_INACTIVITY_CHECK_SIGNAL_VALUE > 0:
LASTFM_INACTIVITY_CHECK = LASTFM_INACTIVITY_CHECK - LASTFM_INACTIVITY_CHECK_SIGNAL_VALUE
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Last.fm timers: [inactivity: {display_time(LASTFM_INACTIVITY_CHECK)}]")
print_cur_ts("Timestamp:\t\t\t")
# Function to access the previous and next elements of the list
def previous_and_next(some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
return zip(prevs, items, nexts)
# Function preparing Spotify, Apple & Genius search URLs for specified track
def get_spotify_apple_genius_search_urls(artist, track):
spotify_search_string = urllib.parse.quote_plus(f"{artist} {track}")
genius_search_string = 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}")
spotify_search_url = f"https://open.spotify.com/search/{spotify_search_string}?si=1"
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={spotify_search_string}"
return spotify_search_url, apple_search_url, genius_search_url, youtube_music_search_url
# Function returning the list of recently played Last.fm tracks
def lastfm_get_recent_tracks(username, network, number):
try:
recent_tracks = network.get_user(username).get_recent_tracks(limit=number)
return recent_tracks
except Exception as e:
raise
# Function displaying the list of recently played Last.fm tracks
def lastfm_list_tracks(username, user, network, number):
try:
new_track = user.get_now_playing()
recent_tracks = lastfm_get_recent_tracks(username, network, number)
except Exception as e:
print(f"* Error: cannot display recent tracks for the user - {e}")
sys.exit(1)
last_played = 0
i = 0
p = 0
duplicate_entries = False
for previous, t, nxt in previous_and_next(reversed(recent_tracks)):
i += 1
if i == len(recent_tracks):
last_played = int(t.timestamp)
print(f'{i}\t{datetime.fromtimestamp(int(t.timestamp)).strftime("%d %b %Y, %H:%M:%S")}\t{calendar.day_abbr[(datetime.fromtimestamp(int(t.timestamp))).weekday()]}\t{t.track}')
if previous:
if previous.timestamp == t.timestamp:
p += 1
duplicate_entries = True
print("DUPLICATE ENTRY")
print("---------------------------------------------------------------------------------------------------------")
if last_played > 0 and not new_track:
print(f"*** User played last time {calculate_timespan(int(time.time()), last_played, show_seconds=True)} ago! ({get_date_from_ts(last_played)})")
if duplicate_entries:
print(f"*** Duplicate entries ({p}) found, possible PRIVATE MODE")
if new_track:
artist = str(new_track.artist)
track = str(new_track.title)
album = str(new_track.info['album'])
print("*** User is currently ACTIVE !")
print(f"\nTrack:\t\t{artist} - {track}")
print(f"Album:\t\t{album}")
# 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}
access_token = ""
try:
response = req.get(url, cookies=cookies, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
access_token = response.json().get("accessToken", "")
except Exception as e:
print(f"spotify_get_access_token error - {e}")
return access_token
# 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 processing track items returned by Spotify search Web API
def spotify_search_process_track_items(track_items, track):
sp_track_uri_id = None
sp_track_duration = 0
for item in track_items:
if str(item.get("name")).lower() == str(track).lower():
sp_track_uri_id = item.get("id")
sp_track_duration = int(item.get("duration_ms") / 1000)
break
if not sp_track_uri_id:
for item in track_items:
if str(track).lower() in str(item.get("name")).lower():
sp_track_uri_id = item.get("id")
sp_track_duration = int(item.get("duration_ms") / 1000)
break
return sp_track_uri_id, sp_track_duration
# Function returning Spotify track ID & duration for specific artist, track and optionally album
def spotify_search_song_trackid_duration(access_token, artist, track, album=""):
re_chars_to_remove = r'([\'])'
artist_sanitized = re.sub(re_chars_to_remove, '', artist, flags=re.IGNORECASE)
track_sanitized = re.sub(re_chars_to_remove, '', track, flags=re.IGNORECASE)
album_sanitized = re.sub(re_chars_to_remove, '', album, flags=re.IGNORECASE)
url1 = f'https://api.spotify.com/v1/search?q={urllib.parse.quote_plus(f"artist:{artist_sanitized} track:{track_sanitized} album:{album_sanitized}")}&type=track&limit=5'
url2 = f'https://api.spotify.com/v1/search?q={urllib.parse.quote_plus(f"artist:{artist_sanitized} track:{track_sanitized}")}&type=track&limit=5'
headers = {"Authorization": "Bearer " + access_token}
sp_track_uri_id = None
sp_track_duration = 0
if album:
try:
response = req.get(url1, headers=headers, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
json_response = response.json()
if json_response.get("tracks"):
if json_response["tracks"].get("total") > 0:
sp_track_uri_id, sp_track_duration = spotify_search_process_track_items(json_response["tracks"]["items"], track)
except Exception as e:
pass
if not sp_track_uri_id:
try:
response = req.get(url2, headers=headers, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
json_response = response.json()
if json_response.get("tracks"):
if json_response["tracks"].get("total") > 0:
sp_track_uri_id, sp_track_duration = spotify_search_process_track_items(json_response["tracks"]["items"], track)
except Exception as e:
pass
return sp_track_uri_id, sp_track_duration
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 Last.fm user
def lastfm_monitor_user(user, network, username, tracks, error_notification, csv_file_name, csv_exists):
lf_active_ts_start = 0
lf_active_ts_last = 0
lf_track_ts_start = 0
lf_track_ts_start_old = 0
lf_track_ts_start_after_resume = 0
lf_user_online = False
alive_counter = 0
track_duration = 0
playing_paused = False
playing_paused_ts = 0
playing_resumed_ts = 0
paused_counter = 0
playing_track = None
new_track = None
listened_songs = 0
looped_songs = 0
skipped_songs = 0
signal_previous_the_same = False
artist = ""
track = ""
artist_old = ""
track_old = ""
song_on_loop = 0
sp_track_uri_id = None
sp_track_duration = 0
duration_mark = ""
pauses_number = 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}")
lastfm_last_activity_file = f"lastfm_{username}_last_activity.json"
last_activity_read = []
last_activity_ts = 0
last_activity_artist = ""
last_activity_track = ""
if os.path.isfile(lastfm_last_activity_file):
try:
with open(lastfm_last_activity_file, 'r', encoding="utf-8") as f:
last_activity_read = json.load(f)
except Exception as e:
print(f"* Cannot load last status from '{lastfm_last_activity_file}' file - {e}")
if last_activity_read:
last_activity_ts = last_activity_read[0]
last_activity_artist = last_activity_read[1]
last_activity_track = last_activity_read[2]
lastfm_last_activity_file_mdate_dt = datetime.fromtimestamp(int(os.path.getmtime(lastfm_last_activity_file)))
lastfm_last_activity_file_mdate = lastfm_last_activity_file_mdate_dt.strftime("%d %b %Y, %H:%M:%S")
lastfm_last_activity_file_mdate_weekday = str(calendar.day_abbr[(lastfm_last_activity_file_mdate_dt).weekday()])
print(f"* Last activity loaded from file '{lastfm_last_activity_file}' ({lastfm_last_activity_file_mdate_weekday} {lastfm_last_activity_file_mdate})")
try:
new_track = user.get_now_playing()
recent_tracks = lastfm_get_recent_tracks(username, network, RECENT_TRACKS_NUMBER)
except Exception as e:
print(f"* Error - {e}")
sys.exit(1)
last_track_start_ts_old2 = int(recent_tracks[0].timestamp)
lf_track_ts_start_old = last_track_start_ts_old2
# User is offline (does not play music at the moment)
if new_track is None:
app_started_and_user_offline = True
playing_track = None
last_track_start_ts_old = 0
lf_user_online = False
lf_active_ts_last = int(recent_tracks[0].timestamp)
if lf_active_ts_last >= last_activity_ts:
last_activity_artist = recent_tracks[0].track.artist
last_activity_track = recent_tracks[0].track.title
elif lf_active_ts_last < last_activity_ts and last_activity_ts > 0:
lf_active_ts_last = last_activity_ts
last_activity_dt = datetime.fromtimestamp(lf_active_ts_last).strftime("%d %b %Y, %H:%M:%S")
last_activity_ts_weekday = str(calendar.day_abbr[(datetime.fromtimestamp(lf_active_ts_last)).weekday()])
artist_old = str(last_activity_artist)
track_old = str(last_activity_track)
print(f"* Last activity:\t\t{last_activity_ts_weekday} {last_activity_dt}")
print(f"* Last track:\t\t\t{last_activity_artist} - {last_activity_track}")
spotify_search_url, apple_search_url, genius_search_url, youtube_music_search_url = get_spotify_apple_genius_search_urls(str(last_activity_artist), str(last_activity_track))
print(f"\n* Spotify search URL:\t\t{spotify_search_url}")
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}\n")
print(f"*** User is OFFLINE for {calculate_timespan(int(time.time()), lf_active_ts_last, show_seconds=False)} !")
# User is online (plays music at the moment)
else:
app_started_and_user_offline = False
lf_active_ts_start = int(time.time())
lf_active_ts_last = lf_active_ts_start
lf_track_ts_start = lf_active_ts_start
lf_track_ts_start_after_resume = lf_active_ts_start
playing_resumed_ts = lf_active_ts_start
song_on_loop = 1
artist = str(new_track.artist)
track = str(new_track.title)
album = str(new_track.info['album'])
artist_old = artist
track_old = track
print(f"\nTrack:\t\t\t\t{artist} - {track}")
print(f"Album:\t\t\t\t{album}")
if (USE_TRACK_DURATION_FROM_SPOTIFY or track_songs) and SP_DC_COOKIE and SP_DC_COOKIE != "your_sp_dc_cookie_value":
accessToken = spotify_get_access_token(SP_DC_COOKIE)
if accessToken:
sp_track_uri_id, sp_track_duration = spotify_search_song_trackid_duration(accessToken, artist, track, album)
if not USE_TRACK_DURATION_FROM_SPOTIFY:
sp_track_duration = 0
if sp_track_duration > 0:
track_duration = sp_track_duration
if not do_not_show_duration_marks:
duration_mark = " S*"
else:
try:
track_duration = pylast.Track(new_track.artist, new_track.title, network).get_duration()
if track_duration > 0:
if USE_TRACK_DURATION_FROM_SPOTIFY:
if not do_not_show_duration_marks:
duration_mark = " L*"
track_duration = int(str(track_duration)[0:-3])
except Exception as e:
track_duration = 0
pass
if track_duration > 0:
print(f"Duration:\t\t\t{display_time(track_duration)}{duration_mark}")
spotify_search_url, apple_search_url, genius_search_url, youtube_music_search_url = get_spotify_apple_genius_search_urls(str(artist), str(track))
print(f"\nSpotify search URL:\t\t{spotify_search_url}")
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("\n*** User is currently ACTIVE !")
listened_songs = 1
last_activity_to_save = []
last_activity_to_save.append(lf_track_ts_start)
last_activity_to_save.append(artist)
last_activity_to_save.append(track)
last_activity_to_save.append(album)
try:
with open(lastfm_last_activity_file, 'w', encoding="utf-8") as f:
json.dump(last_activity_to_save, f, indent=2)
except Exception as e:
print(f"* Cannot save last status to '{lastfm_last_activity_file}' file - {e}")
try:
if csv_file_name:
write_csv_entry(csv_file_name, datetime.fromtimestamp(int(lf_track_ts_start)), artist, track, album)
except Exception as e:
print(f"* Cannot write CSV entry - {e}")