Refactor handleUploadFile (matrix) (#629)

This commit is contained in:
Wim 2018-12-03 16:51:11 +01:00 committed by GitHub
parent 25857591a2
commit 4265d43096
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -99,11 +99,13 @@ func (b *Bmatrix) Send(msg config.Message) (string, error) {
// Upload a file if it exists
if msg.Extra != nil {
for _, rmsg := range helper.HandleExtra(&msg, b.General) {
b.mc.SendText(channel, rmsg.Username+rmsg.Text)
if _, err := b.mc.SendText(channel, rmsg.Username+rmsg.Text); err != nil {
b.Log.Errorf("sendText failed: %s", err)
}
}
// check if we have files to upload (from slack, telegram or mattermost)
if len(msg.Extra["file"]) > 0 {
return b.handleUploadFile(&msg, channel)
return b.handleUploadFiles(&msg, channel)
}
}
@ -257,15 +259,24 @@ func (b *Bmatrix) handleDownloadFile(rmsg *config.Message, content map[string]in
return nil
}
// handleUploadFile handles native upload of files
func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string) (string, error) {
// handleUploadFiles handles native upload of files.
func (b *Bmatrix) handleUploadFiles(msg *config.Message, channel string) (string, error) {
for _, f := range msg.Extra["file"] {
fi := f.(config.FileInfo)
if fi, ok := f.(config.FileInfo); ok {
b.handleUploadFile(msg, channel, &fi)
}
}
return "", nil
}
// handleUploadFile handles native upload of a file.
func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string, fi *config.FileInfo) {
content := bytes.NewReader(*fi.Data)
sp := strings.Split(fi.Name, ".")
mtype := mime.TypeByExtension("." + sp[len(sp)-1])
if strings.Contains(mtype, "image") ||
strings.Contains(mtype, "video") {
if !strings.Contains(mtype, "image") && !strings.Contains(mtype, "video") {
return
}
if fi.Comment != "" {
_, err := b.mc.SendText(channel, msg.Username+fi.Comment)
if err != nil {
@ -276,16 +287,17 @@ func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string) (string,
res, err := b.mc.UploadToContentRepo(content, mtype, int64(len(*fi.Data)))
if err != nil {
b.Log.Errorf("file upload failed: %#v", err)
continue
return
}
if strings.Contains(mtype, "video") {
switch {
case strings.Contains(mtype, "video"):
b.Log.Debugf("sendVideo %s", res.ContentURI)
_, err = b.mc.SendVideo(channel, fi.Name, res.ContentURI)
if err != nil {
b.Log.Errorf("sendVideo failed: %#v", err)
}
}
if strings.Contains(mtype, "image") {
case strings.Contains(mtype, "image"):
b.Log.Debugf("sendImage %s", res.ContentURI)
_, err = b.mc.SendImage(channel, fi.Name, res.ContentURI)
if err != nil {
@ -293,9 +305,6 @@ func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string) (string,
}
}
b.Log.Debugf("result: %#v", res)
}
}
return "", nil
}
// skipMessages returns true if this message should not be handled