Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[plex] Use https for local connections #15306

Merged
merged 2 commits into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,17 @@
import java.net.URISyntaxException;
import java.util.Base64;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
Expand Down Expand Up @@ -129,11 +133,12 @@ private void setupXstream() {
*/
public @Nullable MediaContainer getSessionData() {
try {
String url = "http://" + host + ":" + String.valueOf(port) + "/status/sessions" + "?X-Plex-Token=" + token;
String url = "https://" + host + ":" + String.valueOf(port) + "/status/sessions" + "?X-Plex-Token=" + token;
logger.debug("Getting session data '{}'", url);
MediaContainer mediaContainer = doHttpRequest("GET", url, getClientHeaders(), MediaContainer.class);
MediaContainer mediaContainer = getFromXml(doHttpRequest("GET", url, getClientHeaders(), false),
MediaContainer.class);
return mediaContainer;
} catch (IOException e) {
} catch (IOException | InterruptedException | TimeoutException | ExecutionException e) {
logger.debug("An exception occurred while polling the PLEX Server: '{}'", e.getMessage());
return null;
}
Expand Down Expand Up @@ -161,8 +166,8 @@ public void getToken() {
headers.put("Authorization", "Basic " + authString);

try {
user = doHttpRequest("POST", SIGNIN_URL, headers, User.class);
} catch (IOException e) {
user = getFromXml(doHttpRequest("POST", SIGNIN_URL, headers, true), User.class);
} catch (IOException | InterruptedException | TimeoutException | ExecutionException e) {
logger.debug("An exception occurred while fetching PLEX user token :'{}'", e.getMessage(), e);
throw new ConfigurationException("Error occurred while fetching PLEX user token, please check config");
}
Expand All @@ -180,7 +185,8 @@ public void getToken() {
*/
public boolean getApi() {
try {
MediaContainer api = doHttpRequest("GET", API_URL, getClientHeaders(), MediaContainer.class);
MediaContainer api = getFromXml(doHttpRequest("GET", API_URL, getClientHeaders(), true),
MediaContainer.class);
logger.debug("MediaContainer {}", api.getSize());
if (api.getDevice() != null) {
for (Device tmpDevice : api.getDevice()) {
Expand All @@ -198,28 +204,60 @@ public boolean getApi() {
}
}
return false;
} catch (IOException e) {
} catch (IOException | InterruptedException | TimeoutException | ExecutionException e) {
logger.debug("An exception occurred while fetching API :'{}'", e.getMessage(), e);
}
return false;
}

/**
* Make an HTTP request and return the class object that was used when calling.
* Make an HTTP request and return the response as a string.
*
* @param <T> Class being used(dto)
* @param method GET/POST
* @param url What URL to call
* @param headers Additional headers that will be used
* @param type class type for the XML parsing
* @return Returns a class object from the data returned by the call
* @param verify Flag to indicate if ssl certificate checking should be done
* @return Returns a string of the http response
* @throws IOException
* @throws ExecutionException
* @throws TimeoutException
* @throws InterruptedException
*/
private <T> T doHttpRequest(String method, String url, Properties headers, Class<T> type) throws IOException {
String response = HttpUtil.executeUrl(method, url, headers, null, null, REQUEST_TIMEOUT_MS);
private String doHttpRequest(String method, String url, Properties headers, boolean verify)
throws IOException, InterruptedException, TimeoutException, ExecutionException {
final String response;
if (verify) {
// Requests sent to the PLEX servers should use certificate checking
response = HttpUtil.executeUrl(method, url, headers, null, null, REQUEST_TIMEOUT_MS);
jlaur marked this conversation as resolved.
Show resolved Hide resolved
} else {
// Requests sent to the local server need to bypass certificate checking via the custom httpClient
final Request request = httpClient.newRequest(url).method(HttpUtil.createHttpMethod(method));
if (headers != null) {
for (String httpHeaderKey : headers.stringPropertyNames()) {
if (httpHeaderKey.equalsIgnoreCase(HttpHeader.USER_AGENT.toString())) {
request.agent(headers.getProperty(httpHeaderKey));
} else {
request.header(httpHeaderKey, headers.getProperty(httpHeaderKey));
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems a little overcomplicated. Can you remove the User-Agent header from getClientHeaders() and instead apply it directly in this method (here and when verify is true)?

Since this is a local connection, is it even needed/used for anything?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not a plex user and thus can't test the code directly so it is difficult to assess which headers are actually needed. I took the approach of trying to maintain what was already implemented. I actually borrowed this header adding code from the core HttpUtil.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The core HttpUtil code is partly like that because of a bugfix because of the way Jetty works - see openhab/openhab-core#3411. The other part of the story is that the method was bound by contract to have agent delivered inside Properties. We are not bound by this contract, but can freely write the code.

I think it would be better to avoid for each call to put 9-10 headers into a HashMap, with User-Agent being one of them and then iterate through the map in order to apply it for building a Request. while taking special care of User-Agent by string comparison. At least the User-Agent handling part seems like a work-around as it could have been avoided in the first place.

But I can appreciate that you don't want to mess too much with this code since you are not using the binding yourself, so let's leave it as is for now.

final ContentResponse res = request.send();
response = res.getContentAsString();
}
logger.debug("HTTP response: {}", response);
return response;
}

/**
* Return the class object that was represented by the xml input string.
*
* @param response The xml response to parse
* @param type Class type for the XML parsing
* @return Returns a class object from the input sring
*/
private <T> T getFromXml(String response, Class<T> type) {
@SuppressWarnings("unchecked")
T obj = (T) xStream.fromXML(response);
logger.debug("HTTP response {}", response);
return obj;
}

Expand All @@ -230,7 +268,7 @@ private <T> T doHttpRequest(String method, String url, Properties headers, Class
*/
private Properties getClientHeaders() {
Properties headers = new Properties();
headers.put(HttpHeader.USER_AGENT, "openHAB / PLEX binding "); // + VERSION);
headers.put(HttpHeader.USER_AGENT, "openHAB " + org.openhab.core.OpenHAB.getVersion() + "/ PLEX binding");
jlaur marked this conversation as resolved.
Show resolved Hide resolved
headers.put("X-Plex-Client-Identifier", CLIENT_ID);
headers.put("X-Plex-Product", "openHAB");
headers.put("X-Plex-Version", "");
Expand Down Expand Up @@ -377,11 +415,11 @@ public void controlPlayer(Command command, String playerID) {

if (commandPath != null) {
try {
String url = "http://" + host + ":" + String.valueOf(port) + commandPath;
String url = "https://" + host + ":" + String.valueOf(port) + commandPath;
Properties headers = getClientHeaders();
headers.put("X-Plex-Target-Client-Identifier", playerID);
HttpUtil.executeUrl("GET", url, headers, null, null, REQUEST_TIMEOUT_MS);
} catch (IOException e) {
doHttpRequest("GET", url, headers, false);
} catch (IOException | InterruptedException | TimeoutException | ExecutionException e) {
logger.debug("An exception occurred trying to send command '{}' to the player: {}", commandPath,
e.getMessage());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public void initialize() {
try {
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setEndpointIdentificationAlgorithm(null);
sslContextFactory.setTrustAll(true);
HttpClient localHttpClient = httpClient = httpClientFactory.createHttpClient(httpClientName,
sslContextFactory);
localHttpClient.start();
Expand Down