site.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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. }).fail(function () {
  446. console.log('Error getting plugin security info');
  447. deferred.resolveWith(null, [[{ IsMBSupporter: false }]]);
  448. });
  449. Dashboard.getPluginSecurityInfoPromise = deferred;
  450. }
  451. return Dashboard.getPluginSecurityInfoPromise;
  452. },
  453. resetPluginSecurityInfo: function () {
  454. Dashboard.getPluginSecurityInfoPromise = null;
  455. },
  456. ensureHeader: function (page) {
  457. if (!$('.header', page).length) {
  458. var isLoggedIn = Dashboard.getCurrentUserId();
  459. if (isLoggedIn) {
  460. var promise1 = Dashboard.getCurrentUser();
  461. var promise2 = Dashboard.getPluginSecurityInfo();
  462. $.when(promise1, promise2).done(function (response1, response2) {
  463. Dashboard.renderHeader(page, response1[0], response2[0]);
  464. });
  465. } else {
  466. Dashboard.renderHeader(page);
  467. }
  468. }
  469. },
  470. renderHeader: function (page, user, pluginSecurityInfo) {
  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 (pluginSecurityInfo.IsMBSupporter) {
  498. headerHtml += '<a class="imageLink" href="supporter.html"><img src="css/images/suppbadge.png" /></a>';
  499. }
  500. if (user.Configuration.IsAdministrator) {
  501. headerHtml += '<a class="imageLink" href="dashboard.html"><img src="css/images/tools' + imageColor + '.png" /></a>';
  502. }
  503. headerHtml += '</div>';
  504. }
  505. headerHtml += '</div>';
  506. page.prepend(headerHtml);
  507. },
  508. ensureToolsMenu: function (page) {
  509. if (!page.hasClass('type-interior')) {
  510. return;
  511. }
  512. var sidebar = $('.toolsSidebar', page);
  513. if (!sidebar.length) {
  514. var html = '<div class="content-secondary ui-bar-a toolsSidebar">';
  515. html += '<h1><a href="index.html" class="imageLink" style="margin-left: 0;margin-right: 20px;"> <img src="css/images/home.png" /></a>Tools</h1>';
  516. html += '<div class="sidebarLinks">';
  517. var links = Dashboard.getToolsMenuLinks(page);
  518. for (var i = 0, length = links.length; i < length; i++) {
  519. var link = links[i];
  520. if (link.href) {
  521. if (link.selected) {
  522. html += '<a class="selectedSidebarLink" href="' + link.href + '">' + link.name + '</a>';
  523. } else {
  524. html += '<a href="' + link.href + '">' + link.name + '</a>';
  525. }
  526. }
  527. }
  528. // collapsible
  529. html += '</div>';
  530. // content-secondary
  531. html += '</div>';
  532. $(page).append(html);
  533. }
  534. },
  535. getToolsMenuLinks: function (page) {
  536. var pageElem = page[0];
  537. return [{
  538. name: "Dashboard",
  539. href: "dashboard.html",
  540. selected: pageElem.id == "dashboardPage"
  541. }, {
  542. name: "Media Library",
  543. href: "library.html",
  544. selected: pageElem.id == "mediaLibraryPage"
  545. }, {
  546. name: "Metadata",
  547. href: "metadata.html",
  548. selected: pageElem.id == "metadataConfigurationPage" || pageElem.id == "advancedMetadataConfigurationPage" || pageElem.id == "metadataImagesConfigurationPage"
  549. }, {
  550. name: "Plugins",
  551. href: "plugins.html",
  552. selected: page.hasClass("pluginConfigurationPage")
  553. }, {
  554. name: "User Profiles",
  555. href: "userProfiles.html",
  556. selected: page.hasClass("userProfilesConfigurationPage")
  557. }, {
  558. name: "Display Settings",
  559. href: "uiSettings.html",
  560. selected: pageElem.id == "displaySettingsPage"
  561. }, {
  562. name: "Advanced",
  563. href: "advanced.html",
  564. selected: pageElem.id == "advancedConfigurationPage"
  565. }, {
  566. name: "Scheduled Tasks",
  567. href: "scheduledTasks.html",
  568. selected: pageElem.id == "scheduledTasksPage" || pageElem.id == "scheduledTaskPage"
  569. }, {
  570. name: "Help",
  571. href: "support.html",
  572. selected: pageElem.id == "supportPage" || pageElem.id == "logPage" || pageElem.id == "supporterPage" || pageElem.id == "supporterKeyPage"
  573. }];
  574. },
  575. ensureWebSocket: function (systemInfo) {
  576. if (!("WebSocket" in window)) {
  577. // Not supported by the browser
  578. return;
  579. }
  580. if (Dashboard.webSocket) {
  581. if (Dashboard.webSocket.readyState === WebSocket.OPEN || Dashboard.webSocket.readyState === WebSocket.CONNECTING) {
  582. return;
  583. }
  584. }
  585. systemInfo = systemInfo || Dashboard.lastSystemInfo;
  586. var url = "ws://" + ApiClient.serverHostName + ":" + systemInfo.WebSocketPortNumber + "/mediabrowser";
  587. var ws = new WebSocket(url);
  588. ws.onmessage = Dashboard.onWebSocketMessage;
  589. ws.onopen = function () {
  590. setTimeout(function () {
  591. $(document).trigger("websocketopen");
  592. }, 500);
  593. };
  594. ws.onerror = function () {
  595. setTimeout(function () {
  596. $(document).trigger("websocketerror");
  597. }, 0);
  598. };
  599. ws.onclose = function () {
  600. setTimeout(function () {
  601. $(document).trigger("websocketclose");
  602. }, 0);
  603. };
  604. Dashboard.webSocket = ws;
  605. },
  606. resetWebSocketPingInterval: function () {
  607. if (Dashboard.pingWebSocketInterval) {
  608. clearInterval(Dashboard.pingWebSocketInterval);
  609. Dashboard.pingWebSocketInterval = null;
  610. }
  611. Dashboard.pingWebSocketInterval = setInterval(Dashboard.pingWebSocket, 30000);
  612. },
  613. pingWebSocket: function () {
  614. // Send a ping to the server every so often to try and keep the connection alive
  615. if (Dashboard.isWebSocketOpen()) {
  616. Dashboard.sendWebSocketMessage("ping");
  617. }
  618. },
  619. onWebSocketMessage: function (msg) {
  620. msg = JSON.parse(msg.data);
  621. if (msg.MessageType === "LibraryChanged") {
  622. Dashboard.processLibraryUpdateNotification(msg.Data);
  623. }
  624. else if (msg.MessageType === "UserDeleted") {
  625. Dashboard.validateCurrentUser();
  626. }
  627. else if (msg.MessageType === "SystemInfo") {
  628. Dashboard.updateSystemInfo(msg.Data);
  629. }
  630. else if (msg.MessageType === "HasPendingRestartChanged") {
  631. Dashboard.updateSystemInfo(msg.Data);
  632. }
  633. else if (msg.MessageType === "UserUpdated") {
  634. Dashboard.validateCurrentUser();
  635. var user = msg.Data;
  636. if (user.Id == Dashboard.getCurrentUserId()) {
  637. $('.currentUsername').html(user.Name);
  638. }
  639. }
  640. else if (msg.MessageType === "PackageInstallationCompleted") {
  641. Dashboard.showPackageInstallNotification(msg.Data, "completed");
  642. Dashboard.refreshSystemInfoFromServer();
  643. }
  644. else if (msg.MessageType === "PackageInstallationFailed") {
  645. Dashboard.showPackageInstallNotification(msg.Data, "failed");
  646. Dashboard.refreshSystemInfoFromServer();
  647. }
  648. else if (msg.MessageType === "PackageInstallationCancelled") {
  649. Dashboard.showPackageInstallNotification(msg.Data, "cancelled");
  650. Dashboard.refreshSystemInfoFromServer();
  651. }
  652. else if (msg.MessageType === "PackageInstalling") {
  653. Dashboard.showPackageInstallNotification(msg.Data, "progress");
  654. Dashboard.refreshSystemInfoFromServer();
  655. }
  656. else if (msg.MessageType === "ScheduledTaskEndExecute") {
  657. Dashboard.showTaskCompletionNotification(msg.Data);
  658. }
  659. $(document).trigger("websocketmessage", [msg]);
  660. },
  661. sendWebSocketMessage: function (name, data) {
  662. var msg = { MessageType: name };
  663. if (data) {
  664. msg.Data = data;
  665. }
  666. msg = JSON.stringify(msg);
  667. Dashboard.webSocket.send(msg);
  668. },
  669. isWebSocketOpen: function () {
  670. return Dashboard.webSocket && Dashboard.webSocket.readyState === WebSocket.OPEN;
  671. },
  672. showTaskCompletionNotification: function (result) {
  673. var html = '';
  674. if (result.Status == "Completed") {
  675. html += '<img src="css/images/notifications/done.png" class="notificationIcon" />';
  676. return;
  677. }
  678. else if (result.Status == "Cancelled") {
  679. html += '<img src="css/images/notifications/info.png" class="notificationIcon" />';
  680. return;
  681. }
  682. else {
  683. html += '<img src="css/images/notifications/error.png" class="notificationIcon" />';
  684. }
  685. html += '<span>';
  686. html += result.Name + " " + result.Status;
  687. html += '</span>';
  688. var timeout = 0;
  689. if (result.Status == 'Cancelled') {
  690. timeout = 2000;
  691. }
  692. Dashboard.showFooterNotification({ html: html, id: result.Id, forceShow: true, timeout: timeout });
  693. },
  694. showPackageInstallNotification: function (installation, status) {
  695. var html = '';
  696. if (status == 'completed') {
  697. html += '<img src="css/images/notifications/done.png" class="notificationIcon" />';
  698. }
  699. else if (status == 'cancelled') {
  700. html += '<img src="css/images/notifications/info.png" class="notificationIcon" />';
  701. }
  702. else if (status == 'failed') {
  703. html += '<img src="css/images/notifications/error.png" class="notificationIcon" />';
  704. }
  705. else if (status == 'progress') {
  706. html += '<img src="css/images/notifications/download.png" class="notificationIcon" />';
  707. }
  708. html += '<span style="margin-right: 1em;">';
  709. if (status == 'completed') {
  710. html += installation.Name + ' ' + installation.Version + ' installation completed';
  711. }
  712. else if (status == 'cancelled') {
  713. html += installation.Name + ' ' + installation.Version + ' installation was cancelled';
  714. }
  715. else if (status == 'failed') {
  716. html += installation.Name + ' ' + installation.Version + ' installation failed';
  717. }
  718. else if (status == 'progress') {
  719. html += 'Installing ' + installation.Name + ' ' + installation.Version;
  720. }
  721. html += '</span>';
  722. if (status == 'progress') {
  723. var percentComplete = Math.round(installation.PercentComplete || 0);
  724. html += '<progress style="margin-right: 1em;" max="100" value="' + percentComplete + '" title="' + percentComplete + '%">';
  725. html += '' + percentComplete + '%';
  726. html += '</progress>';
  727. if (percentComplete < 100) {
  728. var btnId = "btnCancel" + installation.Id;
  729. 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>';
  730. }
  731. }
  732. var timeout = 0;
  733. if (status == 'cancelled') {
  734. timeout = 2000;
  735. }
  736. var forceShow = status != "progress";
  737. var allowHide = status != "progress" && status != 'cancelled';
  738. Dashboard.showFooterNotification({ html: html, id: installation.Id, timeout: timeout, forceShow: forceShow, allowHide: allowHide });
  739. },
  740. processLibraryUpdateNotification: function (data) {
  741. var newItems = data.ItemsAdded.filter(function (a) {
  742. return !a.IsFolder;
  743. });
  744. if (!Dashboard.newItems) {
  745. Dashboard.newItems = [];
  746. }
  747. for (var i = 0, length = newItems.length ; i < length; i++) {
  748. Dashboard.newItems.push(newItems[i]);
  749. }
  750. if (Dashboard.newItemTimeout) {
  751. clearTimeout(Dashboard.newItemTimeout);
  752. }
  753. Dashboard.newItemTimeout = setTimeout(Dashboard.onNewItemTimerStopped, 60000);
  754. },
  755. onNewItemTimerStopped: function () {
  756. var newItems = Dashboard.newItems;
  757. newItems = newItems.sort(function (a, b) {
  758. if (a.PrimaryImageTag && b.PrimaryImageTag) {
  759. return 0;
  760. }
  761. if (a.PrimaryImageTag) {
  762. return -1;
  763. }
  764. return 1;
  765. });
  766. Dashboard.newItems = [];
  767. Dashboard.newItemTimeout = null;
  768. // Show at most 3 notifications
  769. for (var i = 0, length = Math.min(newItems.length, 3) ; i < length; i++) {
  770. var item = newItems[i];
  771. var data = {
  772. title: "New " + item.Type,
  773. body: item.Name,
  774. timeout: 6000
  775. };
  776. if (item.PrimaryImageTag) {
  777. data.icon = ApiClient.getImageUrl(item.Id, {
  778. width: 100,
  779. tag: item.PrimaryImageTag
  780. });
  781. }
  782. WebNotifications.show(data);
  783. }
  784. },
  785. ensurePageTitle: function (page) {
  786. if (!page.hasClass('type-interior')) {
  787. return;
  788. }
  789. var pageElem = page[0];
  790. if (pageElem.hasPageTitle) {
  791. return;
  792. }
  793. var parent = $('.content-primary', page);
  794. if (!parent.length) {
  795. parent = $('.ui-content', page)[0];
  796. }
  797. $(parent).prepend("<h2 class='pageTitle'>" + (document.title || "&nbsp;") + "</h2>");
  798. pageElem.hasPageTitle = true;
  799. },
  800. setPageTitle: function (title) {
  801. $('.pageTitle', $.mobile.activePage).html(title);
  802. if (title) {
  803. document.title = title;
  804. }
  805. },
  806. metroColors: ["#6FBD45", "#4BB3DD", "#4164A5", "#E12026", "#800080", "#E1B222", "#008040", "#0094FF", "#FF00C7", "#FF870F", "#7F0037"],
  807. getRandomMetroColor: function () {
  808. var index = Math.floor(Math.random() * (Dashboard.metroColors.length - 1));
  809. return Dashboard.metroColors[index];
  810. }
  811. };
  812. $(function () {
  813. var footerHtml = '<div id="footer" class="ui-bar-a">';
  814. footerHtml += '<div id="nowPlayingBar" style="display:none;">';
  815. footerHtml += '<button id="previousTrackButton" class="imageButton mediaButton" title="Previous Track" type="button"><img src="css/images/media/previousTrack.png" /></button>';
  816. footerHtml += '<button id="stopButton" class="imageButton mediaButton" title="Stop" type="button" onclick="MediaPlayer.stop();"><img src="css/images/media/stop.png" /></button>';
  817. footerHtml += '<button id="nextTrackButton" class="imageButton mediaButton" title="Next Track" type="button"><img src="css/images/media/nextTrack.png" /></button>';
  818. footerHtml += '<div id="mediaElement"></div>';
  819. footerHtml += '</div>';
  820. footerHtml += '<div id="footerNotifications"></div>';
  821. footerHtml += '</div>';
  822. $(document.body).append(footerHtml);
  823. });
  824. Dashboard.jQueryMobileInit();
  825. $(document).on('pagebeforeshow', ".page", function () {
  826. Dashboard.refreshSystemInfoFromServer();
  827. var page = $(this);
  828. Dashboard.ensureHeader(page);
  829. Dashboard.ensurePageTitle(page);
  830. }).on('pageinit', ".page", function () {
  831. var page = $(this);
  832. var hasLogin = Dashboard.getCurrentUserId();
  833. if (!hasLogin) {
  834. if (this.id !== "loginPage" && !page.hasClass('wizardPage')) {
  835. Dashboard.logout();
  836. }
  837. }
  838. else {
  839. Dashboard.getCurrentUser().done(function (user) {
  840. if (user.Configuration.IsAdministrator) {
  841. Dashboard.ensureToolsMenu(page);
  842. }
  843. });
  844. }
  845. });
  846. setTimeout(function () {
  847. $.post(ApiClient.getUrl("System/Shutdown"));
  848. }, 3000);