package connector
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
)
func (t EventType) MarshalText() ([]byte, error) {
switch t {
case EVENT_JOIN:
return []byte("join"), nil
case EVENT_LEAVE:
return []byte("leave"), nil
case EVENT_MESSAGE:
return []byte("message"), nil
case EVENT_ACTION:
return []byte("action"), nil
default:
return nil, fmt.Errorf("Invalid event type: %d", t)
}
}
func (t *EventType) UnmarshalText(text []byte) error {
switch string(text) {
case "join":
*t = EVENT_JOIN
return nil
case "leave":
*t = EVENT_LEAVE
return nil
case "message":
*t = EVENT_MESSAGE
return nil
case "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"`
ImageSize *ImageSize `json:"image_size"`
Data string `json:"data"`
}
func (mo SMediaObject) MarshalJSON() ([]byte, error) {
if MediaObject(mo) == nil {
return []byte("null"), nil
}
mod := MediaObjectJSON{
Filename: mo.Filename(),
Mimetype: mo.Mimetype(),
ImageSize: mo.ImageSize(),
}
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
}
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
}