diff --git a/kronic-chat/chat-controller.js b/kronic-chat/chat-controller.js new file mode 100644 index 0000000..3c0e56a --- /dev/null +++ b/kronic-chat/chat-controller.js @@ -0,0 +1,735 @@ +window.Kronick = + window.Kronick || {}; + + +/* ===================================================== + Chat notification state + ===================================================== */ + +Kronick.chatUnreadCount = + Number( + Kronick.chatUnreadCount + || 0 + ); + + +Kronick.getChatWindow = +function getChatWindow() { + return document.getElementById( + 'chatFrameWrap' + ); +}; + + +Kronick.getChatButton = +function getChatButton() { + return document.getElementById( + 'chatToolButton' + ); +}; + + +Kronick.getChatUnreadBadge = +function getChatUnreadBadge() { + return document.getElementById( + 'chatUnreadCount' + ); +}; + + +Kronick.chatWindowIsVisible = +function chatWindowIsVisible() { + const chatWrap = + Kronick.getChatWindow(); + + if (!chatWrap) { + return false; + } + + if ( + chatWrap.classList.contains( + 'window-minimized' + ) + ) { + return false; + } + + const style = + window.getComputedStyle( + chatWrap + ); + + return ( + style.display !== 'none' + && style.visibility !== 'hidden' + && style.opacity !== '0' + ); +}; + + +Kronick.isOwnChatMessage = +function isOwnChatMessage( + message +) { + const localIdentity = + Kronick.state + ?.room + ?.localParticipant + ?.identity + || ''; + + if (!localIdentity) { + return false; + } + + return ( + String( + message?.sender + || '' + ) + === + String( + localIdentity + ) + ); +}; + + +Kronick.renderChatUnreadState = +function renderChatUnreadState() { + const badge = + Kronick.getChatUnreadBadge(); + + const button = + Kronick.getChatButton(); + + if (!badge || !button) { + return; + } + + const count = + Math.max( + 0, + Number( + Kronick.chatUnreadCount + || 0 + ) + ); + + const hasUnread = + count > 0; + + badge.dataset.count = + String(count); + + badge.textContent = + count > 99 + ? '99+' + : String(count); + + badge.hidden = + !hasUnread; + + button.classList.toggle( + 'chat-alert', + hasUnread + ); + + button.setAttribute( + 'aria-label', + hasUnread + ? ( + `Open chat, ${count} unread ` + + ( + count === 1 + ? 'message' + : 'messages' + ) + ) + : 'Open chat' + ); +}; + + +Kronick.handleIncomingChatNotification = +function handleIncomingChatNotification( + message +) { + if ( + !message + || typeof message !== 'object' + ) { + return; + } + + /* + * Never notify for our own message. + */ + if ( + Kronick.isOwnChatMessage( + message + ) + ) { + return; + } + + /* + * If chat is already visible, the user can see + * the incoming message immediately. + */ + if ( + Kronick.chatWindowIsVisible() + ) { + Kronick.clearChatUnreadCount(); + return; + } + + Kronick.chatUnreadCount += + 1; + + Kronick.renderChatUnreadState(); +}; + + +Kronick.clearChatUnreadCount = +function clearChatUnreadCount() { + Kronick.chatUnreadCount = + 0; + + Kronick.renderChatUnreadState(); +}; + + +/* + * Compatibility alias for any code that was already + * calling the newer name. + */ +Kronick.clearChatNotification = + Kronick.clearChatUnreadCount; + + +/* ===================================================== + Send chat + ===================================================== */ + +Kronick.sendChatToRoom = +function sendChatToRoom( + chatPayload +) { + const room = + Kronick.state.room; + + if (!room?.localParticipant) { + alert( + 'Join a room first.' + ); + + return; + } + + const message = { + id: + chatPayload.id + || Kronick.createId(), + + sender: + room.localParticipant.identity + || 'Unknown', + + text: + chatPayload.text + || '', + + gifUrl: + chatPayload.gifUrl + || null, + + imageUrl: + chatPayload.imageUrl + || null, + + fileId: + chatPayload.fileId + || null, + + filename: + chatPayload.filename + || null, + + fileSize: + chatPayload.fileSize + || null, + + fileUrl: + chatPayload.fileUrl + || null, + + createdAt: + chatPayload.createdAt + || Date.now() + }; + + const payload = + new TextEncoder().encode( + JSON.stringify( + message + ) + ); + + room.localParticipant + .publishData( + payload, + { + reliable: + true, + + topic: + Kronick.config + .DATA_TOPIC_CHAT + } + ) + .catch(error => { + console.error( + 'Could not publish chat message:', + error + ); + }); + + /* + * Save and display locally immediately. + * LiveKit normally does not echo the packet + * back to the sending participant. + */ + Kronick.saveChatMessageToServer( + Kronick.state + .currentRoomName, + message + ); + + Kronick.receiveChatMessage( + message + ); +}; + + +/* ===================================================== + Receive chat + ===================================================== */ + +Kronick.receiveChatMessage = +function receiveChatMessage( + message +) { + if ( + !message + || typeof message !== 'object' + ) { + return; + } + + if (!message.id) { + message.id = + Kronick.createId(); + } + + Kronick.saveChatToHistory( + Kronick.state + .currentRoomName, + message + ); + + const chatFrame = + document.getElementById( + 'chatFrame' + ); + + if ( + chatFrame?.contentWindow + ) { + chatFrame.contentWindow + .postMessage( + { + type: + 'CHAT_MESSAGE', + + message + }, + Kronick.config + .APP_ORIGIN + ); + } + + /* + * Notification ownership lives here. + * One incoming message = one notification check. + */ + Kronick + .handleIncomingChatNotification( + message + ); +}; + + +/* ===================================================== + Persist chat + ===================================================== */ + +Kronick.saveChatMessageToServer = +async function saveChatMessageToServer( + roomName, + message +) { + if ( + !roomName + || !message + ) { + return; + } + + try { + const response = + await fetch( + '/api/chat/message', + { + method: + 'POST', + + headers: { + 'Content-Type': + 'application/json' + }, + + body: + JSON.stringify({ + ...message, + room: + roomName + }) + } + ); + + if (!response.ok) { + throw new Error( + 'Chat save failed: ' + + response.status + ); + } + } catch (error) { + console.warn( + 'Could not save chat message:', + error + ); + } +}; + + +/* ===================================================== + Load history + ===================================================== */ + +Kronick.loadRoomChatHistory = +async function loadRoomChatHistory( + roomName +) { + try { + const response = + await fetch( + '/api/chat/history/' + + encodeURIComponent( + roomName + ) + ); + + if (!response.ok) { + throw new Error( + `History failed: ${ + response.status + }` + ); + } + + const data = + await response.json(); + + const messages = + Array.isArray( + data.messages + ) + ? data.messages + : []; + + messages.forEach( + message => { + Kronick.saveChatToHistory( + roomName, + message + ); + } + ); + + Kronick.sendMessagesToChatFrame( + 'CHAT_HISTORY', + messages + ); + } catch (error) { + console.warn( + 'Could not load chat history:', + error + ); + + Kronick + .sendChatHistoryToFrame(); + } +}; + + +/* ===================================================== + Local history storage + ===================================================== */ + +Kronick.saveChatToHistory = +function saveChatToHistory( + roomName, + message +) { + if ( + !roomName + || !message + ) { + return; + } + + const key = + `chatHistory-${roomName}`; + + let history = []; + + try { + history = + JSON.parse( + localStorage.getItem( + key + ) + ) + || []; + } catch { + history = []; + } + + const exists = + history.some( + item => + item.id + === message.id + ); + + if (exists) { + return; + } + + history.push( + message + ); + + history = + history.slice( + -100 + ); + + localStorage.setItem( + key, + JSON.stringify( + history + ) + ); +}; + + +Kronick.getChatHistory = +function getChatHistory( + roomName +) { + if (!roomName) { + return []; + } + + const key = + `chatHistory-${roomName}`; + + try { + return ( + JSON.parse( + localStorage.getItem( + key + ) + ) + || [] + ); + } catch { + return []; + } +}; + + +/* ===================================================== + Parent -> chat iframe + ===================================================== */ + +Kronick.sendMessagesToChatFrame = +function sendMessagesToChatFrame( + type, + messages +) { + const chatFrame = + document.getElementById( + 'chatFrame' + ); + + if ( + !chatFrame + ?.contentWindow + ) { + return; + } + + chatFrame.contentWindow + .postMessage( + { + type, + messages + }, + Kronick.config + .APP_ORIGIN + ); +}; + + +Kronick.sendChatHistoryToFrame = +function sendChatHistoryToFrame() { + const roomName = + Kronick.state + .currentRoomName; + + if (!roomName) { + return; + } + + const history = + Kronick.getChatHistory( + roomName + ); + + Kronick.sendMessagesToChatFrame( + 'CHAT_HISTORY', + history + ); +}; + + +/* ===================================================== + Unread UI lifecycle + ===================================================== */ + +Kronick.initChatUnreadUi = +function initChatUnreadUi() { + Kronick + .renderChatUnreadState(); + + const chatButton = + Kronick.getChatButton(); + + const chatWrap = + Kronick.getChatWindow(); + + /* + * Opening chat clears unread immediately. + */ + chatButton?.addEventListener( + 'click', + () => { + window.setTimeout( + () => { + if ( + Kronick + .chatWindowIsVisible() + ) { + Kronick + .clearChatUnreadCount(); + } + }, + 0 + ); + } + ); + + /* + * This also catches: + * - restore from minimized + * - opening through another control + * - window manager restore + */ + if (chatWrap) { + const observer = + new MutationObserver( + () => { + if ( + Kronick + .chatWindowIsVisible() + ) { + Kronick + .clearChatUnreadCount(); + } + } + ); + + observer.observe( + chatWrap, + { + attributes: + true, + + attributeFilter: + [ + 'class', + 'style', + 'hidden' + ] + } + ); + } + + /* + * If the browser regains focus while chat is + * visibly open, there is nothing unread. + */ + window.addEventListener( + 'focus', + () => { + if ( + Kronick + .chatWindowIsVisible() + ) { + Kronick + .clearChatUnreadCount(); + } + } + ); +}; + + +if ( + document.readyState + === 'loading' +) { + document.addEventListener( + 'DOMContentLoaded', + Kronick.initChatUnreadUi, + { + once: + true + } + ); +} else { + Kronick + .initChatUnreadUi(); +} diff --git a/kronic-chat/chat.html b/kronic-chat/chat.html new file mode 100644 index 0000000..6926ff8 --- /dev/null +++ b/kronic-chat/chat.html @@ -0,0 +1,116 @@ + + + + + + + + 💬 Kronick Chat 💬 + + + + + + + +
+
+
+ + +
+

+ 💬 Kronick Chat 💬 +

+ +

+ Room messages +

+
+
+
+ +
+
+ No messages yet. +
+
+ + +
+ + diff --git a/kronic-chat/giphy.html b/kronic-chat/giphy.html new file mode 100644 index 0000000..749856c --- /dev/null +++ b/kronic-chat/giphy.html @@ -0,0 +1,141 @@ + + + + + + + + Kronick GIPHY + + + + + + + +
+
+
+ + GIF + + +
+

+ Search GIFs +

+ +

+ Find and share animated GIFs +

+
+
+ + +
+ +
+
+ + + +
+ +
+ Search for a GIF to get started. +
+
+ +
+ + +
+
+
+ GIF +
+ +
+ No GIFs loaded +
+ +
+ Enter a search above to browse results. +
+
+
+
+
+ + diff --git a/kronic-chat/giphy_api.py b/kronic-chat/giphy_api.py new file mode 100644 index 0000000..0919bdc --- /dev/null +++ b/kronic-chat/giphy_api.py @@ -0,0 +1,82 @@ +"""GIPHY search for the embedded Kronic Chat browser. + +This route runs in Chat's FastAPI application and is exposed by the +existing /borg-chat/ gateway, without an Nginx custom location. +""" + +import asyncio +import os +import time +from collections import OrderedDict + +import requests +from fastapi import APIRouter, HTTPException, Query + +router = APIRouter() +_GIPHY_SEARCH_URL = "https://api.giphy.com/v1/gifs/search" +_CACHE_TTL_SECONDS = 300 +_CACHE_LIMIT = 100 +_cache = OrderedDict() + + +def _fetch_giphy(query: str, key: str) -> dict: + try: + response = requests.get( + _GIPHY_SEARCH_URL, + params={"api_key": key, "q": query, "limit": 25, "rating": "g"}, + timeout=(5, 12), + ) + response.raise_for_status() + payload = response.json() + except requests.RequestException as exc: + # Avoid passing the token or upstream URL into user-visible errors. + raise HTTPException(502, "GIPHY search service unavailable") from exc + except ValueError as exc: + raise HTTPException(502, "GIPHY returned an invalid response") from exc + + items = [] + for item in payload.get("data", []): + images = item.get("images") or {} + original = (images.get("original") or {}).get("url") + preview = (images.get("downsized_medium") or {}).get("url") or \ + (images.get("downsized") or {}).get("url") or original + thumbnail = (images.get("fixed_width_small") or {}).get("url") or \ + (images.get("fixed_height_small") or {}).get("url") or preview + if not preview: + continue + items.append({ + "id": item.get("id"), + "title": item.get("title", ""), + "url": preview, + "originalUrl": original or preview, + "thumbnail": thumbnail or preview, + "source": "giphy", + }) + return {"items": items} + + +@router.get("/api/giphy/search") +async def search_giphy( + q: str = Query(..., min_length=1, max_length=150), + refresh: bool = False, +): + key = os.getenv("GIPHY_API_KEY", "").strip() + if not key: + raise HTTPException(503, "GIPHY_API_KEY is not configured in Chat") + query = q.strip() + if not query: + return {"items": []} + cache_key = query.casefold() + now = time.monotonic() + if not refresh and cache_key in _cache: + expiry, result = _cache[cache_key] + if now < expiry: + _cache.move_to_end(cache_key) + return result + del _cache[cache_key] + result = await asyncio.to_thread(_fetch_giphy, query, key) + _cache[cache_key] = (time.monotonic() + _CACHE_TTL_SECONDS, result) + _cache.move_to_end(cache_key) + while len(_cache) > _CACHE_LIMIT: + _cache.popitem(last=False) + return result