Update presets to use safe url base64 for exported string.

This commit is contained in:
ArabCoders 2025-03-13 21:47:01 +03:00
parent cc96879a1d
commit ada7b5db97
8 changed files with 983 additions and 854 deletions

View file

@ -34,6 +34,7 @@
"preferredquality",
"quicktime",
"tmpfilename",
"urandom",
"vcodec",
"vconvert",
"writedescription",

View file

@ -608,3 +608,83 @@ def decrypt_data(data: str, key: bytes) -> str:
return plaintext.decode()
except Exception:
return None
def get(
data: dict | list,
path: str | list | None = None,
default: any = None,
separator=".",
):
"""
Access data in a nested dictionary or list using a path string or list of keys.
Args:
data (dict | list): The data to traverse.
path (str | list, optional): The path to the desired data. Defaults to None.
default (any, optional): The default value to return if the path is not found. Defaults to None.
separator (str, optional): The separator used to split the path string. Defaults to ".".
Returns:
any: The value at the specified path, or the default value if not found.
"""
# If path is empty, return the entire data.
if not path:
return data
# If data is not a dict or list, attempt to convert it (similar to PHP's get_object_vars).
if not isinstance(data, dict | list):
try:
data = vars(data)
except Exception:
pass
# If path is a list, try each key in order.
if isinstance(path, list):
for key in path:
val = get(data, key, "__not_set", separator)
if val != "__not_set":
return val
return default() if callable(default) else default
# For non-list path, attempt a direct lookup.
if isinstance(data, dict):
if path in data and data[path] is not None:
return data[path]
elif isinstance(data, list):
# If path is an integer index.
if isinstance(path, int):
if 0 <= path < len(data) and data[path] is not None:
return data[path]
# If path is a numeric string, convert it.
elif isinstance(path, str) and path.isdigit():
idx = int(path)
if 0 <= idx < len(data) and data[idx] is not None:
return data[idx]
# If path doesn't contain the separator, return the default.
if not (isinstance(path, str) and separator in path):
return default() if callable(default) else default
# Split the path by the separator and traverse the data structure.
segments = path.split(separator)
for segment in segments:
if isinstance(data, dict):
if segment in data:
data = data[segment]
else:
return default() if callable(default) else default
elif isinstance(data, list):
try:
idx = int(segment)
except ValueError:
return default() if callable(default) else default
if 0 <= idx < len(data):
data = data[idx]
else:
return default() if callable(default) else default
else:
return default() if callable(default) else default
return data

View file

@ -1,7 +1,7 @@
<template>
<main class="columns mt-2">
<div class="column">
<form @submit.prevent="addDownload">
<form autocomplete="off" @submit.prevent="addDownload">
<div class="box">
<div class="columns is-multiline is-mobile">
<div class="column is-12">
@ -82,7 +82,8 @@
<label class="label is-inline" for="ytdlpConfig"
v-tooltip="'Extends current global yt-dlp config. (JSON)'">
JSON yt-dlp config or CLI options.
<NuxtLink v-if="ytdlpConfig && ytdlpConfig.trim() && !ytdlpConfig.trim().startsWith('{')" @click="convertOptions()">
<NuxtLink v-if="ytdlpConfig && ytdlpConfig.trim() && !ytdlpConfig.trim().startsWith('{')"
@click="convertOptions()">
Convert to JSON
</NuxtLink>
</label>

View file

@ -4,21 +4,21 @@
<h1 class="is-pointer is-unselectable title is-5" @click="importExpanded = !importExpanded">
<span class="icon-text">
<span class="icon"><i class="fa-solid" :class="importExpanded ? 'fa-arrow-up' : 'fa-arrow-down'" /></span>
<span>Import preset from JSON string.</span>
<span>Import preset.</span>
</span>
</h1>
<form id="importForm" @submit.prevent="importPreset()" v-if="importExpanded">
<div class="box">
<label class="label" for="json_preset">
JSON encoded preset.
Base64 encoded JSON string.
</label>
<div class="field has-addons">
<div class="control has-icons-left is-expanded">
<input type="text" class="input" id="json_preset" v-model="json_preset">
<span class="icon is-small is-left"><i class="fa-solid fa-j" /></span>
<input type="text" class="input" id="json_preset" v-model="json_preset" autocomplete="off">
<span class="icon is-small is-left"><i class="fa-solid fa-t" /></span>
</div>
<div class="control">
@ -41,7 +41,7 @@
</span>
</h1>
<form id="convertOpts" @submit.prevent="convertOptions()" v-if="convertExpanded">
<form autocomplete="off" id="convertOpts" @submit.prevent="convertOptions()" v-if="convertExpanded">
<div class="box">
<label class="label" for="opts">
@ -111,8 +111,9 @@
<span class="icon"><i class="fa-solid fa-info" /></span>
<span>The yt-dlp <code>[--format, -f]</code> video format code. see <NuxtLink
href="https://github.com/yt-dlp/yt-dlp?tab=readme-ov-file#format-selection" target="blank">this
url</NuxtLink> for more info.</span>. Note, as this key is required, you can set the value to <code>not_set</code>
to use the default yt-dlp format.
url</NuxtLink> for more info.</span>. Note, as this key is required, you can set the value to
<code>not_set</code>
to use the default yt-dlp format.
</span>
</div>
</div>
@ -395,18 +396,29 @@ const convertOptions = async () => {
}
const importPreset = async () => {
if (!json_preset) {
let val = json_preset.value.trim()
if (!val) {
toast.error('The preset import string is required.')
return
}
if (form.format || form.args || form.postprocessors) {
if (false === confirm('This will overwrite the current form fields. Are you sure?')) {
if (false === val.startsWith('{')) {
try {
val = base64UrlDecode(val)
} catch (e) {
toast.error('Invalid base64 string.', e)
return
}
}
try {
const preset = JSON.parse(json_preset.value)
const preset = JSON.parse(val)
if (form.format || form.args || form.postprocessors) {
if (false === confirm('This will overwrite the current form fields. Are you sure?')) {
return
}
}
if (preset.name) {
form.name = preset.name
@ -425,16 +437,17 @@ const importPreset = async () => {
}
if (preset.output_template) {
form.template = response.output_template
form.template = preset.output_template
}
if (preset.folder) {
form.folder = response.folder
form.folder = preset.folder
}
json_preset.value = ''
importExpanded.value = false
} catch (e) {
console.error(e)
toast.error(`Failed to import preset. ${e.message}`)
}
}

View file

@ -22,10 +22,10 @@
"floating-vue": "^5.2.2",
"hls.js": "^1.4.12",
"moment": "^2.30.1",
"nuxt": "^3.11.2",
"nuxt": "^3.16",
"pinia": "^2.1.7",
"socket.io-client": "^4.7.2",
"vue": "^3.4.21",
"vue": "^3.4",
"vue-router": "^4.3.0",
"vue-toastification": "^2.0.0-rc.5"
},

View file

@ -25,7 +25,10 @@ div.is-centered {
<div class="is-pulled-right">
<div class="field is-grouped">
<p class="control">
<button class="button is-primary" @click="resetForm(false); toggleForm = !toggleForm">
<button class="button is-primary" @click="
resetForm(false);
toggleForm = !toggleForm;
">
<span class="icon"><i class="fas fa-add"></i></span>
</button>
</p>
@ -38,13 +41,13 @@ div.is-centered {
</div>
</div>
<div class="is-hidden-mobile">
<span class="subtitle">Custom presets. The presets are simply pre-defined yt-dlp settings that you want to
apply to given download.</span>
<span class="subtitle">Custom presets. The presets are simply pre-defined yt-dlp settings
that you want to apply to given download.</span>
</div>
</div>
<div class="column is-12" v-if="toggleForm">
<PresetForm :addInProgress="addInProgress" :reference="presetRef" :preset="preset" @cancel="resetForm(true);"
<PresetForm :addInProgress="addInProgress" :reference="presetRef" :preset="preset" @cancel="resetForm(true)"
@submit="updateItem" :presets="presets" />
</div>
@ -55,12 +58,14 @@ div.is-centered {
<header class="card-header">
<div class="card-header-title is-text-overflow is-block" v-text="item.name" />
<div class="card-header-icon">
<a class="has-text-primary" v-tooltip="'Copy preset.'" @click.prevent="copyItem(item)">
<a class="has-text-primary" v-tooltip="'Export preset.'" @click.prevent="copyItem(item)">
<span class="icon"><i class="fa-solid fa-copy" /></span>
</a>
<button @click="item.raw = !item.raw">
<span class="icon"><i class="fa-solid"
:class="{ 'fa-arrow-down': !item?.raw, 'fa-arrow-up': item?.raw }" /></span>
<span class="icon"><i class="fa-solid" :class="{
'fa-arrow-down': !item?.raw,
'fa-arrow-up': item?.raw,
}" /></span>
</button>
</div>
</header>
@ -91,7 +96,7 @@ div.is-centered {
</div>
<div class="card-footer">
<div class="card-footer-item">
<button class="button is-warning is-fullwidth" @click="editItem(item);">
<button class="button is-warning is-fullwidth" @click="editItem(item)">
<span class="icon"><i class="fa-solid fa-cog" /></span>
<span>Edit</span>
</button>
@ -111,184 +116,211 @@ div.is-centered {
v-if="!presets || presets.length < 1" />
</div>
</div>
<div class="column is-12">
<Message message_class="has-background-info-90 has-text-dark" title="Tips" icon="fas fa-info-circle">
<ul>
<li>
When you export the preset, it doesn't include <code>Cookies</code> field for security reasons. The exported
string is URL safe base64 encoded JSON string.
</li>
</ul>
</Message>
</div>
</div>
</template>
<script setup>
import { request } from '~/utils/index'
import { request } from "~/utils/index";
const toast = useToast()
const config = useConfigStore()
const socket = useSocketStore()
const toast = useToast();
const config = useConfigStore();
const socket = useSocketStore();
const presets = ref([])
const preset = ref({})
const presetRef = ref('')
const toggleForm = ref(false)
const isLoading = ref(false)
const initialLoad = ref(true)
const addInProgress = ref(false)
const presets = ref([]);
const preset = ref({});
const presetRef = ref("");
const toggleForm = ref(false);
const isLoading = ref(false);
const initialLoad = ref(true);
const addInProgress = ref(false);
const presetsNoDefault = computed(() => presets.value.filter(t => !t.default))
const presetsNoDefault = computed(() =>
presets.value.filter((t) => !t.default),
);
watch(() => config.app.basic_mode, async () => {
if (!config.app.basic_mode) {
return
}
await navigateTo('/')
})
watch(
() => config.app.basic_mode,
async () => {
if (!config.app.basic_mode) {
return;
}
await navigateTo("/");
},
);
watch(() => socket.isConnected, async () => {
if (socket.isConnected && initialLoad.value) {
await reloadContent(true)
initialLoad.value = false
}
})
watch(
() => socket.isConnected,
async () => {
if (socket.isConnected && initialLoad.value) {
await reloadContent(true);
initialLoad.value = false;
}
},
);
const reloadContent = async (fromMounted = false) => {
try {
isLoading.value = true
const response = await request('/api/presets')
isLoading.value = true;
const response = await request("/api/presets");
if (fromMounted && !response.ok) {
return
return;
}
const data = await response.json()
const data = await response.json();
if (data.length < 1) {
return
return;
}
presets.value = data
presets.value = data;
} catch (e) {
if (fromMounted) {
return
return;
}
console.error(e)
toast.error('Failed to fetch tasks.')
console.error(e);
toast.error("Failed to fetch tasks.");
} finally {
isLoading.value = false
isLoading.value = false;
}
}
};
const resetForm = (closeForm = false) => {
preset.value = {}
presetRef.value = null
addInProgress.value = false
preset.value = {};
presetRef.value = null;
addInProgress.value = false;
if (closeForm) {
toggleForm.value = false
toggleForm.value = false;
}
}
};
const updatePresets = async items => {
const updatePresets = async (items) => {
let data;
try {
addInProgress.value = true
addInProgress.value = true;
const response = await request('/api/presets', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(items.filter(t => !t.default)),
})
const response = await request("/api/presets", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(items.filter((t) => !t.default)),
});
data = await response.json()
data = await response.json();
if (200 !== response.status) {
toast.error(`Failed to update presets. ${data.error}`);
return false
return false;
}
presets.value = data
resetForm(true)
return true
presets.value = data;
resetForm(true);
return true;
} catch (e) {
toast.error(`Failed to update presets. ${data?.error}. ${e.message}`);
} finally {
addInProgress.value = false
addInProgress.value = false;
}
}
};
const deleteItem = async item => {
const deleteItem = async (item) => {
if (true !== confirm(`Delete preset '${item.name}'?`)) {
return
return;
}
const index = presets.value.findIndex(t => t?.id === item.id)
const index = presets.value.findIndex((t) => t?.id === item.id);
if (index > -1) {
presets.value.splice(index, 1)
presets.value.splice(index, 1);
} else {
toast.error('Preset not found.')
return
toast.error("Preset not found.");
return;
}
const status = await updatePresets(presets.value)
const status = await updatePresets(presets.value);
if (!status) {
return
return;
}
toast.success('Preset deleted.')
}
toast.success("Preset deleted.");
};
const updateItem = async ({ reference, preset }) => {
if (reference) {
const index = presets.value.findIndex((t) => t?.id === reference)
const index = presets.value.findIndex((t) => t?.id === reference);
if (index > -1) {
presets.value[index] = preset
presets.value[index] = preset;
}
} else {
presets.value.push(preset)
presets.value.push(preset);
}
const status = await updatePresets(presets.value)
const status = await updatePresets(presets.value);
if (!status) {
return
return;
}
toast.success(`Preset ${reference ? 'updated' : 'added'}.`)
resetForm(true)
}
toast.success(`Preset ${reference ? "updated" : "added"}.`);
resetForm(true);
};
const filterItem = item => {
const { raw, ...rest } = item
return JSON.stringify(rest, null, 2)
}
const filterItem = (item) => {
const { raw, ...rest } = item;
return JSON.stringify(rest, null, 2);
};
const editItem = item => {
preset.value = item
presetRef.value = item.id
toggleForm.value = true
}
const editItem = (item) => {
preset.value = item;
presetRef.value = item.id;
toggleForm.value = true;
};
onMounted(async () => socket.isConnected ? await reloadContent(true) : '')
onMounted(async () => (socket.isConnected ? await reloadContent(true) : ""));
const copyItem = item => {
let data = JSON.parse(JSON.stringify(item))
const keys = ['id', 'default', 'raw', 'cookies']
keys.forEach(key => {
const copyItem = (item) => {
let data = JSON.parse(JSON.stringify(item));
const keys = ["id", "default", "raw", "cookies"];
keys.forEach((key) => {
if (key in data) {
delete data[key]
delete data[key];
}
})
});
if (data.args && (typeof data.args === 'string')) {
data.args = JSON.parse(data.args)
if (data.args && typeof data.args === "string") {
data.args = JSON.parse(data.args);
}
if (data.postprocessors && (typeof data.postprocessors === 'string')) {
data.postprocessors = JSON.parse(data.postprocessors)
if (data.postprocessors && typeof data.postprocessors === "string") {
data.postprocessors = JSON.parse(data.postprocessors);
}
return copyText(JSON.stringify(data))
}
let userData = {};
const calcPath = path => {
const loc = config.app.download_path || '/downloads'
for (const key of Object.keys(data)) {
if (!data[key]) {
continue;
}
userData[key] = data[key];
}
return copyText(base64UrlEncode(JSON.stringify(userData)));
};
const calcPath = (path) => {
const loc = config.app.download_path || "/downloads";
if (path) {
return loc + '/' + sTrim(path, '/')
return loc + "/" + sTrim(path, "/");
}
return loc
}
return loc;
};
</script>

View file

@ -402,6 +402,32 @@ const convertCliOptions = async opts => {
return data
}
/**
* URL Safe Base64 Encode.
*
* @param {String} data The data to encode
*
* @returns {String} The encoded data
*/
const base64UrlEncode = data => btoa(data).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
/**
* URL Safe Base64 Decode.
*
* @param {String} input The input string to decode
*
* @returns {String} The decoded data
*/
const base64UrlDecode = input => {
let base64 = input.replace(/-/g, '+').replace(/_/g, '/');
const pad = base64.length % 4;
if (pad) {
base64 += '='.repeat(4 - pad);
}
return atob(base64);
}
export {
ag_set,
ag,
@ -424,4 +450,6 @@ export {
makeDownload,
formatBytes,
convertCliOptions,
base64UrlEncode,
base64UrlDecode,
}

File diff suppressed because it is too large Load diff