-
Notifications
You must be signed in to change notification settings - Fork 145
/
soundscrape.py
executable file
·1372 lines (1090 loc) · 47.5 KB
/
soundscrape.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
import argparse
import demjson
import html
import os
import re
import requests
import soundcloud
import sys
import urllib
from clint.textui import colored, puts, progress
from datetime import datetime
from mutagen.mp3 import MP3, EasyMP3
from mutagen.id3 import APIC, WXXX
from mutagen.id3 import ID3 as OldID3
from subprocess import Popen, PIPE
from os.path import dirname, exists, join
from os import access, mkdir, W_OK
if sys.version_info.minor < 4:
html_unescape = html.parser.HTMLParser().unescape
else:
html_unescape = html.unescape
####################################################################
# Please be nice with this!
CLIENT_ID = 'a3dd183a357fcff9a6943c0d65664087'
CLIENT_SECRET = '7e10d33e967ad42574124977cf7fa4b7'
MAGIC_CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
AGGRESSIVE_CLIENT_ID = 'OmTFHKYSMLFqnu2HHucmclAptedxWXkq'
APP_VERSION = '1481046241'
####################################################################
def main():
"""
Main function.
Converts arguments to Python and processes accordingly.
"""
# Hack related to #58
if sys.platform == "win32":
os.system("chcp 65001");
parser = argparse.ArgumentParser(description='SoundScrape. Scrape an artist from SoundCloud.\n')
parser.add_argument('artist_url', metavar='U', type=str, nargs='*',
help='An artist\'s SoundCloud username or URL')
parser.add_argument('-n', '--num-tracks', type=int, default=sys.maxsize,
help='The number of tracks to download')
parser.add_argument('-g', '--group', action='store_true',
help='Use if downloading tracks from a SoundCloud group')
parser.add_argument('-b', '--bandcamp', action='store_true',
help='Use if downloading from Bandcamp rather than SoundCloud')
parser.add_argument('-m', '--mixcloud', action='store_true',
help='Use if downloading from Mixcloud rather than SoundCloud')
parser.add_argument('-a', '--audiomack', action='store_true',
help='Use if downloading from Audiomack rather than SoundCloud')
parser.add_argument('-c', '--hive', action='store_true',
help='Use if downloading from Hive.co rather than SoundCloud')
parser.add_argument('-l', '--likes', action='store_true',
help='Download all of a user\'s Likes.')
parser.add_argument('-L', '--login', type=str, default='soundscrape123@mailinator.com',
help='Set login')
parser.add_argument('-d', '--downloadable', action='store_true',
help='Only fetch tracks with a Downloadable link.')
parser.add_argument('-t', '--track', type=str, default='',
help='The name of a specific track by an artist')
parser.add_argument('-f', '--folders', action='store_true',
help='Organize saved songs in folders by artists')
parser.add_argument('-p', '--path', type=str, default='',
help='Set directory path where downloads should be saved to')
parser.add_argument('-P', '--password', type=str, default='soundscraperocks',
help='Set password')
parser.add_argument('-o', '--open', action='store_true',
help='Open downloaded files after downloading.')
parser.add_argument('-k', '--keep', action='store_true',
help='Keep 30-second preview tracks')
parser.add_argument('-v', '--version', action='store_true', default=False,
help='Display the current version of SoundScrape')
args = parser.parse_args()
vargs = vars(args)
if vargs['version']:
import pkg_resources
version = pkg_resources.require("soundscrape")[0].version
print(version)
return
if not vargs['artist_url']:
parser.error('Please supply an artist\'s username or URL!')
if sys.version_info < (3,0,0):
vargs['artist_url'] = urllib.quote(vargs['artist_url'][0], safe=':/')
else:
vargs['artist_url'] = urllib.parse.quote(vargs['artist_url'][0], safe=':/')
artist_url = vargs['artist_url']
if not exists(vargs['path']):
if not access(dirname(vargs['path']), W_OK):
vargs['path'] = ''
else:
mkdir(vargs['path'])
if 'bandcamp.com' in artist_url or vargs['bandcamp']:
process_bandcamp(vargs)
elif 'mixcloud.com' in artist_url or vargs['mixcloud']:
process_mixcloud(vargs)
elif 'audiomack.com' in artist_url or vargs['audiomack']:
process_audiomack(vargs)
elif 'hive.co' in artist_url or vargs['hive']:
process_hive(vargs)
elif 'musicbed.com' in artist_url:
process_musicbed(vargs)
else:
process_soundcloud(vargs)
####################################################################
# SoundCloud
####################################################################
def process_soundcloud(vargs):
"""
Main SoundCloud path.
"""
artist_url = vargs['artist_url']
track_permalink = vargs['track']
keep_previews = vargs['keep']
folders = vargs['folders']
id3_extras = {}
one_track = False
likes = False
client = get_client()
if 'soundcloud' not in artist_url.lower():
if vargs['group']:
artist_url = 'https://soundcloud.com/groups/' + artist_url.lower()
elif len(track_permalink) > 0:
one_track = True
track_url = 'https://soundcloud.com/' + artist_url.lower() + '/' + track_permalink.lower()
else:
artist_url = 'https://soundcloud.com/' + artist_url.lower()
if vargs['likes'] or 'likes' in artist_url.lower():
likes = True
if 'likes' in artist_url.lower():
artist_url = artist_url[0:artist_url.find('/likes')]
likes = True
if one_track:
num_tracks = 1
else:
num_tracks = vargs['num_tracks']
try:
if one_track:
resolved = client.get('/resolve', url=track_url, limit=200)
elif likes:
userId = str(client.get('/resolve', url=artist_url).id)
resolved = client.get('/users/' + userId + '/favorites', limit=200, linked_partitioning=1)
next_href = False
if(hasattr(resolved, 'next_href')):
next_href = resolved.next_href
while (next_href):
resolved2 = requests.get(next_href).json()
if('next_href' in resolved2):
next_href = resolved2['next_href']
else:
next_href = False
resolved2 = soundcloud.resource.ResourceList(resolved2['collection'])
resolved.collection.extend(resolved2)
resolved = resolved.collection
else:
resolved = client.get('/resolve', url=artist_url, limit=200)
except Exception as e: # HTTPError?
# SoundScrape is trying to prevent us from downloading this.
# We're going to have to stop trusting the API/client and
# do all our own scraping. Boo.
if '404 Client Error' in str(e):
puts(colored.red("Problem downloading [404]: ") + colored.white("Item Not Found"))
return None
message = str(e)
item_id = message.rsplit('/', 1)[-1].split('.json')[0].split('?client_id')[0]
hard_track_url = get_hard_track_url(item_id)
track_data = get_soundcloud_data(artist_url)
puts_safe(colored.green("Scraping") + colored.white(": " + track_data['title']))
filenames = []
filename = sanitize_filename(track_data['artist'] + ' - ' + track_data['title'] + '.mp3')
if folders:
name_path = join(vargs['path'], track_data['artist'])
if not exists(name_path):
mkdir(name_path)
filename = join(name_path, filename)
else:
filename = join(vargs['path'], filename)
if exists(filename):
puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track_data['title']))
return None
filename = download_file(hard_track_url, filename)
tagged = tag_file(filename,
artist=track_data['artist'],
title=track_data['title'],
year='2018',
genre='',
album='',
artwork_url='')
if not tagged:
wav_filename = filename[:-3] + 'wav'
os.rename(filename, wav_filename)
filename = wav_filename
filenames.append(filename)
else:
aggressive = False
# This is is likely a 'likes' page.
if not hasattr(resolved, 'kind'):
tracks = resolved
else:
if resolved.kind == 'artist':
artist = resolved
artist_id = str(artist.id)
tracks = client.get('/users/' + artist_id + '/tracks', limit=200)
elif resolved.kind == 'playlist':
id3_extras['album'] = resolved.title
if resolved.tracks != []:
tracks = resolved.tracks
else:
tracks = get_soundcloud_api_playlist_data(resolved.id)['tracks']
tracks = tracks[:num_tracks]
aggressive = True
for track in tracks:
download_track(track, resolved.title, keep_previews, folders, custom_path=vargs['path'])
elif resolved.kind == 'track':
tracks = [resolved]
elif resolved.kind == 'group':
group = resolved
group_id = str(group.id)
tracks = client.get('/groups/' + group_id + '/tracks', limit=200)
else:
artist = resolved
artist_id = str(artist.id)
tracks = client.get('/users/' + artist_id + '/tracks', limit=200)
if tracks == [] and artist.track_count > 0:
aggressive = True
filenames = []
# this might be buggy
data = get_soundcloud_api2_data(artist_id)
for track in data['collection']:
if len(filenames) >= num_tracks:
break
if track['type'] == 'playlist':
track['playlist']['tracks'] = track['playlist']['tracks'][:num_tracks]
for playlist_track in track['playlist']['tracks']:
album_name = track['playlist']['title']
filename = download_track(playlist_track, album_name, keep_previews, folders, filenames, custom_path=vargs['path'])
if filename:
filenames.append(filename)
else:
d_track = track['track']
filename = download_track(d_track, custom_path=vargs['path'])
if filename:
filenames.append(filename)
if not aggressive:
filenames = download_tracks(client, tracks, num_tracks, vargs['downloadable'], vargs['folders'], vargs['path'],
id3_extras=id3_extras)
if vargs['open']:
open_files(filenames)
def get_client():
"""
Return a new SoundCloud Client object.
"""
client = soundcloud.Client(client_id=CLIENT_ID)
return client
def download_track(track, album_name=u'', keep_previews=False, folders=False, filenames=[], custom_path=''):
"""
Given a track, force scrape it.
"""
hard_track_url = get_hard_track_url(track['id'])
# We have no info on this track whatsoever.
if not 'title' in track:
return None
if not keep_previews:
if (track.get('duration', 0) < track.get('full_duration', 0)):
puts_safe(colored.yellow("Skipping preview track") + colored.white(": " + track['title']))
return None
# May not have a "full name"
name = track['user'].get('full_name', '')
if name == '':
name = track['user']['username']
filename = sanitize_filename(name + ' - ' + track['title'] + '.mp3')
if folders:
name_path = join(custom_path, name)
if not exists(name_path):
mkdir(name_path)
filename = join(name_path, filename)
else:
filename = join(custom_path, filename)
if exists(filename):
puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track['title']))
return None
# Skip already downloaded track.
if filename in filenames:
return None
if hard_track_url:
puts_safe(colored.green("Scraping") + colored.white(": " + track['title']))
else:
# Region coded?
puts_safe(colored.yellow("Unable to download") + colored.white(": " + track['title']))
return None
filename = download_file(hard_track_url, filename)
tagged = tag_file(filename,
artist=name,
title=track['title'],
year=track['created_at'][:4],
genre=track['genre'],
album=album_name,
artwork_url=track['artwork_url'])
if not tagged:
wav_filename = filename[:-3] + 'wav'
os.rename(filename, wav_filename)
filename = wav_filename
return filename
def download_tracks(client, tracks, num_tracks=sys.maxsize, downloadable=False, folders=False, custom_path='', id3_extras={}):
"""
Given a list of tracks, iteratively download all of them.
"""
filenames = []
for i, track in enumerate(tracks):
# "Track" and "Resource" objects are actually different,
# even though they're the same.
if isinstance(track, soundcloud.resource.Resource):
try:
t_track = {}
t_track['downloadable'] = track.downloadable
t_track['streamable'] = track.streamable
t_track['title'] = track.title
t_track['user'] = {'username': track.user['username']}
t_track['release_year'] = track.release
t_track['genre'] = track.genre
t_track['artwork_url'] = track.artwork_url
if track.downloadable:
t_track['stream_url'] = track.download_url
else:
if downloadable:
puts_safe(colored.red("Skipping") + colored.white(": " + track.title))
continue
if hasattr(track, 'stream_url'):
t_track['stream_url'] = track.stream_url
else:
t_track['direct'] = True
streams_url = "https://api.soundcloud.com/i1/tracks/%s/streams?client_id=%s&app_version=%s" % (
str(track.id), AGGRESSIVE_CLIENT_ID, APP_VERSION)
response = requests.get(streams_url).json()
t_track['stream_url'] = response['http_mp3_128_url']
track = t_track
except Exception as e:
puts_safe(colored.white(track.title) + colored.red(' is not downloadable.'))
continue
if i > num_tracks - 1:
continue
try:
if not track.get('stream_url', False):
puts_safe(colored.white(track['title']) + colored.red(' is not downloadable.'))
continue
else:
track_artist = sanitize_filename(track['user']['username'])
track_title = sanitize_filename(track['title'])
track_filename = track_artist + ' - ' + track_title + '.mp3'
if folders:
track_artist_path = join(custom_path, track_artist)
if not exists(track_artist_path):
mkdir(track_artist_path)
track_filename = join(track_artist_path, track_filename)
else:
track_filename = join(custom_path, track_filename)
if exists(track_filename):
puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track_title))
continue
puts_safe(colored.green("Downloading") + colored.white(": " + track['title']))
if track.get('direct', False):
location = track['stream_url']
else:
stream = client.get(track['stream_url'], allow_redirects=False, limit=200)
if hasattr(stream, 'location'):
location = stream.location
else:
location = stream.url
filename = download_file(location, track_filename)
tagged = tag_file(filename,
artist=track['user']['username'],
title=track['title'],
year=track['release_year'],
genre=track['genre'],
album=id3_extras.get('album', None),
artwork_url=track['artwork_url'])
if not tagged:
wav_filename = filename[:-3] + 'wav'
os.rename(filename, wav_filename)
filename = wav_filename
filenames.append(filename)
except Exception as e:
puts_safe(colored.red("Problem downloading ") + colored.white(track['title']))
puts_safe(str(e))
return filenames
def get_soundcloud_data(url):
"""
Scrapes a SoundCloud page for a track's important information.
Returns:
dict: of audio data
"""
data = {}
request = requests.get(url)
title_tag = request.text.split('<title>')[1].split('</title')[0]
data['title'] = title_tag.split(' by ')[0].strip()
data['artist'] = title_tag.split(' by ')[1].split('|')[0].strip()
# XXX Do more..
return data
def get_soundcloud_api2_data(artist_id):
"""
Scrape the new API. Returns the parsed JSON response.
"""
v2_url = "https://api-v2.soundcloud.com/stream/users/%s?limit=500&client_id=%s&app_version=%s" % (
artist_id, AGGRESSIVE_CLIENT_ID, APP_VERSION)
response = requests.get(v2_url)
parsed = response.json()
return parsed
def get_soundcloud_api_playlist_data(playlist_id):
"""
Scrape the new API. Returns the parsed JSON response.
"""
url = "https://api.soundcloud.com/playlists/%s?representation=full&client_id=02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea&app_version=1467724310" % (
playlist_id)
response = requests.get(url)
parsed = response.json()
return parsed
def get_hard_track_url(item_id):
"""
Hard-scrapes a track.
"""
streams_url = "https://api.soundcloud.com/i1/tracks/%s/streams/?client_id=%s&app_version=%s" % (
item_id, AGGRESSIVE_CLIENT_ID, APP_VERSION)
response = requests.get(streams_url)
json_response = response.json()
if response.status_code == 200:
hard_track_url = json_response['http_mp3_128_url']
return hard_track_url
else:
return None
####################################################################
# Bandcamp
####################################################################
def process_bandcamp(vargs):
"""
Main BandCamp path.
"""
artist_url = vargs['artist_url']
if 'bandcamp.com' in artist_url or ('://' in artist_url and vargs['bandcamp']):
bc_url = artist_url
else:
bc_url = 'https://' + artist_url + '.bandcamp.com/music'
filenames = scrape_bandcamp_url(
bc_url,
num_tracks=vargs['num_tracks'],
folders=vargs['folders'],
custom_path=vargs['path'],
)
# check if we have lists inside a list, which indicates the
# scraping has gone recursive, so we must format the output
# ( reference: http://stackoverflow.com/a/5251706 )
if any(isinstance(elem, list) for elem in filenames):
# first, remove any empty sublists inside our outter list
# ( reference: http://stackoverflow.com/a/19875634 )
filenames = [sub for sub in filenames if sub]
# now, make sure we "flatten" the list
# ( reference: http://stackoverflow.com/a/11264751 )
filenames = [val for sub in filenames for val in sub]
if vargs['open']:
open_files(filenames)
return
# Largely borrowed from Ronier's bandcampscrape
def scrape_bandcamp_url(url, num_tracks=sys.maxsize, folders=False, custom_path=''):
"""
Pull out artist and track info from a Bandcamp URL.
Returns:
list: filenames to open
"""
filenames = []
album_data = get_bandcamp_metadata(url)
# If it's a list, we're dealing with a list of Album URLs,
# so we call the scrape_bandcamp_url() method for each one
if type(album_data) is list:
for album_url in album_data:
filenames.append(
scrape_bandcamp_url(
album_url, num_tracks, folders, custom_path
)
)
return filenames
artist = album_data.get("artist")
album_name = album_data.get("album_title")
if folders:
if album_name:
directory = artist + " - " + album_name
else:
directory = artist
directory = sanitize_filename(directory)
directory = join(custom_path, directory)
if not exists(directory):
mkdir(directory)
for i, track in enumerate(album_data["trackinfo"]):
if i > num_tracks - 1:
continue
try:
track_name = track["title"]
if track["track_num"]:
track_number = str(track["track_num"]).zfill(2)
else:
track_number = None
if track_number and folders:
track_filename = '%s - %s.mp3' % (track_number, track_name)
else:
track_filename = '%s.mp3' % (track_name)
track_filename = sanitize_filename(track_filename)
if folders:
path = join(directory, track_filename)
else:
path = join(custom_path, sanitize_filename(artist) + ' - ' + track_filename)
if exists(path):
puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track_name))
continue
if not track['file']:
puts_safe(colored.yellow("Track unavailble for scraping: ") + colored.white(track_name))
continue
puts_safe(colored.green("Downloading") + colored.white(": " + track_name))
path = download_file(track['file']['mp3-128'], path)
album_year = album_data['album_release_date']
if album_year:
album_year = datetime.strptime(album_year, "%d %b %Y %H:%M:%S GMT").year
tag_file(path,
artist,
track_name,
album=album_name,
year=album_year,
genre=album_data['genre'],
artwork_url=album_data['artFullsizeUrl'],
track_number=track_number,
url=album_data['url'])
filenames.append(path)
except Exception as e:
puts_safe(colored.red("Problem downloading ") + colored.white(track_name))
print(e)
return filenames
def extract_embedded_json_from_attribute(request, attribute, debug=False):
"""
Extract JSON object embedded in an element's attribute value.
The JSON is "sloppy". The native python JSON parser often can't deal,
so we use the more tolerant demjson instead.
Args:
request (obj:`requests.Response`): HTTP GET response from which to extract
attribute (str): name of the attribute holding the desired JSON object
debug (bool, optional): whether to print debug messages
Returns:
The embedded JSON object as a dict, or None if extraction failed
"""
try:
embed = request.text.split('{}="'.format(attribute))[1]
embed = html_unescape(
embed.split('"')[0]
)
output = demjson.decode(embed)
if debug:
print(
'extracted JSON: '
+ demjson.encode(
output,
compactly=False,
indent_amount=2,
)
)
except Exception as e:
output = None
if debug:
print(e)
return output
def get_bandcamp_metadata(url):
"""
Read information from Bandcamp embedded JavaScript object notation.
The method may return a list of URLs (indicating this is probably a "main" page which links to one or more albums),
or a JSON if we can already parse album/track info from the given url.
"""
request = requests.get(url)
output = {}
try:
for attr in ['data-tralbum', 'data-embed']:
output.update(
extract_embedded_json_from_attribute(
request, attr
)
)
# if the JSON parser failed, we should consider it's a "/music" page,
# so we generate a list of albums/tracks and return it immediately
except Exception as e:
regex_all_albums = r'<a href="(/(?:album|track)/[^>]+)">'
all_albums = re.findall(regex_all_albums, request.text, re.MULTILINE)
album_url_list = list()
for album in all_albums:
album_url = re.sub(r'music/?$', '', url) + album
album_url_list.append(album_url)
return album_url_list
# if the JSON parser was successful, use a regex to get all tags
# from this album/track, join them and set it as the "genre"
regex_tags = r'<a class="tag" href[^>]+>([^<]+)</a>'
tags = re.findall(regex_tags, request.text, re.MULTILINE)
# make sure we treat integers correctly with join()
# according to http://stackoverflow.com/a/7323861
# (very unlikely, but better safe than sorry!)
output['genre'] = ' '.join(s for s in tags)
try:
artUrl = request.text.split("\"tralbumArt\">")[1].split("\">")[0].split("href=\"")[1]
output['artFullsizeUrl'] = artUrl
except:
puts_safe(colored.red("Couldn't get full artwork") + "")
output['artFullsizeUrl'] = None
return output
####################################################################
# Mixcloud
####################################################################
def process_mixcloud(vargs):
"""
Main MixCloud path.
"""
artist_url = vargs['artist_url']
if 'mixcloud.com' in artist_url:
mc_url = artist_url
else:
mc_url = 'https://mixcloud.com/' + artist_url
filenames = scrape_mixcloud_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames)
return
def scrape_mixcloud_url(mc_url, num_tracks=sys.maxsize, folders=False, custom_path=''):
"""
Returns:
list: filenames to open
"""
try:
data = get_mixcloud_data(mc_url)
except Exception as e:
puts_safe(colored.red("Problem downloading ") + mc_url)
print(e)
return []
filenames = []
track_artist = sanitize_filename(data['artist'])
track_title = sanitize_filename(data['title'])
track_filename = track_artist + ' - ' + track_title + data['mp3_url'][-4:]
if folders:
track_artist_path = join(custom_path, track_artist)
if not exists(track_artist_path):
mkdir(track_artist_path)
track_filename = join(track_artist_path, track_filename)
if exists(track_filename):
puts_safe(colored.yellow("Skipping") + colored.white(': ' + data['title'] + " - it already exists!"))
return []
else:
track_filename = join(custom_path, track_filename)
puts_safe(colored.green("Downloading") + colored.white(
': ' + data['artist'] + " - " + data['title'] + " (" + track_filename[-4:] + ")"))
download_file(data['mp3_url'], track_filename)
if track_filename[-4:] == '.mp3':
tag_file(track_filename,
artist=data['artist'],
title=data['title'],
year=data['year'],
genre="Mix",
artwork_url=data['artwork_url'])
filenames.append(track_filename)
return filenames
def get_mixcloud_data(url):
"""
Scrapes a Mixcloud page for a track's important information.
Returns:
dict: containing audio data
"""
data = {}
request = requests.get(url)
preview_mp3_url = request.text.split('m-preview="')[1].split('" m-preview-light')[0]
song_uuid = request.text.split('m-preview="')[1].split('" m-preview-light')[0].split('previews/')[1].split('.mp3')[0]
# Fish for the m4a..
for server in range(1, 23):
# Ex: https://stream6.mixcloud.com/c/m4a/64/1/2/0/9/30fe-23aa-40da-9bf3-4bee2fba649d.m4a
mp3_url = "https://stream" + str(server) + ".mixcloud.com/c/m4a/64/" + song_uuid + '.m4a'
try:
if requests.head(mp3_url).status_code == 200:
if '?' in mp3_url:
mp3_url = mp3_url.split('?')[0]
break
except Exception as e:
continue
full_title = request.text.split("<title>")[1].split(" | Mixcloud")[0]
title = full_title.split(' by ')[0].strip()
artist = full_title.split(' by ')[1].strip()
img_thumbnail_url = request.text.split('m-thumbnail-url="')[1].split(" ng-class")[0]
artwork_url = img_thumbnail_url.replace('60/', '300/').replace('60/', '300/').replace('//', 'https://').replace('"',
'')
data['mp3_url'] = mp3_url
data['title'] = title
data['artist'] = artist
data['artwork_url'] = artwork_url
data['year'] = None
return data
####################################################################
# Audiomack
####################################################################
def process_audiomack(vargs):
"""
Main Audiomack path.
"""
artist_url = vargs['artist_url']
if 'audiomack.com' in artist_url:
mc_url = artist_url
else:
mc_url = 'https://audiomack.com/' + artist_url
filenames = scrape_audiomack_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames)
return
def scrape_audiomack_url(mc_url, num_tracks=sys.maxsize, folders=False, custom_path=''):
"""
Returns:
list: filenames to open
"""
try:
data = get_audiomack_data(mc_url)
except Exception as e:
puts_safe(colored.red("Problem downloading ") + mc_url)
print(e)
filenames = []
track_artist = sanitize_filename(data['artist'])
track_title = sanitize_filename(data['title'])
track_filename = track_artist + ' - ' + track_title + '.mp3'
if folders:
track_artist_path = join(custom_path, track_artist)
if not exists(track_artist_path):
mkdir(track_artist_path)
track_filename = join(track_artist_path, track_filename)
if exists(track_filename):
puts_safe(colored.yellow("Skipping") + colored.white(': ' + data['title'] + " - it already exists!"))
return []
else:
track_filename = join(custom_path, track_filename)
puts_safe(colored.green("Downloading") + colored.white(': ' + data['artist'] + " - " + data['title']))
download_file(data['mp3_url'], track_filename)
tag_file(track_filename,
artist=data['artist'],
title=data['title'],
year=data['year'],
genre=None,
artwork_url=data['artwork_url'])
filenames.append(track_filename)
return filenames
def get_audiomack_data(url):
"""
Scrapes a Mixcloud page for a track's important information.
Returns:
dict: containing audio data
"""
data = {}
request = requests.get(url)
mp3_url = request.text.split('class="player-icon download-song" title="Download" href="')[1].split('"')[0]
artist = request.text.split('<span class="artist">')[1].split('</span>')[0].strip()
title = request.text.split('<span class="artist">')[1].split('</span>')[1].split('</h1>')[0].strip()
artwork_url = request.text.split('<a class="lightbox-trigger" href="')[1].split('" data')[0].strip()
data['mp3_url'] = mp3_url
data['title'] = title
data['artist'] = artist
data['artwork_url'] = artwork_url
data['year'] = None
return data
####################################################################
# Hive.co
####################################################################
def process_hive(vargs):
"""
Main Hive.co path.
"""
artist_url = vargs['artist_url']
if 'hive.co' in artist_url:
mc_url = artist_url
else:
mc_url = 'https://www.hive.co/downloads/download/' + artist_url
filenames = scrape_hive_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames)
return
def scrape_hive_url(mc_url, num_tracks=sys.maxsize, folders=False, custom_path=''):
"""
Scrape a Hive.co download page.
Returns:
list: filenames to open
"""
try:
data = get_hive_data(mc_url)
except Exception as e:
puts_safe(colored.red("Problem downloading ") + mc_url)
print(e)
filenames = []
# track_artist = sanitize_filename(data['artist'])
# track_title = sanitize_filename(data['title'])
# track_filename = track_artist + ' - ' + track_title + '.mp3'