summaryrefslogtreecommitdiff
path: root/library.py
blob: 762b18b4f63f90a9ff838e775a2474c593d6fe62 (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
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
#!/usr/bin/env python
import configparser
import mutagen
import os

from models.track import Track


def run(path=None):
    print("Scanning files")

    if path is not None:
        if os.path.isdir(path):
            store_dir(path)
        else:
            store_file(path)
    else:
        store_dir("/media/Music")


def store_file(path):
    m = mutagen.File(path, easy=True)
    if m:
        if not Track.store(path, m):
            print("Problem saving %s" % (path,))


def store_dir(path):
    file_store = []

    for root, dirs, files in os.walk(path):
        for name in files:
            file_path = "".join([root, "/", name])
            file_store.append(file_path)

    file_store.sort()
    j = 0
    media_files = 0
    print("Storing files")
    for file_path in file_store:
        j += 1
        m = mutagen.File(file_path, easy=True)
        if m:
            if not Track.store(file_path, m):
                print("Problem saving %s" % (file_path,))

            media_files += 1
        print(
            "%d%% complete, (%d files)" % (((j / len(file_store)) * 100),
                                           j)
        )
    print("Stored %d tracks" % (media_files,))


def delete_file(path):
    track = Track.find_by_path(path)

    if track:
        track_album = track.album
        track_artists = track.artists

        track.delete()

        if track_album and len(track_album.tracks) == 0:
            track_album.delete()

        for artist in track_artists:
            if len(artist.tracks) == 0:
                artist.delete()


def update_file(path):
    m = mutagen.File(path, easy=True)
    if m:
        track = Track.find_by_path(path)
        track.update(m)


def update_track_filename(oldpath, newpath):
    track = Track.find_by_path(oldpath)
    track.filename = newpath
    track.save()

if __name__ == "__main__":
    config = configparser.ConfigParser()
    config.read("mach2.ini")

    run(config["DEFAULT"]["media_dir"])