thrimbletrimmer: Use template literals and other cleanup

Now that we've fixed the function declarations, prettier has also removed the semicolons on them
pull/225/head
Mike Lang 3 years ago committed by Mike Lang
parent a69bee0548
commit 714a16bac4

@ -5,7 +5,7 @@ function pageSetup(isEditor) {
//Get values from ThrimShim //Get values from ThrimShim
if (isEditor && /id=/.test(document.location.search)) { if (isEditor && /id=/.test(document.location.search)) {
const rowId = /id=(.*)(?:&|$)/.exec(document.location.search)[1]; const rowId = /id=(.*)(?:&|$)/.exec(document.location.search)[1];
fetch("/thrimshim/" + rowId) fetch(`/thrimshim/${rowId}`)
.then(data => data.json()) .then(data => data.json())
.then(function (data) { .then(function (data) {
if (!data) { if (!data) {
@ -97,7 +97,7 @@ function pageSetup(isEditor) {
loadPlaylist(isEditor); loadPlaylist(isEditor);
}); });
} }
}; }
// Time-formatting functions // Time-formatting functions
@ -107,30 +107,28 @@ function parseDuration(duration) {
duration = duration.slice(1); duration = duration.slice(1);
direction = -1; direction = -1;
} }
const parts = duration.split(":"); const [hours, mins, secs] = duration.split(":");
return ( return 3600 * parseInt(hours) + 60 * (mins || "0") + (secs || "0") * direction;
(parseInt(parts[0]) + (parts[1] || "0") / 60 + (parts[2] || "0") / 3600) * 60 * 60 * direction }
);
};
function toBustime(date) { function toBustime(date) {
return ( return (
(date < desertBusStart ? "-" : "") + (date < desertBusStart ? "-" : "") +
videojs.formatTime(Math.abs((date - desertBusStart) / 1000), 600.01).padStart(7, "0:") videojs.formatTime(Math.abs((date - desertBusStart) / 1000), 600.01).padStart(7, "0:")
); );
}; }
function fromBustime(bustime) { function fromBustime(bustime) {
return new Date(desertBusStart.getTime() + 1000 * parseDuration(bustime)); return new Date(desertBusStart.getTime() + 1000 * parseDuration(bustime));
}; }
function toTimestamp(date) { function toTimestamp(date) {
return date.toISOString().substring(0, 19); return date.toISOString().substring(0, 19);
}; }
function fromTimestamp(ts) { function fromTimestamp(ts) {
return new Date(ts + "Z"); return new Date(ts + "Z");
}; }
function toAgo(date) { function toAgo(date) {
now = new Date(); now = new Date();
@ -138,11 +136,11 @@ function toAgo(date) {
(date < now ? "" : "-") + (date < now ? "" : "-") +
videojs.formatTime(Math.abs((date - now) / 1000), 600.01).padStart(7, "0:") videojs.formatTime(Math.abs((date - now) / 1000), 600.01).padStart(7, "0:")
); );
}; }
function fromAgo(ago) { function fromAgo(ago) {
return new Date(new Date().getTime() - 1000 * parseDuration(ago)); return new Date(new Date().getTime() - 1000 * parseDuration(ago));
}; }
// Set the stream start/end range from a pair of Dates using the current format // Set the stream start/end range from a pair of Dates using the current format
// If given null, sets to blank. // If given null, sets to blank.
@ -154,7 +152,7 @@ function setTimeRange(start, end) {
}[timeFormat]; }[timeFormat];
document.getElementById("StreamStart").value = start ? toFunc(start) : ""; document.getElementById("StreamStart").value = start ? toFunc(start) : "";
document.getElementById("StreamEnd").value = end ? toFunc(end) : ""; document.getElementById("StreamEnd").value = end ? toFunc(end) : "";
}; }
// Get the current start/end range as Dates using the current format // Get the current start/end range as Dates using the current format
// Returns an object containing 'start' and 'end' fields. // Returns an object containing 'start' and 'end' fields.
@ -171,12 +169,12 @@ function getTimeRange() {
} }
const date = fromFunc(value); const date = fromFunc(value);
return isNaN(date) ? null : date; return isNaN(date) ? null : date;
}; }
return { return {
start: convert(document.getElementById("StreamStart").value), start: convert(document.getElementById("StreamStart").value),
end: convert(document.getElementById("StreamEnd").value), end: convert(document.getElementById("StreamEnd").value),
}; };
}; }
function getTimeRangeAsTimestamp() { function getTimeRangeAsTimestamp() {
const range = getTimeRange(); const range = getTimeRange();
@ -185,26 +183,26 @@ function getTimeRangeAsTimestamp() {
start: range.start && toTimestamp(range.start), start: range.start && toTimestamp(range.start),
end: range.end && toTimestamp(range.end), end: range.end && toTimestamp(range.end),
}; };
}; }
function toggleHiddenPane(paneID) { function toggleHiddenPane(paneID) {
const pane = document.getElementById(paneID); const pane = document.getElementById(paneID);
pane.style.display = pane.style.display === "none" ? "block" : "none"; pane.style.display = pane.style.display === "none" ? "block" : "none";
}; }
function toggleUltrawide() { function toggleUltrawide() {
const body = document.getElementsByTagName("Body")[0]; const body = document.getElementsByTagName("Body")[0];
body.classList.contains("ultrawide") body.classList.contains("ultrawide")
? body.classList.remove("ultrawide") ? body.classList.remove("ultrawide")
: body.classList.add("ultrawide"); : body.classList.add("ultrawide");
}; }
function toggleTimeInput(toggleInput) { function toggleTimeInput(toggleInput) {
// Get times using current format, then change format, then write them back // Get times using current format, then change format, then write them back
const range = getTimeRange(); const range = getTimeRange();
timeFormat = toggleInput; timeFormat = toggleInput;
setTimeRange(range.start, range.end); setTimeRange(range.start, range.end);
}; }
// For a given select input element id, add the given list of options. // For a given select input element id, add the given list of options.
// If selected is given, it should be the name of an option to select. // If selected is given, it should be the name of an option to select.
@ -214,26 +212,22 @@ function setOptions(element, options, selected) {
selected = options[0]; selected = options[0];
} }
options.forEach(option => { options.forEach(option => {
document.getElementById(element).innerHTML += const maybeSelected = option == selected ? "selected" : "";
'<option value="' + const optionHTML = `<option value="${option}" ${maybeSelected}>${option}</option>`;
option + document.getElementById(element).innerHTML += optionHTML;
'" ' +
(option == selected ? "selected" : "") +
">" +
option +
"</option>";
}); });
}; }
function buildQuery(params) { function buildQuery(params) {
return Object.keys(params) return Object.keys(params)
.filter(key => params[key] !== null) .filter(key => params[key] !== null)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(params[key])) .map(key => encodeURIComponent(key) + "=" + encodeURIComponent(params[key]))
.join("&"); .join("&");
}; }
function loadPlaylist(isEditor, startTrim, endTrim, defaultQuality) { function loadPlaylist(isEditor, startTrim, endTrim, defaultQuality) {
const playlist = "/playlist/" + document.getElementById("StreamName").value + ".m3u8"; const stream = document.getElementById("StreamName").value;
const playlist = `/playlist/${stream}.m3u8`;
const range = getTimeRangeAsTimestamp(); const range = getTimeRangeAsTimestamp();
const queryString = buildQuery(range); const queryString = buildQuery(range);
@ -265,7 +259,7 @@ function loadPlaylist(isEditor, startTrim, endTrim, defaultQuality) {
//Get quality levels for advanced properties / download //Get quality levels for advanced properties / download
document.getElementById("qualityLevel").innerHTML = ""; document.getElementById("qualityLevel").innerHTML = "";
fetch("/files/" + document.getElementById("StreamName").value) fetch(`/files/${stream}`)
.then(data => data.json()) .then(data => data.json())
.then(function (data) { .then(function (data) {
if (!data.length) { if (!data.length) {
@ -278,7 +272,7 @@ function loadPlaylist(isEditor, startTrim, endTrim, defaultQuality) {
document.getElementById("wubloaderAdvancedInputTable").style.display = "block"; document.getElementById("wubloaderAdvancedInputTable").style.display = "block";
} }
}); });
}; }
function thrimbletrimmerSubmit(state, override_changes = false) { function thrimbletrimmerSubmit(state, override_changes = false) {
document.getElementById("SubmitButton").disabled = true; document.getElementById("SubmitButton").disabled = true;
@ -341,15 +335,16 @@ function thrimbletrimmerSubmit(state, override_changes = false) {
//Submit to thrimshim //Submit to thrimshim
const rowId = /id=(.*)(?:&|$)/.exec(document.location.search)[1]; const rowId = /id=(.*)(?:&|$)/.exec(document.location.search)[1];
fetch("/thrimshim/" + rowId, { fetch(`/thrimshim/${rowId}`, {
method: "POST", method: "POST",
headers: { headers: {
Accept: "application/json", Accept: "application/json",
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify(wubData), body: JSON.stringify(wubData),
}).then(response => })
response.text().then(text => { .then(response => response.text())
.then(text => {
if (!response.ok) { if (!response.ok) {
if (response.status == 409) { if (response.status == 409) {
dialogue = text + "\nClick Ok to submit anyway; Click Cancel to return to editing"; dialogue = text + "\nClick Ok to submit anyway; Click Cancel to return to editing";
@ -357,7 +352,7 @@ function thrimbletrimmerSubmit(state, override_changes = false) {
thrimbletrimmerSubmit(state, true); thrimbletrimmerSubmit(state, true);
} }
} else { } else {
const error = response.statusText + ": " + text; const error = `${response.statusText}: ${text}`;
console.log("Failed to submit:", error); console.log("Failed to submit:", error);
alert(error); alert(error);
} }
@ -367,9 +362,8 @@ function thrimbletrimmerSubmit(state, override_changes = false) {
alert("Draft saved"); alert("Draft saved");
} }
document.getElementById("SubmitButton").disabled = false; document.getElementById("SubmitButton").disabled = false;
}) });
); }
};
function thrimbletrimmerDownload(isEditor) { function thrimbletrimmerDownload(isEditor) {
const range = getTimeRangeAsTimestamp(); const range = getTimeRangeAsTimestamp();
@ -389,31 +383,28 @@ function thrimbletrimmerDownload(isEditor) {
); );
} }
const targetURL = const stream = document.getElementById("StreamName").value;
"/cut/" + const quality =
document.getElementById("StreamName").value +
"/" +
document.getElementById("qualityLevel").options[ document.getElementById("qualityLevel").options[
document.getElementById("qualityLevel").options.selectedIndex document.getElementById("qualityLevel").options.selectedIndex
].value + ].value;
".ts" + const query = buildQuery({
"?" + start: range.start,
buildQuery({ end: range.end,
start: range.start, // In non-editor, always use rough cut. They don't have the edit controls to do
end: range.end, // fine time selection anyway.
// In non-editor, always use rough cut. They don't have the edit controls to do type: isEditor
// fine time selection anyway. ? document.getElementById("DownloadType").options[
type: isEditor document.getElementById("DownloadType").options.selectedIndex
? document.getElementById("DownloadType").options[ ].value
document.getElementById("DownloadType").options.selectedIndex : "rough",
].value // Always allow holes in non-editor, accidentially including holes isn't important
: "rough", allow_holes: isEditor ? String(document.getElementById("AllowHoles").checked) : "true",
// Always allow holes in non-editor, accidentially including holes isn't important });
allow_holes: isEditor ? String(document.getElementById("AllowHoles").checked) : "true", const targetURL = `/cut/${stream}/${quality}.ts?${query}`;
});
document.getElementById("DownloadLink").href = targetURL; document.getElementById("DownloadLink").href = targetURL;
document.getElementById("DownloadLink").style.display = ""; document.getElementById("DownloadLink").style.display = "";
}; }
function thrimbletrimmerManualLink() { function thrimbletrimmerManualLink() {
document.getElementById("ManualButton").disabled = true; document.getElementById("ManualButton").disabled = true;
@ -428,29 +419,29 @@ function thrimbletrimmerManualLink() {
if (!!user) { if (!!user) {
body.token = user.getAuthResponse().id_token; body.token = user.getAuthResponse().id_token;
} }
fetch("/thrimshim/manual-link/" + rowId, { fetch(`/thrimshim/manual-link/${rowId}`, {
method: "POST", method: "POST",
headers: { headers: {
Accept: "application/json", Accept: "application/json",
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify(body), body: JSON.stringify(body),
}).then(response => })
response.text().then(text => { .then(response => response.text())
.then(text => {
if (!response.ok) { if (!response.ok) {
const error = response.statusText + ": " + text; const error = `${response.statusText}: ${text}`;
console.log("Failed to set manual link:", error); console.log("Failed to set manual link:", error);
alert(error); alert(error);
document.getElementById("ManualButton").disabled = false; document.getElementById("ManualButton").disabled = false;
} else { } else {
alert("Manual link set to " + body.link); alert(`Manual link set to ${body.link}`);
setTimeout(() => { setTimeout(() => {
window.location.href = "/thrimbletrimmer/dashboard.html"; window.location.href = "/thrimbletrimmer/dashboard.html";
}, 500); }, 500);
} }
}) });
); }
};
function thrimbletrimmerResetLink(force) { function thrimbletrimmerResetLink(force) {
const rowId = /id=(.*)(?:&|$)/.exec(document.location.search)[1]; const rowId = /id=(.*)(?:&|$)/.exec(document.location.search)[1];
@ -472,43 +463,43 @@ function thrimbletrimmerResetLink(force) {
if (!!user) { if (!!user) {
body.token = user.getAuthResponse().id_token; body.token = user.getAuthResponse().id_token;
} }
fetch("/thrimshim/reset/" + rowId + "?force=" + force, { fetch(`/thrimshim/reset/${rowId}?force=${force}`, {
method: "POST", method: "POST",
headers: { headers: {
Accept: "application/json", Accept: "application/json",
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify(body), body: JSON.stringify(body),
}).then(response => })
response.text().then(text => { .then(response => response.text())
.then(text => {
if (!response.ok) { if (!response.ok) {
const error = response.statusText + ": " + text; const error = `${response.statusText}: ${text}`;
console.log("Failed to reset:", error); console.log("Failed to reset:", error);
alert(error); alert(error);
document.getElementById("ResetButton").disabled = false; document.getElementById("ResetButton").disabled = false;
document.getElementById("CancelButton").disabled = true; document.getElementById("CancelButton").disabled = true;
} else { } else {
alert("Row has been " + (force ? "reset" : "cancelled") + ". Reloading..."); alert(`Row has been ${force ? "reset" : "cancelled"}. Reloading...`);
setTimeout(() => { setTimeout(() => {
window.location.reload(); window.location.reload();
}, 500); }, 500);
} }
}) });
); }
};
function tags_list_to_string(tag_list) { function tags_list_to_string(tag_list) {
return tag_list.join(", "); return tag_list.join(", ");
}; }
function tags_string_to_list(tag_string) { function tags_string_to_list(tag_string) {
return tag_string return tag_string
.split(",") .split(",")
.map(tag => tag.trim()) .map(tag => tag.trim())
.filter(tag => tag.length > 0); .filter(tag => tag.length > 0);
}; }
function round_trip_tag_string() { function round_trip_tag_string() {
const element = document.getElementById("VideoTags"); const element = document.getElementById("VideoTags");
element.value = tags_list_to_string(tags_string_to_list(element.value)); element.value = tags_list_to_string(tags_string_to_list(element.value));
}; }

@ -81,10 +81,6 @@ document.addEventListener("keypress", event => {
break; break;
} }
} }
// const keyName = event.key;
// console.log('keypress event\n\n' + 'key: ' + keyName);
// console.log(event.target.nodeName);
}); });
//Arrow keys only detected on keydown, keypress only works in "some" browsers //Arrow keys only detected on keydown, keypress only works in "some" browsers

@ -6,7 +6,6 @@ function setupPlayer(isEditor, source, startTrim, endTrim) {
const options = { const options = {
sources: [{src: source}], sources: [{src: source}],
liveui: true, liveui: true,
//fluid:true,
controls: true, controls: true,
autoplay: false, autoplay: false,
width: 1280, width: 1280,
@ -80,7 +79,7 @@ function mapDiscontinuities() {
} }
return discontinuities; return discontinuities;
}; }
function getRealTimeForPlayerTime(discontinuities, playbackIndex) { function getRealTimeForPlayerTime(discontinuities, playbackIndex) {
let streamStart = player.vhs.playlists.master.playlists.filter( let streamStart = player.vhs.playlists.master.playlists.filter(
@ -100,4 +99,4 @@ function getRealTimeForPlayerTime(discontinuities, playbackIndex) {
const realTime = streamStart.getTime() + playbackIndex * 1000; const realTime = streamStart.getTime() + playbackIndex * 1000;
return isFinite(realTime) ? new Date(realTime).toISOString() : null; return isFinite(realTime) ? new Date(realTime).toISOString() : null;
}; }

Loading…
Cancel
Save