RemoteComponent.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. //
  2. // Created by Tobias Hieta on 24/03/15.
  3. //
  4. #include "RemoteComponent.h"
  5. #include <QXmlStreamWriter>
  6. #include <QUrlQuery>
  7. #include "QsLog.h"
  8. #include "settings/SettingsComponent.h"
  9. #include "utils/Utils.h"
  10. #include "Version.h"
  11. static QMap<QString, QString> resourceKeyMap = {
  12. { "Name", "title" },
  13. { "Resource-Identifier", "machineIdentifier" },
  14. { "Product", "product" },
  15. { "Version", "version" },
  16. { "Protocol-Version", "protocolVersion" },
  17. { "Protocol-Capabilities", "protocolCapabilities" },
  18. { "Device-Class", "deviceClass" }
  19. };
  20. static QMap<QString, QString> headerKeyMap = {
  21. { "Name", "X-Plex-Device-Name" },
  22. { "Resource-Identifier", "X-Plex-Client-Identifier" },
  23. { "Product", "X-Plex-Product" },
  24. { "Version", "X-Plex-Version" }
  25. };
  26. /////////////////////////////////////////////////////////////////////////////////////////
  27. RemoteComponent::RemoteComponent(QObject* parent) : ComponentBase(parent), m_commandId(0)
  28. {
  29. m_gdmManager = new GDMManager(this);
  30. m_networkAccessManager = new QNetworkAccessManager(this);
  31. }
  32. /////////////////////////////////////////////////////////////////////////////////////////
  33. bool RemoteComponent::componentInitialize()
  34. {
  35. m_server = new HttpServer(this);
  36. if (!m_server->start())
  37. return false;
  38. m_gdmManager->startAnnouncing();
  39. // check for timed out subscribers
  40. m_subscriberTimer.setInterval(5000);
  41. connect(&m_subscriberTimer, &QTimer::timeout, this, &RemoteComponent::checkSubscribers);
  42. m_subscriberTimer.start();
  43. // connect the network access stuff
  44. connect(m_networkAccessManager, &QNetworkAccessManager::finished, this, &RemoteComponent::timelineFinished);
  45. return true;
  46. }
  47. /////////////////////////////////////////////////////////////////////////////////////////
  48. QVariantMap RemoteComponent::HeaderInformation()
  49. {
  50. QVariantMap gdmInfo = GDMInformation();
  51. QVariantMap headerInfo;
  52. foreach (const QString& key, gdmInfo.keys())
  53. {
  54. if (headerKeyMap.contains(key))
  55. headerInfo[headerKeyMap[key]] = gdmInfo[key];
  56. }
  57. headerInfo["X-Plex-Platform"] = QSysInfo::productType();
  58. headerInfo["X-Plex-Platform-Version"] = QSysInfo::productVersion();
  59. return headerInfo;
  60. }
  61. /////////////////////////////////////////////////////////////////////////////////////////
  62. QVariantMap RemoteComponent::ResourceInformation()
  63. {
  64. QVariantMap gdmInfo = GDMInformation();
  65. QVariantMap resourceInfo;
  66. foreach (const QString& key, gdmInfo.keys())
  67. {
  68. if (resourceKeyMap.contains(key))
  69. resourceInfo[resourceKeyMap[key]] = gdmInfo[key];
  70. }
  71. resourceInfo["platform"] = QSysInfo::productType();
  72. resourceInfo["platformVersion"] = QSysInfo::productVersion();
  73. return resourceInfo;
  74. };
  75. /////////////////////////////////////////////////////////////////////////////////////////
  76. QVariantMap RemoteComponent::GDMInformation()
  77. {
  78. QVariantMap headers = {
  79. {"Name", Utils::ComputerName()},
  80. {"Port", SettingsComponent::Get().value(SETTINGS_SECTION_MAIN, "webserverport")},
  81. {"Version", Version::GetVersionString()},
  82. {"Product", "Plex Media Player"},
  83. {"Protocol", "plex"},
  84. {"Protocol-Version", "1"},
  85. {"Protocol-Capabilities", "navigation,playback,timeline,mirror,playqueues"},
  86. {"Device-Class", "pc"},
  87. {"Resource-Identifier", SettingsComponent::Get().value(SETTINGS_SECTION_WEBCLIENT, "clientID")}
  88. };
  89. return headers;
  90. }
  91. /////////////////////////////////////////////////////////////////////////////////////////
  92. void RemoteComponent::handleResource(QHttpRequest* request, QHttpResponse* response)
  93. {
  94. if (request->method() == QHttpRequest::HTTP_GET)
  95. {
  96. QVariantMap headers = ResourceInformation();
  97. QByteArray outputData;
  98. QXmlStreamWriter output(&outputData);
  99. output.setAutoFormatting(true);
  100. output.writeStartDocument();
  101. output.writeStartElement("MediaContainer");
  102. output.writeStartElement("Player");
  103. foreach (const QString& key, headers.keys())
  104. output.writeAttribute(key, headers[key].toString());
  105. output.writeEndElement();
  106. output.writeEndDocument();
  107. response->writeHead(QHttpResponse::STATUS_OK);
  108. response->write(outputData);
  109. response->end();
  110. }
  111. else
  112. {
  113. response->writeHead(QHttpResponse::STATUS_METHOD_NOT_ALLOWED);
  114. response->end();
  115. }
  116. }
  117. /////////////////////////////////////////////////////////////////////////////////////////
  118. QVariantMap RemoteComponent::QueryToMap(const QUrl& url)
  119. {
  120. QUrlQuery query(url);
  121. QVariantMap queryMap;
  122. QPair<QString, QString> stringPair;
  123. foreach (stringPair, query.queryItems())
  124. {
  125. QString key = stringPair.first;
  126. QString value = stringPair.second;
  127. QVariantList l;
  128. if (queryMap.contains(key))
  129. {
  130. l = queryMap[key].toList();
  131. l.append(value);
  132. }
  133. else
  134. {
  135. l.append(value);
  136. }
  137. queryMap[key] = l;
  138. }
  139. return queryMap;
  140. }
  141. /////////////////////////////////////////////////////////////////////////////////////////
  142. QVariantMap RemoteComponent::HeaderToMap(const HeaderHash& hash)
  143. {
  144. QVariantMap variantMap;
  145. foreach (const QString& key, hash.keys())
  146. variantMap[key] = hash[key];
  147. return variantMap;
  148. }
  149. /////////////////////////////////////////////////////////////////////////////////////////
  150. void RemoteComponent::handleCommand(QHttpRequest* request, QHttpResponse* response)
  151. {
  152. QVariantMap queryMap = QueryToMap(request->url());
  153. QVariantMap headerMap = HeaderToMap(request->headers());
  154. QString identifier = headerMap["x-plex-client-identifier"].toString();
  155. response->setHeader("Access-Control-Allow-Origin", "*");
  156. response->setHeader("X-Plex-Client-Identifier", SettingsComponent::Get().value(SETTINGS_SECTION_WEBCLIENT, "clientID").toString());
  157. // handle CORS requests here
  158. if ((request->method() == QHttpRequest::HTTP_OPTIONS) && headerMap.contains("access-control-request-method"))
  159. {
  160. response->setHeader("Content-Type", "text/plain");
  161. response->setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD");
  162. response->setHeader("Access-Control-Max-Age", "1209600");
  163. response->setHeader("Connection", "close");
  164. if (headerMap.contains("access-control-request-headers"))
  165. {
  166. response->setHeader("Access-Control-Allow-Headers", headerMap["access-control-request-headers"].toString());
  167. }
  168. response->writeHead(QHttpResponse::STATUS_OK);
  169. response->end();
  170. return;
  171. }
  172. // we want to handle the subscription events in the host
  173. // since we are going to handle the updating later.
  174. //
  175. if (request->path() == "/player/timeline/subscribe")
  176. {
  177. handleSubscription(request, response, false);
  178. return;
  179. }
  180. else if (request->path() == "/player/timeline/unsubscribe")
  181. {
  182. subscriberRemove(request->headers()["x-plex-client-identifier"]);
  183. response->writeHead(QHttpResponse::STATUS_OK);
  184. response->end();
  185. return;
  186. }
  187. else if ((request->path() == "/player/timeline/poll"))
  188. {
  189. if (m_subscriberMap.contains(identifier) == false)
  190. handleSubscription(request, response, true);
  191. RemotePollSubscriber *subscriber = (RemotePollSubscriber *)m_subscriberMap[identifier];
  192. subscriber->reSubscribe();
  193. subscriber->setHTTPResponse(response);
  194. // if we don't have to wait, just ship the update right away
  195. // otherwise, this will wait until next update
  196. if (!(queryMap.contains("wait") && ( queryMap["wait"].toList()[0].toInt() == 1)))
  197. {
  198. subscriber->sendUpdate();
  199. }
  200. return;
  201. }
  202. // handle commandID
  203. if (headerMap.contains("x-plex-client-identifier") == false || queryMap.contains("commandID") == false)
  204. {
  205. QLOG_WARN() << "Can't find a X-Plex-Client-Identifier header";
  206. response->writeHead(QHttpResponse::STATUS_NOT_ACCEPTABLE);
  207. response->end();
  208. return;
  209. }
  210. quint64 commandId = 0;
  211. {
  212. QMutexLocker lk(&m_responseLock);
  213. commandId = ++m_commandId;
  214. m_responseMap[commandId] = response;
  215. connect(response, &QHttpResponse::done, this, &RemoteComponent::responseDone);
  216. }
  217. {
  218. QMutexLocker lk(&m_subscriberLock);
  219. if (m_subscriberMap.contains(identifier) == false)
  220. {
  221. QLOG_WARN() << "Failed to lock up subscriber" << identifier;
  222. response->writeHead(QHttpResponse::STATUS_NOT_ACCEPTABLE);
  223. response->end();
  224. return;
  225. }
  226. RemoteSubscriber* subscriber = m_subscriberMap[identifier];
  227. subscriber->setCommandId(m_commandId, queryMap["commandID"].toList()[0].toInt());
  228. }
  229. QVariantMap arg = {
  230. { "method", request->methodString() },
  231. { "headers", headerMap },
  232. { "path", request->path() },
  233. { "query", queryMap },
  234. { "commandID", m_commandId}
  235. };
  236. emit commandReceived(arg);
  237. }
  238. /////////////////////////////////////////////////////////////////////////////////////////
  239. void RemoteComponent::responseDone()
  240. {
  241. QHttpResponse* response = dynamic_cast<QHttpResponse*>(sender());
  242. if (response)
  243. {
  244. QMutexLocker lk(&m_responseLock);
  245. int foundId = -1;
  246. foreach(int responseId, m_responseMap.keys())
  247. {
  248. if (m_responseMap[responseId] == response)
  249. {
  250. foundId = responseId;
  251. break;
  252. }
  253. }
  254. if (foundId != -1)
  255. m_responseMap.remove(foundId);
  256. }
  257. }
  258. /////////////////////////////////////////////////////////////////////////////////////////
  259. void RemoteComponent::commandResponse(const QVariantMap& responseArguments)
  260. {
  261. // check for minimum requirements in the responseArguments
  262. if (responseArguments.contains("commandID") == false ||
  263. responseArguments.contains("responseCode") == false)
  264. {
  265. QLOG_WARN() << "responseArguments did not contain a commandId or responseCode";
  266. return;
  267. }
  268. quint64 commandId = responseArguments["commandID"].toULongLong();
  269. uint responseCode = responseArguments["responseCode"].toUInt();
  270. QMutexLocker lk(&m_responseLock);
  271. if (m_responseMap.contains(commandId) == false)
  272. {
  273. QLOG_WARN() << "Could not find responseId:" << commandId << " - maybe it was removed because of a timeout?";
  274. return;
  275. }
  276. QHttpResponse* response = m_responseMap[commandId];
  277. // no need to hold the lock when we have changed m_responseMap
  278. lk.unlock();
  279. // add headers if we have them
  280. if (responseArguments.contains("headers") && responseArguments["headers"].type() == QVariant::Map)
  281. {
  282. QVariantMap headers = responseArguments["headers"].toMap();
  283. foreach (const QString& key, headers.keys())
  284. response->setHeader(key, headers[key].toString());
  285. }
  286. // write the response HTTP code
  287. response->writeHead(responseCode);
  288. // handle optional body argument
  289. if (responseArguments.contains("body") && responseArguments["body"].type() == QVariant::String)
  290. response->write(responseArguments["body"].toString().toUtf8());
  291. response->end();
  292. }
  293. /////////////////////////////////////////////////////////////////////////////////////////
  294. void RemoteComponent::handleSubscription(QHttpRequest* request, QHttpResponse* response, bool poll)
  295. {
  296. QVariantMap headers = HeaderToMap(request->headers());
  297. // check for required headers
  298. if (headers.contains("x-plex-client-identifier") == false ||
  299. headers.contains("x-plex-device-name") == false)
  300. {
  301. QLOG_ERROR() << "Missing X-Plex headers in /timeline/subscribe request";
  302. response->writeHead(QHttpResponse::STATUS_BAD_REQUEST);
  303. response->end();
  304. return;
  305. }
  306. // check for required arguments
  307. QVariantMap query = QueryToMap(request->url());
  308. if (query.contains("commandID") == false || ((query.contains("port") == false) && !poll))
  309. {
  310. QLOG_ERROR() << "Missing arguments to /timeline/subscribe request";
  311. response->writeHead(QHttpResponse::STATUS_BAD_REQUEST);
  312. response->end();
  313. return;
  314. }
  315. QString clientIdentifier(request->headers()["x-plex-client-identifier"]);
  316. QMutexLocker lk(&m_subscriberLock);
  317. RemoteSubscriber* subscriber = 0;
  318. if (m_subscriberMap.contains(clientIdentifier))
  319. {
  320. QLOG_DEBUG() << "Refreshed subscriber:" << clientIdentifier;
  321. subscriber = m_subscriberMap[clientIdentifier];
  322. subscriber->reSubscribe();
  323. }
  324. else
  325. {
  326. if (poll)
  327. {
  328. QLOG_DEBUG() << "New poll subscriber:" << clientIdentifier << request->headers()["x-plex-device-name"];
  329. subscriber = new RemotePollSubscriber(clientIdentifier, request->headers()["x-plex-device-name"], response, this);
  330. }
  331. else
  332. {
  333. QUrl address;
  334. QString protocol = query.contains("protocol") ? query["protocol"].toList()[0].toString() : "http";
  335. int port = query.contains("port") ? query["port"].toList()[0].toInt() : 32400;
  336. address.setScheme(protocol);
  337. address.setHost(request->remoteAddress());
  338. address.setPort(port);
  339. QLOG_DEBUG() << "New subscriber:" << clientIdentifier << request->headers()["x-plex-device-name"] << address.toString();
  340. subscriber = new RemoteSubscriber(clientIdentifier, request->headers()["x-plex-device-name"], address, this);
  341. }
  342. m_subscriberMap[clientIdentifier] = subscriber;
  343. // if it's our first controller, we notify web for subscription
  344. if (m_subscriberMap.size() == 1)
  345. {
  346. QLOG_DEBUG() << "First subscriber added, subscribing to web";
  347. subscribeToWeb(true);
  348. }
  349. }
  350. subscriber->setCommandId(m_commandId, query["commandID"].toList()[0].toInt());
  351. if (!poll)
  352. {
  353. subscriber->sendUpdate();
  354. response->writeHead(QHttpResponse::STATUS_OK);
  355. response->end();
  356. }
  357. }
  358. /////////////////////////////////////////////////////////////////////////////////////////
  359. void RemoteComponent::subscribeToWeb(bool subscribe)
  360. {
  361. QVariantMap arg = {
  362. { "method", "GET" },
  363. { "path", "/player/timeline/" + (subscribe ? QLatin1String("subscribe") : QLatin1String("unsubscribe")) },
  364. { "commandID", m_commandId}
  365. };
  366. emit commandReceived(arg);
  367. }
  368. /////////////////////////////////////////////////////////////////////////////////////////
  369. void RemoteComponent::checkSubscribers()
  370. {
  371. QMutexLocker lk(&m_subscriberLock);
  372. QList<RemoteSubscriber*> subsToRemove;
  373. foreach(RemoteSubscriber* subscriber, m_subscriberMap.values())
  374. {
  375. // was it more than 10 seconds since this client checked in last?
  376. if (subscriber->lastSubscribe() > 90 * 1000)
  377. {
  378. QLOG_DEBUG() << "more than 10 seconds since we heard from:" << subscriber->deviceName() << "- unsubscribing..";
  379. subsToRemove << subscriber;
  380. }
  381. }
  382. lk.unlock();
  383. foreach(RemoteSubscriber* sub, subsToRemove)
  384. subscriberRemove(sub->clientIdentifier());
  385. }
  386. /////////////////////////////////////////////////////////////////////////////////////////
  387. QNetworkAccessManager* RemoteComponent::getNetworkAccessManager()
  388. {
  389. // we might want to set common options here.
  390. return m_networkAccessManager;
  391. }
  392. /////////////////////////////////////////////////////////////////////////////////////////
  393. void RemoteComponent::timelineFinished(QNetworkReply* reply)
  394. {
  395. QString identifier = reply->request().attribute(QNetworkRequest::User).toString();
  396. // ignore requests with no identifier
  397. if (identifier.isEmpty())
  398. return;
  399. QMutexLocker lk(&m_subscriberLock);
  400. if (m_subscriberMap.contains(identifier) == false)
  401. {
  402. QLOG_WARN() << "Got a networkreply with a identifier we don't know about:" << identifier;
  403. return;
  404. }
  405. RemoteSubscriber* sub = m_subscriberMap[identifier];
  406. lk.unlock();
  407. sub->timelineFinished(reply);
  408. }
  409. /////////////////////////////////////////////////////////////////////////////////////////
  410. void RemoteComponent::subscriberRemove(const QString& identifier)
  411. {
  412. QMutexLocker lk(&m_subscriberLock);
  413. if (m_subscriberMap.contains(identifier) == false)
  414. {
  415. QLOG_ERROR() << "Can't remove client:" << identifier << "since we don't know about it.";
  416. return;
  417. }
  418. RemoteSubscriber* subscriber = m_subscriberMap[identifier];
  419. m_subscriberMap.remove(identifier);
  420. subscriber->deleteLater();
  421. // if it's our first controller, we notify web for subscription
  422. if (m_subscriberMap.size() == 0)
  423. {
  424. QLOG_DEBUG() << "Last subscriber removed, unsubscribing from web";
  425. subscribeToWeb(false);
  426. }
  427. QLOG_DEBUG() << "Removed subscriber:" << identifier;
  428. }
  429. /////////////////////////////////////////////////////////////////////////////////////////
  430. void RemoteComponent::timelineUpdate(quint64 commandID, const QString& timeline)
  431. {
  432. QMutexLocker lk(&m_subscriberLock);
  433. foreach (RemoteSubscriber* subscriber, m_subscriberMap.values())
  434. {
  435. subscriber->queueTimeline(commandID, timeline.toUtf8());
  436. subscriber->sendUpdate();
  437. }
  438. }