site.js 39 KB

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