site.js 38 KB

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