Clean up code and remove dependency on matrix-widget-api. Use giphy.mau.dev for MSC3860 redirects

This commit is contained in:
Nischay
2024-05-12 21:53:39 +05:30
parent 398fc952b6
commit ca99c5f00d
17 changed files with 76 additions and 215 deletions

View File

@@ -32,6 +32,7 @@ if (params.has('config')) {
// This is updated from packs/index.json
let HOMESERVER_URL = "https://matrix-client.matrix.org"
let GIPHY_API_KEY = ""
let GIPHY_HOMESERVER = "mxc://giphy.mau.dev/"
const makeThumbnailURL = mxc => `${HOMESERVER_URL}/_matrix/media/r0/thumbnail/${mxc.substr(6)}?height=128&width=128&method=scale`
@@ -67,8 +68,8 @@ class GiphySearchTab extends Component {
async searchGifs() {
this.setState({ loading: true });
try {
// const apiKey = "Gc7131jiJuvI7IdN0HZ1D7nh0ow5BU6g";
const apiKey = GIPHY_API_KEY;
const gif_homeserver = GIPHY_HOMESERVER;
const url = `https://api.giphy.com/v1/gifs/search?q=${this.state.searchTerm}&api_key=${apiKey}`;
this.setState({ loading: true });
const response = await fetch(url);
@@ -89,10 +90,9 @@ class GiphySearchTab extends Component {
"size": jsonElement.images.fixed_width_still.size,
"w": jsonElement.images.fixed_width_still.width
},
"thumbnail_url": jsonElement.images.fixed_width_still.url
},
"msgtype": "m.image",
"url": jsonElement.images.original.url
"url": gif_homeserver+jsonElement.id+".gif"
};
this.setState((prevState) => ({
GIFById: {...prevState.GIFById, [id]: updatedItem}}));
@@ -265,6 +265,7 @@ class App extends Component {
const indexData = await indexRes.json()
HOMESERVER_URL = indexData.homeserver_url || HOMESERVER_URL
GIPHY_API_KEY = indexData.giphy_api_key || ""
GIPHY_HOMESERVER = indexData.giphy_homeserver || GIPHY_HOMESERVER
// TODO only load pack metadata when scrolled into view?
for (const packFile of indexData.packs) {
let packRes
@@ -385,6 +386,22 @@ class App extends Component {
}
return html`<main class="has-content ${theme}">
<style>
a.tab {
padding: 5% 5%;
width: 40%;
text-align: center;
border: none;
background-color: #f0f0f0;
cursor: pointer;
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
text-decoration: none;
color: initial;
}
</style>
<div class="tab-container" style="display: flex;">
<a href="#stickers" class="tab" onClick=${() => this.setState({ activeTab: "stickers" })}>Stickers</a>
<a href="#gifs" class="tab" onClick=${() => this.setState({ activeTab: "gifs" })}>GIFs</a>

View File

@@ -13,178 +13,68 @@
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
let widgetId = null
const urlParams = new URLSearchParams(window.location.search);
const widgetId = urlParams.get('widgetId'); // if you know the widget ID, supply it.
console.log("Widget ID:"+widgetId);
const api = new mxwidgets.WidgetApi(widgetId, '*');
window.onmessage = event => {
if (!window.parent || !event.data) {
return
}
const request = event.data
if (!request.requestId || !request.widgetId || !request.action || request.api !== "toWidget") {
return
}
// Before doing anything else, request capabilities:
api.requestCapabilities(mxwidgets.StickerpickerCapabilities);
api.requestCapability(mxwidgets.MatrixCapabilities.MSC4039UploadFile);
if (widgetId) {
if (widgetId !== request.widgetId) {
return
}
} else {
widgetId = request.widgetId
}
api.on("ready", () => {console.log("ready event received")});
let response
// Start the messaging
api.start();
if (request.action === "visibility") {
response = {}
} else if (request.action === "capabilities") {
response = { capabilities: ["m.sticker"] }
} else {
response = { error: { message: "Action not supported" } }
}
// If waitForIframeLoad is false, tell the client that we're good to go
//api.sendContentLoaded();
export function sendSticker(content){
const data = {
content: {...content},
name: content.body,
};
// do the same thing that tulir does
delete data.content.id;
// send data
api.sendSticker(data);
window.parent.postMessage({ ...request, response }, event.origin)
}
/*
*export function sendGIF(content){
* // just print out content, should be URL
* console.log("Content:"+content.url);
* return new Promise((resolve, reject) => {
* const xhr = new XMLHttpRequest();
* xhr.open('GET', content.url, true);
* xhr.onreadystatechange = function() {
* if (xhr.readyState === 4) {
* if (xhr.status === 200) {
* const responseData = xhr.responseText;
* // Call uploadFile with response data
* api.uploadFile(responseData)
* .then(result => {
* console.log("Here's the result:"+result.content_uri);
* // mess around with the content object, then send it as sticker
* content.url = result.content_uri;
* sendSticker(content);
* resolve(result);
* })
* .catch(error => {
* reject(error);
* });
* } else {
* reject(new Error('Failed to fetch data')); // Reject the outer promise if fetching data fails
* }
* }
* };
* xhr.send();
* });
*}
*/
export function sendSticker(content) {
const data = {
content: { ...content },
// `name` is for Element Web (and also the spec)
// Element Android uses content -> body as the name
name: content.body,
}
// Custom field that stores the ID even for non-telegram stickers
delete data.content.id
export async function sendGIF(content){
// just print content, since it's a custom type with URL
console.log("Content:"+content.url);
// use fetch because I'm on IE
const lol = await fetch(content.url);
const uri_file = await lol.blob();
// call uploadFile with this
var result = await api.uploadFile(uri_file)
console.log("Got URI:"+result.content_uri);
content.url = result.content_uri;
// get thumbnail
//const thumb_uri = await fetch(content.info.thumbnail_url)
//const thumb_file = await thumb_uri.blob();
//result = await api.uploadFile(thumb_file)
//console.log("Thumb URI:"+result.content_uri);
//content.info.thumbnail_url = result.content_uri;
// actually, just delete the thumbnail
delete content.info.thumbnail_url;
// finally, send it as sticker
sendSticker(content);
// This is for Element iOS
const widgetData = {
...data,
description: content.body,
file: `${content.id}.png`,
}
// Element iOS explodes if there are extra fields present
delete widgetData.content["net.maunium.telegram.sticker"]
window.parent.postMessage({
api: "fromWidget",
action: "m.sticker",
requestId: `sticker-${Date.now()}`,
widgetId,
data,
widgetData,
}, "*")
}
/*
*let widgetId = null
*
*window.onmessage = event => {
* if (!window.parent || !event.data) {
* return
* }
*
* const request = event.data
* if (!request.requestId || !request.widgetId || !request.action || request.api !== "toWidget") {
* return
* }
*
* if (widgetId) {
* if (widgetId !== request.widgetId) {
* return
* }
* } else {
* widgetId = request.widgetId
* }
*
* let response
*
* if (request.action === "visibility") {
* response = {}
* } else if (request.action === "capabilities") {
* response = { capabilities: ["m.sticker", "org.matrix.msc4039.upload_file"] }
* } else {
* response = { error: { message: "Action not supported" } }
* }
*
* window.parent.postMessage({ ...request, response }, event.origin)
*}
*
*export function sendSticker(content) {
* const data = {
* content: { ...content },
* // `name` is for Element Web (and also the spec)
* // Element Android uses content -> body as the name
* name: content.body,
* }
* // Custom field that stores the ID even for non-telegram stickers
* delete data.content.id
*
* // This is for Element iOS
* const widgetData = {
* ...data,
* description: content.body,
* file: `${content.id}.png`,
* }
* // Element iOS explodes if there are extra fields present
* delete widgetData.content["net.maunium.telegram.sticker"]
*
* window.parent.postMessage({
* api: "fromWidget",
* action: "m.sticker",
* requestId: `sticker-${Date.now()}`,
* widgetId,
* data,
* widgetData,
* }, "*")
*}
*
*export function sendGIF(content) {
* const data = {
* content: { ...content },
* name: content.body,
* msgtype: "m.image"
* }
*
* delete data.content.id
* // This is for Element iOS
* const widgetData = {
* ...data,
* description: content.body,
* file: `${content.id}.png`,
* }
*
* window.parent.postMessage({
* api: "fromWidget",
* action: "m.room.message",
* requestId: `gif-${Date.now()}`,
* widgetId,
* data,
* widgetData,
* }, "*")
*}
*/
export function sendGIF(content) {
return sendSticker(content)
}