コード例 #1
0
ファイル: yuan.js プロジェクト: Inzaghi2012/spm
Yuan.prototype.upload = function(data, callback) {
  if (data.private && this.server === 'http://spmjs.io') {
    log.error('yuan', 'this is a private repo');
    process.exit(3);
  }

  var auth = spmrc.get(this.authKey);
  var query = {
    urlpath: 'repository/upload/',
    method: 'POST',
    auth: auth
  };
  var self = this;
  var form = new FormData();
  form.append('name', data.name || '');
  form.append('version', data.version || '');
  form.append('tag', data.tag || 'latest');
  form.append('file', fs.createReadStream(data.tarfile));
  form.getLength(function(err, len) {
    log.info('target', self.server);
    var r = self.request(query, callback);
    r._form = form;
    r.setHeader('Content-Length', len);
  });
};
コード例 #2
0
    this.apps.upload = function (guid, zipFile, callback) {
        var fileStream = typeof zipFile === 'string' ?
            require('fs').createReadStream(zipFile) :
            zipFile;

        var form = new FormData();
        form.append('application', fileStream,
                { contentType: 'application/zip' });

        form.append('resources', '[]');

        form.getLength(function (err, length) {
            if (err) {
                return callback(err);
            }

            var req = request({
                endpoint: [ 'apps', guid, 'bits' ].join('/'),
                method: 'PUT'
            }, callback);

            req.setHeader('Content-Length', length);
            req._form = form;
        });
    };
コード例 #3
0
ファイル: utils.js プロジェクト: tjramage/pivotaltracker
function upload(token, pathSegments, filepath, options, cb) { //cb(error)

    var path = Array.isArray(pathSegments) ? pathSegments.join('/') : '';
    var url = 'https://' + options.pivotalHost + '/services/v5/' + path;

    var form = new FormData();
    form.append('file', fs.createReadStream(filepath));

    form.getLength(function(err,length) {
        var opts = {
            headers: {
                'Content-Length': length,
                'X-TrackerToken': token
            }
        };
        var r = request.post(url, opts, function(error, res, body) {

            if (typeof body === 'string') {
                try {
                    body = JSON.parse(body);
                }
                catch(e) {
                    error = error || e;
                }
            }
            cb(error, _cleanInbound(body));
        });
        r._form = form;
    });
}
コード例 #4
0
ファイル: Source.js プロジェクト: aficionado/bigml-node
Source.prototype.create = function (path, args, cb) {
  /**
   * Creates a source and builds customized error and resource info
   *
   * Uses HTTP POST to send source content.
   *
   * Returns a BigML resource wrapped in an object that includes
   *   code: HTTP status code
   *   resource: The resource/id
   *   location: Remote location of the resource
   *   object: The resource itself
   *   error: An error code and message
   *
   */
  var uri, form, formLength, headers, arg, options,
    message = 'Failed to create the source. First parameter must be' +
    ' a file path.';

  options = utils.optionalCUParams(arguments, message);

  uri = this.connection.resourceUrls.source + this.connection.auth;
  form = new FormData();
  try {
    form.append('file', fs.createReadStream(path));
  } catch (err) {
    return options.cb(err, null);
  }
  for (arg in options.args) {
    if (options.args.hasOwnProperty(arg)) {
      form.append(arg, options.args[arg]);
    }
  }
  form.getLength(function (error, length) {
    formLength = length;
    headers = form.getHeaders({'content-length': formLength});
    var r = request.post({
      uri        : uri,
      method     : 'POST',
      strictSSL  : constants.VERIFY,
      headers    : headers
    }, function (error, response) {
      var code = constants.HTTP_INTERNAL_SERVER_ERROR,
        result = utils.makeEmptyResult('resource',
                                       code,
                                       'The resource couldn\'t be created');

      return utils.requestResponse('create', constants.HTTP_CREATED,
                                   [constants.HTTP_PAYMENT_REQUIRED,
                                    constants.HTTP_UNAUTHORIZED,
                                    constants.HTTP_BAD_REQUEST,
                                    constants.HTTP_NOT_FOUND],
                                   error, undefined, response,
                                   result, options.cb);
    });

    form.pipe(r);
  });
};
コード例 #5
0
exports.multipartFileUpload = function(req, logError, callback)
{

    var headers = {};
    var form = new FormData();

    if(req.filePath !== undefined)
    {
        if(req.apiServerUrl !== undefined && req.route !== undefined && req.route.path !== undefined)
        {
            headers.accept = "application/json";
            headers.Authorization = 'OAuth '+ req.accessToken;

            for(var key in req.headers){
                headers[key] = req.headers[key];
            }

            var requestFilePathParams =  req.filePath.split("/");

            form.getLength(function(err, length){
                if (err)
                {
                    callback({error: err});
                }
                else
                {
                    var baseRequest = request.defaults({
                        headers: headers
                    })

                    var r = baseRequest.put(req.apiServerUrl+req.route.path, function optionalCallback(err, httpResponse, body)
                    {
                        callback({error:err, data: httpResponse, response: body});
                    });

                    var mform = r.form();
                    mform.append("postBody", JSON.stringify(req.body.postBody));
                    mform.append('file', fs.createReadStream(req.filePath), {filename: requestFilePathParams[requestFilePathParams.length-1]});
                }
            });

        }
        else
        {
            console.log("required params missing, check if these params are supplied req.apiServerUrl, req.route.path required");
            callback({error: true});
        }
    }
    else
    {
        console.log("fsReadStream not supplied, looking in req.filePath");
        callback({error: true});
    }
};
コード例 #6
0
ファイル: zapi.js プロジェクト: caliyeti/ZephyrZapi
    function attachScreenshotToExecution(key, stream, screenShotName) {
        var deferred = protractor.promise.defer();

        var zurl = 'http://' + params.zapiAuth + '@' + params.zapiHost + '/rest/zapi/latest/attachment?entityId=' + getExecutionIdByKey(key) + '&entityType=EXECUTION';
        var request = require('request');
        var FormData = require('form-data');

        var form = new FormData();

        form.append('file', stream, {
            contentType: 'image/png',
            filename: screenShotName
        });
        //form.append('file', stream, {contentType: 'image/png'});

        form.getLength(function (err, length) {
            if (err) {
                //console.log("ERROR");
                deferred.fulfill(false);
                return requestCallback(err);
            }

            var zheaders = {
                "X-Atlassian-Token": "nocheck",
                "Accept": "application/json",
                "Content-Type": "multipart/form-data",
                "Content-Length": length
            }

            var r = request.post({
                url: zurl,
                headers: zheaders
            }, requestCallback);

            r._form = form;
            r.on('end', function () {
                deferred.fulfill(true);
            });
        });

        function requestCallback(err, res, body) {
            //console.log("Status", res.statusCode);
            //console.log("Headers", JSON.stringify(res.headers));
            //console.log(body);
        }
        return deferred.promise;
    }
コード例 #7
0
	self.request.get(UPLOAD_END_POINT, authOptions, function(error, response, body) {
		if (error) {
			if (typeof callback === 'function') {
				callback(error);
			}
			return;
		}

		var form = new FormData();
		Object.keys(body.data).forEach(function(key) {
			form.append(key, body.data[key]);
		});
		form.append('file', fs.createReadStream(filePath));

		// Content-Length isn't sent by request for streaming forms so this is a workaround.
		// See https://github.com/mikeal/request/issues/316#issuecomment-10800882
		form.getLength(function(error, length) {
			// Not posting to the API so not using `this.request`
			var req = request.post(body.upload_url, { headers: { 'content-length' : length } }, function(error, response) {
				if (error || response.statusCode !== 204) {
					if (typeof callback === 'function') {
						if ( ! error) {
							error = new Error(http.STATUS_CODES[response.statusCode]);
						}
						callback(error);
					}
					return;
				}

				var parameters = {
					device_iden: deviceIden,
					type: 'file',
					file_name: fileName,
					file_type: fileType,
					file_url: body.file_url
				};

				if (message) {
					parameters.body = message;
				}

				self.push(parameters, callback);
			});
			req._form = form;
		});
	});
コード例 #8
0
ファイル: baidu.js プロジェクト: nevill/baohe
Baidu.prototype.upload = function(file, callback) {
  var remotePath = path.join(AppRoot, path.basename(file));
  var uploadUrl = util.format(Service.upload.url,
    this.session.accessToken,
    encodeURIComponent(remotePath));

  // workround to set header content-length, see: https://github.com/mikeal/request/issues/316#issuecomment-10800882
  var form = new FormData();
  form.append('file', fs.createReadStream(file));

  form.getLength(function(err, length) {
    var options = {
      url: uploadUrl,
      headers: { 'content-length': length }
    };
    var req = request
      .post(options, responseCallback('upload', function() {
      callback();
    }));
    req._form = form;
  });
};
コード例 #9
0
ファイル: zapi.js プロジェクト: caliyeti/ZephyrZapi
    function attachLogToExecution(key, stream, filename, callback) {
        var zurl = 'http://' + params.zapiAuth + '@' + params.zapiHost + '/rest/zapi/latest/attachment?entityId=' + getExecutionIdByKey(key) + '&entityType=EXECUTION';

        var request = require('request');
        var FormData = require('form-data');

        var form = new FormData();

        form.append('file', stream, {
            contentType: 'text/plain',
            filename: filename
        });

        form.getLength(function (err, length) {
            if (err) {
                //console.log("ERROR");
                return requestCallback(err);
            }

            var zheaders = {
                "X-Atlassian-Token": "nocheck",
                "Accept": "application/json",
                "Content-Type": "multipart/form-data"
            }

            var r = request.post({
                url: zurl,
                headers: zheaders
            }, requestCallback);
            r._form = form;
            r.setHeader('content-length', length);
        });

        function requestCallback(err, res, body) {
            //console.log("Status", res.statusCode);
            //console.log("Headers", JSON.stringify(res.headers));
            //console.log(body);
        }
    }
コード例 #10
0
ファイル: form.js プロジェクト: anykeyanykey/request
                ProxyRequester.getRequester(tokens[0].proxyDoc, (err, requester)=> {
                    if (err) return callback(err);

                    let parsed = url.parse(response.response.upload_url);



                    let formData = new FormData();

                    formData.append('photo', fileStream, {
                        filename: "flag_russia.png",//item.originalname,
                        contentType: "image/png",//item.mimetype,
                    });

                    var params = {
                        host: parsed.host,
                        port: parsed.protocol === 'http:' ? 80 : 443,
                        path: parsed.path,
                        method: 'POST',
                        timeout: 10000,
                        headers: {
                            'Content-Type': formData.getHeaders()['content-type']
                        },
                        formData: formData
                    };

                    formData.getLength(function (err, length) {
                        if (err) return callback(err);
                        params.headers['Content-Length'] = length;
                        requester.request(params, (err, response)=> {
                            if (err) return callback(err);
                            return callback(null, response);
                        }).on('progress', (data)=> {
                            console.log(`${data.percent}%`);
                        });
                    });
                });
コード例 #11
0
var edsFileUploadRequest = function(options, callback){
    callback = callback || noop;

    var objData = {
        targetFileProperty: {
            id: options.edsMultipartData.objId,
            objectType: options.edsMultipartData.objType,
            propertyName: options.edsMultipartData.fieldName
        }
    };

    var filePath = options.edsMultipartData.filePath;
    var address = options.protocol + "://" + options.hostname + options.path;

    // create multipart/form data
    var form = new FormData();
    form.append('object', JSON.stringify(objData));
    form.append('filename', path.basename(filePath));
    form.append('file', fs.createReadStream(filePath));
    form.getLength(function(err, theLength){

        options.headers['Content-Length'] = theLength;

        var req = request.post(address, {
            headers: options.headers
        }, function(e, r, body) {
            // TODO: fix the statusCode. Should be 200?
            if(!e && (r.statusCode == 201)){
                body = JSON.parse(body);
                callback(null, body);
            } else {
                callback(r.statusCode, body);
            }
        });
        req._form = form
    });
};
コード例 #12
0
kettle.test.request.formData.sendPayload = function (that) {

    var requestOptions = that.options;
    var req = that.nativeRequest;
    var form = new FormData();

    // Append all files to form
    fluid.each(requestOptions.formData.files, function (filePath, fieldKey) {
        var filePaths = fluid.makeArray(filePath);
        filePaths.forEach(function (filePath) {
            var resolved = fluid.module.resolvePath(filePath);
            form.append(fieldKey, fs.createReadStream(resolved));
        });
    });

    // Append all fields to form
    fluid.each(requestOptions.formData.fields, function (fieldValue, fieldKey) {
        form.append(fieldKey, fieldValue);
    });

    // Set the request headers from the form
    var formHeaders = form.getHeaders();

    fluid.each(formHeaders, function (value, name) {
        req.setHeader(name, value);
    });

    // Calculate the length and set the header,
    // then send the request; we need to do this
    // using the async method, as noted at
    // https://github.com/form-data/form-data#notes

    form.getLength(function (arg1, knownLength) {
        req.setHeader("Content-Length", knownLength);
        form.pipe(req);
    });
};
コード例 #13
0
    redisClient.get(req.body["session_id"] + "_dev", function (err, sessiondata) {

        var uuid_data;
        if (err) {

        }
        else {


            uuid_data = JSON.parse(sessiondata);
            if (uuid_data["posturl"] && uuid_data["posturl"] != "none") {
                //fs.createReadStream(req.files.result["path"]).pipe(request.post(uuid_data["posturl"]))


                var form = new FormData();
                form.append("sessionid", req.body["session_id"]);
                form.append("filename", fs.createReadStream(req.files.result["path"]));

                form.getLength(function (err, length) {
                    if (err) {
                        return requestCallback(err);
                    }

                    var r = request.post(uuid_data["posturl"], requestCallback);
                    r._form = form;
                    r.setHeader('content-length', length);

                });

                function requestCallback(err, res, body) {
                    console.log(body);
                }
            }

        }
    });
コード例 #14
0
ファイル: connector.js プロジェクト: nagykacsa/diploma
    _request: function (segments, method, callback, query, payload, data, headers, pipe, config, getUrl) {
      //Self-invocation with the same params should work transparently for the caller.
      var methods = ['POST', 'GET', 'DELETE', 'PUT', 'OPTIONS'];
      if (!_.contains(methods, method)) {
        throw new Error('Unsupported method: ' + method);
      }

      var self = this,
        url;

      config = _.merge({
        timeout: 120000,
        num_retries: 3,
        ebackoff: 1000
      }, config || {});

      if (_.isString(segments)) {
        url = segments;
      } else if (data) {
        url = 'https://upload.box.com/api/2.0/' + segments.join('/');
      } else {
        url = 'https://www.box.com/api/2.0/' + segments.join('/');
      }

      var opts = {
        url: url,
        method: method,
        headers: {
          Authorization: 'Bearer ' + self.access_token
        },
        timeout: config.timeout
      };

     
      
      if (data) {
        opts.json = true;
      } else {
        _.merge(opts, {
          json: (_.contains(['POST', 'PUT'], method)) ? payload : true,
          qs: query
        });
      }

      headers = headers || {};
      _.merge(opts.headers, headers);
      
      if (data) {
        var form = new FormData();

        form.append('filename', data);
        
        //console.log(data);
        
        _.forIn(payload, function (value, key) {
          form.append(key, value);
        });
        
        form.getLength(function (err, length) {
          if (err) {
            return callback(err);
          }

          // var r = request(opts, _handler);
          // r._form = form;
          // r.setHeader('content-length', length);
          //console.log("form: ",form);
          
          self.queue.push({
            opts: opts,
            handler: _handler,
            form: form,
            'content-length': length
          });
        });
      } else {
        if (pipe && method === 'GET') {
          opts.followRedirect = false;
        }
        // request(opts, _handler);
        self.queue.push({
          opts: opts,
          handler: _handler
        });
      }
      
      function _handler(err, res, body) {
        if (err) {
          if (config.num_retries === 0) {
            return callback(err);
          }

          var ebck = config.ebackoff;

          config.num_retries--;
          config.ebackoff *= 2;
          self.log.debug('Waiting %d milliseconds before retrying...', ebck);

          return _.delay(function () {
            self._request(segments, method, callback, query, payload, data, headers, pipe, config);
          }, ebck);
        }

        switch (res.statusCode) {
        case 200:
          if (pipe) {
            pipe.end(new Buffer(body, 'binary'));
          } else {
            callback(err, body);
          }
          break;

        case 202:
        case 429:
          var wait = res.headers['retry-after'] * 1000 + _.random(0, 10000);
          self.log.debug('Status: %d, Retry-After: %d', res.statusCode, res.headers['retry-after']);
          self.log.debug('Waiting %d milliseconds before retrying...', wait);
          _.delay(function () {
            self._request(segments, method, callback, query, payload, data, headers, pipe, config);
          }, wait);
          break;

        case 301:
          opts.url = res.headers.location;
          // request(opts, _handler);
          self.queue.push({
            opts: opts,
            handler: _handler
          });
          break;

        case 302:
        	if(getUrl){
        		callback(res.headers.location);
        	} else {
        		request.get(res.headers.location, callback).pipe(pipe);
        	}
          break;

        case 400:
        case 403:
        case 404:
        case 405:
        case 409:
        case 412:
          callback(new Error(JSON.stringify(body)));
          break;

        case 401:
          //First check if stale access tokens still exist, and only then refresh.
          //Prevents multiple refreshes.
          if (self.isAuthenticated()) {
            self.log.debug('Access token expired. Refreshing...');
            self._revokeAccess();
            var tokenParams = {
                client_id: self.client_id,
                client_secret: self.client_secret,
                grant_type: 'refresh_token',
                refresh_token: self.refresh_token
              },
              authUrl = 'https://www.box.com/api/oauth2/token';

            request.post({
              url: authUrl,
              form: tokenParams,
              json: true
            }, function (err, res, body) {
              if (err) {
                return callback(err);
              }
              if (res.statusCode === 200) {
                self.log.debug('New tokens received.');
                self._setTokens(body);
                self._request(segments, method, callback, query, payload, data, headers, pipe, config);
              } else {
                callback(new Error(JSON.stringify(body)));
              }
            });
          } else {
            self.ready(function () {
              self._request(segments, method, callback, query, payload, data, headers, pipe, config);
            });
          }
          break;

        default:
          callback(err, body);
        }
      }
    },
コード例 #15
0
ファイル: Source.js プロジェクト: faradayio/bigml-node
Source.prototype.create = function (path, args, retry, cb) {
  /**
   * Creates a source and builds customized error and resource info
   *
   * Uses HTTP POST to send source content.
   *
   * Returns a BigML resource wrapped in an object that includes
   *   code: HTTP status code
   *   resource: The resource/id
   *   location: Remote location of the resource
   *   object: The resource itself
   *   error: An error code and message
   *
   * @param {string} path Path to the source file
   * @param {object} args Arguments that should be used in the call. For
   *                      example {name: "my_name"}
   * @param {boolean} retry Turns on/off the retries if a resumable
   *                        condition happens
   * @param {function} cb Callback function
   */

  var self = this, uri, form, formLength, headers, arg, options,
    message = 'Failed to create the source. First parameter must be' +
    ' a file path.';

  if (arguments.length > 0) {
    options = utils.optionalCUParams(arguments, message);
    options.path = path;
    options = utils.setRetries(options);
    options.type = 'source';
    options.operation = 'create';
    this.options = options;
  } else {
    options = this.options;
  }
  uri = this.connection.resourceUrls.source + this.connection.auth;
  form = new FormData();
  try {
    form.append('file', fs.createReadStream(options.path));
  } catch (err) {
    return options.cb(err, null);
  }
  for (arg in options.args) {
    if (options.args.hasOwnProperty(arg)) {
      form.append(arg, options.args[arg]);
    }
  }
  form.getLength(function (error, length) {
    formLength = length;
    headers = form.getHeaders({'content-length': formLength});
    var r = request.post({
      uri        : uri,
      method     : 'POST',
      strictSSL  : constants.VERIFY,
      headers    : headers
    }, function (error, response) {
      var code = constants.HTTP_INTERNAL_SERVER_ERROR,
        result = utils.makeEmptyResult('resource',
                                       code,
                                       'The resource couldn\'t be created');

      return utils.requestResponse('create', self, constants.HTTP_CREATED,
                                   createErrors,
                                   error, undefined, response,
                                   result, options.cb);
    });

    form.pipe(r);
  });
};
コード例 #16
0
function uploadApp(params, callback) {
    if (!params) {
        return callback('Not enough parameters');
    }
    var functionName = arguments.callee.name;
    var form = new FormData(),
        CRLF = '\r\n',
        length = dataRemoteFile.length,
        filename = params.appFile.substr(params.appFile.lastIndexOf('/') + 1),
        options = {
            header: CRLF + [
                '--' + form.getBoundary(),
                'Content-Disposition: form-data; name="application"; filename="' + filename + '"',
                'Content-Type: application/zip',
                'Content-Length: ' + length,
                'Content-Transfer-Encoding: binary'
            ].join(CRLF) + CRLF + CRLF,
            knownLength: length
        };

    form.append('async', 'true');
    form.append('resources', JSON.stringify(resourceMatched));
    form.append('application', dataRemoteFile, options);

    form.getLength(function () {
        var req = request({
            method: 'PUT',
            url: getUrl(params, 'api') + '/v2/apps/' + appGuid + '/bits',
            headers: {
                'Accept': 'application/json',
                'Authorization': type + ' ' + token
            },
            qs: {
                'async': 'true'
            },
            formData: {
                'async': 'true',
                'resources': JSON.stringify(resourceMatched),
                'application': dataRemoteFile
            }
        }, function (error, response, body) {
            if (error) {
                return callback(error);
            }
            if (response.statusCode === 401) {
                return callback('Authorization error');
            }
            try {
                body = JSON.parse(body);
            } catch (e) {
                body = null;
            }
            if (response.statusCode >= 400) {
                return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));
            }
            if (body && body.metadata && body.metadata.guid && response.statusCode === 201) {
                return callback(null, body.metadata.guid);
            }
            return callback('Upload fail');
        });
        req._form = form;
    });
}
コード例 #17
0
ファイル: launch.js プロジェクト: pauliejes/xapi-launch
    app.post("/launch/:key/xAPI/statements", validateLaunchSession(function(req, res, next)
    {
        //here, we need to validate the activity and append the context data
        //then forward to our registered LRS
        var postedStatement = req.body;
        if (postedStatement.constructor !== 'Array')
        {
            postedStatement = [postedStatement];
        }
        for (var i = 0; i < postedStatement.length; i++)
        {
            if (!postedStatement[i].context)
            {
                postedStatement[i].context = {};
            }
            var contextActivities = postedStatement[i].context.contextActivities;
            if (!contextActivities)
                contextActivities = postedStatement[i].context.contextActivities = {
                    parent: req.launch.xapiForm(),
                    grouping: req.content.xapiForm()
                };
            else
            {
                //if the parent is exists
                if (contextActivities.parent)
                {
                    //if it's an array, check that the parent launch is included, add if not. 
                    //if it's not an array, make it an array and include the context
                    if (contextActivities.parent.constructor == "Array")
                    {
                        var included = false;
                        for (var i in contextActivities.parent)
                        {
                            if (contextActivities.parent[i].uuid = req.launch.uuid)
                            {
                                included = true;
                                break;
                            }
                        }
                        if (!included)
                        {
                            contextActivities.parent.push(req.launch.xapiForm());
                        }
                    }
                    else
                    {
                        contextActivities.parent = [contextActivities.parent, req.launch.xapiForm()];
                    }
                }
                else
                {
                    contextActivities.parent = req.launch.xapiForm();
                }
                //if it's an array, check that the grouping content is included, add if not. 
                //if it's not an array, make it an array and include the context
                if (contextActivities.grouping)
                {
                    if (contextActivities.grouping.constructor == "Array")
                    {
                        var included = false;
                        for (var i in contextActivities.grouping)
                        {
                            if (contextActivities.grouping[i].url = req.content.url)
                            {
                                included = true;
                                break;
                            }
                        }
                        if (!included)
                        {
                            contextActivities.grouping.push(req.content.xapiForm());
                        }
                        if (req.media)
                        {
                            var included = false;
                            for (var i in contextActivities.grouping)
                            {
                                if (contextActivities.grouping[i].url = req.media.url)
                                {
                                    included = true;
                                    break;
                                }
                            }
                            if (!included)
                            {
                                contextActivities.grouping.push(req.media.xapiForm());
                            }
                        }
                    }
                    else
                    {
                        contextActivities.grouping = [contextActivities.grouping, req.content.xapiForm()];
                        if (request.media)
                        {
                            contextActivities.grouping.push(req.media.xapiForm());
                        }
                    }
                }
                else
                {
                    if (!req.media)
                        contextActivities.grouping = req.content.xapiForm();
                    else
                        contextActivities.grouping = [req.content.xapiForm(), req.media.xapiForm()];
                }
            }
        }
        var demoPrivateKey =  config.publicSigningKey || "-----BEGIN RSA PRIVATE KEY-----\nMIICXgIBAAKBgQCq480SFNQfy/HSkox2swxsan4w6zEXQGyMmSMyvxInEj26wuOY\nxj3N7E0GzX5qjKXS12ZjSi618XNgdFuJq4b68oyf5URiR1qrTa3EAK36hPsxtXnE\nO9fse0tcMI5gh5mVk378mTTOl5Kv7MLe9gBkjMveoqg3Tmu1It3Zmh8wZwIDAQAB\nAoGBAIHKOGNmPGHV9Nl4goRYorPpAeTHjGZbgNYcLPaK1g+ktAuXn2LWFfTDZxEm\nm7/zCLKk9Feu7OE0++sjFK7v/rh2D9gU+ocGljjp+uySZkpFovtrszs9mnT7iLMR\nNytenT/sZUsLA72PUP9MDryzMdW1dJi95PdstGJxugAy943hAkEA1uy4jpl6TDai\nITc7Z4IVnH/w2X8p4pkSQJtOtFm2RQlX7MIDNlNZJx4g2G8wc2juonoAIWnWjEnO\nMsKO4szGFwJBAMuMqEORZru0NgVXB2vkVYsZ6fZdcwZlavpaj2wI0miUEIb2dPLe\niNQhuGOL6wZTTIwpphUAp0hmfDOg79TuqjECQQCXiHmrWPzIRXDUWHvSw/32xKIM\nx0LB2EjtMlMwh1wimq7aaAQZxnRCR1TDJMoVZPNzrO7woA28BcGTOmfB8rzrAkEA\ngV83GyrxNuBFbYNxDhwkWrLvx0yB7VDMe67PdYTt5tYk4wMGNc9G/D0qaurlSDHt\ndzCJhNPTfurUiiQCCz5eIQJACZgrfK3pe8YzkmCWJMzFUgcX7O/8qU2aSuP+xkMI\nCvTe0zjWjU7wB5ftdvcQb6Pf7NCKwYJyMgwQHZttHmb4WQ==\n-----END RSA PRIVATE KEY-----";
        var demoPublicKey = config.privateSigningKey || "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCq480SFNQfy/HSkox2swxsan4w\n6zEXQGyMmSMyvxInEj26wuOYxj3N7E0GzX5qjKXS12ZjSi618XNgdFuJq4b68oyf\n5URiR1qrTa3EAK36hPsxtXnEO9fse0tcMI5gh5mVk378mTTOl5Kv7MLe9gBkjMve\noqg3Tmu1It3Zmh8wZwIDAQAB\n-----END PUBLIC KEY-----";
        var jwt = require('jsonwebtoken');
        var FormData = require('form-data');
        var form = new FormData();
        var CRLF = "\r\n";
        var options = {
            header: CRLF + '--' + form.getBoundary() + CRLF + 'content-type: application/json' + CRLF + "Content-Disposition: form-data; name=\"statement\"" + CRLF + CRLF
        };
        var sigs = [];
        for (var i = 0; i < postedStatement.length; i++)
        {
            var token = jwt.sign(postedStatement[i], demoPrivateKey,
            {
                algorithm: 'RS256',
                'headers':
                {
                    'x5c': [(new Buffer(demoPublicKey)).toString('base64')]
                }
            });
            console.log(token);
            var hash = require("crypto").createHash('sha256')
                .update(token).digest();
            hash = hash.toString('base64');
            if (!postedStatement[i].attachments)
                postedStatement[i].attachments = [];
            var attachmentMetadata = {
                "usageType": "http://adlnet.gov/expapi/attachments/signature",
                "display":
                {
                    "en-US": "A JWT signature"
                },
                "description":
                {
                    "en-US": "Signing this doc was posted from the Launch Server"
                },
                "contentType": "application/octet-stream",
                "length": Buffer.byteLength(token),
                "sha2": hash,
            }
            postedStatement[i].attachments.push(attachmentMetadata);
            sigs.push(
            {
                options:
                {
                    header: CRLF + '--' + form.getBoundary() + CRLF + 'x-experience-api-hash: ' + hash + CRLF + "content-type: application/octet-stream" + CRLF + "Content-Transfer-Encoding: binary" + CRLF + CRLF
                },
                val: (new Buffer(token)).toString('base64')
            })
        }
        form.append('statement', JSON.stringify(postedStatement), options);
        for (var i in sigs)
            form.append('signature', sigs[i].val, sigs[i].options);

        function combine(a, b)
        {
            for (var i in b)
                a[i] = b[i];
            return a;
        }
        form.getLength(function(err, len)
        {
            //console.log("got len ", len);
            var concat = require('concat-stream');
            form.pipe(concat(function(buf)
            {
                // buf is a Node Buffer instance which contains the entire data in stream
                // if your stream sends textual data, use buf.toString() to get entire stream as string
                var streamContent = buf.toString();
                require('fs').writeFile("./base64", buf);
                (function post(url)
                {
                    //send the modified statement up to the configured LRS
                    var postReq = require('request')(
                    {
                        uri: url,
                        method: "POST",
                        followRedirect: true,
                        body: buf,
                        headers: combine(
                        {
                            "X-Experience-API-Version": req.headers[
                                "x-experience-api-version"],
                            "Content-Length": len
                        }, form.getHeaders())
                    }).auth(req.lrsConfig.username, req.lrsConfig.password, true);
                    postReq.headers["content-type"] = postReq.headers["content-type"].replace("form-data", "mixed");
                    //console.log(postReq.headers);
                    //console.log(streamContent);
                    postReq.on('response', function(r) {});
                    postReq.on("response", function(r)
                    {
                        var data = "";
                        postReq.on('data', function(chunk)
                        {
                            data += chunk;
                        });
                        postReq.on('end', function()
                        {
                            if (r.statusCode == 301)
                            {
                                post(r.headers.location);
                            }
                            else
                            {
                                res.status(r.statusCode).send(data);
                                //console.log(data);
                            }
                        })
                    });
                    postReq.on('error', function(e)
                    {
                        res.status(500).send(e);
                    });
                })(req.lrsConfig.endpoint + "/statements");
            }));
        })
    }));
コード例 #18
0
ファイル: mailin.js プロジェクト: 2naive/mailin
                    function (cbAuto, results) {
                        if (_this.options.disableWebhook) return cbAuto(null);

                        logger.info('Sending request to webhook ' + _this.options.webhook);
                        var finalizedMessage = results.finalizeMessage;

                        /* Convert the attachments contents from Buffer to
                         * base64 encoded strings and remove them from the
                         * message. They will be posted as multipart of a form
                         * as key values pairs (attachmentName, attachmentContent). */
                        logger.profile('Convert attachments to strings');
                        var attachmentNamesAndContent = {};
                        finalizedMessage.attachments.forEach(function (attachment) {
                            attachmentNamesAndContent[attachment.generatedFileName] = attachment.content.toString('base64');
                            delete attachment.content;
                        });
                        logger.profile('Convert attachments to strings');

                        logger.verbose(finalizedMessage);

                        /* Send the request to the webhook. This is a bit
                         * convoluted way of posting a multipart form, but it
                         * seems to be the only working pattern (see
                         * https://github.com/mikeal/request/issues/316). */
                        var form = new FormData();
                        form.append('mailinMsg', JSON.stringify(finalizedMessage));
                        for (var attachmentName in attachmentNamesAndContent) {
                            if (attachmentNamesAndContent.hasOwnProperty(attachmentName)) {
                                form.append(attachmentName, attachmentNamesAndContent[attachmentName]);
                            }
                        }

                        form.getLength(function (err, length) {
                            logger.verbose('Webhook length: ' + length / 1000000 + 'mb');

                            var headers = form.getHeaders();
                            headers['Content-Length'] = length;

                            var r = request.post({
                                url: _this.options.webhook,
                                timeout: 30000,
                                headers: headers
                            }, function (err, resp, body) {
                                /* Avoid memory leak by hinting the gc. */
                                finalizedMessage = null;
                                attachmentNamesAndContent = null;

                                if (err || resp.statusCode !== 200) {
                                    logger.warn('Error in posting to webhook ' + _this.options.webhook);
                                    if (resp) logger.warn('Response status code: ' + resp.statusCode);
                                    return cbAuto(null);
                                }

                                logger.info('Succesfully posted to webhook ' + _this.options.webhook);
                                logger.verbose(body);
                                return cbAuto(null);
                            });

                            r._form = form;
                        });
                    }
コード例 #19
0
var uploadPhoto = function (args) {
  var path = args['path'];
  var flickrConsumerKey = args['flickrConsumerKey'];
  var flickrConsumerKeySecret = args['flickrConsumerKeySecret'];
  var oauthToken = args['oauthToken'];
  var oauthTokenSecret = args['oauthTokenSecret'];
  var callback = args['callback'];
  var optionalArgs = args['optionalArgs'];

  var parameters = {
    oauth_nonce : generateNonce(),
    oauth_timestamp : generateTimestamp(),
    oauth_consumer_key : flickrConsumerKey,
    oauth_signature_method : 'HMAC-SHA1',
    oauth_version : '1.0',
    oauth_token : oauthToken
  };

  if (optionalArgs) {
    for (prop in optionalArgs) {
      parameters[prop] = optionalArgs[prop];
    }
  }

  var cryptoMessage = createSortedKeyValuePairString('POST&https%3A%2F%2F' +
                                    'up.flickr.com%2Fservices%2Fupload%2F&',
                                    parameters, '%3D', '%26', percentEncodeTwice);

  var cryptoKey = flickrConsumerKeySecret + '&' + oauthTokenSecret;
  var signature = createSignature(cryptoMessage, cryptoKey);
  var parameterString = createSortedKeyValuePairString('', parameters, '=', '&',
                                                        percentEncode);

  parameterString += '&oauth_signature=' + signature;

  var form = new FormData();

  for (var prop in parameters) {
    form.append(prop, parameters[prop]);
  }
  form.append('photo', fs.createReadStream(path));

  form.getLength(function (err, length) {
    if (err) return;

    var path = '/services/upload/';

    var httpsOptions = {
      hostname: 'up.flickr.com',
      port: 443,
      path: path + '?' + parameterString,
      method: 'POST',
      headers: {
        'content-length': length,
        'content-type': 'multipart/form-data; boundary=' + form.getBoundary(),
      }
    };

    var req = https.request(httpsOptions, function(res) {
      // console.log('upload statusCode: ', res.statusCode);
      res.on('data', function(d) {
        //console.log('upload result: ' + d);
        /* for example
        upload statusCode:  200
        upload result: <?xml version="1.0" encoding="utf-8" ?>
        <rsp stat="ok">
        <photoid>14369421238</photoid>
        </rsp>
        */
        var photoId = findStringBetween(String(d), '<photoid>', '</photoid>');
        // console.log('found photo Id: ' + photoId);
        if (callback && (callback instanceof Function)) {
          if (photoId) {
            // console.log('calling callback with photoId ' + photoId);
            callback(null, photoId);
          } else {
            callback(new Error('Upload error: ' + d));
          }
        }
      });
    });
    form.pipe(req);
    req.end();

    req.on('error', function(e) {
      console.error(e);
      if (callback && (callback instanceof Function)) {
        callback(new Error('Upload error: ' + e));
      }
    });
  });
};
コード例 #20
0
ファイル: douban.js プロジェクト: AllenWeb/qiaowei
 _postForm:function (options, callback) {
   for(var i in options){
     if(options.path.indexOf("{{"+i+"}}")!=-1){
       options.path=options.path.replace("{{"+i+"}}",options[i]);
       delete options[i];
     }
   }
   var form = new FormData();
   for (var i in options) {
     if (i=="image") {
       form.append('image', fs.createReadStream(options[i]));
     } else {
       form.append(i, options[i].toString().replace(/__multi__/g, ""));
     }
   };
   var headers = form.getHeaders();
   form.getLength(function(err,len){
     headers ["Content-length"] =len ;
     headers ['Authorization'] = "Bearer "+options.access_token
     var data=""
     var re = https.request({
       method: 'POST',
       host: self.API_HOST,
       path: options.path.replace(self.API_BASE_URL,""),
       headers: headers
     });
     form.pipe(re);
     re.on('response', function(res){
       var chunks = [], size = 0;
       res.on('data', function (chunk) {
         size += chunk.length;
         chunks.push(chunk);
       });  
       res.on('end', function () {
         var data = null;
         switch (chunks.length) {
           case 0:
             data = new Buffer(0);
             break;
           case 1:
             data = chunks[0];
             break;
           default:
             data = new Buffer(size);
             for (var i = 0, pos = 0, l = chunks.length; i < l; i++) {
               chunks[i].copy(data, pos);
               pos += chunks[i].length;
             }
             break;
         }
         var e=null;
         var body=data.toString();
         try{
           body=JSON.parse(body)
           if(body.error_response){
             e=new Error(body.error_response.msg)
           }
         }catch(error){
           e=error;
         }
         callback && callback(e, body); 
       })
     });
     callback && callback(null, {}); 
   })
    
   
 },