-
Notifications
You must be signed in to change notification settings - Fork 7
/
spotify_profile_monitor.py
2228 lines (1848 loc) · 112 KB
/
spotify_profile_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.6
OSINT tool implementing real-time tracking of Spotify users activities and profile changes:
https://github.com/misiektoja/spotify_profile_monitor/
Python pip3 requirements:
python-dateutil
pytz
tzlocal
requests
urllib3
"""
VERSION = 1.6
# ---------------------------
# 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's profile changes, you can also use -c parameter; in seconds
SPOTIFY_CHECK_INTERVAL = 1800 # 30 mins
# How often do we retry in case of errors, you can also use -m parameter; in seconds
SPOTIFY_ERROR_INTERVAL = 180 # 3 mins
# Specify your local time zone so we convert Spotify timestamps to your time (for example: 'Europe/Warsaw')
# If you leave it as 'Auto' we will try to automatically detect the local timezone
LOCAL_TIMEZONE = 'Auto'
# Do you want to be informed about changed user's profile pic ? (via console & email notifications when -p is enabled)
# If so, the tool will save the pic to the file named 'spotify_profile_{user_uri_id/file_suffix}_pic.jpeg' after tool is started
# And also to files named 'spotify_profile_{user_uri_id/file_suffix}_pic_YYmmdd_HHMM.jpeg' when changes are detected
# We need to save the binary form of the image as the pic URL can change, so we need to actually do bin comparison of jpeg files
# It is enabled by default, you can change it below or disable by using -j parameter
DETECT_CHANGED_PROFILE_PIC = True
# If you have 'imgcat' installed, you can configure its path below, so new profile pictures will be displayed right in your terminal
# Leave it empty to disable this feature
# IMGCAT_PATH = "/usr/local/bin/imgcat"
IMGCAT_PATH = ""
# SP_SHA256 is only needed for functionality searching Spotify users (-s), otherwise you can leave it empty
# You need to intercept your Spotify client's network traffic and get the sha256 value
# To simulate the needed request, search for some user in Spotify client
# Then in intercepting proxy look for requests with searchUsers or searchDesktop operation name
# Display details of one of such request and copy the sha256Hash parameter value and put it below
# Example request:
# https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchUsers&variables={"searchTerm":"misiektoja","offset":0,"limit":5,"numberOfTopResults":5,"includeAudiobooks":false}&extensions={"persistedQuery":{"version":1,"sha256Hash":"XXXXXXXXXX"}}
# You are interested in the string marked as "XXXXXXXXXX" here
# I used Proxyman proxy on MacOS to intercept Spotify's client traffic
SP_SHA256 = "your_spotify_client_sha256"
# Do you want to be informed about changes in user's profile public playlists ? (via console & email notifications when -p is enabled)
# It will cover added/removed tracks in playlists, playlists name and description changes, number of likes for playlists
# It is enabled by default, you can change it below or disable by using -q parameter
DETECT_CHANGES_IN_PLAYLISTS = True
# How many user owned public playlists the tool will monitor
PLAYLISTS_LIMIT = 50
# How many recently played artists the tool will display when using -a parameter
RECENTLY_PLAYED_ARTISTS_LIMIT = 50
# 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_profile_monitor_{user_uri_id/file_suffix}.log file
SP_LOGFILE = "spotify_profile_monitor"
# Value used by signal handlers increasing/decreasing the profile check (SPOTIFY_CHECK_INTERVAL); in seconds
SPOTIFY_CHECK_SIGNAL_VALUE = 300 # 5 minutes
# -------------------------
# 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
# Sometimes Spotify API has issues and returns info that all user's playlists disappeared
# We won't notify about such event right away, but only during PLAYLISTS_DISAPPEARED_COUNTER attempt (next check interval)
PLAYLISTS_DISAPPEARED_COUNTER = 2
TOOL_ALIVE_COUNTER = TOOL_ALIVE_INTERVAL / SPOTIFY_CHECK_INTERVAL
stdout_bck = None
csvfieldnames = ['Date', 'Type', 'Name', 'Old', 'New']
profile_notification = False
followers_followings_notification = True
file_suffix = ""
# 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 shutil
import signal
import smtplib
import ssl
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import argparse
import csv
import pytz
try:
from tzlocal import get_localzone
except ImportError:
pass
import platform
import html
import urllib
import re
import ipaddress
from itertools import zip_longest
from html import escape
import subprocess
# 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, image_file="", image_name="image1", 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 image_file:
fp = open(image_file, 'rb')
img_part = MIMEImage(fp.read())
fp.close()
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)
if image_file:
img_part.add_header('Content-ID', f'<{image_name}>')
email_msg.attach(img_part)
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, object_type, object_name, old, new):
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, 'Type': object_type, 'Name': object_name, 'Old': old, 'New': new})
csv_file.close()
except Exception as e:
raise
# Function to convert UTC string returned by Spotify to datetime object in specified timezone
def convert_utc_str_to_tz_datetime(utc_string, timezone, version=1):
try:
if version == 1:
utc_string_sanitize = utc_string.split('Z', 1)[0]
dt_utc = datetime.strptime(utc_string_sanitize, '%Y-%m-%dT%H:%M:%S')
else:
utc_string_sanitize = utc_string.split(' GMT', 1)[0]
dt_utc = datetime.strptime(utc_string_sanitize, '%a, %d %b %Y %H:%M:%S')
old_tz = pytz.timezone("UTC")
new_tz = pytz.timezone(timezone)
dt_new_tz = old_tz.localize(dt_utc).astimezone(new_tz)
return dt_new_tz
except Exception as e:
return datetime.fromtimestamp(0)
# 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 email notifications about profile changes
def toggle_profile_changes_notifications_signal_handler(sig, frame):
global profile_notification
profile_notification = not profile_notification
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Email notifications: [profile changes = {profile_notification}]")
print_cur_ts("Timestamp:\t\t")
# Signal handler for SIGTRAP allowing to increase profile check timer by SPOTIFY_CHECK_SIGNAL_VALUE seconds
def increase_check_signal_handler(sig, frame):
global SPOTIFY_CHECK_INTERVAL
SPOTIFY_CHECK_INTERVAL = SPOTIFY_CHECK_INTERVAL + SPOTIFY_CHECK_SIGNAL_VALUE
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Spotify timers: [check interval: {display_time(SPOTIFY_CHECK_INTERVAL)}]")
print_cur_ts("Timestamp:\t\t")
# Signal handler for SIGABRT allowing to decrease profile check timer by SPOTIFY_CHECK_SIGNAL_VALUE seconds
def decrease_check_signal_handler(sig, frame):
global SPOTIFY_CHECK_INTERVAL
if SPOTIFY_CHECK_INTERVAL - SPOTIFY_CHECK_SIGNAL_VALUE > 0:
SPOTIFY_CHECK_INTERVAL = SPOTIFY_CHECK_INTERVAL - SPOTIFY_CHECK_SIGNAL_VALUE
sig_name = signal.Signals(sig).name
print(f"* Signal {sig_name} received")
print(f"* Spotify timers: [check interval: {display_time(SPOTIFY_CHECK_INTERVAL)}]")
print_cur_ts("Timestamp:\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 removing specified key from list of dictionaries
def remove_key_from_list_of_dicts(list_of_dicts, del_key):
if list_of_dicts:
for items in list_of_dicts:
if del_key in items:
del items[del_key]
# 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 converting Spotify URL (e.g. https://open.spotify.com/user/username) to URI (e.g. spotify:user:username)
def spotify_convert_url_to_uri(url):
uri = ""
if "user" in url:
uri = url.split('user/', 1)[1]
if "?" in uri:
uri = uri.split('?', 1)[0]
uri = f"spotify:user:{uri}"
elif "artist" in url:
uri = url.split('artist/', 1)[1]
if "?" in uri:
uri = uri.split('?', 1)[0]
uri = f"spotify:artist:{uri}"
elif "track" in url:
uri = url.split('track/', 1)[1]
if "?" in uri:
uri = uri.split('?', 1)[0]
uri = f"spotify:track:{uri}"
elif "album" in url:
uri = url.split('album/', 1)[1]
if "?" in uri:
uri = uri.split('?', 1)[0]
uri = f"spotify:album:{uri}"
elif "playlist" in url:
uri = url.split('playlist/', 1)[1]
if "?" in uri:
uri = uri.split('?', 1)[0]
uri = f"spotify:playlist:{uri}"
return uri
# Function returning detailed info about playlist with specified URI (with possibility to get its tracks as well)
def spotify_get_playlist_info(access_token, playlist_uri, get_tracks):
playlist_id = playlist_uri.split(':', 2)[2]
if get_tracks:
url1 = f"https://api.spotify.com/v1/playlists/{playlist_id}?fields=name,description,owner,followers,external_urls,tracks.total"
url2 = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks?fields=next,total,items(added_at,track(name,uri,duration_ms)),items(track(artists(name,uri)))"
else:
url1 = f"https://api.spotify.com/v1/playlists/{playlist_id}?fields=name,description,owner,followers,external_urls,tracks.total"
url2 = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks?fields=next,total,items(added_at)"
headers = {"Authorization": "Bearer " + access_token}
# add si parameter so link opens in native Spotify app after clicking
si = "?si=1"
try:
response1 = req.get(url1, headers=headers, timeout=FUNCTION_TIMEOUT)
response1.raise_for_status()
json_response1 = response1.json()
sp_playlist_tracks_concatenated_list = []
next_url = url2
while next_url:
response2 = req.get(next_url, headers=headers, timeout=FUNCTION_TIMEOUT)
response2.raise_for_status()
json_response2 = response2.json()
for track in json_response2.get("items"):
sp_playlist_tracks_concatenated_list.append(track)
next_url = json_response2.get("next")
sp_playlist_name = json_response1.get("name", "")
sp_playlist_description = json_response1.get("description", "")
sp_playlist_owner = json_response1["owner"].get("display_name", "")
sp_playlist_owner_url = json_response1["owner"]["external_urls"].get("spotify")
sp_playlist_tracks_count = json_response1["tracks"].get("total", 0)
sp_playlist_tracks = sp_playlist_tracks_concatenated_list
if sp_playlist_tracks:
sp_playlist_tracks_count_tmp = len(sp_playlist_tracks)
if sp_playlist_tracks_count_tmp > 0:
sp_playlist_tracks_count = sp_playlist_tracks_count_tmp
sp_playlist_followers_count = int(json_response1["followers"].get("total", 0))
sp_playlist_url = json_response1["external_urls"].get("spotify") + si
return {"sp_playlist_name": sp_playlist_name, "sp_playlist_description": sp_playlist_description, "sp_playlist_owner": sp_playlist_owner, "sp_playlist_owner_url": sp_playlist_owner_url, "sp_playlist_tracks_count": sp_playlist_tracks_count, "sp_playlist_tracks": sp_playlist_tracks, "sp_playlist_followers_count": sp_playlist_followers_count, "sp_playlist_url": sp_playlist_url}
except Exception as e:
raise
# Function returning detailed info about user with specified URI
def spotify_get_user_info(access_token, user_uri_id, get_playlists):
if get_playlists:
url = f"https://spclient.wg.spotify.com/user-profile-view/v3/profile/{user_uri_id}?playlist_limit={PLAYLISTS_LIMIT}&artist_limit={RECENTLY_PLAYED_ARTISTS_LIMIT}&episode_limit=10&market=from_token"
else:
url = f"https://spclient.wg.spotify.com/user-profile-view/v3/profile/{user_uri_id}?playlist_limit=0&artist_limit={RECENTLY_PLAYED_ARTISTS_LIMIT}&episode_limit=10&market=from_token"
headers = {"Authorization": "Bearer " + access_token}
try:
response = req.get(url, headers=headers, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
json_response = response.json()
sp_username = json_response.get("name", "")
sp_user_followers_count = json_response.get("followers_count", 0)
sp_user_show_follows = json_response.get("show_follows")
sp_user_followings_count = json_response.get("following_count", 0)
sp_user_image_url = json_response.get("image_url", "")
if get_playlists:
sp_user_public_playlists_uris = json_response.get("public_playlists", None)
sp_user_public_playlists_count = json_response.get("total_public_playlists_count", 0)
else:
sp_user_public_playlists_uris = None
sp_user_public_playlists_count = 0
if sp_user_public_playlists_uris:
sp_user_public_playlists_uris[:] = [d for d in sp_user_public_playlists_uris if d.get('owner_uri', "") == 'spotify:user:' + str(user_uri_id)]
sp_user_public_playlists_count_tmp = len(sp_user_public_playlists_uris)
if sp_user_public_playlists_count_tmp > 0:
sp_user_public_playlists_count = sp_user_public_playlists_count_tmp
else:
sp_user_public_playlists_count = 0
remove_key_from_list_of_dicts(sp_user_public_playlists_uris, 'image_url')
remove_key_from_list_of_dicts(sp_user_public_playlists_uris, 'is_following')
remove_key_from_list_of_dicts(sp_user_public_playlists_uris, 'name')
remove_key_from_list_of_dicts(sp_user_public_playlists_uris, 'followers_count')
sp_user_recently_played_artists = json_response.get("recently_played_artists")
remove_key_from_list_of_dicts(sp_user_recently_played_artists, 'image_url')
remove_key_from_list_of_dicts(sp_user_recently_played_artists, 'followers_count')
return {"sp_username": sp_username, "sp_user_followers_count": sp_user_followers_count, "sp_user_show_follows": sp_user_show_follows, "sp_user_followings_count": sp_user_followings_count, "sp_user_public_playlists_count": sp_user_public_playlists_count, "sp_user_public_playlists_uris": sp_user_public_playlists_uris, "sp_user_recently_played_artists": sp_user_recently_played_artists, "sp_user_image_url": sp_user_image_url}
except Exception as e:
raise
# Function returning followings for user with specified URI
def spotify_get_user_followings(access_token, user_uri_id):
url = f"https://spclient.wg.spotify.com/user-profile-view/v3/profile/{user_uri_id}/following?market=from_token"
headers = {"Authorization": "Bearer " + access_token}
try:
response = req.get(url, headers=headers, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
json_response = response.json()
sp_user_followings = json_response.get("profiles", None)
if sp_user_followings:
remove_key_from_list_of_dicts(sp_user_followings, 'image_url')
remove_key_from_list_of_dicts(sp_user_followings, 'followers_count')
remove_key_from_list_of_dicts(sp_user_followings, 'following_count')
remove_key_from_list_of_dicts(sp_user_followings, 'color')
remove_key_from_list_of_dicts(sp_user_followings, 'is_following')
return {"sp_user_followings": sp_user_followings}
except Exception as e:
raise
# Function returning followers for user with specified URI
def spotify_get_user_followers(access_token, user_uri_id):
url = f"https://spclient.wg.spotify.com/user-profile-view/v3/profile/{user_uri_id}/followers?market=from_token"
headers = {"Authorization": "Bearer " + access_token}
try:
response = req.get(url, headers=headers, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
json_response = response.json()
sp_user_followers = json_response.get("profiles", None)
if sp_user_followers:
remove_key_from_list_of_dicts(sp_user_followers, 'image_url')
remove_key_from_list_of_dicts(sp_user_followers, 'followers_count')
remove_key_from_list_of_dicts(sp_user_followers, 'following_count')
remove_key_from_list_of_dicts(sp_user_followers, 'color')
remove_key_from_list_of_dicts(sp_user_followers, 'is_following')
return {"sp_user_followers": sp_user_followers}
except Exception as e:
raise
# Function listing tracks for playlist with specified URI (-l parameter)
def spotify_list_tracks_for_playlist(sp_accessToken, playlist_url):
print(f"Listing tracks for playlist '{playlist_url}' ...\n")
playlist_uri = spotify_convert_url_to_uri(playlist_url)
sp_playlist_data = spotify_get_playlist_info(sp_accessToken, playlist_uri, True)
p_name = sp_playlist_data.get("sp_playlist_name", "")
p_descr = html.unescape(sp_playlist_data.get("sp_playlist_description", ""))
p_owner = sp_playlist_data.get("sp_playlist_owner", "")
print(f"Playlist '{p_name}' owned by '{p_owner}':\n")
p_likes = sp_playlist_data.get("sp_playlist_followers_count", 0)
p_tracks = sp_playlist_data.get("sp_playlist_tracks_count", 0)
p_tracks_list = sp_playlist_data.get("sp_playlist_tracks", None)
added_at_ts_lowest = 0
added_at_ts_highest = 0
duration_sum = 0
if p_tracks_list is not None:
for index, track in enumerate(p_tracks_list):
p_artist = track["track"]["artists"][0].get("name", None)
p_track = track["track"].get("name", None)
duration_ms = track["track"].get("duration_ms")
if p_artist and p_track and int(duration_ms) >= 1000:
artist_track = f"{p_artist} - {p_track}"
duration = int(str(duration_ms)[0:-3])
duration_sum = duration_sum + duration
added_at_dt = convert_utc_str_to_tz_datetime(track.get("added_at"), LOCAL_TIMEZONE)
added_at_dt_ts = int(added_at_dt.timestamp())
if index == 0:
added_at_ts_lowest = added_at_dt_ts
added_at_ts_highest = added_at_dt_ts
if added_at_dt_ts < added_at_ts_lowest:
added_at_ts_lowest = added_at_dt_ts
if added_at_dt_ts > added_at_ts_highest:
added_at_ts_highest = added_at_dt_ts
added_at_dt_new = datetime.fromtimestamp(int(added_at_dt_ts)).strftime("%d %b %Y, %H:%M:%S")
added_at_dt_new_week_day = calendar.day_abbr[datetime.fromtimestamp(int(added_at_dt_ts)).weekday()]
artist_track = artist_track[:75]
line_new = '%75s %20s %3s' % (artist_track, added_at_dt_new, added_at_dt_new_week_day)
print(line_new)
print(f"\nName:\t\t'{p_name}'")
if p_descr:
print(f"Description:\t'{p_descr}'")
print(f"URL:\t\t{playlist_url}\nSongs:\t\t{p_tracks}\nLikes:\t\t{p_likes}")
if added_at_ts_lowest > 0:
p_creation_date = get_date_from_ts(int(added_at_ts_lowest))
p_creation_date_since = calculate_timespan(int(time.time()), int(added_at_ts_lowest))
print(f"Creation date:\t{p_creation_date} ({p_creation_date_since} ago)")
if added_at_ts_highest > 0:
p_last_track_date = get_date_from_ts(int(added_at_ts_highest))
p_last_track_date_since = calculate_timespan(int(time.time()), int(added_at_ts_highest))
print(f"Last update:\t{p_last_track_date} ({p_last_track_date_since} ago)")
print(f"Duration:\t{display_time(duration_sum)}")
# Function comparing two lists of dictionaries
def compare_two_lists_of_dicts(list1: list, list2: list):
if not list1:
list1 = []
if not list2:
list2 = []
diff = [i for i in list1 + list2 if i not in list2]
return diff
# Function searching for Spotify users (-s parameter)
def spotify_search_users(access_token, username):
url = f"https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchUsers&variables=%7B%22searchTerm%22%3A%22{username}%22%2C%22offset%22%3A0%2C%22limit%22%3A5%2C%22numberOfTopResults%22%3A5%2C%22includeAudiobooks%22%3Afalse%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%22{SP_SHA256}%22%7D%7D"
headers = {"Authorization": "Bearer " + access_token}
print(f"Searching for users with '{username}' string ...\n")
try:
response = req.get(url, headers=headers, timeout=FUNCTION_TIMEOUT)
response.raise_for_status()
except Exception as e:
raise
json_response = response.json()
if json_response["data"]["searchV2"]["users"].get("totalCount") > 0:
for user in json_response["data"]["searchV2"]["users"]["items"]:
print(f"Username:\t\t{user['data']['displayName']}")
print(f"User URI:\t\t{user['data']['uri']}")
print(f"User URI ID:\t\t{user['data']['id']}")
print(f"User URL:\t\t{spotify_convert_uri_to_url(user['data']['uri'])}")
print("-----------------------------------------------")
else:
print("No results")
# Function processing items of all passed playlists and returning list of dictionaries
def spotify_process_public_playlists(sp_accessToken, playlists, get_tracks):
list_of_playlists = []
error_while_processing = False
if playlists:
for playlist in playlists:
if "uri" in playlist:
list_of_tracks = []
p_uri = playlist.get("uri")
try:
sp_playlist_data = spotify_get_playlist_info(sp_accessToken, p_uri, get_tracks)
p_name = sp_playlist_data.get("sp_playlist_name", "")
p_descr = html.unescape(sp_playlist_data.get("sp_playlist_description", ""))
p_likes = sp_playlist_data.get("sp_playlist_followers_count", 0)
p_tracks = sp_playlist_data.get("sp_playlist_tracks_count", 0)
p_url = spotify_convert_uri_to_url(p_uri)
p_tracks_list = sp_playlist_data.get("sp_playlist_tracks", None)
added_at_ts_lowest = 0
added_at_ts_highest = 0
if p_tracks_list:
for index, track in enumerate(p_tracks_list):
added_at = track.get("added_at")
if get_tracks:
p_artist = track["track"]["artists"][0].get("name", "")
p_track = track["track"].get("name", "")
duration_ms = track["track"].get("duration_ms")
if p_artist and p_track and int(duration_ms) >= 1000:
track_duration = int(str(duration_ms)[0:-3])
track_uri = track["track"].get("uri")
if added_at:
added_at_dt = convert_utc_str_to_tz_datetime(added_at, LOCAL_TIMEZONE)
added_at_dt_ts = int(added_at_dt.timestamp())
added_at_str = get_date_from_ts(added_at_dt_ts)
if index == 0:
added_at_ts_lowest = added_at_dt_ts
added_at_ts_highest = added_at_dt_ts
if added_at_dt_ts < added_at_ts_lowest:
added_at_ts_lowest = added_at_dt_ts
if added_at_dt_ts > added_at_ts_highest:
added_at_ts_highest = added_at_dt_ts
added_at_dt_new = datetime.fromtimestamp(int(added_at_dt_ts)).strftime("%d %b %Y, %H:%M:%S")
if get_tracks and added_at:
list_of_tracks.append({"artist": p_artist, "track": p_track, "duration": track_duration, "added_at": added_at_str, "uri": track_uri})
except Exception as e:
print(f"Error while processing playlist with URI {p_uri}, skipping for now - {e}")
print_cur_ts("Timestamp:\t\t")
error_while_processing = True
continue
p_creation_date = None
p_last_track_date = None
if added_at_ts_lowest > 0:
p_creation_date = datetime.fromtimestamp(int(added_at_ts_lowest))
if added_at_ts_highest > 0:
p_last_track_date = datetime.fromtimestamp(int(added_at_ts_highest))
if list_of_tracks and get_tracks:
list_of_playlists.append({"uri": p_uri, "name": p_name, "desc": p_descr, "likes": p_likes, "tracks_count": p_tracks, "url": p_url, "date": p_creation_date, "update_date": p_last_track_date, "list_of_tracks": list_of_tracks})
else:
list_of_playlists.append({"uri": p_uri, "name": p_name, "desc": p_descr, "likes": p_likes, "tracks_count": p_tracks, "url": p_url, "date": p_creation_date, "update_date": p_last_track_date})
return list_of_playlists, error_while_processing
# Function printing detailed info about user's playlists
def spotify_print_public_playlists(list_of_playlists):
if list_of_playlists:
for playlist in list_of_playlists:
if "uri" in playlist:
p_uri = playlist.get("uri")
p_name = playlist.get("name", "")
p_descr = html.unescape(playlist.get("desc", ""))
p_likes = playlist.get("likes", 0)
p_tracks = playlist.get("tracks_count", 0)
p_url = playlist.get("url")
p_date = playlist.get("date")
p_update = playlist.get("update_date")
print(f"- '{p_name}'\n[ {p_url} ]\n[ songs: {p_tracks}, likes: {p_likes} ]")
if p_date:
p_date_str = p_date.strftime("%d %b %Y, %H:%M:%S")
p_date_week_day = calendar.day_abbr[p_date.weekday()]
p_date_since = calculate_timespan(int(time.time()), p_date)
print(f"[ date: {p_date_week_day} {p_date_str} - {p_date_since} ago ]")
if p_update:
p_update_str = p_update.strftime("%d %b %Y, %H:%M:%S")
p_update_week_day = calendar.day_abbr[p_update.weekday()]
p_update_since = calculate_timespan(int(time.time()), p_update)
print(f"[ update: {p_update_week_day} {p_update_str} - {p_update_since} ago ]")
if p_descr:
print(f"'{p_descr}'")
print()
# Function printing detailed info about user with specified URI ID (-i parameter)
def spotify_get_user_details(sp_accessToken, user_uri_id):
print(f"Getting detailed info for user with URI ID '{user_uri_id}' ...\n")
sp_user_data = spotify_get_user_info(sp_accessToken, user_uri_id, True)
sp_user_followers_data = spotify_get_user_followers(sp_accessToken, user_uri_id)
sp_user_followings_data = spotify_get_user_followings(sp_accessToken, user_uri_id)
username = sp_user_data["sp_username"]
image_url = sp_user_data["sp_user_image_url"]