PYRSS-Website/apps/static/js/home/subscriptions.js

399 lines
13 KiB
JavaScript

var subTable = null;
// Create subscription table
function initSubscriptionTable() {
subTable = $("#subTable").DataTable({
info: false,
paging: false,
searching: false,
autoWidth: false,
order: [],
select: {
style: "multi+shift",
selector: 'th:first-child input[type="checkbox"]'
},
columnDefs: [
{ orderable: false, targets: "no-sort" },
{
targets: 0,
checkboxes: { selectRow: true }
}
],
columns: [
{
// Select row checkbox column
title: '<input type="checkbox" class="form-check-input table-select-all" />',
data: null,
orderable: false,
className: "text-center",
render: function() {
return '<input type="checkbox" class="form-check-input table-select-row" />'
}
},
{ title: "ID", data: "id", visible: false },
{
title: "Name",
data: "name",
render: function(data, type, row) {
return `<a href="#" onclick="showEditSubModal(${row.id})" class="text-decoration-none">${data}</a>`
}
},
{
title: "URL",
data: "url",
render: function(data, type) {
return `<a href="${data}" class="text-decoration-none" target="_blank">${data}</a>`
}
},
{ title: "Channels", data: "channels_count" },
{
title: "Created",
data: "creation_datetime",
render: function(data, type) {
return new Date(data).toISOString().split("T")[0];
}
},
{
title: "Notes",
data: "extra_notes",
orderable: false,
className: "text-center",
render: function(data, type) {
if (!data) return "-";
return $(`<i class="bi bi-chat-left-text" data-bs-trigger="hover focus" data-bs-toggle="popover" data-bs-title="Extra Notes" data-bs-content="${data}"></i>`).popover()[0];
}
},
{
title: "Active",
data: "active",
orderable: false,
className: "text-center form-switch",
render: function(data, type) {
return `<input type="checkbox" class="sub-toggle-active form-check-input ms-0" ${data ? "checked" : ""} />`
}
}
]
});
}
$("#subTable").on("change", ".sub-toggle-active", async function () {
$(".sub-toggle-active").prop("disabled", true);
try {
const active = $(this).prop("checked");
const sub = subTable.row($(this).closest("tr")).data();
const subPrimaryKey = await saveSubscription(
sub.id,
sub.name,
sub.url,
sub.guild_id,
sub.extra_notes,
sub.filters,
active
);
showToast(
active ? "success" : "danger",
"Subscription " + (active ? "Activated" : "Deactivated"),
"Subscription ID: " + subPrimaryKey
);
}
finally {
setTimeout(() => { $(".sub-toggle-active").prop("disabled", false); }, 500)
}
});
// Open new subscription modal
$("#addSubscriptionBtn").on("click", async function() {
await showEditSubModal(-1);
});
async function showEditSubModal(subId) {
if (subId === -1) {
$("#subFormModal input, #subFormModal textarea").val("");
$("#subFormModal .form-create").show();
$("#subFormModal .form-edit").hide();
$("#subChannels").val("").change();
$("#subFilters").val("").change();
$("#subActive").prop("checked", true);
$("#subImagePreview img").attr("src", "").hide();
$("#subImagePreview small").show();
}
else {
const subscription = subTable.row(function(idx, data, node) {
return data.id === subId;
}).data();
$("#subName").val(subscription.name);
$("#subUrl").val(subscription.url);
$("#subExtraNotes").val(subscription.extra_notes);
$("#subActive").prop("checked", subscription.active);
$("#subFormModal .form-create").hide();
$("#subFormModal .form-edit").show();
const channels = await getSubChannels(subscription.id);
$("#subChannels").val("").change();
$("#subChannels").val(channels.results.map(channel => channel.channel_id)).change();
$("#subFilters").val("").change();
$("#subFilters").val(subscription.filters).change();
}
$("#subId").val(subId);
$("#subFormModal").modal("show");
}
$("#subForm").on("submit", async function(event) {
event.preventDefault();
var id = $("#subId").val();
name = $("#subName").val();
url = $("#subUrl").val();
guildId = getCurrentlyActiveServer().guild_id;
extraNotes = $("#subExtraNotes").val();
subChannels = $("#subChannels option:selected").toArray().map(channel => channel.value);
subFilters = $("#subFilters option:selected").toArray().map(filter => parseInt(filter.value));
active = $("#subActive").prop("checked");
// alert(JSON.stringify(subFilters, null, 4));
var subPrimaryKey = await saveSubscription(id, name, url, guildId, extraNotes, subFilters, active);
await deleteSubChannels(subPrimaryKey);
subChannels.forEach(async channelId => {
await saveSubChannel(channelId, subPrimaryKey);
});
if (subPrimaryKey)
showToast("success", "Subscription Saved", "Subscription ID: " + subPrimaryKey);
await loadSubscriptions(guildId);
$("#subFormModal").modal("hide");
});
async function saveSubscription(id, name, url, guildId, extraNotes, filters, active) {
var formData = new FormData();
formData.append("name", name);
formData.append("url", url);
formData.append("guild_id", guildId);
formData.append("extra_notes", extraNotes);
filters.forEach(filter => formData.append("filters", filter));
formData.append("active", active);
var response;
try {
if (id === "-1") response = await newSubscription(formData);
else response = await editSubscription(id, formData);
}
catch (err) {
showToast("danger", "Subscription Error", err.responseText, 18000);
return false;
}
return response.id;
}
async function saveSubChannel(channelId, subscriptionId) {
var formData = new FormData();
formData.append("channel_id", channelId);
formData.append("subscription", subscriptionId);
var response
try {
response = await newSubChannel(formData);
}
catch (error) {
console.log(error);
showToast("danger", "Failed to save subchannel", error, 18000);
return false
}
return response.id
}
function clearExistingSubRows() {
$("#subTable thead .table-select-all").prop("checked", false).prop("indeterminate", false);
subTable.clear().draw(false);
}
async function loadSubscriptions(guildId) {
if (!guildId)
return;
$("#deleteSelectedSubscriptionsBtn").prop("disabled", true);
clearExistingSubRows();
try {
const subscriptions = await getSubscriptions(guildId);
subTable.rows.add(subscriptions.results).draw(false);
$("#subTable thead .table-select-all").prop("disabled", subscriptions.results.length === 0);
}
catch (err) {
console.error(JSON.stringify(err, null, 4));
showToast("danger", `Error Loading Subscriptions: HTTP ${err.status}`, err.responseJSON.message, 15000);
}
}
$(document).on("selectedServerChange", async function() {
// Hide alerts
$("#serverJoinAlert").attr("style", "display: none !important");
const activeServer = getCurrentlyActiveServer();
await loadSubscriptions(activeServer.guild_id);
await loadChannelOptions(activeServer.guild_id);
await loadFilterOptions(activeServer.guild_id);
})
// Delete button on the 'edit subscription' modal
$("#deleteEditSub").on("click", async function() {
const subId = $("#subId").val();
await deleteSubscription(subId);
await loadSubscriptions(getCurrentlyActiveServer().guild_id);
$("#subFormModal").modal("hide");
showToast("danger", "Deleted Subscription", "Subscription ID: " + subId);
});
$("#deleteSelectedSubscriptionsBtn").on("click", async function() {
// showToast("danger", "Not Implemented", "This feature isn't implemented");
var rows = subTable.rows(".selected").data();
$.each(rows, async function() {
// alert(JSON.stringify(this, null, 4));
await deleteSubscription(this.id);
showToast("danger", "Deleted Subscription", "Subscription ID: " + this.id);
});
await loadSubscriptions(getCurrentlyActiveServer().guild_id);
})
async function loadChannelOptions(guildId) {
// Disable input while options are loading
$("#subChannels").prop("disabled", true);
// Delete existing options
$("#subChannels option").each(function() {
if ($(this).val())
$(this).remove();
});
// Clear select2 input
$("#subChannels").val("").change();
try {
const channels = await loadChannels(guildId);
console.debug(JSON.stringify(channels));
// If we have reached the discord API rate limit
if (channels.message && channels.message.includes("rate limit")) {
throw new Error(
`${channels.message} Retry after ${channels.retry_after} seconds.`
)
}
// If we can't fetch channels due to error
if (channels.code === 50001) {
// Also check that the user hasn't changed the currently active guild, otherwise
// the alert will show under the wrong server.
if (getCurrentlyActiveServer().guild_id === guildId)
showServerJoinAlert();
const guildName = getServerFromSnowflake(guildId).name;
throw new Error(
`Unable to retrieve channels from Guild <b>${guildName}</b>.
Ensure that @PYRSS is a member with permissions
to view channels.`
);
}
channels.forEach(channel => {
// We only want TextChannels, which have a type of 0
if (channel.type !== 0)
return;
$("#subChannels").append($("<option>", {
text: "#" + channel.name,
value: channel.id
}));
});
}
catch(error) {
console.error(error);
showToast("danger", "Error loading channels", error, 18000);
}
finally {
// Re-enable the input
$("#subChannels").prop("disabled", false);
}
}
async function loadFilterOptions(guildId) {
// Disable input while options are loading
$("#subFilters").prop("disabled", true);
// Delete existing options
$("#subFilters option").each(function() {
if ($(this).val())
$(this).remove();
});
// Clear select2 input
$("#subFilters").val("").change();
try {
const filters = await getFilters(guildId);
console.log(JSON.stringify(filters));
filters.results.forEach(filter => {
$("#subFilters").append($("<option>", {
text: filter.name,
value: filter.id
}));
});
}
catch(error) {
console.error(error);
showToast("danger", "Error loading sub filters", error, 18000);
}
finally {
// Re-enable the input
$("#subFilters").prop("disabled", false);
}
}
function showServerJoinAlert() {
const guildId = getCurrentlyActiveServer().guild_id;
const inviteUrl = `https://discord.com/oauth2/authorize
?client_id=1129345991758336020
&permissions=2147534848&scope=bot+applications.commands
&guild_id=${guildId}
&disable_guild_select=true`
$("#serverJoinAlert a.alert-link").attr("href", inviteUrl);
$("#serverJoinAlert").show();
}
$("#subImage").on("change", function () {
const [file] = $("#subImage")[0].files;
if (file) {
$("#subImagePreview small").hide();
$("#subImagePreview img").attr("src", URL.createObjectURL(file)).show();
}
});
imgInp.onchange = evt => {
const [file] = imgInp.files
if (file) {
blah.src = URL.createObjectURL(file)
}
}