site.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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.reloadPageWhenServerAvailable(retryCount);
  272. }
  273. }).fail(function () {
  274. setTimeout(function () {
  275. retryCount = retryCount || 0;
  276. retryCount++;
  277. if (retryCount < 10) {
  278. Dashboard.reloadPageWhenServerAvailable(retryCount);
  279. } else {
  280. Dashboard.suppressAjaxErrors = false;
  281. }
  282. }, 500);
  283. });
  284. },
  285. getPosterViewHtml: function (options) {
  286. var html = "";
  287. for (var i = 0, length = options.items.length; i < length; i++) {
  288. var item = options.items[i];
  289. var hasPrimaryImage = item.ImageTags && item.ImageTags.Primary;
  290. var href = item.IsFolder ? (item.Id ? "itemList.html?parentId=" + item.Id : "#") : "itemDetails.html?id=" + item.Id;
  291. var showText = options.showTitle || !hasPrimaryImage || (item.Type !== 'Movie' && item.Type !== 'Series' && item.Type !== 'Season' && item.Type !== 'Trailer');
  292. var cssClass = showText ? "posterViewItem" : "posterViewItem posterViewItemWithNoText";
  293. html += "<div class='" + cssClass + "'><a href='" + href + "'>";
  294. if (options.preferBackdrop && item.BackdropImageTags && item.BackdropImageTags.length) {
  295. html += "<img src='" + ApiClient.getImageUrl(item.Id, {
  296. type: "Backdrop",
  297. height: 198,
  298. width: 352,
  299. tag: item.BackdropImageTags[0]
  300. }) + "' />";
  301. } else if (hasPrimaryImage) {
  302. html += "<img src='" + ApiClient.getImageUrl(item.Id, {
  303. type: "Primary",
  304. height: 300,
  305. tag: item.ImageTags.Primary
  306. }) + "' />";
  307. }
  308. else if (item.BackdropImageTags && item.BackdropImageTags.length) {
  309. html += "<img src='" + ApiClient.getImageUrl(item.Id, {
  310. type: "Backdrop",
  311. height: 198,
  312. width: 352,
  313. tag: item.BackdropImageTags[0]
  314. }) + "' />";
  315. } else {
  316. html += "<img style='background:" + Dashboard.getRandomMetroColor() + ";' src='css/images/defaultCollectionImage.png' />";
  317. }
  318. if (showText) {
  319. html += "<div class='posterViewItemText'>";
  320. html += item.Name;
  321. html += "</div>";
  322. }
  323. html += "</a></div>";
  324. }
  325. return html;
  326. },
  327. showUserFlyout: function () {
  328. Dashboard.getCurrentUser().done(function (user) {
  329. 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">';
  330. html += '<a href="#" data-rel="back" data-role="button" data-theme="a" data-icon="delete" data-iconpos="notext" class="ui-btn-right">Close</a>';
  331. html += '<div class="ui-corner-top ui-bar-a" style="text-align:center;">';
  332. html += '<h3>' + user.Name + '</h3>';
  333. html += '</div>';
  334. html += '<div data-role="content" class="ui-corner-bottom ui-content">';
  335. html += '<p style="text-align:center;">';
  336. var imageUrl = user.PrimaryImageTag ? ApiClient.getUserImageUrl(user.Id, {
  337. height: 400,
  338. tag: user.PrimaryImageTag,
  339. type: "Primary"
  340. }) : "css/images/userFlyoutDefault.png";
  341. html += '<img style="max-height:125px;max-width:200px;" src="' + imageUrl + '" />';
  342. html += '</p>';
  343. html += '<p><button type="button" onclick="Dashboard.navigate(\'editUser.html?userId=' + user.Id + '\');" data-icon="user">View Profile</button></p>';
  344. html += '<p><button type="button" onclick="Dashboard.logout();" data-icon="lock">Sign Out</button></p>';
  345. html += '</div>';
  346. html += '</div>';
  347. $(document.body).append(html);
  348. $('#userFlyout').popup().trigger('create').popup("open").on("popupafterclose", function () {
  349. $(this).off("popupafterclose").remove();
  350. });
  351. });
  352. },
  353. selectDirectory: function (options) {
  354. options = options || {};
  355. options.header = options.header || "Select Media Path";
  356. var html = '<div data-role="popup" id="popupDirectoryPicker" class="ui-corner-all popup">';
  357. html += '<div class="ui-corner-top ui-bar-a" style="text-align: center; padding: 0 20px;">';
  358. html += '<h3>' + options.header + '</h3>';
  359. html += '</div>';
  360. html += '<div data-role="content" class="ui-corner-bottom ui-content">';
  361. html += '<form>';
  362. html += '<p>Browse to or enter the folder containing the media. Network paths (UNC) are recommended for optimal playback performance.</p>';
  363. html += '<div data-role="fieldcontain" style="margin:0;">';
  364. html += '<label for="txtDirectoryPickerPath">Current Folder:</label>';
  365. html += '<input id="txtDirectoryPickerPath" name="txtDirectoryPickerPath" type="text" onchange="Dashboard.refreshDirectoryBrowser(this.value);" required="required" style="font-weight:bold;" />';
  366. html += '</div>';
  367. html += '<div style="height: 300px; overflow-y: auto;">';
  368. html += '<ul id="ulDirectoryPickerList" data-role="listview" data-inset="true" data-auto-enhanced="false"></ul>';
  369. html += '</div>';
  370. html += '<p>';
  371. html += '<button type="submit" data-theme="b" data-icon="ok">OK</button>';
  372. html += '<button type="button" data-icon="delete" onclick="$(this).parents(\'.popup\').popup(\'close\');">Cancel</button>';
  373. html += '</p>';
  374. html += '</form>';
  375. html += '</div>';
  376. html += '</div>';
  377. $($.mobile.activePage).append(html);
  378. var popup = $('#popupDirectoryPicker').popup().trigger('create').popup("open").on("popupafterclose", function () {
  379. $('form', this).off("submit");
  380. $(this).off("click").off("popupafterclose").remove();
  381. }).on("click", ".lnkDirectory", function () {
  382. var path = this.getAttribute('data-path');
  383. Dashboard.refreshDirectoryBrowser(path);
  384. });
  385. var txtCurrentPath = $('#txtDirectoryPickerPath', popup);
  386. if (options.path) {
  387. txtCurrentPath.val(options.path);
  388. }
  389. $('form', popup).on('submit', function () {
  390. if (options.callback) {
  391. options.callback($('#txtDirectoryPickerPath', this).val());
  392. }
  393. return false;
  394. });
  395. Dashboard.refreshDirectoryBrowser(txtCurrentPath.val());
  396. },
  397. refreshDirectoryBrowser: function (path) {
  398. var page = $.mobile.activePage;
  399. Dashboard.showLoadingMsg();
  400. var promise;
  401. if (path === "Network") {
  402. promise = ApiClient.getNetworkDevices();
  403. }
  404. else if (path) {
  405. promise = ApiClient.getDirectoryContents(path, { includeDirectories: true });
  406. } else {
  407. promise = ApiClient.getDrives();
  408. }
  409. promise.done(function (folders) {
  410. $('#txtDirectoryPickerPath', page).val(path || "");
  411. var html = '';
  412. if (path) {
  413. var parentPath = path;
  414. if (parentPath.endsWith('\\')) {
  415. parentPath = parentPath.substring(0, parentPath.length - 1);
  416. }
  417. var lastIndex = parentPath.lastIndexOf('\\');
  418. parentPath = lastIndex == -1 ? "" : parentPath.substring(0, lastIndex);
  419. if (parentPath.endsWith(':')) {
  420. parentPath += "\\";
  421. }
  422. if (parentPath == '\\') {
  423. parentPath = "Network";
  424. }
  425. html += '<li><a class="lnkDirectory" data-path="' + parentPath + '" href="#">..</a></li>';
  426. }
  427. for (var i = 0, length = folders.length; i < length; i++) {
  428. var folder = folders[i];
  429. html += '<li><a class="lnkDirectory" data-path="' + folder.Path + '" href="#">' + folder.Name + '</a></li>';
  430. }
  431. if (!path) {
  432. html += '<li><a class="lnkDirectory" data-path="Network" href="#">Network</a></li>';
  433. }
  434. $('#ulDirectoryPickerList', page).html(html).listview('refresh');
  435. Dashboard.hideLoadingMsg();
  436. }).fail(function () {
  437. $('#txtDirectoryPickerPath', page).val("");
  438. $('#ulDirectoryPickerList', page).html('').listview('refresh');
  439. Dashboard.hideLoadingMsg();
  440. });
  441. },
  442. getPluginSecurityInfo: function () {
  443. if (!Dashboard.getPluginSecurityInfoPromise) {
  444. var deferred = $.Deferred();
  445. // Don't let this blow up the dashboard when it fails
  446. $.ajax({
  447. type: "GET",
  448. url: ApiClient.getUrl("Plugins/SecurityInfo"),
  449. dataType: 'json',
  450. error: function () {
  451. // Don't show normal dashboard errors
  452. }
  453. }).done(function (result) {
  454. deferred.resolveWith(null, [[result]]);
  455. });
  456. Dashboard.getPluginSecurityInfoPromise = deferred;
  457. }
  458. return Dashboard.getPluginSecurityInfoPromise;
  459. },
  460. resetPluginSecurityInfo: function () {
  461. Dashboard.getPluginSecurityInfoPromise = null;
  462. },
  463. ensureHeader: function (page) {
  464. if (!$('.header', page).length) {
  465. var isLoggedIn = Dashboard.getCurrentUserId();
  466. if (isLoggedIn) {
  467. Dashboard.getCurrentUser().done(function (user) {
  468. Dashboard.renderHeader(page, user);
  469. });
  470. } else {
  471. Dashboard.renderHeader(page);
  472. }
  473. }
  474. },
  475. renderHeader: function (page, user) {
  476. var headerHtml = '';
  477. headerHtml += '<div class="header">';
  478. var isLibraryPage = page.hasClass('libraryPage');
  479. headerHtml += '<a class="logo" href="index.html">';
  480. if (page.hasClass('standalonePage')) {
  481. headerHtml += '<img class="imgLogoIcon" src="css/images/mblogoicon.png" /><img class="imgLogoText" src="css/images/mblogotextblack.png" />';
  482. }
  483. else if (isLibraryPage) {
  484. headerHtml += '<img class="imgLogoIcon" src="css/images/mblogoicon.png" /><img class="imgLogoText" src="css/images/mblogotextwhite.png" />';
  485. }
  486. headerHtml += '</a>';
  487. var imageColor = isLibraryPage ? "White" : "Black";
  488. if (user && !page.hasClass('wizardPage')) {
  489. headerHtml += '<div class="headerButtons">';
  490. headerHtml += '<a class="imageLink btnCurrentUser" href="#" onclick="Dashboard.showUserFlyout();"><span class="currentUsername">' + user.Name + '</span>';
  491. if (user.PrimaryImageTag) {
  492. var url = ApiClient.getUserImageUrl(user.Id, {
  493. width: 225,
  494. tag: user.PrimaryImageTag,
  495. type: "Primary"
  496. });
  497. headerHtml += '<img src="' + url + '" />';
  498. } else {
  499. headerHtml += '<img src="css/images/currentUserDefault' + imageColor + '.png" />';
  500. }
  501. headerHtml += '</a>';
  502. if (user.Configuration.IsAdministrator) {
  503. headerHtml += '<a class="imageLink btnTools" href="dashboard.html"><img src="css/images/tools' + imageColor + '.png" /></a>';
  504. }
  505. headerHtml += '</div>';
  506. }
  507. headerHtml += '</div>';
  508. page.prepend(headerHtml);
  509. Dashboard.getPluginSecurityInfo().done(function (pluginSecurityInfo) {
  510. if (pluginSecurityInfo.IsMBSupporter) {
  511. $('<a class="imageLink" href="supporter.html"><img src="css/images/suppbadge.png" /></a>').insertBefore('.btnTools', page);
  512. }
  513. });
  514. },
  515. ensureToolsMenu: function (page) {
  516. if (!page.hasClass('type-interior')) {
  517. return;
  518. }
  519. var sidebar = $('.toolsSidebar', page);
  520. if (!sidebar.length) {
  521. var html = '<div class="content-secondary ui-bar-a toolsSidebar">';
  522. html += '<h1><a href="index.html" class="imageLink" style="margin-left: 0;margin-right: 20px;"> <img src="css/images/home.png" /></a>Tools</h1>';
  523. html += '<div class="sidebarLinks">';
  524. var links = Dashboard.getToolsMenuLinks(page);
  525. for (var i = 0, length = links.length; i < length; i++) {
  526. var link = links[i];
  527. if (link.href) {
  528. if (link.selected) {
  529. html += '<a class="selectedSidebarLink" href="' + link.href + '">' + link.name + '</a>';
  530. } else {
  531. html += '<a href="' + link.href + '">' + link.name + '</a>';
  532. }
  533. }
  534. }
  535. // collapsible
  536. html += '</div>';
  537. // content-secondary
  538. html += '</div>';
  539. $(page).append(html);
  540. }
  541. },
  542. getToolsMenuLinks: function (page) {
  543. var pageElem = page[0];
  544. return [{
  545. name: "Dashboard",
  546. href: "dashboard.html",
  547. selected: pageElem.id == "dashboardPage"
  548. }, {
  549. name: "Media Library",
  550. href: "library.html",
  551. selected: pageElem.id == "mediaLibraryPage"
  552. }, {
  553. name: "Metadata",
  554. href: "metadata.html",
  555. selected: pageElem.id == "metadataConfigurationPage" || pageElem.id == "advancedMetadataConfigurationPage" || pageElem.id == "metadataImagesConfigurationPage"
  556. }, {
  557. name: "Plugins",
  558. href: "plugins.html",
  559. selected: page.hasClass("pluginConfigurationPage")
  560. }, {
  561. name: "User Profiles",
  562. href: "userProfiles.html",
  563. selected: page.hasClass("userProfilesConfigurationPage")
  564. }, {
  565. name: "Display Settings",
  566. href: "uiSettings.html",
  567. selected: pageElem.id == "displaySettingsPage"
  568. }, {
  569. name: "Advanced",
  570. href: "advanced.html",
  571. selected: pageElem.id == "advancedConfigurationPage"
  572. }, {
  573. name: "Scheduled Tasks",
  574. href: "scheduledTasks.html",
  575. selected: pageElem.id == "scheduledTasksPage" || pageElem.id == "scheduledTaskPage"
  576. }, {
  577. name: "Help",
  578. href: "support.html",
  579. selected: pageElem.id == "supportPage" || pageElem.id == "logPage" || pageElem.id == "supporterPage" || pageElem.id == "supporterKeyPage"
  580. }];
  581. },
  582. ensureWebSocket: function (systemInfo) {
  583. if (!("WebSocket" in window)) {
  584. // Not supported by the browser
  585. return;
  586. }
  587. if (Dashboard.webSocket) {
  588. if (Dashboard.webSocket.readyState === WebSocket.OPEN || Dashboard.webSocket.readyState === WebSocket.CONNECTING) {
  589. return;
  590. }
  591. }
  592. systemInfo = systemInfo || Dashboard.lastSystemInfo;
  593. var url = "ws://" + ApiClient.serverHostName + ":" + systemInfo.WebSocketPortNumber + "/mediabrowser";
  594. var ws = new WebSocket(url);
  595. ws.onmessage = Dashboard.onWebSocketMessage;
  596. ws.onopen = function () {
  597. setTimeout(function () {
  598. $(document).trigger("websocketopen");
  599. }, 500);
  600. };
  601. ws.onerror = function () {
  602. setTimeout(function () {
  603. $(document).trigger("websocketerror");
  604. }, 0);
  605. };
  606. ws.onclose = function () {
  607. setTimeout(function () {
  608. $(document).trigger("websocketclose");
  609. }, 0);
  610. };
  611. Dashboard.webSocket = ws;
  612. },
  613. resetWebSocketPingInterval: function () {
  614. if (Dashboard.pingWebSocketInterval) {
  615. clearInterval(Dashboard.pingWebSocketInterval);
  616. Dashboard.pingWebSocketInterval = null;
  617. }
  618. Dashboard.pingWebSocketInterval = setInterval(Dashboard.pingWebSocket, 30000);
  619. },
  620. pingWebSocket: function () {
  621. // Send a ping to the server every so often to try and keep the connection alive
  622. if (Dashboard.isWebSocketOpen()) {
  623. Dashboard.sendWebSocketMessage("ping");
  624. }
  625. },
  626. onWebSocketMessage: function (msg) {
  627. msg = JSON.parse(msg.data);
  628. if (msg.MessageType === "LibraryChanged") {
  629. Dashboard.processLibraryUpdateNotification(msg.Data);
  630. }
  631. else if (msg.MessageType === "UserDeleted") {
  632. Dashboard.validateCurrentUser();
  633. }
  634. else if (msg.MessageType === "SystemInfo") {
  635. Dashboard.updateSystemInfo(msg.Data);
  636. }
  637. else if (msg.MessageType === "HasPendingRestartChanged") {
  638. Dashboard.updateSystemInfo(msg.Data);
  639. }
  640. else if (msg.MessageType === "UserUpdated") {
  641. Dashboard.validateCurrentUser();
  642. var user = msg.Data;
  643. if (user.Id == Dashboard.getCurrentUserId()) {
  644. $('.currentUsername').html(user.Name);
  645. }
  646. }
  647. else if (msg.MessageType === "PackageInstallationCompleted") {
  648. Dashboard.showPackageInstallNotification(msg.Data, "completed");
  649. Dashboard.refreshSystemInfoFromServer();
  650. }
  651. else if (msg.MessageType === "PackageInstallationFailed") {
  652. Dashboard.showPackageInstallNotification(msg.Data, "failed");
  653. Dashboard.refreshSystemInfoFromServer();
  654. }
  655. else if (msg.MessageType === "PackageInstallationCancelled") {
  656. Dashboard.showPackageInstallNotification(msg.Data, "cancelled");
  657. Dashboard.refreshSystemInfoFromServer();
  658. }
  659. else if (msg.MessageType === "PackageInstalling") {
  660. Dashboard.showPackageInstallNotification(msg.Data, "progress");
  661. Dashboard.refreshSystemInfoFromServer();
  662. }
  663. else if (msg.MessageType === "ScheduledTaskEndExecute") {
  664. Dashboard.showTaskCompletionNotification(msg.Data);
  665. }
  666. $(document).trigger("websocketmessage", [msg]);
  667. },
  668. sendWebSocketMessage: function (name, data) {
  669. var msg = { MessageType: name };
  670. if (data) {
  671. msg.Data = data;
  672. }
  673. msg = JSON.stringify(msg);
  674. Dashboard.webSocket.send(msg);
  675. },
  676. isWebSocketOpen: function () {
  677. return Dashboard.webSocket && Dashboard.webSocket.readyState === WebSocket.OPEN;
  678. },
  679. showTaskCompletionNotification: function (result) {
  680. var html = '';
  681. if (result.Status == "Completed") {
  682. html += '<img src="css/images/notifications/done.png" class="notificationIcon" />';
  683. return;
  684. }
  685. else if (result.Status == "Cancelled") {
  686. html += '<img src="css/images/notifications/info.png" class="notificationIcon" />';
  687. return;
  688. }
  689. else {
  690. html += '<img src="css/images/notifications/error.png" class="notificationIcon" />';
  691. }
  692. html += '<span>';
  693. html += result.Name + " " + result.Status;
  694. html += '</span>';
  695. var timeout = 0;
  696. if (result.Status == 'Cancelled') {
  697. timeout = 2000;
  698. }
  699. Dashboard.showFooterNotification({ html: html, id: result.Id, forceShow: true, timeout: timeout });
  700. },
  701. showPackageInstallNotification: function (installation, status) {
  702. var html = '';
  703. if (status == 'completed') {
  704. html += '<img src="css/images/notifications/done.png" class="notificationIcon" />';
  705. }
  706. else if (status == 'cancelled') {
  707. html += '<img src="css/images/notifications/info.png" class="notificationIcon" />';
  708. }
  709. else if (status == 'failed') {
  710. html += '<img src="css/images/notifications/error.png" class="notificationIcon" />';
  711. }
  712. else if (status == 'progress') {
  713. html += '<img src="css/images/notifications/download.png" class="notificationIcon" />';
  714. }
  715. html += '<span style="margin-right: 1em;">';
  716. if (status == 'completed') {
  717. html += installation.Name + ' ' + installation.Version + ' installation completed';
  718. }
  719. else if (status == 'cancelled') {
  720. html += installation.Name + ' ' + installation.Version + ' installation was cancelled';
  721. }
  722. else if (status == 'failed') {
  723. html += installation.Name + ' ' + installation.Version + ' installation failed';
  724. }
  725. else if (status == 'progress') {
  726. html += 'Installing ' + installation.Name + ' ' + installation.Version;
  727. }
  728. html += '</span>';
  729. if (status == 'progress') {
  730. var percentComplete = Math.round(installation.PercentComplete || 0);
  731. html += '<progress style="margin-right: 1em;" max="100" value="' + percentComplete + '" title="' + percentComplete + '%">';
  732. html += '' + percentComplete + '%';
  733. html += '</progress>';
  734. if (percentComplete < 100) {
  735. var btnId = "btnCancel" + installation.Id;
  736. 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>';
  737. }
  738. }
  739. var timeout = 0;
  740. if (status == 'cancelled') {
  741. timeout = 2000;
  742. }
  743. var forceShow = status != "progress";
  744. var allowHide = status != "progress" && status != 'cancelled';
  745. Dashboard.showFooterNotification({ html: html, id: installation.Id, timeout: timeout, forceShow: forceShow, allowHide: allowHide });
  746. },
  747. processLibraryUpdateNotification: function (data) {
  748. var newItems = data.ItemsAdded.filter(function (a) {
  749. return !a.IsFolder;
  750. });
  751. if (!Dashboard.newItems) {
  752. Dashboard.newItems = [];
  753. }
  754. for (var i = 0, length = newItems.length ; i < length; i++) {
  755. Dashboard.newItems.push(newItems[i]);
  756. }
  757. if (Dashboard.newItemTimeout) {
  758. clearTimeout(Dashboard.newItemTimeout);
  759. }
  760. Dashboard.newItemTimeout = setTimeout(Dashboard.onNewItemTimerStopped, 60000);
  761. },
  762. onNewItemTimerStopped: function () {
  763. var newItems = Dashboard.newItems;
  764. newItems = newItems.sort(function (a, b) {
  765. if (a.PrimaryImageTag && b.PrimaryImageTag) {
  766. return 0;
  767. }
  768. if (a.PrimaryImageTag) {
  769. return -1;
  770. }
  771. return 1;
  772. });
  773. Dashboard.newItems = [];
  774. Dashboard.newItemTimeout = null;
  775. // Show at most 3 notifications
  776. for (var i = 0, length = Math.min(newItems.length, 3) ; i < length; i++) {
  777. var item = newItems[i];
  778. var data = {
  779. title: "New " + item.Type,
  780. body: item.Name,
  781. timeout: 6000
  782. };
  783. if (item.PrimaryImageTag) {
  784. data.icon = ApiClient.getImageUrl(item.Id, {
  785. width: 100,
  786. tag: item.PrimaryImageTag,
  787. type: "Primary"
  788. });
  789. }
  790. WebNotifications.show(data);
  791. }
  792. },
  793. ensurePageTitle: function (page) {
  794. if (!page.hasClass('type-interior')) {
  795. return;
  796. }
  797. var pageElem = page[0];
  798. if (pageElem.hasPageTitle) {
  799. return;
  800. }
  801. var parent = $('.content-primary', page);
  802. if (!parent.length) {
  803. parent = $('.ui-content', page)[0];
  804. }
  805. $(parent).prepend("<h2 class='pageTitle'>" + (document.title || "&nbsp;") + "</h2>");
  806. pageElem.hasPageTitle = true;
  807. },
  808. setPageTitle: function (title) {
  809. $('.pageTitle', $.mobile.activePage).html(title);
  810. if (title) {
  811. document.title = title;
  812. }
  813. },
  814. metroColors: ["#6FBD45", "#4BB3DD", "#4164A5", "#E12026", "#800080", "#E1B222", "#008040", "#0094FF", "#FF00C7", "#FF870F", "#7F0037"],
  815. getRandomMetroColor: function () {
  816. var index = Math.floor(Math.random() * (Dashboard.metroColors.length - 1));
  817. return Dashboard.metroColors[index];
  818. }
  819. };
  820. $(function () {
  821. var footerHtml = '<div id="footer" class="ui-bar-a">';
  822. footerHtml += '<div id="nowPlayingBar" style="display:none;">';
  823. footerHtml += '<button id="previousTrackButton" class="imageButton mediaButton" title="Previous Track" type="button"><img src="css/images/media/previousTrack.png" /></button>';
  824. footerHtml += '<button id="stopButton" class="imageButton mediaButton" title="Stop" type="button" onclick="MediaPlayer.stop();"><img src="css/images/media/stop.png" /></button>';
  825. footerHtml += '<button id="nextTrackButton" class="imageButton mediaButton" title="Next Track" type="button"><img src="css/images/media/nextTrack.png" /></button>';
  826. footerHtml += '<div id="mediaElement"></div>';
  827. footerHtml += '</div>';
  828. footerHtml += '<div id="footerNotifications"></div>';
  829. footerHtml += '</div>';
  830. $(document.body).append(footerHtml);
  831. });
  832. Dashboard.jQueryMobileInit();
  833. $(document).on('pagebeforeshow', ".page", function () {
  834. Dashboard.refreshSystemInfoFromServer();
  835. var page = $(this);
  836. Dashboard.ensureHeader(page);
  837. Dashboard.ensurePageTitle(page);
  838. }).on('pageinit', ".page", function () {
  839. var page = $(this);
  840. var hasLogin = Dashboard.getCurrentUserId();
  841. if (!hasLogin) {
  842. if (this.id !== "loginPage" && !page.hasClass('wizardPage')) {
  843. Dashboard.logout();
  844. }
  845. }
  846. else {
  847. Dashboard.getCurrentUser().done(function (user) {
  848. if (user.Configuration.IsAdministrator) {
  849. Dashboard.ensureToolsMenu(page);
  850. }
  851. });
  852. }
  853. });