| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- #!/usr/bin/env python3
- """Minimal MPD server for exercising the UI's commands without touching a real
- player. Records every command received to the file given as the second
- argument. Usage: fake_mpd.py PORT LOGFILE [IDLE_EVENT_SECONDS]
- """
- import socketserver
- import sys
- import threading
- log_path = sys.argv[2]
- idle_event_s = float(sys.argv[3]) if len(sys.argv) > 3 else None
- class Player:
- state = "play"
- volume = 50
- song = 2
- player = Player()
- def record(line):
- with open(log_path, "a") as f:
- f.write(line + "\n")
- class Handler(socketserver.StreamRequestHandler):
- def send(self, text):
- self.wfile.write(text.encode())
- self.wfile.flush()
- def handle(self):
- self.send("OK MPD 0.21.4\n")
- announced = False
- for raw in self.rfile:
- line = raw.decode("utf8").strip()
- cmd = line.split(" ")[0]
- if cmd != "idle":
- record(line)
- if cmd == "idle":
- # normally answered by the following noidle; optionally
- # announce a change once per connection, as a real server would
- if idle_event_s is not None and not announced:
- announced = True
- threading.Timer(
- idle_event_s, self.send, ["changed: player\nOK\n"]
- ).start()
- continue
- if cmd == "status":
- self.send(
- f"volume: {player.volume}\nrepeat: 1\nrandom: 1\nsingle: 0\n"
- f"consume: 0\nplaylist: 7\nplaylistlength: 10\n"
- f"state: {player.state}\nsong: {player.song}\nsongid: 3\n"
- "time: 83:296\nelapsed: 83.100\nbitrate: 320\nduration: 296.000\n"
- "OK\n"
- )
- elif cmd == "currentsong":
- self.send(
- "file: muzyka/test.flac\nArtist: Zażółć Gęślą\n"
- "Title: Jaźń – bardzo długi tytuł utworu, który na pewno "
- "nie zmieści się w jednej linii wyświetlacza\n"
- f"Pos: {player.song}\nId: 3\nOK\n"
- )
- elif cmd == "noidle":
- self.send("OK\n")
- elif cmd == "volume":
- player.volume += int(line.split(" ")[1].strip('"'))
- self.send("OK\n")
- elif cmd == "stop":
- player.state = "stop"
- self.send("OK\n")
- elif cmd == "play":
- player.state = "play"
- self.send("OK\n")
- elif cmd == "pause":
- player.state = "pause" if player.state == "play" else "play"
- self.send("OK\n")
- elif cmd == "next":
- player.song += 1
- self.send("OK\n")
- elif cmd == "previous":
- player.song -= 1
- self.send("OK\n")
- elif cmd == "close":
- return
- else:
- self.send(f"ACK [5@0] {{{cmd}}} unknown command\n")
- class Server(socketserver.ThreadingTCPServer):
- allow_reuse_address = True
- daemon_threads = True
- Server(("127.0.0.1", int(sys.argv[1])), Handler).serve_forever()
|