(function () {
function onAuthFailure(data, textStatus, xhr) {
var url = (this.url || '').toLowerCase();
// Bounce to the login screen, but not if a password entry fails, obviously
if (url.indexOf('/password') == -1 &&
url.indexOf('/authenticate') == -1 &&
!$($.mobile.activePage).is('.standalonePage')) {
Dashboard.logout(false);
}
}
$.ajaxSetup({
crossDomain: true,
statusCode: {
401: onAuthFailure
},
error: function (event) {
Dashboard.hideLoadingMsg();
if (!Dashboard.suppressAjaxErrors) {
setTimeout(function () {
var msg = event.getResponseHeader("X-Application-Error-Code") || Dashboard.defaultErrorMessage;
Dashboard.showError(msg);
}, 500);
}
}
});
})();
if ($.browser.msie) {
// This is unfortuantely required due to IE's over-aggressive caching.
// https://github.com/MediaBrowser/MediaBrowser/issues/179
$.ajaxSetup({
cache: false
});
}
$.support.cors = true;
$(document).one('click', WebNotifications.requestPermission);
var Dashboard = {
jQueryMobileInit: function () {
// Page
//$.mobile.page.prototype.options.theme = "a";
//$.mobile.page.prototype.options.headerTheme = "a";
//$.mobile.page.prototype.options.contentTheme = "a";
//$.mobile.page.prototype.options.footerTheme = "a";
//$.mobile.button.prototype.options.theme = "c";
//$.mobile.listview.prototype.options.dividerTheme = "b";
//$.mobile.popup.prototype.options.theme = "c";
$.mobile.popup.prototype.options.transition = "fade";
$.mobile.defaultPageTransition = "none";
//$.mobile.collapsible.prototype.options.contentTheme = "a";
},
getCurrentUser: function () {
if (!Dashboard.getUserPromise) {
var userId = Dashboard.getCurrentUserId();
Dashboard.getUserPromise = ApiClient.getUser(userId).fail(Dashboard.logout);
}
return Dashboard.getUserPromise;
},
validateCurrentUser: function () {
Dashboard.getUserPromise = null;
if (Dashboard.getCurrentUserId()) {
Dashboard.getCurrentUser();
}
},
getAccessToken: function () {
return store.getItem('token');
},
getCurrentUserId: function () {
var autoLoginUserId = getParameterByName('u');
var storedUserId = store.getItem("userId");
if (autoLoginUserId && autoLoginUserId != storedUserId) {
var token = getParameterByName('t');
Dashboard.setCurrentUser(autoLoginUserId, token);
}
return autoLoginUserId || storedUserId;
},
setCurrentUser: function (userId, token) {
store.setItem("userId", userId);
store.setItem("token", token);
ApiClient.setCurrentUserId(userId, token);
Dashboard.getUserPromise = null;
},
logout: function (logoutWithServer) {
store.removeItem("userId");
store.removeItem("token");
if (logoutWithServer === false) {
window.location = "login.html";
} else {
ApiClient.logout().done(function () {
window.location = "login.html";
});
}
},
showError: function (message) {
$.mobile.loading('show', {
text: message,
textonly: true,
textVisible: true
});
setTimeout(function () {
$.mobile.loading('hide');
}, 3000);
},
alert: function (options) {
if (typeof options == "string") {
var message = options;
$.mobile.loading('show', {
text: message,
textonly: true,
textVisible: true
});
setTimeout(function () {
$.mobile.loading('hide');
}, 3000);
return;
}
Dashboard.confirmInternal(options.message, options.title || Globalize.translate('HeaderAlert'), false, options.callback);
},
updateSystemInfo: function (info) {
Dashboard.lastSystemInfo = info;
Dashboard.ensureWebSocket();
if (!Dashboard.initialServerVersion) {
Dashboard.initialServerVersion = info.Version;
}
if (info.HasPendingRestart) {
Dashboard.hideDashboardVersionWarning();
Dashboard.getCurrentUser().done(function (currentUser) {
if (currentUser.Configuration.IsAdministrator) {
Dashboard.showServerRestartWarning(info);
}
});
} else {
Dashboard.hideServerRestartWarning();
if (Dashboard.initialServerVersion != info.Version) {
Dashboard.showDashboardVersionWarning();
}
}
Dashboard.showInProgressInstallations(info.InProgressInstallations);
},
showInProgressInstallations: function (installations) {
installations = installations || [];
for (var i = 0, length = installations.length; i < length; i++) {
var installation = installations[i];
var percent = installation.PercentComplete || 0;
if (percent < 100) {
Dashboard.showPackageInstallNotification(installation, "progress");
}
}
if (installations.length) {
Dashboard.ensureInstallRefreshInterval();
} else {
Dashboard.stopInstallRefreshInterval();
}
},
ensureInstallRefreshInterval: function () {
if (!Dashboard.installRefreshInterval) {
if (ApiClient.isWebSocketOpen()) {
ApiClient.sendWebSocketMessage("SystemInfoStart", "0,500");
}
Dashboard.installRefreshInterval = 1;
}
},
stopInstallRefreshInterval: function () {
if (Dashboard.installRefreshInterval) {
if (ApiClient.isWebSocketOpen()) {
ApiClient.sendWebSocketMessage("SystemInfoStop");
}
Dashboard.installRefreshInterval = null;
}
},
cancelInstallation: function (id) {
ApiClient.cancelPackageInstallation(id).always(Dashboard.refreshSystemInfoFromServer);
},
showServerRestartWarning: function (systemInfo) {
var html = '' + Globalize.translate('MessagePleaseRestart') + '';
if (systemInfo.CanSelfRestart) {
html += '';
}
Dashboard.showFooterNotification({ id: "serverRestartWarning", html: html, forceShow: true, allowHide: false });
},
hideServerRestartWarning: function () {
$('#serverRestartWarning').remove();
},
showDashboardVersionWarning: function () {
var html = '' + Globalize.translate('MessagePleaseRefreshPage') + '';
html += '';
Dashboard.showFooterNotification({ id: "dashboardVersionWarning", html: html, forceShow: true, allowHide: false });
},
reloadPage: function () {
var currentUrl = window.location.toString().toLowerCase();
// If they're on a plugin config page just go back to the dashboard
// The plugin may not have been loaded yet, or could have been uninstalled
if (currentUrl.indexOf('configurationpage') != -1) {
window.location.href = "dashboard.html";
} else {
window.location.href = window.location.href;
}
},
hideDashboardVersionWarning: function () {
$('#dashboardVersionWarning').remove();
},
showFooterNotification: function (options) {
var removeOnHide = !options.id;
options.id = options.id || "notification" + new Date().getTime() + parseInt(Math.random());
var footer = $("#footer").css("top", "initial").show();
var parentElem = $('#footerNotifications', footer);
var elem = $('#' + options.id, parentElem);
if (!elem.length) {
elem = $('
').appendTo(parentElem);
}
var onclick = removeOnHide ? "$(\"#" + options.id + "\").trigger(\"notification.remove\").remove();" : "$(\"#" + options.id + "\").trigger(\"notification.hide\").hide();";
if (options.allowHide !== false) {
options.html += "";
}
if (options.forceShow) {
elem.slideDown(400);
}
elem.html(options.html).trigger("create");
if (options.timeout) {
setTimeout(function () {
if (removeOnHide) {
elem.trigger("notification.remove").remove();
} else {
elem.trigger("notification.hide").hide();
}
}, options.timeout);
}
footer.on("notification.remove notification.hide", function (e) {
setTimeout(function () { // give the DOM time to catch up
if (!parentElem.html()) {
footer.slideUp();
}
}, 50);
});
},
getConfigurationPageUrl: function (name) {
return "ConfigurationPage?name=" + encodeURIComponent(name);
},
navigate: function (url, preserveQueryString) {
var queryString = getWindowLocationSearch();
if (preserveQueryString && queryString) {
url += queryString;
}
$.mobile.changePage(url);
},
showLoadingMsg: function () {
$.mobile.loading("show");
},
hideLoadingMsg: function () {
$.mobile.loading("hide");
},
processPluginConfigurationUpdateResult: function () {
Dashboard.hideLoadingMsg();
Dashboard.alert("Settings saved.");
},
defaultErrorMessage: "There was an error processing the request.",
processServerConfigurationUpdateResult: function (result) {
Dashboard.hideLoadingMsg();
Dashboard.alert(Globalize.translate('MessageSettingsSaved'));
},
confirmInternal: function (message, title, showCancel, callback) {
$('.confirmFlyout').popup("close").remove();
var html = '
';
html += '
';
html += '
' + title + '
';
html += '
';
html += '
';
html += '
';
html += message;
html += '
';
html += '';
if (showCancel) {
html += '';
}
html += '
';
html += '
';
$(document.body).append(html);
$('.confirmFlyout').popup({ history: false }).trigger('create').popup("open").on("popupafterclose", function () {
if (callback) {
callback(this.confirm == true);
}
$(this).off("popupafterclose").remove();
});
},
confirm: function (message, title, callback) {
Dashboard.confirmInternal(message, title, true, callback);
},
refreshSystemInfoFromServer: function () {
if (Dashboard.getAccessToken()) {
ApiClient.getSystemInfo().done(function (info) {
Dashboard.updateSystemInfo(info);
});
}
},
restartServer: function () {
Dashboard.suppressAjaxErrors = true;
Dashboard.showLoadingMsg();
ApiClient.restartServer().done(function () {
setTimeout(function () {
Dashboard.reloadPageWhenServerAvailable();
}, 250);
}).fail(function () {
Dashboard.suppressAjaxErrors = false;
});
},
reloadPageWhenServerAvailable: function (retryCount) {
// Don't use apiclient method because we don't want it reporting authentication under the old version
ApiClient.getJSON(ApiClient.getUrl("System/Info")).done(function (info) {
// If this is back to false, the restart completed
if (!info.HasPendingRestart) {
Dashboard.reloadPage();
} else {
Dashboard.retryReload(retryCount);
}
}).fail(function () {
Dashboard.retryReload(retryCount);
});
},
retryReload: function (retryCount) {
setTimeout(function () {
retryCount = retryCount || 0;
retryCount++;
if (retryCount < 10) {
Dashboard.reloadPageWhenServerAvailable(retryCount);
} else {
Dashboard.suppressAjaxErrors = false;
}
}, 500);
},
showUserFlyout: function (context) {
Dashboard.getCurrentUser().done(function (user) {
var html = '
';
html += '
';
if (user.PrimaryImageTag) {
var imageUrl = ApiClient.getUserImageUrl(user.Id, {
width: 28,
tag: user.PrimaryImageTag,
type: "Primary"
});
html += '';
}
html += user.Name;
html += '
';
html += '';
html += '
';
$(document.body).append(html);
var elem = $('#userFlyout').panel({}).trigger('create').panel("open").on("panelclose", function () {
$(this).off("panelclose").remove();
});
});
},
getPluginSecurityInfo: function () {
if (!Dashboard.getPluginSecurityInfoPromise) {
var deferred = $.Deferred();
// Don't let this blow up the dashboard when it fails
ApiClient.ajax({
type: "GET",
url: ApiClient.getUrl("Plugins/SecurityInfo"),
dataType: 'json',
error: function () {
// Don't show normal dashboard errors
}
}).done(function (result) {
deferred.resolveWith(null, [result]);
});
Dashboard.getPluginSecurityInfoPromise = deferred;
}
return Dashboard.getPluginSecurityInfoPromise;
},
resetPluginSecurityInfo: function () {
Dashboard.getPluginSecurityInfoPromise = null;
Dashboard.validateCurrentUser();
},
ensureHeader: function (page) {
if (page.hasClass('standalonePage')) {
Dashboard.renderHeader(page);
}
},
renderHeader: function (page) {
var header = $('.header', page);
if (!header.length) {
var headerHtml = '';
headerHtml += '
';
page.prepend(headerHtml);
}
},
ensureToolsMenu: function (page, user) {
if (!page.hasClass('type-interior')) {
return;
}
var sidebar = $('.toolsSidebar', page);
if (!sidebar.length) {
var html = '
';
html += '
';
var links = Dashboard.getToolsMenuLinks(page);
var i, length, link;
for (i = 0, length = links.length; i < length; i++) {
link = links[i];
if (!user.Configuration.IsAdministrator) {
break;
}
if (link.divider) {
html += "";
}
if (link.href) {
if (link.selected) {
html += '' + link.name + '';
} else {
html += '' + link.name + '';
}
}
}
// collapsible
html += '
';
for (i = 0, length = links.length; i < length; i++) {
link = links[i];
if (!user.Configuration.IsAdministrator) {
break;
}
if (link.divider) {
html += "";
}
if (link.href) {
if (link.selected) {
html += '' + link.name + '';
} else {
html += '' + link.name + '';
}
}
}
html += '
';
$('.content-primary', page).before(html);
$(page).trigger('create');
}
},
getToolsMenuLinks: function (page) {
var pageElem = page[0];
return [{
name: Globalize.translate('TabServer'),
href: "dashboard.html",
selected: page.hasClass("dashboardHomePage")
}, {
name: Globalize.translate('TabUsers'),
href: "userprofiles.html",
selected: page.hasClass("userProfilesPage")
}, {
name: Globalize.translate('TabLibrary'),
divider: true,
href: "library.html",
selected: page.hasClass("mediaLibraryPage")
}, {
name: Globalize.translate('TabMetadata'),
href: "metadata.html",
selected: page.hasClass('metadataConfigurationPage')
}, {
name: Globalize.translate('TabAutoOrganize'),
href: "autoorganizelog.html",
selected: page.hasClass("organizePage")
}, {
name: Globalize.translate('TabDLNA'),
href: "dlnasettings.html",
selected: page.hasClass("dlnaPage")
}, {
name: Globalize.translate('TabLiveTV'),
href: "livetvstatus.html",
selected: page.hasClass("liveTvSettingsPage")
}, {
name: Globalize.translate('TabPlugins'),
href: "plugins.html",
selected: page.hasClass("pluginConfigurationPage")
}, {
name: Globalize.translate('TabAdvanced'),
divider: true,
href: "advanced.html",
selected: page.hasClass("advancedConfigurationPage")
}, {
name: Globalize.translate('TabHelp'),
href: "support.html",
selected: pageElem.id == "supportPage" || pageElem.id == "logPage" || pageElem.id == "supporterPage" || pageElem.id == "supporterKeyPage" || pageElem.id == "aboutPage"
}];
},
ensureWebSocket: function () {
if (!("WebSocket" in window)) {
// Not supported by the browser
return;
}
if (ApiClient.isWebSocketOpenOrConnecting()) {
return;
}
var location = window.location;
var webSocketUrl = "ws://" + location.hostname;
if (location.port) {
webSocketUrl += ':' + location.port;
}
ApiClient.openWebSocket(webSocketUrl);
},
onWebSocketOpened: function () {
ApiClient.reportCapabilities({
PlayableMediaTypes: "Audio,Video",
SupportedCommands: Dashboard.getSupportedRemoteCommands().join(',')
});
},
processGeneralCommand: function (cmd) {
// Full list
// https://github.com/MediaBrowser/MediaBrowser/blob/master/MediaBrowser.Model/Session/GeneralCommand.cs#L23
switch (cmd.Name) {
case 'GoHome':
Dashboard.navigate('index.html');
break;
case 'GoToSettings':
Dashboard.navigate('dashboard.html');
break;
case 'DisplayContent':
Dashboard.onBrowseCommand(cmd.Arguments);
break;
case 'GoToSearch':
Search.showSearchPanel($.mobile.activePage);
break;
case 'DisplayMessage':
{
var args = cmd.Arguments;
if (args.TimeoutMs && WebNotifications.supported()) {
var notification = {
title: args.Header,
body: args.Text,
timeout: args.TimeoutMs
};
WebNotifications.show(notification);
}
else {
Dashboard.showFooterNotification({ html: "
" + args.Header + "
" + args.Text, timeout: args.TimeoutMs });
}
break;
}
case 'VolumeUp':
case 'VolumeDown':
case 'Mute':
case 'Unmute':
case 'ToggleMute':
case 'SetVolume':
case 'SetAudioStreamIndex':
case 'SetSubtitleStreamIndex':
case 'ToggleFullscreen':
break;
default:
console.log('Unrecognized command: ' + cmd.Name);
break;
}
},
onWebSocketMessageReceived: function (e, data) {
var msg = data;
if (msg.MessageType === "LibraryChanged") {
Dashboard.processLibraryUpdateNotification(msg.Data);
}
else if (msg.MessageType === "ServerShuttingDown") {
Dashboard.hideServerRestartWarning();
}
else if (msg.MessageType === "ServerRestarting") {
Dashboard.hideServerRestartWarning();
}
else if (msg.MessageType === "UserDeleted") {
Dashboard.validateCurrentUser();
}
else if (msg.MessageType === "SystemInfo") {
Dashboard.updateSystemInfo(msg.Data);
}
else if (msg.MessageType === "RestartRequired") {
Dashboard.updateSystemInfo(msg.Data);
}
else if (msg.MessageType === "UserUpdated" || msg.MessageType === "UserConfigurationUpdated") {
Dashboard.validateCurrentUser();
var user = msg.Data;
if (user.Id == Dashboard.getCurrentUserId()) {
$('.currentUsername').html(user.Name);
}
}
else if (msg.MessageType === "PackageInstallationCompleted") {
Dashboard.getCurrentUser().done(function (currentUser) {
if (currentUser.Configuration.IsAdministrator) {
Dashboard.showPackageInstallNotification(msg.Data, "completed");
Dashboard.refreshSystemInfoFromServer();
}
});
}
else if (msg.MessageType === "PackageInstallationFailed") {
Dashboard.getCurrentUser().done(function (currentUser) {
if (currentUser.Configuration.IsAdministrator) {
Dashboard.showPackageInstallNotification(msg.Data, "failed");
Dashboard.refreshSystemInfoFromServer();
}
});
}
else if (msg.MessageType === "PackageInstallationCancelled") {
Dashboard.getCurrentUser().done(function (currentUser) {
if (currentUser.Configuration.IsAdministrator) {
Dashboard.showPackageInstallNotification(msg.Data, "cancelled");
Dashboard.refreshSystemInfoFromServer();
}
});
}
else if (msg.MessageType === "PackageInstalling") {
Dashboard.getCurrentUser().done(function (currentUser) {
if (currentUser.Configuration.IsAdministrator) {
Dashboard.showPackageInstallNotification(msg.Data, "progress");
Dashboard.refreshSystemInfoFromServer();
}
});
}
else if (msg.MessageType === "GeneralCommand") {
var cmd = msg.Data;
Dashboard.processGeneralCommand(cmd);
}
},
onBrowseCommand: function (cmd) {
var url;
var type = (cmd.ItemType || "").toLowerCase();
if (type == "genre") {
url = "itembynamedetails.html?id=" + cmd.ItemId;
}
else if (type == "musicgenre") {
url = "itembynamedetails.html?id=" + cmd.ItemId;
}
else if (type == "gamegenre") {
url = "itembynamedetails.html?id=" + cmd.ItemId;
}
else if (type == "studio") {
url = "itembynamedetails.html?id=" + cmd.ItemId;
}
else if (type == "person") {
url = "itembynamedetails.html?id=" + cmd.ItemId;
}
else if (type == "musicartist") {
url = "itembynamedetails.html?id=" + cmd.ItemId;
}
if (url) {
Dashboard.navigate(url);
return;
}
ApiClient.getItem(Dashboard.getCurrentUserId(), cmd.ItemId).done(function (item) {
Dashboard.navigate(LibraryBrowser.getHref(item, null, ''));
});
},
showPackageInstallNotification: function (installation, status) {
var html = '';
if (status == 'completed') {
html += '';
}
else if (status == 'cancelled') {
html += '';
}
else if (status == 'failed') {
html += '';
}
else if (status == 'progress') {
html += '';
}
html += '';
if (status == 'completed') {
html += Globalize.translate('LabelPackageInstallCompleted').replace('{0}', installation.Name + ' ' + installation.Version);
}
else if (status == 'cancelled') {
html += Globalize.translate('LabelPackageInstallCancelled').replace('{0}', installation.Name + ' ' + installation.Version);
}
else if (status == 'failed') {
html += Globalize.translate('LabelPackageInstallFailed').replace('{0}', installation.Name + ' ' + installation.Version);
}
else if (status == 'progress') {
html += Globalize.translate('LabelInstallingPackage').replace('{0}', installation.Name + ' ' + installation.Version);
}
html += '';
if (status == 'progress') {
var percentComplete = Math.round(installation.PercentComplete || 0);
html += '';
if (percentComplete < 100) {
var btnId = "btnCancel" + installation.Id;
html += '';
}
}
var timeout = 0;
if (status == 'cancelled') {
timeout = 2000;
}
var forceShow = status != "progress";
var allowHide = status != "progress" && status != 'cancelled';
Dashboard.showFooterNotification({ html: html, id: installation.Id, timeout: timeout, forceShow: forceShow, allowHide: allowHide });
},
processLibraryUpdateNotification: function (data) {
var newItems = data.ItemsAdded;
if (!newItems.length) {
return;
}
ApiClient.getItems(Dashboard.getCurrentUserId(), {
Recursive: true,
Limit: 3,
Filters: "IsNotFolder",
SortBy: "DateCreated",
SortOrder: "Descending",
ImageTypes: "Primary",
Ids: newItems.join(',')
}).done(function (result) {
var items = result.Items;
for (var i = 0, length = Math.min(items.length, 2) ; i < length; i++) {
var item = items[i];
var notification = {
title: "New " + item.Type,
body: item.Name,
timeout: 5000
};
var imageTags = item.ImageTags || {};
if (imageTags.Primary) {
notification.icon = ApiClient.getScaledImageUrl(item.Id, {
width: 60,
tag: imageTags.Primary,
type: "Primary"
});
}
WebNotifications.show(notification);
}
});
},
ensurePageTitle: function (page) {
if (!page.hasClass('type-interior')) {
return;
}
if ($('.pageTitle', page).length) {
return;
}
var parent = $('.content-primary', page);
if (!parent.length) {
parent = $('.ui-content', page)[0];
}
$(parent).prepend("
" + (document.title || " ") + "
");
},
setPageTitle: function (title) {
$('.pageTitle', $.mobile.activePage).html(title);
if (title) {
document.title = title;
}
},
getDisplayTime: function (ticks) {
var ticksPerHour = 36000000000;
var ticksPerMinute = 600000000;
var ticksPerSecond = 10000000;
var parts = [];
var hours = ticks / ticksPerHour;
hours = Math.floor(hours);
if (hours) {
parts.push(hours);
}
ticks -= (hours * ticksPerHour);
var minutes = ticks / ticksPerMinute;
minutes = Math.floor(minutes);
ticks -= (minutes * ticksPerMinute);
if (minutes < 10 && hours) {
minutes = '0' + minutes;
}
parts.push(minutes);
var seconds = ticks / ticksPerSecond;
seconds = Math.floor(seconds);
if (seconds < 10) {
seconds = '0' + seconds;
}
parts.push(seconds);
return parts.join(':');
},
populateLanguages: function (select, languages) {
var html = "";
html += "";
for (var i = 0, length = languages.length; i < length; i++) {
var culture = languages[i];
html += "";
}
$(select).html(html).selectmenu("refresh");
},
populateCountries: function (select, allCountries) {
var html = "";
html += "";
for (var i = 0, length = allCountries.length; i < length; i++) {
var culture = allCountries[i];
html += "";
}
$(select).html(html).selectmenu("refresh");
},
getSupportedRemoteCommands: function () {
// Full list
// https://github.com/MediaBrowser/MediaBrowser/blob/master/MediaBrowser.Model/Session/GeneralCommand.cs
return [
"GoHome",
"GoToSettings",
"VolumeUp",
"VolumeDown",
"Mute",
"Unmute",
"ToggleMute",
"SetVolume",
"SetAudioStreamIndex",
"SetSubtitleStreamIndex",
"DisplayContent",
"GoToSearch",
"DisplayMessage"
];
}
};
(function () {
if (!window.WebSocket) {
alert(Globalize.translate('MessageBrowserDoesNotSupportWebSockets'));
}
window.ApiClient = MediaBrowser.ApiClient.create("Dashboard", window.dashboardVersion);
$(ApiClient).on("websocketopen", Dashboard.onWebSocketOpened)
.on("websocketmessage", Dashboard.onWebSocketMessageReceived);
ApiClient.setCurrentUserId(Dashboard.getCurrentUserId(), Dashboard.getAccessToken());
})();
$(function () {
var videoPlayerHtml = '