forked from j62/ctbrec
1
0
Fork 0

Introduced new HttpException for unsuccessful HTTP responses

Instead of throwing an IOException with String message, use the new
HttpException. The exception handling code can then use the status
code to be more specific how to handle the exception.

Also: use try-with-resources for the okhttp response where possible
This commit is contained in:
0xboobface 2018-11-14 14:43:26 +01:00
parent 8e1aabc7b7
commit 5b8d65ab27
20 changed files with 430 additions and 399 deletions

View File

@ -0,0 +1,23 @@
package ctbrec.io;
import java.io.IOException;
public class HttpException extends IOException {
private int code;
private String msg;
public HttpException(int code, String msg) {
super(code + " - " + msg);
this.code = code;
this.msg = msg;
}
public int getResponseCode() {
return code;
}
public String getResponseMessage() {
return msg;
}
}

View File

@ -33,6 +33,7 @@ import ctbrec.Config;
import ctbrec.Model; import ctbrec.Model;
import ctbrec.OS; import ctbrec.OS;
import ctbrec.Recording; import ctbrec.Recording;
import ctbrec.io.HttpException;
import ctbrec.io.StreamRedirectThread; import ctbrec.io.StreamRedirectThread;
import ctbrec.recorder.PlaylistGenerator.InvalidPlaylistException; import ctbrec.recorder.PlaylistGenerator.InvalidPlaylistException;
import ctbrec.recorder.download.Download; import ctbrec.recorder.download.Download;
@ -408,6 +409,9 @@ public class LocalRecorder implements Recorder {
startRecordingProcess(model); startRecordingProcess(model);
} }
} }
} catch (HttpException e) {
LOG.error("Couldn't check if model {} is online. HTTP Response: {} - {}",
model.getName(), e.getResponseCode(), e.getResponseMessage());
} catch (Exception e) { } catch (Exception e) {
LOG.error("Couldn't check if model {} is online", model.getName(), e); LOG.error("Couldn't check if model {} is online", model.getName(), e);
} }

View File

@ -19,6 +19,7 @@ import ctbrec.Hmac;
import ctbrec.Model; import ctbrec.Model;
import ctbrec.Recording; import ctbrec.Recording;
import ctbrec.io.HttpClient; import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import ctbrec.io.InstantJsonAdapter; import ctbrec.io.InstantJsonAdapter;
import ctbrec.io.ModelJsonAdapter; import ctbrec.io.ModelJsonAdapter;
import ctbrec.sites.Site; import ctbrec.sites.Site;
@ -79,21 +80,22 @@ public class RemoteRecorder implements Recorder {
.post(body); .post(body);
addHmacIfNeeded(payload, builder); addHmacIfNeeded(payload, builder);
Request request = builder.build(); Request request = builder.build();
Response response = client.execute(request); try (Response response = client.execute(request)) {
String json = response.body().string(); String json = response.body().string();
if(response.isSuccessful()) { if (response.isSuccessful()) {
ModelListResponse resp = modelListResponseAdapter.fromJson(json); ModelListResponse resp = modelListResponseAdapter.fromJson(json);
if(!resp.status.equals("success")) { if (!resp.status.equals("success")) {
throw new IOException("Server returned error " + resp.status + " " + resp.msg); throw new IOException("Server returned error " + resp.status + " " + resp.msg);
} }
if("start".equals(action)) { if ("start".equals(action)) {
models.add(model); models.add(model);
} else if("stop".equals(action)) { } else if ("stop".equals(action)) {
models.remove(model); models.remove(model);
} }
} else { } else {
throw new IOException("Server returned error. HTTP status: " + response.code()); throw new HttpException(response.code(), response.message());
}
} }
} }
@ -161,7 +163,7 @@ public class RemoteRecorder implements Recorder {
.post(body); .post(body);
addHmacIfNeeded(msg, builder); addHmacIfNeeded(msg, builder);
Request request = builder.build(); Request request = builder.build();
Response response = client.execute(request); try(Response response = client.execute(request)) {
String json = response.body().string(); String json = response.body().string();
if(response.isSuccessful()) { if(response.isSuccessful()) {
ModelListResponse resp = modelListResponseAdapter.fromJson(json); ModelListResponse resp = modelListResponseAdapter.fromJson(json);
@ -181,6 +183,7 @@ public class RemoteRecorder implements Recorder {
} else { } else {
LOG.error("Couldn't synchronize with server. HTTP status: {} - {}", response.code(), json); LOG.error("Couldn't synchronize with server. HTTP status: {} - {}", response.code(), json);
} }
}
} catch (IOException | InvalidKeyException | NoSuchAlgorithmException | IllegalStateException e) { } catch (IOException | InvalidKeyException | NoSuchAlgorithmException | IllegalStateException e) {
LOG.error("Couldn't synchronize with server", e); LOG.error("Couldn't synchronize with server", e);
} }
@ -195,15 +198,15 @@ public class RemoteRecorder implements Recorder {
.post(body); .post(body);
addHmacIfNeeded(msg, builder); addHmacIfNeeded(msg, builder);
Request request = builder.build(); Request request = builder.build();
Response response = client.execute(request); try (Response response = client.execute(request)) {
String json = response.body().string(); String json = response.body().string();
if(response.isSuccessful()) { if (response.isSuccessful()) {
ModelListResponse resp = modelListResponseAdapter.fromJson(json); ModelListResponse resp = modelListResponseAdapter.fromJson(json);
if(resp.status.equals("success")) { if (resp.status.equals("success")) {
onlineModels = resp.models; onlineModels = resp.models;
for (Model model : models) { for (Model model : models) {
for (Site site : sites) { for (Site site : sites) {
if(site.isSiteForModel(model)) { if (site.isSiteForModel(model)) {
model.setSite(site); model.setSite(site);
} }
} }
@ -214,6 +217,7 @@ public class RemoteRecorder implements Recorder {
} else { } else {
LOG.error("Couldn't synchronize with server. HTTP status: {} - {}", response.code(), json); LOG.error("Couldn't synchronize with server. HTTP status: {} - {}", response.code(), json);
} }
}
} catch (IOException | InvalidKeyException | NoSuchAlgorithmException | IllegalStateException e) { } catch (IOException | InvalidKeyException | NoSuchAlgorithmException | IllegalStateException e) {
LOG.error("Couldn't synchronize with server", e); LOG.error("Couldn't synchronize with server", e);
} }
@ -254,7 +258,7 @@ public class RemoteRecorder implements Recorder {
.post(body); .post(body);
addHmacIfNeeded(msg, builder); addHmacIfNeeded(msg, builder);
Request request = builder.build(); Request request = builder.build();
Response response = client.execute(request); try(Response response = client.execute(request)) {
String json = response.body().string(); String json = response.body().string();
if(response.isSuccessful()) { if(response.isSuccessful()) {
RecordingListResponse resp = recordingListResponseAdapter.fromJson(json); RecordingListResponse resp = recordingListResponseAdapter.fromJson(json);
@ -267,7 +271,7 @@ public class RemoteRecorder implements Recorder {
} else { } else {
LOG.error("Couldn't synchronize with server. HTTP status: {} - {}", response.code(), json); LOG.error("Couldn't synchronize with server. HTTP status: {} - {}", response.code(), json);
} }
}
return Collections.emptyList(); return Collections.emptyList();
} }
@ -280,7 +284,7 @@ public class RemoteRecorder implements Recorder {
.post(body); .post(body);
addHmacIfNeeded(msg, builder); addHmacIfNeeded(msg, builder);
Request request = builder.build(); Request request = builder.build();
Response response = client.execute(request); try(Response response = client.execute(request)) {
String json = response.body().string(); String json = response.body().string();
RecordingListResponse resp = recordingListResponseAdapter.fromJson(json); RecordingListResponse resp = recordingListResponseAdapter.fromJson(json);
if(response.isSuccessful()) { if(response.isSuccessful()) {
@ -289,7 +293,7 @@ public class RemoteRecorder implements Recorder {
} }
} else { } else {
throw new IOException("Couldn't delete recording: " + resp.msg); throw new IOException("Couldn't delete recording: " + resp.msg);
//throw new IOException("Couldn't delete recording: " + response.code() + " " + json); }
} }
} }

View File

@ -7,6 +7,7 @@ import org.json.JSONObject;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.Model; import ctbrec.Model;
import ctbrec.io.HttpClient; import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import ctbrec.recorder.Recorder; import ctbrec.recorder.Recorder;
import ctbrec.sites.AbstractSite; import ctbrec.sites.AbstractSite;
import ctbrec.sites.ConfigUI; import ctbrec.sites.ConfigUI;
@ -89,7 +90,7 @@ public class BongaCams extends AbstractSite {
throw new IOException("Request was not successful: " + json.toString(2)); throw new IOException("Request was not successful: " + json.toString(2));
} }
} else { } else {
throw new IOException(response.code() + " " + response.message()); throw new HttpException(response.code(), response.message());
} }
} }
} }

View File

@ -17,6 +17,7 @@ import org.slf4j.LoggerFactory;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.io.HttpClient; import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import javafx.application.Platform; import javafx.application.Platform;
import okhttp3.Cookie; import okhttp3.Cookie;
import okhttp3.FormBody; import okhttp3.FormBody;
@ -144,7 +145,7 @@ public class BongaCamsHttpClient extends HttpClient {
throw new IOException("Request was not successful: " + json.toString(2)); throw new IOException("Request was not successful: " + json.toString(2));
} }
} else { } else {
throw new IOException(response.code() + " " + response.message()); throw new HttpException(response.code(), response.message());
} }
} }
} }
@ -174,7 +175,7 @@ public class BongaCamsHttpClient extends HttpClient {
throw new IOException("Request was not successful: " + content); throw new IOException("Request was not successful: " + content);
} }
} else { } else {
throw new IOException(response.code() + ' ' + response.message()); throw new HttpException(response.code(), response.message());
} }
} }
} }
@ -229,7 +230,7 @@ public class BongaCamsHttpClient extends HttpClient {
// throw new IOException("Login not successful"); // throw new IOException("Login not successful");
// } // }
// } else { // } else {
// throw new IOException(response.code() + " " + response.message()); // throw new HttpException(response.code(), response.message());
// } // }
// } // }
// } // }

View File

@ -16,6 +16,7 @@ import org.slf4j.LoggerFactory;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.Model; import ctbrec.Model;
import ctbrec.io.HttpException;
import ctbrec.ui.HtmlParser; import ctbrec.ui.HtmlParser;
import ctbrec.ui.PaginatedScheduledService; import ctbrec.ui.PaginatedScheduledService;
import javafx.concurrent.Task; import javafx.concurrent.Task;
@ -51,7 +52,7 @@ public class Cam4FollowedUpdateService extends PaginatedScheduledService {
String username = Config.getInstance().getSettings().cam4Username; String username = Config.getInstance().getSettings().cam4Username;
String url = site.getBaseUrl() + '/' + username + "/edit/friends_favorites"; String url = site.getBaseUrl() + '/' + username + "/edit/friends_favorites";
Request req = new Request.Builder().url(url).build(); Request req = new Request.Builder().url(url).build();
Response response = site.getHttpClient().execute(req, true); try(Response response = site.getHttpClient().execute(req, true)) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
String content = response.body().string(); String content = response.body().string();
Elements cells = HtmlParser.getTags(content, "div#favorites div.ff_thumb"); Elements cells = HtmlParser.getTags(content, "div#favorites div.ff_thumb");
@ -75,9 +76,8 @@ public class Cam4FollowedUpdateService extends PaginatedScheduledService {
} }
}).collect(Collectors.toList()); }).collect(Collectors.toList());
} else { } else {
IOException e = new IOException(response.code() + " " + response.message()); throw new HttpException(response.code(), response.message());
response.close(); }
throw e;
} }
} }

View File

@ -24,6 +24,7 @@ import com.iheartradio.m3u8.data.PlaylistData;
import ctbrec.AbstractModel; import ctbrec.AbstractModel;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.io.HttpException;
import ctbrec.recorder.download.StreamSource; import ctbrec.recorder.download.StreamSource;
import ctbrec.sites.Site; import ctbrec.sites.Site;
import ctbrec.ui.CamrecApplication; import ctbrec.ui.CamrecApplication;
@ -62,7 +63,7 @@ public class Cam4Model extends AbstractModel {
String url = site.getBaseUrl() + "/getBroadcasting?usernames=" + getName(); String url = site.getBaseUrl() + "/getBroadcasting?usernames=" + getName();
LOG.trace("Loading model details {}", url); LOG.trace("Loading model details {}", url);
Request req = new Request.Builder().url(url).build(); Request req = new Request.Builder().url(url).build();
Response response = site.getHttpClient().execute(req); try(Response response = site.getHttpClient().execute(req)) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
JSONArray json = new JSONArray(response.body().string()); JSONArray json = new JSONArray(response.body().string());
if(json.length() == 0) { if(json.length() == 0) {
@ -77,9 +78,8 @@ public class Cam4Model extends AbstractModel {
resolution = new int[] {Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])}; resolution = new int[] {Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])};
} }
} else { } else {
IOException io = new IOException(response.code() + " " + response.message()); throw new HttpException(response.code(), response.message());
response.close(); }
throw io;
} }
} }
@ -185,7 +185,7 @@ public class Cam4Model extends AbstractModel {
// we have to use a client without any cam4 cookies here, otherwise // we have to use a client without any cam4 cookies here, otherwise
// this request is redirected to the login page. no idea why // this request is redirected to the login page. no idea why
Response response = CamrecApplication.httpClient.execute(req); try(Response response = CamrecApplication.httpClient.execute(req)) {
String broadCasterId = null; String broadCasterId = null;
if(response.isSuccessful()) { if(response.isSuccessful()) {
String content = response.body().string(); String content = response.body().string();
@ -209,18 +209,18 @@ public class Cam4Model extends AbstractModel {
.post(body) .post(body)
.addHeader("X-Requested-With", "XMLHttpRequest") .addHeader("X-Requested-With", "XMLHttpRequest")
.build(); .build();
response = site.getHttpClient().execute(req, true); Response resp = site.getHttpClient().execute(req, true);
if(response.isSuccessful()) { if(resp.isSuccessful()) {
return Objects.equals(response.body().string(), "Ok"); return Objects.equals(resp.body().string(), "Ok");
} else { } else {
response.close(); resp.close();
return false; return false;
} }
} else { } else {
response.close();
return false; return false;
} }
} }
}
@Override @Override
public void setSite(Site site) { public void setSite(Site site) {

View File

@ -17,6 +17,7 @@ import org.slf4j.LoggerFactory;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.Model; import ctbrec.Model;
import ctbrec.io.HttpException;
import ctbrec.ui.HtmlParser; import ctbrec.ui.HtmlParser;
import ctbrec.ui.PaginatedScheduledService; import ctbrec.ui.PaginatedScheduledService;
import javafx.concurrent.Task; import javafx.concurrent.Task;
@ -58,7 +59,7 @@ public class Cam4UpdateService extends PaginatedScheduledService {
String url = Cam4UpdateService.this.url + "&page=" + page; String url = Cam4UpdateService.this.url + "&page=" + page;
LOG.debug("Fetching page {}", url); LOG.debug("Fetching page {}", url);
Request request = new Request.Builder().url(url).build(); Request request = new Request.Builder().url(url).build();
Response response = site.getHttpClient().execute(request, loginRequired); try (Response response = site.getHttpClient().execute(request, loginRequired)) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
JSONObject json = new JSONObject(response.body().string()); JSONObject json = new JSONObject(response.body().string());
String html = json.getString("html"); String html = json.getString("html");
@ -72,16 +73,14 @@ public class Cam4UpdateService extends PaginatedScheduledService {
Cam4Model model = (Cam4Model) site.createModel(slug); Cam4Model model = (Cam4Model) site.createModel(slug);
String playlistUrl = profileLink.attr("data-hls-preview-url"); String playlistUrl = profileLink.attr("data-hls-preview-url");
model.setPlaylistUrl(playlistUrl); model.setPlaylistUrl(playlistUrl);
model.setPreview("https://snapshots.xcdnpro.com/thumbnails/"+model.getName()+"?s=" + System.currentTimeMillis()); model.setPreview("https://snapshots.xcdnpro.com/thumbnails/" + model.getName() + "?s=" + System.currentTimeMillis());
model.setDescription(parseDesription(boxHtml)); model.setDescription(parseDesription(boxHtml));
models.add(model); models.add(model);
} }
response.close();
return models; return models;
} else { } else {
int code = response.code(); throw new HttpException(response.code(), response.message());
response.close(); }
throw new IOException("HTTP status " + code);
} }
} }
} }

View File

@ -7,6 +7,7 @@ import org.json.JSONObject;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.Model; import ctbrec.Model;
import ctbrec.io.HttpClient; import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import ctbrec.recorder.Recorder; import ctbrec.recorder.Recorder;
import ctbrec.sites.AbstractSite; import ctbrec.sites.AbstractSite;
import ctbrec.sites.ConfigUI; import ctbrec.sites.ConfigUI;
@ -72,7 +73,7 @@ public class Camsoda extends AbstractSite {
String username = Config.getInstance().getSettings().camsodaUsername; String username = Config.getInstance().getSettings().camsodaUsername;
String url = BASE_URI + "/api/v1/user/" + username; String url = BASE_URI + "/api/v1/user/" + username;
Request request = new Request.Builder().url(url).build(); Request request = new Request.Builder().url(url).build();
Response response = getHttpClient().execute(request, true); try(Response response = getHttpClient().execute(request, true)) {
if(response.isSuccessful()) { if(response.isSuccessful()) {
JSONObject json = new JSONObject(response.body().string()); JSONObject json = new JSONObject(response.body().string());
if(json.has("user")) { if(json.has("user")) {
@ -82,7 +83,8 @@ public class Camsoda extends AbstractSite {
} }
} }
} else { } else {
throw new IOException(response.code() + " " + response.message()); throw new HttpException(response.code(), response.message());
}
} }
throw new RuntimeException("Tokens not found in response"); throw new RuntimeException("Tokens not found in response");
} }

View File

@ -11,6 +11,7 @@ import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import ctbrec.Model; import ctbrec.Model;
import ctbrec.io.HttpException;
import ctbrec.ui.PaginatedScheduledService; import ctbrec.ui.PaginatedScheduledService;
import javafx.concurrent.Task; import javafx.concurrent.Task;
import okhttp3.Request; import okhttp3.Request;
@ -32,7 +33,7 @@ public class CamsodaFollowedUpdateService extends PaginatedScheduledService {
List<Model> models = new ArrayList<>(); List<Model> models = new ArrayList<>();
String url = camsoda.getBaseUrl() + "/api/v1/user/current"; String url = camsoda.getBaseUrl() + "/api/v1/user/current";
Request request = new Request.Builder().url(url).build(); Request request = new Request.Builder().url(url).build();
Response response = camsoda.getHttpClient().execute(request, true); try(Response response = camsoda.getHttpClient().execute(request, true)) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
JSONObject json = new JSONObject(response.body().string()); JSONObject json = new JSONObject(response.body().string());
if(json.has("status") && json.getBoolean("status")) { if(json.has("status") && json.getBoolean("status")) {
@ -59,9 +60,8 @@ public class CamsodaFollowedUpdateService extends PaginatedScheduledService {
return Collections.emptyList(); return Collections.emptyList();
} }
} else { } else {
int code = response.code(); throw new HttpException(response.code(), response.message());
response.close(); }
throw new IOException("HTTP status " + code);
} }
} }
}; };

View File

@ -15,6 +15,7 @@ import org.slf4j.LoggerFactory;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.io.HttpClient; import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import ctbrec.sites.cam4.Cam4LoginDialog; import ctbrec.sites.cam4.Cam4LoginDialog;
import ctbrec.ui.HtmlParser; import ctbrec.ui.HtmlParser;
import javafx.application.Platform; import javafx.application.Platform;
@ -55,13 +56,13 @@ public class CamsodaHttpClient extends HttpClient {
.url(url) .url(url)
.post(body) .post(body)
.build(); .build();
Response response = execute(request); try (Response response = execute(request)) {
if(response.isSuccessful()) { if (response.isSuccessful()) {
JSONObject resp = new JSONObject(response.body().string()); JSONObject resp = new JSONObject(response.body().string());
if(resp.has("error")) { if (resp.has("error")) {
String error = resp.getString("error"); String error = resp.getString("error");
if (Objects.equals(error, "Please confirm that you are not a robot.")) { if (Objects.equals(error, "Please confirm that you are not a robot.")) {
//return loginWithDialog(); // return loginWithDialog();
throw new IOException("CamSoda requested to solve a captcha. Please try again in a while (maybe 15 min)."); throw new IOException("CamSoda requested to solve a captcha. Please try again in a while (maybe 15 min).");
} else { } else {
throw new IOException(resp.getString("error")); throw new IOException(resp.getString("error"));
@ -70,7 +71,8 @@ public class CamsodaHttpClient extends HttpClient {
return true; return true;
} }
} else { } else {
throw new IOException(response.code() + " " + response.message()); throw new HttpException(response.code(), response.message());
}
} }
} }
@ -147,14 +149,13 @@ public class CamsodaHttpClient extends HttpClient {
if(csrfToken == null) { if(csrfToken == null) {
String url = Camsoda.BASE_URI; String url = Camsoda.BASE_URI;
Request request = new Request.Builder().url(url).build(); Request request = new Request.Builder().url(url).build();
Response resp = execute(request, true); try(Response response = execute(request, true)) {
if(resp.isSuccessful()) { if(response.isSuccessful()) {
Element meta = HtmlParser.getTag(resp.body().string(), "meta[name=\"_token\"]"); Element meta = HtmlParser.getTag(response.body().string(), "meta[name=\"_token\"]");
csrfToken = meta.attr("content"); csrfToken = meta.attr("content");
} else { } else {
IOException e = new IOException(resp.code() + " " + resp.message()); throw new HttpException(response.code(), response.message());
resp.close(); }
throw e;
} }
} }
return csrfToken; return csrfToken;

View File

@ -26,6 +26,7 @@ import com.iheartradio.m3u8.data.StreamInfo;
import ctbrec.AbstractModel; import ctbrec.AbstractModel;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.io.HttpException;
import ctbrec.recorder.download.StreamSource; import ctbrec.recorder.download.StreamSource;
import ctbrec.sites.Site; import ctbrec.sites.Site;
import okhttp3.FormBody; import okhttp3.FormBody;
@ -189,7 +190,7 @@ public class CamsodaModel extends AbstractModel {
.build(); .build();
try(Response response = site.getHttpClient().execute(request, true)) { try(Response response = site.getHttpClient().execute(request, true)) {
if(!response.isSuccessful()) { if(!response.isSuccessful()) {
throw new IOException("HTTP status " + response.code() + " " + response.message()); throw new HttpException(response.code(), response.message());
} }
} }
} }
@ -209,13 +210,12 @@ public class CamsodaModel extends AbstractModel {
.addHeader("Accept-Language", "en") .addHeader("Accept-Language", "en")
.addHeader("X-CSRF-Token", csrfToken) .addHeader("X-CSRF-Token", csrfToken)
.build(); .build();
Response resp = site.getHttpClient().execute(request, true); try(Response response = site.getHttpClient().execute(request, true)) {
if (resp.isSuccessful()) { if (response.isSuccessful()) {
resp.close();
return true; return true;
} else { } else {
resp.close(); throw new HttpException(response.code(), response.message());
throw new IOException("HTTP status " + resp.code() + " " + resp.message()); }
} }
} }
@ -233,13 +233,12 @@ public class CamsodaModel extends AbstractModel {
.addHeader("Accept-Language", "en") .addHeader("Accept-Language", "en")
.addHeader("X-CSRF-Token", csrfToken) .addHeader("X-CSRF-Token", csrfToken)
.build(); .build();
Response resp = site.getHttpClient().execute(request, true); try (Response response = site.getHttpClient().execute(request, true)) {
if (resp.isSuccessful()) { if (response.isSuccessful()) {
resp.close();
return true; return true;
} else { } else {
resp.close(); throw new HttpException(response.code(), response.message());
throw new IOException("HTTP status " + resp.code() + " " + resp.message()); }
} }
} }

View File

@ -82,7 +82,7 @@ public class CamsodaShowsTab extends Tab implements TabSelectionListener {
protected List<ShowBox> call() throws Exception { protected List<ShowBox> call() throws Exception {
String url = camsoda.getBaseUrl() + "/api/v1/user/model_shows"; String url = camsoda.getBaseUrl() + "/api/v1/user/model_shows";
Request req = new Request.Builder().url(url).build(); Request req = new Request.Builder().url(url).build();
Response response = camsoda.getHttpClient().execute(req); try(Response response = camsoda.getHttpClient().execute(req)) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
JSONObject json = new JSONObject(response.body().string()); JSONObject json = new JSONObject(response.body().string());
if (json.optInt("success") == 1) { if (json.optInt("success") == 1) {
@ -103,10 +103,10 @@ public class CamsodaShowsTab extends Tab implements TabSelectionListener {
showErrorDialog("Oh no!", "Couldn't load upcoming CamSoda shows", "Got an unexpected response from server"); showErrorDialog("Oh no!", "Couldn't load upcoming CamSoda shows", "Got an unexpected response from server");
} }
} else { } else {
response.close();
showErrorDialog("Oh no!", "Couldn't load upcoming CamSoda shows", "Got an unexpected response from server"); showErrorDialog("Oh no!", "Couldn't load upcoming CamSoda shows", "Got an unexpected response from server");
LOG.error("Couldn't load upcoming camsoda shows: {} {}", response.code(), response.message()); LOG.error("Couldn't load upcoming camsoda shows: {} {}", response.code(), response.message());
} }
}
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -13,6 +13,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import ctbrec.Model; import ctbrec.Model;
import ctbrec.io.HttpException;
import ctbrec.ui.PaginatedScheduledService; import ctbrec.ui.PaginatedScheduledService;
import javafx.concurrent.Task; import javafx.concurrent.Task;
import okhttp3.Request; import okhttp3.Request;
@ -45,7 +46,7 @@ public class CamsodaUpdateService extends PaginatedScheduledService {
String url = CamsodaUpdateService.this.url; String url = CamsodaUpdateService.this.url;
LOG.debug("Fetching page {}", url); LOG.debug("Fetching page {}", url);
Request request = new Request.Builder().url(url).build(); Request request = new Request.Builder().url(url).build();
Response response = camsoda.getHttpClient().execute(request, loginRequired); try(Response response = camsoda.getHttpClient().execute(request, loginRequired)) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
JSONObject json = new JSONObject(response.body().string()); JSONObject json = new JSONObject(response.body().string());
if(json.has("status") && json.getBoolean("status")) { if(json.has("status") && json.getBoolean("status")) {
@ -72,11 +73,9 @@ public class CamsodaUpdateService extends PaginatedScheduledService {
} }
models.add(model); models.add(model);
} else { } else {
//LOG.debug("{}", result.toString(2));
String name = result.getString("username"); String name = result.getString("username");
CamsodaModel model = (CamsodaModel) camsoda.createModel(name); CamsodaModel model = (CamsodaModel) camsoda.createModel(name);
if(result.has("server_prefix")) { if(result.has("server_prefix")) {
String serverPrefix = result.getString("server_prefix"); String serverPrefix = result.getString("server_prefix");
String streamName = result.getString("stream_name"); String streamName = result.getString("stream_name");
@ -98,7 +97,6 @@ public class CamsodaUpdateService extends PaginatedScheduledService {
+ streamName + '/' + serverPrefix + '/' + tsize + '/' + unixtime + '/' + name + ".jpg?cb=" + unixtime; + streamName + '/' + serverPrefix + '/' + tsize + '/' + unixtime + '/' + name + ".jpg?cb=" + unixtime;
model.setPreview(preview); model.setPreview(preview);
} }
} }
} }
} }
@ -108,13 +106,11 @@ public class CamsodaUpdateService extends PaginatedScheduledService {
.limit(modelsPerPage) .limit(modelsPerPage)
.collect(Collectors.toList()); .collect(Collectors.toList());
} else { } else {
response.close();
return Collections.emptyList(); return Collections.emptyList();
} }
} else { } else {
int code = response.code(); throw new HttpException(response.code(), response.message());
response.close(); }
throw new IOException("HTTP status " + code);
} }
} }
} }

View File

@ -27,6 +27,7 @@ import com.squareup.moshi.Moshi;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.Model; import ctbrec.Model;
import ctbrec.io.HttpClient; import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import ctbrec.recorder.Recorder; import ctbrec.recorder.Recorder;
import ctbrec.sites.AbstractSite; import ctbrec.sites.AbstractSite;
import ctbrec.sites.ConfigUI; import ctbrec.sites.ConfigUI;
@ -207,7 +208,7 @@ public class Chaturbate extends AbstractSite {
return streamInfoCache.get(modelName); return streamInfoCache.get(modelName);
} }
StreamInfo loadStreamInfo(String modelName) throws IOException, InterruptedException { StreamInfo loadStreamInfo(String modelName) throws HttpException, IOException, InterruptedException {
throttleRequests(); throttleRequests();
RequestBody body = new FormBody.Builder() RequestBody body = new FormBody.Builder()
.add("room_slug", modelName) .add("room_slug", modelName)
@ -231,7 +232,7 @@ public class Chaturbate extends AbstractSite {
} else { } else {
int code = response.code(); int code = response.code();
String message = response.message(); String message = response.message();
throw new IOException("Server responded with " + code + " - " + message + " headers: [" + response.headers() + "]"); throw new HttpException(code, message);
} }
} finally { } finally {
response.close(); response.close();

View File

@ -47,7 +47,7 @@ public class FriendsUpdateService extends PaginatedScheduledService {
.url(url) .url(url)
.header("Referer", myFreeCams.getBaseUrl()) .header("Referer", myFreeCams.getBaseUrl())
.build(); .build();
Response resp = myFreeCams.getHttpClient().execute(req, true); try(Response resp = myFreeCams.getHttpClient().execute(req, true)) {
if(resp.isSuccessful()) { if(resp.isSuccessful()) {
String body = resp.body().string().substring(4); String body = resp.body().string().substring(4);
try { try {
@ -76,7 +76,7 @@ public class FriendsUpdateService extends PaginatedScheduledService {
} }
} else { } else {
LOG.error("Couldn't load friends list {} {}", resp.code(), resp.message()); LOG.error("Couldn't load friends list {} {}", resp.code(), resp.message());
resp.close(); }
} }
boolean filterOnline = mode == Mode.ONLINE; boolean filterOnline = mode == Mode.ONLINE;
return models.stream() return models.stream()

View File

@ -6,6 +6,7 @@ import org.jsoup.select.Elements;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.Model; import ctbrec.Model;
import ctbrec.io.HttpException;
import ctbrec.recorder.Recorder; import ctbrec.recorder.Recorder;
import ctbrec.sites.AbstractSite; import ctbrec.sites.AbstractSite;
import ctbrec.sites.ConfigUI; import ctbrec.sites.ConfigUI;
@ -74,15 +75,15 @@ public class MyFreeCams extends AbstractSite {
@Override @Override
public Integer getTokenBalance() throws IOException { public Integer getTokenBalance() throws IOException {
Request req = new Request.Builder().url(BASE_URI + "/php/account.php?request=status").build(); Request req = new Request.Builder().url(BASE_URI + "/php/account.php?request=status").build();
Response resp = getHttpClient().execute(req, true); try(Response response = getHttpClient().execute(req, true)) {
if(resp.isSuccessful()) { if(response.isSuccessful()) {
String content = resp.body().string(); String content = response.body().string();
Elements tags = HtmlParser.getTags(content, "div.content > p > b"); Elements tags = HtmlParser.getTags(content, "div.content > p > b");
String tokens = tags.get(2).text(); String tokens = tags.get(2).text();
return Integer.parseInt(tokens); return Integer.parseInt(tokens);
} else { } else {
resp.close(); throw new HttpException(response.code(), response.message());
throw new IOException(resp.code() + " " + resp.message()); }
} }
} }

View File

@ -282,11 +282,11 @@ public class MyFreeCamsClient {
String url = base + "?respkey="+respkey+"&opts="+opts+"&serv="+serv+"&type="+type; String url = base + "?respkey="+respkey+"&opts="+opts+"&serv="+serv+"&type="+type;
Request req = new Request.Builder().url(url).build(); Request req = new Request.Builder().url(url).build();
LOG.trace("Requesting EXTDATA {}", url); LOG.trace("Requesting EXTDATA {}", url);
Response resp = mfc.getHttpClient().execute(req); try(Response resp = mfc.getHttpClient().execute(req)) {
if(resp.isSuccessful()) { if(resp.isSuccessful()) {
parseExtDataSessionStates(resp.body().string()); parseExtDataSessionStates(resp.body().string());
} }
}
} catch(Exception e) { } catch(Exception e) {
LOG.warn("Couldn't request EXTDATA", e); LOG.warn("Couldn't request EXTDATA", e);
} }

View File

@ -11,6 +11,7 @@ import org.slf4j.LoggerFactory;
import ctbrec.Config; import ctbrec.Config;
import ctbrec.io.HttpClient; import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import ctbrec.ui.HtmlParser; import ctbrec.ui.HtmlParser;
import okhttp3.Cookie; import okhttp3.Cookie;
import okhttp3.CookieJar; import okhttp3.CookieJar;
@ -75,9 +76,9 @@ public class MyFreeCamsHttpClient extends HttpClient {
private boolean checkLogin() throws IOException { private boolean checkLogin() throws IOException {
Request req = new Request.Builder().url(MyFreeCams.BASE_URI + "/php/account.php?request=status").build(); Request req = new Request.Builder().url(MyFreeCams.BASE_URI + "/php/account.php?request=status").build();
Response resp = execute(req); try(Response response = execute(req)) {
if(resp.isSuccessful()) { if(response.isSuccessful()) {
String content = resp.body().string(); String content = response.body().string();
try { try {
Elements tags = HtmlParser.getTags(content, "div.content > p > b"); Elements tags = HtmlParser.getTags(content, "div.content > p > b");
tags.get(2).text(); tags.get(2).text();
@ -87,8 +88,8 @@ public class MyFreeCamsHttpClient extends HttpClient {
return false; return false;
} }
} else { } else {
resp.close(); throw new HttpException(response.code(), response.message());
throw new IOException(resp.code() + " " + resp.message()); }
} }
} }

View File

@ -27,6 +27,7 @@ import com.squareup.moshi.JsonReader;
import com.squareup.moshi.JsonWriter; import com.squareup.moshi.JsonWriter;
import ctbrec.AbstractModel; import ctbrec.AbstractModel;
import ctbrec.io.HttpException;
import ctbrec.recorder.download.StreamSource; import ctbrec.recorder.download.StreamSource;
import ctbrec.sites.Site; import ctbrec.sites.Site;
import ctbrec.ui.HtmlParser; import ctbrec.ui.HtmlParser;
@ -104,8 +105,7 @@ public class MyFreeCamsModel extends AbstractModel {
} }
LOG.trace("Loading master playlist {}", hlsUrl); LOG.trace("Loading master playlist {}", hlsUrl);
Request req = new Request.Builder().url(hlsUrl).build(); Request req = new Request.Builder().url(hlsUrl).build();
Response response = site.getHttpClient().execute(req); try(Response response = site.getHttpClient().execute(req)) {
try {
if(response.isSuccessful()) { if(response.isSuccessful()) {
InputStream inputStream = response.body().byteStream(); InputStream inputStream = response.body().byteStream();
PlaylistParser parser = new PlaylistParser(inputStream, Format.EXT_M3U, Encoding.UTF_8); PlaylistParser parser = new PlaylistParser(inputStream, Format.EXT_M3U, Encoding.UTF_8);
@ -113,10 +113,8 @@ public class MyFreeCamsModel extends AbstractModel {
MasterPlaylist master = playlist.getMasterPlaylist(); MasterPlaylist master = playlist.getMasterPlaylist();
return master; return master;
} else { } else {
throw new IOException(response.code() + " " + response.message()); throw new HttpException(response.code(), response.message());
} }
} finally {
response.close();
} }
} }
@ -130,7 +128,7 @@ public class MyFreeCamsModel extends AbstractModel {
String tipUrl = MyFreeCams.BASE_URI + "/php/tip.php"; String tipUrl = MyFreeCams.BASE_URI + "/php/tip.php";
String initUrl = tipUrl + "?request=tip&username="+getName()+"&broadcaster_id="+getUid(); String initUrl = tipUrl + "?request=tip&username="+getName()+"&broadcaster_id="+getUid();
Request req = new Request.Builder().url(initUrl).build(); Request req = new Request.Builder().url(initUrl).build();
Response resp = site.getHttpClient().execute(req); try(Response resp = site.getHttpClient().execute(req)) {
if(resp.isSuccessful()) { if(resp.isSuccessful()) {
String page = resp.body().string(); String page = resp.body().string();
Element hiddenInput = HtmlParser.getTag(page, "input[name=token]"); Element hiddenInput = HtmlParser.getTag(page, "input[name=token]");
@ -157,13 +155,13 @@ public class MyFreeCamsModel extends AbstractModel {
.build(); .build();
try(Response response = site.getHttpClient().execute(req, true)) { try(Response response = site.getHttpClient().execute(req, true)) {
if(!response.isSuccessful()) { if(!response.isSuccessful()) {
throw new IOException(response.code() + " " + response.message()); throw new HttpException(response.code(), response.message());
} }
} }
} }
} else { } else {
resp.close(); throw new HttpException(resp.code(), resp.message());
throw new IOException(resp.code() + " " + resp.message()); }
} }
} }