package connector
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
)
const (
S_EVENT_JOIN = "join"
S_EVENT_LEAVE = "leave"
S_EVENT_MESSAGE = "message"
S_EVENT_ACTION = "action"
)
func (t EventType) MarshalText() ([]byte, error) {
switch t {
case EVENT_JOIN:
return []byte(S_EVENT_JOIN), nil
case EVENT_LEAVE:
return []byte(S_EVENT_LEAVE), nil
case EVENT_MESSAGE:
return []byte(S_EVENT_MESSAGE), nil
case EVENT_ACTION:
return []byte(S_EVENT_ACTION), nil
default:
return nil, fmt.Errorf("Invalid event type: %d", t)
}
}
func (t *EventType) UnmarshalText(text []byte) error {
switch string(text) {
case S_EVENT_JOIN:
*t = EVENT_JOIN
return nil
case S_EVENT_LEAVE:
*t = EVENT_LEAVE
return nil
case S_EVENT_MESSAGE:
*t = EVENT_MESSAGE
return nil
case S_EVENT_ACTION:
*t = EVENT_ACTION
return nil
default:
return fmt.Errorf("Invalid event type: %s", string(text))
}
}
// ----
type MediaObjectJSON struct {
Filename string `json:"filename"`
Mimetype string `json:"mime_type"`
Size int64 `json:"size"`
ImageSize *ImageSize `json:"image_size"`
Data string `json:"data"`
URL string `json:"url"`
}
func (mo SMediaObject) MarshalJSON() ([]byte, error) {
if mo.MediaObject == nil {
return []byte("null"), nil
}
mod := MediaObjectJSON{
Filename: mo.Filename(),
Mimetype: mo.Mimetype(),
Size: mo.Size(),
ImageSize: mo.ImageSize(),
URL: mo.URL(),
}
if mod.URL == "" {
// If we don't have a URL, the only way is to pass the blob itself
rd, err := mo.Read()
if err != nil {
return nil, err
}
defer rd.Close()
buf := bytes.NewBuffer([]byte{})
_, err = io.Copy(buf, rd)
if err != nil {
return nil, err
}
mod.Data = base64.StdEncoding.EncodeToString(buf.Bytes())
}
return json.Marshal(&mod)
}
func (mo *SMediaObject) UnmarshalJSON(jdata []byte) error {
if string(jdata) == "null" {
return nil
}
var d MediaObjectJSON
err := json.Unmarshal(jdata, &d)
if err != nil {
return err
}
if d.URL != "" {
*mo = SMediaObject{&LazyBlobMediaObject{
ObjectFilename: d.Filename,
ObjectMimetype: d.Mimetype,
ObjectImageSize: d.ImageSize,
GetFn: func(o *LazyBlobMediaObject) error {
resp, err := http.Get(d.URL)
if err != nil {
return err
}
if o.ObjectMimetype == "" {
o.ObjectMimetype = strings.Join(resp.Header["Content-Type"], "")
}
o.ObjectData, err = ioutil.ReadAll(resp.Body)
return err
},
}}
return nil
}
bytes, err := base64.StdEncoding.DecodeString(d.Data)
if err != nil {
return err
}
*mo = SMediaObject{&BlobMediaObject{
ObjectFilename: d.Filename,
ObjectMimetype: d.Mimetype,
ObjectImageSize: d.ImageSize,
ObjectData: bytes,
}}
return nil
}