コード例 #1
0
ファイル: twilio.js プロジェクト: VictoriousResistance/iDioma
const twilioSetup = (store, renderApp) => {
  const conversationStarted = (conversation) => {
    ReactDOM.render(<Video conversation={conversation} handleVideoDisconnectClick={() => { ReactDOM.unmountComponentAtNode(document.getElementById('video')); }} />, document.getElementById('video'));
    conversation.on('disconnected', () => {
      store.dispatch(toggleIsInVideo());
      ReactDOM.unmountComponentAtNode(document.getElementById('video'));
    });
  };

  request('GET', '/token', {
    qs: {
      identity: store.getState().profile.id + '+' + store.getState().profile.firstName + '+' + store.getState().profile.lastName,
    },
  })
  .done(data => {
    const accessManager = new Twilio.AccessManager(JSON.parse(data.body).token);
    const conversationsClient = new Twilio.Conversations.Client(accessManager);
    conversationsClient.listen().then(() => {
      window.conversationsClient = conversationsClient;
      conversationsClient.on('invite', invite => {
        store.dispatch(toggleIsInVideo());
        const sender = invite.from.split('+').slice(1).join(' ');
        ReactDOM.render(<IncomingVideoCallBanner invite={invite} handleConversationStarted={conversationStarted} sender={sender} handleToggleIsInVideo={() => { store.dispatch(toggleIsInVideo()); }} />, document.getElementById('invite'));
        invite.on('canceled', () => {
          ReactDOM.unmountComponentAtNode(document.getElementById('invite'));
          store.dispatch(toggleIsInVideo());
        });
      });
      return renderApp();
    }, error => {
      console.error('Could not connect to Twilio: ' + error.message);
      renderApp();
    });
  });
};
コード例 #2
0
 onConnectClick: (selfId, id, selfFB, otherFB) => {
   request('POST', '/api/relationships', {
     json: {
       newType: 'request',
       selfId,
       matchId: id,
     },
   })
   .done(data => {
     if (data.statusCode === 201) {
       dispatch(unmountMatch(id));
       request('POST', '/service/notifications', {
         json: {
           selfFB,
           otherFB,
         },
       });
       setTimeout(
         () => {
           dispatch(removeMatch(id));
         },
         120
       );
     } else {
       // TODO: handle error
     }
   });
 },
コード例 #3
0
ファイル: validate.js プロジェクト: Calamitizer/IPv6-Heatmap
 var getLiveMd5 = function() {
     return request('GET', cf.url + cf.names.md5)
         .getBody('ascii')
         .then(function(md5) {
             console.log('Live md5 for ' + cf.names.zip + ': ' + md5);
             return md5;
         });
 };
コード例 #4
0
function loadRealName(username, path) {
  if (realNames[username]) return;
  realNames[username] = username;
  request('GET', url.resolve(location.href, path)).getBody().done(function (res) {
    var name = /\<div class\=\"vcard-fullname\" itemprop\=\"name\">([^<]+)\<\/div\>/.exec(res);
    name = name && he.decode(name[1]);
    realNames[username] = name || username;
    update();
  });
}
コード例 #5
0
 roomDeleter: (e, roomIndex, selfId, roomId) => {
   dispatch(deleteRoom(roomIndex));
   e.stopPropagation();
   request('PUT', '/api/rooms', {
     json: {
       userId: selfId,
       roomId,
     },
   });
 },
コード例 #6
0
 _onSubmit(e) {
   e.preventDefault();
   if (!this.state.body) return;
   request('put', '/api/stories', {
     json: {body: this.state.body},
   }).getBody('utf8').then(JSON.parse).done(
     () => this.props.onUpdate()
   );
   this.setState({body: ''});
 }
コード例 #7
0
 handleOnSend: (msg) => {
   // send it
   socket.emitMsg(msg);
   // add it (second argument is a boolean that tells it to add to current room and therefore skip searching for the room)
   dispatch(addMsg(msg, true));
   // add message to database
   request('POST', '/api/messages', {
     json: msg,
   });
 },
コード例 #8
0
ファイル: worker.js プロジェクト: ablage/sync-req
module.exports = function (method, url, options) {

	return thenRequest(method, url, options).then(function (response) {

		return { error: null, response: response };

	}, function (err) {
		return { error: true, response: err.message };

	});
};
コード例 #9
0
ファイル: gittip.js プロジェクト: ForbesLindesay/dashboard
Gittip.prototype.update = function () {
  return request('https://www.gittip.com/' + this.username() + '/public.json').then(function (res) {
    if (res.statusCode !== 200) {
      throw new Error('gittip returned a status code of ' + res.statusCode);
    }
    var body = JSON.parse(res.body);
    this.receiving(body.receiving);
    this.giving(body.giving);
    this.loading(false);
  }.bind(this));
};
コード例 #10
0
ファイル: worldSetup.js プロジェクト: BlueInt32/super-sprint
  that.loadResource = function (resourceNode) {
    if (resourceNode.data === "") {
      throw {
        "ErrorCode": "WORLD_SETUP_ERROR",
        "ErrorMessage": "Supersprint : Empty sub-worlds list !"
      };
    }

    request('GET', resourceNode.data)
      .done(function (retrievedData) {
        var subWorldJson = retrievedData.getBody();
        that.loadRawJson(subWorldJson, resourceNode);
      });
  };
コード例 #11
0
function getShowGuidFromTitle(callback) {
  var rawTitle = 'Studio C';
  if (process.argv.length >= 3) {
    var rawTitle = process.argv[2];
  }

  var parsedTitle = rawTitle.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');

  switch (parsedTitle) {
    case 'extinct':
      return callback('e5f3bb84-3e34-4b51-8d71-e4d538fd93b2');
      break;

    case 'random':
    case 'random-acts':
    case 'randomacts':
      return callback('2f11a156-dfaa-454c-a104-60165b2a5625');
      break;

    case 'tricked':
      return callback('5215330f-fd7d-4f56-a0d8-11cefcb6f204');
      break;

    case 'just-like-mom-and-dad':
      return callback('8b58273c-013f-4370-b50d-e6d68d2ed322');
      break;

    case 'studio-c':
    case 'studioc':
      return callback('c68c4e4f-6322-4a23-8b8e-a5be75b70635');
      break;

    default:
      var request = require('then-request');
      var url = 'http://www.byutv.org/api/Television/GetShowsByName?context=Android%24US%24Release&name=' + encodeURIComponent(rawTitle);
      request('GET', url).then(function (res) {
        var jsonData = JSON.parse(res.getBody('utf-8'));
        if (0 in jsonData) {
          callback(jsonData[0].guid);
        } else {
          console.error("Unknown show!");
        }
      });
  }
}
コード例 #12
0
ファイル: loadtlds.js プロジェクト: FreeFeed/freefeed-lite
module.exports = (function(){
	return request("GET", "http://data.iana.org/TLD/tlds-alpha-by-domain.txt")
	.then(function(res){
		var tlds = res.getBody("utf8").split("\n").reduce((prev,curr)=>{
			if(curr[0] == "#") return prev;
			if(curr.indexOf("XN--") != -1){
				prev[punycode.decode(curr.slice(4)).toLocaleLowerCase()] = true;
			}
			prev[curr.toLocaleLowerCase()] = true;
			return prev;
		} ,{});
		return write("tlds.json", JSON.stringify(tlds), "utf8");
	});
})();
コード例 #13
0
 onUpdateClick: (profile) => {
   request('PUT', '/api/profile', {
     json: {
       id: profile.id,
       languages: profile.languages,
       description: profile.description ? profile.description.replace(/'/g, '\\\'').replace(/</g, '&lt;').replace(/>/g, '&gt;') : 'No description added yet.',
     },
   })
   .done(data => {
     if (data.statusCode === 200) {
       dispatch(completeUpdate());
       window.location.reload();
     }
   });
 },
コード例 #14
0
 chrome.runtime.sendMessage({action: "get-real-name", username: username}, function(response) {
   if (response && response.cached) {
     realNames[username] = response.cached;
     update();
     return;
   }
   request('GET', url.resolve('https://api.github.com/users/', username)).getBody().done(function (res) {
     res = JSON.parse(res);
     if (res.name) {
       realNames[username] = res.name;
       chrome.runtime.sendMessage({action: "set-real-name", username: username, realName: res.name}, function(response) {
       });
     }
     update();
   });
 });
コード例 #15
0
function soapAction(method, responseElement, body) {
    return request(HNAP_METHOD, HNAP_AUTH.URL,
        {
            headers: {
                "Content-Type": "text/xml; charset=utf-8",
                "SOAPAction": '"' + HNAP1_XMLNS + method + '"',
                "HNAP_AUTH": getHnapAuth('"' + HNAP1_XMLNS + method + '"', HNAP_AUTH.PrivateKey),
                "Cookie": "uid=" + HNAP_AUTH.Cookie
            },
            body: body
        }).then(function (response) {
        return readResponseValue(response.getBody(HNAP_BODY_ENCODING), responseElement);
    }).catch(function (err) {
        console.log("error:", err);
    });
}
コード例 #16
0
ファイル: read-month.js プロジェクト: elf-pavlik/pipermail
function readMonth(url, options) {
  url = url.replace(/\/$/, '').replace(/\/date\.html$/, '')
  return request('GET', url + '/date.html', options).getBody('utf8').then(function (body) {
    var pattern = /href=\"(\d+\.html)\"/gi
    var match
    var dedupe = {}
    var urls = []
    while (match = pattern.exec(body)) {
      var u = url + '/' + match[1]
      if (!dedupe[u]) {
        urls.push(u)
        dedupe[u] = u
      }
    }
    return urls
  })
}
コード例 #17
0
 onLoadMoreClick: (self, offset) => {
   // use the offset to get additional matches from db, then
   request('GET', '/api/matches', {
     qs: {
       self,
       offset,
     },
   })
   .done((matches) => {
     if (matches.statusCode === 200) {
       dispatch(addMatches(JSON.parse(matches.body)));
       dispatch(incrementOffset(20));
     } else {
       // TODO: handle error
     }
   });
 },
コード例 #18
0
 .post((req, res) => {
   const selfFB = req.body.selfFB;
   const otherFB = req.body.otherFB;
   const requestURL = `https://graph.facebook.com/${otherFB}/notifications`;
   request('POST', requestURL, {
     qs: {
       access_token: `${fbConfig.ID}|${fbConfig.SECRET}`,
       href: 'requests',
       template: `@[${selfFB}] sent you a pair request on iDioma.`,
     },
   })
   .done(data => {
     if (data.statusCode === 200) {
       return res.sendStatus(201);
     }
     res.sendStatus(404);
   });
 });
コード例 #19
0
 .done(data => {
   if (data.statusCode === 201) {
     dispatch(unmountMatch(id));
     request('POST', '/service/notifications', {
       json: {
         selfFB,
         otherFB,
       },
     });
     setTimeout(
       () => {
         dispatch(removeMatch(id));
       },
       120
     );
   } else {
     // TODO: handle error
   }
 });
コード例 #20
0
exports.login = function (user, password, url) {
    HNAP_AUTH.User = user;
    HNAP_AUTH.Pwd = password;
    HNAP_AUTH.URL = url;

    return request(HNAP_METHOD, HNAP_AUTH.URL,
        {
            headers: {
                "Content-Type": "text/xml; charset=utf-8",
                "SOAPAction": '"' + HNAP1_XMLNS + HNAP_LOGIN_METHOD + '"'
            },
            body: requestBody(HNAP_LOGIN_METHOD, loginRequest())
        }).then(function (response) {
        save_login_result(response.getBody(HNAP_BODY_ENCODING));
        return soapAction(HNAP_LOGIN_METHOD, "LoginResult", requestBody(HNAP_LOGIN_METHOD, loginParameters()));
    }).catch(function (err) {
        console.log("error:", err);
    });
};
コード例 #21
0
app.get('/places', function(req, res) {
  var keyword = req.query.keyword;
  var location = req.query.location;
  request('GET', 'https://maps.googleapis.com/maps/api/place/nearbysearch/json',
    {
      qs: {
        key: process.env.GOOGLE_PLACES_API_KEY,
        location: location,
        radius: 30000,
        keyword: keyword
      }
    }
  )
  .done(function(data) {
    if (data.statusCode === 200) {
      return res.json(JSON.parse(data.body));
    }
    res.sendStatus(404);
  })
});
コード例 #22
0
function gotCard(id, isNew) {
  request('/account/sponsor', {
    body: JSON.stringify({
      list: listId,
      card: id,
      isNew: isNew,
      name: sponsorName.value,
      url: sponsorURL.value,
      _csrf: csrf
    }),
    headers: {'content-type': 'application/json'},
    method: 'POST'
  }).then(function (res) {
    return res.getBody();
  }).done(function () {
    location.assign(returnAddress || ('/' + listId));
  }, function (err) {
    console.log(err);
    enable();
  });
}
コード例 #23
0
 onHideClick: (selfId, id) => {
   request('POST', '/api/relationships', {
     json: {
       newType: 'reject',
       selfId,
       matchId: id,
     },
   })
   .done(data => {
     if (data.statusCode === 201) {
       dispatch(unmountMatch(id));
       setTimeout(
         () => {
           dispatch(removeMatch(id));
         },
         120
       );
     } else {
       // TODO: handle error
     }
   });
 },
コード例 #24
0
ファイル: read-message.js プロジェクト: masondesu/pipermail
function readMessage(url, options) {
  return request('GET', url, options).getBody('utf8').then(function (body) {
    try {
      var dom = html(body)
      

      console.log('date content is...', dom.select(['html', 'body', 'i']).first().textContent().trim())

      var dateString = dom.select(['html', 'body', 'i']).first().textContent().trim().replace('CEST','UTC+0200').replace('CET','UTC+0100');

      var attemptedDateParse = new Date(dateString);
      // this sucks
      var date = attemptedDateParse !== 'Invalid Date' ? attemptedDateParse : dateString.replace(/[A-Z]+ /, '')

      var header = {
        subject: dom.select(['html', 'body', 'h1']).first().textContent().trim(),
        from: {
          name: dom.select(['html', 'body', 'b']).first().textContent().trim(),
          email: dom.select(['html', 'body', 'a']).first().textContent().trim().replace(' at ', '@')
        },
        reply: dom.select(['html', 'body', 'a']).first().attr('href'),
        date: date,
      }


      return {
        url: url,
        header: header,
        body: dom.select(['html', 'body', 'p', 'pre']).first().textContent().trim()
      }
    } catch (ex) {
      ex.message += '\n\n\n' + body
      throw ex
    }
  })
}
コード例 #25
0
'use strict';

var fs = require('fs');
var Promise = require('promise');
var request = require('then-request');

// https://github.com/adobe/brackets/blob/master/src/extensions/default/HTMLCodeHints/main.js

var host = 'https://raw.githubusercontent.com';
var base = host + '/adobe/brackets/master/src/extensions/default/HTMLCodeHints';

function parseJSON(res) {
  return JSON.parse(res.getBody().toString());
}

var tags = request(base + '/HtmlTags.json', {}).then(parseJSON);
var attrs = request(base + '/HtmlAttributes.json', {}).then(parseJSON);

Promise.all([tags, attrs]).done(function (res) {
  var tags = res[0];
  var attrs = res[1];
  fs.writeFileSync(__dirname + '/lib/autocomplete/html-structure.js', '"use strict";\n\n' +
                   '// This file is generated by /update-auto-complete.js\n' +
                   '// Do not edit it directly\n\n' +
                   'exports.tags = ' + JSON.stringify(tags, null, '  ') + '\n\n' +
                   'exports.attrs = ' + JSON.stringify(attrs, null, '  ') + ';');
});
コード例 #26
0
ファイル: cli.js プロジェクト: ForbesLindesay/monploy-agent
  forever.list(null, function (err, processes) {
    if (err) throw err;
    if ((processes || []).some(function (proc, index) {
      if (proc.uid === 'monploy_agent') {
        forever.stop(index);
        return true;
      } else {
        return false;
      }
    })) {
      setTimeout(stop, 1000);
    } else {
      console.log('stopped');
    }
  });
}

switch (command) {
  case 'start':
    start();
    break;
  case 'stop':
    stop();
    break;
  case 'list':
    request('http://localhost:3000/list').done(function (res) {
      console.dir(JSON.parse(res.getBody()));
    });
    break;
}
コード例 #27
0
ファイル: index.js プロジェクト: frozinoer/hello-parser
function processHelloPages() {


	for (var i = 0; i < urls.length; ++i) {

		console.log("Parsing de la page " + urls[i]);

		request({
		    url: urls[i],
		    method: "GET"
		}, function(err, response, body){		

		    if (response.statusCode == 200) {
		    	console.log("code 200");
				$ = cheerio.load(body);
				var categoryTitle = $("header h1").text();
				var pageId = $("form").attr("action").substr('./?category='.length);
		    	var subCategories = [];
				$('.title-content h2').each(function(i, elem) {
					var subCategoryTitle = $(this).text();
					console.log("category : " + categoryTitle);				
					console.log("subCategory : " + subCategoryTitle);
					var subCategoryQuestions = [];

					console.log("nombre de openFaq : " + $(this).parents(".title-content").next().find('li').length + "\n");

					$(this).parents(".title-content").next().find('li').each(function(i, elem) {
						var req = $(this).find("a.openFaq").text();
						var rawResponse = $(this).find("div.well").text();

						var questionId = $(this).find("div.collapse").attr("id");
						var id = anonymize(pageId) + "-" + questionId;

						var response = anonymize(transformResponse(rawResponse));

						var links = [];
						$(this).find("div.well a").each(function(i, elem) {
							var href = $(this).attr("href");
							var text = $(this).text();

              if(href.indexOf('/') === 0) href = 'https://www.hellobank.be' + href;

							links[links.length] = {
								href: anonymize(href),
								text: anonymize(text)
							}
						});

						++responseCount;
						responseSum += response.length;

						if (response.length < responseMin) {
							responseMin = response.length;
						}

						if (response.length > responseMax) {
							responseMax = response.length;
						}

						if (response.length > responseThreshold) {
							++responseCountAboveThreshold;
						}

						var item = {
							categoryTitle: anonymize(categoryTitle),
							request: anonymize(transformResponse(req)),
							responses: [response],
							links: links
						}
						if (subCategoryTitle !== categoryTitle) {
							item.subCategoryTitle = anonymize(subCategoryTitle);
						}
						items[id] = item;
					});
				});
				console.log("nombre d'url parsees : " + (parsed + 1));
				if (++parsed == urls.length) {
					var file = './leeched.json'
					 
					jsonfile.writeFile(file, items, {spaces: 2}, function (err) {
					  console.error(err)
					})


					var detectedUserSays = 0;
					var keys = Object.keys(items);

					var writer = csvWriter(
						{
						  separator: ',',
						  newline: '\n',
						  headers: ["Key", "SubCategory", "FAQ Question", "Previous alternative User Says", "New User Says", "FAQ Response"],
						  sendHeaders: true
						}
					)
					writer.pipe(fs.createWriteStream('./out.csv'))

					

					for (var key in items) {
						var item = items[key];
						var response = item.responses[0].replace(/\n/g, " ");;

						var userSaysText = "";
						var newUserSayFound = false;

						if (!deanonimizedUserSays[key]) {

//							console.log("pas de userSays trouve pour " + key + ":(");
						} else {
						
							for (var i = 0; i < deanonimizedUserSays[key].length; ++i) {
								var userSay = deanonimizedUserSays[key][i].trim();
								if (userSay === item.request) {
									detectedUserSays++;
								} else {
									userSaysText += userSay + " --- ";
									newUserSayFound = true;
								}
							}
						}
						if (newUserSayFound) {
							userSaysText = userSaysText.substring(0, userSaysText.length - 5);
//							console.log("suppression de la fin");
						}
						// retirer les 4 derniers caracteres
						writer.write([key, item.subCategoryTitle, item.request, userSaysText, "", response])					
					}
					writer.end();
					console.log("UserSay detectes comme question initiale : " + detectedUserSays);


					console.log("taille moyenne de reponse : " + (responseSum / responseCount));
					console.log("taille min de reponse : " + responseMin);
					console.log("taille max de reponse : " + responseMax);
					console.log("nombre de responses : " + responseCount);
					console.log("nombre de responses > " + responseThreshold + " : " + responseCountAboveThreshold);				
				}

			}
		//		console.log(body);
			if (response.statusCode === 400) {
		  		console.log("400");			
			} else if (response.statusCode === 409) {
		  		console.log("409");			
			}  else if (response.statusCode !== 400 && response.statusCode !== 409 && response.statusCode !== 200) {
				console.log("code error : " + response.statusCode); 
			}			

	    });
	}
}
コード例 #28
0
ファイル: index.js プロジェクト: RCSA/rooms
var application = new Application(pages);

page('*', function (ctx, next) {
  application.setPathname(ctx.pathname);
  application.setQueryString({
    edit: ctx.querystring.indexOf('edit=true') !== -1
  });
  if (application.isLoaded() && !application.getPage()) {
    return next();
  }

  if (application.accessDenied() && !application.user.isAuthenticated) {
    return next();
  }
});
page.start();

request('/data/user').then(function (res) {
  var user = JSON.parse(res.getBody());
  token = user.token;
  application.setUser(user);
}).done();


application.subscribe(update);
function update() {
  if (application.isLoaded()) {
    React.renderComponent(application.render(), document.getElementById('page'));
  }
}
コード例 #29
0
    _loadSchema : function() {
        try {
            if(!this._fileExists(this.projectFile)) {
                return;
            }
            let config = this._loadJSON(this.projectFile);
            if(config && config.schema) {
                let schemaConfig = config.schema;
                if(schemaConfig.file) {
                    try {
                        let schemaFile = path.isAbsolute(schemaConfig.file) ? schemaConfig.file : path.join(this.projectDir, schemaConfig.file);
                        let schema = this._loadJSON(schemaFile);
                        if(schema && schema.data) {
                            this.schemaFile = schemaFile;
                            this._watch(schemaFile, true);
                            this._sendSchemaChanged(schema, schemaFile);
                            return;
                        }
                    } catch(e) {
                        console.error("Couldn't load schema", e);
                    }

                } else if(schemaConfig.request && schemaConfig.request.url) {

                    try {
                        // need to do a network request to fetch the schema
                        let schemaRequestConfig = schemaConfig.request;
                        let doIntrospectionQuery = schemaRequestConfig.postIntrospectionQuery;
                        let method = doIntrospectionQuery ? 'POST' : schemaRequestConfig.method || 'GET';
                        if(doIntrospectionQuery) {
                            schemaRequestConfig.options = schemaRequestConfig.options || {};
                            schemaRequestConfig.options.headers = schemaRequestConfig.options.headers || {};
                            schemaRequestConfig.options.headers['Content-Type'] = 'application/json';
                            schemaRequestConfig.options.body = JSON.stringify({query: introspectionQuery});
                        }
                        request(method, schemaRequestConfig.url, schemaRequestConfig.options).then((schemaResponse) => {
                            if (schemaResponse.statusCode == 200) {
                                let schemaBody = schemaResponse.getBody('utf-8');
                                let schema = JSON.parse(schemaBody);
                                if(schema && schema.data) {
                                    this.schemaUrl = schemaRequestConfig.url;
                                    this._sendSchemaChanged(schema, schemaRequestConfig.url);
                                }
                            } else {
                                console.error("Error loading schema from '"+schemaRequestConfig.url+"'", schemaResponse, schemaConfig.request);
                                this._sendSchemaChanged(null);
                            }
                        }).catch((error) => {
                            console.error("Error loading schema from '"+schemaRequestConfig.url+"'", error, schemaConfig.request);
                        });
                    } catch (e) {
                        console.error("Couldn't load schema using request config", e, schemaConfig.request);
                    }
                    return;
                }
            }
        } catch (e) {
            console.error("Error loading schema from '" + this.projectFile + "'", e);
        }
        // fallback is no schema
        this._sendSchemaChanged(null);
    },
コード例 #30
0
ファイル: request.js プロジェクト: hagabaka/dofusportal-api
module.exports = function(url) {
  return request('GET', url).getBody();
}