PageRenderTime 35ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/front/platforms/android/cordova/node_modules/cordova-common/src/ConfigParser/ConfigParser.js

https://gitlab.com/boxnia/NFU_MOVIL
JavaScript | 499 lines | 353 code | 36 blank | 110 comment | 61 complexity | 3f3351bbb8a06a0d388ea50d2de9144d MD5 | raw file
  1. /**
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. /* jshint sub:true */
  18. var et = require('elementtree'),
  19. xml= require('../util/xml-helpers'),
  20. CordovaError = require('../CordovaError/CordovaError'),
  21. fs = require('fs'),
  22. events = require('../events');
  23. /** Wraps a config.xml file */
  24. function ConfigParser(path) {
  25. this.path = path;
  26. try {
  27. this.doc = xml.parseElementtreeSync(path);
  28. this.cdvNamespacePrefix = getCordovaNamespacePrefix(this.doc);
  29. et.register_namespace(this.cdvNamespacePrefix, 'http://cordova.apache.org/ns/1.0');
  30. } catch (e) {
  31. console.error('Parsing '+path+' failed');
  32. throw e;
  33. }
  34. var r = this.doc.getroot();
  35. if (r.tag !== 'widget') {
  36. throw new CordovaError(path + ' has incorrect root node name (expected "widget", was "' + r.tag + '")');
  37. }
  38. }
  39. function getNodeTextSafe(el) {
  40. return el && el.text && el.text.trim();
  41. }
  42. function findOrCreate(doc, name) {
  43. var ret = doc.find(name);
  44. if (!ret) {
  45. ret = new et.Element(name);
  46. doc.getroot().append(ret);
  47. }
  48. return ret;
  49. }
  50. function getCordovaNamespacePrefix(doc){
  51. var rootAtribs = Object.getOwnPropertyNames(doc.getroot().attrib);
  52. var prefix = 'cdv';
  53. for (var j = 0; j < rootAtribs.length; j++ ) {
  54. if(rootAtribs[j].indexOf('xmlns:') === 0 &&
  55. doc.getroot().attrib[rootAtribs[j]] === 'http://cordova.apache.org/ns/1.0'){
  56. var strings = rootAtribs[j].split(':');
  57. prefix = strings[1];
  58. break;
  59. }
  60. }
  61. return prefix;
  62. }
  63. /**
  64. * Finds the value of an element's attribute
  65. * @param {String} attributeName Name of the attribute to search for
  66. * @param {Array} elems An array of ElementTree nodes
  67. * @return {String}
  68. */
  69. function findElementAttributeValue(attributeName, elems) {
  70. elems = Array.isArray(elems) ? elems : [ elems ];
  71. var value = elems.filter(function (elem) {
  72. return elem.attrib.name.toLowerCase() === attributeName.toLowerCase();
  73. }).map(function (filteredElems) {
  74. return filteredElems.attrib.value;
  75. }).pop();
  76. return value ? value : '';
  77. }
  78. ConfigParser.prototype = {
  79. packageName: function(id) {
  80. return this.doc.getroot().attrib['id'];
  81. },
  82. setPackageName: function(id) {
  83. this.doc.getroot().attrib['id'] = id;
  84. },
  85. android_packageName: function() {
  86. return this.doc.getroot().attrib['android-packageName'];
  87. },
  88. android_activityName: function() {
  89. return this.doc.getroot().attrib['android-activityName'];
  90. },
  91. ios_CFBundleIdentifier: function() {
  92. return this.doc.getroot().attrib['ios-CFBundleIdentifier'];
  93. },
  94. name: function() {
  95. return getNodeTextSafe(this.doc.find('name'));
  96. },
  97. setName: function(name) {
  98. var el = findOrCreate(this.doc, 'name');
  99. el.text = name;
  100. },
  101. description: function() {
  102. return getNodeTextSafe(this.doc.find('description'));
  103. },
  104. setDescription: function(text) {
  105. var el = findOrCreate(this.doc, 'description');
  106. el.text = text;
  107. },
  108. version: function() {
  109. return this.doc.getroot().attrib['version'];
  110. },
  111. windows_packageVersion: function() {
  112. return this.doc.getroot().attrib('windows-packageVersion');
  113. },
  114. android_versionCode: function() {
  115. return this.doc.getroot().attrib['android-versionCode'];
  116. },
  117. ios_CFBundleVersion: function() {
  118. return this.doc.getroot().attrib['ios-CFBundleVersion'];
  119. },
  120. setVersion: function(value) {
  121. this.doc.getroot().attrib['version'] = value;
  122. },
  123. author: function() {
  124. return getNodeTextSafe(this.doc.find('author'));
  125. },
  126. getGlobalPreference: function (name) {
  127. return findElementAttributeValue(name, this.doc.findall('preference'));
  128. },
  129. setGlobalPreference: function (name, value) {
  130. var pref = this.doc.find('preference[@name="' + name + '"]');
  131. if (!pref) {
  132. pref = new et.Element('preference');
  133. pref.attrib.name = name;
  134. this.doc.getroot().append(pref);
  135. }
  136. pref.attrib.value = value;
  137. },
  138. getPlatformPreference: function (name, platform) {
  139. return findElementAttributeValue(name, this.doc.findall('platform[@name=\'' + platform + '\']/preference'));
  140. },
  141. getPreference: function(name, platform) {
  142. var platformPreference = '';
  143. if (platform) {
  144. platformPreference = this.getPlatformPreference(name, platform);
  145. }
  146. return platformPreference ? platformPreference : this.getGlobalPreference(name);
  147. },
  148. /**
  149. * Returns all resources for the platform specified.
  150. * @param {String} platform The platform.
  151. * @param {string} resourceName Type of static resources to return.
  152. * "icon" and "splash" currently supported.
  153. * @return {Array} Resources for the platform specified.
  154. */
  155. getStaticResources: function(platform, resourceName) {
  156. var ret = [],
  157. staticResources = [];
  158. if (platform) { // platform specific icons
  159. this.doc.findall('platform[@name=\'' + platform + '\']/' + resourceName).forEach(function(elt){
  160. elt.platform = platform; // mark as platform specific resource
  161. staticResources.push(elt);
  162. });
  163. }
  164. // root level resources
  165. staticResources = staticResources.concat(this.doc.findall(resourceName));
  166. // parse resource elements
  167. var that = this;
  168. staticResources.forEach(function (elt) {
  169. var res = {};
  170. res.src = elt.attrib.src;
  171. res.density = elt.attrib['density'] || elt.attrib[that.cdvNamespacePrefix+':density'] || elt.attrib['gap:density'];
  172. res.platform = elt.platform || null; // null means icon represents default icon (shared between platforms)
  173. res.width = +elt.attrib.width || undefined;
  174. res.height = +elt.attrib.height || undefined;
  175. // default icon
  176. if (!res.width && !res.height && !res.density) {
  177. ret.defaultResource = res;
  178. }
  179. ret.push(res);
  180. });
  181. /**
  182. * Returns resource with specified width and/or height.
  183. * @param {number} width Width of resource.
  184. * @param {number} height Height of resource.
  185. * @return {Resource} Resource object or null if not found.
  186. */
  187. ret.getBySize = function(width, height) {
  188. return ret.filter(function(res) {
  189. if (!res.width && !res.height) {
  190. return false;
  191. }
  192. return ((!res.width || (width == res.width)) &&
  193. (!res.height || (height == res.height)));
  194. })[0] || null;
  195. };
  196. /**
  197. * Returns resource with specified density.
  198. * @param {string} density Density of resource.
  199. * @return {Resource} Resource object or null if not found.
  200. */
  201. ret.getByDensity = function(density) {
  202. return ret.filter(function(res) {
  203. return res.density == density;
  204. })[0] || null;
  205. };
  206. /** Returns default icons */
  207. ret.getDefault = function() {
  208. return ret.defaultResource;
  209. };
  210. return ret;
  211. },
  212. /**
  213. * Returns all icons for specific platform.
  214. * @param {string} platform Platform name
  215. * @return {Resource[]} Array of icon objects.
  216. */
  217. getIcons: function(platform) {
  218. return this.getStaticResources(platform, 'icon');
  219. },
  220. /**
  221. * Returns all splash images for specific platform.
  222. * @param {string} platform Platform name
  223. * @return {Resource[]} Array of Splash objects.
  224. */
  225. getSplashScreens: function(platform) {
  226. return this.getStaticResources(platform, 'splash');
  227. },
  228. /**
  229. * Returns all hook scripts for the hook type specified.
  230. * @param {String} hook The hook type.
  231. * @param {Array} platforms Platforms to look for scripts into (root scripts will be included as well).
  232. * @return {Array} Script elements.
  233. */
  234. getHookScripts: function(hook, platforms) {
  235. var self = this;
  236. var scriptElements = self.doc.findall('./hook');
  237. if(platforms) {
  238. platforms.forEach(function (platform) {
  239. scriptElements = scriptElements.concat(self.doc.findall('./platform[@name="' + platform + '"]/hook'));
  240. });
  241. }
  242. function filterScriptByHookType(el) {
  243. return el.attrib.src && el.attrib.type && el.attrib.type.toLowerCase() === hook;
  244. }
  245. return scriptElements.filter(filterScriptByHookType);
  246. },
  247. /**
  248. * Returns a list of plugin (IDs).
  249. *
  250. * This function also returns any plugin's that
  251. * were defined using the legacy <feature> tags.
  252. * @return {string[]} Array of plugin IDs
  253. */
  254. getPluginIdList: function () {
  255. var plugins = this.doc.findall('plugin');
  256. var result = plugins.map(function(plugin){
  257. return plugin.attrib.name;
  258. });
  259. var features = this.doc.findall('feature');
  260. features.forEach(function(element ){
  261. var idTag = element.find('./param[@name="id"]');
  262. if(idTag){
  263. result.push(idTag.attrib.value);
  264. }
  265. });
  266. return result;
  267. },
  268. getPlugins: function () {
  269. return this.getPluginIdList().map(function (pluginId) {
  270. return this.getPlugin(pluginId);
  271. }, this);
  272. },
  273. /**
  274. * Adds a plugin element. Does not check for duplicates.
  275. * @name addPlugin
  276. * @function
  277. * @param {object} attributes name and spec are supported
  278. * @param {Array|object} variables name, value or arbitary object
  279. */
  280. addPlugin: function (attributes, variables) {
  281. if (!attributes && !attributes.name) return;
  282. var el = new et.Element('plugin');
  283. el.attrib.name = attributes.name;
  284. if (attributes.spec) {
  285. el.attrib.spec = attributes.spec;
  286. }
  287. // support arbitrary object as variables source
  288. if (variables && typeof variables === 'object' && !Array.isArray(variables)) {
  289. variables = Object.keys(variables)
  290. .map(function (variableName) {
  291. return {name: variableName, value: variables[variableName]};
  292. });
  293. }
  294. if (variables) {
  295. variables.forEach(function (variable) {
  296. el.append(new et.Element('variable', { name: variable.name, value: variable.value }));
  297. });
  298. }
  299. this.doc.getroot().append(el);
  300. },
  301. /**
  302. * Retrives the plugin with the given id or null if not found.
  303. *
  304. * This function also returns any plugin's that
  305. * were defined using the legacy <feature> tags.
  306. * @name getPlugin
  307. * @function
  308. * @param {String} id
  309. * @returns {object} plugin including any variables
  310. */
  311. getPlugin: function(id){
  312. if(!id){
  313. return undefined;
  314. }
  315. var pluginElement = this.doc.find('./plugin/[@name="' + id + '"]');
  316. if (null === pluginElement) {
  317. var legacyFeature = this.doc.find('./feature/param[@name="id"][@value="' + id + '"]/..');
  318. if(legacyFeature){
  319. events.emit('log', 'Found deprecated feature entry for ' + id +' in config.xml.');
  320. return featureToPlugin(legacyFeature);
  321. }
  322. return undefined;
  323. }
  324. var plugin = {};
  325. plugin.name = pluginElement.attrib.name;
  326. plugin.spec = pluginElement.attrib.spec || pluginElement.attrib.src || pluginElement.attrib.version;
  327. plugin.variables = {};
  328. var variableElements = pluginElement.findall('variable');
  329. variableElements.forEach(function(varElement){
  330. var name = varElement.attrib.name;
  331. var value = varElement.attrib.value;
  332. if(name){
  333. plugin.variables[name] = value;
  334. }
  335. });
  336. return plugin;
  337. },
  338. /**
  339. * Remove the plugin entry with give name (id).
  340. *
  341. * This function also operates on any plugin's that
  342. * were defined using the legacy <feature> tags.
  343. * @name removePlugin
  344. * @function
  345. * @param id name of the plugin
  346. */
  347. removePlugin: function(id){
  348. if(id){
  349. var plugins = this.doc.findall('./plugin/[@name="' + id + '"]')
  350. .concat(this.doc.findall('./feature/param[@name="id"][@value="' + id + '"]/..'));
  351. var children = this.doc.getroot().getchildren();
  352. plugins.forEach(function (plugin) {
  353. var idx = children.indexOf(plugin);
  354. if (idx > -1) {
  355. children.splice(idx, 1);
  356. }
  357. });
  358. }
  359. },
  360. // Add any element to the root
  361. addElement: function(name, attributes) {
  362. var el = et.Element(name);
  363. for (var a in attributes) {
  364. el.attrib[a] = attributes[a];
  365. }
  366. this.doc.getroot().append(el);
  367. },
  368. /**
  369. * Adds an engine. Does not check for duplicates.
  370. * @param {String} name the engine name
  371. * @param {String} spec engine source location or version (optional)
  372. */
  373. addEngine: function(name, spec){
  374. if(!name) return;
  375. var el = et.Element('engine');
  376. el.attrib.name = name;
  377. if(spec){
  378. el.attrib.spec = spec;
  379. }
  380. this.doc.getroot().append(el);
  381. },
  382. /**
  383. * Removes all the engines with given name
  384. * @param {String} name the engine name.
  385. */
  386. removeEngine: function(name){
  387. var engines = this.doc.findall('./engine/[@name="' +name+'"]');
  388. for(var i=0; i < engines.length; i++){
  389. var children = this.doc.getroot().getchildren();
  390. var idx = children.indexOf(engines[i]);
  391. if(idx > -1){
  392. children.splice(idx,1);
  393. }
  394. }
  395. },
  396. getEngines: function(){
  397. var engines = this.doc.findall('./engine');
  398. return engines.map(function(engine){
  399. var spec = engine.attrib.spec || engine.attrib.version;
  400. return {
  401. 'name': engine.attrib.name,
  402. 'spec': spec ? spec : null
  403. };
  404. });
  405. },
  406. /* Get all the access tags */
  407. getAccesses: function() {
  408. var accesses = this.doc.findall('./access');
  409. return accesses.map(function(access){
  410. var minimum_tls_version = access.attrib['minimum-tls-version']; /* String */
  411. var requires_forward_secrecy = access.attrib['requires-forward-secrecy']; /* Boolean */
  412. return {
  413. 'origin': access.attrib.origin,
  414. 'minimum_tls_version': minimum_tls_version,
  415. 'requires_forward_secrecy' : requires_forward_secrecy
  416. };
  417. });
  418. },
  419. /* Get all the allow-navigation tags */
  420. getAllowNavigations: function() {
  421. var allow_navigations = this.doc.findall('./allow-navigation');
  422. return allow_navigations.map(function(allow_navigation){
  423. var minimum_tls_version = allow_navigation.attrib['minimum-tls-version']; /* String */
  424. var requires_forward_secrecy = allow_navigation.attrib['requires-forward-secrecy']; /* Boolean */
  425. return {
  426. 'href': allow_navigation.attrib.href,
  427. 'minimum_tls_version': minimum_tls_version,
  428. 'requires_forward_secrecy' : requires_forward_secrecy
  429. };
  430. });
  431. },
  432. write:function() {
  433. fs.writeFileSync(this.path, this.doc.write({indent: 4}), 'utf-8');
  434. }
  435. };
  436. function featureToPlugin(featureElement) {
  437. var plugin = {};
  438. plugin.variables = [];
  439. var pluginVersion,
  440. pluginSrc;
  441. var nodes = featureElement.findall('param');
  442. nodes.forEach(function (element) {
  443. var n = element.attrib.name;
  444. var v = element.attrib.value;
  445. if (n === 'id') {
  446. plugin.name = v;
  447. } else if (n === 'version') {
  448. pluginVersion = v;
  449. } else if (n === 'url' || n === 'installPath') {
  450. pluginSrc = v;
  451. } else {
  452. plugin.variables[n] = v;
  453. }
  454. });
  455. var spec = pluginSrc || pluginVersion;
  456. if (spec) {
  457. plugin.spec = spec;
  458. }
  459. return plugin;
  460. }
  461. module.exports = ConfigParser;