summaryrefslogtreecommitdiffstats
path: root/mpdrast/client.py
blob: 307200dc8031f6cbb959530b8ecc0c2b28c6a2b0 (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
import mpd

import time
import random

import mpdrast.process as process

class MPDrastClient(mpd.MPDClient):
    def __init__(self):
        mpd.MPDClient.__init__(self)
        self.final_dirs = []


    def connect_from_env(self, host, port):
        password = None
        infos = host.split('@')
        if len(infos) == 2:
            password = infos[0]
            host = infos[1]

        self.connect(host, port)
        if password:
            self.password(password)


    def update_final_dirs(self, path="", first=True):
        if first:
            self.final_dirs = []

        items = self.lsinfo(path)
        if first and not items:
            raise Exception("database is empty")

        files, dirs = process.get_files_and_dirs_from_db(items)
        if len(files) and len(dirs) == 0:
            self.final_dirs.append(path)
        else:
            for dir in dirs:
                self.update_final_dirs(dir, False)


    def wait_for_update(self):
        while self.status().has_key("updating_db"):
            time.sleep(1)


    def get_random_dir(self):
        return random.choice(self.final_dirs)


    def is_playlist_hungry(self, hungriness=100):
        return int(self.status()["playlistlength"]) < hungriness


    def is_playlist_empty(self):
        return int(self.status()["playlistlength"]) == 0


    def _find_changing_pos(self, number, type):
        pl = (process.process_song(item) for item in self.playlistinfo())
        value = None
        count = -1
        for song in pl:
            if value != song[type]:
                count = count + 1
                value = song[type]
            if count == number:
                return song["pos"]


    def clean_but(self, number=1, type="album"):
        pos = self._find_changing_pos(number, type)

        if pos:
            try:
                while True:
                    self.delete(pos)
            except mpd.CommandError:
                pass