-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel.js
More file actions
278 lines (249 loc) · 9.73 KB
/
Copy pathModel.js
File metadata and controls
278 lines (249 loc) · 9.73 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Pure JS helpers for the cliamp Omarchy plugin. No QML imports here so the
// same file is loadable from QML (`import "Model.js" as Model`) and runnable
// under node/deno for the tests in tests/model.test.js.
// ---- status ---------------------------------------------------------------
// Parse the stdout of `cliamp status --json`. Returns a normalized object, or
// null when cliamp is not running / the output is not usable (empty string,
// invalid JSON, or `ok:false`). cliamp omits zero-valued fields
// (position/duration/volume) via `omitempty`, so every read is defensive.
function parseStatus(jsonText) {
if (!jsonText || !String(jsonText).trim()) return null
var obj
try {
obj = JSON.parse(jsonText)
} catch (e) {
return null
}
if (!obj || obj.ok === false) return null
var track = obj.track || {}
var state = String(obj.state || "stopped").toLowerCase()
if (state !== "playing" && state !== "paused") state = "stopped"
return {
running: true,
state: state,
title: String(track.title || track.stream_title || ""),
artist: String(track.artist || ""),
album: String(track.album || ""),
station: String(track.station || ""),
path: String(track.path || ""),
albumArtUrl: String(track.album_art_url || ""),
isStream: !!track.stream,
positionSec: num(obj.position),
durationSec: num(obj.duration) || num(track.duration_secs),
volumeDb: num(obj.volume),
shuffle: !!obj.shuffle,
repeat: normalizeRepeat(obj.repeat),
themeName: obj.theme && obj.theme.name ? String(obj.theme.name) : "",
index: Math.round(num(obj.index)),
total: Math.round(num(obj.total))
}
}
function num(v) {
var n = Number(v)
return isFinite(n) ? n : 0
}
// cliamp reports repeat as "Off" | "All" | "One" in --json (capitalized) but
// the docs/protocol also show lowercase; fold both to off | all | one.
function normalizeRepeat(v) {
var s = String(v || "off").toLowerCase()
return (s === "all" || s === "one") ? s : "off"
}
// ---- labels -------------------------------------------------------------
// The single line shown in the bar. Mirrors the ICY/station formatting from
// cliamp's own docs/headless.md Waybar example:
// station + "artist - title" for internet radio with ICY metadata
// "artist — title" for tracks with a separate artist tag
// title otherwise
function nowPlayingLabel(st, showArtist) {
if (!st || !st.running) return ""
var title = st.title || ""
var artist = st.artist || ""
var station = st.station || ""
if (station) {
var inner = (artist && title) ? (artist + " - " + title) : (title || artist)
return inner ? (station + ": " + inner) : station
}
if (showArtist && artist && title) return artist + " — " + title
return title || artist || station || ""
}
function tooltipText(st, yt) {
if (!st || !st.running) return "cliamp no está corriendo"
var lines = []
var head = nowPlayingLabel(st, true)
if (head) lines.push(head)
lines.push("Estado: " + stateLabel(st.state))
if (st.themeName) lines.push("Tema: " + st.themeName)
lines.push("Volumen: " + fmtVolume(st.volumeDb))
var modes = []
if (st.shuffle) modes.push("aleatorio")
if (st.repeat !== "off") modes.push("repetir " + st.repeat)
if (modes.length) lines.push(modes.join(" · "))
if (yt && yt.known) lines.push("yt-radio: " + (yt.enabled ? "on" : "off"))
return lines.join("\n")
}
function stateLabel(state) {
if (state === "playing") return "reproduciendo"
if (state === "paused") return "en pausa"
return "detenido"
}
// mdi nerd-font glyph for the current transport state.
function stateGlyph(state) {
if (state === "playing") return "" // nf-md-play (U+F040A)
if (state === "paused") return "" // nf-md-pause (U+F03E4)
return "" // nf-md-stop (U+F04DB)
}
function fmtTime(sec) {
var s = Math.max(0, Math.floor(Number(sec) || 0))
var h = Math.floor(s / 3600)
var m = Math.floor((s % 3600) / 60)
var ss = s % 60
var mm = h > 0 && m < 10 ? "0" + m : String(m)
var p = ss < 10 ? "0" + ss : String(ss)
return (h > 0 ? h + ":" : "") + mm + ":" + p
}
function fmtVolume(db) {
var n = Math.round(Number(db) || 0)
return (n > 0 ? "+" : "") + n + " dB"
}
function repeatLabel(mode) {
if (mode === "all") return "Todo"
if (mode === "one") return "Una"
return "Off"
}
// Compact view-count, truncated like YouTube: 1250000 -> "1.2M",
// 288389622 -> "288M", 830219 -> "830K", 420 -> "420".
function fmtViews(n) {
n = Number(n) || 0
function scaled(x) { return x >= 10 ? String(Math.floor(x)) : String(Math.floor(x * 10) / 10) }
if (n >= 1e9) return scaled(n / 1e9) + "B"
if (n >= 1e6) return scaled(n / 1e6) + "M"
if (n >= 1e3) return scaled(n / 1e3) + "K"
return String(Math.round(n))
}
// ---- youtube search ------------------------------------------------
// Parse `yt-dlp "ytsearchN:..." --flat-playlist -J` output (a playlist object
// with `entries[]`). Returns [{ id, title, channel, durationSec, views, url }]
// with null-guards; [] on invalid JSON / no entries.
function parseYtdlpResults(jsonText) {
var out = []
var obj
try {
obj = JSON.parse(jsonText)
} catch (e) {
return out
}
var entries = obj && Array.isArray(obj.entries) ? obj.entries
: (Array.isArray(obj) ? obj : [])
for (var i = 0; i < entries.length; i++) {
var e = entries[i] || {}
var id = String(e.id || "")
if (!id) continue
var dur = Number(e.duration)
out.push({
id: id,
title: String(e.title || id),
channel: String(e.channel || e.uploader || ""),
durationSec: isFinite(dur) && dur > 0 ? dur : 0,
views: Number(e.view_count) || 0,
url: String(e.url || ("https://www.youtube.com/watch?v=" + id))
})
}
return out
}
// "canal · 3:38 · 288M" (skips the empty parts).
function resultCaption(r) {
if (!r) return ""
var parts = []
if (r.channel) parts.push(r.channel)
if (r.durationSec) parts.push(fmtTime(r.durationSec))
if (r.views) parts.push(fmtViews(r.views))
return parts.join(" · ")
}
// ---- cover art -------------------------------------------------------
// YouTube / YouTube Music video id out of a cliamp track path
// (https://www.youtube.com/watch?v=ID , https://music.youtube.com/watch?v=ID ,
// https://youtu.be/ID). "" when the path isn't a YouTube URL.
function youtubeIdFromPath(path) {
var s = String(path || "")
var m = s.match(/[?&]v=([A-Za-z0-9_-]{6,})/) || s.match(/youtu\.be\/([A-Za-z0-9_-]{6,})/)
return m ? m[1] : ""
}
// Best-effort cover art URL for the current track:
// - local files -> cliamp's own album_art_url (file:// or data:)
// - YouTube (Music) -> the `hqdefault` video thumbnail from i.ytimg.com
// - radio / other -> "" (caller falls back to a glyph)
// `hqdefault` for both bar and panel: it's present on effectively every video,
// whereas `mqdefault`/`sddefault` 404 for some auto-generated "art tracks".
function artUrl(st) {
if (!st || !st.running) return ""
if (st.albumArtUrl) return st.albumArtUrl
var id = youtubeIdFromPath(st.path)
return id ? "https://i.ytimg.com/vi/" + id + "/hqdefault.jpg" : ""
}
// 120x90, present even when hqdefault isn't — used as the error fallback.
function artUrlFallback(st) {
if (!st || !st.running || st.albumArtUrl) return ""
var id = youtubeIdFromPath(st.path)
return id ? "https://i.ytimg.com/vi/" + id + "/default.jpg" : ""
}
// ---- spectrum -------------------------------------------------------
// Resample an arbitrary-length band array (from `cliamp visstream`) to exactly
// `n` buckets by averaging each source range, clamped to [0, 1]. A missing /
// empty / non-array `src`, or n <= 0, yields an all-zero array of length
// max(n, 0) — so the renderer always gets a stable-length model and just
// flattens to the baseline when there's no data.
function sampleBands(src, n) {
n = Math.max(0, Math.floor(n) || 0)
var out = new Array(n)
for (var i = 0; i < n; i++) out[i] = 0
if (!Array.isArray(src) || src.length === 0 || n === 0) return out
for (var b = 0; b < n; b++) {
var start = Math.floor(b * src.length / n)
var end = Math.floor((b + 1) * src.length / n)
if (end <= start) end = start + 1
var sum = 0, count = 0
for (var k = start; k < end && k < src.length; k++) {
var v = Number(src[k])
if (!isFinite(v)) v = 0
sum += v < 0 ? 0 : (v > 1 ? 1 : v)
count++
}
out[b] = count ? sum / count : 0
}
return out
}
// ---- yt-radio ----------------------------------------------------------
// Parse the reply of `cliamp plugins call yt-radio status` (or `toggle`).
// status : "yt-radio: auto=on | min_ahead=3 batch=10 cooldown=0s history=12"
// toggle : "yt-radio: auto-refill on"
// Returns { known, enabled }. `known:false` means the plugin isn't loaded
// (cliamp not in the TUI) or the output was unexpected.
function parseYtRadioStatus(text) {
var s = String(text || "")
var m = s.match(/auto(?:-refill)?\s*[=:]?\s*(on|off|true|false|enabled|disabled)/i)
if (!m) return { known: false, enabled: false }
var v = m[1].toLowerCase()
return { known: true, enabled: v === "on" || v === "true" || v === "enabled" }
}
// node/deno test entry point; ignored by QML's JS import.
if (typeof module !== "undefined" && module.exports) {
module.exports = {
parseStatus: parseStatus,
normalizeRepeat: normalizeRepeat,
youtubeIdFromPath: youtubeIdFromPath,
artUrl: artUrl,
artUrlFallback: artUrlFallback,
nowPlayingLabel: nowPlayingLabel,
tooltipText: tooltipText,
stateLabel: stateLabel,
stateGlyph: stateGlyph,
fmtTime: fmtTime,
fmtVolume: fmtVolume,
repeatLabel: repeatLabel,
sampleBands: sampleBands,
fmtViews: fmtViews,
parseYtdlpResults: parseYtdlpResults,
resultCaption: resultCaption,
parseYtRadioStatus: parseYtRadioStatus
}
}