kamax-matrix / matrix-java-sdk

Matrix Java SDK
GNU Affero General Public License v3.0
21 stars 14 forks source link

Get image info from MatrixJsonRoomMessageEvent #44

Open MrCustomizer opened 6 years ago

MrCustomizer commented 6 years ago

Currently it's not possible to query the contents of an event with an image via the API. Image events have next to the body an info JSON-object which contains the necessary information like mimetype information, the mxc-URL of the image etc. It would be nice to be able to query this stuff via the API instead of having to parse the JSON-info object itself.

MrCustomizer commented 6 years ago

The msgtype is m.image in this case.

MTRNord commented 5 years ago

For anyone looking at this if needed here is a code snippet used in SimpleMatrix:

package blog.nordgedanken.simplematrix.data.matrix.additionaltypes.messages;

import com.google.gson.JsonObject;

import io.kamax.matrix.json.GsonUtil;
import io.kamax.matrix.json.event.MatrixJsonRoomMessageEvent;
import java8.util.Optional;

public class MatrixJsonRoomImageMessageEvent extends MatrixJsonRoomMessageEvent {
    public MatrixJsonRoomImageMessageEvent(JsonObject obj) {
        super(obj);
        this.content = obj;
    }

    public Optional<String> getURL() {
        return GsonUtil.findString(this.content, "url");
    }

    public Optional<JsonObject> getInfo() {
        return GsonUtil.findObj(this.content, "info");
    }

    public Optional<JsonObject> getThumbnailInfo() {
        Optional<JsonObject> info = this.getInfo();
        if (info.isPresent()) {
            return GsonUtil.findObj(info.get(), "thumbnail_info");
        }
        return Optional.empty();
    }

    public Optional<Integer> getWidth() {
        Optional<JsonObject> info = this.getInfo();
        if (info.isPresent()) {
            Optional<JsonObject> thumbnail_info = this.getThumbnailInfo();
            if (thumbnail_info.isPresent()) {
                Optional<Long> width = GsonUtil.findLong(info.get(), "w");
                if (width.isPresent()) {
                    int width_int = width.get().intValue();
                    return Optional.ofNullable(width_int);
                }
            }
        }
        return Optional.empty();
    }

    public Optional<Integer> getHeight() {
        Optional<JsonObject> info = this.getInfo();
        if (info.isPresent()) {
            Optional<JsonObject> thumbnail_info = this.getThumbnailInfo();
            if (thumbnail_info.isPresent()) {
                Optional<Long> width = GsonUtil.findLong(info.get(), "h");
                if (width.isPresent()) {
                    int width_int = width.get().intValue();
                    return Optional.ofNullable(width_int);
                }
            }
        }
        return Optional.empty();
    }
}