-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathStreamModal.jsx
More file actions
427 lines (398 loc) Β· 17.7 KB
/
StreamModal.jsx
File metadata and controls
427 lines (398 loc) Β· 17.7 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import React from "react";
import PropTypes from "prop-types";
import "./StreamModal.scss";
import StreamTemplates from "../StreamTemplates.json";
import ModalCard from "@/components/ModalCard/ModalCard";
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import Checkbox from '@mui/material/Checkbox';
import List from '@mui/material/List';
import ListItemAvatar from '@mui/material/ListItemAvatar';
import ListItemText from '@mui/material/ListItemText';
import ListItemButton from '@mui/material/ListItemButton';
import Avatar from '@mui/material/Avatar';
import AlertBar from "@/components/StatusBars/AlertBar";
import { useStatusStore } from "@/App";
const NAME_DESC =
"This name can be anything - it will be used to select this stream from the source selection dropdown";
const DISABLED_DESC = "Don't show this stream in the input dropdown";
const RESTART_DESC = "Sometimes the stream gets into a bad state and neds to be restarted. If that happened to this stream, click this to restart the stream.";
const TextArg = ({ name, desc, type="text", value, onChange, required, error }) => {
return (
<>
<div className="stream-field">
<TextField
className="stream-field-input"
type={type}
label={name}
error={error}
value={value ? value : ''}
onChange={(e) => {
onChange(e.target.value);
}}
required={required}
id={required? "outlined-required" : "outlined-basic"}
fullWidth
/>
<div className="stream-field-desc">{desc}</div>
</div>
</>
);
};
TextArg.propTypes = {
name: PropTypes.string.isRequired,
desc: PropTypes.string,
type: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func.isRequired,
required: PropTypes.bool.isRequired,
error: PropTypes.bool
};
// this could be collapsed into TextField by adding a prop named something like "mode" or "type" with a switch dependant on it to return a version with checkbox or text
const BoolField = ({ name, desc, value, onChange }) => {
return (
<>
<div className="stream-field">
<div className="stream-field-bool">
<div className="stream-field-name">{name}</div>
<Checkbox
checked={value}
onChange={(e) => {
onChange(e.target.checked);
}}
/>
</div>
<div className="stream-field-desc">{desc}</div>
</div>
</>
);
};
BoolField.propTypes = {
name: PropTypes.string.isRequired,
desc: PropTypes.string.isRequired,
defaultValue: PropTypes.bool,
onChange: PropTypes.func.isRequired,
};
const ButtonField = ({ name, text, onClick, desc }) => {
return (
<>
<div className="stream-field">
<div className="stream-field-button">
<div className="stream-field-name">{name}</div>
<Button variant="outlined" onClick={onClick == undefined ? () => {} : onClick}>{text}</Button>
</div>
<div className="stream-field-desc">{desc}</div>
</div>
</>
);
};
ButtonField.propTypes = {
name: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
desc: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
};
const InternetRadioSearch = ({ onChange }) => {
const [results, setResults] = React.useState([]);
const [query, setQuery] = React.useState("");
const [selectedUuid, setSelectedUuid] = React.useState("");
const search = (name) => {
fetch("https://all.api.radio-browser.info/json/servers", {
method: "GET",
headers: { "Content-Type": "application/json" },
cache: "default",
}).then(r => r.json().then(servers => {
const fetchWithTimeout = (url, options, timeoutMs) => {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
return fetch(url, { ...options, signal: controller.signal })
.finally(() => clearTimeout(timer));
};
// A blank search returns a 55MB JSON blob. At best, it reloads the list
// once that completes and potentially clear out a successful search; at
// worst, it'll mess with low performance machines.
if (name === "") {
return;
}
setResults([{ name: "Loading..." }]);
let found = false;
const tryNext = (index = 0) => {
if (index >= servers.length || found) return;
const url = servers[index]["name"];
// Every server is pinged one by one until there's a successful result, with a max wait time of 5 seconds for any given server
// After this, the standard browser caching rules apply: If the same search is made within (time period defined by browser)
fetchWithTimeout(`https://${url}/json/stations/search`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
}, 5000)
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((stations) => {
if (found) return;
found = true;
setResults(stations.slice(0, 10).valueOf());
})
.catch((err) => {
console.warn(`Request to ${url} failed: ${err.message}`);
tryNext(index + 1);
});
};
tryNext(0);
}));
};
return (
(
<>
<div className="stream-field">
<div className="internet-radio-search">
<TextField
label="Search"
className="internet-radio-search-input"
fullWidth
sx={{ mr: '1rem' }}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={ (e) => {
if (e.key === 'Enter') {
search(query);
}
}}
/>
<Button variant="outlined" className="internet-radio-search-button" onClick={() => search(query)}>Search</Button>
</div>
<div className="stream-field-desc">
Search for internet radio stations
</div>
<List className="radio-search-results">
{ results.map((s) => (
<ListItemButton
className="internet-radio-result"
key={s.changeuuid}
selected={selectedUuid == s.changeuuid}
onClick={() => {
setSelectedUuid(s.changeuuid.valueOf());
onChange({ name: s.name, url: s.url, logo: s.favicon });
}}
>
<ListItemAvatar>
<Avatar variant="rounded"
src={s.favicon ? s.favicon : null}
alt={s.name}
sx={{ height: '2rem' }}
className="internet-radio-image"
/>
</ListItemAvatar>
<ListItemText className="internet-radio-name">{s.name}</ListItemText>
</ListItemButton>
))}
</List>
</div>
</>
)
);
};
InternetRadioSearch.propTypes = {
onChange: PropTypes.func.isRequired,
};
const StreamModal = ({ stream, onClose, apply, del }) => {
const [streamFields, setStreamFields] = React.useState(
JSON.parse(JSON.stringify(stream))
); // set streamFields to copy of stream
const [errorMessage, setErrorMessage] = React.useState("");
const [errorField, setErrorField] = React.useState("");
const [hasError, setHasError] = React.useState(false); // Need a discrete hasError bool to trigger error
const [renderAlertAnimation, setAlertAnimation] = React.useState(0); // Need a discrete hasError bool to trigger error
const streamTemplate = StreamTemplates.filter(
(t) => t.type === stream.type
)[0];
// prepend name field to template fields
const templateFields = [{
"key": "name",
"name": "name",
"title": "Name",
"type": "text",
"desc": NAME_DESC,
"required": true
}].concat(streamTemplate.fields);
return (
<ModalCard
onClose={onClose}
header={stream.name}
footer={
<AlertBar
renderAnimationState={renderAlertAnimation}
open={hasError}
onClose={() => {setHasError(false);}}
text={errorMessage}
/>
}
// del is only used during edit, so use that to define when the modal should be in edit mode
// Would use apply instead of del for the first one if apply didn't have a default as well
buttons={[
[ del ? "Edit Stream" : "Create Stream", () => {
// Check if all required fields are filled
for (const field of templateFields) {
if (field.required && (!(field.name.toLowerCase() in streamFields) || streamFields[field.name.toLowerCase()] === "")) {
setErrorField(field.name);
setErrorMessage(`Field ${field.name} is required`);
setAlertAnimation(renderAlertAnimation + 1);
setHasError(true);
return;
}
}
// Omit any fields that are simply empty. This permits Pydantic to cast to None,
// and then our constructors et al use their defaults.
// ref: https://github.com/pydantic/pydantic/discussions/2687
const filteredStreamFields = Object.fromEntries(
Object.entries(streamFields).filter( ([key, value]) => value !== "" )
);
apply(filteredStreamFields).then((response)=>{
if(response.ok)
{
setErrorField("");
onClose();
}
response.json().then((error)=>{
/*
Check type of error detail...
if it's a string it's some internal error
if it's an object it's a field error
otherwise we don't even know how to render it
TODO: if/when we refactor API errors this probably
also needs a refactor
*/
if(typeof error.detail === "string"){
setErrorMessage(error.detail);
}
else if(typeof error.detail === "object"){
// We use the 'field' member to report an invalid field during stream validation,
// but this isn't present on simple Pydantic model errors
if(error.detail.field) {
setErrorField(error.detail.field);
setErrorMessage(error.detail.msg);
} else if(error.detail[0]) {
setErrorField(error.detail[0].loc[1]);
// example: 'port: not a valid integer'
setErrorMessage(`${error.detail[0].loc[1]}: ${error.detail[0].msg}`);
} else {
setErrorMessage("Unknown error");
}
}
else{
setErrorMessage("Unknown error");
}
});
});
}
],
[
del ? "Delete" : "Cancel", () => {
if (del) del(streamFields);
onClose();
}
]
]}
>
<div>
{
// Render fields from StreamFields.json
templateFields.map((field) => {
switch (field.type) {
case "text":
return (
<TextArg
key={field.name}
name={field.title}
desc={field.desc}
type={"text"}
required={field.required == true}
error={errorField.toLowerCase()==field.name.toLowerCase()}
value={streamFields[field.name]}
onChange={(v) => {
setStreamFields({ ...streamFields, [field.name]: v });
}}
/>
);
case "password":
return (
<TextArg
key={field.name}
name={field.title}
desc={field.desc}
type={"password"}
required={field.required == true}
error={errorField.toLowerCase()==field.name.toLowerCase()}
value={streamFields[field.name]}
onChange={(v) => {
setStreamFields({ ...streamFields, [field.name]: v });
}}
/>
);
case "bool":
return (
<BoolField
key={field.name}
name={field.title}
desc={field.desc}
value={streamFields[field.name]}
onChange={(v) => {
setStreamFields({ ...streamFields, [field.name]: v });
}}
/>
);
case "internet-radio-search":
return (
<InternetRadioSearch
key={field.name}
onChange={(v) => {
setStreamFields({
...streamFields,
["name"]: v.name,
["logo"]: v.logo,
["url"]: v.url,
});
}}
/>
);
}
})
}
<BoolField
name="Disable"
desc={DISABLED_DESC}
value={streamFields.disabled}
onChange={(v) => {
setStreamFields({ ...streamFields, disabled: v });
}}
/>
{/* del is only used during edit, so use that to define when the modal should be in edit mode */}
{del && <ButtonField
name="Restart"
text="Restart Stream"
desc={RESTART_DESC}
onClick={() => fetch("/api/streams/" + stream.id + "/restart",{
method: "POST"
})}
/>}
</div>
</ModalCard>
);
};
StreamModal.propTypes = {
stream: PropTypes.any.isRequired,
onClose: PropTypes.func.isRequired,
apply: PropTypes.func,
del: PropTypes.func,
};
StreamModal.defaultProps = {
apply: (stream) => {
return fetch("/api/stream", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(stream),
});
},
}
export default StreamModal;