-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
executable file
·1219 lines (1031 loc) · 62.3 KB
/
data.py
File metadata and controls
executable file
·1219 lines (1031 loc) · 62.3 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
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
import sqlite3 as sql
import pbkdf2
import os
import os.path
import sys
import re
import threading
import subprocess
import mutagen.mp4
import mutagen.aiff
import mutagen.wave
import mutagen.flac
import mutagen.mp3
import mutagen.ogg
import contextlib
import io
import json
import time
import warnings
#import urllib.parse
#import urllib.request
import logging
from itunes_artwork import AppleDownloader, MetadataContainer
PRODUCTION = True # Determines whether the application uses a development-grade or production-grade server
configuration = {}
DO_ARTWORK = False
#Initialize logging
logging.basicConfig(format='%(asctime)s %(levelname)s %(filename)s %(funcName)s:%(lineno)d %(name)s %(message)s')
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
pbkdf2.salt = os.urandom(32)
lock = threading.Lock() # This is a multithreaded application, use a lock to prevent the entire program from doing segfault.
# I was previously unaware it was even possible to cause Python to segfault. Isn't this something that should only exist in the depths
# of C somewhere, a holdover from the 1980s?
# Define structure of database.
STRUCTURE_ALBUMS = '''
CREATE TABLE ALBUMS(
TITLE TEXT NOT NULL,
ARTIST TEXT NOT NULL,
GENRE TEXT NOT NULL,
ARTWORK TEXT NOT NULL,
YEAR TEXT NOT NULL,
UNIQUE_ID INTEGER NOT NULL,
ARTIST_SORTED TEXT NOT NULL)
'''
STRUCTURE_SONGS = '''
CREATE TABLE SONGS(
FILE TEXT NOT NULL,
TITLE TEXT NOT NULL,
ALBUM TEXT NOT NULL,
NUMBER TEXT NOT NULL,
LENGTH TEXT NOT NULL,
ENCTYPE TEXT NOT NULL,
UNIQUE_ID INTEGER NOT NULL,
SORTING TEXT NOT NULL)
'''
STRUCTURE_PLAYLISTS = '''
CREATE TABLE PLAYLISTS(
NAME TEXT NOT NULL,
CONTENTS TEXT NOT NULL,
MODIFIED_TIME INTEGER NOT NULL)
'''
# Set these to -1 so that the first id is 0; they are incremented before the value is returned because `return` causes the function to exit
#SQLite may have a way to do this automatically, but to keep things isolated, I do it this way. If I used SQL IDs, I don't think I would get separate
# namespaces for songs and albums.
ID_COUNTER_SONGS = -1
ID_COUNTER_ALBUMS = -1
def generate_song_id():
global ID_COUNTER_SONGS
ID_COUNTER_SONGS += 1
assert not ID_COUNTER_SONGS < 0 # sanity check
return ID_COUNTER_SONGS
def generate_album_id():
global ID_COUNTER_ALBUMS
ID_COUNTER_ALBUMS += 1
assert not ID_COUNTER_ALBUMS < 0
return ID_COUNTER_ALBUMS
class DuplicateCreationError(Exception):
# raised when the web app tries to create a duplicate that should not exist
pass
class DuplicateAdditionError(Exception):
# raised when a song is added in duplicate to a playlist
pass
class PlaylistContainer:
# contains playlist information in named quantites, used to work around a problem with Jinja templates caused by esoteric three- and four-dimensional arrays
def __init__(self, array, db):
# array is presumed to be the result of webstereoDB.fetch_all_playlists()[0]
self.title = array[0]
self.contents = []
self.modified_time = time.ctime(int(array[2]))
pl_songs = array[1].split('\t')
if len(pl_songs) > 1:
for i in pl_songs:
try:
self.contents.append(db.find_song_by_id(i))
except IndexError:
pass
else:
self.contents = []
log.debug('contents: %s' % self.contents)
class WebStereoDB:
# Due in roughly equal measure to early design mistakes and the nature of SQL/SQLite's Python bindings, data is handled in lists with numbered indices rather than dicts with named keys.
# For that reason, the following constants are used to avoid magic numbers scattered throughout the code.
DB_SONG_FILE = 0
DB_SONG_TITLE = 1
DB_SONG_ALBUM = 2
DB_SONG_TRACK_NUMBER = 3
DB_SONG_LENGTH = 4
DB_SONG_ENCTYPE = 5
DB_SONG_ID = 6
# Don't expose the sorting mechanism in the database. However, some routes in webstereo.py add data onto the arrays returned by the database using append. In the event that the structure of the SQL table is ever expanded, use
# this variable referring to a nonexistent space so as to make that data accessible without magic-number constants in certain routes/templates and, relatedly, without requiring major refactors each time that happens
DB_SONG_UNALLOCATED_SPACE = 8
DB_ALBUM_TITLE = 0
DB_ALBUM_ARTIST = 1
DB_ALBUM_GENRE = 2
DB_ALBUM_ARTWORK = 3
DB_ALBUM_YEAR = 4
DB_ALBUM_ID = 5
DB_ALBUM_UNALLOCATED_SPACE = 7 # See above note for songs
DB_PLAYLIST_NAME = 0
DB_PLAYLIST_CONTENTS = 1
DB_PLAYLIST_MODIFIED_TIME = 2
PAUSE_COMMIT = False # When this is set to true, query() will not automatically commit changes to disk. This helps to optimize situations (such as in build_from()) where there are hundreds or thousands of database transactions.
IGNORE_SORTING_CHARACTERS = ['the ', 'a ', "'", '(', '[', '...'] # Don't include the following at the beginnig of the database field that controls sorting, to avoid placing "The" under T and so forth.
def __init__(self, dbpath=None):
# Check for explicit database path to override config.json
if dbpath:
path = dbpath
else:
path = configuration['db-path']
# Connect to the database and write (if it does not already exist) the structure defined above
self.connection = sql.connect(path, check_same_thread=False)
self.cursor = self.connection.cursor()
try:
self.cursor.execute(STRUCTURE_ALBUMS)
self.cursor.execute(STRUCTURE_SONGS)
self.cursor.execute(STRUCTURE_PLAYLISTS)
except sql.OperationalError as e:
sys.stderr.write(str(e))
sys.stderr.write('\n')
# Get statistics on DB
albums_count = len(self.fetch_albums(silence=True))
songs_count = len(self.fetch_songs())
self.STATISTICS_MSG = "{} albums, {} songs".format(albums_count, songs_count)
def query(self, command, data=None):
# Perform an SQL query on the database. This wrapper function exists so that another SQL client/implementation could be used as a (at any rate, more of a) drop-in replacement for Python's built-in SQLite.
if data:
try:
lock.acquire(True)
cmd = self.cursor.execute(command, data)
finally:
lock.release()
else:
try:
lock.acquire(True)
cmd = self.cursor.execute(command)
finally:
lock.release()
try:
lock.acquire(True)
result = cmd.fetchall()
finally:
lock.release()
if not self.PAUSE_COMMIT:
self.commit()
return result
def commit(self):
self.connection.commit()
def create_album(self, title, artist, genre, year, artwork=''):
artist_sorted = artist
for i in self.IGNORE_SORTING_CHARACTERS:
artist_sorted = artist_sorted.removeprefix(i)
self.query('INSERT INTO ALBUMS (TITLE, ARTIST, GENRE, ARTWORK, YEAR, UNIQUE_ID, ARTIST_SORTED) VALUES (?, ?, ?, ?, ?, ?, ?)', [str(title),
str(artist),
str(genre),
str(artwork),
str(year),
generate_album_id(),
artist_sorted
])
self.commit()
def edit_album(self, album_id, data):
self.query('UPDATE ALBUMS SET TITLE = ?, ARTIST = ?, GENRE = ?, YEAR = ? WHERE UNIQUE_ID = ?',
[data['title'], data['artist'], data['genre'], data['year'], album_id])
self.commit()
def fetch_albums(self, sort_by='ARTIST', silence=False):
# Ideally, this would pass sort_by directly into the SQL, but that doesn't work- I'm not quite certain as to why.
if sort_by == 'ARTIST':
result = self.query('SELECT * FROM ALBUMS ORDER BY ARTIST, YEAR COLLATE NOCASE ASC') # [sort_by])
elif sort_by == 'TITLE':
result = self.query('SELECT * FROM ALBUMS ORDER BY TITLE COLLATE NOCASE ASC')
elif sort_by == 'GENRE':
result = self.query('SELECT * FROM ALBUMS ORDER BY GENRE COLLATE NOCASE ASC')
elif sort_by == 'YEAR':
result = self.query('SELECT * FROM ALBUMS ORDER BY YEAR COLLATE NOCASE ASC')
if not silence:
log.debug('ALBUMS: %s' % result)
return result
def search_albums(self, title):
result = self.query('SELECT * FROM ALBUMS WHERE TITLE = ?', [str(title)])
return result
def find_album_by_id(self, uid):
result = self.query('SELECT * FROM ALBUMS WHERE UNIQUE_ID = ?', [uid])
return result[0]
def fetch_album_artwork_by_name(self, name):
return self.fetch_album_artwork_by_id(self.search_albums(name)[0][self.DB_ALBUM_ID])
def fetch_album_artwork_by_id(self, uid):
result = self.query('SELECT * FROM ALBUMS WHERE UNIQUE_ID = ?', [uid])
if len(result) != 0:
path = result[0][self.DB_ALBUM_ARTWORK] # Artwork path
if os.path.isfile(path):
return path # If the file exists, return its path
else:
# if the file does not exist, return nothing. The flask application will send default artwork.
return None
else:
return None
def fetch_album_contents(self, name):
result = self.query('SELECT * FROM SONGS WHERE ALBUM = ? ORDER BY NUMBER', [name])
songs = []
return result # songs
def search_in_albums(self, search_query):
q = '%' + search_query + '%'
results = self.query('SELECT * FROM ALBUMS WHERE TITLE like ?', [q])
return results
def create_song(self, file, title, album, number, length=0, enctype=''):
# Create a separate field without leading special characters or articles to prevent placing songs with "The" under T and similar problems.
sorted_title = title.lower() # case-insensitive
for i in self.IGNORE_SORTING_CHARACTERS:
sorted_title = sorted_title.removeprefix(i)
self.query('INSERT INTO SONGS (FILE, TITLE, ALBUM, NUMBER, LENGTH, ENCTYPE, UNIQUE_ID, SORTING) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [
str(file),
str(title),
str(album),
str(number),
str(length),
str(enctype),
generate_song_id(),
sorted_title
])
self.commit()
def edit_song(self, song_id, data):
global VERBOSE
# Update values in database
self.query('UPDATE SONGS SET TITLE = ?, ALBUM = ?, NUMBER = ? WHERE UNIQUE_ID = ?',
[data['new_title'],
data['album'],
data['number'],
unique_id])
# Write metadata to the file itself on disk
try:
result = self.query('SELECT * FROM SONGS WHERE TITLE = ?', [data['title']])
file_path = result[0] # [0] # Get first attribute of first result.
file_type = os.path.splitext(file_path) # Extension
if file_type == 'm4a':
file = mutagen.mp4.MP4(file_path)
file['\xa9alb'] = data['album']
elif file_type == 'flac':
file = mutagen.flac.FLAC(file_path)
file['TALB'] = data['album']
self.commit()
except Exception as e:
log.debug('Encountered the following exception in writing metadata: %s' % str(e))
def fetch_songs(self, sort_by='TITLE'):
# See the fetch_albums function an explanation of this inelegant approach
if sort_by == 'NUMBER':
q = 'SELECT * FROM SONGS ORDER BY NUMBER COLLATE NOCASE ASC'
elif sort_by == 'ALBUM':
q = 'SELECT * FROM SONGS ORDER BY ALBUM COLLATE NOCASE ASC'
elif sort_by == 'TITLE':
q = 'SELECT * FROM SONGS ORDER BY SORTING COLLATE NOCASE ASC'
# result = self.query('SELECT * FROM SONG S ORDER BY ?', [sort_by])
result = self.query(q)
return result
def fetch_all_song_data(self, sort_by='NUMBER, TITLE'):
song_query = self.query('SELECT * FROM SONGS ORDER BY ?', [sort_by])
return song_query
def find_songs(self, name):
result = self.query('SELECT * FROM SONGS WHERE TITLE = ?', [name])
return result[0]
def find_song_by_id(self, uid):
result = self.query('SELECT * FROM SONGS WHERE UNIQUE_ID = ?', [uid])
if len(result) == 0:
# Don't throw an IndexError if there are no results.
return []
return result[0] # only one result, so nothing is lost here.
def find_songs_with_album(self, name, album):
result = self.query('SELECT * FROM SONGS WHERE TITLE = ? AND ALBUM = ?', [name, album])[0] # There should only ever be one result
return result
def search_in_songs(self, search_query):
q = '%' + search_query + '%'
results = self.query('SELECT * FROM SONGS WHERE TITLE like ?', [q])
return results
def check_if_song_exists(self, file):
# Used to determine whether to index a song - does it exist.
result = self.query('SELECT * FROM SONGS WHERE FILE = ?', [file])
if result:
return True
else:
return False
# Playlist contents are stored as strings with song IDs delineated by \t.
def create_playlist(self, name):
# creates a new playlist of name, with a delimiter string as initial contents
(self.search_playlist(name))
if self.search_playlist(name):
raise DuplicateCreationError('cannot create duplicate playlist')
else:
self.query('INSERT INTO PLAYLISTS (NAME, CONTENTS, MODIFIED_TIME) VALUES (?, ?, ?)', [name, '', int(time.time())])
def append_to_playlist(self, plist, song_id):
log.debug('playlist is %s, song is %d' % (plist, song_id))
contents = self.query('SELECT * from PLAYLISTS WHERE NAME = ?', [plist])[0][1] # Get present contents of playlist
log.debug('playlist contents are %s' % contents)
contents = contents + '\t' + str(song_id)
self.query('UPDATE PLAYLISTS SET CONTENTS = ?, MODIFIED_TIME = ? WHERE NAME = ?', [contents, int(time.time()), plist])
log.debug('playlist contents set to %s' % contents)
log.debug('playlist contents accessible as %s' % self.fetch_playlist_contents(plist))
self.commit()
def delete_from_playlist(self, plist, song_id):
contents = self.query('SELECT * FROM PLAYLISTS WHERE NAME = ?', [plist])[0][1]
contents = contents.replace('\t{}'.format(song_id), '\t') # preserve delineating tab character while removing value
while '\t\t' in contents:
contents = contents.replace('\t\t', '\t') # If a value occurs at the end of the contents string, duplicate \t s are possible; pre-empt them here.
# Empty song spaces will appear if this is only one tab characters; contents will create the object over which Jinja iterates.
if contents == '\t':
contents = ""
self.query('UPDATE PLAYLISTS SET CONTENTS = ? WHERE NAME = ?', [contents, plist])
def fetch_playlist_contents(self, plist):
results = self.query('SELECT * FROM PLAYLISTS WHERE NAME = ?', [plist])[0][1].split('\t')
return results
def fetch_all_playlist_names(self):
_results = self.query('SELECT * FROM PLAYLISTS ORDER BY MODIFIED_TIME')
results = []
for i in _results:
results.append(i[0]) # only add name of each playlist
return results
def fetch_all_playlists(self):
sql_results = self.query('SELECT * FROM PLAYLISTS ORDER BY MODIFIED_TIME')
playlists = []
for i in sql_results:
playlists.append(PlaylistContainer(i, self))
# a webstereoDB object must be passed because this object's constructor calls a non-static method on it; do that unsightly part here, safely obscured in the database
# logic that is already unpleasant to look at.
return playlists
def search_playlist(self, name):
results = self.query('SELECT * FROM PLAYLISTS WHERE NAME = ? ORDER BY MODIFIED_TIME', [name])
return results
def build_from(self, location):
# Here be dragons, to borrow the time-honored adage
build_timer = time.time()
self.PAUSE_COMMIT = True
log.info(location)
artists = os.listdir(location)
downloader = AppleDownloader(True, True, DO_ARTWORK)
log.info('WILL REMOVE %s' % location)
self.query('DROP TABLE SONGS')
self.query('DROP TABLE ALBUMS')
self.query(STRUCTURE_SONGS)
self.query(STRUCTURE_ALBUMS)
for artist in artists:
log.debug('level 1: %s' % artist)
if os.path.isdir(location + artist):
albums = os.listdir(location + artist)
for album in albums:
log.debug('level 2: %s' % album)
if os.path.isdir(location + artist + '/' + album):
songs = sorted(os.listdir(location + artist + '/' + album))
song_index = 1 # used to assign track numbers if all else fails.
for song in songs:
log.info(song)
# MacOS X (presumably for Spotlight search indexing) creates files that have the exact same name- and thus, crucially, the same extension
#that are prepended with ._. Should mutagen try to read these, it dies. Do this to prevent that unpleasant outcome.
if song[0] == '.' and song[1] == '_':
os.remove(location + artist + '/' + album + '/' + song)
continue
log.debug('level 3: %s' % song)
encoding_type = os.path.splitext(song)[1]
#APPLE M4A AAC IMPORT ENGINE
if encoding_type.__contains__('m4a'): # song.__contains__('m4a'):
# Song is an AAC MP4 audio file, process it accordingly
song_file = mutagen.mp4.MP4(location + artist + '/' + album + '/' + song) # mutagen.M4A is depreciated, use this as a replacement
song_file.pprint()
song_album = song_file.tags['\xa9alb'][0]
try:
song_number = song_file.tags['TRCK']
except KeyError:
# sometimes iTunes libraries will put this before the song name. We can't remove it, because there is a chance that it's not there, and some song titles consist only of numbers
# see "99" by Toto and "7" by Prince, for example.
song_number = song.split(' ')[0]
except TypeError:
song_number = song.split(' ')[0]
for i in song_number:
if i not in '1234567890': # non-numerical value
if song_index > 10:
song_number = str(song_index)
else:
song_number = '0' + str(song_index)
break
song_title = song_file.tags['\xa9nam'][0]
# The _ operator in Python is used to denote hidden / preliminary things but also has some semantic meaning. This seems to work, however, and I really, really do not want to refactor it.
_length = song_file.info.length
_length_minutes = int(_length / 60)
_length_seconds = int(_length % 60)
if _length_seconds < 10:
# Add leading zero if needed
_length_seconds = '0{}'.format(_length_seconds)
song_length = str(_length_minutes) + ':' + str(_length_seconds)
# If this album does not exist, create it
if not self.search_albums(song_album):
album_artist = song_file.tags['\xa9ART'][0]
try:
album_year = song_file.tags['\xa9day'][0][
0:4] # Only use the year, omit the rest of this timestamp.
album_genre = song_file.tags['\xa9gen'][0]
except KeyError:
album_year = '2021' # This tag in particular has given me problems with KeyError
album_genre = 'Unknown Genre'
artwork_path = location + artist + '/' + album + '/' + 'artwork.jpg'
try:
album_cover = song_file.tags['covr']
try:
os.remove(artwork_path) # Keep artwork up-to-date
except FileNotFoundError:
pass
except UnboundLocalError:
pass
fbuf = open(artwork_path, 'wb')
fbuf.write(album_cover[0])
fbuf.flush()
fbuf.close()
except KeyError:
log.error('could not read cover art from metadata, downloading from network')
meta = MetadataContainer(album, artist)
downloader.download(meta, artwork_path)
self.create_album(song_album,
album_artist,
album_genre,
album_year,
artwork=artwork_path)
if not self.check_if_song_exists(
location + artist + '/' + album + '/' + song):
self.create_song(location + artist + '/' + album + '/' + song,
song_title,
song_album,
song_number,
song_length,
'MP4')
else:
log.debug("song exists")
# APPLE LOSSLESS (AIFF) IMPORT CODE
elif encoding_type.__contains__('aif'):
# Song is in Apple lossless format, process its tags accordingly.
song_path = location + artist + '/' + album + '/' + song
try:
song_file = mutagen.aiff.AIFF(song_path)
except Exception as e:
log.error('failed to read :%s' % song, )
continue
song_file.pprint()
try:
song_album = song_file.tags['TALB'][0]
except KeyError:
# If the album tag can't be read, use the folder name
song_album = album
except TypeError:
# NoneType returned, not subscriptable
song_album = album
if song_file.tags is None: continue
try:
song_number = song_file.tags['TRCK']
except KeyError:
song_number = song.split(' ')[0]
for i in song_number:
if i not in '1234567890': # non-numerical data
if song_index > 10:
song_number = str(song_index)
else:
song_number = '0' + str(song_index)
break
try:
song_title = song_file.tags['TIT2'][0]
except KeyError:
# If the title tag can't be read, use the filename without the extensions
song_title = os.path.splitext(song)[0]
except TypeError:
# NoneType returned, not subscriptable
song_album = album
_length = song_file.info.length
_length_minutes = int(_length / 60)
_length_seconds = int(_length % 60)
if _length_seconds < 10:
_length_seconds = '0{}'.format(_length_seconds)
song_length = str(_length_minutes) + ':' + str(_length_seconds)
# If this album does not exist, create it
if not self.search_albums(song_album):
artwork_path = location + artist + '/' + album + '/' + 'artwork.jpg'
try:
album_cover = song_file.tags['covr']
try:
os.remove(artwork_path) # Keep artwork up-to-date
except FileNotFoundError:
pass
fbuf = open(artwork_path, 'wb')
fbuf.write(album_cover[0])
fbuf.flush()
fbuf.close()
except KeyError:
log.error('could not read cover art from metadata, downloading from network')
if artist.lower() == 'compilations': # Compilations directory from iTunes
_artist = 'Various Artists'
else:
_artist = artist
meta = MetadataContainer(album, _artist)
downloader.download(meta, artwork_path)
except TypeError:
log.debug('could not read cover art from metadata, downloading from network')
meta = MetadataContainer(album, artist)
downloader.download(meta, artwork_path)
try:
album_artist = song_file.tags['TOPE'][0]
except KeyError:
# If the album tag can't be read, use the name of the artist directory
album_artist = artist
if album_artist == 'Compilations':
# This is in the 'compilations' directory from iTunes. Make artist name 'Various Artists'
album_artist = 'Various Artists'
except TypeError:
album_artist = artist
try:
album_genre = song_file.tags[''][0]
except KeyError:
# album_year = '2021' # This tag in particular has given me problems with KeyError
album_genre = 'Unknown Genre'
except TypeError:
# album_year = '2021' # This tag in particular has given me problems with KeyError
album_genre = 'Unknown Genre'
try:
album_year = song_file.tags['TYER'][0]
except KeyError:
album_year = '2021'
except TypeError:
album_year = '2021'
self.create_album(song_album,
album_artist,
album_genre,
album_year,
artwork=artwork_path)
# if True: # self.check_if_song_exists(flac_path):
self.create_song(song_path, # Add FLAC file to database
song_title,
song_album,
song_number,
song_length,
'AIFF'
)
# self.create_song(location + artist + '/' + album + '/' + song,
# song_title, song_album, song_number, song_length)
elif encoding_type.__contains__('flac'):
# Song is a FLAC file, process it accordingly.
try:
song_file = mutagen.aiff.AIFF(
location + artist + '/' + album + '/' + song)
except Exception:
# bind to Exception because a broad array of errors can occur and none of them really matter.
log.error('failed to read :%s' % song, )
continue
song_file.pprint()
try:
song_album = song_file.tags['TALB'][0]
except KeyError:
# If the album tag can't be read, use the folder name
song_album = album
except TypeError:
# NoneType returned, not subscriptable
song_album = album
song_number = song.split(' ')[0]
if song_number[0] == '0':
song_number = song_number[1]
try:
song_title = song_file.tags['TIT2'][0]
except KeyError:
# If the title tag can't be read, use the filename without the extensions
song_title = os.path.splitext(song)[0]
except TypeError:
# NoneType returned, not subscriptable
song_album = album
_length = song_file.info.length
_length_minutes = int(_length / 60)
_length_seconds = int(_length % 60)
if _length_seconds < 10:
# Add leading zero if needed
_length_seconds = '0{}'.format(_length_seconds)
song_length = str(_length_minutes) + ':' + str(_length_seconds)
# If this album does not exist, create it
if not self.search_albums(song_album):
artwork_path = location + artist + '/' + album + '/' + 'artwork.jpg'
try:
album_cover = song_file.tags['covr']
try:
os.remove(artwork_path) # Keep artwork up-to-date
except FileNotFoundError:
pass
fbuf = open(artwork_path, 'wb')
fbuf.write(album_cover[0])
fbuf.flush()
fbuf.close()
except KeyError:
log.debug('could not read cover art from metadata, downloading from network')
if artist.lower() == 'compilations': # Compilations directory from iTunes
_artist = 'Various Artists'
else:
_artist = artist
meta = MetadataContainer(album, _artist)
downloader.download(meta, artwork_path)
except TypeError:
log.debug('could not read cover art from metadata, downloading from network')
meta = MetadataContainer(album, artist)
downloader.download(meta, artwork_path)
try:
album_artist = song_file.tags['TOPE'][0]
except KeyError:
# If the album tag can't be read, use the name of the artist directory
album_artist = artist
if album_artist == 'Compilations':
# This is in the 'compilations' directory from iTunes. Make artist name 'Various Artists'
album_artist = 'Various Artists'
except TypeError:
album_artist = artist
try:
album_genre = song_file.tags[''][0]
except KeyError:
# album_year = '2021' # This tag in particular has given me problems with KeyError
album_genre = 'Unknown Genre'
except TypeError:
# album_year = '2021' # This tag in particular has given me problems with KeyError
album_genre = 'Unknown Genre'
try:
album_year = song_file.tags['TYER'][0]
except KeyError:
album_year = '2021'
except TypeError:
album_year = '2021'
self.create_album(song_album,
album_artist,
album_genre,
album_year,
artwork=artwork_path
)
self.create_song(location + artist + '/' + album + '/' + song,
song_title,
song_album,
song_number,
song_length,
'FLAC'
)
# MPEG-3 AUDIO IMPORT CODE
elif encoding_type.__contains__('mp3'):
# Song is an MP3 file, process it accordingly
try:
song_file = mutagen.mp3.MP3(location + artist + '/' + album + '/' + song)
except Exception as e:
log.error('failed to read :%s' % song, )
continue
song_file.pprint()
try:
song_album = song_file.tags['TALB'][0]
except KeyError:
# If the album tag can't be read, use the folder name
song_album = album
except TypeError:
# NoneType returned, not subscriptable
song_album = album
try:
song_number = song_file.tags['TRCK']
finally:
song_number = song.split(' ')[0]
for i in song_number:
if i not in '1234567890': # non-numerical data is not a valid track number
if song_index > 10:
song_number = str(song_index)
else:
song_number = '0' + str(song_index)
break
try:
song_title = song_file.tags['TIT2'][0]
except KeyError:
# If the title tag can't be read, use the filename without the extensions
song_title = os.path.splitext(song)[0]
except TypeError:
# NoneType returned, not subscriptable
song_album = album
_length = song_file.info.length
_length_minutes = int(_length / 60)
_length_seconds = int(_length % 60)
if _length_seconds < 10:
_length_seconds = '0%s' % str(_length_seconds)
song_length = str(_length_minutes) + ':' + str(_length_seconds)
# If this album does not exist, create it
if not self.search_albums(song_album):
artwork_path = location + artist + '/' + album + '/' + 'artwork.jpg'
try:
album_cover = song_file.tags['covr']
try:
os.remove(artwork_path) # Keep artwork up-to-date
except FileNotFoundError:
pass
fbuf = open(artwork_path, 'wb')
fbuf.write(album_cover[0])
log.info('cover data: %s' % album_cover)
fbuf.flush()
fbuf.close()
except KeyError:
log.debug('could not read cover art from metadata, downloading from network')
if artist.lower() == 'compilations': # Compilations directory from iTunes
_artist = 'Various Artists'
else:
_artist = artist
meta = MetadataContainer(album, _artist)
downloader.download(meta, artwork_path)
except TypeError:
log.info('could not read cover art from metadata, downloading from network')
meta = MetadataContainer(album, artist)
downloader.download(meta, artwork_path)
try:
album_artist = song_file.tags['TOPE'][0]
except KeyError:
# If the album tag can't be read, use the name of the artist directory
album_artist = artist
if album_artist == 'Compilations':
# This is in the 'compilations' directory from iTunes. Make artist name 'Various Artists'
album_artist = 'Various Artists'
except TypeError:
album_artist = artist
try:
album_genre = song_file.tags[''][0]
except KeyError:
# album_year = '2021' # This tag in particular has given me problems with KeyError
album_genre = 'Unknown Genre'
except TypeError:
# album_year = '2021' # This tag in particular has given me problems with KeyError
album_genre = 'Unknown Genre'
try:
album_year = song_file.tags['TYER'][0]
except KeyError:
album_year = '2021'
except TypeError:
album_year = '2021'
self.create_album(song_album,
album_artist,
album_genre,
album_year,
artwork=artwork_path
)
self.create_song(location + artist + '/' + album + '/' + song,
song_title,
song_album,
song_number,
song_length,
'MP3'
)
# WAVE AUDIO IMPORT CODE
elif encoding_type.__contains__('wav'):
# WAV files don't have portable metadata. Just use file names etc.
song_title = os.path.splitext(song)[0]
song_number = song.split(' ')[0]
for i in song_number: # non-numerical value
if i not in '1234567890':
if song_index > 10:
song_number = str(song_index)
else:
song_number = '0' + str(song_index)
break
song_album = album
song_file = mutagen.wave.WAVE(
location + artist + '/' + album + '/' + song)
# Control for track numbers that contain leading zeroes
if song_number[0] == '0' and len(song_number) > 1:
song_number = song_number[1]
_length = song_file.info.length
_length_minutes = int(_length / 60)
_length_seconds = int(_length % 60)
if _length_seconds < 10:
# Append leading zero if required
_length_seconds = '0{}'.format(_length_seconds)
song_length = str(_length_minutes) + ':' + str(_length_seconds)
if not self.search_albums(song_album):
artwork_path = location + artist + '/' + album + '/' + 'artwork.jpg'
try:
album_cover = song_file.tags['covr']
try:
os.remove(artwork_path) # Keep artwork up-to-date
except FileNotFoundError:
pass
fbuf = open(artwork_path, 'wb')
fbuf.write(album_cover[0])
log.info('cover data: %s' % album_cover)
fbuf.flush()
fbuf.close()
except KeyError:
log.debug('could not read cover art from metadata, downloading from network')
meta = MetadataContainer(album, artist)
downloader.download(meta, artwork_path)
except TypeError:
log.info('could not read cover art from metadata, downloading from network')
meta = MetadataContainer(album, artist)
downloader.download(meta, artwork_path)
album_title = album
album_year = '2021'
album_genre = 'Unknown Genre'
album_artist = artist
self.create_album(song_album,
album_artist,
album_genre,
album_year,
artwork=artwork_path
)
self.create_song(location + artist + '/' + album + '/' + song,
song_title,
song_album,
song_number,
song_length,
'WAVE'
)
# OGG CONTAINER IMPORT CODE
elif encoding_type.__contains__('ogg'):
# Song is an OGG audio file, process it accordingly
song_file = mutagen.ogg.OggFileType(
location + artist + '/' + album + '/' + song)
song_file.pprint()
song_album = song_file.tags['\xa9alb'][0]
try:
song_number = song_file.tags['TRCK']
except KeyError:
song_number = song.split(' ')[0]
for i in song_number:
if i not in '1234567890':
if song_index > 10:
song_number = str(song_index)
else:
song_number = '0' + str(song_index)
break
song_title = song_file.tags['\xa9nam'][0]
_length = song_file.info.length
_length_minutes = int(_length / 60)
_length_seconds = int(_length % 60)
if _length_seconds < 10:
# Add leading zero if needed
_length_seconds = '0{}'.format(_length_seconds)