site.js 38 KB

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