site.js 39 KB

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