diff --git a/main.js b/main.js index e7e8e24..aa6cbe2 100644 --- a/main.js +++ b/main.js @@ -14,6 +14,8 @@ import https from 'https'; import { fileURLToPath } from 'url'; import { dirname } from 'path'; +const request = require('request'); + // Load settings from config.json const __filename = fileURLToPath(import.meta.url); @@ -121,6 +123,31 @@ function createOrJoinSMSRoom(tel, callback) { }); } +function getAndUploadFile(url, callback) { + logger.info("Downloading MMS media " + url); + // download + request({url, encoding: null}, (err, resp, buffer) => { + // upload + logger.info("Uploading MMS media to Matrix " + url); + client.uploadContent(buffer, { + onlyContentUri: true + }).then((res) => { + if (typeof callback == "function") { + callback(res); + logger.info("Media URI: " + res); + } + }).catch((err) => { + if (typeof callback == "function") { + callback(false); + } + if (err.data.error == "Unknown room") { + return; + } + logger.error(err); + }); + }); +} + /** * Send a message to a Matrix room. * @param {string} roomid the room to post the message in. @@ -135,30 +162,11 @@ function sendMatrix(roomid, body, media, callback) { } if (typeof media == "string") { - var content = { - body: media, - msgtype: "m.file", - url: media - } - client.sendEvent(roomid, "m.room.message", content, "").then((res) => { - if (typeof callback == "function") { - callback(true); - } - }).catch((err) => { - if (typeof callback == "function") { - callback(false); - } - if (err.data.error == "Unknown room") { - return; - } - logger.error(err); - }); - } else if (Array.isArray(media)) { - for (var i = 0; i < media.length; i++) { + getAndUploadFile(media, function (uri) { var content = { - body: media[i], + body: body, msgtype: "m.file", - url: media[i] + url: uri } client.sendEvent(roomid, "m.room.message", content, "").then((res) => { if (typeof callback == "function") { @@ -173,6 +181,29 @@ function sendMatrix(roomid, body, media, callback) { } logger.error(err); }); + }); + } else if (Array.isArray(media)) { + for (var i = 0; i < media.length; i++) { + getAndUploadFile(media[i], function (uri) { + var content = { + body: body, + msgtype: "m.file", + url: uri + } + client.sendEvent(roomid, "m.room.message", content, "").then((res) => { + if (typeof callback == "function") { + callback(true); + } + }).catch((err) => { + if (typeof callback == "function") { + callback(false); + } + if (err.data.error == "Unknown room") { + return; + } + logger.error(err); + }); + }); } }