thrimbletrimmer: Replace var with let/const and other related bits

pull/225/head
Mike Lang 3 years ago committed by Mike Lang
parent 241d302220
commit a69bee0548

@ -1,10 +1,10 @@
var desertBusStart = new Date("1970-01-01T00:00:00Z"); let desertBusStart = new Date("1970-01-01T00:00:00Z");
var timeFormat = "AGO"; let timeFormat = "AGO";
function pageSetup(isEditor) { 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)) {
var 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) {
@ -24,10 +24,10 @@ function pageSetup(isEditor) {
// Apply padding - start 1min early, finish 2min late because these times are generally // Apply padding - start 1min early, finish 2min late because these times are generally
// rounded down to the minute, so if something ends at "00:10" it might actually end // rounded down to the minute, so if something ends at "00:10" it might actually end
// at 00:10:59 so we should pad to 00:12:00. // at 00:10:59 so we should pad to 00:12:00.
var start = data.event_start const start = data.event_start
? new Date(fromTimestamp(data.event_start).getTime() - 60 * 1000) ? new Date(fromTimestamp(data.event_start).getTime() - 60 * 1000)
: null; : null;
var end = data.event_end const end = data.event_end
? new Date(fromTimestamp(data.event_end).getTime() + 2 * 60 * 1000) ? new Date(fromTimestamp(data.event_end).getTime() + 2 * 60 * 1000)
: null; : null;
setTimeRange(start, end); setTimeRange(start, end);
@ -102,12 +102,12 @@ function pageSetup(isEditor) {
// Time-formatting functions // Time-formatting functions
function parseDuration(duration) { function parseDuration(duration) {
var direction = 1; let direction = 1;
if (duration.startsWith("-")) { if (duration.startsWith("-")) {
duration = duration.slice(1); duration = duration.slice(1);
direction = -1; direction = -1;
} }
var parts = duration.split(":"); const parts = duration.split(":");
return ( return (
(parseInt(parts[0]) + (parts[1] || "0") / 60 + (parts[2] || "0") / 3600) * 60 * 60 * direction (parseInt(parts[0]) + (parts[1] || "0") / 60 + (parts[2] || "0") / 3600) * 60 * 60 * direction
); );
@ -147,7 +147,7 @@ function fromAgo(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.
function setTimeRange(start, end) { function setTimeRange(start, end) {
var toFunc = { const toFunc = {
UTC: toTimestamp, UTC: toTimestamp,
BUSTIME: toBustime, BUSTIME: toBustime,
AGO: toAgo, AGO: toAgo,
@ -160,16 +160,16 @@ function setTimeRange(start, end) {
// Returns an object containing 'start' and 'end' fields. // Returns an object containing 'start' and 'end' fields.
// If either is empty / invalid, returns null. // If either is empty / invalid, returns null.
function getTimeRange() { function getTimeRange() {
var fromFunc = { const fromFunc = {
UTC: fromTimestamp, UTC: fromTimestamp,
BUSTIME: fromBustime, BUSTIME: fromBustime,
AGO: fromAgo, AGO: fromAgo,
}[timeFormat]; }[timeFormat];
var convert = function (value) { function convert(value) {
if (!value) { if (!value) {
return null; return null;
} }
var date = fromFunc(value); const date = fromFunc(value);
return isNaN(date) ? null : date; return isNaN(date) ? null : date;
}; };
return { return {
@ -179,7 +179,7 @@ function getTimeRange() {
}; };
function getTimeRangeAsTimestamp() { function getTimeRangeAsTimestamp() {
var range = getTimeRange(); const range = getTimeRange();
return { return {
// if not null, format as timestamp // if not null, format as timestamp
start: range.start && toTimestamp(range.start), start: range.start && toTimestamp(range.start),
@ -188,12 +188,12 @@ function getTimeRangeAsTimestamp() {
}; };
function toggleHiddenPane(paneID) { function toggleHiddenPane(paneID) {
var 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() {
var 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");
@ -201,7 +201,7 @@ function toggleUltrawide() {
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
var range = getTimeRange(); const range = getTimeRange();
timeFormat = toggleInput; timeFormat = toggleInput;
setTimeRange(range.start, range.end); setTimeRange(range.start, range.end);
}; };
@ -213,7 +213,7 @@ function setOptions(element, options, selected) {
if (!selected && options.length > 0) { if (!selected && options.length > 0) {
selected = options[0]; selected = options[0];
} }
options.forEach(function (option) { options.forEach(option => {
document.getElementById(element).innerHTML += document.getElementById(element).innerHTML +=
'<option value="' + '<option value="' +
option + option +
@ -233,14 +233,14 @@ function buildQuery(params) {
}; };
function loadPlaylist(isEditor, startTrim, endTrim, defaultQuality) { function loadPlaylist(isEditor, startTrim, endTrim, defaultQuality) {
var playlist = "/playlist/" + document.getElementById("StreamName").value + ".m3u8"; const playlist = "/playlist/" + document.getElementById("StreamName").value + ".m3u8";
var range = getTimeRangeAsTimestamp(); const range = getTimeRangeAsTimestamp();
var queryString = buildQuery(range); const queryString = buildQuery(range);
// Preserve existing edit times // Preserve existing edit times
if (player && player.trimmingControls && player.vhs.playlists.master) { if (player && player.trimmingControls && player.vhs.playlists.master) {
var discontinuities = mapDiscontinuities(); const discontinuities = mapDiscontinuities();
if (!startTrim) { if (!startTrim) {
startTrim = getRealTimeForPlayerTime( startTrim = getRealTimeForPlayerTime(
discontinuities, discontinuities,
@ -282,21 +282,21 @@ function loadPlaylist(isEditor, startTrim, endTrim, defaultQuality) {
function thrimbletrimmerSubmit(state, override_changes = false) { function thrimbletrimmerSubmit(state, override_changes = false) {
document.getElementById("SubmitButton").disabled = true; document.getElementById("SubmitButton").disabled = true;
var discontinuities = mapDiscontinuities(); const discontinuities = mapDiscontinuities();
var start = getRealTimeForPlayerTime( let start = getRealTimeForPlayerTime(
discontinuities, discontinuities,
player.trimmingControls().options.startTrim player.trimmingControls().options.startTrim
); );
if (start) { if (start) {
start = start.replace("Z", ""); start = start.replace("Z", "");
} }
var end = getRealTimeForPlayerTime(discontinuities, player.trimmingControls().options.endTrim); let end = getRealTimeForPlayerTime(discontinuities, player.trimmingControls().options.endTrim);
if (end) { if (end) {
end = end.replace("Z", ""); end = end.replace("Z", "");
} }
var wubData = { const wubData = {
video_start: start, video_start: start,
video_end: end, video_end: end,
video_title: document.getElementById("VideoTitle").value, video_title: document.getElementById("VideoTitle").value,
@ -326,10 +326,9 @@ function thrimbletrimmerSubmit(state, override_changes = false) {
wubData.token = user.getAuthResponse().id_token; wubData.token = user.getAuthResponse().id_token;
} }
if (override_changes) { if (override_changes) {
wubData["override_changes"] = true; wubData.override_changes = true;
} }
console.log(wubData); console.log("Submitting", wubData);
console.log(JSON.stringify(wubData));
if (!wubData.video_start) { if (!wubData.video_start) {
alert("No start time set"); alert("No start time set");
@ -341,7 +340,7 @@ function thrimbletrimmerSubmit(state, override_changes = false) {
} }
//Submit to thrimshim //Submit to thrimshim
var 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: {
@ -352,13 +351,14 @@ function thrimbletrimmerSubmit(state, override_changes = false) {
}).then(response => }).then(response =>
response.text().then(text => { response.text().then(text => {
if (!response.ok) { if (!response.ok) {
var error = response.statusText + ": " + text;
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";
if (confirm(dialogue)) { if (confirm(dialogue)) {
thrimbletrimmerSubmit(state, true); thrimbletrimmerSubmit(state, true);
} }
} else { } else {
const error = response.statusText + ": " + text;
console.log("Failed to submit:", error);
alert(error); alert(error);
} }
} else if (state == "EDITED") { } else if (state == "EDITED") {
@ -372,13 +372,13 @@ function thrimbletrimmerSubmit(state, override_changes = false) {
}; };
function thrimbletrimmerDownload(isEditor) { function thrimbletrimmerDownload(isEditor) {
var range = getTimeRangeAsTimestamp(); const range = getTimeRangeAsTimestamp();
if (isEditor) { if (isEditor) {
if (player.trimmingControls().options.startTrim >= player.trimmingControls().options.endTrim) { if (player.trimmingControls().options.startTrim >= player.trimmingControls().options.endTrim) {
alert("End Time must be greater than Start Time"); alert("End Time must be greater than Start Time");
return; return;
} }
var discontinuities = mapDiscontinuities(); const discontinuities = mapDiscontinuities();
range.start = getRealTimeForPlayerTime( range.start = getRealTimeForPlayerTime(
discontinuities, discontinuities,
player.trimmingControls().options.startTrim player.trimmingControls().options.startTrim
@ -389,7 +389,7 @@ function thrimbletrimmerDownload(isEditor) {
); );
} }
var targetURL = const targetURL =
"/cut/" + "/cut/" +
document.getElementById("StreamName").value + document.getElementById("StreamName").value +
"/" + "/" +
@ -411,18 +411,17 @@ function thrimbletrimmerDownload(isEditor) {
// Always allow holes in non-editor, accidentially including holes isn't important // Always allow holes in non-editor, accidentially including holes isn't important
allow_holes: isEditor ? String(document.getElementById("AllowHoles").checked) : "true", allow_holes: isEditor ? String(document.getElementById("AllowHoles").checked) : "true",
}); });
console.log(targetURL);
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;
var rowId = /id=(.*)(?:&|$)/.exec(document.location.search)[1]; const rowId = /id=(.*)(?:&|$)/.exec(document.location.search)[1];
var upload_location = document.getElementById("ManualYoutube").checked const upload_location = document.getElementById("ManualYoutube").checked
? "youtube-manual" ? "youtube-manual"
: "manual"; : "manual";
var body = { const body = {
link: document.getElementById("ManualLink").value, link: document.getElementById("ManualLink").value,
upload_location: upload_location, upload_location: upload_location,
}; };
@ -439,8 +438,8 @@ function thrimbletrimmerManualLink() {
}).then(response => }).then(response =>
response.text().then(text => { response.text().then(text => {
if (!response.ok) { if (!response.ok) {
var error = response.statusText + ": " + text; const error = response.statusText + ": " + text;
console.log(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 {
@ -454,7 +453,7 @@ function thrimbletrimmerManualLink() {
}; };
function thrimbletrimmerResetLink(force) { function thrimbletrimmerResetLink(force) {
var rowId = /id=(.*)(?:&|$)/.exec(document.location.search)[1]; const rowId = /id=(.*)(?:&|$)/.exec(document.location.search)[1];
if ( if (
force && force &&
!confirm( !confirm(
@ -469,7 +468,7 @@ function thrimbletrimmerResetLink(force) {
} }
document.getElementById("ResetButton").disabled = true; document.getElementById("ResetButton").disabled = true;
document.getElementById("CancelButton").disabled = true; document.getElementById("CancelButton").disabled = true;
var body = {}; const body = {};
if (!!user) { if (!!user) {
body.token = user.getAuthResponse().id_token; body.token = user.getAuthResponse().id_token;
} }
@ -483,8 +482,8 @@ function thrimbletrimmerResetLink(force) {
}).then(response => }).then(response =>
response.text().then(text => { response.text().then(text => {
if (!response.ok) { if (!response.ok) {
var error = response.statusText + ": " + text; const error = response.statusText + ": " + text;
console.log(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;
@ -510,6 +509,6 @@ function tags_string_to_list(tag_string) {
}; };
function round_trip_tag_string() { function round_trip_tag_string() {
var 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));
}; };

@ -1,11 +1,11 @@
function changeSpeed(direction) { function changeSpeed(direction) {
var speeds = [0.5, 1, 1.25, 1.5, 2]; const speeds = [0.5, 1, 1.25, 1.5, 2];
var currentIndex = speeds.indexOf(player.playbackRate()); const currentIndex = speeds.indexOf(player.playbackRate());
if (currentIndex < 0) { if (currentIndex < 0) {
// not present // not present
return; return;
} }
var newIndex = currentIndex + direction; const newIndex = currentIndex + direction;
if (newIndex < 0 || newIndex >= speeds.length) { if (newIndex < 0 || newIndex >= speeds.length) {
// out of range // out of range
return; return;

@ -1,9 +1,9 @@
var player = null; let player = null;
function setupPlayer(isEditor, source, startTrim, endTrim) { function setupPlayer(isEditor, source, startTrim, endTrim) {
document.getElementById("my-player").style.display = ""; document.getElementById("my-player").style.display = "";
//Make poster of DB logo in correct aspect ratio, to control initial size of fluid container. //Make poster of DB logo in correct aspect ratio, to control initial size of fluid container.
var options = { const options = {
sources: [{src: source}], sources: [{src: source}],
liveui: true, liveui: true,
//fluid:true, //fluid:true,
@ -30,60 +30,48 @@ function setupPlayer(isEditor, source, startTrim, endTrim) {
`; `;
} }
player = videojs("my-player", options, function onPlayerReady() { player = videojs("my-player", options, function onPlayerReady() {
videojs.log("Your player is ready!"); videojs.log("Video player is ready");
// Set player volume to 50% by default // Set player volume to 50% by default
var defaultVolume = 0.5; const defaultVolume = 0.5;
this.volume(defaultVolume); this.volume(defaultVolume);
// In this context, `this` is the player that was created by Video.js.
this.on("ready", function () {
//this.play();
});
this.vhs.playlists.on("loadedmetadata", function () { this.vhs.playlists.on("loadedmetadata", function () {
// setTimeout(function() { player.play(); }, 1000);
player.hasStarted(true); //So it displays all the controls. player.hasStarted(true); //So it displays all the controls.
if (isEditor) { if (isEditor) {
var stream_start = player.vhs.playlists.master.playlists.filter( const stream_start = player.vhs.playlists.master.playlists.filter(
playlist => typeof playlist.discontinuityStarts !== "undefined" playlist => typeof playlist.discontinuityStarts !== "undefined"
)[0].dateTimeObject; )[0].dateTimeObject;
startTrim = startTrim ? (new Date(startTrim + "Z") - stream_start) / 1000 : 0; startTrim = startTrim ? (new Date(startTrim + "Z") - stream_start) / 1000 : 0;
endTrim = endTrim ? (new Date(endTrim + "Z") - stream_start) / 1000 : player.duration(); endTrim = endTrim ? (new Date(endTrim + "Z") - stream_start) / 1000 : player.duration();
var trimmingControls = player.trimmingControls({startTrim: startTrim, endTrim: endTrim}); const trimmingControls = player.trimmingControls({startTrim: startTrim, endTrim: endTrim});
} }
}); });
// How about an event listener?
this.on("ended", function () {
videojs.log("Awww...over so soon?!");
});
this.on("error", function () { this.on("error", function () {
videojs.log("Could not load video stream"); videojs.log("Could not load video stream");
alert("No video available for stream."); alert("No video available for stream.");
}); });
}); });
var hlsQS = player.hlsQualitySelector(); const hlsQS = player.hlsQualitySelector();
} }
function mapDiscontinuities() { function mapDiscontinuities() {
var playlist = player.vhs.playlists.master.playlists.filter( const playlist = player.vhs.playlists.master.playlists.filter(
playlist => typeof playlist.discontinuityStarts !== "undefined" playlist => typeof playlist.discontinuityStarts !== "undefined"
)[0]; //Only one of the playlists will have the discontinuity or stream start objects, and it's not necessarily the first one or the source one. )[0]; //Only one of the playlists will have the discontinuity or stream start objects, and it's not necessarily the first one or the source one.
var discontinuities = playlist.discontinuityStarts.map(segmentIndex => { const discontinuities = playlist.discontinuityStarts.map(segmentIndex => {
return { return {
segmentIndex: segmentIndex, segmentIndex: segmentIndex,
segmentTimestamp: playlist.segments[segmentIndex].dateTimeObject, segmentTimestamp: playlist.segments[segmentIndex].dateTimeObject,
playbackIndex: null, playbackIndex: null,
}; };
}); });
//var lastDiscontinuity = Math.max(...playlist.discontinuityStarts); const lastDiscontinuity = playlist.discontinuityStarts.slice(-1).pop(); //Assumes discontinuities are sorted in ascending order.
var lastDiscontinuity = playlist.discontinuityStarts.slice(-1).pop(); //Assumes discontinuities are sorted in ascending order.
var durationMarker = 0; let durationMarker = 0;
for (var index = 0; index <= lastDiscontinuity; index++) { for (let index = 0; index <= lastDiscontinuity; index++) {
let segment = playlist.segments[index]; const segment = playlist.segments[index];
if (segment.discontinuity) { if (segment.discontinuity) {
discontinuities.find(discontinuity => discontinuity.segmentIndex == index).playbackIndex = discontinuities.find(discontinuity => discontinuity.segmentIndex == index).playbackIndex =
durationMarker; durationMarker;
@ -95,12 +83,12 @@ function mapDiscontinuities() {
}; };
function getRealTimeForPlayerTime(discontinuities, playbackIndex) { function getRealTimeForPlayerTime(discontinuities, playbackIndex) {
var streamStart = player.vhs.playlists.master.playlists.filter( let streamStart = player.vhs.playlists.master.playlists.filter(
playlist => typeof playlist.dateTimeObject !== "undefined" playlist => typeof playlist.dateTimeObject !== "undefined"
)[0].dateTimeObject; //Only one of the playlists will have the discontinuity or stream start objects, and it's not necessarily the first one or the source one. )[0].dateTimeObject; //Only one of the playlists will have the discontinuity or stream start objects, and it's not necessarily the first one or the source one.
//Find last discontinuity before playbackIndex //Find last discontinuity before playbackIndex
var lastDiscontinuity = discontinuities const lastDiscontinuity = discontinuities
.filter(discontinuity => discontinuity.playbackIndex < playbackIndex) .filter(discontinuity => discontinuity.playbackIndex < playbackIndex)
.slice(-1) .slice(-1)
.pop(); .pop();
@ -109,7 +97,7 @@ function getRealTimeForPlayerTime(discontinuities, playbackIndex) {
playbackIndex -= lastDiscontinuity.playbackIndex; playbackIndex -= lastDiscontinuity.playbackIndex;
} }
var 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