Example #1
0
Dispatcher.register(function(action) {
    switch (action.type) {
    case 'login':
        xhr({
            method: 'POST',
            uri: '/auth/login',
            json: {
                user: action.user,
                pass: action.pass
            }
        }, function(err, resp, data) {
            if (err || data.error !== null || !data.token) {
                return;
            }
            user = data.user;
            token = data.token;
            if (hasLocalStorage) {
                localStorage.setItem('comments.lastToken', token);
                localStorage.setItem('comments.lastUser', user);
            }
            emit();
            CommentActions.loadComments();
        });
        break;
        
    case 'logout':
        xhr({
            method: 'POST',
            uri: '/auth/logout',
            json: {
                token: token
            }
        }, function(err, resp, data) {
            if (err || data.error !== null) {
                return;
            }
            user = '';
            token = '';
            if (hasLocalStorage) {
                localStorage.removeItem('comments.lastToken');
                localStorage.removeItem('comments.lastUser');
            }
            emit();
            CommentActions.loadComments();
        });
        break;    

    default:
        break;
    }
});
Example #2
0
  rtc.recordVideo(function(err, frames) {
    if (err) return logError(err);
    console.log(frames);
    //envia mediante post las imagenes
    xhr({
      uri: '/process',
      method: 'post',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        images: frames
      })
    }, function(err, res, body) {
      if (err) return logError(err)

      body = JSON.parse(body)

      if (body.video) {
        var video = document.querySelector('#video')
        video.src = body.video
        video.loop = true
        video.play()
      }

    });

  }); //start to record
                Object.keys(result).forEach(function (name) {
                    var el = document.createElement('li');
                    var versions = result[name];
                    var text = name + ": " + versions.join(' | ');
                    el.innerHTML = text;
                    document.querySelector('[data-hook~=versions]').appendChild(el);

                    xhr({
                        method: 'get',
                        url: 'http://www.corsproxy.com/registry.npmjs.org/' + name + '/latest',
                    }, function (err, response, body) {
                        if (err) { return debug.error(err); }
                        var json = JSON.parse(body.toString());
                        var latest = json.version;
                        var anyInvalid = false;

                        var link = json.homepage;

                        versionsValidated = versions.map(function (v) {
                            var valid = v === latest;
                            v += (valid ? " ✔" : " ✘");
                            anyInvalid = anyInvalid || !valid;
                            return v;
                        });

                        el.innerHTML = name + ": " +
                                        versionsValidated.join(' | ') +
                                        (anyInvalid ? " - latest: " + latest : "") +
                                        (link ? " <a href='" + link + "' target='_blank'>docs</a>" : "");
                    });
                });
Example #4
0
 on(document.body, '.uploadBlob', 'change', function(e) {
   e.preventDefault()
   var files = Array.prototype.slice.call(e.target.files)
   var first = files[0]
   var container = parents(e.target, '.inspectContainer')
   var key = dom(container).attr('data-key')
   var row = state.rows[key]
   
   var uploaderEl = dom('.blobUploader')
   uploaderEl.html('<progress max="100" value="0"></progress>')
   var progressBar = uploaderEl.select('progress')
   
   var uri = state.remote + '/api/' + row.key + '/' + first.name + '?version=' + row.version
   
   var req = xhr({uri: uri, method: "POST", timeout: 0, body: first, cors: true, onUploadProgress: onProgress}, function(err, resp, body) {
     if (err) notify(err)
     var updated = JSON.parse(body)
     state.rows[updated.key] = updated
     showInspector(updated)
   })
   
   function onProgress(e) {
     if (e.lengthComputable) {
       var progress = ((e.loaded / e.total) * 100)
       progressBar.attr('value', progress)
     }
   }
 })
Example #5
0
api.signUp = function (options, callback) {
  if (!options) {
    return callback(new Error('You must supply options.json to sign up'));
  }

  var json = assign({
    client_id: 'wm_id_zIPGbkEDB5Cv9dCzo7nS'
  }, options.json);

  xhr({
    method: 'POST',
    uri: api.SIGN_UP_URI,
    body: jsonToFormEncoded(json),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }, function (err, resp, body) {
    if (err || resp.statusCode !== 200) {
      return callback(parseJSON(body));
    }
    body = parseJSON(body);
    // Cool, let's authenticate now
    api.authenticate({
      user: body,
      json: {
        uid: body.username,
        password: json.password
      }
    }, callback);
  });
};
Example #6
0
export default (attrs, cb = () => {}) => {
  const attributes = extend({}, attrs, {
    headers: headers(),
  });

  xhr(attributes, cb);
};
Example #7
0
open.addEventListener('click', function(e) {
  var src = '/open' + window.location.pathname

  xhr(src, function(err) {
    if (err) throw err
  })
}, false)
Example #8
0
// GET /queue/${queue_id}/${url}.json
function api(state, method, url, params, callback) {
    const uri = (
        get_protocol() + "//" + get_hostname() +
        "/queue/" + get_queue_id() + "/" +
        url + ".json" +
        (params ? "?" + queryString.stringify(params) : "")
    );
    xhr({
        method: method,
        uri: uri,
        useXDR: true,  // cross-domain, so file:// can reach karakara.org.uk
        json: true,
    }, function (err, resp, body) {
        console.groupCollapsed("api(" + uri + ")");
        if(resp.statusCode === 200) {
            console.log(body.data);
            callback(body.data);
        }
        else {
            console.log(err, resp, body);
        }
        console.groupEnd();
    })

}
Example #9
0
function loadTexture(cb) {
  var handle = gl.createTexture()
  gl.bindTexture(gl.TEXTURE_2D, handle)
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)

  xhr({
    uri: '../test/fixtures/test-dxt1.dds',
    responseType: 'arraybuffer'
  }, function (err, resp, data) {
    if (err)
      return cb(err)

    var dds = parseDDS(data)
    var ext = gl.getExtension('WEBGL_compressed_texture_s3tc')
    
    var internalFormat = getFormat(ext, dds.format)

    dds.images.forEach(function (image, i) {
      var array = new Uint8Array(data, image.offset, image.length)
      var width = image.shape[0]
      var height = image.shape[1]
      gl.compressedTexImage2D(gl.TEXTURE_2D, i, internalFormat, width, height, 0, array);
    })

    cb(null)
  })
}
			return new Promise(function(resolveCallback, rejectCallback) {
				const options = {
					url: endpoint.getUrl(data, host, port, secure),
					method: endpoint.getAction().getHttpVerb(),
					json: endpoint.getPayload(data)
				};

				xhr(options, (error, response, body) => {
					if (error) {
						rejectCallback(error);
					} else if (response.statusCode !== 200) {
						let message;

						if (_.isObject(body) && _.isString(body.message)) {
							message = body.message;
						} else {
							message = 'The server returned an HTTP ' + response.statusCode + ' error.';
						}

						rejectCallback(new Error(message));
					} else {
						resolveCallback(body);
					}
				});
			});
Example #11
0
function get (url, callback) {
  xhr({ method: 'GET', url: url, json: true, timeout: 30000 }, function (err, resp, body) {
    if (err) return callback(err)
    if (resp.statusCode !== 200) return callback(new Error('HTTP status code: ' + resp.statusCode))
    callback(null, body)
  })
}
 require('./github-get-blob')(options, function (err, res) {
   if (err) return callback(err)
   request(requestOptions, function (err, res, body) {
     if (err) return callback(err)
     callback(null, body)
   })
 })
IdSiteRequestExecutor.prototype.execute = function (xhrRequestOptions,callback) {

  var executor = this;

  if (typeof xhrRequestOptions !== 'object') {
    throw new Error('Must provide xhrRequestOptions as first parameter');
  }

  if (typeof callback !== 'function') {
    throw new Error('Must provide callback as second parameter');
  }

  if (!xhrRequestOptions.headers) {
    xhrRequestOptions.headers = {};
  }

  if (!executor.authToken) {
    return callback(new Error(strings.errors.NO_AUTH_TOKEN));
  }

  xhrRequestOptions.headers.Authorization = 'Bearer ' + executor.authToken;

  return xhr(xhrRequestOptions, function xhrCallback (err,response,body) {
    executor.handleResponse(err,response,body,callback);
  });

};
Example #14
0
function xhr(options, callback, errback) {
  var req = xobj();

  if(Object.prototype.toString.call(options) == '[object String]') {
    options = { url: options };
  } else if(options.method !== 'POST' && options.data) {
	options.url = queryBuilder.buildUrl(options.url, options.data);
  }

  req.open(options.method || 'GET', options.url, true);

  if(options.credentials) {
    req.withCredentials = true;
  }

  forIn(options.headers || {}, function (value, key) {
    req.setRequestHeader(key, value);
  });
  
  req.onreadystatechange = function() {  
    if(req.readyState != 4) return;
    
    if([
      200, 
      304
    ].indexOf(req.status) === -1) {
      (errback || noop)(new XhrError('Server responded with a status of ' + req.status, req.status));
    } else {
      (callback || noop)(req);
    }
  };

  req.send(options.data || void 0);
}
Example #15
0
  function fetch (args) {
    if (button.getAttribute('disabled')) return

    loading.classList.add('show')
    $.remove('.error')
    $.remove('.results')
    $.remove('.nolint')

    if ((input.url.value || '').trim().length > 0 && !/^http/.test(input.url.value)) {
      input.url.value = input.url.value.replace(/^|^.*:\/\//, 'http://')
    }
    if (!args) {
      args = {}
      for (var k in input) args[k] = input[k].value
    }

    xhr({
      body: JSON.stringify(args),
      method: 'POST',
      uri: '/',
      headers: { 'Content-Type': 'application/json' }
    },
      function (err, resp, body) {
        try {
          if (!(resp.statusCode >= 200 && resp.statusCode < 400)) {
            throw new Error('The server responded with a bad status: ' + resp.statusCode)
          }
          body = JSON.parse(body)
        } catch (e) { err = e }
        body = body || resp
        body.args = body.args || args
        update(err, body)
      })
  }
Example #16
0
 toBlobURL(stream, 'text/plain', function (err, url) {
   t.error(err)
   xhr(url, function (err, res, buf) {
     t.error(err)
     t.deepEqual(buf, str)
   })
 })
 return new Promise(function (resolve, reject) {
   var responseType = 'text';
   if (type === 'json') responseType = 'text';
   else if (type === 'binary') responseType = 'arraybuffer';
   else if (type === 'blob') responseType = 'blob';
   opt = assign({}, opt, {
     json: false,
     responseType: responseType
   });
   xhr(opt, function (err, res, body) {
     if (err) return reject(err);
     if (/404/.test(res.statusCode)) {
       throw new Error('Resource not found');
     }
     if (!/^2/.test(res.statusCode)) {
       return reject(new Error('Unexpected HTTP Status Code: ' + res.statusCode));
     }
     if (type === 'json') {
       try {
         body = JSON.parse(body);
       } catch (err) {
         return reject(err);
       }
     }
     resolve(body);
   });
 });
Example #18
0
 return new Promise(function (resolve, reject) {
     xhr(url ,{timeout:5000},function(err, res , body){
         if(err) return reject(err);
         if(res.statusCode !== 200) return reject(new Error(body));
         resolve(body)
     })
 })
Example #19
0
function inject(element, callback) {
  callback = typeof callback === 'function' ? callback : noop

  var url = element.getAttribute('src')
  if (!url) return

  var attributes = slice(element.attributes).map(function(attr) {
    return [attr.name, attr.value]
  })

  xhr({
    uri: url
  }, function(err, res, body) {
    if (err) return callback(err)

    if (!res.responseXML) {
      return callback(new Error(
        'Invalid SVG file: ' + url
      ))
    }

    var svg = res.responseXML.querySelector('svg')
    for (var i = 0; i < attributes.length; i++) {
      svg.setAttribute(attributes[i][0], attributes[i][1])
    }

    if (element.parentNode) {
      element.parentNode.replaceChild(svg, element)
    }

    callback(null, svg)
  })
}
Example #20
0
 init: function() {
     if (hasLocalStorage) {
         var lastToken = localStorage.getItem('comments.lastToken');
         var lastUser = localStorage.getItem('comments.lastUser');
         if (lastToken && lastUser) {
             user = lastUser;
             token = lastToken;
             xhr({
                 method: 'POST',
                 uri: '/auth/verify',
                 json: {
                     user: user,
                     token: token
                 }
             }, function(err, resp, data) {
                 if (!err && data.error === null) {
                     // Use last token
                     return;
                 }
                 user = '';
                 token = '';
                 emit();
             });
         }
     }
 },
Example #21
0
	get_favoritos() {
		let that = this;
		//FAZ UMA BUSCA NO BANCO DE DADOS DO FIREBASE
		xhr({
			method: 'get',
			uri: 'https://frontend-desafio.firebaseio.com/favoritos.json',
			headers: {
				'Content-Type': 'application/json'
			}
		}, function (err, resp, body) {

			if (resp.statusCode == 200) {
				let fav = JSON.parse(body);
				//CONVERTE O RESULTADO EM JS ARRAY
				if (fav) {
					let res1 = Object.keys(fav).map(key => {
						let _res = fav[key];
						_res.fbid = key;
						return _res;
					});
					//DEFINE ESTADO COM  RESULTADO 
					that.setState({ r: res1 , loading: false});
				}else{
					//DEFINE ESTADO COM RESULTADO VAZIO
					that.setState({ r: [], loading: false });
				}
			} else {
				//DEFINE ESTADO COM RESULTADO VAZIO
				that.setState({ r: [], loading: false});
			}

		})

	}
IdSiteRequestExecutor.prototype.execute = function (xhrRequestOptions,callback) {

  var executor = this;

  if (typeof xhrRequestOptions !== 'object') {
    throw new Error('Must provide xhrRequestOptions as first parameter');
  }

  if (typeof callback !== 'function') {
    throw new Error('Must provide callback as second parameter');
  }

  if (!xhrRequestOptions.headers) {
    xhrRequestOptions.headers = {};
  }

  if (!executor.authToken) {
    return setTimeout(callback.bind(null,new Error(strings.errors.SESSION_EXPIRED)),1);
  }

  xhrRequestOptions.headers.Authorization = 'Bearer ' + executor.authToken;
  xhrRequestOptions.responseType = 'json';

  return xhr(xhrRequestOptions, function xhrCallback (err,response,body) {
    executor.handleResponse(err,response,body,callback);
  });

};
Example #23
0
  }, function (err, resp, body) {

    if (err || resp.statusCode !== 200) {
      return callback(parseJSON(body));
    }

    body = parseJSON(body);
    var token = body.access_token;

    // If we provided a user object already, just return it with the token
    if (options.user) {
      return callback(null, {token, user: options.user});
    }

    // Assuming the request was successful, get user info
    xhr({
      method: 'GET',
      uri: api.USER_URI,
      headers: {
        Authorization: 'token ' + token
      }
    }, function (err, resp, body) {
      if (err || resp.statusCode !== 200) {
        return callback(parseJSON(body));
      }
      body = parseJSON(body);
      callback(null, {token, user: body});
    });
  });
Example #24
0
function xhr(url, options) {
  var req = xobj()
  req.open(options.method || 'GET', url, true)

  if (options.credentials)
    req.withCredentials = true 
  if (options.headers) for (var key in options.headers) if (hop.call(options.headers, key))
    req.setRequestHeader(key, options.headers[key])

  return new Promise(function(resolve, reject) {
    req.onreadystatechange = function() {
      if (req.readyState !== 4) return
      if (req.status < 400)
        augment({}, resolve)
      else
        augment(new Error('Server responded with a status of ' + req.status), reject)

      function augment(res, cb) {
        res.status = req.status
        res.headers = parseHeaders(req)
        res.body = req.responseText
        cb(res)
      }
    }
    req.onerror = reject

    req.send(options.data || void 0)
  })
}
module.exports = function createBlob (options, callback) {
  var opts = {
    url: 'https://api.github.com/repos/' + options.owner + '/' + options.repo + '/contents/' + options.path,
    headers: { authorization: 'token ' + options.token },
    method: 'put',
    json: {
      path: options.path,
      message: options.message,
      content: base64.encode(utf8.encode(options.content)),
      branch: options.branch
    }
  }

  request(opts, function (err, res, body) {
    if (err) return callback(err)
    var save = {
      branch: options.branch,
      owner: options.owner,
      repo: options.repo,
      location: body.content,
      source: 'github'
    }
    callback(null, body, save)
  })
}
Example #26
0
 return new Promise(function (resolve, reject) {
     xhr(url , {method:"POST",json:  file } ,function(err, res , body){
         if(err) return reject(err);
         if(res.statusCode !== 200) return reject(new Error(body));
         resolve(body)
     })
 })
Example #27
0
   on(document.body, '.json-paste-import .okButton', 'click', function(e) {
     var container = parents(e.target, '.json-paste-import')
     var textarea = dom(container).select('.data-table-cell-copypaste-editor')
     var input = textarea.val()
     if (input.length === 0) return notify('No JSON in input!')
 
     try {
       var rows = input.split(/\r?\n/)
       var objects = []
       rows.map(function(r) { if (r.length > 0) objects.push(JSON.parse(r)) })
     } catch(e) {
       return notify('Could not parse newline separated JSON --- Invalid JSON')
     }
 
     notify('Uploading data...')
 
     xhr({uri: state.remote + '/api/bulk?results=true', method: "POST", body: input, cors: true, headers: {"content-type": "application/json"}}, function(err, resp, body) {
       if (err) return notify(err)
       var lines = body.split(/\r?\n/)
       var created = []
       var updated = []
       var conflicts = []
       lines.map(function(r) {
         if (r.length === 0) return
         var row = JSON.parse(r)
         if (row.conflict) conflicts.push(row)
         else if (row.version === 1) created.push(row)
         else updated.push(row)
       })
       notify("New: " + created.length + ' rows, updated: ' + updated.length + ' rows, conflicts: ' + conflicts.length + ' rows')
       refreshTable()
     })
     dialog.hide()
     dialogOverlay.hide()
   })
Example #28
0
const loadTrack = function(src, track) {
  let opts = {
    uri: src
  };
  let crossOrigin = isCrossOrigin(src);

  if (crossOrigin) {
    opts.cors = crossOrigin;
  }

  XHR(opts, Fn.bind(this, function(err, response, responseBody) {
    if (err) {
      return log.error(err, response);
    }

    track.loaded_ = true;

    // Make sure that vttjs has loaded, otherwise, wait till it finished loading
    // NOTE: this is only used for the alt/video.novtt.js build
    if (typeof window.WebVTT !== 'function') {
      if (track.tech_) {
        let loadHandler = () => parseCues(responseBody, track);
        track.tech_.on('vttjsloaded', loadHandler);
        track.tech_.on('vttjserror', () => {
          log.error(`vttjs failed to load, stopping trying to process ${track.src}`);
          track.tech_.off('vttjsloaded', loadHandler);
        });

      }
    } else {
      parseCues(responseBody, track);
    }

  }));
};
Example #29
0
File: user.js Project: kuno/csviz
 return new Promise(function(resolve, reject) {
   if (!self._token)
     return reject(new Error('401'));
   xhr({
     uri: 'http://csviz.dev.wiredcraft.com/user',
     headers: {
       'Content-Type': 'application/json',
       'Authorization': 'Bearer ' + self._token
     }
   },
   function(err, resp, body) {
     if(err) {
       self.clear()
       return reject(err);
     }
     if (resp.statusCode === 200) {
       try {
         var attrs = JSON.parse(body)
       } catch (e) {
         return reject(e)
       }
       self.attrs = attrs
     }
     resolve(resp);
   });
 });
Example #30
0
  function go (files) {
    var file = valid(files);
    if (!file) {
      return;
    }
    var form = new FormData();
    var options = {
      'Content-Type': 'multipart/form-data',
      headers: {
        Accept: 'application/json'
      },
      method: configure.imageUploads.method,
      url: configure.imageUploads.url,
      timeout: configure.imageUploads.timeout,
      body: form
    };
    form.append(configure.imageUploads.key, file, file.name);
    up.upload.classList.add('pmk-prompt-uploading');
    xhr(options, done);

    function done (err, xhr, body) {
      up.upload.classList.remove('pmk-prompt-uploading');
      if (err) {
        up.failed.classList.add('pmk-prompt-error-show');
        return;
      }
      var json = JSON.parse(body);
      dom.input.value = json.url + ' "' + json.alt + '"';
      close();
      cb(dom.input.value);
    }
  }