site.js 36 KB

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