site.js 36 KB

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