demo / network-computer
Public
Copy of github.com/askrobots/network-computer (MIT): a desk you reach from anything. The original lives on GitHub.
GitStable demo
README: say this is a copy and where the original is
cde82c2
14 hours, 4 minutes ago
History
nc-radio · 7.2 KB · 195 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """Internet radio on the desk: the sound goes to whatever device is connected. |
| 3 | |
| 4 | nc-radio play NAME|URL|WORDS a station from ~/.config/nc/stations.txt by name, a |
| 5 | stream URL, or else the most-liked station on |
| 6 | radio-browser.info for those words ("jazz", "bbc world") |
| 7 | nc-radio stop |
| 8 | nc-radio now what is playing |
| 9 | nc-radio list your stations |
| 10 | nc-radio search WORDS stations on radio-browser.info (not played) |
| 11 | nc-radio pick a list to tap (the Radio icon on the desktop) |
| 12 | |
| 13 | One station at a time; playing another stops the first. Stations are a plain |
| 14 | file, "Name | stream URL" per line, made from /etc/nc-dashboard/stations.txt |
| 15 | the first time. radio-browser.info is a free, community-kept directory. |
| 16 | """ |
| 17 | import json, os, re, signal, shutil, subprocess, sys, time, urllib.parse, urllib.request |
| 18 | |
| 19 | HOME = os.path.expanduser("~") |
| 20 | STATIONS = f"{HOME}/.config/nc/stations.txt" |
| 21 | RUN = f"{os.environ.get('XDG_RUNTIME_DIR', '/tmp')}/nc-radio" |
| 22 | UA = "network-computer-desk/1 (+https://github.com/askrobots/network-computer)" |
| 23 | DIRECTORY = ["https://de1.api.radio-browser.info", "https://de2.api.radio-browser.info", |
| 24 | "https://all.api.radio-browser.info"] |
| 25 | |
| 26 | |
| 27 | def mine(): |
| 28 | if not os.path.exists(STATIONS) and os.path.exists("/etc/nc-dashboard/stations.txt"): |
| 29 | os.makedirs(os.path.dirname(STATIONS), exist_ok=True) |
| 30 | shutil.copyfile("/etc/nc-dashboard/stations.txt", STATIONS) |
| 31 | out = [] |
| 32 | try: |
| 33 | for line in open(STATIONS): |
| 34 | line = line.strip() |
| 35 | if line and not line.startswith("#") and "|" in line: |
| 36 | name, _, url = line.rpartition("|") |
| 37 | out.append((name.strip(), url.strip())) |
| 38 | except OSError: |
| 39 | pass |
| 40 | return out |
| 41 | |
| 42 | |
| 43 | def search(words, limit=8): |
| 44 | q = urllib.parse.urlencode({"name": words, "limit": limit, "order": "votes", "reverse": "true", |
| 45 | "hidebroken": "true"}) |
| 46 | tq = urllib.parse.urlencode({"tag": words.lower(), "limit": limit, "order": "votes", "reverse": "true", |
| 47 | "hidebroken": "true"}) |
| 48 | for base in DIRECTORY: |
| 49 | try: |
| 50 | got = [] |
| 51 | for path in (f"/json/stations/search?{q}", f"/json/stations/search?{tq}"): |
| 52 | req = urllib.request.Request(base + path, headers={"User-Agent": UA}) |
| 53 | got += json.loads(urllib.request.urlopen(req, timeout=8).read()) |
| 54 | seen, out = set(), [] |
| 55 | for s in sorted(got, key=lambda s: -int(s.get("votes") or 0)): |
| 56 | url = s.get("url_resolved") or s.get("url") |
| 57 | if url and url not in seen and url.startswith(("http://", "https://")): |
| 58 | seen.add(url) |
| 59 | out.append((re.sub(r"\s+", " ", s.get("name", "")).strip()[:60] or url, url)) |
| 60 | return out[:limit] |
| 61 | except Exception: |
| 62 | continue |
| 63 | raise RuntimeError("the radio directory is not answering") |
| 64 | |
| 65 | |
| 66 | def now(): |
| 67 | try: |
| 68 | pid = int(open(f"{RUN}/pid").read()) |
| 69 | os.kill(pid, 0) |
| 70 | return open(f"{RUN}/now").read().strip() |
| 71 | except (OSError, ValueError): |
| 72 | return "" |
| 73 | |
| 74 | |
| 75 | def stop(): |
| 76 | try: |
| 77 | pid = int(open(f"{RUN}/pid").read()) |
| 78 | os.killpg(pid, signal.SIGTERM) |
| 79 | except (OSError, ValueError): |
| 80 | pass |
| 81 | for f in ("pid", "now"): |
| 82 | try: |
| 83 | os.remove(f"{RUN}/{f}") |
| 84 | except OSError: |
| 85 | pass |
| 86 | |
| 87 | |
| 88 | def resolve(what): |
| 89 | what = what.strip() |
| 90 | if re.match(r"^https?://", what): |
| 91 | return what, what |
| 92 | ms = mine() |
| 93 | w = what.lower() |
| 94 | for name, url in ms: # exact, then a part of the name |
| 95 | if name.lower() == w: |
| 96 | return name, url |
| 97 | for name, url in ms: |
| 98 | if w in name.lower(): |
| 99 | return name, url |
| 100 | hits = search(what, limit=1) |
| 101 | if not hits: |
| 102 | raise RuntimeError(f"no station for {what!r}") |
| 103 | return hits[0] |
| 104 | |
| 105 | |
| 106 | def play(what): |
| 107 | name, url = resolve(what) |
| 108 | stop() |
| 109 | os.makedirs(RUN, exist_ok=True) |
| 110 | player = ["cvlc", "--intf", "dummy", "--no-video", "--quiet", url] if shutil.which("cvlc") else \ |
| 111 | ["ffplay", "-nodisp", "-loglevel", "quiet", url] |
| 112 | p = subprocess.Popen(player, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) |
| 113 | time.sleep(2.5) |
| 114 | if p.poll() is not None: |
| 115 | raise RuntimeError(f"{name} did not play (the stream may be down)") |
| 116 | open(f"{RUN}/pid", "w").write(str(p.pid)) |
| 117 | open(f"{RUN}/now", "w").write(name) |
| 118 | return name |
| 119 | |
| 120 | |
| 121 | def pick(): |
| 122 | """A list to tap: your stations, and Stop when something plays.""" |
| 123 | rows = [] |
| 124 | playing = now() |
| 125 | if playing: |
| 126 | rows += ["■ Stop", f"playing {playing}"] |
| 127 | for name, url in mine(): |
| 128 | rows += [name, ""] |
| 129 | rows += ["Find a station…", "search radio-browser.info"] |
| 130 | r = subprocess.run(["zenity", "--list", "--title=Radio", "--width=420", "--height=520", |
| 131 | "--column=Station", "--column=", "--hide-header", *rows], |
| 132 | capture_output=True, text=True) |
| 133 | choice = r.stdout.strip().split("|")[0] |
| 134 | if not choice: |
| 135 | return |
| 136 | if choice.startswith("■"): |
| 137 | stop() |
| 138 | return |
| 139 | if choice.startswith("Find"): |
| 140 | q = subprocess.run(["zenity", "--entry", "--title=Radio", "--text=A station, a town or a kind of music:"], |
| 141 | capture_output=True, text=True).stdout.strip() |
| 142 | if not q: |
| 143 | return |
| 144 | try: |
| 145 | hits = search(q) |
| 146 | except RuntimeError as e: |
| 147 | subprocess.run(["zenity", "--error", f"--text={e}"]) |
| 148 | return |
| 149 | rows = [x for name, url in hits for x in (name, url)] |
| 150 | r = subprocess.run(["zenity", "--list", "--title=Radio", "--width=520", "--height=480", |
| 151 | "--column=Station", "--column=Stream", "--hide-header", "--print-column=2", *rows], |
| 152 | capture_output=True, text=True) |
| 153 | url = r.stdout.strip().split("|")[0] |
| 154 | if not url: |
| 155 | return |
| 156 | choice = url |
| 157 | name = next(n for n, u in hits if u == url) |
| 158 | if subprocess.run(["zenity", "--question", f"--text=Add {name} to your stations?"]).returncode == 0: |
| 159 | with open(STATIONS, "a") as f: |
| 160 | f.write(f"{name} | {url}\n") |
| 161 | try: |
| 162 | play(choice) |
| 163 | except RuntimeError as e: |
| 164 | subprocess.run(["zenity", "--error", f"--text={e}"]) |
| 165 | |
| 166 | |
| 167 | def main(): |
| 168 | cmd, rest = (sys.argv[1] if len(sys.argv) > 1 else "pick"), " ".join(sys.argv[2:]) |
| 169 | try: |
| 170 | if cmd == "play": |
| 171 | print(f"playing {play(rest)}") |
| 172 | elif cmd == "stop": |
| 173 | was = now() |
| 174 | stop() |
| 175 | print(f"stopped {was}" if was else "nothing was playing") |
| 176 | elif cmd == "now": |
| 177 | print(now() or "nothing is playing") |
| 178 | elif cmd == "list": |
| 179 | for name, url in mine(): |
| 180 | print(f"{name} | {url}") |
| 181 | elif cmd == "search": |
| 182 | for name, url in search(rest): |
| 183 | print(f"{name} | {url}") |
| 184 | elif cmd == "pick": |
| 185 | pick() |
| 186 | else: |
| 187 | print(__doc__) |
| 188 | sys.exit(2) |
| 189 | except RuntimeError as e: |
| 190 | print(e, file=sys.stderr) |
| 191 | sys.exit(1) |
| 192 | |
| 193 | |
| 194 | if __name__ == "__main__": |
| 195 | main() |