migrated more code to ts

This commit is contained in:
arabcoders 2025-07-25 19:41:17 +03:00
parent 4e1a1e65ed
commit dcaeb7acc8
9 changed files with 249 additions and 263 deletions

View file

@ -198,7 +198,7 @@
</label>
<div class="columns is-multiline is-mobile">
<template v-for="_, key in form.request.headers" :key="key">
<div class="column is-5">
<div class="column is-5" v-if="form.request.headers[key]">
<div class="field">
<div class="control has-icons-left">
<input type="text" class="input" v-model="form.request.headers[key].key"
@ -211,7 +211,7 @@
<span>The header key to send with the notification.</span>
</span>
</div>
<div class="column is-6">
<div class="column is-6" v-if="form.request.headers[key]">
<div class="field">
<div class="control has-icons-left">
<input type="text" class="input" v-model="form.request.headers[key].value"
@ -267,11 +267,14 @@
</main>
</template>
<script setup>
<script setup lang="ts">
import { useStorage } from '@vueuse/core'
import type { notification, notificationImport } from '~/types/notification'
const emitter = defineEmits(['cancel', 'submit'])
const toast = useNotification()
const box = useConfirm()
const emitter = defineEmits(['cancel', 'submit']);
const toast = useNotification();
const props = defineProps({
reference: {
type: String,
@ -279,11 +282,11 @@ const props = defineProps({
default: null,
},
allowedEvents: {
type: Array,
type: Array as () => string[],
required: true,
},
item: {
type: Object,
type: Object as () => notification,
required: true,
},
addInProgress: {
@ -293,71 +296,75 @@ const props = defineProps({
},
})
const form = reactive(props.item);
const requestMethods = ['POST', 'PUT'];
const requestType = ['json', 'form'];
const showImport = useStorage('showImport', false);
const import_string = ref('');
const box = useConfirm()
const form = reactive<notification>({ ...props.item })
const requestMethods = ['POST', 'PUT']
const requestType = ['json', 'form']
const showImport = useStorage('showImport', false)
const import_string = ref('')
onMounted(() => {
if (!form.request.data_key) {
form.request.data_key = 'data';
form.request.data_key = 'data'
}
});
})
const checkInfo = async () => {
let required;
let required: string[]
if (!isApprise.value) {
required = ['name', 'request.url', 'request.method', 'request.type', 'request.data_key'];
required = ['name', 'request.url', 'request.method', 'request.type', 'request.data_key']
} else {
required = ['name', 'request.url'];
required = ['name', 'request.url']
}
for (const key of required) {
if (key.includes('.')) {
const [parent, child] = key.split('.');
if (!form[parent][child]) {
toast.error(`The field ${parent}.${child} is required.`);
return;
const [parent, child] = key.split('.') as [keyof typeof form, string]
const parentObj = form[parent] as Record<string, any> | undefined
if (!parentObj || !parentObj[child]) {
toast.error(`The field ${parent}.${child} is required.`)
return
}
} else {
const value = (form as Record<string, any>)[key]
if (!value) {
toast.error(`The field ${key} is required.`)
return
}
} else if (!form[key]) {
toast.error(`The field ${key} is required.`);
return;
}
}
if (!isApprise.value) {
try {
new URL(form.request.url);
} catch (e) {
toast.error('Invalid URL');
return;
new URL(form.request.url)
} catch (_) {
toast.error('Invalid URL')
return
}
}
let headers = []
const headers = []
for (const header of form.request.headers) {
if (!header.key || !header.value) {
continue
}
headers.push({ key: String(header.key).trim(), value: String(header.value).trim() })
}
form.request.headers = headers
form.request.headers = headers;
emitter('submit', { reference: toRaw(props.reference), item: toRaw(form) });
emitter('submit', { reference: toRaw(props.reference), item: toRaw(form) })
}
const importItem = async () => {
let val = import_string.value.trim()
const val = import_string.value.trim()
if (!val) {
toast.error('The import string is required.')
return
}
try {
const item = decode(val)
const item = decode(val) as notificationImport
if ('notification' !== item._type) {
toast.error(`Invalid import string. Expected type 'notification', got '${item._type}'.`)
@ -365,7 +372,7 @@ const importItem = async () => {
return
}
if (form.target) {
if (form.name || form.request?.url) {
if (false === box.confirm('Overwrite the current form fields?', true)) {
return
}
@ -375,24 +382,25 @@ const importItem = async () => {
form.name = item.name
}
if (item.url) {
form.url = item.url
if (!form.request) {
form.request = {} as any
}
if (item.request) {
form.request = item.request
}
if (item.data_key) {
form.data_key = item.data_key
if (item.request?.data_key) {
form.request.data_key = item.request.data_key
}
if (item.on) {
form.on = item.on
}
import_string.value = ''
} catch (e) {
} catch (e: any) {
console.error(e)
toast.error(`Failed to import task. ${e.message}`)
}

View file

@ -1,3 +1,46 @@
<style scoped>
.notification-item {
border-left: 4px solid transparent;
padding-left: 0.75rem;
border-bottom: 1px solid #f5f5f5;
}
.notification-info {
border-color: var(--bulma-info);
}
.notification-success {
border-color: var(--bulma-primary);
}
.notification-warning {
border-color: var(--bulma-warning);
}
.notification-error {
border-color: var(--bulma-danger);
}
.notification-list {
max-height: 300px;
overflow-y: auto;
}
.notification-message {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
max-width: 280px;
}
.notification-message.expanded {
white-space: normal;
word-break: break-word;
max-width: 100%;
}
</style>
<template>
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link">
@ -73,64 +116,21 @@
</div>
</template>
<script setup>
<script setup lang="ts">
import moment from 'moment'
const store = useNotificationStore()
const copiedId = ref(null)
const expandedId = ref(null)
const toggleExpand = id => expandedId.value = expandedId.value === id ? null : id
const copiedId = ref<string | null>(null)
const expandedId = ref<string | null>(null)
const copy_text = (id, text) => {
const toggleExpand = (id: string) => expandedId.value = expandedId.value === id ? null : id
const copy_text = (id: string, text: string): void => {
copiedId.value = id
copyText(text, false, false)
setTimeout(() => {
if (copiedId.value === id) {
copiedId.value = null
}
if (copiedId.value === id) copiedId.value = null
}, 2000)
}
</script>
<style scoped>
.notification-item {
border-left: 4px solid transparent;
padding-left: 0.75rem;
border-bottom: 1px solid #f5f5f5;
}
.notification-info {
border-color: var(--bulma-info);
}
.notification-success {
border-color: var(--bulma-primary);
}
.notification-warning {
border-color: var(--bulma-warning);
}
.notification-error {
border-color: var(--bulma-danger);
}
.notification-list {
max-height: 300px;
overflow-y: auto;
}
.notification-message {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
max-width: 280px;
}
.notification-message.expanded {
white-space: normal;
word-break: break-word;
max-width: 100%;
}
</style>

View file

@ -230,102 +230,74 @@
</main>
</template>
<script setup>
<script setup lang="ts">
import { useStorage } from '@vueuse/core'
import type { Preset, PresetImport } from '~/types/presets'
const emitter = defineEmits(['cancel', 'submit']);
const emitter = defineEmits<{
(event: 'cancel'): void
(event: 'submit', payload: { reference: string | null, preset: Preset }): void
}>()
const props = defineProps({
reference: {
type: String,
required: false,
default: null,
},
preset: {
type: Object,
required: true,
},
addInProgress: {
type: Boolean,
required: false,
default: false,
},
presets: {
type: Array,
required: false,
default: () => [],
},
})
const props = defineProps<{
reference?: string | null
preset: Preset
addInProgress?: boolean
presets?: Preset[]
}>()
const config = useConfigStore()
const toast = useNotification()
const form = reactive(JSON.parse(JSON.stringify(props.preset)))
const import_string = ref('')
const showImport = useStorage('showImport', false)
const box = useConfirm()
const selected_preset = ref('')
const form = reactive<Preset>(JSON.parse(JSON.stringify(props.preset)))
const import_string = ref<string>('')
const showImport = useStorage<boolean>('showImport', false)
const selected_preset = ref<string>('')
onMounted(() => {
if (props.preset?.cli && '' !== props.preset?.cli) {
return
}
if (props.preset?.args && (typeof props.preset.args === 'object')) {
form.args = JSON.stringify(props.preset.args, null, 2)
}
if (props.preset?.postprocessors && (typeof props.preset.postprocessors === 'object')) {
form.postprocessors = JSON.stringify(props.preset.postprocessors, null, 2)
}
})
const checkInfo = async () => {
const checkInfo = async (): Promise<void> => {
for (const key of ['name']) {
if (!form[key]) {
toast.error(`The ${key} field is required.`);
if (!form[key as keyof Preset]) {
toast.error(`The ${key} field is required.`)
return
}
}
if (form?.cli && '' !== form.cli) {
const options = await convertOptions(form.cli);
if (form.cli && '' !== form.cli) {
const options = await convertOptions(form.cli)
if (null === options) {
return
}
form.cli = form.cli.trim()
}
let copy = JSON.parse(JSON.stringify(form));
const copy: Preset = JSON.parse(JSON.stringify(form))
let usedName = false
const name = String(form.name).trim().toLowerCase()
let usedName = false;
let name = String(form.name).trim().toLowerCase();
props.presets.forEach(p => {
props.presets?.forEach(p => {
if (p.id === props.reference) {
return;
return
}
if (String(p.name).toLowerCase() === name) {
usedName = true;
usedName = true
}
});
})
if (true === usedName) {
toast.error('The preset name is already in use.');
return;
if (usedName) {
toast.error('The preset name is already in use.')
return
}
for (const key in copy) {
if (typeof copy[key] !== 'string') {
continue
const val = copy[key as keyof Preset]
if ('string' === typeof val) {
(copy as any)[key] = val.trim()
}
copy[key] = copy[key].trim()
}
emitter('submit', { reference: toRaw(props.reference), preset: toRaw(copy) });
emitter('submit', { reference: toRaw(props.reference ?? null), preset: toRaw(copy) })
}
const convertOptions = async args => {
const convertOptions = async (args: string): Promise<Record<string, any> | null> => {
try {
const response = await convertCliOptions(args)
@ -337,23 +309,22 @@ const convertOptions = async args => {
form.folder = response.download_path
}
return response.opts
} catch (e) {
return response.opts as Record<string, any>
} catch (e: any) {
toast.error(e.message)
return null
}
return null;
}
const importItem = async () => {
let val = import_string.value.trim()
const importItem = async (): Promise<void> => {
const val = import_string.value.trim()
if (!val) {
toast.error('The import string is required.')
return
}
try {
const item = decode(val)
const item = decode(val) as PresetImport
if (!item?._type || 'preset' !== item._type) {
toast.error(`Invalid import string. Expected type 'preset', got '${item._type ?? 'unknown'}'.`)
@ -368,16 +339,6 @@ const importItem = async () => {
form.cli = item.cli
}
// -- backwards compatibility for old presets.
if (item.format) {
if (!item?.cli) {
form.cli = `--format '${item.format}'`
} else {
form.cli = `--format '${item.format}'\n${form.cli}`
}
form.cli = form.cli.trim()
}
if (item.template) {
form.template = item.template
}
@ -392,15 +353,15 @@ const importItem = async () => {
import_string.value = ''
showImport.value = false
} catch (e) {
} catch (e: any) {
console.error(e)
toast.error(`Failed to parse. ${e.message}`)
}
}
const filter_presets = (flag = true) => config.presets.filter(item => item.default === flag)
const filter_presets = (flag = true): Preset[] => config.presets.filter(item => item.default === flag)
const import_existing_preset = async () => {
const import_existing_preset = async (): Promise<void> => {
if (!selected_preset.value) {
return
}

View file

@ -288,52 +288,45 @@
</main>
</template>
<script setup>
<script lang="ts" setup>
import 'assets/css/bulma-switch.css'
import { useStorage } from '@vueuse/core'
import { CronExpressionParser } from 'cron-parser'
import type { exported_task, task_item } from '~/types/tasks'
const props = defineProps({
reference: {
type: String,
required: false,
default: null,
},
task: {
type: Object,
required: true,
},
addInProgress: {
type: Boolean,
required: false,
default: false,
},
})
const props = defineProps<{
reference?: string | null | undefined
task: task_item
addInProgress?: boolean
}>()
const emitter = defineEmits(['cancel', 'submit'])
const emitter = defineEmits<{
(e: 'cancel'): void
(e: 'submit', payload: { reference: string | null | undefined, task: task_item }): void
}>()
const toast = useNotification()
const config = useConfigStore()
const box = useConfirm()
const showImport = useStorage('showImport', false)
const import_string = ref('')
const import_string = ref<string>('')
const CHANNEL_REGEX = /^https?:\/\/(?:www\.)?youtube\.com\/(?:(?:channel\/(?<channelId>UC[0-9A-Za-z_-]{22}))|(?:c\/(?<customName>[A-Za-z0-9_-]+))|(?:user\/(?<userName>[A-Za-z0-9_-]+))|(?:@(?<handle>[A-Za-z0-9_-]+)))\/?$/;
const CHANNEL_REGEX = /^https?:\/\/(?:www\.)?youtube\.com\/(?:(?:channel\/(?<channelId>UC[0-9A-Za-z_-]{22}))|(?:c\/(?<customName>[A-Za-z0-9_-]+))|(?:user\/(?<userName>[A-Za-z0-9_-]+))|(?:@(?<handle>[A-Za-z0-9_-]+)))\/?$/
const form = reactive(props.task)
const form = reactive<task_item>({ ...props.task })
onMounted(() => {
if (!props.task?.preset || '' === props.task.preset) {
form.preset = toRaw(config.app.default_preset)
}
if (typeof form.auto_start === 'undefined' || form.auto_start === null) {
if (typeof form.auto_start === 'undefined' || null === form.auto_start) {
form.auto_start = true
}
})
const checkInfo = async () => {
const required = ['name', 'url']
const checkInfo = async (): Promise<void> => {
const required = ['name', 'url'] as const
for (const key of required) {
if (!form[key]) {
toast.error(`The ${key} field is required.`)
@ -344,7 +337,7 @@ const checkInfo = async () => {
if (form.timer) {
try {
CronExpressionParser.parse(form.timer)
} catch (e) {
} catch (e: any) {
console.error(e)
toast.error(`Invalid CRON expression. ${e.message}`)
return
@ -353,31 +346,29 @@ const checkInfo = async () => {
try {
new URL(form.url)
} catch (e) {
} catch {
toast.error('Invalid URL')
return
}
if (form?.cli && '' !== form.cli) {
if (form.cli && '' !== form.cli) {
const options = await convertOptions(form.cli)
if (null === options) {
return
}
form.cli = form.cli.trim(" ")
if (null === options) return
form.cli = form.cli.trim()
}
emitter('submit', { reference: toRaw(props.reference), task: toRaw(form) })
}
const importItem = async () => {
let val = import_string.value.trim()
const importItem = async (): Promise<void> => {
const val = import_string.value.trim()
if (!val) {
toast.error('The import string is required.')
return
}
try {
const item = decode(val)
const item = decode(val) as exported_task
if ('task' !== item._type) {
toast.error(`Invalid import string. Expected type 'task', got '${item._type}'.`)
@ -391,34 +382,15 @@ const importItem = async () => {
}
}
if (item.name) {
form.name = item.name
}
if (item.url) {
form.url = item.url
}
if (item.template) {
form.template = item.template
}
if (item.timer) {
form.timer = item.timer
}
if (item.folder) {
form.folder = item.folder
}
if (item.cli) {
form.cli = item.cli
}
form.auto_start = item?.auto_start ?? true
form.name = item.name ?? form.name
form.url = item.url ?? form.url
form.template = item.template ?? form.template
form.timer = item.timer ?? form.timer
form.folder = item.folder ?? form.folder
form.cli = item.cli ?? form.cli
form.auto_start = item.auto_start ?? true
if (item.preset) {
// -- check if the preset exists in config.presets
const preset = config.presets.find(p => p.name === item.preset)
if (!preset) {
toast.warning(`Preset '${item.preset}' not found. Preset will be set to default.`)
@ -429,13 +401,13 @@ const importItem = async () => {
}
import_string.value = ''
} catch (e) {
} catch (e: any) {
console.error(e)
toast.error(`Failed to import string. ${e.message}`)
}
}
const convertOptions = async args => {
const convertOptions = async (args: string): Promise<Record<string, any> | null> => {
try {
const response = await convertCliOptions(args)
@ -447,51 +419,42 @@ const convertOptions = async args => {
form.folder = response.download_path
}
return response.opts
} catch (e) {
return response.opts as Record<string, any>
} catch (e: any) {
toast.error(e.message)
}
return null
}
const hasFormatInConfig = computed(() => {
if (!form?.cli) {
return false
}
return /(?<!\S)(-f|--format)(=|\s)(\S+)/.test(form.cli)
})
const hasFormatInConfig = computed<boolean>(() => !!form.cli && /(?<!\S)(-f|--format)(=|\s)(\S+)/.test(form.cli))
const filter_presets = (flag = true) => config.presets.filter(item => item.default === flag)
const get_download_folder = () => {
if (form.preset && !hasFormatInConfig.value) {
const get_download_folder = (): string => {
if (form.preset && false === hasFormatInConfig.value) {
const preset = config.presets.find(p => p.name === form.preset)
if (preset && preset.folder) {
if (preset?.folder) {
return preset.folder.replace(config.app.download_path, '')
}
}
return '/'
}
const get_output_template = () => {
if (form.preset && !hasFormatInConfig.value) {
const get_output_template = (): string => {
if (form.preset && false === hasFormatInConfig.value) {
const preset = config.presets.find(p => p.name === form.preset)
if (preset && preset.template) {
if (preset?.template) {
return preset.template
}
}
return config.app.output_template || '%(title)s.%(ext)s'
}
function is_yt_handle(url) {
let m = url.match(CHANNEL_REGEX);
const is_yt_handle = (url: string): boolean => {
const m = url.match(CHANNEL_REGEX)
if (m?.groups) {
if (m.groups?.channelId) {
return false
}
return true
return !m.groups.channelId
}
return false
}

View file

@ -28,6 +28,7 @@
<script setup lang="ts">
import { useStorage } from '@vueuse/core'
import Hls from 'hls.js'
import type { StoreItem } from '~/types/store'
type video_track_element = {
file: string,
@ -58,7 +59,7 @@ const toast = useNotification()
const props = defineProps({
item: {
type: Object,
type: Object as () => StoreItem,
default: () => ({}),
}
})
@ -122,8 +123,8 @@ onMounted(async () => {
if (props.item.extras?.thumbnail) {
thumbnail.value = '/api/thumbnail?url=' + encodePath(props.item.extras.thumbnail)
} else {
if (response?.sidecar?.image && response.sidecar.image.length > 0) {
thumbnail.value = makeDownload(config, { "filename": response.sidecar.image[0]['file'] })
if (response.sidecar?.image?.[0]?.file) {
thumbnail.value = makeDownload(config, { "filename": response.sidecar.image[0].file })
}
}

26
ui/app/types/notification.d.ts vendored Normal file
View file

@ -0,0 +1,26 @@
type notificationRequestHeaderItem = {
key: string;
value: string;
};
type notificationRequest = {
data_key: string;
headers: notificationRequestHeaderItem[];
method: string;
type: string;
url: string;
};
type notification = {
id?: string;
name: string;
request: notificationRequest;
on: string[];
};
type notificationImport = notification & {
_type: 'notification';
_version: string;
};
export type { notificationRequestHeaderItem, notification, notificationRequest, notificationImport };

17
ui/app/types/presets.d.ts vendored Normal file
View file

@ -0,0 +1,17 @@
type Preset = {
id?: string
name: string
cli: string
cookies: string
default: boolean
description: string
folder: string
template: string
}
type PresetImport = Preset & {
_type: 'preset'
_version: string
}
export type { Preset, PresetImport }

View file

@ -54,6 +54,11 @@ export type StoreItem = {
thumbnail?: string
/** The uploader of the item if available */
uploader?: string
/** Uploader name if available */
is_audio?: boolean
/** If the item has audio stream */
is_video?: boolean
/** If the item has video stream */
}
/** The item temporary filename */
tmpfilename?: string | null

View file

@ -1,4 +1,5 @@
import type { convert_args_response } from "~/types/responses";
import type { StoreItem } from "~/types/store";
const runtimeConfig = useRuntimeConfig()
const toast = useNotification()
@ -437,7 +438,7 @@ const getQueryParams = (url: string = window.location.search): Record<string, st
* @param base - The base endpoint type (default: 'api/download').
* @returns The fully constructed download URI.
*/
const makeDownload = (config: any, item: { folder?: string; filename: string }, base: string = 'api/download'): string => {
const makeDownload = (config: any, item: StoreItem | { folder?: string; filename: string }, base: string = 'api/download'): string => {
let baseDir = 'api/player/m3u8/video/'
if ('m3u8' !== base) {
baseDir = `${base}/`
@ -448,6 +449,10 @@ const makeDownload = (config: any, item: { folder?: string; filename: string },
baseDir += item.folder + '/'
}
if (!item.filename) {
return ''
}
const url = `/${sTrim(baseDir, '/')}${encodePath(item.filename)}`
return uri('m3u8' === base ? `${url}.m3u8` : url)
}