summaryrefslogtreecommitdiff
path: root/file_operations.py
blob: 9cb74fe959b39ae577f26e769ece598635d3e6b4 (plain)
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
import errors
import os
from pathlib import Path
import shutil


def remove_special_characters_for_filename(filename):
    special_chars = [
        ['-', ' '],
        ['(', ''],
        [')', ''],
        ['/', ' '],
        ['/', ' '],
        [' ', '_'],
        ["'", ''],
        ["&", 'and'],
        [chr(8217), ''],
        ['$', 's'],
        ['.', '']
    ]
    new_name = filename

    for char_set in special_chars:
        new_name = new_name.replace(char_set[0], char_set[1])

    return new_name.lower()


def save_debug_data(filename, data, debug=True):
    if debug:
        with open(filename, 'w') as f:
            f.write(data)


def move_song_to_permanent_location(music_directory, song_data, filename):
    try:
        # move song to music_directory/artist/album/artist_album_title.ext
        # excluding non filesafe characters
        artist_for_filename = remove_special_characters_for_filename(
            song_data['artists'][0])
        album_for_filename = remove_special_characters_for_filename(
            song_data['album'])
        title_for_filename = remove_special_characters_for_filename(
            song_data['title'])

        song_output_dir = os.path.join(music_directory,
                                       artist_for_filename,
                                       album_for_filename)

        try:
            Path(song_output_dir).mkdir(parents=True, exist_ok=True)
        except OSError as ex:
            raise errors.UnableToCreateAlbumDirectoryError(ex)

        new_filename = '{}_{}_{}.mp3'.format(artist_for_filename,
                                             album_for_filename,
                                             title_for_filename)

        shutil.move(filename, os.path.join(song_output_dir, new_filename))
    except Exception:
        print("could not move file to correct directory!")