var DashboardPage = { newsStartIndex: 0, onPageShow: function () { var page = this; DashboardPage.newsStartIndex = 0; Dashboard.showLoadingMsg(); DashboardPage.pollForInfo(page); DashboardPage.startInterval(); $(ApiClient).on("websocketmessage", DashboardPage.onWebSocketMessage) .on("websocketopen", DashboardPage.onWebSocketOpen); DashboardPage.lastAppUpdateCheck = null; DashboardPage.lastPluginUpdateCheck = null; Dashboard.getPluginSecurityInfo().done(function (pluginSecurityInfo) { if (pluginSecurityInfo.IsMBSupporter) { $('#contribute', page).hide(); } else { $('#contribute', page).show(); } DashboardPage.renderSupporterIcon(page, pluginSecurityInfo); }); DashboardPage.reloadSystemInfo(page); DashboardPage.reloadNews(page); DashboardPage.sessionUpdateTimer = setInterval(DashboardPage.refreshSessionsLocally, 60000); }, refreshSessionsLocally: function () { var list = DashboardPage.sessionsList; if (list) { console.log('refreshSessionsLocally'); DashboardPage.renderActiveConnections($.mobile.activePage, list); } }, reloadSystemInfo: function (page) { ApiClient.getSystemInfo().done(function (systemInfo) { Dashboard.updateSystemInfo(systemInfo); $('#appVersionNumber', page).html(Globalize.translate('LabelVersionNumber').replace('{0}', systemInfo.Version)); var port = systemInfo.HttpServerPortNumber; if (port == systemInfo.WebSocketPortNumber) { $('#ports', page).html(Globalize.translate('LabelRunningOnPort').replace('{0}', '' + port + '')); } else { $('#ports', page).html(Globalize.translate('LabelRunningOnPorts').replace('{0}', '' + port + '').replace('{1}', '' + systemInfo.WebSocketPortNumber + '')); } if (systemInfo.CanSelfRestart) { $('.btnRestartContainer', page).removeClass('hide'); } else { $('.btnRestartContainer', page).addClass('hide'); } DashboardPage.renderUrls(page, systemInfo); DashboardPage.renderPendingInstallations(page, systemInfo); if (systemInfo.CanSelfUpdate) { $('#btnUpdateApplicationContainer', page).show(); $('#btnManualUpdateContainer', page).hide(); } else { $('#btnUpdateApplicationContainer', page).hide(); $('#btnManualUpdateContainer', page).show(); } DashboardPage.renderHasPendingRestart(page, systemInfo.HasPendingRestart); }); }, reloadNews: function (page) { var query = { StartIndex: DashboardPage.newsStartIndex, Limit: 5 }; ApiClient.getProductNews(query).done(function (result) { var html = result.Items.map(function (item) { var itemHtml = ''; itemHtml += '
'; itemHtml += '' + item.Title + ''; var date = parseISO8601Date(item.Date, { toLocal: true }); itemHtml += '
' + date.toLocaleDateString() + '
'; itemHtml += '
' + item.DescriptionHtml + '
'; itemHtml += '
'; return itemHtml; }); var pagingHtml = ''; pagingHtml += '
'; pagingHtml += LibraryBrowser.getPagingHtml(query, result.TotalRecordCount, false, [], false); pagingHtml += '
'; html = html.join('') + pagingHtml; var elem = $('.latestNewsItems', page).html(html).trigger('create'); $('.btnNextPage', elem).on('click', function () { DashboardPage.newsStartIndex += query.Limit; DashboardPage.reloadNews(page); }); $('.btnPreviousPage', elem).on('click', function () { DashboardPage.newsStartIndex -= query.Limit; DashboardPage.reloadNews(page); }); }); }, onPageHide: function () { $(ApiClient).off("websocketmessage", DashboardPage.onWebSocketMessage).off("websocketopen", DashboardPage.onWebSocketConnectionChange).off("websocketerror", DashboardPage.onWebSocketConnectionChange).off("websocketclose", DashboardPage.onWebSocketConnectionChange); DashboardPage.stopInterval(); if (DashboardPage.sessionUpdateTimer) { clearInterval(DashboardPage.sessionUpdateTimer); } }, startInterval: function () { if (ApiClient.isWebSocketOpen()) { ApiClient.sendWebSocketMessage("SessionsStart", "0,1500"); ApiClient.sendWebSocketMessage("ScheduledTasksInfoStart", "0,1000"); } }, stopInterval: function () { if (ApiClient.isWebSocketOpen()) { ApiClient.sendWebSocketMessage("SessionsStop"); ApiClient.sendWebSocketMessage("ScheduledTasksInfoStop"); } }, onWebSocketMessage: function (e, msg) { var page = $.mobile.activePage; if (msg.MessageType == "Sessions") { DashboardPage.renderInfo(page, msg.Data); } else if (msg.MessageType == "RestartRequired") { DashboardPage.renderHasPendingRestart(page, true); } else if (msg.MessageType == "ServerShuttingDown") { DashboardPage.renderHasPendingRestart(page, true); } else if (msg.MessageType == "ServerRestarting") { DashboardPage.renderHasPendingRestart(page, true); } else if (msg.MessageType == "ScheduledTasksInfo") { var tasks = msg.Data; DashboardPage.renderRunningTasks(page, tasks); } else if (msg.MessageType == "PackageInstalling" || msg.MessageType == "PackageInstallationCompleted") { DashboardPage.pollForInfo(page, true); DashboardPage.reloadSystemInfo(page); } }, onWebSocketOpen: function () { DashboardPage.startInterval(); }, pollForInfo: function (page, forceUpdate) { ApiClient.getSessions().done(function (sessions) { DashboardPage.renderInfo(page, sessions, forceUpdate); }); ApiClient.getScheduledTasks().done(function (tasks) { DashboardPage.renderRunningTasks(page, tasks); }); }, renderInfo: function (page, sessions, forceUpdate) { DashboardPage.renderActiveConnections(page, sessions); DashboardPage.renderPluginUpdateInfo(page, forceUpdate); Dashboard.hideLoadingMsg(); }, renderActiveConnections: function (page, sessions) { var html = ''; DashboardPage.sessionsList = sessions; var parentElement = $('.activeDevices', page); $('.activeSession', parentElement).addClass('deadSession'); for (var i = 0, length = sessions.length; i < length; i++) { var session = sessions[i]; var rowId = 'session' + session.Id; var elem = $('#' + rowId, page); if (elem.length) { DashboardPage.updateSession(elem, session); continue; } var nowPlayingItem = session.NowPlayingItem; var className = nowPlayingItem ? 'playingSession activeSession' : 'activeSession'; if (session.TranscodingInfo && session.TranscodingInfo.CompletionPercentage) { className += ' transcodingSession'; } html += '
'; html += '
'; html += '
' + DashboardPage.getAppSecondaryText(session) + '
'; html += '
'; html += '
'; html += '
'; var userImage = DashboardPage.getUserImage(session); if (userImage) { html += '
'; html += ''; } else { html += '
'; } html += '
'; html += '
'; html += DashboardPage.getUsersHtml(session); html += '
'; html += '
'; var nowPlayingName = DashboardPage.getNowPlayingName(session); html += '
'; html += nowPlayingName.html; html += '
'; if (nowPlayingItem && nowPlayingItem.RunTimeTicks) { var position = session.PlayState.PositionTicks || 0; var value = (100 * position) / nowPlayingItem.RunTimeTicks; html += ''; } else { html += ''; } if (session.TranscodingInfo && session.TranscodingInfo.CompletionPercentage) { html += ''; } else { html += ''; } html += '
'; html += '
'; html += '
' + DashboardPage.getSessionNowPlayingStreamInfo(session) + '
'; html += '
' + DashboardPage.getSessionNowPlayingTime(session) + '
'; if (session.TranscodingInfo && session.TranscodingInfo.Framerate) { html += '
' + session.TranscodingInfo.Framerate + ' fps
'; } else { html += '
'; } html += '
'; html += ''; } parentElement.append(html).createSessionItemMenus().trigger('create'); $('.deadSession', parentElement).remove(); }, getSessionNowPlayingStreamInfo: function (session) { var html = ''; html += '
'; if (session.PlayState.PlayMethod == 'Transcode') { html += Globalize.translate('LabelPlayMethodTranscoding'); } else if (session.PlayState.PlayMethod == 'DirectStream') { html += Globalize.translate('LabelPlayMethodDirectStream'); } else if (session.PlayState.PlayMethod == 'DirectPlay') { html += Globalize.translate('LabelPlayMethodDirectPlay'); } html += '
'; if (session.TranscodingInfo) { html += '
'; var line = []; if (session.TranscodingInfo.Container) { line.push(session.TranscodingInfo.Container); } if (session.TranscodingInfo.Bitrate) { if (session.TranscodingInfo.Bitrate > 1000000) { line.push((session.TranscodingInfo.Bitrate / 1000000).toFixed(1) + ' Mbps'); } else { line.push(Math.floor(session.TranscodingInfo.Bitrate / 1000) + ' kbps'); } } if (line.length) { html += '
' + line.join(' ') + '
'; } if (session.TranscodingInfo.VideoCodec) { html += '
' + Globalize.translate('LabelVideoCodec').replace('{0}', session.TranscodingInfo.VideoCodec) + '
'; } if (session.TranscodingInfo.AudioCodec && session.TranscodingInfo.AudioCodec != session.TranscodingInfo.Container) { html += '
' + Globalize.translate('LabelAudioCodec').replace('{0}', session.TranscodingInfo.AudioCodec) + '
'; } } return html; }, getSessionNowPlayingTime: function (session) { var html = ''; if (session.PlayState.PositionTicks) { html += Dashboard.getDisplayTime(session.PlayState.PositionTicks); } else { html += '--:--:--'; } html += ' / '; var nowPlayingItem = session.NowPlayingItem; if (nowPlayingItem && nowPlayingItem.RunTimeTicks) { html += Dashboard.getDisplayTime(nowPlayingItem.RunTimeTicks); } else { html += '--:--:--'; } return html; }, getAppSecondaryText: function (session) { return session.ApplicationVersion; }, getNowPlayingName: function (session) { var imgUrl = ''; var nowPlayingItem = session.NowPlayingItem; if (!nowPlayingItem) { return { html: 'Last seen ' + humane_date(session.LastActivityDate), image: imgUrl }; } var topText = nowPlayingItem.Name; var bottomText = ''; if (nowPlayingItem.Artists && nowPlayingItem.Artists.length) { bottomText = topText; topText = nowPlayingItem.Artists[0]; } else if (nowPlayingItem.SeriesName || nowPlayingItem.Album) { bottomText = topText; topText = nowPlayingItem.SeriesName || nowPlayingItem.Album; } else if (nowPlayingItem.ProductionYear) { bottomText = nowPlayingItem.ProductionYear; } if (nowPlayingItem.LogoItemId) { imgUrl = ApiClient.getScaledImageUrl(nowPlayingItem.LogoItemId, { tag: session.LogoImageTag, maxHeight: 24, maxWidth: 130, type: 'Logo' }); topText = ''; } var text = bottomText ? topText + '
' + bottomText : topText; return { html: text, image: imgUrl }; }, getUsersHtml: function (session) { var html = []; if (session.UserId) { html.push(session.UserName); } for (var i = 0, length = session.AdditionalUsers.length; i < length; i++) { html.push(session.AdditionalUsers[i].UserName); } return html.join(', '); }, getUserImage: function (session) { if (session.UserId && session.UserPrimaryImageTag) { return ApiClient.getUserImageUrl(session.UserId, { tag: session.UserPrimaryImageTag, height: 24, type: 'Primary' }); } return null; }, updateSession: function (row, session) { row.removeClass('deadSession'); var nowPlayingItem = session.NowPlayingItem; if (nowPlayingItem) { row.addClass('playingSession'); } else { row.removeClass('playingSession'); } $('.sessionNowPlayingStreamInfo', row).html(DashboardPage.getSessionNowPlayingStreamInfo(session)); $('.sessionNowPlayingTime', row).html(DashboardPage.getSessionNowPlayingTime(session)); $('.sessionUserName', row).html(DashboardPage.getUsersHtml(session)); $('.sessionAppSecondaryText', row).html(DashboardPage.getAppSecondaryText(session)); $('.sessionTranscodingFramerate', row).html((session.TranscodingInfo && session.TranscodingInfo.Framerate) ? session.TranscodingInfo.Framerate + ' fps' : ''); var nowPlayingName = DashboardPage.getNowPlayingName(session); var nowPlayingInfoElem = $('.sessionNowPlayingInfo', row); if (!nowPlayingName.image || nowPlayingName.image != nowPlayingInfoElem.attr('data-imgsrc')) { nowPlayingInfoElem.html(nowPlayingName.html); nowPlayingInfoElem.attr('data-imgsrc', nowPlayingName.image || ''); } if (nowPlayingItem && nowPlayingItem.RunTimeTicks) { var position = session.PlayState.PositionTicks || 0; var value = (100 * position) / nowPlayingItem.RunTimeTicks; $('.playbackProgress', row).show().val(value); } else { $('.playbackProgress', row).hide(); } if (session.TranscodingInfo && session.TranscodingInfo.CompletionPercentage) { row.addClass('transcodingSession'); $('.transcodingProgress', row).show().val(session.TranscodingInfo.CompletionPercentage); } else { $('.transcodingProgress', row).hide(); row.removeClass('transcodingSession'); } var imgUrl = DashboardPage.getNowPlayingImageUrl(nowPlayingItem) || ''; var imgElem = $('.sessionNowPlayingContent', row)[0]; if (imgUrl != imgElem.getAttribute('data-src')) { imgElem.style.backgroundImage = imgUrl ? 'url(\'' + imgUrl + '\')' : ''; imgElem.setAttribute('data-src', imgUrl); } }, getClientImage: function (connection) { var clientLowered = connection.Client.toLowerCase(); if (clientLowered == "dashboard") { var device = connection.DeviceName.toLowerCase(); var imgUrl; if (device.indexOf('chrome') != -1) { imgUrl = 'css/images/clients/chrome.png'; } else if (device.indexOf('firefox') != -1) { imgUrl = 'css/images/clients/firefox.png'; } else if (device.indexOf('internet explorer') != -1) { imgUrl = 'css/images/clients/ie.png'; } else if (device.indexOf('safari') != -1) { imgUrl = 'css/images/clients/safari.png'; } else { imgUrl = 'css/images/clients/html5.png'; } return "Dashboard"; } if (clientLowered == "mb-classic") { return ""; } if (clientLowered == "media browser theater") { return ""; } if (clientLowered == "android") { return ""; } if (clientLowered == "roku") { return ""; } if (clientLowered == "ios") { return ""; } if (clientLowered == "windows rt") { return ""; } if (clientLowered == "windows phone") { return ""; } if (clientLowered == "dlna") { return ""; } if (clientLowered == "mbkinect") { return ""; } if (clientLowered == "xbmc") { return ""; } if (clientLowered == "chromecast") { return ""; } return null; }, getNowPlayingImageUrl: function (item) { if (item && item.BackdropImageTag) { return ApiClient.getScaledImageUrl(item.BackdropItemId, { type: "Backdrop", width: 275, tag: item.BackdropImageTag }); } if (item && item.ThumbImageTag) { return ApiClient.getScaledImageUrl(item.ThumbItemId, { type: "Thumb", width: 275, tag: item.ThumbImageTag }); } if (item && item.PrimaryImageTag) { return ApiClient.getScaledImageUrl(item.PrimaryImageItemId, { type: "Primary", width: 275, tag: item.PrimaryImageTag }); } return null; }, systemUpdateTaskKey: "SystemUpdateTask", renderRunningTasks: function (page, tasks) { var html = ''; tasks = tasks.filter(function (t) { return t.State != 'Idle'; }); if (tasks.filter(function (t) { return t.Key == DashboardPage.systemUpdateTaskKey; }).length) { $('#btnUpdateApplication', page).buttonEnabled(false); } else { $('#btnUpdateApplication', page).buttonEnabled(true); } if (!tasks.length) { $('#runningTasksCollapsible', page).hide(); } else { $('#runningTasksCollapsible', page).show(); } for (var i = 0, length = tasks.length; i < length; i++) { var task = tasks[i]; html += '

'; html += task.Name + "
"; if (task.State == "Running") { var progress = (task.CurrentProgressPercentage || 0).toFixed(1); html += ''; html += '' + progress + '%'; html += ''; html += "" + progress + "%"; html += ''; } else if (task.State == "Cancelling") { html += '' + Globalize.translate('LabelStopping') + ''; } html += '

'; } $('#divRunningTasks', page).html(html).trigger('create'); }, renderUrls: function (page, systemInfo) { var url = ApiClient.serverAddress() + "/mediabrowser"; $('#bookmarkUrl', page).html(url).attr("href", url); if (systemInfo.WanAddress) { var externalUrl = systemInfo.WanAddress + "/mediabrowser"; var remoteAccessHtml = Globalize.translate('LabelRemoteAccessUrl').replace('{0}', '' + externalUrl + ''); $('.externalUrl', page).html(remoteAccessHtml).show().trigger('create'); } else { $('.externalUrl', page).hide(); } }, renderSupporterIcon: function (page, pluginSecurityInfo) { var imgUrl, text; if (pluginSecurityInfo.IsMBSupporter) { imgUrl = "css/images/supporter/supporterbadge.png"; text = "Thank you for supporting Media Browser."; $('.supporterIconContainer', page).html('' + text + ''); } else { imgUrl = "css/images/supporter/nonsupporterbadge.png"; text = "Please support Media Browser."; $('.supporterIconContainer', page).html('' + text + ''); } }, renderHasPendingRestart: function (page, hasPendingRestart) { $('#updateFail', page).hide(); if (!hasPendingRestart) { // Only check once every 30 mins if (DashboardPage.lastAppUpdateCheck && (new Date().getTime() - DashboardPage.lastAppUpdateCheck) < 1800000) { return; } DashboardPage.lastAppUpdateCheck = new Date().getTime(); ApiClient.getAvailableApplicationUpdate().done(function (packageInfo) { var version = packageInfo[0]; if (!version) { $('#pUpToDate', page).show(); $('#pUpdateNow', page).hide(); } else { $('#pUpToDate', page).hide(); $('#pUpdateNow', page).show(); $('#newVersionNumber', page).html(Globalize.translate('VersionXIsAvailableForDownload').replace('{0}', version.versionStr)); } }).fail(function () { $('#updateFail', page).show(); }); } else { $('#pUpToDate', page).hide(); $('#pUpdateNow', page).hide(); } }, renderPendingInstallations: function (page, systemInfo) { if (systemInfo.CompletedInstallations.length) { $('#collapsiblePendingInstallations', page).show(); } else { $('#collapsiblePendingInstallations', page).hide(); return; } var html = ''; for (var i = 0, length = systemInfo.CompletedInstallations.length; i < length; i++) { var update = systemInfo.CompletedInstallations[i]; html += '
' + update.Name + ' (' + update.Version + ')
'; } $('#pendingInstallations', page).html(html); }, renderPluginUpdateInfo: function (page, forceUpdate) { // Only check once every 30 mins if (!forceUpdate && DashboardPage.lastPluginUpdateCheck && (new Date().getTime() - DashboardPage.lastPluginUpdateCheck) < 1800000) { return; } DashboardPage.lastPluginUpdateCheck = new Date().getTime(); ApiClient.getAvailablePluginUpdates().done(function (updates) { var elem = $('#pPluginUpdates', page); if (updates.length) { elem.show(); } else { elem.hide(); return; } var html = ''; for (var i = 0, length = updates.length; i < length; i++) { var update = updates[i]; html += '

' + Globalize.translate('NewVersionOfSomethingAvailable').replace('{0}', update.name) + '

'; html += ''; } elem.html(html).trigger('create'); }).fail(function () { $('#updateFail', page).show(); }); }, installPluginUpdate: function (button) { $(button).buttonEnabled(false); var name = button.getAttribute('data-name'); var guid = button.getAttribute('data-guid'); var version = button.getAttribute('data-version'); var classification = button.getAttribute('data-classification'); Dashboard.showLoadingMsg(); ApiClient.installPlugin(name, guid, classification, version).done(function () { Dashboard.hideLoadingMsg(); }); }, updateApplication: function () { var page = $.mobile.activePage; $('#btnUpdateApplication', page).buttonEnabled(false); Dashboard.showLoadingMsg(); ApiClient.getScheduledTasks().done(function (tasks) { var task = tasks.filter(function (t) { return t.Key == DashboardPage.systemUpdateTaskKey; })[0]; ApiClient.startScheduledTask(task.Id).done(function () { DashboardPage.pollForInfo(page); Dashboard.hideLoadingMsg(); }); }); }, stopTask: function (id) { var page = $.mobile.activePage; ApiClient.stopScheduledTask(id).done(function () { DashboardPage.pollForInfo(page); }); }, restart: function () { Dashboard.confirm(Globalize.translate('MessageConfirmRestart'), Globalize.translate('HeaderRestart'), function (result) { if (result) { $('#btnRestartServer').buttonEnabled(false); $('#btnShutdown').buttonEnabled(false); Dashboard.restartServer(); } }); }, shutdown: function () { Dashboard.confirm(Globalize.translate('MessageConfirmShutdown'), Globalize.translate('HeaderShutdown'), function (result) { if (result) { $('#btnRestartServer').buttonEnabled(false); $('#btnShutdown').buttonEnabled(false); ApiClient.shutdownServer(); } }); } }; $(document).on('pagebeforeshow', "#dashboardPage", DashboardPage.onPageShow) .on('pagehide', "#dashboardPage", DashboardPage.onPageHide); (function ($, document, window) { var showOverlayTimeout; function onHoverOut() { if (showOverlayTimeout) { clearTimeout(showOverlayTimeout); showOverlayTimeout = null; } $('.posterItemOverlayTarget:visible', this).each(function () { var elem = this; $(this).animate({ "height": "0" }, "fast", function () { $(elem).hide(); }); }); $('.posterItemOverlayTarget:visible', this).stop().animate({ "height": "0" }, function () { $(this).hide(); }); } $.fn.createSessionItemMenus = function () { function onShowTimerExpired(elem) { if ($('.itemSelectionPanel:visible', elem).length) { return; } var innerElem = $('.posterItemOverlayTarget', elem); innerElem.show().each(function () { this.style.height = 0; }).animate({ "height": "100%" }, "fast"); } function onHoverIn() { if (showOverlayTimeout) { clearTimeout(showOverlayTimeout); showOverlayTimeout = null; } var elem = this; showOverlayTimeout = setTimeout(function () { onShowTimerExpired(elem); }, 1000); } // https://hacks.mozilla.org/2013/04/detecting-touch-its-the-why-not-the-how/ if (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)) { /* browser with either Touch Events of Pointer Events running on touch-capable device */ return this; } return this.off('.sessionItemMenu').on('mouseenter.sessionItemMenu', '.playingSession', onHoverIn) .on('mouseleave.sessionItemMenu', '.playingSession', onHoverOut); }; })(jQuery, document, window);