site.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. $.ajaxSetup({
  2. crossDomain: true,
  3. error: function (event, jqxhr, settings, exception) {
  4. Dashboard.hideLoadingMsg();
  5. if (!Dashboard.suppressAjaxErrors) {
  6. setTimeout(function () {
  7. var msg = event.getResponseHeader("X-Application-Error-Code") || Dashboard.defaultErrorMessage;
  8. Dashboard.showError(msg);
  9. }, 500);
  10. }
  11. }
  12. });
  13. $.support.cors = true;
  14. $(document).one('click', WebNotifications.requestPermission);
  15. var Dashboard = {
  16. jQueryMobileInit: function () {
  17. //$.mobile.defaultPageTransition = 'slide';
  18. // Page
  19. //$.mobile.page.prototype.options.theme = "a";
  20. //$.mobile.page.prototype.options.headerTheme = "a";
  21. //$.mobile.page.prototype.options.contentTheme = "a";
  22. //$.mobile.page.prototype.options.footerTheme = "a";
  23. //$.mobile.button.prototype.options.theme = "c";
  24. $.mobile.listview.prototype.options.dividerTheme = "b";
  25. $.mobile.popup.prototype.options.theme = "c";
  26. //$.mobile.collapsible.prototype.options.contentTheme = "a";
  27. },
  28. getCurrentUser: function () {
  29. if (!Dashboard.getUserPromise) {
  30. Dashboard.getUserPromise = ApiClient.getUser(Dashboard.getCurrentUserId()).fail(Dashboard.logout);
  31. }
  32. return Dashboard.getUserPromise;
  33. },
  34. validateCurrentUser: function () {
  35. Dashboard.getUserPromise = null;
  36. if (Dashboard.getCurrentUserId()) {
  37. Dashboard.getCurrentUser();
  38. }
  39. var header = $('.header', $.mobile.activePage);
  40. if (header.length) {
  41. // Re-render the header
  42. header.remove();
  43. Dashboard.ensureHeader($.mobile.activePage);
  44. }
  45. },
  46. getCurrentUserId: function () {
  47. var userId = localStorage.getItem("userId");
  48. if (!userId) {
  49. var autoLoginUserId = getParameterByName('u');
  50. if (autoLoginUserId) {
  51. userId = autoLoginUserId;
  52. localStorage.setItem("userId", userId);
  53. }
  54. }
  55. return userId;
  56. },
  57. setCurrentUser: function (userId) {
  58. localStorage.setItem("userId", userId);
  59. Dashboard.getUserPromise = null;
  60. },
  61. logout: function () {
  62. localStorage.removeItem("userId");
  63. Dashboard.getUserPromise = null;
  64. window.location = "login.html";
  65. },
  66. showError: function (message) {
  67. $.mobile.loading('show', {
  68. theme: "e",
  69. text: message,
  70. textonly: true,
  71. textVisible: true
  72. });
  73. setTimeout(function () {
  74. $.mobile.loading('hide');
  75. }, 2000);
  76. },
  77. alert: function (message) {
  78. $.mobile.loading('show', {
  79. theme: "e",
  80. text: message,
  81. textonly: true,
  82. textVisible: true
  83. });
  84. setTimeout(function () {
  85. $.mobile.loading('hide');
  86. }, 2000);
  87. },
  88. updateSystemInfo: function (info) {
  89. var isFirstLoad = !Dashboard.lastSystemInfo;
  90. Dashboard.lastSystemInfo = info;
  91. Dashboard.ensureWebSocket(info);
  92. if (!Dashboard.initialServerVersion) {
  93. Dashboard.initialServerVersion = info.Version;
  94. }
  95. if (info.HasPendingRestart) {
  96. Dashboard.hideDashboardVersionWarning();
  97. Dashboard.showServerRestartWarning();
  98. } else {
  99. Dashboard.hideServerRestartWarning();
  100. if (Dashboard.initialServerVersion != info.Version) {
  101. Dashboard.showDashboardVersionWarning();
  102. }
  103. }
  104. if (isFirstLoad) {
  105. Dashboard.showFailedAssemblies(info.FailedPluginAssemblies);
  106. }
  107. Dashboard.showInProgressInstallations(info.InProgressInstallations);
  108. },
  109. showFailedAssemblies: function (failedAssemblies) {
  110. for (var i = 0, length = failedAssemblies.length; i < length; i++) {
  111. var assembly = failedAssemblies[i];
  112. var html = '<img src="css/images/notifications/error.png" class="notificationIcon" />';
  113. var index = assembly.lastIndexOf('\\');
  114. if (index != -1) {
  115. assembly = assembly.substring(index + 1);
  116. }
  117. html += '<span>';
  118. html += assembly + " failed to load.";
  119. html += '</span>';
  120. Dashboard.showFooterNotification({ html: html });
  121. }
  122. },
  123. showInProgressInstallations: function (installations) {
  124. installations = installations || [];
  125. for (var i = 0, length = installations.length; i < length; i++) {
  126. var installation = installations[i];
  127. var percent = installation.PercentComplete || 0;
  128. if (percent < 100) {
  129. Dashboard.showPackageInstallNotification(installation, "progress");
  130. }
  131. }
  132. if (installations.length) {
  133. Dashboard.ensureInstallRefreshInterval();
  134. } else {
  135. Dashboard.stopInstallRefreshInterval();
  136. }
  137. },
  138. ensureInstallRefreshInterval: function () {
  139. if (!Dashboard.installRefreshInterval) {
  140. if (Dashboard.isWebSocketOpen()) {
  141. Dashboard.sendWebSocketMessage("SystemInfoStart", "0,350");
  142. }
  143. Dashboard.installRefreshInterval = 1;
  144. }
  145. },
  146. stopInstallRefreshInterval: function () {
  147. if (Dashboard.installRefreshInterval) {
  148. if (Dashboard.isWebSocketOpen()) {
  149. Dashboard.sendWebSocketMessage("SystemInfoStop");
  150. }
  151. Dashboard.installRefreshInterval = null;
  152. }
  153. },
  154. cancelInstallation: function (id) {
  155. ApiClient.cancelPackageInstallation(id).always(Dashboard.refreshSystemInfoFromServer);
  156. },
  157. showServerRestartWarning: function () {
  158. var html = '<span style="margin-right: 1em;">Please restart Media Browser Server to finish updating.</span>';
  159. html += '<button type="button" data-icon="refresh" onclick="Dashboard.restartServer();" data-theme="b" data-inline="true" data-mini="true">Restart Server</button>';
  160. Dashboard.showFooterNotification({ id: "serverRestartWarning", html: html, forceShow: true, allowHide: false });
  161. },
  162. hideServerRestartWarning: function () {
  163. $('#serverRestartWarning').remove();
  164. },
  165. showDashboardVersionWarning: function () {
  166. var html = '<span style="margin-right: 1em;">Please refresh this page to receive new updates from the server.</span>';
  167. html += '<button type="button" data-icon="refresh" onclick="Dashboard.reloadPage();" data-theme="b" data-inline="true" data-mini="true">Refresh Page</button>';
  168. Dashboard.showFooterNotification({ id: "dashboardVersionWarning", html: html, forceShow: true, allowHide: false });
  169. },
  170. reloadPage: function () {
  171. window.location.href = window.location.href;
  172. },
  173. hideDashboardVersionWarning: function () {
  174. $('#dashboardVersionWarning').remove();
  175. },
  176. showFooterNotification: function (options) {
  177. var removeOnHide = !options.id;
  178. options.id = options.id || "notification" + new Date().getTime() + parseInt(Math.random());
  179. var parentElem = $('#footerNotifications');
  180. var elem = $('#' + options.id, parentElem);
  181. if (!elem.length) {
  182. elem = $('<p id="' + options.id + '" class="footerNotification"></p>').appendTo(parentElem);
  183. }
  184. var onclick = removeOnHide ? "$(\"#" + options.id + "\").remove();" : "$(\"#" + options.id + "\").hide();";
  185. if (options.allowHide !== false) {
  186. options.html += "<span style='margin-left: 1em;'><button type='button' onclick='" + onclick + "' data-icon='delete' data-iconpos='notext' data-mini='true' data-inline='true' data-theme='a'>Hide</button></span>";
  187. }
  188. if (options.forceShow) {
  189. elem.show();
  190. }
  191. elem.html(options.html).trigger('create');
  192. if (options.timeout) {
  193. setTimeout(function () {
  194. if (removeOnHide) {
  195. elem.remove();
  196. } else {
  197. elem.hide();
  198. }
  199. }, options.timeout);
  200. }
  201. },
  202. getConfigurationPageUrl: function (name) {
  203. return "ConfigurationPage?name=" + encodeURIComponent(name);
  204. },
  205. navigate: function (url, preserveQueryString) {
  206. var queryString = window.location.search;
  207. if (preserveQueryString && queryString) {
  208. url += queryString;
  209. }
  210. $.mobile.changePage(url);
  211. },
  212. showLoadingMsg: function () {
  213. $.mobile.showPageLoadingMsg();
  214. },
  215. hideLoadingMsg: function () {
  216. $.mobile.hidePageLoadingMsg();
  217. },
  218. processPluginConfigurationUpdateResult: function () {
  219. Dashboard.hideLoadingMsg();
  220. Dashboard.alert("Settings saved.");
  221. },
  222. defaultErrorMessage: "There was an error processing the request.",
  223. processServerConfigurationUpdateResult: function (result) {
  224. Dashboard.hideLoadingMsg();
  225. Dashboard.alert("Settings saved.");
  226. },
  227. confirm: function (message, title, callback) {
  228. $('#confirmFlyout').popup("close").remove();
  229. var html = '<div data-role="popup" id="confirmFlyout" style="max-width:500px;" class="ui-corner-all">';
  230. html += '<div class="ui-corner-top ui-bar-a" style="text-align:center;">';
  231. html += '<h3>' + title + '</h3>';
  232. html += '</div>';
  233. html += '<div data-role="content" class="ui-corner-bottom ui-content">';
  234. html += '<div style="padding: 1em .25em;margin: 0;">';
  235. html += message;
  236. html += '</div>';
  237. html += '<p><button type="button" data-icon="ok" onclick="$(\'#confirmFlyout\')[0].confirm=true;$(\'#confirmFlyout\').popup(\'close\');" data-theme="b">Ok</button></p>';
  238. html += '<p><button type="button" data-icon="delete" onclick="$(\'#confirmFlyout\').popup(\'close\');" data-theme="a">Cancel</button></p>';
  239. html += '</div>';
  240. html += '</div>';
  241. $(document.body).append(html);
  242. $('#confirmFlyout').popup().trigger('create').popup("open").on("popupafterclose", function () {
  243. if (callback) {
  244. callback(this.confirm == true);
  245. }
  246. $(this).off("popupafterclose").remove();
  247. });
  248. },
  249. refreshSystemInfoFromServer: function () {
  250. ApiClient.getSystemInfo().done(function (info) {
  251. Dashboard.updateSystemInfo(info);
  252. });
  253. },
  254. restartServer: function () {
  255. Dashboard.suppressAjaxErrors = true;
  256. Dashboard.showLoadingMsg();
  257. ApiClient.performPendingRestart().done(function () {
  258. setTimeout(function () {
  259. Dashboard.reloadPageWhenServerAvailable();
  260. }, 250);
  261. }).fail(function () {
  262. Dashboard.suppressAjaxErrors = false;
  263. });
  264. },
  265. reloadPageWhenServerAvailable: function (retryCount) {
  266. ApiClient.getSystemInfo().done(function (info) {
  267. // If this is back to false, the restart completed
  268. if (!info.HasPendingRestart) {
  269. Dashboard.reloadPage();
  270. } else {
  271. Dashboard.retryReload(retryCount);
  272. }
  273. }).fail(function() {
  274. Dashboard.retryReload(retryCount);
  275. });
  276. },
  277. retryReload: function (retryCount) {
  278. setTimeout(function () {
  279. retryCount = retryCount || 0;
  280. retryCount++;
  281. if (retryCount < 10) {
  282. Dashboard.reloadPageWhenServerAvailable(retryCount);
  283. } else {
  284. Dashboard.suppressAjaxErrors = false;
  285. }
  286. }, 500);
  287. },
  288. getPosterViewHtml: function (options) {
  289. var html = "";
  290. for (var i = 0, length = options.items.length; i < length; i++) {
  291. var item = options.items[i];
  292. var hasPrimaryImage = item.ImageTags && item.ImageTags.Primary;
  293. var href = item.IsFolder ? (item.Id ? "itemList.html?parentId=" + item.Id : "#") : "itemDetails.html?id=" + item.Id;
  294. var showText = options.showTitle || !hasPrimaryImage || (item.Type !== 'Movie' && item.Type !== 'Series' && item.Type !== 'Season' && item.Type !== 'Trailer');
  295. var cssClass = showText ? "posterViewItem" : "posterViewItem posterViewItemWithNoText";
  296. html += "<div class='" + cssClass + "'><a href='" + href + "'>";
  297. if (options.preferBackdrop && item.BackdropImageTags && item.BackdropImageTags.length) {
  298. html += "<img src='" + ApiClient.getImageUrl(item.Id, {
  299. type: "Backdrop",
  300. height: 198,
  301. width: 352,
  302. tag: item.BackdropImageTags[0]
  303. }) + "' />";
  304. } else if (hasPrimaryImage) {
  305. html += "<img src='" + ApiClient.getImageUrl(item.Id, {
  306. type: "Primary",
  307. height: 300,
  308. tag: item.ImageTags.Primary
  309. }) + "' />";
  310. }
  311. else if (item.BackdropImageTags && item.BackdropImageTags.length) {
  312. html += "<img src='" + ApiClient.getImageUrl(item.Id, {
  313. type: "Backdrop",
  314. height: 198,
  315. width: 352,
  316. tag: item.BackdropImageTags[0]
  317. }) + "' />";
  318. } else {
  319. html += "<img style='background:" + Dashboard.getRandomMetroColor() + ";' src='css/images/defaultCollectionImage.png' />";
  320. }
  321. if (showText) {
  322. html += "<div class='posterViewItemText'>";
  323. html += item.Name;
  324. html += "</div>";
  325. }
  326. html += "</a></div>";
  327. }
  328. return html;
  329. },
  330. showUserFlyout: function () {
  331. Dashboard.getCurrentUser().done(function (user) {
  332. var html = '<div data-role="popup" id="userFlyout" style="max-width:400px;margin-top:50px;margin-right:20px;" class="ui-corner-all" data-position-to=".btnCurrentUser:visible">';
  333. html += '<a href="#" data-rel="back" data-role="button" data-theme="a" data-icon="delete" data-iconpos="notext" class="ui-btn-right">Close</a>';
  334. html += '<div class="ui-corner-top ui-bar-a" style="text-align:center;">';
  335. html += '<h3>' + user.Name + '</h3>';
  336. html += '</div>';
  337. html += '<div data-role="content" class="ui-corner-bottom ui-content">';
  338. html += '<p style="text-align:center;">';
  339. var imageUrl = user.PrimaryImageTag ? ApiClient.getUserImageUrl(user.Id, {
  340. height: 400,
  341. tag: user.PrimaryImageTag,
  342. type: "Primary"
  343. }) : "css/images/userFlyoutDefault.png";
  344. html += '<img style="max-height:125px;max-width:200px;" src="' + imageUrl + '" />';
  345. html += '</p>';
  346. html += '<p><button type="button" onclick="Dashboard.navigate(\'editUser.html?userId=' + user.Id + '\');" data-icon="user">View Profile</button></p>';
  347. html += '<p><button type="button" onclick="Dashboard.logout();" data-icon="lock">Sign Out</button></p>';
  348. html += '</div>';
  349. html += '</div>';
  350. $(document.body).append(html);
  351. $('#userFlyout').popup().trigger('create').popup("open").on("popupafterclose", function () {
  352. $(this).off("popupafterclose").remove();
  353. });
  354. });
  355. },
  356. selectDirectory: function (options) {
  357. options = options || {};
  358. options.header = options.header || "Select Media Path";
  359. var html = '<div data-role="popup" id="popupDirectoryPicker" class="ui-corner-all popup">';
  360. html += '<div class="ui-corner-top ui-bar-a" style="text-align: center; padding: 0 20px;">';
  361. html += '<h3>' + options.header + '</h3>';
  362. html += '</div>';
  363. html += '<div data-role="content" class="ui-corner-bottom ui-content">';
  364. html += '<form>';
  365. html += '<p>Browse to or enter the folder containing the media. Network paths (UNC) are recommended for optimal playback performance.</p>';
  366. html += '<div data-role="fieldcontain" style="margin:0;">';
  367. html += '<label for="txtDirectoryPickerPath">Current Folder:</label>';
  368. html += '<input id="txtDirectoryPickerPath" name="txtDirectoryPickerPath" type="text" onchange="Dashboard.refreshDirectoryBrowser(this.value);" required="required" style="font-weight:bold;" />';
  369. html += '</div>';
  370. html += '<div style="height: 300px; overflow-y: auto;">';
  371. html += '<ul id="ulDirectoryPickerList" data-role="listview" data-inset="true" data-auto-enhanced="false"></ul>';
  372. html += '</div>';
  373. html += '<p>';
  374. html += '<button type="submit" data-theme="b" data-icon="ok">OK</button>';
  375. html += '<button type="button" data-icon="delete" onclick="$(this).parents(\'.popup\').popup(\'close\');">Cancel</button>';
  376. html += '</p>';
  377. html += '</form>';
  378. html += '</div>';
  379. html += '</div>';
  380. $($.mobile.activePage).append(html);
  381. var popup = $('#popupDirectoryPicker').popup().trigger('create').popup("open").on("popupafterclose", function () {
  382. $('form', this).off("submit");
  383. $(this).off("click").off("popupafterclose").remove();
  384. }).on("click", ".lnkDirectory", function () {
  385. var path = this.getAttribute('data-path');
  386. Dashboard.refreshDirectoryBrowser(path);
  387. });
  388. var txtCurrentPath = $('#txtDirectoryPickerPath', popup);
  389. if (options.path) {
  390. txtCurrentPath.val(options.path);
  391. }
  392. $('form', popup).on('submit', function () {
  393. if (options.callback) {
  394. options.callback($('#txtDirectoryPickerPath', this).val());
  395. }
  396. return false;
  397. });
  398. Dashboard.refreshDirectoryBrowser(txtCurrentPath.val());
  399. },
  400. refreshDirectoryBrowser: function (path) {
  401. var page = $.mobile.activePage;
  402. Dashboard.showLoadingMsg();
  403. var promise;
  404. if (path === "Network") {
  405. promise = ApiClient.getNetworkDevices();
  406. }
  407. else if (path) {
  408. promise = ApiClient.getDirectoryContents(path, { includeDirectories: true });
  409. } else {
  410. promise = ApiClient.getDrives();
  411. }
  412. promise.done(function (folders) {
  413. $('#txtDirectoryPickerPath', page).val(path || "");
  414. var html = '';
  415. if (path) {
  416. var parentPath = path;
  417. if (parentPath.endsWith('\\')) {
  418. parentPath = parentPath.substring(0, parentPath.length - 1);
  419. }
  420. var lastIndex = parentPath.lastIndexOf('\\');
  421. parentPath = lastIndex == -1 ? "" : parentPath.substring(0, lastIndex);
  422. if (parentPath.endsWith(':')) {
  423. parentPath += "\\";
  424. }
  425. if (parentPath == '\\') {
  426. parentPath = "Network";
  427. }
  428. html += '<li><a class="lnkDirectory" data-path="' + parentPath + '" href="#">..</a></li>';
  429. }
  430. for (var i = 0, length = folders.length; i < length; i++) {
  431. var folder = folders[i];
  432. html += '<li><a class="lnkDirectory" data-path="' + folder.Path + '" href="#">' + folder.Name + '</a></li>';
  433. }
  434. if (!path) {
  435. html += '<li><a class="lnkDirectory" data-path="Network" href="#">Network</a></li>';
  436. }
  437. $('#ulDirectoryPickerList', page).html(html).listview('refresh');
  438. Dashboard.hideLoadingMsg();
  439. }).fail(function () {
  440. $('#txtDirectoryPickerPath', page).val("");
  441. $('#ulDirectoryPickerList', page).html('').listview('refresh');
  442. Dashboard.hideLoadingMsg();
  443. });
  444. },
  445. getPluginSecurityInfo: function () {
  446. if (!Dashboard.getPluginSecurityInfoPromise) {
  447. var deferred = $.Deferred();
  448. // Don't let this blow up the dashboard when it fails
  449. $.ajax({
  450. type: "GET",
  451. url: ApiClient.getUrl("Plugins/SecurityInfo"),
  452. dataType: 'json',
  453. error: function () {
  454. // Don't show normal dashboard errors
  455. }
  456. }).done(function (result) {
  457. deferred.resolveWith(null, [[result]]);
  458. });
  459. Dashboard.getPluginSecurityInfoPromise = deferred;
  460. }
  461. return Dashboard.getPluginSecurityInfoPromise;
  462. },
  463. resetPluginSecurityInfo: function () {
  464. Dashboard.getPluginSecurityInfoPromise = null;
  465. },
  466. ensureHeader: function (page) {
  467. if (!$('.header', page).length) {
  468. var isLoggedIn = Dashboard.getCurrentUserId();
  469. if (isLoggedIn) {
  470. Dashboard.getCurrentUser().done(function (user) {
  471. Dashboard.renderHeader(page, user);
  472. });
  473. } else {
  474. Dashboard.renderHeader(page);
  475. }
  476. }
  477. },
  478. renderHeader: function (page, user) {
  479. var headerHtml = '';
  480. headerHtml += '<div class="header">';
  481. var isLibraryPage = page.hasClass('libraryPage');
  482. headerHtml += '<a class="logo" href="index.html">';
  483. if (page.hasClass('standalonePage')) {
  484. headerHtml += '<img class="imgLogoIcon" src="css/images/mblogoicon.png" /><img class="imgLogoText" src="css/images/mblogotextblack.png" />';
  485. }
  486. else if (isLibraryPage) {
  487. headerHtml += '<img class="imgLogoIcon" src="css/images/mblogoicon.png" /><img class="imgLogoText" src="css/images/mblogotextwhite.png" />';
  488. }
  489. headerHtml += '</a>';
  490. var imageColor = isLibraryPage ? "White" : "Black";
  491. if (user && !page.hasClass('wizardPage')) {
  492. headerHtml += '<div class="headerButtons">';
  493. headerHtml += '<a class="imageLink btnCurrentUser" href="#" onclick="Dashboard.showUserFlyout();"><span class="currentUsername">' + user.Name + '</span>';
  494. if (user.PrimaryImageTag) {
  495. var url = ApiClient.getUserImageUrl(user.Id, {
  496. width: 225,
  497. tag: user.PrimaryImageTag,
  498. type: "Primary"
  499. });
  500. headerHtml += '<img src="' + url + '" />';
  501. } else {
  502. headerHtml += '<img src="css/images/currentUserDefault' + imageColor + '.png" />';
  503. }
  504. headerHtml += '</a>';
  505. if (user.Configuration.IsAdministrator) {
  506. headerHtml += '<a class="imageLink btnTools" href="dashboard.html"><img src="css/images/tools' + imageColor + '.png" /></a>';
  507. }
  508. headerHtml += '</div>';
  509. }
  510. headerHtml += '</div>';
  511. page.prepend(headerHtml);
  512. Dashboard.getPluginSecurityInfo().done(function (pluginSecurityInfo) {
  513. if (pluginSecurityInfo.IsMBSupporter) {
  514. $('<a class="imageLink" href="supporter.html"><img src="css/images/suppbadge.png" /></a>').insertBefore('.btnTools', page);
  515. }
  516. });
  517. },
  518. ensureToolsMenu: function (page) {
  519. if (!page.hasClass('type-interior')) {
  520. return;
  521. }
  522. var sidebar = $('.toolsSidebar', page);
  523. if (!sidebar.length) {
  524. var html = '<div class="content-secondary ui-bar-a toolsSidebar">';
  525. html += '<h1><a href="index.html" class="imageLink" style="margin-left: 0;margin-right: 20px;"> <img src="css/images/home.png" /></a>Tools</h1>';
  526. html += '<div class="sidebarLinks">';
  527. var links = Dashboard.getToolsMenuLinks(page);
  528. for (var i = 0, length = links.length; i < length; i++) {
  529. var link = links[i];
  530. if (link.href) {
  531. if (link.selected) {
  532. html += '<a class="selectedSidebarLink" href="' + link.href + '">' + link.name + '</a>';
  533. } else {
  534. html += '<a href="' + link.href + '">' + link.name + '</a>';
  535. }
  536. }
  537. }
  538. // collapsible
  539. html += '</div>';
  540. // content-secondary
  541. html += '</div>';
  542. $(page).append(html);
  543. }
  544. },
  545. getToolsMenuLinks: function (page) {
  546. var pageElem = page[0];
  547. return [{
  548. name: "Dashboard",
  549. href: "dashboard.html",
  550. selected: pageElem.id == "dashboardPage"
  551. }, {
  552. name: "Media Library",
  553. href: "library.html",
  554. selected: pageElem.id == "mediaLibraryPage"
  555. }, {
  556. name: "Metadata",
  557. href: "metadata.html",
  558. selected: pageElem.id == "metadataConfigurationPage" || pageElem.id == "advancedMetadataConfigurationPage" || pageElem.id == "metadataImagesConfigurationPage"
  559. }, {
  560. name: "Plugins",
  561. href: "plugins.html",
  562. selected: page.hasClass("pluginConfigurationPage")
  563. }, {
  564. name: "User Profiles",
  565. href: "userProfiles.html",
  566. selected: page.hasClass("userProfilesConfigurationPage")
  567. }, {
  568. name: "Display Settings",
  569. href: "uiSettings.html",
  570. selected: pageElem.id == "displaySettingsPage"
  571. }, {
  572. name: "Advanced",
  573. href: "advanced.html",
  574. selected: pageElem.id == "advancedConfigurationPage"
  575. }, {
  576. name: "Scheduled Tasks",
  577. href: "scheduledTasks.html",
  578. selected: pageElem.id == "scheduledTasksPage" || pageElem.id == "scheduledTaskPage"
  579. }, {
  580. name: "Help",
  581. href: "support.html",
  582. selected: pageElem.id == "supportPage" || pageElem.id == "logPage" || pageElem.id == "supporterPage" || pageElem.id == "supporterKeyPage" || pageElem.id == "aboutPage"
  583. }];
  584. },
  585. ensureWebSocket: function (systemInfo) {
  586. if (!("WebSocket" in window)) {
  587. // Not supported by the browser
  588. return;
  589. }
  590. if (Dashboard.webSocket) {
  591. if (Dashboard.webSocket.readyState === WebSocket.OPEN || Dashboard.webSocket.readyState === WebSocket.CONNECTING) {
  592. return;
  593. }
  594. }
  595. systemInfo = systemInfo || Dashboard.lastSystemInfo;
  596. var url = "ws://" + ApiClient.serverHostName + ":" + systemInfo.WebSocketPortNumber + "/mediabrowser";
  597. var ws = new WebSocket(url);
  598. ws.onmessage = Dashboard.onWebSocketMessage;
  599. ws.onopen = function () {
  600. setTimeout(function () {
  601. $(document).trigger("websocketopen");
  602. }, 500);
  603. };
  604. ws.onerror = function () {
  605. setTimeout(function () {
  606. $(document).trigger("websocketerror");
  607. }, 0);
  608. };
  609. ws.onclose = function () {
  610. setTimeout(function () {
  611. $(document).trigger("websocketclose");
  612. }, 0);
  613. };
  614. Dashboard.webSocket = ws;
  615. },
  616. resetWebSocketPingInterval: function () {
  617. if (Dashboard.pingWebSocketInterval) {
  618. clearInterval(Dashboard.pingWebSocketInterval);
  619. Dashboard.pingWebSocketInterval = null;
  620. }
  621. Dashboard.pingWebSocketInterval = setInterval(Dashboard.pingWebSocket, 30000);
  622. },
  623. pingWebSocket: function () {
  624. // Send a ping to the server every so often to try and keep the connection alive
  625. if (Dashboard.isWebSocketOpen()) {
  626. Dashboard.sendWebSocketMessage("ping");
  627. }
  628. },
  629. onWebSocketMessage: function (msg) {
  630. msg = JSON.parse(msg.data);
  631. if (msg.MessageType === "LibraryChanged") {
  632. Dashboard.processLibraryUpdateNotification(msg.Data);
  633. }
  634. else if (msg.MessageType === "UserDeleted") {
  635. Dashboard.validateCurrentUser();
  636. }
  637. else if (msg.MessageType === "SystemInfo") {
  638. Dashboard.updateSystemInfo(msg.Data);
  639. }
  640. else if (msg.MessageType === "HasPendingRestartChanged") {
  641. Dashboard.updateSystemInfo(msg.Data);
  642. }
  643. else if (msg.MessageType === "UserUpdated") {
  644. Dashboard.validateCurrentUser();
  645. var user = msg.Data;
  646. if (user.Id == Dashboard.getCurrentUserId()) {
  647. $('.currentUsername').html(user.Name);
  648. }
  649. }
  650. else if (msg.MessageType === "PackageInstallationCompleted") {
  651. Dashboard.showPackageInstallNotification(msg.Data, "completed");
  652. Dashboard.refreshSystemInfoFromServer();
  653. }
  654. else if (msg.MessageType === "PackageInstallationFailed") {
  655. Dashboard.showPackageInstallNotification(msg.Data, "failed");
  656. Dashboard.refreshSystemInfoFromServer();
  657. }
  658. else if (msg.MessageType === "PackageInstallationCancelled") {
  659. Dashboard.showPackageInstallNotification(msg.Data, "cancelled");
  660. Dashboard.refreshSystemInfoFromServer();
  661. }
  662. else if (msg.MessageType === "PackageInstalling") {
  663. Dashboard.showPackageInstallNotification(msg.Data, "progress");
  664. Dashboard.refreshSystemInfoFromServer();
  665. }
  666. else if (msg.MessageType === "ScheduledTaskEndExecute") {
  667. Dashboard.showTaskCompletionNotification(msg.Data);
  668. }
  669. $(document).trigger("websocketmessage", [msg]);
  670. },
  671. sendWebSocketMessage: function (name, data) {
  672. var msg = { MessageType: name };
  673. if (data) {
  674. msg.Data = data;
  675. }
  676. msg = JSON.stringify(msg);
  677. Dashboard.webSocket.send(msg);
  678. },
  679. isWebSocketOpen: function () {
  680. return Dashboard.webSocket && Dashboard.webSocket.readyState === WebSocket.OPEN;
  681. },
  682. showTaskCompletionNotification: function (result) {
  683. var html = '';
  684. if (result.Status == "Completed") {
  685. html += '<img src="css/images/notifications/done.png" class="notificationIcon" />';
  686. return;
  687. }
  688. else if (result.Status == "Cancelled") {
  689. html += '<img src="css/images/notifications/info.png" class="notificationIcon" />';
  690. return;
  691. }
  692. else {
  693. html += '<img src="css/images/notifications/error.png" class="notificationIcon" />';
  694. }
  695. html += '<span>';
  696. html += result.Name + " " + result.Status;
  697. html += '</span>';
  698. var timeout = 0;
  699. if (result.Status == 'Cancelled') {
  700. timeout = 2000;
  701. }
  702. Dashboard.showFooterNotification({ html: html, id: result.Id, forceShow: true, timeout: timeout });
  703. },
  704. showPackageInstallNotification: function (installation, status) {
  705. var html = '';
  706. if (status == 'completed') {
  707. html += '<img src="css/images/notifications/done.png" class="notificationIcon" />';
  708. }
  709. else if (status == 'cancelled') {
  710. html += '<img src="css/images/notifications/info.png" class="notificationIcon" />';
  711. }
  712. else if (status == 'failed') {
  713. html += '<img src="css/images/notifications/error.png" class="notificationIcon" />';
  714. }
  715. else if (status == 'progress') {
  716. html += '<img src="css/images/notifications/download.png" class="notificationIcon" />';
  717. }
  718. html += '<span style="margin-right: 1em;">';
  719. if (status == 'completed') {
  720. html += installation.Name + ' ' + installation.Version + ' installation completed';
  721. }
  722. else if (status == 'cancelled') {
  723. html += installation.Name + ' ' + installation.Version + ' installation was cancelled';
  724. }
  725. else if (status == 'failed') {
  726. html += installation.Name + ' ' + installation.Version + ' installation failed';
  727. }
  728. else if (status == 'progress') {
  729. html += 'Installing ' + installation.Name + ' ' + installation.Version;
  730. }
  731. html += '</span>';
  732. if (status == 'progress') {
  733. var percentComplete = Math.round(installation.PercentComplete || 0);
  734. html += '<progress style="margin-right: 1em;" max="100" value="' + percentComplete + '" title="' + percentComplete + '%">';
  735. html += '' + percentComplete + '%';
  736. html += '</progress>';
  737. if (percentComplete < 100) {
  738. var btnId = "btnCancel" + installation.Id;
  739. html += '<button id="' + btnId + '" type="button" data-icon="delete" onclick="$(\'' + btnId + '\').button(\'disable\');Dashboard.cancelInstallation(\'' + installation.Id + '\');" data-theme="b" data-inline="true" data-mini="true">Cancel</button>';
  740. }
  741. }
  742. var timeout = 0;
  743. if (status == 'cancelled') {
  744. timeout = 2000;
  745. }
  746. var forceShow = status != "progress";
  747. var allowHide = status != "progress" && status != 'cancelled';
  748. Dashboard.showFooterNotification({ html: html, id: installation.Id, timeout: timeout, forceShow: forceShow, allowHide: allowHide });
  749. },
  750. processLibraryUpdateNotification: function (data) {
  751. var newItems = data.ItemsAdded.filter(function (a) {
  752. return !a.IsFolder;
  753. });
  754. if (!Dashboard.newItems) {
  755. Dashboard.newItems = [];
  756. }
  757. for (var i = 0, length = newItems.length ; i < length; i++) {
  758. Dashboard.newItems.push(newItems[i]);
  759. }
  760. if (Dashboard.newItemTimeout) {
  761. clearTimeout(Dashboard.newItemTimeout);
  762. }
  763. Dashboard.newItemTimeout = setTimeout(Dashboard.onNewItemTimerStopped, 60000);
  764. },
  765. onNewItemTimerStopped: function () {
  766. var newItems = Dashboard.newItems;
  767. newItems = newItems.sort(function (a, b) {
  768. if (a.PrimaryImageTag && b.PrimaryImageTag) {
  769. return 0;
  770. }
  771. if (a.PrimaryImageTag) {
  772. return -1;
  773. }
  774. return 1;
  775. });
  776. Dashboard.newItems = [];
  777. Dashboard.newItemTimeout = null;
  778. // Show at most 3 notifications
  779. for (var i = 0, length = Math.min(newItems.length, 3) ; i < length; i++) {
  780. var item = newItems[i];
  781. var data = {
  782. title: "New " + item.Type,
  783. body: item.Name,
  784. timeout: 6000
  785. };
  786. if (item.PrimaryImageTag) {
  787. data.icon = ApiClient.getImageUrl(item.Id, {
  788. width: 100,
  789. tag: item.PrimaryImageTag,
  790. type: "Primary"
  791. });
  792. }
  793. WebNotifications.show(data);
  794. }
  795. },
  796. ensurePageTitle: function (page) {
  797. if (!page.hasClass('type-interior')) {
  798. return;
  799. }
  800. var pageElem = page[0];
  801. if (pageElem.hasPageTitle) {
  802. return;
  803. }
  804. var parent = $('.content-primary', page);
  805. if (!parent.length) {
  806. parent = $('.ui-content', page)[0];
  807. }
  808. $(parent).prepend("<h2 class='pageTitle'>" + (document.title || "&nbsp;") + "</h2>");
  809. pageElem.hasPageTitle = true;
  810. },
  811. setPageTitle: function (title) {
  812. $('.pageTitle', $.mobile.activePage).html(title);
  813. if (title) {
  814. document.title = title;
  815. }
  816. },
  817. metroColors: ["#6FBD45", "#4BB3DD", "#4164A5", "#E12026", "#800080", "#E1B222", "#008040", "#0094FF", "#FF00C7", "#FF870F", "#7F0037"],
  818. getRandomMetroColor: function () {
  819. var index = Math.floor(Math.random() * (Dashboard.metroColors.length - 1));
  820. return Dashboard.metroColors[index];
  821. }
  822. };
  823. $(function () {
  824. var footerHtml = '<div id="footer" class="ui-bar-a">';
  825. footerHtml += '<div id="nowPlayingBar" style="display:none;">';
  826. footerHtml += '<button id="previousTrackButton" class="imageButton mediaButton" title="Previous Track" type="button"><img src="css/images/media/previousTrack.png" /></button>';
  827. footerHtml += '<button id="stopButton" class="imageButton mediaButton" title="Stop" type="button" onclick="MediaPlayer.stop();"><img src="css/images/media/stop.png" /></button>';
  828. footerHtml += '<button id="nextTrackButton" class="imageButton mediaButton" title="Next Track" type="button"><img src="css/images/media/nextTrack.png" /></button>';
  829. footerHtml += '<div id="mediaElement"></div>';
  830. footerHtml += '</div>';
  831. footerHtml += '<div id="footerNotifications"></div>';
  832. footerHtml += '</div>';
  833. $(document.body).append(footerHtml);
  834. });
  835. Dashboard.jQueryMobileInit();
  836. $(document).on('pagebeforeshow', ".page", function () {
  837. Dashboard.refreshSystemInfoFromServer();
  838. var page = $(this);
  839. Dashboard.ensureHeader(page);
  840. Dashboard.ensurePageTitle(page);
  841. }).on('pageinit', ".page", function () {
  842. var page = $(this);
  843. var hasLogin = Dashboard.getCurrentUserId();
  844. if (!hasLogin) {
  845. if (this.id !== "loginPage" && !page.hasClass('wizardPage')) {
  846. Dashboard.logout();
  847. }
  848. }
  849. else {
  850. Dashboard.getCurrentUser().done(function (user) {
  851. if (user.Configuration.IsAdministrator) {
  852. Dashboard.ensureToolsMenu(page);
  853. }
  854. });
  855. }
  856. });