apps.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. /* global Handlebars */
  2. Handlebars.registerHelper('score', function() {
  3. if(this.score) {
  4. var score = Math.round( this.score * 10 );
  5. var imageName = 'rating/s' + score + '.svg';
  6. return new Handlebars.SafeString('<img src="' + OC.imagePath('core', imageName) + '">');
  7. }
  8. return new Handlebars.SafeString('');
  9. });
  10. Handlebars.registerHelper('level', function() {
  11. if(typeof this.level !== 'undefined') {
  12. if(this.level === 200) {
  13. return new Handlebars.SafeString('<span class="official icon-checkmark">' + t('settings', 'Official') + '</span>');
  14. }
  15. }
  16. });
  17. OC.Settings = OC.Settings || {};
  18. OC.Settings.Apps = OC.Settings.Apps || {
  19. markedOptions: {},
  20. setupGroupsSelect: function($elements) {
  21. OC.Settings.setupGroupsSelect($elements, {
  22. placeholder: t('core', 'All')
  23. });
  24. },
  25. State: {
  26. currentCategory: null,
  27. currentCategoryElements: null,
  28. apps: null,
  29. $updateNotification: null,
  30. availableUpdates: 0
  31. },
  32. loadCategories: function() {
  33. if (this._loadCategoriesCall) {
  34. this._loadCategoriesCall.abort();
  35. }
  36. var categories = [
  37. {displayName: t('settings', 'Your apps'), ident: 'installed', id: '0'},
  38. {displayName: t('settings', 'Enabled apps'), ident: 'enabled', id: '1'},
  39. {displayName: t('settings', 'Disabled apps'), ident: 'disabled', id: '2'}
  40. ];
  41. var source = $("#categories-template").html();
  42. var template = Handlebars.compile(source);
  43. var html = template(categories);
  44. $('#apps-categories').html(html);
  45. OC.Settings.Apps.loadCategory($('#app-navigation').attr('data-category'));
  46. this._loadCategoriesCall = $.ajax(OC.generateUrl('settings/apps/categories'), {
  47. data:{},
  48. type:'GET',
  49. success:function (jsondata) {
  50. var html = template(jsondata);
  51. var updateCategory = $.grep(jsondata, function(element, index) {
  52. return element.ident === 'updates'
  53. });
  54. $('#apps-categories').html(html);
  55. $('#app-category-' + OC.Settings.Apps.State.currentCategory).addClass('active');
  56. if (updateCategory.length === 1) {
  57. OC.Settings.Apps.State.availableUpdates = updateCategory[0].counter;
  58. OC.Settings.Apps.refreshUpdateCounter();
  59. }
  60. },
  61. complete: function() {
  62. $('#app-navigation').removeClass('icon-loading');
  63. }
  64. });
  65. },
  66. loadCategory: function(categoryId) {
  67. if (OC.Settings.Apps.State.currentCategory === categoryId) {
  68. return;
  69. }
  70. if (this._loadCategoryCall) {
  71. this._loadCategoryCall.abort();
  72. }
  73. $('#app-content').addClass('icon-loading');
  74. $('#apps-list')
  75. .removeClass('hidden')
  76. .html('');
  77. $('#apps-list-empty').addClass('hidden');
  78. $('#app-category-' + OC.Settings.Apps.State.currentCategory).removeClass('active');
  79. $('#app-category-' + categoryId).addClass('active');
  80. OC.Settings.Apps.State.currentCategory = categoryId;
  81. this._loadCategoryCall = $.ajax(OC.generateUrl('settings/apps/list?category={categoryId}', {
  82. categoryId: categoryId
  83. }), {
  84. type:'GET',
  85. success: function (apps) {
  86. OC.Settings.Apps.State.currentCategoryElements = apps.apps;
  87. var appListWithIndex = _.indexBy(apps.apps, 'id');
  88. OC.Settings.Apps.State.apps = appListWithIndex;
  89. var appList = _.map(appListWithIndex, function(app) {
  90. // default values for missing fields
  91. return _.extend({level: 0}, app);
  92. });
  93. var source;
  94. if (categoryId === 'enabled' || categoryId === 'updates' || categoryId === 'disabled' || categoryId === 'installed' || categoryId === 'app-bundles') {
  95. source = $("#app-template-installed").html();
  96. $('#apps-list').addClass('installed');
  97. } else {
  98. source = $("#app-template").html();
  99. $('#apps-list').removeClass('installed');
  100. }
  101. var template = Handlebars.compile(source);
  102. if (appList.length) {
  103. if(categoryId !== 'app-bundles') {
  104. appList.sort(function (a, b) {
  105. if (a.active !== b.active) {
  106. return (a.active ? -1 : 1)
  107. }
  108. if (a.update !== b.update) {
  109. return (a.update ? -1 : 1)
  110. }
  111. return OC.Util.naturalSortCompare(a.name, b.name);
  112. });
  113. }
  114. var firstExperimental = false;
  115. var hasNewUpdates = false;
  116. _.each(appList, function(app) {
  117. if(app.level === 0 && firstExperimental === false) {
  118. firstExperimental = true;
  119. OC.Settings.Apps.renderApp(app, template, null, true);
  120. } else {
  121. OC.Settings.Apps.renderApp(app, template, null, false);
  122. }
  123. if (app.update) {
  124. hasNewUpdates = true;
  125. var $update = $('#app-' + app.id + ' .update');
  126. $update.removeClass('hidden');
  127. $update.val(t('settings', 'Update to %s').replace(/%s/g, app.update));
  128. }
  129. });
  130. // reload updates if a list with new updates is loaded
  131. if (hasNewUpdates) {
  132. OC.Settings.Apps.reloadUpdates();
  133. } else {
  134. // hide update category after all updates are installed
  135. // and the user is switching away from the empty updates view
  136. OC.Settings.Apps.refreshUpdateCounter();
  137. }
  138. } else {
  139. if (categoryId === 'updates') {
  140. OC.Settings.Apps.showEmptyUpdates();
  141. } else {
  142. $('#apps-list').addClass('hidden');
  143. $('#apps-list-empty').removeClass('hidden').find('h2').text(t('settings', 'No apps found for your version'));
  144. $('#app-list-empty-icon').addClass('icon-search').removeClass('icon-download');
  145. }
  146. }
  147. $('.enable.needs-download').tooltip({
  148. title: t('settings', 'The app will be downloaded from the app store'),
  149. placement: 'bottom',
  150. container: 'body'
  151. });
  152. $('.app-level .official').tooltip({
  153. title: t('settings', 'Official apps are developed by and within the community. They offer central functionality and are ready for production use.'),
  154. placement: 'bottom',
  155. container: 'body'
  156. });
  157. $('.app-level .approved').tooltip({
  158. title: t('settings', 'Approved apps are developed by trusted developers and have passed a cursory security check. They are actively maintained in an open code repository and their maintainers deem them to be stable for casual to normal use.'),
  159. placement: 'bottom',
  160. container: 'body'
  161. });
  162. $('.app-level .experimental').tooltip({
  163. title: t('settings', 'This app is not checked for security issues and is new or known to be unstable. Install at your own risk.'),
  164. placement: 'bottom',
  165. container: 'body'
  166. });
  167. },
  168. complete: function() {
  169. $('#app-content').removeClass('icon-loading');
  170. }
  171. });
  172. },
  173. renderApp: function(app, template, selector, firstExperimental) {
  174. if (!template) {
  175. var source = $("#app-template").html();
  176. template = Handlebars.compile(source);
  177. }
  178. if (typeof app === 'string') {
  179. app = OC.Settings.Apps.State.apps[app];
  180. }
  181. app.firstExperimental = firstExperimental;
  182. if (!app.preview) {
  183. app.preview = OC.imagePath('core', 'places/default-app-icon');
  184. app.previewAsIcon = true;
  185. }
  186. if (_.isArray(app.author)) {
  187. var authors = [];
  188. _.each(app.author, function (author) {
  189. if (typeof author === 'string') {
  190. authors.push(author);
  191. } else {
  192. authors.push(author['@value']);
  193. }
  194. });
  195. app.author = authors.join(', ');
  196. } else if (typeof app.author !== 'string') {
  197. app.author = app.author['@value'];
  198. }
  199. // Parse markdown in app description
  200. app.description = DOMPurify.sanitize(
  201. marked(app.description.trim(), OC.Settings.Apps.markedOptions),
  202. {
  203. SAFE_FOR_JQUERY: true,
  204. ALLOWED_TAGS: [
  205. 'strong',
  206. 'p',
  207. 'a',
  208. 'ul',
  209. 'ol',
  210. 'li',
  211. 'em',
  212. 'del',
  213. 'blockquote'
  214. ]
  215. }
  216. );
  217. var html = template(app);
  218. if (selector) {
  219. selector.html(html);
  220. } else {
  221. $('#apps-list').append(html);
  222. }
  223. var page = $('#app-' + app.id);
  224. if (app.preview) {
  225. var currentImage = new Image();
  226. currentImage.src = app.preview;
  227. currentImage.onload = function() {
  228. /* Trigger color inversion for placeholder image too */
  229. if(app.previewAsIcon) {
  230. page.find('.app-image')
  231. .append(OC.Settings.Apps.imageUrl(app.preview, false))
  232. .removeClass('icon-loading');
  233. } else {
  234. page.find('.app-image')
  235. .append(OC.Settings.Apps.imageUrl(app.preview, app.fromAppStore))
  236. .removeClass('icon-loading');
  237. }
  238. };
  239. }
  240. // set group select properly
  241. if(OC.Settings.Apps.isType(app, 'filesystem') || OC.Settings.Apps.isType(app, 'prelogin') ||
  242. OC.Settings.Apps.isType(app, 'authentication') || OC.Settings.Apps.isType(app, 'logging') ||
  243. OC.Settings.Apps.isType(app, 'prevent_group_restriction')) {
  244. page.find(".groups-enable").hide();
  245. page.find(".groups-enable__checkbox").prop('checked', false);
  246. } else {
  247. page.find('.group_select').val((app.groups || []).join('|'));
  248. if (app.active) {
  249. if (app.groups.length) {
  250. OC.Settings.Apps.setupGroupsSelect(page.find('.group_select'));
  251. page.find(".groups-enable__checkbox").prop('checked', true);
  252. } else {
  253. page.find(".groups-enable__checkbox").prop('checked', false);
  254. }
  255. page.find(".groups-enable").show();
  256. } else {
  257. page.find(".groups-enable").hide();
  258. }
  259. }
  260. },
  261. /**
  262. * Returns the image for apps listing
  263. * url : the url of the image
  264. * appfromstore: bool to check whether the app is fetched from store or not.
  265. */
  266. imageUrl : function (url, appfromstore) {
  267. var img;
  268. if (appfromstore) {
  269. img = '<svg viewBox="0 0 72 72">';
  270. img += '<image x="0" y="0" width="72" height="72" preserveAspectRatio="xMinYMin meet" xlink:href="' + url + '" class="app-icon" /></svg>';
  271. } else {
  272. var rnd = Math.floor((Math.random() * 100 )) + new Date().getSeconds() + new Date().getMilliseconds();
  273. img = '<svg width="32" height="32" viewBox="0 0 32 32">';
  274. img += '<defs><filter id="invertIconApps-' + rnd + '"><feColorMatrix in="SourceGraphic" type="matrix" values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0"></feColorMatrix></filter></defs>'
  275. img += '<image x="0" y="0" width="32" height="32" preserveAspectRatio="xMinYMin meet" filter="url(#invertIconApps-' + rnd + ')" xlink:href="' + url + '?v=' + oc_config.version + '" class="app-icon"></image></svg>';
  276. }
  277. return img;
  278. },
  279. isType: function(app, type){
  280. return app.types && app.types.indexOf(type) !== -1;
  281. },
  282. /**
  283. * Checks the server health.
  284. *
  285. * If the promise fails, the server is broken.
  286. *
  287. * @return {Promise} promise
  288. */
  289. _checkServerHealth: function() {
  290. return $.get(OC.generateUrl('apps/files'));
  291. },
  292. enableAppBundle:function(bundleId, active, element, groups) {
  293. if (OC.PasswordConfirmation.requiresPasswordConfirmation()) {
  294. OC.PasswordConfirmation.requirePasswordConfirmation(_.bind(this.enableAppBundle, this, bundleId, active, element, groups));
  295. return;
  296. }
  297. var apps = OC.Settings.Apps.State.currentCategoryElements;
  298. var appsToEnable = [];
  299. apps.forEach(function(app) {
  300. if(app['bundleId'] === bundleId) {
  301. if(app['active'] === false) {
  302. appsToEnable.push(app['id']);
  303. }
  304. }
  305. });
  306. OC.Settings.Apps.enableApp(appsToEnable, false, groups);
  307. },
  308. /**
  309. * @param {string[]} appId
  310. * @param {boolean} active
  311. * @param {array} groups
  312. */
  313. enableApp:function(appId, active, groups) {
  314. if (OC.PasswordConfirmation.requiresPasswordConfirmation()) {
  315. OC.PasswordConfirmation.requirePasswordConfirmation(_.bind(this.enableApp, this, appId, active, groups));
  316. return;
  317. }
  318. var elements = [];
  319. appId.forEach(function(appId) {
  320. elements.push($('#app-'+appId+' .enable'));
  321. });
  322. var self = this;
  323. appId.forEach(function(appId) {
  324. OC.Settings.Apps.hideErrorMessage(appId);
  325. });
  326. groups = groups || [];
  327. var appItems = [];
  328. appId.forEach(function(appId) {
  329. appItems.push($('div#app-'+appId+''));
  330. });
  331. if(active && !groups.length) {
  332. elements.forEach(function(element) {
  333. element.val(t('settings','Disabling app …'));
  334. });
  335. $.post(OC.filePath('settings','ajax','disableapp.php'),{appid:appId},function(result) {
  336. if(!result || result.status !== 'success') {
  337. if (result.data && result.data.message) {
  338. OC.Settings.Apps.showErrorMessage(appId, result.data.message);
  339. appItems.forEach(function(appItem) {
  340. appItem.data('errormsg', result.data.message);
  341. })
  342. } else {
  343. OC.Settings.Apps.showErrorMessage(appId, t('settings', 'Error while disabling app'));
  344. appItems.forEach(function(appItem) {
  345. appItem.data('errormsg', t('settings', 'Error while disabling app'));
  346. });
  347. }
  348. elements.forEach(function(element) {
  349. element.val(t('settings','Disable'));
  350. });
  351. appItems.forEach(function(appItem) {
  352. appItem.addClass('appwarning');
  353. });
  354. } else {
  355. OC.Settings.Apps.rebuildNavigation();
  356. appItems.forEach(function(appItem) {
  357. appItem.data('active', false);
  358. appItem.data('groups', '');
  359. });
  360. elements.forEach(function(element) {
  361. element.data('active', false);
  362. });
  363. appItems.forEach(function(appItem) {
  364. appItem.removeClass('active');
  365. });
  366. elements.forEach(function(element) {
  367. element.val(t('settings', 'Enable'));
  368. element.parent().find(".groups-enable").hide();
  369. element.parent().find('.group_select').hide().val(null);
  370. });
  371. OC.Settings.Apps.State.apps[appId].active = false;
  372. }
  373. },'json');
  374. } else {
  375. // TODO: display message to admin to not refresh the page!
  376. // TODO: lock UI to prevent further operations
  377. elements.forEach(function(element) {
  378. element.val(t('settings', 'Enabling app …'));
  379. });
  380. var appIdArray = [];
  381. if( typeof appId === 'string' ) {
  382. appIdArray = [appId];
  383. } else {
  384. appIdArray = appId;
  385. }
  386. $.post(OC.filePath('settings','ajax','enableapp.php'),{appIds: appIdArray, groups: groups},function(result) {
  387. if(!result || result.status !== 'success') {
  388. if (result.data && result.data.message) {
  389. OC.Settings.Apps.showErrorMessage(appId, result.data.message);
  390. appItems.forEach(function(appItem) {
  391. appItem.data('errormsg', result.data.message);
  392. });
  393. } else {
  394. OC.Settings.Apps.showErrorMessage(appId, t('settings', 'Error while enabling app'));
  395. appItems.forEach(function(appItem) {
  396. appItem.data('errormsg', t('settings', 'Error while disabling app'));
  397. });
  398. }
  399. elements.forEach(function(element) {
  400. element.val(t('settings', 'Enable'));
  401. });
  402. appItems.forEach(function(appItem) {
  403. appItem.addClass('appwarning');
  404. });
  405. } else {
  406. self._checkServerHealth().done(function() {
  407. if (result.data.update_required) {
  408. OC.Settings.Apps.showReloadMessage();
  409. setTimeout(function() {
  410. location.reload();
  411. }, 5000);
  412. }
  413. OC.Settings.Apps.rebuildNavigation();
  414. appItems.forEach(function(appItem) {
  415. appItem.data('active', true);
  416. });
  417. elements.forEach(function(element) {
  418. element.data('active', true);
  419. });
  420. appItems.forEach(function(appItem) {
  421. appItem.addClass('active');
  422. });
  423. elements.forEach(function(element) {
  424. element.val(t('settings', 'Disable'));
  425. });
  426. var app = OC.Settings.Apps.State.apps[appId];
  427. app.active = true;
  428. if (OC.Settings.Apps.isType(app, 'filesystem') || OC.Settings.Apps.isType(app, 'prelogin') ||
  429. OC.Settings.Apps.isType(app, 'authentication') || OC.Settings.Apps.isType(app, 'logging')) {
  430. elements.forEach(function(element) {
  431. element.parent().find(".groups-enable").prop('checked', true);
  432. element.parent().find(".groups-enable").hide();
  433. element.parent().find('.group_select').hide().val(null);
  434. });
  435. } else {
  436. elements.forEach(function(element) {
  437. element.parent().find("#groups-enable").show();
  438. });
  439. if (groups) {
  440. appItems.forEach(function(appItem) {
  441. appItem.data('groups', JSON.stringify(groups));
  442. });
  443. } else {
  444. appItems.forEach(function(appItem) {
  445. appItem.data('groups', '');
  446. });
  447. }
  448. }
  449. }).fail(function() {
  450. // server borked, emergency disable app
  451. $.post(OC.webroot + '/index.php/disableapp', {appid: appId}, function() {
  452. OC.Settings.Apps.showErrorMessage(
  453. appId,
  454. t('settings', 'Error: This app can not be enabled because it makes the server unstable')
  455. );
  456. appItems.forEach(function(appItem) {
  457. appItem.data('errormsg', t('settings', 'Error while enabling app'));
  458. });
  459. elements.forEach(function(element) {
  460. element.val(t('settings', 'Enable'));
  461. });
  462. appItems.forEach(function(appItem) {
  463. appItem.addClass('appwarning');
  464. });
  465. }).fail(function() {
  466. OC.Settings.Apps.showErrorMessage(
  467. appId,
  468. t('settings', 'Error: Could not disable broken app')
  469. );
  470. appItems.forEach(function(appItem) {
  471. appItem.data('errormsg', t('settings', 'Error while disabling broken app'));
  472. });
  473. elements.forEach(function(element) {
  474. element.val(t('settings', 'Enable'));
  475. });
  476. });
  477. });
  478. }
  479. },'json')
  480. .fail(function() {
  481. OC.Settings.Apps.showErrorMessage(appId, t('settings', 'Error while enabling app'));
  482. appItems.forEach(function(appItem) {
  483. appItem.data('errormsg', t('settings', 'Error while enabling app'));
  484. appItem.data('active', false);
  485. appItem.addClass('appwarning');
  486. });
  487. elements.forEach(function(element) {
  488. element.val(t('settings', 'Enable'));
  489. });
  490. });
  491. }
  492. },
  493. showEmptyUpdates: function() {
  494. $('#apps-list').addClass('hidden');
  495. $('#apps-list-empty').removeClass('hidden').find('h2').text(t('settings', 'App up to date'));
  496. $('#app-list-empty-icon').removeClass('icon-search').addClass('icon-download');
  497. },
  498. updateApp:function(appId, element) {
  499. var oldButtonText = element.val();
  500. element.val(t('settings','Updating …'));
  501. OC.Settings.Apps.hideErrorMessage(appId);
  502. $.post(OC.filePath('settings','ajax','updateapp.php'),{appid:appId},function(result) {
  503. if(!result || result.status !== 'success') {
  504. if (result.data && result.data.message) {
  505. OC.Settings.Apps.showErrorMessage(appId, result.data.message);
  506. } else {
  507. OC.Settings.Apps.showErrorMessage(appId, t('settings','Could not update app'));
  508. }
  509. element.val(oldButtonText);
  510. }
  511. else {
  512. element.val(t('settings','Updated'));
  513. element.hide();
  514. var $update = $('#app-' + appId + ' .update');
  515. $update.addClass('hidden');
  516. var $version = $('#app-' + appId + ' .app-version');
  517. $version.text(OC.Settings.Apps.State.apps[appId]['update']);
  518. OC.Settings.Apps.State.availableUpdates--;
  519. OC.Settings.Apps.refreshUpdateCounter();
  520. if (OC.Settings.Apps.State.currentCategory === 'updates') {
  521. $('#app-' + appId).remove();
  522. if (OC.Settings.Apps.State.availableUpdates === 0) {
  523. OC.Settings.Apps.showEmptyUpdates();
  524. }
  525. }
  526. }
  527. },'json');
  528. },
  529. uninstallApp:function(appId, element) {
  530. if (OC.PasswordConfirmation.requiresPasswordConfirmation()) {
  531. OC.PasswordConfirmation.requirePasswordConfirmation(_.bind(this.uninstallApp, this, appId, element));
  532. return;
  533. }
  534. OC.Settings.Apps.hideErrorMessage(appId);
  535. element.val(t('settings','Removing …'));
  536. $.post(OC.filePath('settings','ajax','uninstallapp.php'),{appid:appId},function(result) {
  537. if(!result || result.status !== 'success') {
  538. OC.Settings.Apps.showErrorMessage(appId, t('settings','Could not remove app'));
  539. element.val(t('settings','Remove'));
  540. } else {
  541. OC.Settings.Apps.rebuildNavigation();
  542. element.parents('#apps-list > .section').fadeOut(function() {
  543. this.remove();
  544. });
  545. }
  546. },'json');
  547. },
  548. rebuildNavigation: function() {
  549. $.getJSON(OC.linkToOCS('core/navigation', 2) + 'apps?format=json').done(function(response){
  550. if(response.ocs.meta.status === 'ok') {
  551. var addedApps = {};
  552. var navEntries = response.ocs.data;
  553. var container = $('#apps ul');
  554. // remove disabled apps
  555. for (var i = 0; i < navEntries.length; i++) {
  556. var entry = navEntries[i];
  557. if(container.children('li[data-id="' + entry.id + '"]').length === 0) {
  558. addedApps[entry.id] = true;
  559. }
  560. }
  561. container.children('li[data-id]').each(function (index, el) {
  562. var id = $(el).data('id');
  563. // remove all apps that are not in the correct order
  564. if (!navEntries[index] || (navEntries[index] && navEntries[index].id !== $(el).data('id'))) {
  565. $(el).remove();
  566. $('#appmenu li[data-id='+id+']').remove();
  567. }
  568. });
  569. var previousEntry = {};
  570. // add enabled apps to #navigation and #appmenu
  571. for (var i = 0; i < navEntries.length; i++) {
  572. var entry = navEntries[i];
  573. if (container.children('li[data-id="' + entry.id + '"]').length === 0) {
  574. var li = $('<li></li>');
  575. li.attr('data-id', entry.id);
  576. var img = '<svg width="16" height="16" viewBox="0 0 16 16">';
  577. img += '<defs><filter id="invert"><feColorMatrix in="SourceGraphic" type="matrix" values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0" /></filter></defs>';
  578. img += '<image x="0" y="0" width="16" height="16" preserveAspectRatio="xMinYMin meet" filter="url(#invert)" xlink:href="' + entry.icon + '" class="app-icon" /></svg>';
  579. var a = $('<a></a>').attr('href', entry.href);
  580. var filename = $('<span></span>');
  581. var loading = $('<div class="icon-loading-dark"></div>').css('display', 'none');
  582. filename.text(entry.name);
  583. a.prepend(filename);
  584. a.prepend(loading);
  585. a.prepend(img);
  586. li.append(a);
  587. $('#navigation li[data-id=' + previousEntry.id + ']').after(li);
  588. // draw attention to the newly added app entry
  589. // by flashing twice the more apps menu
  590. if(addedApps[entry.id]) {
  591. $('#header #more-apps')
  592. .animate({opacity: 0.5})
  593. .animate({opacity: 1})
  594. .animate({opacity: 0.5})
  595. .animate({opacity: 1});
  596. }
  597. }
  598. if ($('#appmenu').children('li[data-id="' + entry.id + '"]').length === 0) {
  599. var li = $('<li></li>');
  600. li.attr('data-id', entry.id);
  601. var img = '<img src="' + entry.icon + '" class="app-icon">';
  602. if (OCA.Theming && OCA.Theming.inverted) {
  603. img = '<svg width="20" height="20" viewBox="0 0 20 20">';
  604. img += '<defs><filter id="invert"><feColorMatrix in="SourceGraphic" type="matrix" values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0" /></filter></defs>';
  605. img += '<image x="0" y="0" width="20" height="20" preserveAspectRatio="xMinYMin meet" filter="url(#invert)" xlink:href="' + entry.icon + '" class="app-icon" /></svg>';
  606. }
  607. var a = $('<a></a>').attr('href', entry.href);
  608. var filename = $('<span></span>');
  609. var loading = $('<div class="icon-loading-dark"></div>').css('display', 'none');
  610. filename.text(entry.name);
  611. a.prepend(filename);
  612. a.prepend(loading);
  613. a.prepend(img);
  614. li.append(a);
  615. $('#appmenu li[data-id='+ previousEntry.id+']').after(li);
  616. if(addedApps[entry.id]) {
  617. li.animate({opacity: 0.5})
  618. .animate({opacity: 1})
  619. .animate({opacity: 0.5})
  620. .animate({opacity: 1});
  621. }
  622. }
  623. previousEntry = entry;
  624. }
  625. $(window).trigger('resize');
  626. }
  627. });
  628. },
  629. reloadUpdates: function() {
  630. if (this._loadUpdatesCall) {
  631. this._loadUpdatesCall.abort();
  632. }
  633. this._loadUpdatesCall = $.ajax(OC.generateUrl('settings/apps/list?category=updates'), {
  634. type:'GET',
  635. success: function (apps) {
  636. OC.Settings.Apps.State.availableUpdates = apps.apps.length;
  637. OC.Settings.Apps.refreshUpdateCounter();
  638. }
  639. });
  640. },
  641. refreshUpdateCounter: function() {
  642. var $appCategoryUpdates = $('#app-category-updates');
  643. var $updateCount = $appCategoryUpdates.find('.app-navigation-entry-utils-counter');
  644. if (OC.Settings.Apps.State.availableUpdates > 0) {
  645. $updateCount.html(OC.Settings.Apps.State.availableUpdates);
  646. $appCategoryUpdates.show();
  647. } else {
  648. $updateCount.empty();
  649. if (OC.Settings.Apps.State.currentCategory !== 'updates') {
  650. $appCategoryUpdates.hide();
  651. }
  652. }
  653. },
  654. showErrorMessage: function(appId, message) {
  655. $('div#app-'+appId+' .warning')
  656. .show()
  657. .text(message);
  658. },
  659. hideErrorMessage: function(appId) {
  660. $('div#app-'+appId+' .warning')
  661. .hide()
  662. .text('');
  663. },
  664. showReloadMessage: function() {
  665. OC.dialogs.info(
  666. t(
  667. 'settings',
  668. 'The app has been enabled but needs to be updated. You will be redirected to the update page in 5 seconds.'
  669. ),
  670. t('settings','App update'),
  671. function () {
  672. window.location.reload();
  673. },
  674. true
  675. );
  676. },
  677. /**
  678. * Splits the query by spaces and tries to find all substring in the app
  679. * @param {string} string
  680. * @param {string} query
  681. * @returns {boolean}
  682. */
  683. _search: function(string, query) {
  684. var keywords = query.split(' '),
  685. stringLower = string.toLowerCase(),
  686. found = true;
  687. _.each(keywords, function(keyword) {
  688. found = found && stringLower.indexOf(keyword) !== -1;
  689. });
  690. return found;
  691. },
  692. filter: function(query) {
  693. var $appList = $('#apps-list'),
  694. $emptyList = $('#apps-list-empty');
  695. $('#app-list-empty-icon').addClass('icon-search').removeClass('icon-download');
  696. $appList.removeClass('hidden');
  697. $appList.find('.section').removeClass('hidden');
  698. $emptyList.addClass('hidden');
  699. if (query === '') {
  700. return;
  701. }
  702. query = query.toLowerCase();
  703. $appList.find('.section').addClass('hidden');
  704. // App Name
  705. var apps = _.filter(OC.Settings.Apps.State.apps, function (app) {
  706. return OC.Settings.Apps._search(app.name, query);
  707. });
  708. // App ID
  709. apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
  710. return OC.Settings.Apps._search(app.id, query);
  711. }));
  712. // App Description
  713. apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
  714. return OC.Settings.Apps._search(app.description, query);
  715. }));
  716. // Author Name
  717. apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
  718. var authors = [];
  719. if (_.isArray(app.author)) {
  720. _.each(app.author, function (author) {
  721. if (typeof author === 'string') {
  722. authors.push(author);
  723. } else {
  724. authors.push(author['@value']);
  725. if (!_.isUndefined(author['@attributes']['homepage'])) {
  726. authors.push(author['@attributes']['homepage']);
  727. }
  728. if (!_.isUndefined(author['@attributes']['mail'])) {
  729. authors.push(author['@attributes']['mail']);
  730. }
  731. }
  732. });
  733. return OC.Settings.Apps._search(authors.join(' '), query);
  734. } else if (typeof app.author !== 'string') {
  735. authors.push(app.author['@value']);
  736. if (!_.isUndefined(app.author['@attributes']['homepage'])) {
  737. authors.push(app.author['@attributes']['homepage']);
  738. }
  739. if (!_.isUndefined(app.author['@attributes']['mail'])) {
  740. authors.push(app.author['@attributes']['mail']);
  741. }
  742. return OC.Settings.Apps._search(authors.join(' '), query);
  743. }
  744. return OC.Settings.Apps._search(app.author, query);
  745. }));
  746. // App status
  747. if (t('settings', 'Official').toLowerCase().indexOf(query) !== -1) {
  748. apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
  749. return app.level === 200;
  750. }));
  751. }
  752. if (t('settings', 'Approved').toLowerCase().indexOf(query) !== -1) {
  753. apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
  754. return app.level === 100;
  755. }));
  756. }
  757. if (t('settings', 'Experimental').toLowerCase().indexOf(query) !== -1) {
  758. apps = apps.concat(_.filter(OC.Settings.Apps.State.apps, function (app) {
  759. return app.level !== 100 && app.level !== 200;
  760. }));
  761. }
  762. apps = _.uniq(apps, function(app){return app.id;});
  763. if (apps.length === 0) {
  764. $appList.addClass('hidden');
  765. $emptyList.removeClass('hidden');
  766. $emptyList.removeClass('hidden').find('h2').text(t('settings', 'No apps found for {query}', {
  767. query: query
  768. }));
  769. } else {
  770. _.each(apps, function (app) {
  771. $('#app-' + app.id).removeClass('hidden');
  772. });
  773. $('#searchresults').hide();
  774. }
  775. },
  776. _onPopState: function(params) {
  777. params = _.extend({
  778. category: 'enabled'
  779. }, params);
  780. OC.Settings.Apps.loadCategory(params.category);
  781. },
  782. /**
  783. * Initializes the apps list
  784. */
  785. initialize: function($el) {
  786. var renderer = new marked.Renderer();
  787. renderer.link = function(href, title, text) {
  788. try {
  789. var prot = decodeURIComponent(unescape(href))
  790. .replace(/[^\w:]/g, '')
  791. .toLowerCase();
  792. } catch (e) {
  793. return '';
  794. }
  795. if (prot.indexOf('http:') !== 0 && prot.indexOf('https:') !== 0) {
  796. return '';
  797. }
  798. var out = '<a href="' + href + '" rel="noreferrer noopener"';
  799. if (title) {
  800. out += ' title="' + title + '"';
  801. }
  802. out += '>' + text + '</a>';
  803. return out;
  804. };
  805. renderer.image = function(href, title, text) {
  806. if (text) {
  807. return text;
  808. }
  809. return title;
  810. };
  811. renderer.blockquote = function(quote) {
  812. return quote;
  813. };
  814. OC.Settings.Apps.markedOptions = {
  815. renderer: renderer,
  816. gfm: false,
  817. highlight: false,
  818. tables: false,
  819. breaks: false,
  820. pedantic: false,
  821. sanitize: true,
  822. smartLists: true,
  823. smartypants: false
  824. };
  825. OC.Plugins.register('OCA.Search', OC.Settings.Apps.Search);
  826. OC.Settings.Apps.loadCategories();
  827. OC.Util.History.addOnPopStateHandler(_.bind(this._onPopState, this));
  828. $(document).on('click', 'ul#apps-categories li', function () {
  829. var categoryId = $(this).data('categoryId');
  830. OC.Settings.Apps.loadCategory(categoryId);
  831. OC.Util.History.pushState({
  832. category: categoryId
  833. });
  834. $('#searchbox').val('');
  835. });
  836. $(document).on('click', '.app-description-toggle-show', function () {
  837. $(this).addClass('hidden');
  838. $(this).siblings('.app-description-toggle-hide').removeClass('hidden');
  839. $(this).siblings('.app-description-container').slideDown();
  840. });
  841. $(document).on('click', '.app-description-toggle-hide', function () {
  842. $(this).addClass('hidden');
  843. $(this).siblings('.app-description-toggle-show').removeClass('hidden');
  844. $(this).siblings('.app-description-container').slideUp();
  845. });
  846. $(document).on('click', '#apps-list input.enable', function () {
  847. var appId = $(this).data('appid');
  848. var bundleId = $(this).data('bundleid');
  849. var element = $(this);
  850. var active = $(this).data('active');
  851. var category = $('#app-navigation').attr('data-category');
  852. if(bundleId) {
  853. OC.Settings.Apps.enableAppBundle(bundleId, active, element);
  854. element.val(t('settings', 'Enable all'));
  855. } else {
  856. OC.Settings.Apps.enableApp([appId], active);
  857. }
  858. });
  859. $(document).on('click', '#apps-list input.uninstall', function () {
  860. var appId = $(this).data('appid');
  861. var element = $(this);
  862. OC.Settings.Apps.uninstallApp(appId, element);
  863. });
  864. $(document).on('click', '#apps-list input.update', function () {
  865. var appId = $(this).data('appid');
  866. var element = $(this);
  867. OC.Settings.Apps.updateApp(appId, element);
  868. });
  869. $(document).on('change', '.group_select', function() {
  870. var element = $(this).closest('.section').find('input.enable');
  871. var groups = $(this).val();
  872. if (groups && groups !== '') {
  873. groups = groups.split('|');
  874. } else {
  875. groups = [];
  876. }
  877. var appId = element.data('appid');
  878. if (appId) {
  879. OC.Settings.Apps.enableApp([appId], false, groups);
  880. OC.Settings.Apps.State.apps[appId].groups = groups;
  881. }
  882. });
  883. $(document).on('change', ".groups-enable__checkbox", function() {
  884. var $select = $(this).closest('.section').find('.group_select');
  885. $select.val('');
  886. if (this.checked) {
  887. OC.Settings.Apps.setupGroupsSelect($select);
  888. } else {
  889. $select.select2('destroy');
  890. }
  891. $select.change();
  892. });
  893. $(document).on('click', '#enable-experimental-apps', function () {
  894. var state = $(this).prop('checked');
  895. $.ajax(OC.generateUrl('settings/apps/experimental'), {
  896. data: {state: state},
  897. type: 'POST',
  898. success:function () {
  899. location.reload();
  900. }
  901. });
  902. });
  903. }
  904. };
  905. OC.Settings.Apps.Search = {
  906. attach: function (search) {
  907. search.setFilter('settings', OC.Settings.Apps.filter);
  908. }
  909. };
  910. $(document).ready(function () {
  911. // HACK: FIXME: use plugin approach
  912. if (!window.TESTING) {
  913. OC.Settings.Apps.initialize($('#apps-list'));
  914. }
  915. });