Downloads the resources for a source language.

@param project {{}}
@returns {Promise}
556715
function(project) {
        return request.read(project.resourceUrl)
            .then(function(response) {
                // consume resource data
                if(response.status !== 200) return Promise.reject(response);

                let data;
                try {
                    data = JSON.parse(response.data);
                } catch(err) {
                    return Promise.reject(err);
                }

                for(let resource of data) {
                    try {
                        resource.slug = resource.slug.toLowerCase();
                        switch (resource.slug) {
                            case 'obs':
                            case 'ulb':
                                resource.status.translate_mode = 'all';
                                break;
                            default:
                                resource.status.translate_mode = 'gl';
                        }

                        resource.status.pub_date = resource.status.publish_date;
                        resource.translation_words_assignments_url = resource.tw_cat;
                        resource.type = 'book';
                        resource.formats = [{
                            package_version: rc.tools.spec.version,
                            mime_type: rc.tools.typeToMime('book'),
                            modified_at: resource.date_modified,
                            imported: 0,
                            url: resource.source
                        }];
                        library.addResource(resource, project.id);

                        // coerce notes to resource
                        let helpResource = {
                            slug: 'tn',
                            name: 'translationNotes',
                            type: 'help',
                            status: resource.status,
                            formats: [{
                                package_version: rc.tools.spec.version,
                                mime_type: rc.tools.typeToMime('help'),
                                modified_at: resource.date_modified,
                                imported: 0,
                                url: resource.notes
                            }]
                        };
                        helpResource.status.translate_mode = 'gl';
                        helpResource.status.source_translations = [{
                            language_slug: project.source_language_slug,
                            resource_slug: 'tn',
                            version: resource.status.version
                        }];
                        if (resource.notes) {
                            library.addResource(helpResource, project.id);
                        }

                        // coerce questions to resource
                        helpResource.slug = 'tq';
                        helpResource.name = 'translationQuestions';
                        helpResource.formats = [{
                            package_version: rc.tools.spec.version,
                            mime_type: rc.tools.typeToMime('help'),
                            modified_at: resource.date_modified,
                            imported: 0,
                            url: resource.checking_questions
                        }];
                        helpResource.status.source_translations = [{
                            language_slug: project.source_language_slug,
                            resource_slug: 'tq',
                            version: resource.status.version
                        }];
                        if (resource.checking_questions) {
                            library.addResource(helpResource, project.id);
                        }

                        // add words project (this is insert/update so it will only be added once)
                        // TRICKY: obs tw has not been unified with bible tw yet so we add it as separate project.
                        let wordsProjectId = library.addProject({
                            slug: project.slug === 'obs' ? 'bible-obs' : 'bible',
                            name: 'translationWords' + (project.slug === 'obs' ? ' OBS' : ''),
                            desc: '',
                            icon: '',
                            sort: 100,
                            chunks_url: '',
                            categories: []
                        }, project.source_language_id);

                        // add resource to words project
                        let dictResource = _.clone(helpResource);
                        dictResource.slug = 'tw';
                        dictResource.name = 'translationWords';
                        dictResource.type = 'dict';
                        dictResource.formats = [{
                            package_version: rc.tools.spec.version,
                            mime_type: rc.tools.typeToMime('dict'),
                            modified_at: resource.date_modified,
                            imported: 0,
                            url: resource.terms
                        }];
                        dictResource.status.source_translations = [{
                            language_slug: project.source_language_slug,
                            resource_slug: 'tw',
                            version: resource.status.version
                        }];
                        if (resource.terms) {
                            library.addResource(dictResource, wordsProjectId);
                        }
                    } catch (err) {
                        return Promise.reject(err);
                    }
                }
            });
    }
445142
function _createResource() {
    this._log(
        util.format(
            'PromisePool._createResource() - creating client - count=%d min=%d max=%d',
            this._count, this._opts.min, this._opts.max
        ),
        'verbose'
    );

    return Promise.resolve(this._opts.create());
}
114996
function updateSource(zipFile, project) {
	return project.updateZip(zipFile)
	.catch((error) => {
		console.error("Project source with ID: " + project.id + " couldn't be updated.");
		console.trace(error);
		throw error;
	});
}
263552
function(app, dest, from) {

    // Assess our situation
    var localPath = from || app.task.pkg.dir;
    var needsDownload = (app.task.pkg.url && !localPath) ? true : false;
    log.debug(format('App requires download: %s', needsDownload));

    // Start the chain
    return Promise.try(function() {

      // If this is a remote package then download it and
      // return the directory
      if (needsDownload) {
        return kbox.util.download.downloadFiles([app.task.pkg.url], dest);
      }

      // Otherwise just copy from --from
      else {

        return Promise.fromNode(function(cb) {

          // Make sure we overwrite
          var options = {clobber: true};

          // Do the copying
          fs.copy(localPath, dest, options, cb);
          log.debug(format('Copied %s to %s', localPath, dest));

        });

      }

    });

  }
1164508
function getLanguages(options) {
  options.hash = _private.getDevHash(options.secret);
  return _private.makeRequest(_getLink(options), 'Unable to fetch project languages');
}
831298
public Resource getResource(String name, Locale locale, String encoding) throws IOException {
        name = UrlUtils.cleanName(name);
        locale = cleanLocale(locale);
        return loadResource(name, locale, encoding);
    }
802856
function mapSources (sourceMap, mapCallback) {
  let chain = Promise.resolve()
  function pushChain (path, index, arr) {
    chain = chain
      .then(() => mapCallback(path))
      .then(replacement => {
        arr[index] = replacement || path
      })
  }
  if (sourceMap.sources) {
    sourceMap.sources.forEach(pushChain)
  }
  if (sourceMap.sections) {
    sourceMap.sections.forEach(section => {
      if (section.map && section.map.sources) {
        section.map.sources.forEach(pushChain)
      }
    })
  }
  return chain.then(() => sourceMap)
}
41903
function processResult(loaderContext, resultPromise) {
  const { callback } = loaderContext;

  resultPromise
    .then(
      ({ css, map, imports }) => {
        imports.forEach(loaderContext.addDependency, loaderContext);
        return {
          // Removing the sourceMappingURL comment.
          // See removeSourceMappingUrl.js for the reasoning behind this.
          css: removeSourceMappingUrl(css),
          map: typeof map === 'string' ? JSON.parse(map) : map,
        };
      },
      (lessError) => {
        if (lessError.filename) {
          loaderContext.addDependency(lessError.filename);
        }
        throw formatLessError(lessError);
      }
    )
    .then(({ css, map }) => {
      callback(null, css, map);
    }, callback);
}
559307
function downloadPlatform(projectRoot, platform, version, opts) {
    var target = version ? (platform + '@' + version) : platform;
    return Q().then(function() {
        if (opts.fetch) {
            //append cordova to platform
            if(platform in platforms) {
                target = 'judpack-'+target;
            }

            //gitURLs don't supply a platform, it equals null
            if(!platform) {
                target = version;
            }

            events.emit('log', 'Using cordova-fetch for '+ target);
            return fetch(target, projectRoot, opts);
        }

        if (cordova_util.isUrl(version)) {
            events.emit('log', 'git cloning: ' + version);
            var parts = version.split('#');
            var git_url = parts[0];
            var branchToCheckout = parts[1];
            return lazy_load.git_clone(git_url, branchToCheckout).fail(function(err) {
                // If it looks like a url, but cannot be cloned, try handling it differently.
                // it's because it's a tarball of the form:
                //     - wp8@https://git-wip-us.apache.org/repos/asf?p=cordova-wp8.git;a=snapshot;h=3.7.0;sf=tgz
                //     - https://api.github.com/repos/msopenTech/cordova-browser/tarball/my-branch
                events.emit('verbose', err.message);
                events.emit('verbose', 'Cloning failed. Let\'s try handling it as a tarball');
                return lazy_load.based_on_config(projectRoot, target, opts);
            });
        }
        return lazy_load.based_on_config(projectRoot, target, opts);
    }).fail(function (error) {
        var message = 'Failed to fetch platform ' + target +
            '\nProbably this is either a connection problem, or platform spec is incorrect.' +
            '\nCheck your connection and platform name/version/URL.' +
            '\n' + error;
        return Q.reject(new CordovaError(message));
    }).then(function(libDir) {
        return getPlatformDetailsFromDir(libDir, platform);
    });
}
1192848
function loadResources (styleArray) {
  const publicPath = '/public';
  var results = {};
  for (let source of styleArray) {
    if (source.resources) {
      for (let category in source.resources) {
        if (source.resources.hasOwnProperty(category)) {
          if (!results.hasOwnProperty(category)) {
            results[category] = {};
          }
          for (let item in source.resources[category]) {
            results[category][item] = source.resources[category][item];
            results[category][item].dataPromise = new Promise(resolve => {
              getJSON(publicPath + results[category][item].src)
                .then(data => {
                  resolve(data);
                });
            });
          }
        }
      }
    }
  }
  return results;
}
276789
function i18n() {
				const i18nElement = findChild(libraryAppData, "i18n");
				if ( i18nElement ) {
					const i18n = i18nElement._;
					if ( i18n === "false" ) {
						return false;
					} else if ( i18n === "true" ) {
						return "messagebundle.properties";
					} else {
						return i18n;
					}
					// log.verbose("  sap.ui5/library/i18n property taken from .library appData: '%s'", library.i18n);
				} else {
					if ( libBundle.findResource("messagebundle.properties") != null ) {
						// log.verbose("  sap.ui5/library/i18n property determined from resources: '%s'", library.i18n);
						return "messagebundle.properties";
					} else {
						return false;
					}
				}
			}
1106017
@Route(method = HttpMethod.GET, uri = "i18n/bundles/{file<.+>}.json")
    public Result getBundleResourceForI18Next(@QueryParameter("locales") String listOfLocales,
                                              @HttpParameter(HeaderNames.IF_NONE_MATCH) String ifNoneMatch) {
        // Parse the list of locale
        List<Locale> locales = new ArrayList<>();
        if (!Strings.isNullOrEmpty(listOfLocales)) {
            String[] items = listOfLocales.split(" ");
            for (String item : items) {
                // Manage the 'dev' value (it's the default locale used by i18next
                if ("dev".equalsIgnoreCase(item)) {
                    locales.add(InternationalizationService.DEFAULT_LOCALE);
                } else {
                    locales.add(Locale.forLanguageTag(item));
                }
            }
        }

        String etag;
        StringBuilder builder = new StringBuilder();
        for (Locale locale : locales) {
            builder.append(service.etag(locale));
        }
        etag = builder.toString();

        if (ifNoneMatch != null && ifNoneMatch.equals(etag)) {
            return new Result(Status.NOT_MODIFIED);
        }

        // i18next use a specific Json Format
        ObjectNode result = json.newObject();
        for (Locale locale : locales) {
            ObjectNode lang = json.newObject();
            ObjectNode translation = json.newObject();
            lang.set("translation", translation);
            Collection<ResourceBundle> bundles = service.bundles(locale);
            for (ResourceBundle bundle : bundles) {
                for (String key : bundle.keySet()) {
                    populateJsonResourceBundle(translation, key, bundle.getString(key));
                }
            }
            String langName = locale.toLanguageTag();
            if (locale.equals(InternationalizationService.DEFAULT_LOCALE)) {
                langName = "dev";
            }
            result.set(langName, lang);
        }
        return ok(result).with(HeaderNames.ETAG, etag);
    }
1155351
public function downloadProject($project, $version, $type, $path = null)
    {
        $commandKey = str_replace(':', '.', $this->getName());

        $this->getIo()->comment(
            sprintf(
                $this->trans('commands.' . $commandKey . '.messages.downloading'),
                $project,
                $version
            )
        );

        try {
            $destination = $this->drupalApi->downloadProjectRelease(
                $project,
                $version
            );

            if (!$path) {
                $path = $this->getExtractPath($type);
            }

            $projectPath = sprintf(
                '%s/%s',
                $this->appRoot,
                $path
            );

            if (!file_exists($projectPath)) {
                if (!mkdir($projectPath, 0777, true)) {
                    $this->getIo()->error(
                        sprintf(
                            $this->trans('commands.'.$commandKey.'.messages.error-creating-folder'),
                            $projectPath
                        )
                    );
                    return null;
                }
            }

            $zippy = Zippy::load();
            if (PHP_OS === 'WIN32' || PHP_OS === 'WINNT') {
                $container = AdapterContainer::load();
                $container['Drupal\\Console\\Zippy\\Adapter\\TarGzGNUTarForWindowsAdapter'] = function ($container) {
                    return TarGzGNUTarForWindowsAdapter::newInstance(
                        $container['executable-finder'],
                        $container['resource-manager'],
                        $container['gnu-tar.inflator'],
                        $container['gnu-tar.deflator']
                    );
                };
                $zippy->addStrategy(new TarGzFileForWindowsStrategy($container));
            }
            $archive = $zippy->open($destination);
            if ($type == 'core') {
                $archive->extract(getenv('MSYSTEM') ? null : $projectPath);
            } elseif (getenv('MSYSTEM')) {
                $current_dir = getcwd();
                $temp_dir = sys_get_temp_dir();
                chdir($temp_dir);
                $archive->extract();
                $fileSystem = new Filesystem();
                $fileSystem->rename($temp_dir . '/' . $project, $projectPath . '/' . $project);
                chdir($current_dir);
            } else {
                $archive->extract($projectPath);
            }

            unlink($destination);

            if ($type != 'core') {
                $this->getIo()->success(
                    sprintf(
                        $this->trans(
                            'commands.' . $commandKey . '.messages.downloaded'
                        ),
                        $project,
                        $version,
                        sprintf('%s/%s', $projectPath, $project)
                    )
                );
            }
        } catch (\Exception $e) {
            $this->getIo()->error($e->getMessage());

            return null;
        }

        return $projectPath;
    }
737107
function inlineResources(projectPath) {

  // Match only TypeScript files in projectPath.
  const files = glob.sync('**/*.ts', {cwd: projectPath});

  // For each file, inline the templates and styles under it and write the new file.
  return Promise.all(files.map(filePath => {
    const fullFilePath = path.join(projectPath, filePath);
    return readFile(fullFilePath, 'utf-8')
      .then(content => inlineResourcesFromString(content, url => {
        // Resolve the template url.
        return path.join(path.dirname(fullFilePath), url);
      }))
      .then(content => writeFile(fullFilePath, content))
      .catch(err => console.error('An error occured: ', err));
  }));
}
800906
function updateSourceWithId(zipFile, projectId) {
	return fetchProject(projectId)
	.then((project) => {
		return updateSource(zipFile, project);
	})
	.catch((error) => {
		console.trace(error);
		throw error;
	});
}
266885
function downloadProjectCompilationWithId(projectId, platform, outputDir) {
	return fetchProject(projectId)
	.then((project) => {
		return downloadProjectCompilation(project, platform, outputDir);
	})
	.catch((error) => {
		console.trace(error);
		throw error;
	});
}
579360
function buildJSONSource() {

  var data = getModularSource();

  addCorePackage();
  prepareData();
  outputJSON('source.json', data);

  function addCorePackage() {
    data.modules.unshift({
      name: 'Core'
    });
    data.packages.unshift({
      name: 'Sugar',
      type: 'core',
      module: 'Core',
      dependencies: [],
      bodyWithComments: readFile('lib/core.js').trim()
    });
  }

  function bundleSetPackages() {
    var packages = [], handledSets = {}, p;

    for (var i = 0; i < data.packages.length; i++) {
      p = data.packages[i];
      if (p.set) {
        // If the package has been handled already then just skip.
        if (!handledSets[p.namespace + p.setName]) {
          packages.push({
            setName: p.setName,
            name: p.setName.replace(/[\[\]]/g, ''),
            sample: p.set.slice(0, 3).concat('...').join(', '),
            type: p.type,
            alias: p.alias,
            module: p.module,
            namespace: p.namespace,
            dependencies: p.dependencies,
            bodyWithComments: p.bodyWithComments
          });
          handledSets[p.namespace + p.setName] = true;
        }
      } else {
        packages.push(p);
      }
    }

    return packages;
  }

  function prepareData() {
    var bundledPackages = bundleSetPackages();
    data.modules.forEach(function(m) {
      indentField(m, 'comment');
    });
    bundledPackages.forEach(function(p) {

      // Pre-indenting all packages rather than doing it on compile to
      // save some cycles and also correctly calculate the package size.
      indentField(p, 'blockStart');
      indentField(p, 'blockEnd');
      indentField(p, 'bodyWithComments');

      cleanSourcePackage(p);
    });
    data.packages = bundledPackages;
  }

  function indentField(p, field) {
    if (p[field]) {
      p[field] = p[field].replace(/^(?=.)/gm, '  ');
    }
  }

  function cleanSourcePackage(p) {
    if (sourcePackageIsDependency(p)) {
      delete p.type;
    }
    delete p.vars;
    delete p.target;
    delete p.body;
    delete p.path;
    delete p.assigns;
    delete p.comments;
    delete p.defineMethod;
    delete p.varDependencies;
    compactField(p, 'bodyWithComments');
    compactField(p, 'dependencies');
  }

  function compactField(p, field) {
    var val = p[field];
    if (!val || (Array.isArray(val) && !val.length)) {
      delete p[field];
    }
  }

}