<commit_before>module System.Tianbar.Socket where

-- Socket connectivity

import Control.Exception
import Control.Concurrent
import Control.Monad

import Graphics.UI.Gtk.WebKit.WebView

import Network.Socket
import Network.URI

import System.Tianbar.Plugin

data SocketPlugin = SocketPlugin { spHost :: WebView }

instance Plugin SocketPlugin where
    initialize = return . SocketPlugin

    handleRequest (SocketPlugin wk) = withScheme "socket:" $ \uri -> do
        let params = parseQuery uri
        let Just callbackIndex = lookupQueryParam "callbackIndex" params
        let Just socketPath = lookupQueryParam "path" params
        -- TODO: support sending data more than once
        let Just dataToSend = lookupQueryParam "data" params
        sock <- socket AF_UNIX Stream defaultProtocol
        connect sock $ SockAddrUnix socketPath
        -- TODO: replace with ByteStrings
        -- TODO: resend data until done
        _ <- send sock dataToSend
        shutdown sock ShutdownSend
        forkIO $ bracket_ (return ()) (close sock) $ forever $ do
            response <- recv sock 4096
            callback wk callbackIndex [response]
        returnContent ""<commit_msg>Fix socket close handling<commit_after>module System.Tianbar.Socket where

-- Socket connectivity

import Control.Exception
import Control.Concurrent
import Control.Monad

import Graphics.UI.Gtk.WebKit.WebView

import Network.Socket
import Network.URI

import System.Tianbar.Plugin

data SocketPlugin = SocketPlugin { spHost :: WebView }

instance Plugin SocketPlugin where
    initialize = return . SocketPlugin

    handleRequest (SocketPlugin wk) = withScheme "socket:" $ \uri -> do
        let params = parseQuery uri
        let Just callbackIndex = lookupQueryParam "callbackIndex" params
        let Just socketPath = lookupQueryParam "path" params
        -- TODO: support sending data more than once
        let Just dataToSend = lookupQueryParam "data" params
        sock <- socket AF_UNIX Stream defaultProtocol
        connect sock $ SockAddrUnix socketPath
        -- TODO: replace with ByteStrings
        -- TODO: resend data until done
        _ <- send sock dataToSend
        shutdown sock ShutdownSend
        let closeSocket = const (close sock) :: IOException -> IO ()
        forkIO $ flip catch closeSocket $ forever $ do
            response <- recv sock 4096
            callback wk callbackIndex [response]
        returnContent ""
{'fraction_non_alphanumeric': 0.06173344235486509, 'fraction_numerical': 0.003270645952575634, 'mean_word_length': 2.884126984126984, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3839542', 'n_tokens_mistral': 631, 'n_tokens_neox': 605, 'n_words': 223}