ctbrec/client/src/main/java/ctbrec/ui/news/NewsTab.java

88 lines
3.5 KiB
Java

package ctbrec.ui.news;
import java.io.IOException;
import org.json.JSONObject;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import ctbrec.io.HttpException;
import ctbrec.ui.CamrecApplication;
import ctbrec.ui.TabSelectionListener;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tab;
import javafx.scene.layout.VBox;
import okhttp3.Request;
import okhttp3.Response;
public class NewsTab extends Tab implements TabSelectionListener {
private static final String ACCESS_TOKEN = "a2804d73a89951a22e0f8483a6fcec8943afd88b7ba17c459c095aa9e6f94fd0";
private static final String URL = "https://mastodon.cloud/api/v1/timelines/home";
private VBox layout = new VBox();
public NewsTab() {
setText("News");
layout.setMaxWidth(800);
layout.setAlignment(Pos.CENTER);
setContent(new ScrollPane(layout));
}
@Override
public void selected() {
new Thread(() -> {
try {
Request request = new Request.Builder()
.url(URL)
.header("Authorization", "Bearer " + ACCESS_TOKEN)
.header("User-Agent", "ctbrec " + CamrecApplication.getVersion().toString())
.build();
try(Response response = CamrecApplication.httpClient.execute(request)) {
if(response.isSuccessful()) {
String body = response.body().string();
if(body.startsWith("[")) {
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<Status[]> statusListAdapter = moshi.adapter(Status[].class);
Status[] statusArray = statusListAdapter.fromJson(body);
Platform.runLater(() -> {
layout.getChildren().clear();
for (Status status : statusArray) {
if(status.getInReplyToId() == null) {
StatusPane stp = new StatusPane(status);
layout.getChildren().add(stp);
VBox.setMargin(stp, new Insets(10));
}
}
});
} else if(body.startsWith("{")) {
JSONObject json = new JSONObject(response.body().string());
if(json.has("error")) {
throw new IOException("Request not successful: " + json.getString("error"));
} else {
throw new IOException("Unexpected response: " + body);
}
} else {
throw new IOException("Unexpected response: " + body);
}
} else {
throw new HttpException(response.code(), response.message());
}
}
} catch (IOException e) {
Dialogs.showError("News", "Couldn't load news from mastodon", e);
}
}).start();
}
@Override
public void deselected() {
// TODO Auto-generated method stub
}
}