(:~ : Simple WebSocket chat. Utility functions. : @author BaseX Team, BSD License :) module namespace lsp-util = 'chat/util'; import module namespace ws = 'http://basex.org/modules/ws'; (:~ User id (bound to sessions and WebSockets). :) declare variable $lsp-util:id := 'id'; (:~ : Sends a users list (all, active) to all registered clients. :) declare function lsp-util:users() as empty-sequence() { ws:emit(map{ 'type': 'users', 'users': array { sort(user:list()) }, 'active': array { distinct-values( for $id in ws:ids() return ws:get($id, $lsp-util:id) )} }) }; (:~ : Sends a message to all clients, or to the clients of a specific user. : @param $text text to be sent : @param $to receiver of a private message (optional) :) declare function lsp-util:message( $text as xs:string, $to as xs:string? ) as empty-sequence() { let $ws-ids := ws:ids()[not($to) or ws:get(., $lsp-util:id) = $to] return ws:send(map{ 'type': 'message', 'text': serialize($text), 'from': ws:get(ws:id(), $lsp-util:id), 'date': format-time(current-time(), '[H02]:[m02]:[s02]'), 'private': boolean($to) }, $ws-ids) }; (:~ : Closes all WebSocket connections from the specified user. : @param $name username :) declare function lsp-util:close( $name as xs:string ) as empty-sequence() { for $id in ws:ids() where ws:get($id, $lsp-util:id) = $name return ws:close($id) };