jellyfin-web/dashboard-ui/bower_components/emby-apiclient/connectionmanager.js

1526 lines
47 KiB
JavaScript
Raw Normal View History

2015-12-23 10:46:01 -07:00
define(['events', 'apiclient'], function (Events, apiClientFactory) {
2014-10-15 20:26:39 -07:00
2015-12-23 10:46:01 -07:00
var ConnectionState = {
2015-02-15 20:05:21 -07:00
Unavailable: 0,
2014-10-23 21:54:35 -07:00
ServerSelection: 1,
ServerSignIn: 2,
2014-10-29 15:01:02 -07:00
SignedIn: 3,
ConnectSignIn: 4
2014-10-23 21:54:35 -07:00
};
2015-12-23 10:46:01 -07:00
var ConnectionMode = {
2014-10-23 21:54:35 -07:00
Local: 0,
Remote: 1,
Manual: 2
2014-10-23 21:54:35 -07:00
};
2015-12-23 10:46:01 -07:00
var ServerInfo = {
2015-06-08 14:32:20 -07:00
getServerAddress: function (server, mode) {
switch (mode) {
2015-12-23 10:46:01 -07:00
case ConnectionMode.Local:
2015-06-08 14:32:20 -07:00
return server.LocalAddress;
2015-12-23 10:46:01 -07:00
case ConnectionMode.Manual:
2015-06-08 14:32:20 -07:00
return server.ManualAddress;
2015-12-23 10:46:01 -07:00
case ConnectionMode.Remote:
2015-06-08 14:32:20 -07:00
return server.RemoteAddress;
default:
return server.ManualAddress || server.LocalAddress || server.RemoteAddress;
}
}
};
2015-12-23 10:46:01 -07:00
var ConnectionManager = function (credentialProvider, appName, appVersion, deviceName, deviceId, capabilities, devicePixelRatio) {
2015-01-16 13:54:37 -07:00
2015-12-23 10:46:01 -07:00
console.log('Begin ConnectionManager constructor');
2014-10-15 20:26:39 -07:00
var self = this;
2014-10-23 21:54:35 -07:00
var apiClients = [];
2015-07-06 19:25:23 -07:00
var defaultTimeout = 20000;
2014-10-23 21:54:35 -07:00
function mergeServers(list1, list2) {
for (var i = 0, length = list2.length; i < length; i++) {
credentialProvider.addOrUpdateServer(list1, list2[i]);
}
return list1;
}
2015-12-14 08:43:03 -07:00
function resolveFailure(resolve) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
resolve({
2015-12-23 10:46:01 -07:00
State: ConnectionState.Unavailable,
2015-02-15 20:05:21 -07:00
ConnectUser: self.connectUser()
2015-12-14 08:43:03 -07:00
});
2014-10-23 21:54:35 -07:00
}
2014-10-15 20:26:39 -07:00
2014-10-23 21:54:35 -07:00
function updateServerInfo(server, systemInfo) {
2014-10-15 20:26:39 -07:00
2014-10-23 21:54:35 -07:00
server.Name = systemInfo.ServerName;
server.Id = systemInfo.Id;
if (systemInfo.LocalAddress) {
server.LocalAddress = systemInfo.LocalAddress;
}
if (systemInfo.WanAddress) {
server.RemoteAddress = systemInfo.WanAddress;
}
if (systemInfo.MacAddress) {
server.WakeOnLanInfos = [
{ MacAddress: systemInfo.MacAddress }
];
}
}
2015-10-05 19:50:20 -07:00
function getEmbyServerUrl(baseUrl, handler) {
return baseUrl + "/emby/" + handler;
}
2015-12-14 08:43:03 -07:00
function getFetchPromise(request) {
var headers = request.headers || {};
if (request.dataType == 'json') {
headers.accept = 'application/json';
}
var fetchRequest = {
headers: headers,
2015-12-26 11:35:53 -07:00
method: request.type,
credentials: 'same-origin'
2015-12-14 08:43:03 -07:00
};
var contentType = request.contentType;
if (request.data) {
if (typeof request.data === 'string') {
fetchRequest.body = request.data;
} else {
fetchRequest.body = paramsToString(request.data);
contentType = contentType || 'application/x-www-form-urlencoded; charset=UTF-8';
}
}
if (contentType) {
headers['Content-Type'] = contentType;
}
if (!request.timeout) {
return fetch(request.url, fetchRequest);
}
return fetchWithTimeout(request.url, fetchRequest, request.timeout);
}
function fetchWithTimeout(url, options, timeoutMs) {
2015-12-23 10:46:01 -07:00
console.log('fetchWithTimeout: timeoutMs: ' + timeoutMs + ', url: ' + url);
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
var timeout = setTimeout(reject, timeoutMs);
2015-12-26 11:35:53 -07:00
options = options || {};
options.credentials = 'same-origin';
2015-12-14 08:43:03 -07:00
fetch(url, options).then(function (response) {
clearTimeout(timeout);
2015-12-23 10:46:01 -07:00
console.log('fetchWithTimeout: succeeded connecting to url: ' + url);
2015-12-14 08:43:03 -07:00
resolve(response);
}, function (error) {
clearTimeout(timeout);
2015-12-23 10:46:01 -07:00
console.log('fetchWithTimeout: timed out connecting to url: ' + url);
2015-12-14 08:43:03 -07:00
reject();
});
});
}
function paramsToString(params) {
var values = [];
for (var key in params) {
var value = params[key];
if (value !== null && value !== undefined && value !== '') {
values.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
}
}
return values.join('&');
}
function ajax(request) {
if (!request) {
throw new Error("Request cannot be null");
}
request.headers = request.headers || {};
2015-12-23 10:46:01 -07:00
console.log('ConnectionManager requesting url: ' + request.url);
2015-12-14 08:43:03 -07:00
return getFetchPromise(request).then(function (response) {
2015-12-23 10:46:01 -07:00
console.log('ConnectionManager response status: ' + response.status + ', url: ' + request.url);
2015-12-14 08:43:03 -07:00
if (response.status < 400) {
if (request.dataType == 'json' || request.headers.accept == 'application/json') {
return response.json();
} else {
return response;
}
} else {
return Promise.reject(response);
}
}, function (err) {
2015-12-23 10:46:01 -07:00
console.log('ConnectionManager request failed to url: ' + request.url);
2015-12-14 08:43:03 -07:00
throw err;
});
}
2014-12-20 22:57:06 -07:00
function tryConnect(url, timeout) {
2014-10-23 21:54:35 -07:00
2015-10-05 19:50:20 -07:00
url = getEmbyServerUrl(url, "system/info/public");
2015-12-23 10:46:01 -07:00
console.log('tryConnect url: ' + url);
2015-12-14 08:43:03 -07:00
return ajax({
2014-10-23 21:54:35 -07:00
type: "GET",
url: url,
2014-10-23 21:54:35 -07:00
dataType: "json",
2015-05-20 09:28:55 -07:00
timeout: timeout || defaultTimeout
2014-10-23 21:54:35 -07:00
});
}
var connectUser;
self.connectUser = function () {
return connectUser;
2014-10-21 05:42:02 -07:00
};
2014-10-27 14:45:50 -07:00
self.appVersion = function () {
2014-12-02 20:13:03 -07:00
return appVersion;
2014-10-25 11:32:58 -07:00
};
2015-05-28 16:37:43 -07:00
self.capabilities = function () {
return capabilities;
};
2014-10-25 11:32:58 -07:00
self.deviceId = function () {
return deviceId;
};
2015-05-28 16:37:43 -07:00
self.credentialProvider = function () {
return credentialProvider;
};
2015-01-16 13:54:37 -07:00
self.connectUserId = function () {
return credentialProvider.credentials().ConnectUserId;
};
self.connectToken = function () {
return credentialProvider.credentials().ConnectAccessToken;
};
2015-09-09 10:49:44 -07:00
self.getServerInfo = function (id) {
var servers = credentialProvider.credentials().Servers;
2015-09-09 20:22:52 -07:00
return servers.filter(function (s) {
2015-09-09 10:49:44 -07:00
return s.Id == id;
})[0];
};
2015-06-08 14:32:20 -07:00
self.getLastUsedServer = function () {
var servers = credentialProvider.credentials().Servers;
servers.sort(function (a, b) {
return (b.DateLastAccessed || 0) - (a.DateLastAccessed || 0);
});
if (!servers.length) {
return null;
}
return servers[0];
};
2015-05-24 11:33:28 -07:00
self.getLastUsedApiClient = function () {
2015-05-20 09:28:55 -07:00
2015-05-28 16:37:43 -07:00
var servers = credentialProvider.credentials().Servers;
2015-05-20 09:28:55 -07:00
servers.sort(function (a, b) {
2015-06-08 14:32:20 -07:00
return (b.DateLastAccessed || 0) - (a.DateLastAccessed || 0);
2015-05-20 09:28:55 -07:00
});
if (!servers.length) {
return null;
}
var server = servers[0];
return getOrAddApiClient(server, server.LastConnectionMode);
};
self.addApiClient = function (apiClient) {
2014-10-25 11:32:58 -07:00
apiClients.push(apiClient);
2015-06-03 08:26:39 -07:00
var existingServers = credentialProvider.credentials().Servers.filter(function (s) {
2015-05-22 08:59:17 -07:00
2015-06-03 08:26:39 -07:00
return stringEqualsIgnoreCase(s.ManualAddress, apiClient.serverAddress()) ||
stringEqualsIgnoreCase(s.LocalAddress, apiClient.serverAddress()) ||
stringEqualsIgnoreCase(s.RemoteAddress, apiClient.serverAddress());
2015-05-22 08:59:17 -07:00
2015-06-03 08:26:39 -07:00
});
2015-05-22 08:59:17 -07:00
2015-06-03 08:26:39 -07:00
var existingServer = existingServers.length ? existingServers[0] : {};
existingServer.DateLastAccessed = new Date().getTime();
2015-12-23 10:46:01 -07:00
existingServer.LastConnectionMode = ConnectionMode.Manual;
if (existingServer.LastConnectionMode == ConnectionMode.Local) {
2015-12-14 08:43:03 -07:00
existingServer.DateLastLocalConnection = new Date().getTime();
}
2015-06-03 08:26:39 -07:00
existingServer.ManualAddress = apiClient.serverAddress();
apiClient.serverInfo(existingServer);
2015-05-22 08:59:17 -07:00
2015-07-24 14:44:25 -07:00
apiClient.onAuthenticated = function (instance, result) {
onAuthenticated(instance, result, {}, true);
};
2015-05-20 09:28:55 -07:00
2015-06-03 08:26:39 -07:00
if (!existingServers.length) {
2015-05-22 08:59:17 -07:00
var credentials = credentialProvider.credentials();
2015-06-03 08:26:39 -07:00
credentials.Servers = [existingServer];
credentialProvider.credentials(credentials);
}
2015-05-22 08:59:17 -07:00
2015-06-03 08:26:39 -07:00
Events.trigger(self, 'apiclientcreated', [apiClient]);
2014-10-28 16:17:55 -07:00
2015-06-03 08:26:39 -07:00
if (existingServer.Id) {
return;
}
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
apiClient.getPublicSystemInfo().then(function (systemInfo) {
2015-05-22 08:59:17 -07:00
2015-06-03 08:26:39 -07:00
var credentials = credentialProvider.credentials();
existingServer.Id = systemInfo.Id;
apiClient.serverInfo(existingServer);
2015-05-22 08:59:17 -07:00
2015-06-03 08:26:39 -07:00
credentials.Servers = [existingServer];
2015-05-22 08:59:17 -07:00
credentialProvider.credentials(credentials);
2014-10-25 11:32:58 -07:00
});
};
2015-06-18 21:23:55 -07:00
self.clearData = function () {
2015-12-23 10:46:01 -07:00
console.log('connection manager clearing data');
2015-06-18 21:23:55 -07:00
connectUser = null;
var credentials = credentialProvider.credentials();
credentials.ConnectAccessToken = null;
credentials.ConnectUserId = null;
credentials.Servers = [];
credentialProvider.credentials(credentials);
};
function onConnectUserSignIn(user) {
2014-10-23 21:54:35 -07:00
connectUser = user;
Events.trigger(self, 'connectusersignedin', [user]);
2014-10-23 21:54:35 -07:00
}
function getOrAddApiClient(server, connectionMode) {
var apiClient = self.getApiClient(server.Id);
if (!apiClient) {
2015-12-23 10:46:01 -07:00
var url = ServerInfo.getServerAddress(server, connectionMode);
2014-10-23 21:54:35 -07:00
2015-12-23 10:46:01 -07:00
apiClient = new apiClientFactory(url, appName, appVersion, deviceName, deviceId, devicePixelRatio);
2014-10-23 21:54:35 -07:00
apiClients.push(apiClient);
2014-10-25 11:32:58 -07:00
apiClient.serverInfo(server);
2015-07-24 14:44:25 -07:00
apiClient.onAuthenticated = function (instance, result) {
onAuthenticated(instance, result, {}, true);
};
2014-10-23 21:54:35 -07:00
Events.trigger(self, 'apiclientcreated', [apiClient]);
2014-10-23 21:54:35 -07:00
}
2015-12-23 10:46:01 -07:00
console.log('returning instance from getOrAddApiClient');
2014-10-23 21:54:35 -07:00
return apiClient;
}
2015-02-16 23:12:48 -07:00
self.getOrCreateApiClient = function (serverId) {
var credentials = credentialProvider.credentials();
2015-06-03 21:50:10 -07:00
var servers = credentials.Servers.filter(function (s) {
2015-02-16 23:12:48 -07:00
return stringEqualsIgnoreCase(s.Id, serverId);
2015-06-03 21:50:10 -07:00
});
if (!servers.length) {
throw new Error('Server not found: ' + serverId);
}
var server = servers[0];
2015-02-16 23:12:48 -07:00
return getOrAddApiClient(server, server.LastConnectionMode);
};
function onAuthenticated(apiClient, result, options, saveCredentials) {
2014-10-23 21:54:35 -07:00
var credentials = credentialProvider.credentials();
2015-06-03 21:50:10 -07:00
var servers = credentials.Servers.filter(function (s) {
return s.Id == result.ServerId;
});
var server = servers.length ? servers[0] : apiClient.serverInfo();
2014-10-23 21:54:35 -07:00
2015-09-09 10:49:44 -07:00
if (options.updateDateLastAccessed !== false) {
server.DateLastAccessed = new Date().getTime();
2015-12-14 08:43:03 -07:00
2015-12-23 10:46:01 -07:00
if (server.LastConnectionMode == ConnectionMode.Local) {
2015-12-14 08:43:03 -07:00
server.DateLastLocalConnection = new Date().getTime();
}
2015-09-09 10:49:44 -07:00
}
2015-05-24 11:33:28 -07:00
server.Id = result.ServerId;
2014-10-23 21:54:35 -07:00
if (saveCredentials) {
server.UserId = result.User.Id;
server.AccessToken = result.AccessToken;
} else {
server.UserId = null;
server.AccessToken = null;
}
2014-10-26 17:13:47 -07:00
2015-05-28 16:37:43 -07:00
credentialProvider.addOrUpdateServer(credentials.Servers, server);
saveUserInfoIntoCredentials(server, result.User);
credentialProvider.credentials(credentials);
2014-10-23 21:54:35 -07:00
afterConnected(apiClient, options);
2014-10-23 21:54:35 -07:00
2016-01-06 09:38:19 -07:00
onLocalUserSignIn(server, server.LastConnectionMode, result.User);
}
2014-10-23 21:54:35 -07:00
function saveUserInfoIntoCredentials(server, user) {
2014-10-23 21:54:35 -07:00
2015-09-11 09:26:06 -07:00
var info = {
2015-09-10 11:28:22 -07:00
Id: user.Id,
IsSignedInOffline: true
}
2015-09-10 11:28:22 -07:00
credentialProvider.addOrUpdateUser(server, info);
2014-10-23 21:54:35 -07:00
}
function afterConnected(apiClient, options) {
options = options || {};
if (options.reportCapabilities !== false) {
apiClient.reportCapabilities(capabilities);
}
if (options.enableWebSocket !== false) {
2015-12-23 10:46:01 -07:00
if (!apiClient.isWebSocketOpenOrConnecting() && apiClient.isWebSocketSupported()) {
console.log('calling apiClient.openWebSocket');
apiClient.openWebSocket();
}
2014-10-23 21:54:35 -07:00
}
}
2016-01-06 09:38:19 -07:00
function onLocalUserSignIn(server, connectionMode, user) {
// Ensure this is created so that listeners of the event can get the apiClient instance
getOrAddApiClient(server, connectionMode);
2014-10-23 21:54:35 -07:00
Events.trigger(self, 'localusersignedin', [user]);
2014-10-23 21:54:35 -07:00
}
function ensureConnectUser(credentials) {
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
if (connectUser && connectUser.Id == credentials.ConnectUserId) {
resolve();
}
2014-10-30 21:57:24 -07:00
2015-12-14 08:43:03 -07:00
else if (credentials.ConnectUserId && credentials.ConnectAccessToken) {
2014-10-30 21:57:24 -07:00
2015-12-14 08:43:03 -07:00
connectUser = null;
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
getConnectUser(credentials.ConnectUserId, credentials.ConnectAccessToken).then(function (user) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
onConnectUserSignIn(user);
resolve();
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
}, function () {
resolve();
});
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
} else {
resolve();
}
});
2014-10-23 21:54:35 -07:00
}
function getConnectUser(userId, accessToken) {
2014-11-04 16:50:26 -07:00
if (!userId) {
throw new Error("null userId");
}
if (!accessToken) {
throw new Error("null accessToken");
}
2015-08-27 21:19:08 -07:00
var url = "https://connect.emby.media/service/user?id=" + userId;
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
return ajax({
2014-10-23 21:54:35 -07:00
type: "GET",
url: url,
dataType: "json",
headers: {
2014-12-03 22:24:41 -07:00
"X-Application": appName + "/" + appVersion,
"X-Connect-UserToken": accessToken
2014-10-23 21:54:35 -07:00
}
});
}
function addAuthenticationInfoFromConnect(server, connectionMode, credentials) {
2014-11-11 21:51:40 -07:00
if (!server.ExchangeToken) {
throw new Error("server.ExchangeToken cannot be null");
}
if (!credentials.ConnectUserId) {
throw new Error("credentials.ConnectUserId cannot be null");
}
2015-12-23 10:46:01 -07:00
var url = ServerInfo.getServerAddress(server, connectionMode);
2014-10-23 21:54:35 -07:00
2015-10-05 19:50:20 -07:00
url = getEmbyServerUrl(url, "Connect/Exchange?format=json&ConnectUserId=" + credentials.ConnectUserId);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
return ajax({
2014-10-23 21:54:35 -07:00
type: "GET",
url: url,
dataType: "json",
headers: {
"X-MediaBrowser-Token": server.ExchangeToken
2014-10-23 21:54:35 -07:00
}
2015-12-14 08:43:03 -07:00
}).then(function (auth) {
2014-10-23 21:54:35 -07:00
server.UserId = auth.LocalUserId;
server.AccessToken = auth.AccessToken;
2015-12-14 08:43:03 -07:00
return auth;
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}, function () {
2014-10-23 21:54:35 -07:00
server.UserId = null;
server.AccessToken = null;
2015-12-14 08:43:03 -07:00
return Promise.reject();
2014-10-23 21:54:35 -07:00
});
}
function validateAuthentication(server, connectionMode) {
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2014-10-23 21:54:35 -07:00
2015-12-23 10:46:01 -07:00
var url = ServerInfo.getServerAddress(server, connectionMode);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
ajax({
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
type: "GET",
url: getEmbyServerUrl(url, "System/Info"),
dataType: "json",
headers: {
"X-MediaBrowser-Token": server.AccessToken
}
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}).then(function (systemInfo) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
updateServerInfo(server, systemInfo);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
if (server.UserId) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
ajax({
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
type: "GET",
url: getEmbyServerUrl(url, "users/" + server.UserId),
dataType: "json",
headers: {
"X-MediaBrowser-Token": server.AccessToken
}
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}).then(function (user) {
2014-10-23 21:54:35 -07:00
2016-01-06 09:38:19 -07:00
onLocalUserSignIn(server, connectionMode, user);
2015-12-14 08:43:03 -07:00
resolve();
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}, function () {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
server.UserId = null;
server.AccessToken = null;
resolve();
});
}
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}, function () {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
server.UserId = null;
server.AccessToken = null;
resolve();
});
2014-10-23 21:54:35 -07:00
});
}
2014-10-25 11:32:58 -07:00
function getImageUrl(localUser) {
2014-10-27 14:45:50 -07:00
2014-10-25 11:32:58 -07:00
if (connectUser && connectUser.ImageUrl) {
return {
url: connectUser.ImageUrl
};
}
2015-02-25 11:11:49 -07:00
if (localUser && localUser.PrimaryImageTag) {
2014-10-25 11:32:58 -07:00
var apiClient = self.getApiClient(localUser);
var url = apiClient.getUserImageUrl(localUser.Id, {
tag: localUser.PrimaryImageTag,
type: "Primary"
});
return {
url: url,
2015-02-25 11:11:49 -07:00
supportsParams: true
2014-10-25 11:32:58 -07:00
};
}
return {
url: null,
2015-02-25 11:11:49 -07:00
supportsParams: false
2014-10-25 11:32:58 -07:00
};
}
2015-05-18 15:23:03 -07:00
self.user = function (apiClient) {
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
var localUser;
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
function onLocalUserDone(e) {
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
var image = getImageUrl(localUser);
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
resolve({
localUser: localUser,
name: connectUser ? connectUser.Name : (localUser ? localUser.Name : null),
imageUrl: image.url,
supportsImageParams: image.supportsParams
});
}
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
function onEnsureConnectUserDone() {
2014-10-27 14:45:50 -07:00
2015-12-14 08:43:03 -07:00
if (apiClient && apiClient.getCurrentUserId()) {
apiClient.getCurrentUser().then(function (u) {
localUser = u;
onLocalUserDone();
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
}, onLocalUserDone);
} else {
onLocalUserDone();
}
}
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
var credentials = credentialProvider.credentials();
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
if (credentials.ConnectUserId && credentials.ConnectAccessToken && !(apiClient && apiClient.getCurrentUserId())) {
ensureConnectUser(credentials).then(onEnsureConnectUserDone, onEnsureConnectUserDone);
} else {
onEnsureConnectUserDone();
}
});
2014-10-25 11:32:58 -07:00
};
2014-10-21 05:42:02 -07:00
self.isLoggedIntoConnect = function () {
2015-02-23 11:55:38 -07:00
// Make sure it returns true or false
2015-04-01 10:09:08 -07:00
if (!self.connectToken() || !self.connectUserId()) {
return false;
}
return true;
2014-10-21 05:42:02 -07:00
};
2014-10-23 21:54:35 -07:00
self.logout = function () {
2015-12-23 10:46:01 -07:00
console.log('begin connectionManager loguot');
2014-10-23 21:54:35 -07:00
var promises = [];
2014-10-29 18:17:31 -07:00
for (var i = 0, length = apiClients.length; i < length; i++) {
2014-10-23 21:54:35 -07:00
var apiClient = apiClients[i];
if (apiClient.accessToken()) {
2015-02-23 11:55:38 -07:00
promises.push(logoutOfServer(apiClient));
2014-10-23 21:54:35 -07:00
}
}
2014-10-15 20:26:39 -07:00
2015-12-14 08:43:03 -07:00
return Promise.all(promises).then(function () {
2014-10-15 20:26:39 -07:00
2014-10-23 21:54:35 -07:00
var credentials = credentialProvider.credentials();
2015-05-28 16:37:43 -07:00
var servers = credentials.Servers.filter(function (u) {
2014-10-29 18:17:31 -07:00
return u.UserLinkType != "Guest";
});
for (var j = 0, numServers = servers.length; j < numServers; j++) {
var server = servers[j];
2015-05-19 12:15:40 -07:00
server.UserId = null;
server.AccessToken = null;
server.ExchangeToken = null;
var serverUsers = server.Users || [];
for (var k = 0, numUsers = serverUsers.length; k < numUsers; k++) {
serverUsers[k].IsSignedInOffline = false;
}
2014-10-23 21:54:35 -07:00
}
2015-05-28 16:37:43 -07:00
credentials.Servers = servers;
2014-10-23 21:54:35 -07:00
credentials.ConnectAccessToken = null;
credentials.ConnectUserId = null;
credentialProvider.credentials(credentials);
if (connectUser) {
connectUser = null;
Events.trigger(self, 'connectusersignedout');
}
2014-10-29 18:17:31 -07:00
});
2014-10-15 20:26:39 -07:00
};
2014-10-21 05:42:02 -07:00
2015-02-23 11:55:38 -07:00
function logoutOfServer(apiClient) {
2015-02-25 11:11:49 -07:00
var serverInfo = apiClient.serverInfo() || {};
2015-02-23 11:55:38 -07:00
var logoutInfo = {
serverId: serverInfo.Id
};
2015-12-14 08:43:03 -07:00
return apiClient.logout().then(function () {
Events.trigger(self, 'localusersignedout', [logoutInfo]);
}, function () {
2015-02-23 11:55:38 -07:00
Events.trigger(self, 'localusersignedout', [logoutInfo]);
});
}
2015-02-16 13:56:57 -07:00
function getConnectServers(credentials) {
2014-10-23 21:54:35 -07:00
2015-12-23 10:46:01 -07:00
console.log('Begin getConnectServers');
2014-11-04 16:50:26 -07:00
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2014-10-21 05:42:02 -07:00
2015-12-14 08:43:03 -07:00
if (!credentials.ConnectAccessToken || !credentials.ConnectUserId) {
resolve([]);
return;
}
2015-01-16 13:54:37 -07:00
2015-12-14 08:43:03 -07:00
var url = "https://connect.emby.media/service/servers?userId=" + credentials.ConnectUserId;
2014-10-21 05:42:02 -07:00
2015-12-14 08:43:03 -07:00
ajax({
type: "GET",
url: url,
dataType: "json",
headers: {
"X-Application": appName + "/" + appVersion,
"X-Connect-UserToken": credentials.ConnectAccessToken
}
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}).then(function (servers) {
servers = servers.map(function (i) {
return {
ExchangeToken: i.AccessKey,
ConnectServerId: i.Id,
Id: i.SystemId,
Name: i.Name,
RemoteAddress: i.Url,
LocalAddress: i.LocalAddress,
UserLinkType: (i.UserType || '').toLowerCase() == "guest" ? "Guest" : "LinkedUser"
};
});
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
resolve(servers);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}, function () {
resolve([]);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
});
2014-10-21 05:42:02 -07:00
});
2014-10-23 21:54:35 -07:00
}
2015-09-26 07:51:26 -07:00
self.getSavedServers = function () {
var credentials = credentialProvider.credentials();
var servers = credentials.Servers.slice(0);
servers.sort(function (a, b) {
return (b.DateLastAccessed || 0) - (a.DateLastAccessed || 0);
});
return servers;
};
self.getAvailableServers = function () {
2014-10-23 21:54:35 -07:00
2015-12-23 10:46:01 -07:00
console.log('Begin getAvailableServers');
2015-01-16 13:54:37 -07:00
2014-10-23 21:54:35 -07:00
// Clone the array
var credentials = credentialProvider.credentials();
2015-12-14 08:43:03 -07:00
return Promise.all([getConnectServers(credentials), findServers()]).then(function (responses) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
var connectServers = responses[0];
var foundServers = responses[1];
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
var servers = credentials.Servers.slice(0);
mergeServers(servers, foundServers);
mergeServers(servers, connectServers);
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
servers = filterServers(servers, connectServers);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
servers.sort(function (a, b) {
return (b.DateLastAccessed || 0) - (a.DateLastAccessed || 0);
});
2015-01-16 13:54:37 -07:00
2015-12-14 08:43:03 -07:00
credentials.Servers = servers;
2015-02-16 13:56:57 -07:00
2015-12-14 08:43:03 -07:00
credentialProvider.credentials(credentials);
2015-02-16 13:56:57 -07:00
2015-12-14 08:43:03 -07:00
return servers;
2014-10-23 21:54:35 -07:00
});
2014-10-21 05:42:02 -07:00
};
2014-10-15 20:26:39 -07:00
2015-02-16 13:56:57 -07:00
function filterServers(servers, connectServers) {
return servers.filter(function (server) {
// It's not a connect server, so assume it's still valid
if (!server.ExchangeToken) {
return true;
}
return connectServers.filter(function (connectServer) {
return server.Id == connectServer.Id;
}).length > 0;
});
}
function findServers() {
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2015-02-16 13:56:57 -07:00
2015-12-30 15:11:43 -07:00
var onFinish = function (foundServers) {
var servers = foundServers.map(function (foundServer) {
var info = {
Id: foundServer.Id,
LocalAddress: foundServer.Address,
Name: foundServer.Name,
ManualAddress: convertEndpointAddressToManualAddress(foundServer),
DateLastLocalConnection: new Date().getTime()
};
2015-06-08 14:32:20 -07:00
2015-12-30 15:11:43 -07:00
info.LastConnectionMode = info.ManualAddress ? ConnectionMode.Manual : ConnectionMode.Local;
2015-05-24 11:33:28 -07:00
2015-12-30 15:11:43 -07:00
return info;
});
resolve(servers);
};
2015-05-24 11:33:28 -07:00
2015-12-30 15:11:43 -07:00
require(['serverdiscovery'], function (serverDiscovery) {
serverDiscovery.findServers(1000).then(onFinish, function () {
onFinish([]);
2015-06-08 14:32:20 -07:00
});
2015-12-14 08:43:03 -07:00
});
2015-02-16 13:56:57 -07:00
});
}
2015-02-16 20:49:47 -07:00
function convertEndpointAddressToManualAddress(info) {
if (info.Address && info.EndpointAddress) {
var address = info.EndpointAddress.split(":")[0];
// Determine the port, if any
var parts = info.Address.split(":");
if (parts.length > 1) {
var portString = parts[parts.length - 1];
if (!isNaN(parseInt(portString))) {
address += ":" + portString;
}
}
return normalizeAddress(address);
}
return null;
}
2014-10-23 21:54:35 -07:00
self.connect = function () {
2015-12-23 10:46:01 -07:00
console.log('Begin connect');
2015-01-16 13:54:37 -07:00
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
self.getAvailableServers().then(function (servers) {
2015-12-14 08:43:03 -07:00
self.connectToServers(servers).then(function (result) {
2015-12-14 08:43:03 -07:00
resolve(result);
});
2014-10-23 21:54:35 -07:00
});
2015-05-27 22:51:48 -07:00
});
2014-10-23 21:54:35 -07:00
};
self.getOffineResult = function () {
// TODO: Implement
};
2014-10-23 21:54:35 -07:00
self.connectToServers = function (servers) {
2015-12-23 10:46:01 -07:00
console.log('Begin connectToServers, with ' + servers.length + ' servers');
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
if (servers.length == 1) {
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
self.connectToServer(servers[0]).then(function (result) {
2014-10-25 11:32:58 -07:00
2015-12-23 10:46:01 -07:00
if (result.State == ConnectionState.Unavailable) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
result.State = result.ConnectUser == null ?
2015-12-23 10:46:01 -07:00
ConnectionState.ConnectSignIn :
ConnectionState.ServerSelection;
2015-12-14 08:43:03 -07:00
}
2014-10-25 11:32:58 -07:00
2015-12-23 10:46:01 -07:00
console.log('resolving connectToServers with result.State: ' + result.State);
2015-12-14 08:43:03 -07:00
resolve(result);
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
});
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
} else {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
var firstServer = servers.length ? servers[0] : null;
// See if we have any saved credentials and can auto sign in
if (firstServer) {
self.connectToServer(firstServer).then(function (result) {
2014-10-23 21:54:35 -07:00
2015-12-23 10:46:01 -07:00
if (result.State == ConnectionState.SignedIn) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
resolve(result);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
} else {
resolve({
Servers: servers,
2015-12-23 10:46:01 -07:00
State: (!servers.length && !self.connectUser()) ? ConnectionState.ConnectSignIn : ConnectionState.ServerSelection,
2015-12-14 08:43:03 -07:00
ConnectUser: self.connectUser()
});
}
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
});
} else {
2014-10-25 11:32:58 -07:00
2015-12-14 08:43:03 -07:00
resolve({
Servers: servers,
2015-12-23 10:46:01 -07:00
State: (!servers.length && !self.connectUser()) ? ConnectionState.ConnectSignIn : ConnectionState.ServerSelection,
2015-12-14 08:43:03 -07:00
ConnectUser: self.connectUser()
});
}
2014-10-23 21:54:35 -07:00
}
2015-12-14 08:43:03 -07:00
});
2014-10-23 21:54:35 -07:00
};
function beginWakeServer(server) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
require(['wakeonlan'], function (wakeonlan) {
2015-06-08 14:32:20 -07:00
var infos = server.WakeOnLanInfos || [];
for (var i = 0, length = infos.length; i < length; i++) {
2015-12-14 08:43:03 -07:00
wakeonlan.send(infos[i]);
2015-06-08 14:32:20 -07:00
}
});
}
2014-10-23 21:54:35 -07:00
self.connectToServer = function (server, options) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
var tests = [];
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
if (server.LastConnectionMode != null) {
//tests.push(server.LastConnectionMode);
}
2015-12-23 10:46:01 -07:00
if (tests.indexOf(ConnectionMode.Manual) == -1) { tests.push(ConnectionMode.Manual); }
if (tests.indexOf(ConnectionMode.Local) == -1) { tests.push(ConnectionMode.Local); }
if (tests.indexOf(ConnectionMode.Remote) == -1) { tests.push(ConnectionMode.Remote); }
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
beginWakeServer(server);
2015-12-14 08:43:03 -07:00
var wakeOnLanSendTime = new Date().getTime();
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
options = options || {};
testNextConnectionMode(tests, 0, server, wakeOnLanSendTime, options, resolve);
});
};
2014-10-23 21:54:35 -07:00
function stringEqualsIgnoreCase(str1, str2) {
2014-10-23 21:54:35 -07:00
return (str1 || '').toLowerCase() == (str2 || '').toLowerCase();
}
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
function testNextConnectionMode(tests, index, server, wakeOnLanSendTime, options, resolve) {
2014-10-23 21:54:35 -07:00
if (index >= tests.length) {
2015-12-23 10:46:01 -07:00
console.log('Tested all connection modes. Failing server connection.');
2015-12-14 08:43:03 -07:00
resolveFailure(resolve);
return;
2014-10-23 21:54:35 -07:00
}
var mode = tests[index];
2015-12-23 10:46:01 -07:00
var address = ServerInfo.getServerAddress(server, mode);
var enableRetry = false;
var skipTest = false;
2015-05-20 09:28:55 -07:00
var timeout = defaultTimeout;
2014-10-23 21:54:35 -07:00
2015-12-23 10:46:01 -07:00
if (mode == ConnectionMode.Local) {
2014-10-23 21:54:35 -07:00
enableRetry = true;
2015-12-14 08:43:03 -07:00
timeout = 8000;
}
2014-10-23 21:54:35 -07:00
2015-12-23 10:46:01 -07:00
else if (mode == ConnectionMode.Manual) {
if (stringEqualsIgnoreCase(address, server.LocalAddress) ||
stringEqualsIgnoreCase(address, server.RemoteAddress)) {
skipTest = true;
2014-10-23 21:54:35 -07:00
}
}
if (skipTest || !address) {
2015-12-14 08:43:03 -07:00
testNextConnectionMode(tests, index + 1, server, wakeOnLanSendTime, options, resolve);
return;
}
2014-10-23 21:54:35 -07:00
2015-12-23 10:46:01 -07:00
console.log('testing connection mode ' + mode + ' with server ' + server.Name);
2015-02-15 20:05:21 -07:00
2015-12-14 08:43:03 -07:00
tryConnect(address, timeout).then(function (result) {
2014-10-23 21:54:35 -07:00
2015-12-23 10:46:01 -07:00
console.log('calling onSuccessfulConnection with connection mode ' + mode + ' with server ' + server.Name);
2015-12-14 08:43:03 -07:00
onSuccessfulConnection(server, result, mode, options, resolve);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}, function () {
2015-12-23 10:46:01 -07:00
console.log('test failed for connection mode ' + mode + ' with server ' + server.Name);
2015-02-15 21:00:33 -07:00
if (enableRetry) {
var sleepTime = 10000 - (new Date().getTime() - wakeOnLanSendTime);
// TODO: Implement delay and retry
2015-12-14 08:43:03 -07:00
testNextConnectionMode(tests, index + 1, server, wakeOnLanSendTime, options, resolve);
2014-10-23 21:54:35 -07:00
} else {
2015-12-14 08:43:03 -07:00
testNextConnectionMode(tests, index + 1, server, wakeOnLanSendTime, options, resolve);
2014-10-23 21:54:35 -07:00
}
});
}
2015-12-14 08:43:03 -07:00
function onSuccessfulConnection(server, systemInfo, connectionMode, options, resolve) {
2014-10-23 21:54:35 -07:00
var credentials = credentialProvider.credentials();
if (credentials.ConnectAccessToken) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
ensureConnectUser(credentials).then(function () {
2014-10-23 21:54:35 -07:00
if (server.ExchangeToken) {
2015-12-14 08:43:03 -07:00
addAuthenticationInfoFromConnect(server, connectionMode, credentials).then(function () {
afterConnectValidated(server, credentials, systemInfo, connectionMode, true, options, resolve);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}, function () {
afterConnectValidated(server, credentials, systemInfo, connectionMode, true, options, resolve);
});
2014-10-23 21:54:35 -07:00
} else {
2015-12-14 08:43:03 -07:00
afterConnectValidated(server, credentials, systemInfo, connectionMode, true, options, resolve);
}
});
2014-10-23 21:54:35 -07:00
}
else {
2015-12-14 08:43:03 -07:00
afterConnectValidated(server, credentials, systemInfo, connectionMode, true, options, resolve);
}
}
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
function afterConnectValidated(server, credentials, systemInfo, connectionMode, verifyLocalAuthentication, options, resolve) {
2014-10-23 21:54:35 -07:00
if (verifyLocalAuthentication && server.AccessToken) {
2015-12-14 08:43:03 -07:00
validateAuthentication(server, connectionMode).then(function () {
2015-12-14 08:43:03 -07:00
afterConnectValidated(server, credentials, systemInfo, connectionMode, false, options, resolve);
2014-10-23 21:54:35 -07:00
});
return;
2014-10-23 21:54:35 -07:00
}
updateServerInfo(server, systemInfo);
2015-12-14 08:43:03 -07:00
server.LastConnectionMode = connectionMode;
2015-09-09 10:49:44 -07:00
if (options.updateDateLastAccessed !== false) {
server.DateLastAccessed = new Date().getTime();
2015-12-14 08:43:03 -07:00
2015-12-23 10:46:01 -07:00
if (server.LastConnectionMode == ConnectionMode.Local) {
2015-12-14 08:43:03 -07:00
server.DateLastLocalConnection = new Date().getTime();
}
2015-09-09 10:49:44 -07:00
}
2015-05-28 16:37:43 -07:00
credentialProvider.addOrUpdateServer(credentials.Servers, server);
credentialProvider.credentials(credentials);
var result = {
Servers: []
};
result.ApiClient = getOrAddApiClient(server, connectionMode);
result.State = server.AccessToken ?
2015-12-23 10:46:01 -07:00
ConnectionState.SignedIn :
ConnectionState.ServerSignIn;
result.Servers.push(server);
2015-06-03 21:50:10 -07:00
result.ApiClient.updateServerInfo(server, connectionMode);
2015-12-23 10:46:01 -07:00
if (result.State == ConnectionState.SignedIn) {
afterConnected(result.ApiClient, options);
}
2015-12-14 08:43:03 -07:00
resolve(result);
Events.trigger(self, 'connected', [result]);
}
2015-02-16 20:49:47 -07:00
function normalizeAddress(address) {
2014-10-23 21:54:35 -07:00
2015-06-08 14:32:20 -07:00
// attempt to correct bad input
address = address.trim();
2015-06-07 12:13:44 -07:00
2014-10-23 21:54:35 -07:00
if (address.toLowerCase().indexOf('http') != 0) {
address = "http://" + address;
}
2015-05-20 09:28:55 -07:00
// Seeing failures in iOS when protocol isn't lowercase
address = address.replace('Http:', 'http:');
address = address.replace('Https:', 'https:');
2015-02-16 20:49:47 -07:00
return address;
}
self.connectToAddress = function (address) {
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2015-12-14 08:43:03 -07:00
if (!address) {
reject();
return;
}
2015-05-19 12:15:40 -07:00
2015-12-14 08:43:03 -07:00
address = normalizeAddress(address);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
function onFail() {
2015-12-23 10:46:01 -07:00
console.log('connectToAddress ' + address + ' failed');
2015-12-14 08:43:03 -07:00
resolveFailure(resolve);
}
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
tryConnect(address, defaultTimeout).then(function (publicInfo) {
2014-10-23 21:54:35 -07:00
2015-12-23 10:46:01 -07:00
console.log('connectToAddress ' + address + ' succeeded');
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
var server = {
ManualAddress: address,
2015-12-23 10:46:01 -07:00
LastConnectionMode: ConnectionMode.Manual
2015-12-14 08:43:03 -07:00
};
updateServerInfo(server, publicInfo);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
self.connectToServer(server).then(resolve, onFail);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}, onFail);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
});
2014-10-23 21:54:35 -07:00
};
self.loginToConnect = function (username, password) {
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2015-06-08 14:32:20 -07:00
2015-12-14 08:43:03 -07:00
if (!username) {
reject();
return;
}
if (!password) {
reject();
return;
}
2014-11-04 16:50:26 -07:00
2015-12-23 10:46:01 -07:00
require(['connectservice', 'cryptojs-md5'], function (connectservice) {
2015-06-08 14:32:20 -07:00
2015-12-23 10:46:01 -07:00
var md5 = getConnectPasswordHash(connectservice, password);
2015-06-08 14:32:20 -07:00
2015-12-14 08:43:03 -07:00
ajax({
type: "POST",
url: "https://connect.emby.media/service/user/authenticate",
data: {
nameOrEmail: username,
password: md5
},
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
headers: {
"X-Application": appName + "/" + appVersion
}
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
}).then(function (result) {
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
var credentials = credentialProvider.credentials();
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
credentials.ConnectAccessToken = result.AccessToken;
credentials.ConnectUserId = result.User.Id;
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
credentialProvider.credentials(credentials);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
onConnectUserSignIn(result.User);
2014-10-23 21:54:35 -07:00
2015-12-14 08:43:03 -07:00
resolve(result);
2015-06-08 14:32:20 -07:00
2015-12-14 08:43:03 -07:00
}, reject);
2015-06-08 14:32:20 -07:00
});
2015-06-13 16:56:59 -07:00
});
};
self.signupForConnect = function (email, username, password, passwordConfirm) {
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2015-06-13 16:56:59 -07:00
2015-12-14 08:43:03 -07:00
if (!email) {
reject({ errorCode: 'invalidinput' });
return;
}
if (!username) {
reject({ errorCode: 'invalidinput' });
return;
}
if (!password) {
reject({ errorCode: 'invalidinput' });
return;
}
if (!passwordConfirm) {
reject({ errorCode: 'passwordmatch' });
return;
}
if (password != passwordConfirm) {
reject({ errorCode: 'passwordmatch' });
return;
}
2015-06-13 16:56:59 -07:00
2015-12-23 10:46:01 -07:00
require(['connectservice', 'cryptojs-md5'], function (connectservice) {
2015-06-17 08:39:46 -07:00
2015-12-23 10:46:01 -07:00
var md5 = getConnectPasswordHash(connectservice, password);
2015-06-17 08:39:46 -07:00
2015-12-14 08:43:03 -07:00
ajax({
type: "POST",
url: "https://connect.emby.media/service/register",
data: {
email: email,
userName: username,
password: md5
},
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
headers: {
"X-Application": appName + "/" + appVersion,
"X-CONNECT-TOKEN": "CONNECT-REGISTER"
}
2015-06-13 16:56:59 -07:00
2015-12-14 08:43:03 -07:00
}).then(resolve, function (response) {
2015-06-13 16:56:59 -07:00
2015-12-14 08:43:03 -07:00
try {
return response.json();
2015-06-13 16:56:59 -07:00
2015-12-14 08:43:03 -07:00
} catch (err) {
reject();
}
2015-06-13 16:56:59 -07:00
2015-12-14 08:43:03 -07:00
}).then(function (result) {
2015-06-13 16:56:59 -07:00
2015-12-14 08:43:03 -07:00
if (result && result.Status) {
reject({ errorCode: result.Status });
}
2015-06-13 16:56:59 -07:00
2015-12-14 08:43:03 -07:00
}, reject);
2015-06-17 08:39:46 -07:00
});
2014-10-23 21:54:35 -07:00
});
};
2015-12-23 10:46:01 -07:00
function getConnectPasswordHash(connectService, password) {
2014-10-30 21:57:24 -07:00
2015-12-23 10:46:01 -07:00
password = connectService.cleanPassword(password);
2014-10-30 21:57:24 -07:00
return CryptoJS.MD5(password).toString();
2015-12-23 10:46:01 -07:00
}
2014-10-30 21:57:24 -07:00
2014-10-23 21:54:35 -07:00
self.getApiClient = function (item) {
2014-10-25 11:32:58 -07:00
// Accept string + object
if (item.ServerId) {
item = item.ServerId;
}
return apiClients.filter(function (a) {
2014-10-30 21:57:24 -07:00
var serverInfo = a.serverInfo();
// We have to keep this hack in here because of the addApiClient method
return !serverInfo || serverInfo.Id == item;
2014-10-25 11:32:58 -07:00
})[0];
2014-10-23 21:54:35 -07:00
};
2014-11-04 05:41:12 -07:00
self.getUserInvitations = function () {
2015-02-16 13:56:57 -07:00
var connectToken = self.connectToken();
if (!connectToken) {
2014-11-04 16:50:26 -07:00
throw new Error("null connectToken");
}
if (!self.connectUserId()) {
throw new Error("null connectUserId");
}
2015-08-27 21:19:08 -07:00
var url = "https://connect.emby.media/service/servers?userId=" + self.connectUserId() + "&status=Waiting";
2014-11-04 05:41:12 -07:00
2015-12-14 08:43:03 -07:00
return ajax({
2014-11-04 05:41:12 -07:00
type: "GET",
url: url,
dataType: "json",
headers: {
2015-02-16 13:56:57 -07:00
"X-Connect-UserToken": connectToken,
2014-12-02 20:13:03 -07:00
"X-Application": appName + "/" + appVersion
2014-11-04 05:41:12 -07:00
}
});
};
self.deleteServer = function (serverId) {
2015-08-03 09:54:01 -07:00
if (!serverId) {
throw new Error("null serverId");
}
2015-05-12 21:55:19 -07:00
2015-08-29 17:40:52 -07:00
var server = credentialProvider.credentials().Servers.filter(function (s) {
return s.Id == serverId;
});
server = server.length ? server[0] : null;
2015-12-14 08:43:03 -07:00
return new Promise(function (resolve, reject) {
2015-05-12 21:55:19 -07:00
2015-12-14 08:43:03 -07:00
function onDone() {
var credentials = credentialProvider.credentials();
2014-11-04 16:50:26 -07:00
2015-12-14 08:43:03 -07:00
credentials.Servers = credentials.Servers.filter(function (s) {
return s.Id != serverId;
});
2015-08-29 17:40:52 -07:00
2015-12-14 08:43:03 -07:00
credentialProvider.credentials(credentials);
resolve();
}
2015-08-29 17:40:52 -07:00
2015-12-14 08:43:03 -07:00
if (!server.ConnectServerId) {
onDone();
return;
}
2014-11-18 19:45:12 -07:00
2015-12-14 08:43:03 -07:00
var connectToken = self.connectToken();
var connectUserId = self.connectUserId();
2015-05-12 21:55:19 -07:00
2015-12-14 08:43:03 -07:00
if (!connectToken || !connectUserId) {
onDone();
return;
2014-11-18 19:45:12 -07:00
}
2015-12-14 08:43:03 -07:00
var url = "https://connect.emby.media/service/serverAuthorizations?serverId=" + server.ConnectServerId + "&userId=" + connectUserId;
ajax({
type: "DELETE",
url: url,
headers: {
"X-Connect-UserToken": connectToken,
"X-Application": appName + "/" + appVersion
}
2014-11-18 19:45:12 -07:00
2015-12-14 08:43:03 -07:00
}).then(onDone, onDone);
});
2014-11-18 19:45:12 -07:00
};
self.rejectServer = function (serverId) {
2015-02-16 13:56:57 -07:00
var connectToken = self.connectToken();
2014-11-18 19:45:12 -07:00
if (!serverId) {
throw new Error("null serverId");
}
2015-02-16 13:56:57 -07:00
if (!connectToken) {
2014-11-18 19:45:12 -07:00
throw new Error("null connectToken");
}
if (!self.connectUserId()) {
throw new Error("null connectUserId");
}
2015-08-27 21:19:08 -07:00
var url = "https://connect.emby.media/service/serverAuthorizations?serverId=" + serverId + "&userId=" + self.connectUserId();
2014-11-04 05:41:12 -07:00
2015-12-14 08:43:03 -07:00
return fetch(url, {
method: "DELETE",
2014-11-04 05:41:12 -07:00
headers: {
2015-02-16 13:56:57 -07:00
"X-Connect-UserToken": connectToken,
2014-12-02 20:13:03 -07:00
"X-Application": appName + "/" + appVersion
2014-11-04 05:41:12 -07:00
}
});
};
2014-11-04 15:43:02 -07:00
self.acceptServer = function (serverId) {
2014-11-04 05:41:12 -07:00
2015-02-16 13:56:57 -07:00
var connectToken = self.connectToken();
2014-11-04 16:50:26 -07:00
if (!serverId) {
throw new Error("null serverId");
}
2015-02-16 13:56:57 -07:00
if (!connectToken) {
2014-11-04 16:50:26 -07:00
throw new Error("null connectToken");
}
if (!self.connectUserId()) {
throw new Error("null connectUserId");
}
2015-08-27 21:19:08 -07:00
var url = "https://connect.emby.media/service/ServerAuthorizations/accept?serverId=" + serverId + "&userId=" + self.connectUserId();
2014-11-04 05:41:12 -07:00
2015-12-14 08:43:03 -07:00
return ajax({
2014-11-04 05:41:12 -07:00
type: "GET",
url: url,
headers: {
2015-02-16 13:56:57 -07:00
"X-Connect-UserToken": connectToken,
2014-12-02 20:13:03 -07:00
"X-Application": appName + "/" + appVersion
2014-11-04 05:41:12 -07:00
}
});
};
2015-05-26 08:31:50 -07:00
self.getRegistrationInfo = function (feature, apiClient) {
2015-12-14 08:43:03 -07:00
return self.getAvailableServers().then(function (servers) {
2015-05-26 10:48:05 -07:00
var matchedServers = servers.filter(function (s) {
return stringEqualsIgnoreCase(s.Id, apiClient.serverInfo().Id);
});
if (!matchedServers.length) {
2015-12-14 08:43:03 -07:00
return {};
2015-05-26 10:48:05 -07:00
}
var match = matchedServers[0];
2015-12-14 08:43:03 -07:00
if (!match.DateLastLocalConnection) {
2015-05-26 10:48:05 -07:00
2015-12-14 08:43:03 -07:00
return ApiClient.getJSON(ApiClient.getUrl('System/Endpoint')).then(function (info) {
2015-05-26 10:48:05 -07:00
2015-12-14 08:43:03 -07:00
if (info.IsInNetwork) {
2015-05-26 10:48:05 -07:00
2015-12-14 08:43:03 -07:00
updateDateLastLocalConnection(match.Id);
return apiClient.getRegistrationInfo(feature);
} else {
return {};
}
2015-05-26 10:48:05 -07:00
2015-12-14 08:43:03 -07:00
});
2015-05-26 10:48:05 -07:00
2015-12-14 08:43:03 -07:00
} else {
return apiClient.getRegistrationInfo(feature);
}
2015-05-26 10:48:05 -07:00
});
2015-05-26 08:31:50 -07:00
};
2015-12-14 08:43:03 -07:00
function updateDateLastLocalConnection(serverId) {
var credentials = credentialProvider.credentials();
var servers = credentials.Servers.filter(function (s) {
return s.Id == serverId;
});
var server = servers.length ? servers[0] : null;
if (server) {
server.DateLastLocalConnection = new Date().getTime();
credentialProvider.addOrUpdateServer(credentials.Servers, server);
credentialProvider.credentials(credentials);
}
}
2015-05-26 08:31:50 -07:00
2015-01-16 13:54:37 -07:00
return self;
2014-10-23 21:54:35 -07:00
};
2014-10-21 05:42:02 -07:00
2015-12-23 10:46:01 -07:00
return {
ConnectionState: ConnectionState,
ConnectionMode: ConnectionMode,
ServerInfo: ServerInfo,
ConnectionManager: ConnectionManager
};
});