<commit_before>package client

import (
	"encoding/json"
	"io"
	"net/http"
	"net/url"
	"sync/atomic"

	"github.com/cozy/cozy-stack/client/request"
	"github.com/gorilla/websocket"
)

// RealtimeOptions contains the options to create the realtime subscription
// channel.
type RealtimeOptions struct {
	DocTypes []string
}

// RealtimeChannel is used to create a realtime connection with the server. The
// Channel method can be used to retrieve a channel on which the realtime
// events can be received.
type RealtimeChannel struct {
	socket *websocket.Conn
	ch     chan *RealtimeServerMessage
	closed uint32
}

// RealtimeClientMessage is a struct containing the structure of the client
// messages sent to the server.
type RealtimeClientMessage struct {
	Method  string      `json:"method"`
	Payload interface{} `json:"payload"`
}

// RealtimeServerMessage is a struct containing the structure of the server
// messages received by the client.
type RealtimeServerMessage struct {
	Event   string                `json:"event"`
	Payload RealtimeServerPayload `json:"payload"`
}

// RealtimeServerPayload is the payload content of the RealtimeServerMessage.
type RealtimeServerPayload struct {
	// Response payload
	Type string          `json:"type"`
	ID   string          `json:"id"`
	Doc  json.RawMessage `json:"doc"`

	// Error payload
	Status string `json:"status"`
	Code   string `json:"code"`
	Title  string `json:"title"`
}

// RealtimeClient returns a new RealtimeChannel that instantiate a realtime
// connection with the client server.
func (c *Client) RealtimeClient(opts RealtimeOptions) (*RealtimeChannel, error) {
	var scheme string
	if c.Scheme == "https" {
		scheme = "wss"
	} else {
		scheme = "ws"
	}

	var err error
	var authorizer request.Authorizer
	if c.Authorizer != nil {
		authorizer = c.Authorizer
	} else {
		authorizer, err = c.Authenticate()
	}
	if err != nil {
		return nil, err
	}

	u := url.URL{
		Scheme: scheme,
		Host:   c.Domain,
		Path:   "/realtime/",
	}
	var headers http.Header
	if authHeader := authorizer.AuthHeader(); authHeader != "" {
		headers.Add("Authorization", authHeader)
	}
	socket, _, err := websocket.DefaultDialer.Dial(u.String(), headers)
	if err != nil {
		return nil, err
	}

	realtimeToken := authorizer.RealtimeToken()
	if realtimeToken != "" {
		err = socket.WriteJSON(RealtimeClientMessage{
			Method:  "AUTH",
			Payload: authorizer.RealtimeToken(),
		})
		if err != nil {
			return nil, err
		}
	}

	for _, docType := range opts.DocTypes {
		err = socket.WriteJSON(RealtimeClientMessage{
			Method: "SUBSCRIBE",
			Payload: struct {
				Type string `json:"type"`<commit_msg>Fix empty Add on empty header<commit_after>package client

import (
	"encoding/json"
	"io"
	"net/http"
	"net/url"
	"sync/atomic"

	"github.com/cozy/cozy-stack/client/request"
	"github.com/gorilla/websocket"
)

// RealtimeOptions contains the options to create the realtime subscription
// channel.
type RealtimeOptions struct {
	DocTypes []string
}

// RealtimeChannel is used to create a realtime connection with the server. The
// Channel method can be used to retrieve a channel on which the realtime
// events can be received.
type RealtimeChannel struct {
	socket *websocket.Conn
	ch     chan *RealtimeServerMessage
	closed uint32
}

// RealtimeClientMessage is a struct containing the structure of the client
// messages sent to the server.
type RealtimeClientMessage struct {
	Method  string      `json:"method"`
	Payload interface{} `json:"payload"`
}

// RealtimeServerMessage is a struct containing the structure of the server
// messages received by the client.
type RealtimeServerMessage struct {
	Event   string                `json:"event"`
	Payload RealtimeServerPayload `json:"payload"`
}

// RealtimeServerPayload is the payload content of the RealtimeServerMessage.
type RealtimeServerPayload struct {
	// Response payload
	Type string          `json:"type"`
	ID   string          `json:"id"`
	Doc  json.RawMessage `json:"doc"`

	// Error payload
	Status string `json:"status"`
	Code   string `json:"code"`
	Title  string `json:"title"`
}

// RealtimeClient returns a new RealtimeChannel that instantiate a realtime
// connection with the client server.
func (c *Client) RealtimeClient(opts RealtimeOptions) (*RealtimeChannel, error) {
	var scheme string
	if c.Scheme == "https" {
		scheme = "wss"
	} else {
		scheme = "ws"
	}

	var err error
	var authorizer request.Authorizer
	if c.Authorizer != nil {
		authorizer = c.Authorizer
	} else {
		authorizer, err = c.Authenticate()
	}
	if err != nil {
		return nil, err
	}

	u := url.URL{
		Scheme: scheme,
		Host:   c.Domain,
		Path:   "/realtime/",
	}
	headers := make(http.Header)
	if authHeader := authorizer.AuthHeader(); authHeader != "" {
		headers.Add("Authorization", authHeader)
	}
	socket, _, err := websocket.DefaultDialer.Dial(u.String(), headers)
	if err != nil {
		return nil, err
	}

	realtimeToken := authorizer.RealtimeToken()
	if realtimeToken != "" {
		err = socket.WriteJSON(RealtimeClientMessage{
			Method:  "AUTH",
			Payload: authorizer.RealtimeToken(),
		})
		if err != nil {
			return nil, err
		}
	}

	for _, docType := range opts.DocTypes {
		err = socket.WriteJSON(RealtimeClientMessage{
			Method: "SUBSCRIBE",
			Payload: struct {
				Type string `json:"type"`
{'fraction_non_alphanumeric': 0.10768940109578688, 'fraction_numerical': 0.0007557150954090308, 'mean_word_length': 3.7183600713012477, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '4966297', 'n_tokens_mistral': 1699, 'n_tokens_neox': 1620, 'n_words': 511}