-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.py
More file actions
800 lines (663 loc) · 24 KB
/
Copy pathclasses.py
File metadata and controls
800 lines (663 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Nimbus ~ UserBot
# Copyright (C) 2023 NimbusTheCloud, ufoptg, @TrueSaiyan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# This file is a part of < https://github.com/ufoptg/Nimbus/ > and < https://github.com/ToxygenX/Megatron/ >
# This file is licensed explicitly for and to the use of Both @TrueSaiyan(636002102) and @Hackintush(1601105531)
# PLease read the GNU Affero General Public License in
# <https://www.github.com/ufoptg/Nimbus/blob/main/LICENSE/>.
# If not, see <https://www.gnu.org/licenses/>.
# THIS FILE IS RESPONSABLE FOR MANY CLASS DECLARATIONS
import json
import math
from base64 import b64encode
from urllib.request import urlretrieve
from . import calls, constructor
class Authenticator:
"""
Handles authentication and token retrieval for Spotify API.
"""
def __init__(self, client_id: str, client_secret: str):
"""
Initializes the Authenticator with client credentials.
:param client_id: Spotify client ID.
:param client_secret: Spotify client secret.
"""
self.credentials = self.encode_credentials(client_id, client_secret)
def encode_credentials(self, client_id, client_secret):
"""
Encodes client credentials for token retrieval.
:param client_id: Spotify client ID.
:param client_secret: Spotify client secret.
:return: Encoded credentials.
"""
credentials = f"{client_id}:{client_secret}"
encoded_credentials = b64encode(credentials.encode("utf-8"))
return str(encoded_credentials, "utf-8")
def get_acess_token(self):
"""
Retrieves access token using encoded credentials.
:return: Access token.
"""
response = calls.call_acess_token(self.credentials)
return response.json()["access_token"]
# OBJECTS
# Base class for all classes
class Base:
"""
Base class for all Spotify API objects.
"""
def __init__(self, data, type, name, url, id):
"""
Initializes Base object.
:param data: Data dictionary.
:param type: Object type.
:param name: Name of the object.
:param url: URL of the object.
:param id: ID of the object.
"""
self.data = data
self.type = type
self.name = name
self.url = url
self.id = id
def export_json(self, path: str):
"""
Exports object data to JSON file.
:param path: File path.
"""
file = open(path, "w")
json.dump(self.data, file, indent=4)
file.close()
class TrackBase(Base):
"""
Base class for track-like Spotify API objects.
"""
def __init__(self, data, type, name, url, id, explicit, duration_ms):
"""
Initializes TrackBase object.
:param data: Data dictionary.
:param type: Object type.
:param name: Name of the object.
:param url: URL of the object.
:param id: ID of the object.
:param explicit: Explicit content indicator.
:param duration_ms: Duration of the object in milliseconds.
"""
super().__init__(data, type, name, url, id)
self.explicit = explicit
self.duration_ms = duration_ms
def get_formatted_duration(self) -> dict:
"""
Gets the formatted duration of the object.
:return: Dictionary containing hours, minutes, and seconds.
"""
duration_in_seconds = self.duration_ms / 1000
hours = 0
mins = math.floor(duration_in_seconds // 60)
if mins >= 60:
hours = math.floor(mins // 60)
mins = math.floor(mins % 60)
secs = math.floor(duration_in_seconds % 60)
return {"hours": hours, "minutes": mins, "seconds": secs}
def get_string_duration(self) -> str:
"""
Gets the duration of the object as a formatted string.
:return: Formatted duration string.
"""
duration = self.get_formatted_duration()
format = self.__format_duration
hours = format(str(duration["hours"]))
mins = format(str(duration["minutes"]))
secs = format(str(duration["seconds"]))
if int(hours):
return f"{hours}:{mins}:{secs}"
else:
return f"{mins}:{secs}"
def __format_duration(self, value: str):
"""
Formats duration value.
:param value: Value to format.
:return: Formatted value.
"""
if len(value) < 2:
return "0" + value
else:
return value
class Artist(Base):
"""
Represents an artist on Spotify.
"""
def __init__(self, data: dict, type: str, name: str, url: str, id: str):
"""
Initializes Artist object.
:param data: Data dictionary.
:param type: Object type.
:param name: Name of the artist.
:param url: URL of the artist.
:param id: ID of the artist.
"""
super().__init__(data, type, name, url, id)
class AlbumCover:
"""
Represents the cover image of an album.
"""
def __init__(self, width, height, url):
"""
Initializes AlbumCover object.
:param width: Width of the image.
:param height: Height of the image.
:param url: URL of the image.
"""
self.width = width
self.height = height
self.url = url
def export_image(self, path):
"""
Exports the image to a file.
:param path: File path.
"""
urlretrieve(self.url, path)
class Album(Base):
"""
Represents an album on Spotify.
"""
def __init__(
self,
data: dict,
type: str,
name: str,
url: str,
id: str,
images: list,
artists: list,
available_markets: list,
release_date: str,
total_tracks: int,
):
"""
Initializes Album object.
:param data: Data dictionary.
:param type: Object type.
:param name: Name of the album.
:param url: URL of the album.
:param id: ID of the album.
:param images: List of album cover images.
:param artists: List of artists associated with the album.
:param available_markets: List of available markets.
:param release_date: Release date of the album.
:param total_tracks: Total number of tracks in the album.
"""
super().__init__(data, type, name, url, id)
self.images = images
self.artists = artists
self.available_markets = available_markets
self.release_date = release_date
self.total_tracks = total_tracks
class AlbumTrack:
"""
Represents a track in an album.
"""
def __init__(self, track_data):
"""
Initializes AlbumTrack object.
:param track_data: Data dictionary for the track.
:param url: Spotify URL of the track.
:param name: Name of the track.
:param artists: List of artists associated with the track.
:param track_number: Track number in the album.
:param duration_ms: Duration of the track in milliseconds.
"""
self.url = track_data.get("external_urls", {}).get("spotify")
self.name = track_data.get("name")
self.artists = ", ".join(
artist.get("name", "") for artist in track_data.get("artists", [])
)
self.track_number = track_data.get("track_number")
self.duration_ms = track_data.get("duration_ms", 0)
def get_formatted_duration(self) -> dict:
"""
Gets the formatted duration of the object.
:return: Dictionary containing hours, minutes, and seconds.
"""
duration_in_seconds = self.duration_ms / 1000
hours = 0
mins = math.floor(duration_in_seconds // 60)
if mins >= 60:
hours = math.floor(mins // 60)
mins = math.floor(mins % 60)
secs = math.floor(duration_in_seconds % 60)
return {"hours": hours, "minutes": mins, "seconds": secs}
def get_string_duration(self) -> str:
"""
Gets the duration of the object as a formatted string.
:return: Formatted duration string.
"""
duration = self.get_formatted_duration()
format = self.__format_duration
hours = format(str(duration["hours"]))
mins = format(str(duration["minutes"]))
secs = format(str(duration["seconds"]))
if int(hours):
return f"{hours}:{mins}:{secs}"
else:
return f"{mins}:{secs}"
def __format_duration(self, value: str):
"""
Formats duration value.
:param value: Value to format.
:return: Formatted value.
"""
if len(value) < 2:
return "0" + value
else:
return value
class Albums:
"""
Represents an album.
"""
def __init__(self, album_data):
"""
Initializes Album object.
:param album_data: Data dictionary for the album.
:param name: Name of the album.
:param artists: List of artists associated with the album.
:param release_date: Release date of the album.
:param total_tracks: Total number of tracks in the album.
:param thumb: URL of the album's thumbnail image.
:param url: URL of the album's thumbnail image.
:param label: Record label of the album.
:param popularity: Popularity score of the album.
:param tracks: List of AlbumTrack objects representing tracks in the album.
"""
self.name = album_data.get("name", "Unknown Album")
self.artists = ", ".join(
artist.get("name", "") for artist in album_data.get("artists", [])
)
self.release_date = album_data.get("release_date")
self.total_tracks = album_data.get("total_tracks", 0)
self.thumb = (
album_data.get("images", [])[0].get("url")
if album_data.get("images")
else None
)
self.label = album_data.get("label")
self.popularity = album_data.get("popularity")
self.tracks = [
AlbumTrack(track) for track in album_data.get("tracks", {}).get("items", [])
]
def total_duration(self):
"""
Calculate the total duration of all tracks in the album.
:return: Total duration as a formatted string.
"""
total_seconds = sum(track.duration_ms for track in self.tracks) / 1000
hours = int(total_seconds // 3600)
minutes = int((total_seconds % 3600) // 60)
seconds = int(total_seconds % 60)
return f"{hours}:{minutes}:{seconds}"
def total_duration_string(self):
"""
Calculate the total duration of all tracks in the album as a formatted string.
:return: Total duration as a formatted string.
"""
total_seconds = sum(track.duration_ms for track in self.tracks) / 1000
total_duration_track = AlbumTrack({"duration_ms": total_seconds * 1000})
return total_duration_track.get_string_duration()
class TrackPreview:
"""
Represents a preview of a track.
"""
def __init__(self, url):
"""
Initializes TrackPreview object.
:param url: URL of the track preview.
"""
self.url = url
def export_audio(self, path):
"""
Exports the audio preview to a file.
:param path: File path.
"""
urlretrieve(self.url, path)
class Track(TrackBase):
"""
Represents a track on Spotify.
"""
def __init__(
self,
data: dict,
type: str,
name: str,
url: str,
id: str,
explicit: bool,
duration_ms: int,
preview: TrackPreview,
artists: list,
album: Album,
available_markets: list,
disc_number: int,
popularity: int,
):
"""
Initializes Track object.
:param data: Data dictionary.
:param type: Object type.
:param name: Name of the track.
:param url: URL of the track.
:param id: ID of the track.
:param explicit: Explicit content indicator.
:param duration_ms: Duration of the track in milliseconds.
:param preview: Track preview object.
:param artists: List of artists associated with the track.
:param album: Album object associated with the track.
:param available_markets: List of available markets.
:param disc_number: Disc number of the track.
:param popularity: Popularity of the track.
"""
super().__init__(data, type, name, url, id, explicit, duration_ms)
self.preview = preview
self.artists = artists
self.album = album
self.available_markets = available_markets
self.disc_number = disc_number
self.popularity = popularity
class Episode(TrackBase):
"""
Represents an episode on Spotify.
"""
def __init__(
self,
data: dict,
type: str,
name: str,
url: str,
id: str,
explicit: bool,
duration_ms: int,
preview: str,
description: str,
html_description: str,
images: list,
language: str,
languages: list,
release_date: str,
):
"""
Initializes Episode object.
:param data: Data dictionary.
:param type: Object type.
:param name: Name of the episode.
:param url: URL of the episode.
:param id: ID of the episode.
:param explicit: Explicit content indicator.
:param duration_ms: Duration of the episode in milliseconds.
:param preview: URL of the episode preview.
:param description: Description of the episode.
:param html_description: HTML description of the episode.
:param images: List of images associated with the episode.
:param language: Language of the episode.
:param languages: List of languages available for the episode.
:param release_date: Release date of the episode.
"""
super().__init__(data, type, name, url, id, explicit, duration_ms)
self.preview = preview
self.description = description
self.html_description = html_description
self.images = images
self.language = language
self.languages = languages
self.release_date = release_date
class Playlist(Base):
"""
Represents a playlist on Spotify.
"""
def __init__(
self,
data: dict,
type: str,
name: str,
url: str,
id: str,
description: str,
images: list,
tracks: list,
public: bool,
total_tracks: int,
):
"""
Initializes Playlist object.
:param data: Data dictionary.
:param type: Object type.
:param name: Name of the playlist.
:param url: URL of the playlist.
:param id: ID of the playlist.
:param description: Description of the playlist.
:param images: List of images associated with the playlist.
:param tracks: List of tracks in the playlist.
:param public: Public visibility indicator.
"""
super().__init__(data, type, name, url, id)
self.description = description
self.images = images
self.tracks = tracks
self.public = public
self.total_tracks = total_tracks
class PlaylistTrack:
"""
Represents a track in a playlist.
"""
def __init__(self, track_data):
"""
Initializes PlaylistTrack object.
:param track_data: Data dictionary for the track.
:param url: Spotify URL of the track.
:param name: Name of the track.
:param artists: List of artists associated with the track.
:param album: Name of the album the track belongs to.
:param release_date: Release date of the track's album.
:param preview_url: Preview URL of the track.
:param thumb: URL of the track's thumbnail image.
:param duration_ms: Duration of the track in milliseconds.
"""
self.url = track_data.get("external_urls", {}).get("spotify")
self.name = track_data.get("name")
self.artists = ", ".join(
artist.get("name", "") for artist in track_data.get("artists", [])
)
self.album = track_data.get("album", {}).get("name")
self.release_date = track_data.get("album", {}).get("release_date")
self.preview_url = track_data.get("preview_url")
self.thumb = (
track_data.get("album", {}).get("images", [])[0].get("url")
if track_data.get("album", {}).get("images")
else None
)
self.duration_ms = track_data.get("duration_ms", 0)
def get_formatted_duration(self) -> dict:
"""
Gets the formatted duration of the object.
:return: Dictionary containing hours, minutes, and seconds.
"""
duration_in_seconds = self.duration_ms / 1000
hours = 0
mins = math.floor(duration_in_seconds // 60)
if mins >= 60:
hours = math.floor(mins // 60)
mins = math.floor(mins % 60)
secs = math.floor(duration_in_seconds % 60)
return {"hours": hours, "minutes": mins, "seconds": secs}
def get_string_duration(self) -> str:
"""
Gets the duration of the object as a formatted string.
:return: Formatted duration string.
"""
duration = self.get_formatted_duration()
format = self.__format_duration
hours = format(str(duration["hours"]))
mins = format(str(duration["minutes"]))
secs = format(str(duration["seconds"]))
if int(hours):
return f"{hours}:{mins}:{secs}"
else:
return f"{mins}:{secs}"
def __format_duration(self, value: str):
"""
Formats duration value.
:param value: Value to format.
:return: Formatted value.
"""
if len(value) < 2:
return "0" + value
else:
return value
class Playlists:
"""
Represents a collection of playlists.
"""
def __init__(self, playlist_data):
"""
Initializes Playlists object.
:param playlist_data: Data dictionary for the playlists.
:param name: Name of the playlist.
:param description: Description of the playlist.
:param total_tracks: Total number of tracks in the playlist.
:param thumb: URL of the playlist's thumbnail image.
:param tracks: List of PlaylistTrack objects representing tracks in the playlist.
"""
self.name = playlist_data.get("name", "Unknown Playlist")
self.description = playlist_data.get("description", "")
self.total_tracks = playlist_data.get("tracks", {}).get("total", 0)
self.thumb = playlist_data.get("images", [])[0].get("url")
self.tracks = [
PlaylistTrack(item.get("track"))
for item in playlist_data.get("tracks", {}).get("items", [])
]
def total_duration(self):
"""
Calculate the total duration of all tracks in the playlist.
:return: Total duration as a string.
"""
total_seconds = sum(track.duration_ms for track in self.tracks) / 1000
hours = int(total_seconds // 3600)
minutes = int((total_seconds % 3600) // 60)
seconds = int(total_seconds % 60)
return f"{hours}:{minutes}:{seconds}"
def total_duration_string(self):
"""
Calculate the total duration of all tracks in the album as a formatted string.
:return: Total duration as a formatted string.
"""
total_seconds = sum(track.duration_ms for track in self.tracks) / 1000
total_duration_track = PlaylistTrack({"duration_ms": total_seconds * 1000})
return total_duration_track.get_string_duration()
# CLIENT OBJECTS
class Results(Base):
"""
Represents results obtained from Spotify API.
"""
def __init__(self, data):
"""
Initializes Results object.
:param data: Data dictionary.
"""
self.data = data
def __get_items(self, type):
"""
Retrieves items from the data dictionary based on the type.
:param type: Type of items to retrieve.
:return: List of items.
"""
if type == "artist":
try:
data = self.data["artists"]["items"]
func = constructor.artist
except KeyError:
return []
elif type == "track":
try:
data = self.data["tracks"]["items"]
func = constructor.track
except KeyError:
return []
elif type == "album":
try:
data = [item["album"] for item in self.data["tracks"]["items"]]
func = constructor.album
except KeyError:
return []
elif type == "episode":
try:
data = self.data["episodes"]["items"]
func = constructor.episode
except KeyError:
return []
elif type == "playlist":
try:
data = self.data["playlists"]["items"]
func = constructor.playlist
except KeyError:
return []
return [func(item) for item in data]
def get_playlist(self) -> "Playlists":
"""
Retrieves playlist items from the results.
:return: Playlists object.
"""
try:
playlist_data = self.data
return Playlists(playlist_data)
except KeyError:
return None
def get_album(self) -> "Albums":
"""
Retrieves album items from the results.
:return: Albums object.
"""
try:
album_data = self.data
return Albums(album_data)
except KeyError:
return None
def get_tracks(self) -> list:
"""
Retrieves track items from the results.
:return: List of track items.
"""
return self.__get_items("track")
def get_artists(self) -> list:
"""
Retrieves artist items from the results.
:return: List of artist items.
"""
return self.__get_items("artist")
def get_albums(self) -> list:
"""
Retrieves album items from the results.
:return: List of album items.
"""
return self.__get_items("album")
def get_episodes(self) -> list:
"""
Retrieves episode items from the results.
:return: List of episode items.
"""
return self.__get_items("episode")
def get_playlists(self) -> list:
"""
Retrieves playlist items from the results.
:return: List of playlist items.
"""
return self.__get_items("playlist")