mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
refac
This commit is contained in:
1 parent
e06ee9338f
commit
149f34bfd2
16 files changed
+118
-30
No files matched your search
@@ -20,6 +20,7 @@ export interface NotificationTarget {
|
||||
id: string;
|
||||
type: NotificationTargetType;
|
||||
enabled: boolean;
|
||||
is_default?: boolean;
|
||||
events: ChatNotificationEvent[];
|
||||
delivery: NotificationDelivery;
|
||||
config: {
|
||||
@@ -77,6 +78,10 @@ export function testNotificationTarget(id: string) {
|
||||
return fetchJSON<{ ok: boolean }>(`/api/notifications/targets/${id}/test`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export function setDefaultNotificationTarget(id: string) {
|
||||
return fetchJSON<NotificationTarget>(`/api/notifications/targets/${id}/default`, { method: 'PUT' });
|
||||
}
|
||||
|
||||
export async function listNotificationBotOptions(): Promise<BotOption[]> {
|
||||
const data = await fetchJSON<{ bots: BotOption[] }>('/api/notifications/bot-options');
|
||||
return data.bots;
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
listNotificationBotOptions,
|
||||
listNotificationEvents,
|
||||
listNotificationTargets,
|
||||
setDefaultNotificationTarget,
|
||||
testNotificationTarget,
|
||||
updateNotificationTarget,
|
||||
type BotOption,
|
||||
@@ -63,20 +64,22 @@
|
||||
|
||||
async function loadNotificationTargets() {
|
||||
loadingTargets = true;
|
||||
try {
|
||||
const [nextTargets, bots, events] = await Promise.all([
|
||||
listNotificationTargets(),
|
||||
listNotificationBotOptions(),
|
||||
listNotificationEvents()
|
||||
]);
|
||||
targets = nextTargets;
|
||||
botOptions = bots;
|
||||
eventOptions = events.length ? events : fallbackEventOptions;
|
||||
} catch {
|
||||
const [targetResult, botResult, eventResult] = await Promise.allSettled([
|
||||
listNotificationTargets(),
|
||||
listNotificationBotOptions(),
|
||||
listNotificationEvents()
|
||||
]);
|
||||
if (targetResult.status === 'fulfilled') {
|
||||
targets = targetResult.value;
|
||||
} else {
|
||||
toast.error($t('general.notificationTargetsLoadFailed'));
|
||||
} finally {
|
||||
loadingTargets = false;
|
||||
}
|
||||
botOptions = botResult.status === 'fulfilled' ? botResult.value : [];
|
||||
eventOptions =
|
||||
eventResult.status === 'fulfilled' && eventResult.value.length
|
||||
? eventResult.value
|
||||
: fallbackEventOptions;
|
||||
loadingTargets = false;
|
||||
}
|
||||
|
||||
async function toggleNotifications() {
|
||||
@@ -150,12 +153,12 @@
|
||||
destination_chat_id: form.destination_chat_id.trim()
|
||||
};
|
||||
}
|
||||
const saved = originalId
|
||||
? await updateNotificationTarget(originalId, payload)
|
||||
: await createNotificationTarget(payload);
|
||||
targets = originalId
|
||||
? targets.map((target) => (target.id === originalId ? saved : target))
|
||||
: [...targets, saved];
|
||||
if (originalId) {
|
||||
await updateNotificationTarget(originalId, payload);
|
||||
} else {
|
||||
await createNotificationTarget(payload);
|
||||
}
|
||||
await loadNotificationTargets();
|
||||
formOpen = false;
|
||||
toast.success($t('settings.saved'));
|
||||
} catch (error) {
|
||||
@@ -167,8 +170,8 @@
|
||||
|
||||
async function patchTarget(target: NotificationTarget, patch: Partial<NotificationTarget>) {
|
||||
try {
|
||||
const saved = await updateNotificationTarget(target.id, patch as any);
|
||||
targets = targets.map((item) => (item.id === saved.id ? saved : item));
|
||||
await updateNotificationTarget(target.id, patch as any);
|
||||
await loadNotificationTargets();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
}
|
||||
@@ -177,7 +180,16 @@
|
||||
async function removeTarget(target: NotificationTarget) {
|
||||
try {
|
||||
await deleteNotificationTarget(target.id);
|
||||
targets = targets.filter((item) => item.id !== target.id);
|
||||
await loadNotificationTargets();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
async function makeDefault(target: NotificationTarget) {
|
||||
try {
|
||||
await setDefaultNotificationTarget(target.id);
|
||||
await loadNotificationTargets();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
}
|
||||
@@ -255,6 +267,11 @@
|
||||
<span class="shrink-0 text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{target.type === 'webhook' ? $t('general.webhook') : $t('general.bot')}
|
||||
</span>
|
||||
{#if target.is_default}
|
||||
<span class="shrink-0 text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('general.default')}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="truncate text-[0.625rem] text-gray-400 dark:text-gray-600 leading-tight">
|
||||
{targetDestination}
|
||||
@@ -274,6 +291,14 @@
|
||||
>
|
||||
{$t('general.sendTest')}
|
||||
</button>
|
||||
{#if !target.is_default}
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => makeDefault(target)}
|
||||
>
|
||||
{$t('general.makeDefault')}
|
||||
</button>
|
||||
{/if}
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => openEditTarget(target)}
|
||||
|
||||
@@ -412,6 +412,7 @@
|
||||
"general.onlyWhenAway": "Nur wenn ich abwesend bin",
|
||||
"general.always": "Immer",
|
||||
"general.sendTest": "Test senden",
|
||||
"general.makeDefault": "Als Standard festlegen",
|
||||
"general.platformDestinationId": "Plattform-Ziel-ID",
|
||||
"general.targetId": "Ziel-ID",
|
||||
"general.targetIdForNotify": "Ziel-ID",
|
||||
|
||||
@@ -412,6 +412,7 @@
|
||||
"general.onlyWhenAway": "Only when I'm away",
|
||||
"general.always": "Always",
|
||||
"general.sendTest": "Send test",
|
||||
"general.makeDefault": "Make default",
|
||||
"general.platformDestinationId": "Platform destination ID",
|
||||
"general.targetId": "Target ID",
|
||||
"general.targetIdForNotify": "Target ID",
|
||||
|
||||
@@ -412,6 +412,7 @@
|
||||
"general.onlyWhenAway": "Solo cuando estoy ausente",
|
||||
"general.always": "Siempre",
|
||||
"general.sendTest": "Enviar prueba",
|
||||
"general.makeDefault": "Hacer predeterminado",
|
||||
"general.platformDestinationId": "ID de destino de la plataforma",
|
||||
"general.targetId": "ID del destino",
|
||||
"general.targetIdForNotify": "ID del destino",
|
||||
|
||||
@@ -412,6 +412,7 @@
|
||||
"general.onlyWhenAway": "Seulement quand je suis absent",
|
||||
"general.always": "Toujours",
|
||||
"general.sendTest": "Envoyer un test",
|
||||
"general.makeDefault": "Définir par défaut",
|
||||
"general.platformDestinationId": "ID de destination de la plateforme",
|
||||
"general.targetId": "ID de la cible",
|
||||
"general.targetIdForNotify": "ID de la cible",
|
||||
|
||||
@@ -412,6 +412,7 @@
|
||||
"general.onlyWhenAway": "離席中のみ",
|
||||
"general.always": "常に",
|
||||
"general.sendTest": "テスト送信",
|
||||
"general.makeDefault": "既定に設定",
|
||||
"general.platformDestinationId": "プラットフォーム送信先ID",
|
||||
"general.targetId": "通知先ID",
|
||||
"general.targetIdForNotify": "通知先ID",
|
||||
|
||||
@@ -412,6 +412,7 @@
|
||||
"general.onlyWhenAway": "자리 비움일 때만",
|
||||
"general.always": "항상",
|
||||
"general.sendTest": "테스트 보내기",
|
||||
"general.makeDefault": "기본값으로 설정",
|
||||
"general.platformDestinationId": "플랫폼 대상 ID",
|
||||
"general.targetId": "대상 ID",
|
||||
"general.targetIdForNotify": "대상 ID",
|
||||
|
||||
@@ -412,6 +412,7 @@
|
||||
"general.onlyWhenAway": "Só quando eu estiver ausente",
|
||||
"general.always": "Sempre",
|
||||
"general.sendTest": "Enviar teste",
|
||||
"general.makeDefault": "Definir como padrão",
|
||||
"general.platformDestinationId": "ID do destino na plataforma",
|
||||
"general.targetId": "ID do destino",
|
||||
"general.targetIdForNotify": "ID do destino",
|
||||
|
||||
@@ -412,6 +412,7 @@
|
||||
"general.onlyWhenAway": "Только когда меня нет",
|
||||
"general.always": "Всегда",
|
||||
"general.sendTest": "Отправить тест",
|
||||
"general.makeDefault": "Сделать по умолчанию",
|
||||
"general.platformDestinationId": "ID назначения платформы",
|
||||
"general.targetId": "ID цели",
|
||||
"general.targetIdForNotify": "ID цели",
|
||||
|
||||
@@ -412,6 +412,7 @@
|
||||
"general.onlyWhenAway": "仅在我离开时",
|
||||
"general.always": "始终",
|
||||
"general.sendTest": "发送测试",
|
||||
"general.makeDefault": "设为默认",
|
||||
"general.platformDestinationId": "平台目标 ID",
|
||||
"general.targetId": "目标 ID",
|
||||
"general.targetIdForNotify": "目标 ID",
|
||||
|
||||
@@ -412,6 +412,7 @@
|
||||
"general.onlyWhenAway": "僅在我離開時",
|
||||
"general.always": "一律",
|
||||
"general.sendTest": "傳送測試",
|
||||
"general.makeDefault": "設為預設",
|
||||
"general.platformDestinationId": "平台目標 ID",
|
||||
"general.targetId": "目標 ID",
|
||||
"general.targetIdForNotify": "目標 ID",
|
||||
|
||||
@@ -12,6 +12,7 @@ from cptr.utils.notifications import (
|
||||
get_notification_event_catalog,
|
||||
get_bot_options,
|
||||
list_targets,
|
||||
set_default_target,
|
||||
test_target,
|
||||
update_target,
|
||||
)
|
||||
@@ -90,6 +91,14 @@ async def api_test_target(request: Request, target_id: str):
|
||||
raise _error(exc) from exc
|
||||
|
||||
|
||||
@router.put("/targets/{target_id}/default")
|
||||
async def api_set_default_target(request: Request, target_id: str):
|
||||
try:
|
||||
return await set_default_target(_user_id(request), target_id)
|
||||
except NotificationError as exc:
|
||||
raise _error(exc) from exc
|
||||
|
||||
|
||||
@router.get("/bot-options")
|
||||
async def api_bot_options(request: Request):
|
||||
return {
|
||||
|
||||
@@ -111,7 +111,8 @@ async def put_preferences(request: Request):
|
||||
if not user_id:
|
||||
return {"status": "skipped"}
|
||||
body = await request.json()
|
||||
await UserStates.save_data(user_id, body)
|
||||
current = await UserStates.get_data(user_id)
|
||||
await UserStates.save_data(user_id, {**current, **body})
|
||||
return {"status": "saved"}
|
||||
|
||||
|
||||
|
||||
@@ -64,6 +64,10 @@ def _public_target(target: dict) -> dict:
|
||||
return public
|
||||
|
||||
|
||||
def _default_target_id(data: dict) -> str:
|
||||
return str((data.get("notifications") or {}).get("default_target_id") or "")
|
||||
|
||||
|
||||
def _validate_events(events) -> list[str]:
|
||||
if events is None:
|
||||
return []
|
||||
@@ -110,13 +114,16 @@ def validate_webhook_url(url: str) -> str:
|
||||
async def list_targets(user_id: str) -> list[dict]:
|
||||
data = await _state(user_id)
|
||||
visible = []
|
||||
default_id = _default_target_id(data)
|
||||
for target in _targets(data):
|
||||
if target.get("type") == "bot":
|
||||
try:
|
||||
await _ensure_user_bot(user_id, str((target.get("config") or {}).get("bot_id") or ""))
|
||||
except NotificationError:
|
||||
continue
|
||||
visible.append(_public_target(target))
|
||||
public = _public_target(target)
|
||||
public["is_default"] = target.get("id") == default_id
|
||||
visible.append(public)
|
||||
return visible
|
||||
|
||||
|
||||
@@ -221,8 +228,15 @@ async def create_target(user_id: str, payload: dict) -> dict:
|
||||
await _ensure_user_bot(user_id, target["config"]["bot_id"])
|
||||
_check_unique_id(targets, target["id"])
|
||||
targets.append(target)
|
||||
notifications = data.setdefault("notifications", {})
|
||||
is_default = False
|
||||
if not notifications.get("default_target_id"):
|
||||
notifications["default_target_id"] = target["id"]
|
||||
is_default = True
|
||||
await _save_state(user_id, data)
|
||||
return _public_target(target)
|
||||
public = _public_target(target)
|
||||
public["is_default"] = is_default
|
||||
return public
|
||||
|
||||
|
||||
async def update_target(user_id: str, target_id: str, payload: dict) -> dict:
|
||||
@@ -235,8 +249,13 @@ async def update_target(user_id: str, target_id: str, payload: dict) -> dict:
|
||||
await _ensure_user_bot(user_id, target["config"]["bot_id"])
|
||||
_check_unique_id(targets, target["id"], target_id)
|
||||
targets[idx] = target
|
||||
notifications = data.setdefault("notifications", {})
|
||||
if notifications.get("default_target_id") == target_id:
|
||||
notifications["default_target_id"] = target["id"]
|
||||
await _save_state(user_id, data)
|
||||
return _public_target(target)
|
||||
public = _public_target(target)
|
||||
public["is_default"] = notifications.get("default_target_id") == target["id"]
|
||||
return public
|
||||
raise NotificationError("notification target not found")
|
||||
|
||||
|
||||
@@ -247,10 +266,24 @@ async def delete_target(user_id: str, target_id: str) -> bool:
|
||||
if len(kept) == len(targets):
|
||||
return False
|
||||
data["notifications"]["targets"] = kept
|
||||
if data["notifications"].get("default_target_id") == target_id:
|
||||
data["notifications"]["default_target_id"] = kept[0]["id"] if kept else None
|
||||
await _save_state(user_id, data)
|
||||
return True
|
||||
|
||||
|
||||
async def set_default_target(user_id: str, target_id: str) -> dict:
|
||||
data = await _state(user_id)
|
||||
for target in _targets(data):
|
||||
if target.get("id") == target_id:
|
||||
data.setdefault("notifications", {})["default_target_id"] = target_id
|
||||
await _save_state(user_id, data)
|
||||
public = _public_target(target)
|
||||
public["is_default"] = True
|
||||
return public
|
||||
raise NotificationError("notification target not found")
|
||||
|
||||
|
||||
async def _find_target(user_id: str, target_id: str) -> dict | None:
|
||||
data = await _state(user_id)
|
||||
needle = target_id.lower()
|
||||
@@ -409,10 +442,15 @@ async def dispatch_notification_event(event: Event) -> None:
|
||||
|
||||
async def notify_target(
|
||||
user_id: str,
|
||||
target_id: str,
|
||||
message: str,
|
||||
target_id: str | None = None,
|
||||
title: str | None = None,
|
||||
) -> str:
|
||||
if not target_id:
|
||||
data = await _state(user_id)
|
||||
target_id = _default_target_id(data)
|
||||
if not target_id:
|
||||
raise NotificationError("no default notification target is set")
|
||||
target = await _find_target(user_id, target_id)
|
||||
if not target:
|
||||
raise NotificationError(f'notification target "{target_id}" was not found')
|
||||
|
||||
+4
-4
@@ -1887,11 +1887,11 @@ async def search_chats(
|
||||
)
|
||||
|
||||
|
||||
async def notify(target: str, message: str, title: str = "", *, __context__: dict) -> str:
|
||||
"""Send a notification to a named user notification target.
|
||||
async def notify(message: str, target: str = "", title: str = "", *, __context__: dict) -> str:
|
||||
"""Send a notification to a user notification target.
|
||||
|
||||
:param target: Notification target name from Settings > Notifications.
|
||||
:param message: Message body to send.
|
||||
:param target: Optional notification target ID from Settings > Notifications. Uses the default target when omitted.
|
||||
:param title: Optional notification title.
|
||||
"""
|
||||
user_id = __context__.get("user_id")
|
||||
@@ -1900,7 +1900,7 @@ async def notify(target: str, message: str, title: str = "", *, __context__: dic
|
||||
try:
|
||||
from cptr.utils.notifications import NotificationError, notify_target
|
||||
|
||||
return await notify_target(user_id, target, message, title or None)
|
||||
return await notify_target(user_id, message, target or None, title or None)
|
||||
except NotificationError as exc:
|
||||
return f"Error: {exc}"
|
||||
except Exception as exc:
|
||||
|
||||
Reference in new issue
Block a user