$.ajaxSetup({ crossDomain: true, 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.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 (page) { Dashboard.getUserPromise = null; if (Dashboard.getCurrentUserId()) { Dashboard.getCurrentUser(); } page = page || $.mobile.activePage; var header = $('.header', page); if (header.length) { // Re-render the header header.remove(); if (Dashboard.getUserPromise) { Dashboard.getUserPromise.done(function(user) { Dashboard.ensureHeader(page, user); }); } else { Dashboard.ensureHeader(page); } } }, getCurrentUserId: function () { var userId = localStorage.getItem("userId"); if (!userId) { var autoLoginUserId = getParameterByName('u'); if (autoLoginUserId) { userId = autoLoginUserId; localStorage.setItem("userId", userId); } } return userId; }, setCurrentUser: function (userId) { localStorage.setItem("userId", userId); ApiClient.currentUserId(userId); Dashboard.getUserPromise = null; }, logout: function () { localStorage.removeItem("userId"); Dashboard.getUserPromise = null; ApiClient.currentUserId(null); window.location = "login.html"; }, showError: function (message) { $.mobile.loading('show', { theme: "e", text: message, textonly: true, textVisible: true }); setTimeout(function () { $.mobile.loading('hide'); }, 2000); }, alert: function (message) { $.mobile.loading('show', { theme: "e", text: message, textonly: true, textVisible: true }); setTimeout(function () { $.mobile.loading('hide'); }, 2000); }, updateSystemInfo: function (info) { var isFirstLoad = !Dashboard.lastSystemInfo; Dashboard.lastSystemInfo = info; Dashboard.ensureWebSocket(info); if (!Dashboard.initialServerVersion) { Dashboard.initialServerVersion = info.Version; } if (info.HasPendingRestart) { Dashboard.hideDashboardVersionWarning(); Dashboard.getCurrentUser().done(function (currentUser) { if (currentUser.Configuration.IsAdministrator) { Dashboard.showServerRestartWarning(); } }); } else { Dashboard.hideServerRestartWarning(); if (Dashboard.initialServerVersion != info.Version) { Dashboard.showDashboardVersionWarning(); } } if (isFirstLoad) { Dashboard.showFailedAssemblies(info.FailedPluginAssemblies); } Dashboard.showInProgressInstallations(info.InProgressInstallations); }, showFailedAssemblies: function (failedAssemblies) { for (var i = 0, length = failedAssemblies.length; i < length; i++) { var assembly = failedAssemblies[i]; var html = ''; var index = assembly.lastIndexOf('\\'); if (index != -1) { assembly = assembly.substring(index + 1); } html += ''; html += assembly + " failed to load."; html += ''; Dashboard.showFooterNotification({ html: html }); } }, 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,350"); } 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 () { var html = 'Please restart Media Browser Server to finish updating.'; html += ''; Dashboard.showFooterNotification({ id: "serverRestartWarning", html: html, forceShow: true, allowHide: false }); }, hideServerRestartWarning: function () { $('#serverRestartWarning').remove(); }, showDashboardVersionWarning: function () { var html = 'Please refresh this page to receive new updates from the server.'; html += ''; Dashboard.showFooterNotification({ id: "dashboardVersionWarning", html: html, forceShow: true, allowHide: false }); }, reloadPage: function () { 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 parentElem = $('#footerNotifications'); var elem = $('#' + options.id, parentElem); if (!elem.length) { elem = $('

').appendTo(parentElem); } var onclick = removeOnHide ? "$(\"#" + options.id + "\").remove();" : "$(\"#" + options.id + "\").hide();"; if (options.allowHide !== false) { options.html += ""; } if (options.forceShow) { elem.show(); } elem.html(options.html).trigger('create'); if (options.timeout) { setTimeout(function () { if (removeOnHide) { elem.remove(); } else { elem.hide(); } }, options.timeout); } }, getConfigurationPageUrl: function (name) { return "ConfigurationPage?name=" + encodeURIComponent(name); }, navigate: function (url, preserveQueryString) { var queryString = window.location.search; 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("Settings saved."); }, confirm: function (message, title, callback) { $('#confirmFlyout').popup("close").remove(); var html = '
'; html += '
'; html += '

' + title + '

'; html += '
'; html += '
'; html += '
'; html += message; html += '
'; html += '

'; 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(); }); }, refreshSystemInfoFromServer: function () { 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 $.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 += 'Close'; html += '
'; html += '

' + user.Name + '

'; html += '
'; html += '
'; html += '

'; var imageUrl = user.PrimaryImageTag ? ApiClient.getUserImageUrl(user.Id, { height: 400, tag: user.PrimaryImageTag, type: "Primary" }) : "css/images/userflyoutdefault.png"; html += ''; html += '

'; html += '

'; html += '

'; html += '
'; html += '
'; $(document.body).append(html); $('#userFlyout').popup({ positionTo: context }).trigger('create').popup("open").on("popupafterclose", function () { $(this).off("popupafterclose").remove(); }); }); }, getPluginSecurityInfo: function () { if (!Dashboard.getPluginSecurityInfoPromise) { var deferred = $.Deferred(); // Don't let this blow up the dashboard when it fails $.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; }, ensureHeader: function (page, user) { if (!page.hasClass('libraryPage') && !$('.headerButtons', page).length) { Dashboard.renderHeader(page, user); } }, renderHeader: function (page, user) { var headerHtml = ''; var header = $('.header', page); if (!header.length) { headerHtml += '
'; headerHtml += ''; headerHtml += '
'; page.prepend(headerHtml); header = $('.header', page); } var imageColor = "black"; headerHtml = ''; headerHtml += '
'; if (user && !page.hasClass('wizardPage')) { headerHtml += '' + user.Name + ''; if (user.PrimaryImageTag) { var url = ApiClient.getUserImageUrl(user.Id, { width: 225, tag: user.PrimaryImageTag, type: "Primary" }); headerHtml += ''; } else { headerHtml += ''; } headerHtml += ''; if (user.Configuration.IsAdministrator) { headerHtml += ''; } } headerHtml += '
'; header.append(headerHtml); if (!$('.supporterIcon', header).length) { Dashboard.getPluginSecurityInfo().done(function (pluginSecurityInfo) { if (pluginSecurityInfo.IsMBSupporter) { $('').insertBefore($('.btnTools', header)); } else { $('').insertBefore($('.btnTools', header)); } }); } $(Dashboard).trigger('interiorheaderrendered', [header, user]); }, ensureToolsMenu: function (page) { if (!page.hasClass('type-interior')) { return; } var sidebar = $('.toolsSidebar', page); if (!sidebar.length) { var html = '
'; html += '

Tools

'; html += ''; // content-secondary html += '
'; $(page).append(html); } }, getToolsMenuLinks: function (page) { var pageElem = page[0]; return [{ name: "Dashboard", href: "dashboard.html", selected: pageElem.id == "dashboardPage" }, { name: "Default Media Library", href: "library.html", selected: pageElem.id == "mediaLibraryPage" && !getParameterByName('userId') }, { name: "Metadata", href: "metadata.html", selected: pageElem.id == "metadataConfigurationPage" || pageElem.id == "advancedMetadataConfigurationPage" || pageElem.id == "metadataImagesConfigurationPage" }, { name: "Plugins", href: "plugins.html", selected: page.hasClass("pluginConfigurationPage") }, { name: "User Profiles", href: "userprofiles.html", selected: page.hasClass("userProfilesConfigurationPage") || (pageElem.id == "mediaLibraryPage" && getParameterByName('userId')) }, { name: "Client Settings", href: "clientsettings.html", selected: pageElem.id == "clientSettingsPage" }, { name: "Advanced", href: "advanced.html", selected: pageElem.id == "advancedConfigurationPage" }, { name: "Scheduled Tasks", href: "scheduledtasks.html", selected: pageElem.id == "scheduledTasksPage" || pageElem.id == "scheduledTaskPage" }, { name: "Help", href: "support.html", selected: pageElem.id == "supportPage" || pageElem.id == "logPage" || pageElem.id == "supporterPage" || pageElem.id == "supporterKeyPage" || pageElem.id == "aboutPage" }]; }, ensureWebSocket: function (systemInfo) { if (!("WebSocket" in window)) { // Not supported by the browser return; } if (ApiClient.isWebSocketOpenOrConnecting()) { return; } systemInfo = systemInfo || Dashboard.lastSystemInfo; ApiClient.openWebSocket(systemInfo.WebSocketPortNumber); $(ApiClient).on("websocketmessage", Dashboard.onWebSocketMessageReceived); }, onWebSocketMessageReceived: function (e, data) { var msg = data; if (msg.MessageType === "LibraryChanged") { Dashboard.processLibraryUpdateNotification(msg.Data); } 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") { 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 === "ScheduledTaskEnded") { Dashboard.getCurrentUser().done(function (currentUser) { if (currentUser.Configuration.IsAdministrator) { Dashboard.showTaskCompletionNotification(msg.Data); } }); } else if (msg.MessageType === "Browse") { Dashboard.onBrowseCommand(msg.Data); } else if (msg.MessageType === "Play") { MediaPlayer.getItemsForPlayback({ Ids: msg.Data.ItemIds.join(',') }).done(function (result) { MediaPlayer.play(result.Items, msg.Data.StartPositionTicks); }); } else if (msg.MessageType === "Playstate") { if (msg.Data.Command === 'Stop') { MediaPlayer.stop(); } else if (msg.Data.Command === 'Pause') { MediaPlayer.pause(); } else if (msg.Data.Command === 'Unpause') { MediaPlayer.unpause(); } else if (msg.Data.Command === 'Seek') { MediaPlayer.seek(msg.Data.SeekPositionTicks); } else if (msg.Data.Command === 'NextTrack') { MediaPlayer.nextTrack(); } else if (msg.Data.Command === 'PreviousTrack') { MediaPlayer.previousTrack(); } } }, onBrowseCommand: function (cmd) { var context = cmd.Context || ""; var url; var type = (cmd.ItemType || "").toLowerCase(); if (type == "genre") { url = "itembynamedetails.html?genre=" + ApiClient.encodeName(cmd.ItemName) + "&context=" + context; } else if (type == "musicgenre") { url = "itembynamedetails.html?musicgenre=" + ApiClient.encodeName(cmd.ItemName) + "&context=" + (context || "music"); } else if (type == "gamegenre") { url = "itembynamedetails.html?gamegenre=" + ApiClient.encodeName(cmd.ItemName) + "&context=" + (context || "games"); } else if (type == "studio") { url = "itembynamedetails.html?studio=" + ApiClient.encodeName(cmd.ItemName) + "&context=" + context; } else if (type == "person") { url = "itembynamedetails.html?person=" + ApiClient.encodeName(cmd.ItemName) + "&context=" + context; } else if (type == "artist") { url = "itembynamedetails.html?artist=" + ApiClient.encodeName(cmd.ItemName) + "&context=" + (context || "music"); } if (url) { Dashboard.navigate(url); return; } ApiClient.getItem(Dashboard.getCurrentUserId(), cmd.ItemId).done(function (item) { Dashboard.navigate(LibraryBrowser.getHref(item, context)); }); }, showTaskCompletionNotification: function (result) { var html = ''; if (result.Status == "Completed") { html += ''; return; } else if (result.Status == "Cancelled") { html += ''; return; } else { html += ''; } html += ''; html += result.Name + " " + result.Status; html += ''; var timeout = 0; if (result.Status == 'Cancelled') { timeout = 2000; } Dashboard.showFooterNotification({ html: html, id: result.Id, forceShow: true, timeout: timeout }); }, 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 += installation.Name + ' ' + installation.Version + ' installation completed'; } else if (status == 'cancelled') { html += installation.Name + ' ' + installation.Version + ' installation was cancelled'; } else if (status == 'failed') { html += installation.Name + ' ' + installation.Version + ' installation failed'; } else if (status == 'progress') { html += 'Installing ' + installation.Name + ' ' + installation.Version; } html += ''; if (status == 'progress') { var percentComplete = Math.round(installation.PercentComplete || 0); html += ''; html += '' + percentComplete + '%'; 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.getImageUrl(item.Id, { width: 100, tag: imageTags.Primary, type: "Primary" }); } WebNotifications.show(notification); } }); }, ensurePageTitle: function (page) { if (!page.hasClass('type-interior')) { return; } var pageElem = page[0]; if (pageElem.hasPageTitle) { return; } var parent = $('.content-primary', page); if (!parent.length) { parent = $('.ui-content', page)[0]; } $(parent).prepend("

" + (document.title || " ") + "

"); pageElem.hasPageTitle = true; }, setPageTitle: function (title) { $('.pageTitle', $.mobile.activePage).html(title); if (title) { document.title = title; } }, getDisplayTime: function (ticks) { var ticksPerHour = 36000000000; var parts = []; var hours = ticks / ticksPerHour; hours = parseInt(hours); if (hours) { parts.push(hours); } ticks -= (hours * ticksPerHour); var ticksPerMinute = 600000000; var minutes = ticks / ticksPerMinute; minutes = parseInt(minutes); ticks -= (minutes * ticksPerMinute); if (minutes < 10 && hours) { minutes = '0' + minutes; } parts.push(minutes); var ticksPerSecond = 10000000; var seconds = ticks / ticksPerSecond; seconds = parseInt(seconds); if (seconds < 10) { seconds = '0' + seconds; } parts.push(seconds); return parts.join(':'); } }; var ApiClient = MediaBrowser.ApiClient.create("Dashboard", window.dashboardVersion); $(function () { var footerHtml = ''; $(document.body).append(footerHtml); if (!window.WebSocket) { alert("This browser does not support web sockets. For a better experience, try a newer browser such as Chrome (android, desktop), Firefox, IE10, Safari (iOS) or Opera."); } }); Dashboard.jQueryMobileInit(); $(document).on('pagebeforeshow', ".page", function () { var page = $(this); var userId = Dashboard.getCurrentUserId(); ApiClient.currentUserId(userId); if (!userId) { if (this.id !== "loginPage" && !page.hasClass('wizardPage')) { Dashboard.logout(); return; } Dashboard.ensureHeader(page); Dashboard.ensurePageTitle(page); Dashboard.refreshSystemInfoFromServer(); } else { Dashboard.getCurrentUser().done(function (user) { if (user.Configuration.IsAdministrator) { Dashboard.ensureToolsMenu(page); } Dashboard.ensureHeader(page, user); Dashboard.ensurePageTitle(page); }); Dashboard.refreshSystemInfoFromServer(); } });