site.js 38 KB

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