summaryrefslogtreecommitdiff
path: root/plexgdm.cpp
blob: e76279daf59077054412369bea6358e229cbbead (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#include <vdr/tools.h>
#include "plexgdm.h"
#include "Config.h"
#include <ctime>
#include "Plexservice.h"

namespace plexclient
{

plexgdm::plexgdm()
{
	_discoverMessage = "M-SEARCH * HTTP/1.0";
	_clientHeader = "* HTTP/1.0";
	_multicastAddress = "239.0.0.250";
	_clientUpdatePort = 32412;
	_helloSent = false;
	_discoverInterval = 30 * 1000;
	_discoverTimer.Set(1);

	m_discoverAdress = Poco::Net::SocketAddress(_multicastAddress, 32414);
	m_clientRegisterGroup = Poco::Net::SocketAddress(_multicastAddress, 32413);

	m_discoveryComplete = false;
	m_registrationIsRunning = false;
	m_clientRegistered = false;
	m_discoveryInterval = 120;
	m_discoveryIsRunning = false;
}

plexgdm::~plexgdm()
{
}

void plexgdm::clientDetails(std::string c_id,
                            std::string c_name,
                            std::string c_port,
                            std::string c_product,
                            std::string c_version)
{
	_clientData =   "Content-Type: plex/media-player\r\n"
	                "Resource-Identifier: " + c_id + "\r\n"
	                "Device-Class: PC\r\n"
	                "Name: " +  c_name + "\r\n"
	                "Port: " + c_port + "\r\n"
	                "Product: " + c_product + "\r\n"
	                "Protocol: plex\r\n"
	                "Protocol-Capabilities: navigation,playback,timeline\r\n"
	                "Protocol-Version: 1\r\n"
	                "Version: " + c_version + "\r\n";
	_clientId = c_id;
}

std::string plexgdm::getClientDetails()
{
	if(_clientData.empty())
		throw "client_Data not initialized";
	return _clientData;
}

void plexgdm::Action()
{
	if(Config::GetInstance().UseConfiguredServer) {
		// Adds a Server to vector
		GetServer(Config::GetInstance().s_serverHost, Config::GetInstance().ServerPort);

		if(Config::GetInstance().UsePlexAccount) {
			GetServer(Config::GetInstance().s_serverHost, Config::GetInstance().ServerPort)->SetAuthToken(Plexservice::GetMyPlexToken());
		}
	}
	
	// Get remote Resources
	Plexservice::UpdateResources();
	
	char buffer[1024];
	m_registrationIsRunning = true;
	m_discoveryIsRunning = true;
	cMutexLock lock(&m_mutex);

	Poco::Net::MulticastSocket update_sock(Poco::Net::SocketAddress(Poco::Net::IPAddress(), _clientUpdatePort), true);

	update_sock.setLoopback(true);
	update_sock.setReuseAddress(true);
	update_sock.setTimeToLive(255);
	update_sock.setBlocking(false);

	while(Running()) {
		try {
			if(!_helloSent) {
				// Send initial Client Registration
				std::string s = Poco::format("HELLO %s\n%s", _clientHeader, _clientData);
				update_sock.sendTo(s.c_str(), s.length(), m_clientRegisterGroup, 0);
				_helloSent = true;
			}
			if(m_registrationIsRunning) {
				Poco::Net::SocketAddress sender;
				int n = 0;
				try {
					n = update_sock.receiveFrom(buffer, sizeof(buffer), sender);
				} catch(Poco::TimeoutException& e) {
					n = 0;
				}
				if(n > 0) {
					std::string buf(buffer, n);
					if(buf.find("M-SEARCH * HTTP/1.") != std::string::npos) {
						//dsyslog("[plex]: Detected client discovery request from %s", sender.host().toString().c_str());
						int t = std::time(0);
						std::string s = Poco::format("HTTP/1.0 200 OK\r\n%sUpdated-At: %d", _clientData, t);
						update_sock.sendTo(s.c_str(), s.length(), sender, 0);
						m_clientRegistered = true;
					}
				}
			}

		} catch(Poco::IOException&) {
			// networkconnection is lost, reset
			_helloSent = false;
		} catch (Poco::Exception&) {
			
		}

		if(m_discoveryIsRunning && _discoverTimer.TimedOut()) {
			discover();
			_discoverTimer.Set(_discoverInterval);
		}
		m_waitCondition.TimedWait(m_mutex, 500);
	}
	// Client loop stopped
	try {
		// unregister from Server
		std::string s = Poco::format("BYE %s\r\n%s", _clientHeader, _clientData);
		update_sock.sendTo(s.c_str(), s.length(), m_clientRegisterGroup, 0);
	} catch (Poco::Exception) {}

	m_clientRegistered = false;
}

void plexgdm::discover()
{
	try {
		

		char buffer[1024];
		std::map<std::string, std::string> vBuffer;

		Poco::Net::MulticastSocket socket(Poco::Net::SocketAddress(Poco::Net::IPAddress(), m_discoverAdress.port()), true);
		socket.setLoopback(true);
		socket.setTimeToLive(1);
		socket.setReceiveTimeout(Poco::Timespan(0, 600 * 1000)); // microseconds
		socket.joinGroup(m_discoverAdress.host()); // Throws a NotFoundException if there is no multicast network device
		socket.sendTo(_discoverMessage.c_str(), _discoverMessage.length(), m_discoverAdress, 0);
		
		try {
			
			while(true) {
				Poco::Net::SocketAddress sender;
				int n = socket.receiveFrom(buffer, sizeof(buffer), sender);
				std::string buf(buffer, n);
				if(buf.find("200 OK") != std::string::npos) {
					vBuffer[sender.host().toString()] = buf;
				}
			}
			
		} catch(Poco::TimeoutException) {}
		
		socket.close();

		m_discoveryComplete = true;

		for(std::map<std::string, std::string>::iterator it = vBuffer.begin(); it != vBuffer.end(); ++it) {
			std::string host = it->first;
			std::string data = it->second;
			bool flag = true;
			// Check for duplicates
			for(std::vector<PlexServer>::iterator s_it = m_vServers.begin(); s_it != m_vServers.end(); ++s_it) {
				if(s_it->GetHost() == host) {
					flag = false;
					s_it->ParseData(data, host);
					dsyslog("[plex] Server Updated: %s", host.c_str());
				}
			}
			if(flag) {
				m_vServers.push_back(PlexServer(data, host));
				// Set token for local servers
				if(Config::GetInstance().UsePlexAccount) {
					m_vServers[m_vServers.size()-1].SetAuthToken(Plexservice::GetMyPlexToken());
				}
				isyslog("[plex] New Server Discovered: %s", host.c_str());
			}
		}
	} catch (Poco::IOException&) {
		// No Networkconnection
	} catch(Poco::NotFoundException&) {
		// there is no multicast network device
	} catch (Poco::Exception&) {}
}

void plexgdm::stopRegistration()
{
	if(m_registrationIsRunning) {
		m_registrationIsRunning = false;
		m_waitCondition.Broadcast();
		Cancel();
	}
}

PlexServer* plexgdm::GetServer(std::string ip, int port)
{
	for(std::vector<PlexServer>::iterator s_it = m_vServers.begin(); s_it != m_vServers.end(); ++s_it) {
		if(s_it->GetHost() == ip && s_it->GetPort() == port) {
			return &(*s_it);
		}
	}
	m_vServers.push_back(PlexServer(ip, port));
	return &m_vServers[m_vServers.size()-1];
}

PlexServer* plexgdm::GetFirstServer()
{
	if(m_vServers.size() > 0 && !m_vServers[0].Offline) return &m_vServers[0];
	else return NULL;
}

PlexServer* plexgdm::GetServer(std::string uuid)
{
	for(std::vector<PlexServer>::iterator s_it = m_vServers.begin(); s_it != m_vServers.end(); ++s_it) {
		if(s_it->GetUuid() == uuid ){
			return &(*s_it);
		}
	}
	return NULL;
}

void plexgdm::AddServer(PlexServer server)
{
	for(std::vector<PlexServer>::iterator s_it = m_vServers.begin(); s_it != m_vServers.end(); ++s_it) {
		if(s_it->GetUuid() == server.GetUuid() ){
			dsyslog("[plex] Server already in list: %s", server.GetUri().c_str());
			return;
		}
	}
	m_vServers.push_back(server);
	isyslog("[plex] New Server Added: %s", server.GetUri().c_str());
}

} // namespace