2022-05-22 19:16:42 +00:00
|
|
|
package main
|
2022-02-11 10:04:07 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2023-02-04 14:10:03 +00:00
|
|
|
"context"
|
2023-06-23 12:32:18 +00:00
|
|
|
"errors"
|
2022-07-03 09:58:57 +00:00
|
|
|
"fmt"
|
2022-02-11 10:04:07 +00:00
|
|
|
"image"
|
2022-05-28 20:03:24 +00:00
|
|
|
"io"
|
2022-02-11 10:04:07 +00:00
|
|
|
"net/http"
|
2023-02-04 14:10:03 +00:00
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"path/filepath"
|
|
|
|
"strconv"
|
2022-02-11 10:04:07 +00:00
|
|
|
"strings"
|
2023-06-23 12:32:18 +00:00
|
|
|
"sync"
|
2023-01-27 23:57:44 +00:00
|
|
|
"time"
|
2022-07-03 09:58:57 +00:00
|
|
|
|
2022-02-11 10:04:07 +00:00
|
|
|
"github.com/bwmarrin/discordgo"
|
2023-01-28 01:16:33 +00:00
|
|
|
"github.com/gabriel-vasile/mimetype"
|
2022-02-11 10:04:07 +00:00
|
|
|
|
2022-04-26 03:29:35 +00:00
|
|
|
"maunium.net/go/mautrix"
|
2022-02-11 10:04:07 +00:00
|
|
|
"maunium.net/go/mautrix/appservice"
|
2023-01-27 23:57:44 +00:00
|
|
|
"maunium.net/go/mautrix/crypto/attachment"
|
2022-02-11 10:04:07 +00:00
|
|
|
"maunium.net/go/mautrix/event"
|
2023-01-29 23:35:17 +00:00
|
|
|
"maunium.net/go/mautrix/id"
|
2023-01-31 11:11:02 +00:00
|
|
|
"maunium.net/go/mautrix/util"
|
2023-02-04 14:10:03 +00:00
|
|
|
"maunium.net/go/mautrix/util/ffmpeg"
|
2023-01-27 23:57:44 +00:00
|
|
|
|
|
|
|
"go.mau.fi/mautrix-discord/database"
|
2022-02-11 10:04:07 +00:00
|
|
|
)
|
|
|
|
|
2023-06-23 12:32:18 +00:00
|
|
|
func downloadDiscordAttachment(url string, maxSize int64) ([]byte, error) {
|
2022-02-11 10:04:07 +00:00
|
|
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-05-28 20:03:24 +00:00
|
|
|
for key, value := range discordgo.DroidDownloadHeaders {
|
|
|
|
req.Header.Set(key, value)
|
|
|
|
}
|
2022-02-11 10:04:07 +00:00
|
|
|
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
2022-07-03 09:58:57 +00:00
|
|
|
if resp.StatusCode > 300 {
|
|
|
|
data, _ := io.ReadAll(resp.Body)
|
2023-06-17 16:37:08 +00:00
|
|
|
return nil, fmt.Errorf("unexpected status %d downloading %s: %s", resp.StatusCode, url, data)
|
2022-07-03 09:58:57 +00:00
|
|
|
}
|
2023-06-23 12:32:18 +00:00
|
|
|
if resp.Header.Get("Content-Length") != "" {
|
|
|
|
length, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse content length: %w", err)
|
|
|
|
} else if length > maxSize {
|
|
|
|
return nil, fmt.Errorf("attachment too large (%d > %d)", length, maxSize)
|
|
|
|
}
|
|
|
|
return io.ReadAll(resp.Body)
|
|
|
|
} else {
|
|
|
|
var mbe *http.MaxBytesError
|
|
|
|
data, err := io.ReadAll(http.MaxBytesReader(nil, resp.Body, maxSize))
|
|
|
|
if err != nil && errors.As(err, &mbe) {
|
|
|
|
return nil, fmt.Errorf("attachment too large (over %d)", maxSize)
|
|
|
|
}
|
|
|
|
return data, err
|
|
|
|
}
|
2022-02-11 10:04:07 +00:00
|
|
|
}
|
|
|
|
|
2023-01-28 13:43:16 +00:00
|
|
|
func uploadDiscordAttachment(url string, data []byte) error {
|
|
|
|
req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(data))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for key, value := range discordgo.DroidFetchHeaders {
|
|
|
|
req.Header.Set(key, value)
|
|
|
|
}
|
|
|
|
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode > 300 {
|
|
|
|
respData, _ := io.ReadAll(resp.Body)
|
|
|
|
return fmt.Errorf("unexpected status %d: %s", resp.StatusCode, respData)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-01-29 23:35:17 +00:00
|
|
|
func downloadMatrixAttachment(intent *appservice.IntentAPI, content *event.MessageEventContent) ([]byte, error) {
|
2022-02-19 13:37:12 +00:00
|
|
|
var file *event.EncryptedFileInfo
|
|
|
|
rawMXC := content.URL
|
|
|
|
|
|
|
|
if content.File != nil {
|
|
|
|
file = content.File
|
|
|
|
rawMXC = file.URL
|
|
|
|
}
|
|
|
|
|
|
|
|
mxc, err := rawMXC.Parse()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-01-29 23:35:17 +00:00
|
|
|
data, err := intent.DownloadBytes(mxc)
|
2022-02-19 13:37:12 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if file != nil {
|
2022-05-22 19:16:42 +00:00
|
|
|
err = file.DecryptInPlace(data)
|
2022-02-19 13:37:12 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return data, nil
|
|
|
|
}
|
|
|
|
|
2023-06-23 12:32:18 +00:00
|
|
|
func (br *DiscordBridge) uploadMatrixAttachment(intent *appservice.IntentAPI, data []byte, url string, encrypt bool, meta AttachmentMeta, semaWg *sync.WaitGroup) (*database.File, error) {
|
2023-01-27 23:57:44 +00:00
|
|
|
dbFile := br.DB.File.New()
|
|
|
|
dbFile.Timestamp = time.Now()
|
|
|
|
dbFile.URL = url
|
2023-01-29 23:35:17 +00:00
|
|
|
dbFile.ID = meta.AttachmentID
|
|
|
|
dbFile.EmojiName = meta.EmojiName
|
2023-01-27 23:57:44 +00:00
|
|
|
dbFile.Size = len(data)
|
2023-01-28 11:11:35 +00:00
|
|
|
dbFile.MimeType = mimetype.Detect(data).String()
|
2023-01-29 23:35:17 +00:00
|
|
|
if meta.MimeType == "" {
|
|
|
|
meta.MimeType = dbFile.MimeType
|
2023-01-28 01:16:33 +00:00
|
|
|
}
|
2023-01-29 23:35:17 +00:00
|
|
|
if strings.HasPrefix(meta.MimeType, "image/") {
|
2022-07-03 09:58:57 +00:00
|
|
|
cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
|
2023-01-27 23:57:44 +00:00
|
|
|
dbFile.Width = cfg.Width
|
|
|
|
dbFile.Height = cfg.Height
|
2022-07-03 09:58:57 +00:00
|
|
|
}
|
|
|
|
|
2023-01-29 23:35:17 +00:00
|
|
|
uploadMime := meta.MimeType
|
2023-01-27 23:57:44 +00:00
|
|
|
if encrypt {
|
|
|
|
dbFile.Encrypted = true
|
|
|
|
dbFile.DecryptionInfo = attachment.NewEncryptedFile()
|
|
|
|
dbFile.DecryptionInfo.EncryptInPlace(data)
|
2022-07-03 09:58:57 +00:00
|
|
|
uploadMime = "application/octet-stream"
|
|
|
|
}
|
2022-04-26 03:29:35 +00:00
|
|
|
req := mautrix.ReqUploadMedia{
|
|
|
|
ContentBytes: data,
|
2022-07-03 09:58:57 +00:00
|
|
|
ContentType: uploadMime,
|
2022-04-26 03:29:35 +00:00
|
|
|
}
|
2023-01-27 23:57:44 +00:00
|
|
|
if br.Config.Homeserver.AsyncMedia {
|
2023-06-16 11:42:12 +00:00
|
|
|
resp, err := intent.CreateMXC()
|
2022-04-26 03:29:35 +00:00
|
|
|
if err != nil {
|
2023-01-27 23:57:44 +00:00
|
|
|
return nil, err
|
2022-04-26 03:29:35 +00:00
|
|
|
}
|
2023-01-27 23:57:44 +00:00
|
|
|
dbFile.MXC = resp.ContentURI
|
2023-06-16 11:42:12 +00:00
|
|
|
req.MXC = resp.ContentURI
|
|
|
|
req.UnstableUploadURL = resp.UnstableUploadURL
|
2023-06-23 12:32:18 +00:00
|
|
|
semaWg.Add(1)
|
2023-01-27 23:57:44 +00:00
|
|
|
go func() {
|
2023-06-23 12:32:18 +00:00
|
|
|
defer semaWg.Done()
|
2023-01-27 23:57:44 +00:00
|
|
|
_, err = intent.UploadMedia(req)
|
|
|
|
if err != nil {
|
2023-06-16 11:42:12 +00:00
|
|
|
br.Log.Errorfln("Failed to upload %s: %v", req.MXC, err)
|
2023-01-27 23:57:44 +00:00
|
|
|
dbFile.Delete()
|
|
|
|
}
|
|
|
|
}()
|
2022-04-26 03:29:35 +00:00
|
|
|
} else {
|
|
|
|
uploaded, err := intent.UploadMedia(req)
|
|
|
|
if err != nil {
|
2023-01-27 23:57:44 +00:00
|
|
|
return nil, err
|
2022-04-26 03:29:35 +00:00
|
|
|
}
|
2023-01-27 23:57:44 +00:00
|
|
|
dbFile.MXC = uploaded.ContentURI
|
2022-02-11 10:04:07 +00:00
|
|
|
}
|
2023-01-27 23:57:44 +00:00
|
|
|
return dbFile, nil
|
|
|
|
}
|
2022-02-11 10:04:07 +00:00
|
|
|
|
2023-01-29 23:35:17 +00:00
|
|
|
type AttachmentMeta struct {
|
2023-01-31 11:11:02 +00:00
|
|
|
AttachmentID string
|
|
|
|
MimeType string
|
|
|
|
EmojiName string
|
|
|
|
CopyIfMissing bool
|
2023-02-04 14:10:03 +00:00
|
|
|
Converter func([]byte) ([]byte, string, error)
|
2023-01-29 23:35:17 +00:00
|
|
|
}
|
|
|
|
|
2023-01-31 11:11:02 +00:00
|
|
|
var NoMeta = AttachmentMeta{}
|
2022-02-11 10:04:07 +00:00
|
|
|
|
2023-01-31 11:11:02 +00:00
|
|
|
type attachmentKey struct {
|
|
|
|
URL string
|
|
|
|
Encrypt bool
|
|
|
|
}
|
|
|
|
|
2023-02-04 14:10:03 +00:00
|
|
|
func (br *DiscordBridge) convertLottie(data []byte) ([]byte, string, error) {
|
|
|
|
fps := br.Config.Bridge.AnimatedSticker.Args.FPS
|
|
|
|
width := br.Config.Bridge.AnimatedSticker.Args.Width
|
|
|
|
height := br.Config.Bridge.AnimatedSticker.Args.Height
|
|
|
|
target := br.Config.Bridge.AnimatedSticker.Target
|
|
|
|
var lottieTarget, outputMime string
|
|
|
|
switch target {
|
|
|
|
case "png":
|
|
|
|
lottieTarget = "png"
|
|
|
|
outputMime = "image/png"
|
|
|
|
fps = 1
|
|
|
|
case "gif":
|
|
|
|
lottieTarget = "gif"
|
|
|
|
outputMime = "image/gif"
|
|
|
|
case "webm":
|
|
|
|
lottieTarget = "pngs"
|
|
|
|
outputMime = "video/webm"
|
|
|
|
case "webp":
|
|
|
|
lottieTarget = "pngs"
|
|
|
|
outputMime = "image/webp"
|
|
|
|
case "disable":
|
|
|
|
return data, "application/json", nil
|
|
|
|
default:
|
|
|
|
return nil, "", fmt.Errorf("invalid animated sticker target %q in bridge config", br.Config.Bridge.AnimatedSticker.Target)
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx := context.Background()
|
|
|
|
tempdir, err := os.MkdirTemp("", "mautrix_discord_lottie_")
|
|
|
|
if err != nil {
|
|
|
|
return nil, "", fmt.Errorf("failed to create temp dir: %w", err)
|
|
|
|
}
|
2023-02-15 19:42:02 +00:00
|
|
|
defer func() {
|
|
|
|
removErr := os.RemoveAll(tempdir)
|
|
|
|
if removErr != nil {
|
|
|
|
br.Log.Warnfln("Failed to delete lottie conversion temp dir: %v", removErr)
|
|
|
|
}
|
|
|
|
}()
|
2023-02-04 14:10:03 +00:00
|
|
|
|
|
|
|
lottieOutput := filepath.Join(tempdir, "out_")
|
|
|
|
if lottieTarget != "pngs" {
|
|
|
|
lottieOutput = filepath.Join(tempdir, "output."+lottieTarget)
|
|
|
|
}
|
|
|
|
cmd := exec.CommandContext(ctx, "lottieconverter", "-", lottieOutput, lottieTarget, fmt.Sprintf("%dx%d", width, height), strconv.Itoa(fps))
|
|
|
|
cmd.Stdin = bytes.NewReader(data)
|
|
|
|
err = cmd.Run()
|
|
|
|
if err != nil {
|
|
|
|
return nil, "", fmt.Errorf("failed to run lottieconverter: %w", err)
|
|
|
|
}
|
|
|
|
var path string
|
|
|
|
if lottieTarget == "pngs" {
|
|
|
|
var videoCodec string
|
|
|
|
outputExtension := "." + target
|
|
|
|
if target == "webm" {
|
|
|
|
videoCodec = "libvpx-vp9"
|
|
|
|
} else if target == "webp" {
|
|
|
|
videoCodec = "libwebp_anim"
|
|
|
|
} else {
|
|
|
|
panic(fmt.Errorf("impossible case: unknown target %q", target))
|
|
|
|
}
|
|
|
|
path, err = ffmpeg.ConvertPath(
|
|
|
|
ctx, lottieOutput+"*.png", outputExtension,
|
|
|
|
[]string{"-framerate", strconv.Itoa(fps), "-pattern_type", "glob"},
|
|
|
|
[]string{"-c:v", videoCodec, "-pix_fmt", "yuva420p", "-f", target},
|
|
|
|
false,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, "", fmt.Errorf("failed to run ffmpeg: %w", err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
path = lottieOutput
|
|
|
|
}
|
|
|
|
data, err = os.ReadFile(path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, "", fmt.Errorf("failed to read converted file: %w", err)
|
|
|
|
}
|
|
|
|
return data, outputMime, nil
|
|
|
|
}
|
|
|
|
|
2023-01-31 11:11:02 +00:00
|
|
|
func (br *DiscordBridge) copyAttachmentToMatrix(intent *appservice.IntentAPI, url string, encrypt bool, meta AttachmentMeta) (returnDBFile *database.File, returnErr error) {
|
2023-05-05 09:50:55 +00:00
|
|
|
isCacheable := br.Config.Bridge.CacheMedia != "never" && (br.Config.Bridge.CacheMedia == "always" || !encrypt)
|
2023-01-31 11:11:02 +00:00
|
|
|
returnDBFile = br.DB.File.Get(url, encrypt)
|
|
|
|
if returnDBFile == nil {
|
|
|
|
transferKey := attachmentKey{url, encrypt}
|
|
|
|
once, _ := br.attachmentTransfers.GetOrSet(transferKey, &util.ReturnableOnce[*database.File]{})
|
|
|
|
returnDBFile, returnErr = once.Do(func() (onceDBFile *database.File, onceErr error) {
|
|
|
|
if isCacheable {
|
|
|
|
onceDBFile = br.DB.File.Get(url, encrypt)
|
|
|
|
if onceDBFile != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-23 12:32:18 +00:00
|
|
|
const attachmentSizeVal = 1
|
2023-06-29 12:18:54 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
onceErr = br.parallelAttachmentSemaphore.Acquire(ctx, attachmentSizeVal)
|
|
|
|
cancel()
|
2023-06-23 12:32:18 +00:00
|
|
|
if onceErr != nil {
|
2023-06-29 12:18:54 +00:00
|
|
|
br.ZLog.Warn().Err(onceErr).Msg("Failed to acquire semaphore")
|
|
|
|
ctx, cancel = context.WithTimeout(context.Background(), 50*time.Second)
|
|
|
|
onceErr = br.parallelAttachmentSemaphore.Acquire(ctx, attachmentSizeVal)
|
|
|
|
cancel()
|
|
|
|
if onceErr != nil {
|
|
|
|
onceErr = fmt.Errorf("reuploading timed out")
|
|
|
|
return
|
|
|
|
}
|
2023-06-23 12:32:18 +00:00
|
|
|
}
|
|
|
|
var semaWg sync.WaitGroup
|
|
|
|
semaWg.Add(1)
|
|
|
|
go func() {
|
|
|
|
semaWg.Wait()
|
|
|
|
br.parallelAttachmentSemaphore.Release(attachmentSizeVal)
|
|
|
|
}()
|
|
|
|
|
2023-01-31 11:11:02 +00:00
|
|
|
var data []byte
|
2023-06-23 12:32:18 +00:00
|
|
|
data, onceErr = downloadDiscordAttachment(url, br.MediaConfig.UploadSize)
|
2023-01-31 11:11:02 +00:00
|
|
|
if onceErr != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-02-04 14:10:03 +00:00
|
|
|
if meta.Converter != nil {
|
|
|
|
data, meta.MimeType, onceErr = meta.Converter(data)
|
|
|
|
if onceErr != nil {
|
|
|
|
onceErr = fmt.Errorf("failed to convert attachment: %w", onceErr)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-23 12:32:18 +00:00
|
|
|
onceDBFile, onceErr = br.uploadMatrixAttachment(intent, data, url, encrypt, meta, &semaWg)
|
2023-01-31 11:11:02 +00:00
|
|
|
if onceErr != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if isCacheable {
|
|
|
|
onceDBFile.Insert(nil)
|
|
|
|
}
|
|
|
|
br.attachmentTransfers.Delete(transferKey)
|
2023-06-23 12:32:18 +00:00
|
|
|
semaWg.Done()
|
2023-01-31 11:11:02 +00:00
|
|
|
return
|
|
|
|
})
|
2023-01-27 23:57:44 +00:00
|
|
|
}
|
2023-01-31 11:11:02 +00:00
|
|
|
return
|
2022-02-11 10:04:07 +00:00
|
|
|
}
|
2023-01-29 23:35:17 +00:00
|
|
|
|
|
|
|
func (portal *Portal) getEmojiMXCByDiscordID(emojiID, name string, animated bool) id.ContentURI {
|
2023-04-25 22:39:17 +00:00
|
|
|
var url, mimeType, ext string
|
2023-01-29 23:35:17 +00:00
|
|
|
if animated {
|
|
|
|
url = discordgo.EndpointEmojiAnimated(emojiID)
|
|
|
|
mimeType = "image/gif"
|
2023-04-25 22:39:17 +00:00
|
|
|
ext = "gif"
|
2023-01-29 23:35:17 +00:00
|
|
|
} else {
|
|
|
|
url = discordgo.EndpointEmoji(emojiID)
|
|
|
|
mimeType = "image/png"
|
2023-04-25 22:39:17 +00:00
|
|
|
ext = "png"
|
|
|
|
}
|
|
|
|
mxc := portal.bridge.Config.Bridge.MediaPatterns.Emoji(emojiID, ext)
|
|
|
|
if !mxc.IsEmpty() {
|
|
|
|
return mxc
|
2023-01-29 23:35:17 +00:00
|
|
|
}
|
2023-01-31 11:11:02 +00:00
|
|
|
dbFile, err := portal.bridge.copyAttachmentToMatrix(portal.MainIntent(), url, false, AttachmentMeta{
|
2023-01-29 23:35:17 +00:00
|
|
|
AttachmentID: emojiID,
|
|
|
|
MimeType: mimeType,
|
|
|
|
EmojiName: name,
|
|
|
|
})
|
|
|
|
if err != nil {
|
2023-04-30 15:49:14 +00:00
|
|
|
portal.log.Warn().Err(err).Str("emoji_id", emojiID).Msg("Failed to copy emoji to Matrix")
|
2023-01-29 23:35:17 +00:00
|
|
|
return id.ContentURI{}
|
|
|
|
}
|
|
|
|
return dbFile.MXC
|
|
|
|
}
|