Handling requests for browsing file-system

@param {Object|String} options
@param {Function} callback
172211
function handle(options, callback) {
  if (_.isString(options)) {
    options = { path: options };
  }

  if (_.isObject(options)) {
    const opts = { };
    _.merge(opts, config, options);
    options = opts;
  } else {
    options = _.cloneDeep(config);
  }

  options.path = options.path || config.get("home");
  return stat(options.path, function(err, stats) {
    if (err) {
      return callback(err);
    }

    const done = wrap(stats, callback);

    if (stats.isDirectory()) {
      options.dirStats = stats;
      return processDir(options, done);
    } else if (stats.isFile()) {
      return processFile(options, done);
    }

    return callback(null, null);
  });
}
476143
function upload (options, callback) {
  const promise = (
    Promise.resolve(options)
      .then(applyDefaults)
      .then(validateOptions)
      .then(opts => {
        options = opts
        return options
      })
      .then(transformOptions)
      .then(prepareRequest)
      .then(sendRequest)
      .catch(err => {
        return cleanupTempFiles(options)
          .then(() => Promise.reject(err))
      })
      .then(cleanupTempFiles)
  )
  if (callback) {
    promise
      .then(message => callback(null, message))
      .catch(err => callback(err, null))
  }
  return promise
}
1194960
function(params, callback) {
                getFileData = {};

                if (params) {
                    if (typeof params.fileId != 'undefined') {
                        getFileData.fileId = params.fileId;
                    }

                    if (typeof params.hashCode == 'string') {
                        getFileData.hashCode = params.hashCode;
                    }

                    if (typeof params.downloadable == 'boolean') {
                        getFileData.downloadable = params.downloadable;
                    }
                }

                httpRequest({
                    url: SERVICE_ADDRESSES.FILESERVER_ADDRESS +
                    SERVICES_PATH.GET_FILE,
                    method: 'GET',
                    data: getFileData
                }, function(result) {
                    if (!result.hasError) {
                        var queryString = '?';
                        for (var i in params) {
                            queryString += i + '=' + params[i] + '&';
                        }
                        queryString = queryString.slice(0, -1);
                        var file = SERVICE_ADDRESSES.FILESERVER_ADDRESS + SERVICES_PATH.GET_FILE + queryString;
                        callback({
                            hasError: result.hasError,
                            result: file
                        });
                    }
                    else {
                        callback({
                            hasError: true
                        });
                    }
                });
            }
124461
function FileCache(options){
  var self = this;
  // cordova-promise-fs
  this._fs = options.fs;
  if(!this._fs) {
    throw new Error('Missing required option "fs". Add an instance of cordova-promise-fs.');
  }
  // Use Promises from fs.
  Promise = this._fs.Promise;

  // 'mirror' mirrors files structure from "serverRoot" to "localRoot"
  // 'hash' creates a 1-deep filestructure, where the filenames are hashed server urls (with extension)
  this._mirrorMode = options.mode !== 'hash';
  this._retry = options.retry || [500,1500,8000];
  this._cacheBuster = !!options.cacheBuster;

  // normalize path
  this.localRoot = this._fs.normalize(options.localRoot || 'data');
  this.serverRoot = this._fs.normalize(options.serverRoot || '');

  // set internal variables
  this._downloading = [];    // download promises
  this._added = [];          // added files
  this._cached = {};         // cached files

  // list existing cache contents
  this.ready = this._fs.ensure(this.localRoot)
  .then(function(entry){
    self.localInternalURL = typeof entry.toInternalURL === 'function'? entry.toInternalURL(): entry.toURL();
    self.localUrl = entry.toURL();
    return self.list();
  });
}
616917
function(file, callback) {
        if (isBrowser && file instanceof window.File) {
            // Browser File instance
            return this.addImageFromBuffer(file, callback);
        }

        // File on filesystem. Note: the reason why we need the size of the file
        // is because of reverse proxies like Varnish which doesn't handle chunked
        // Transfer-Encoding properly - instead we need to explicitly pass the
        // content length so it knows not to terminate the HTTP connection
        readers.getLengthOfFile(file, function(err, fileSize) {
            if (err) {
                return callback(err);
            }

            readers.createReadStream(file).pipe(request({
                method: 'POST',
                uri: this.getSignedResourceUrl('POST', this.getImagesUrl()),
                json: true,
                headers: {
                    'Accept': 'application/json',
                    'User-Agent': 'imboclient-js',
                    'Content-Length': fileSize
                },
                onComplete: function(addErr, res, body) {
                    callback(addErr, body ? body.imageIdentifier : null, body, res);
                }
            }));
        }.bind(this));

        return this;
    }
253623
function (options, callback) {
    if (this.stopAppServerFunc) {
      this.stopAppServerFunc(options, callback);
    } else if (this.appServer) {
      this.appServer.stop(callback);
    } else {
      callback();
    }
  }
861760
function( files, options, callback ) {
	if ( !Array.isArray( files ) ) {
		files = [files];
	}
	if ( typeof options === 'function' ) {
		callback = options;
		options = null;
	} else if ( typeof options === 'string' ) {
		options = { msg: options };
	}
	options = options || {};
	addExtraOptions( [ 'quiet', 'depth', 'msg' ], options );
	executeSvn( [ 'commit' ].concat( files ), options, callback );
}
403736
function loadImage (file, callback, options) {
    var img = document.createElement('img')
    var url
    img.onerror = function (event) {
      return loadImage.onerror(img, event, file, callback, options)
    }
    img.onload = function (event) {
      return loadImage.onload(img, event, file, callback, options)
    }
    if (typeof file === 'string') {
      loadImage.fetchBlob(
        file,
        function (blob) {
          if (blob) {
            file = blob
            url = loadImage.createObjectURL(file)
          } else {
            url = file
            if (options && options.crossOrigin) {
              img.crossOrigin = options.crossOrigin
            }
          }
          img.src = url
        },
        options
      )
      return img
    } else if (
      loadImage.isInstanceOf('Blob', file) ||
      // Files are also Blob instances, but some browsers
      // (Firefox 3.6) support the File API but not Blobs:
      loadImage.isInstanceOf('File', file)
    ) {
      url = img._objectURL = loadImage.createObjectURL(file)
      if (url) {
        img.src = url
        return img
      }
      return loadImage.readFile(file, function (e) {
        var target = e.target
        if (target && target.result) {
          img.src = target.result
        } else if (callback) {
          callback(e)
        }
      })
    }
  }
129112
function(url, callback) {
        if (isBrowser) {
            // Browser environments can't pipe, so download the file and add it
            return this.getImageDataFromUrl(url, function(err, data) {
                if (err) {
                    return callback(err);
                }

                this.addImageFromBuffer(data, callback);
            }.bind(this));
        }

        // Pipe the source URL into a POST-request
        request({ uri: url }).pipe(request({
            method: 'POST',
            uri: this.getSignedResourceUrl('POST', this.getImagesUrl()),
            json: true,
            headers: {
                'Accept': 'application/json',
                'User-Agent': 'imboclient-js'
            },
            onComplete: function(err, res, body) {
                callback(err, body ? body.imageIdentifier : null, body, res);
            }
        }));

        return this;
    }
442962
function(options, callback) {
        var that = this;
        var data = that._searchInBbox(options.bbox);
        callback(null, data);
    }
1123544
function(file, callback) {
        var number = arguments[2] || 0;
        var location = url.parse(file);
        var protocol = location.protocol === 'http:' ? http : https;
        var timeoutEventId;
        var that = this;
        var REDIRECTION_MAX = 3;

        var done = function(errors, data) {
            clearTimeout(timeoutEventId);
            callback(errors, data);
        }


        var request = protocol.request({
                method: 'GET',
                host: location.host,
                hostname: location.hostname,
                path: location.path,
                port: location.port,
                headers: this.adapter.resourceRequestHeaders(file)
            }, function(res) {

                var encoding = res.headers['content-encoding'];
                var type = res.headers['content-type'];
                var statusCode = res.statusCode;
                var errors = null;

                if (/3\d\d/.test(statusCode) && res.headers.location && number < REDIRECTION_MAX) {
                    clearTimeout(timeoutEventId);
                    var file = res.headers.location;
                    number++;
                    that.loadRemoteFile(file, callback, number);
                    return;
                } else if (!/2\d\d/.test(statusCode)) {
                    errors = new Error(res.statusMessage);
                }

                if (type.indexOf('text/') !== 0) {
                    errors = new Error('only supports `text/*` resources');
                }


                if (errors) {
                    done(errors);
                } else {

                    var buffer = new Buffer([]);


                    if (encoding === 'undefined') {
                        res.setEncoding('utf-8');
                    }


                    res.on('data', function(chunk) {
                        buffer = Buffer.concat([buffer, chunk]);
                    });

                    res.on('end', function() {

                        if (encoding === 'gzip') {

                            zlib.unzip(buffer, function(errors, buffer) {
                                if (errors) {
                                    done(errors);
                                } else {
                                    done(null, buffer);
                                }
                            });

                        } else if (encoding == 'deflate') {

                            zlib.inflate(buffer, function(errors, decoded) {
                                if (errors) {
                                    done(errors);
                                } else {
                                    done(null, decoded);
                                }
                            });

                        } else {
                            done(null, buffer);
                        }

                    });

                }

            })
            .on('error', done)
            .on('timeout', function(errors) {
                request.abort();
                done(errors);
            });


        timeoutEventId = setTimeout(function() {
            request.emit('timeout', new Error('have been timeout'));
        }, this.adapter.resourceTimeout);


        request.end();

    }
123411
function (request, callback) {
            if (ariaCoreBrowser.isOpera) {
                // Opera doesn't work with file protocol but the iFrameHack seems to work
                return this._iFrameHack(request, callback);
            }

            this.$BaseXHR.request.call(this, request, callback);
        }
1062224
function(options, callback) {
    request({
      method: 'post',
      url: options.url,
      headers: {
        'Authorization': 'Bearer ' + access_token,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      form: options.data
    },
    function(error, response, body) {
      callback(error, body);
    });
  }
149607
function (options, callback) {

			fs.stat(options.file_path, function (err, stats) {

				if (err) {
					callback(err);
				}
				else {
					var local_date = new Date(stats.mtime).getTime();
					var server_date = new Date(options.server_date).getTime();

					if (options.compare_date === 'newer') {
						callback(null, local_date > server_date);
					}
					else {
						callback(null, local_date < server_date);
					}
				}
			});
		}
1182738
@ObjectiveCName("requestStateWithFileId:withCallback:")
    public void requestState(long fileId, final FileCallback callback) {
        modules.getFilesModule().requestState(fileId, callback);
    }
958732
function(path, callback, opts) {

		if (!callback) callback = function() { };

		var fallbacks = [];
		if (path.each) {
			if (path.length==0) return;
			fallbacks = path;
			path      = fallbacks.shift()+"";
		}

		//Stuff that will make us not want to load files.
		if (this.failedFiles.contains(path)) return;

		opts = opts || {};
		var file = this.worldPath+path+'.js';
		if (opts.rootPath) file = path+'.js';

		var my = this;
		var err;
		var handleData = function(e,raw) {
			data = false;
			if (!raw) {
				err = e;
				my.failedFiles.push(path);
				/* Continue down our list of fallbacks. */
				if (fallbacks.length>0) {
					my.loadFile(fallbacks, callback, opts);
				} else {
					log_error("File not found: "+file);
				}
			} else {
				try { eval('data='+raw); }
				catch (e) { log_error(e); }
			} callback(err, data);
			return data;
		};

		if (opts.sync) {
			try {
				var data = fs.readFileSync(file);
			} catch (e) {
				this.failedFiles.push(path);
				/* Continue down our list of fallbacks. */
				if (fallbacks.length>0) {
					return this.loadFile(fallbacks, callback, opts);
				} else return e;
			} return handleData(false,data);
		} else {
			fs.readFile(file, handleData);
		}
	}
1197339
function(callback) {
            fs.exists(file, function(exists) {
                if(!exists) {
                    rawData = file;
                    if(typeof rawData === "string") rawData = new Buffer(file);
                    return callback();
                }

                fs.readFile(file, function(err, data) {
                    if(err) return callback(err);
                    rawData = data;
                    return callback();
                });
            });
        }