Example #1
0
	getSupportedLanguages(target) {
		if (this.enabled && this.apiKey) {
			if (this.supportedLanguages[target]) {
				return this.supportedLanguages[target];
			}

			let result;
			const params = { key: this.apiKey };
			if (target) {
				params.target = target;
			}

			try {
				result = HTTP.get('https://translation.googleapis.com/language/translate/v2/languages', { params });
			} catch (e) {
				if (e.response && e.response.statusCode === 400 && e.response.data && e.response.data.error && e.response.data.error.status === 'INVALID_ARGUMENT') {
					params.target = 'en';
					target = 'en';
					if (!this.supportedLanguages[target]) {
						result = HTTP.get('https://translation.googleapis.com/language/translate/v2/languages', { params });
					}
				}
			} finally {
				if (this.supportedLanguages[target]) {
					return this.supportedLanguages[target];
				} else {
					this.supportedLanguages[target || 'en'] = result && result.data && result.data.data && result.data.data.languages;
					return this.supportedLanguages[target || 'en'];
				}
			}
		}
	}
Example #2
0
export default function () {
    Meteor.methods({
        'statistics.user'(userId, token) {
            check(userId, Number);
            check(token, String);

            let statistics = HTTP.call('GET', 'https://localhost:8080/api/users/' + userId + '/statistics', {
                headers: {
                    "Clockwise-Token": token
                }
            });

            return statistics;
        },

        'statistics.screenshots.user.all'(userId, token) {
            check(userId, Number);
            check(token, String);

            let screenshots = HTTP.get('https://localhost:8080/api/screenshots/all/' + userId, {
                headers: {
                    "Clockwise-Token": token
                }
            });

            return screenshots;
        }
    });
}
Example #3
0
export default function() {
	Meteor.methods({
		'user.login'(login, password) {
			check(login, String);
			check(password, String);

			var responseTk = HTTP.call('POST', 'https://localhost:8080/api/authenticate', {
				data: {
					"username": login,
					"password": password
				}
			});

			console.log(responseTk.data.token);

			return responseTk.data.token;
		},

		'user.info'(username, token) {
			check(username, String);
			check(token, String);

			let response = HTTP.call('GET', 'https://localhost:8080/api/users?username='******'user.register'(username, email, password) {
			check(username, String);
			check(email, String);
			check(password, String);

			var responseToken = HTTP.call('POST', 'https://localhost:8080/api/users', {
				data: {
					"username": username,
					"email"	  : email,
					"password": password,
					"role"	  : "ROLE_TEAM_LEADER"
				}
			});

			return responseToken;
		}
	});
}
Example #4
0
Meteor.publish('currentUser', function (userId, authToken) {
	var currentUser = Users.findOne({_id: userId, spotifyAuthToken: authToken});
	if(!currentUser){
		return [];
	}

	if(currentUser.spotifyAuthToken && currentUser.spotifyAuthToken === authToken){
		return Users.find({_id: userId}, { fields: { spotifyAuthToken: 0 } });
	}

	if(authToken){
		var response = [];
		try
		{
			response = HTTP.get('https://api.spotify.com/v1/me', {headers: {
	           'Authorization': 'Bearer ' + authToken
	        }});
		}
		catch(ex)
		{
			console.log(ex);
			return [];
		}

		// if we have a valid spotify ID - then we are still authenticated
		if(response && response.data && response.data.id){
			if(currentUser.spotifyUserId === response.data.id){
				return Users.find({_id: userId}, { fields: { spotifyAuthToken: 0 } });
			}
		}		
	}

  	return [];
});
Sparkpost.prototype.request = function(method, endpoint, data, callback) {
	method = method.toUpperCase();

	// override callback if data is a function
	if (typeof data === "function") {
		callback = data;
		data = {};
	}

	// setup url
	var urlData = {
		endpoint: endpoint,
		path: data.path || data.id,
		params: data.params
	};

	// setup header
	var headers = this.options.headers;
	headers['Authorization'] = this.options.apiKey;

	HTTP.call(
		method,
		this._buildURL(urlData),
		{
			data: data.data || {},
			headers: headers
		},
		callback);
};
	getIdentity(accessToken) {
		const params = {};
		const headers = {
			'User-Agent': this.userAgent, // http://doc.gitlab.com/ce/api/users.html#Current-user
		};

		if (this.identityTokenSentVia === 'header') {
			headers.Authorization = `Bearer ${ accessToken }`;
		} else {
			params.access_token = accessToken;
		}

		try {
			const response = HTTP.get(this.identityPath, {
				headers,
				params,
			});

			let data;

			if (response.data) {
				data = response.data;
			} else {
				data = JSON.parse(response.content);
			}

			logger.debug('Identity response', JSON.stringify(data, null, 2));

			return data;
		} catch (err) {
			const error = new Error(`Failed to fetch identity from ${ this.name } at ${ this.identityPath }. ${ err.message }`);
			throw _.extend(error, { response: err.response });
		}
	}
Example #7
0
	send(fromNumber, toNumber, message) {
		const options = {
			timeout: 30000,
			followRedirects: false,
			headers: {
				Authorization: `Bearer ${ this.authToken }`,
			},
			data: {
				to: [toNumber],
				from: fromNumber,
				body: message,
			},
			npmRequestOptions: {
				agentOptions: {
					ecdhCurve: 'auto',
				},
				forever: true,
			},
		};

		try {
			HTTP.call('POST', this.URL || 'https://smsapi.voxtelesys.net/api/v1/sms', options);
		} catch (error) {
			console.error(`Error connecting to Voxtelesys SMS API: ${ error }`);
		}
	}
Example #8
0
      jsonContent.items.map(function (calendar) {
        console.log(calendar);
        let min = moment()
          .hour(0)
          .minute(0)
          .second(0)
          .format(),
          max = moment()
          .hour(48)
          .minute(0)
          .second(0)
          .format(),
          url = 'https://www.googleapis.com/calendar/v3/calendars/' + encodeURIComponent(calendar.id) + '/events?singleEvents=true&timeMax=' + encodeURIComponent(max) + '&timeMin=' + encodeURIComponent(min);
        options = {
          'headers': {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + Meteor.user()
              .services.google.accessToken,
            'X-JavaScript-User-Agent': "Google APIs Explorer"
          }
        };

        let result = HTTP.get(url, options),
          jsonContent = JSON.parse(result.content);

        if (jsonContent.items && jsonContent.items.length > 0) {
          jsonContent.items.map(function (item) {
            CalendarEvents.remove({
              id: item.id
            });
            CalendarEvents.insert(item);
          });
        }
      });
Example #9
0
 serversArray.forEach(({ _id, ip, port, fullUrl, failedHealthChecks }) => {
   console.log(`ProseMeteor AuthorityRegistry: running health check against ${fullUrl}`);
   if (ip === proseMeteorConfig.ip && port === proseMeteorConfig.port) {
     console.log('ProseMeteor AuthorityRegistry: Skipping this server\'s health check');
     return;
   }
   // if this server has failed too many times, remove it from the registry since we can assume it's down
   if (failedHealthChecks >= proseMeteorConfig.failedHealthChecksThreshold) {
     console.log(`ProseMeteor AuthorityRegistry: ${ip}:${port} has failed ${failedHealthChecks} consecutive health checks, marking it to be removed from the registry`);
     failedConnectionsAboveThreshold.push(_id);
     return;
   }
   const healthCheckUrl = `${ip}:${port}/prosemeteor-health-check`;
   // use http or https depending on port
   const healthCheckUrlWithProtocol = `${proseMeteorConfig.protocol}://${healthCheckUrl}`;
   let healthCheckRes;
   let healthCheckFailed = false;
   try {
     healthCheckRes = HTTP.get(healthCheckUrlWithProtocol);
     if (healthCheckRes !== HEALTH_CHECK_RESPONSE) {
       healthCheckFailed = true;
     }
   } catch (e) {
     healthCheckFailed = true;
   }
   if (healthCheckFailed) {
     failedConnections.push(_id);
   } else {
     console.log(`ProseMeteor AuthorityRegistry: Server passed health check: ${ip}:${port}`);
     // if this server failed a previous health check but passed this time, mark it to reset its failedHealthChecks count
     if (failedHealthChecks > 0) {
       successfulChecksThatFailedPreviously.push(_id);
     }
   }
 });
Example #10
0
const fetchPicture = function (db, url) {
  try {
    const result = HTTP.get(url, {
      npmRequestOptions: { encoding: null },
      timeout: 5000,
    });

    const metadata = {};

    metadata.mimeType = result.headers["content-type"];
    if (metadata.mimeType.lastIndexOf("image/png", 0) === -1 &&
        metadata.mimeType.lastIndexOf("image/jpeg", 0) === -1) {
      throw new Error("unexpected Content-Type:", metadata.mimeType);
    }

    const enc = result.headers["content-encoding"];
    if (enc && enc !== "identity") {
      metadata.encoding = enc;
    }

    return db.addStaticAsset(metadata, result.content);
  } catch (err) {
    console.error("failed to fetch user profile picture:", url, err.stack);
  }
};
Example #11
0
export const call = (pathname, query) => {
	const result = HTTP.get(formatUrl(pathname, query));
	if (!result.data) {
		throw new Error(`No JSON returned for ${pathname} ${JSON.stringify(query)}`);
	}
	return mapKeys(result.data, camelCase);
};
Example #12
0
	postGetChannelInfo(slackChID) {
		logger.slack.debug('Getting slack channel info', slackChID);
		const response = HTTP.get('https://slack.com/api/channels.info', { params: { token: this.apiToken, channel: slackChID } });
		if (response && response.data) {
			return response.data.channel;
		}
	}
Example #13
0
Meteor.setInterval(function(){
	console.log("videoscruter launched");
	var videosRows = Videos.find({}, {fields: {}}).fetch();
	for (var i=0; i < videosRows.length; i++) {
		try{
			var resultUrl       = HTTP.call('GET', 'http://api.brightcove.com/services/library?command=find_videos_by_tags&token=' + videosRows[i].token + '&and_tags=' + videosRows[i].tag + '&page_size=1&fields=name%2Cid%2CpublishedDate&sort_by=PUBLISH_DATE');
			var lastVideo       = resultUrl.content;
			var jsonLastVideo   = EJSON.parse(lastVideo); 
			var videoAttributes = jsonLastVideo.items[0];

			var videoDateMs   = Math.round(videoAttributes.publishedDate);
			videoDateFormated = msDateToJSDate(videoDateMs);
			
			Videos.update({token: videosRows[i].token,
						   tag:videosRows[i].tag},
						  {$set: {video_id: videoAttributes.id, 
							      video_name : videoAttributes.name, 
							      video_date : videoDateFormated}});
			
		}catch(e){
			console.log(e.response.headers);
		}
		checkVideoImportIsON(videosRows[i]);
	}
},
Example #14
0
	copyPins(rid, channelMap) {
		const response = HTTP.get('https://slack.com/api/pins.list', { params: { token: this.apiToken, channel: channelMap.id } });
		if (response && response.data && _.isArray(response.data.items) && response.data.items.length > 0) {
			for (const pin of response.data.items) {
				if (pin.message) {
					const user = this.rocket.findUser(pin.message.user);
					const msgObj = {
						rid,
						t: 'message_pinned',
						msg: '',
						u: {
							_id: user._id,
							username: user.username,
						},
						attachments: [{
							text : this.rocket.convertSlackMsgTxtToRocketTxtFormat(pin.message.text),
							author_name : user.username,
							author_icon : getAvatarUrlFromUsername(user.username),
							ts : new Date(parseInt(pin.message.ts.split('.')[0]) * 1000),
						}],
					};

					RocketChat.models.Messages.setPinnedByIdAndUserId(`slack-${ pin.channel }-${ pin.message.ts.replace(/\./g, '-') }`, msgObj.u, true, new Date(parseInt(pin.message.ts.split('.')[0]) * 1000));
				}
			}
		}
	}
Example #15
0
  "paypalexpress/refund/create": function (paymentMethod, amount) {
    check(paymentMethod, Reaction.Schemas.PaymentMethod);
    check(amount, Number);
    this.unblock();

    const options = Paypal.expressCheckoutAccountOptions();
    const previousTransaction = _.last(paymentMethod.transactions);
    const transactionId = previousTransaction.TRANSACTIONID;
    const currencycode = previousTransaction.CURRENCYCODE;

    let response;
    try {
      response = HTTP.post(options.url, {
        params: {
          USER: options.username,
          PWD: options.password,
          SIGNATURE: options.signature,
          VERSION: nvpVersion,
          METHOD: "RefundTransaction",
          TRANSACTIONID: transactionId,
          REFUNDTYPE: "Partial",
          AMT: amount,
          CURRENCYCODE: currencycode
        }
      });
    }  catch (error) {
      Logger.debug(error, "Failed paypalexpress/refund/create");
      throw new Meteor.Error(error.message);
    }

    if (!response || response.statusCode !== 200) {
      Logger.debug(error, "Bad Response from Paypal during Refund Creation");
      throw new Meteor.Error("Bad Response from Paypal during Refund Creation");
    }

    let parsedResponse = parseResponse(response);
    if (parsedResponse.ACK !== "Success") {
      throw new Meteor.Error("ACK " + parsedResponse.ACK + ": " + parsedResponse.L_LONGMESSAGE0);
    }

    let amountFormatted = {
      total: amount,
      currency: currencycode
    };

    let result = {
      saved: true,
      type: "refund",
      created: new Date(),
      transactionId: transactionId,
      refundTransactionId: parsedResponse.REFUNDTRANSACTIONID,
      grossRefundAmount: parsedResponse.GROSSREFUNDAMT,
      netRefundAmount: parsedResponse.NETREFUNDAMT,
      correlationId: parsedResponse.CORRELATIONID,
      currencycode: parsedResponse.CURRENCYCODE,
      amount: amountFormatted,
      rawTransaction: parsedResponse
    };
    return result;
  },
Example #16
0
export function initTrackedUsers() {
  const appKey = _.has(Meteor, 'settings.public.growjective.appKey') ?
    Meteor.settings.public.growjective.appKey : null;

  const forceUpdate = _.has(Meteor, 'settings.public.growjective.forceUpdate') ?
    Meteor.settings.public.growjective.forceUpdate : null;

  if (appKey) {
    // GET request to check if this app has been initialized
    const url = `${remoteUrl}/${Random.hexString(32)}/${appKey}`;
    HTTP.get(url, (err, res) => {
      if (err) {
        console.log(err); // eslint-disable no-console
        return;
      }
      const notInitialized = res.data === 0;
      if (notInitialized || forceUpdate) uploadUserData(appKey);
    });
  } else {
    /* eslint-disable no-console */
    console.log('Growjective cannot find your application key in the settings.json file');
    console.log('Please obtain the key from our website and execute your Meteor app by using:');
    console.log('meteor --settings settings.json');
    /* eslint-enable */
  }
}
Example #17
0
const getStackexchange = function() {
    //I ended up making this synchronous rather than async b/c weird problems with more_pages. TODO investigate
    let more_pages=true;
    let page=1;
    while (more_pages==true){
        //TODO look into using ETag header
         var response = HTTP.get(`http://api.stackexchange.com/2.2/users/${config.user_id}/network-activity`,
            {
                headers: {"User-Agent": "Meteor/1.3"},
                params: {"page":page},
                npmRequestOptions: {"gzip":true}
            },
        );
        for (item of response.data.items) {
            if (item.post_id) { //medals and privileges and such don't have post_ids, just forget them
                item['service'] = 'stackexchange';
                item['summaryHTML'] = summaryHTML(item);
                item['timestamp'] = new Date(item.creation_date*1000);
                Lifestreams.upsert({post_id: item.post_id}, item);
            }
        }
        page+=1;
        more_pages = response.data.has_more;
    }
};
Example #18
0
  fetchWeather: function (callback) {
    let params = {
      query: "units=metric&q=Warsaw,pl&APPID=" + process.env.OWAPI_KEY
    };

    HTTP.get(WeatherService.OWAPI_URL, params, function (error, result) {
      if (error || !result.data) {
        console.log("Error fetching weather data");
      } else {
        let readings = result.data.weather;
        let main = result.data.main;

        if (readings.length > 0) {
          let reading = readings[0];
          let icon = reading.icon;
          let description = reading.description;

          Weather.insert({
            icon: WeatherService.ICON_MAPPING[icon],
            temperature: Math.round(main.temp),
            pressure: main.pressure,
            humidity: main.humidity,
            description: WeatherService.DESCRIPTION_MAPPING[description],
            createdAt: new Date()
          });
        }
      }
    });
  }
Example #19
0
 playoffTeams.forEach((team) => {
   const playersResult = HTTP.call('GET', `http://www.nhl.com/stats/rest/skaters?isAggregate=false&reportType=basic&isGame=false&reportName=skatersummary&sort=[{%22property%22:%22points%22,%22direction%22:%22DESC%22},{%22property%22:%22goals%22,%22direction%22:%22DESC%22},{%22property%22:%22assists%22,%22direction%22:%22DESC%22}]&factCayenneExp=gamesPlayed%3E=1&cayenneExp=gameTypeId=2%20and%20seasonId%3E=20182019%20and%20seasonId%3C=20182019%20and%20teamId=${team.teamId}`);
   playersResult.data.data.forEach((player) => {
     const newPlayer = player;
     newPlayer.teamId = team._id;
     Players.insert(newPlayer);
   });
 });
Example #20
0
 Meteor.setTimeout(()=> {
   var result = HTTP.post(url, {
     headers: {
       "content-type": "application/json"
     },
     data: requestData
   });
 }, timeout);
Example #21
0
 nextResponse.data.forEach((repo) => {
   HTTP.get(`${repo.issues_url.replace(/{.*}/, '')}?${creds}&state=open`,
   options, (err, data) => {
     const insertRepo = repo;
     insertRepo.issues = data.data;
     Meteor.call('addRepo', insertRepo);
   });
 });
const getSlideText = async (url) => {
  let content = '';
  try {
    content = await HTTP.get(url).content;
  } catch (error) {
    Logger.error(`No file found. ${error}`);
  }
  return content;
};
Example #23
0
const postCatchError = Meteor.wrapAsync(function(url, options, resolve) {
	HTTP.post(url, options, function(err, res) {
		if (err) {
			resolve(null, err.response);
		} else {
			resolve(null, res);
		}
	});
});
Example #24
0
 function http(resolve,reject){
   HTTP.call(type, url, options, function(err, res){
       if(err)
         reject(err)
       else {
         resolve(res)
       }
     })
 };
Example #25
0
			HTTP: (method, url, options) => {
				try {
					return {
						result: HTTP.call(method, url, options),
					};
				} catch (error) {
					return { error };
				}
			},
Example #26
0
function getScopes(accessToken) {
	try {
		return HTTP.get(
			'https://www.googleapis.com/oauth2/v1/tokeninfo',
			{ params: { access_token: accessToken } }).data.scope.split(' ');
	} catch (err) {
		throw _.extend(new Error(`Failed to fetch tokeninfo from Google. ${ err.message }`), { response: err.response });
	}
}
Example #27
0
                response.data.results.forEach(function(result, index, arr) {
                    if (result['video_link/_source'].startsWith(prefix)) {
                        let videoId = result['video_link/_source'].substring(prefix.length);
                        let YOUTUBE_API_URL = `https://www.googleapis.com/youtube/v3/videos?id=${videoId}&part=snippet,statistics,recordingDetails&key=AIzaSyA_ltEFFYL4E_rOBYkQtA8aKHnL5QR_uMA`;

                        HTTP.call('GET', YOUTUBE_API_URL, function(err, response) {

                            if (!err) {
                                if (response.statusCode == '200' && response.data) {
                                    var item = response.data.items[0];
                                    let date = new Date(item.snippet.publishedAt);
                                    var singleVideo = {
                                        title: item.snippet.title,
                                        description: item.snippet.description,
                                        videoLink: result['video_link'],
                                        imageLink: (item.snippet.thumbnails.standard && item.snippet.thumbnails.standard.url) || (item.snippet.thumbnails.default && item.snippet.thumbnails.default.url) || 'default',
                                        videoId: item.id,
                                        channelId: item.snippet.channelId,
                                        channelTitle: channel,
                                        date: date
                                    };
                                    var singlePost = {
                                        type: 'youtube',
                                        views: 0,
                                        newPost: true,
                                        edited: false,
                                        deleted: false,
                                        deleteDate: new Date(),
                                        categories: [],
                                        author: 'bot',
                                        tags: item.snippet.tags || [],
                                        postingDate: new Date(),
                                        title: item.snippet.title,
                                        date: date
                                    };
                                    if (latestPost) {
                                        if (date.getTime() > latestPost.date.getTime()) {
                                            //console.log(date.getTime(), latestPost.date, 'New post added');
                                            singlePost.dataId = insertVideo.call(singleVideo);
                                            insertPost.call(singlePost);
                                        } else {
                                            //console.log(date.getTime(), latestPost.date, 'old');
                                        }
                                    } else {
                                        //console.log('all new');
                                        singlePost.dataId = insertVideo.call(singleVideo);
                                        insertPost.call(singlePost);
                                    }
                                }
                            } else {
                                if (Debug) {
                                    console.log(err)
                                }
                            }
                        })
                    }
                })
Example #28
0
function getIdentity(accessToken) {
	try {
		return HTTP.get(
			'https://www.googleapis.com/oauth2/v1/userinfo',
			{ params: { access_token: accessToken } }).data;
	} catch (err) {
		throw _.extend(new Error(`Failed to fetch identity from Google. ${ err.message }`), { response: err.response });
	}
}
Example #29
0
var pushForecastToOrion = function () {
    for (id in dataWeatherMap) {
        HTTP.call('GET', "http://api.openweathermap.org/data/2.5/forecast/daily?appid=ec57dc1b5b186be9c7900a63a3e34066&id=" + id + "&units=metric", {}, handleError(function (response) {
            for (i = 1; i < response.data.list.length; i++) {
                postOrionData(createForecastData(response.data.list[i], i, response.data.city.id));
            }
        }));
    }
}
Example #30
0
  loadPackage(packageName) {
    if (packageName instanceof vm.Script)
      return packageName.runInContext(this.context);

    const path = '/packages/' + packageName + '.js';
    if (!packageCache[path])
      packageCache[path] = new vm.Script(HTTP.get(Meteor.absoluteUrl(path)).content, path);
    packageCache[path].runInContext(this.context);
  }