Example #1
0
exports.write = function() {
	var level = Array.prototype.shift.call(arguments);

	var parsed_text = Array.prototype.join.call(_parse(arguments), ' ');

	// Write to the Telegram bot
	HTTP.send({
		url: String.format(API_URL, exports.config.token) + 'sendMessage',
		data: {
			chat_id: exports.config.chatId,
			text: '\\[' + level.toUpperCase() + '] ' + parsed_text,
			parse_mode: exports.config.parseMode,
			disable_notification: exports.config.disableNotification
		},
		format: 'json',
		success: function(response) {
			if (response.ok === true) {
				Ti.API.info(CLASS_NAME + ' message successfully sent to ' + exports.config.chatId);
			} else {
				Ti.API.error(CLASS_NAME + ' message send failed:', response);
			}
		},
		error: function (err) {
			Ti.API.error(CLASS_NAME + ' error while sending message to bot:', err);
		}
	});
};
exports.logout = function(callback) {
	Event.trigger('auth.logout', {
		id: exports.getUserID()
	});

	var driver = getStoredDriverString();
	if (driver != null) {
		exports.loadDriver(driver).logout();
	}

	var logoutUrl = (driver && driver.config ? driver.config.logoutUrl : null) || exports.config.logoutUrl;

	HTTP.send({
		url: logoutUrl,
		method: 'POST',
		timeout: 3000,
		complete: function() {
			currentUser = null;

			Prop.removeProperty('auth.me');

			Cache.purge();

			if (exports.config.useOAuth == true) {
				exports.OAuth.resetCredentials();
			} else {
				Ti.Network.removeHTTPCookiesForDomain(Util.getDomainFromURL(HTTP.config.base));
			}

			if (_.isFunction(callback)) callback();
		}
	});
};
	return Q.promise(function(resolve, reject) {
		HTTP.send({
			url: opt.loginUrl,
			method: 'POST',
			data: dataFromDriver,
			success: function(data) {
				HTTP.exportCookiesToSystem();
				resolve(data);
			},
			error: reject,
		});
	});
	return Q.promise(function(resolve, reject) {
		HTTP.send({
			url: exports.config.oAuthAccessTokenURL,
			method: 'POST',
			data: _.extend({}, oAuthPostData, dataFromDriver),
			suppressFilters: ['oauth'],
			success: function(data) {
				exports.OAuth.storeCredentials(data);
				resolve(data);
			},
			error: reject,
		});
	});
Example #5
0
function apiLogin(data) {
	var q = Q.defer();

	HTTP.send({
		url: config.loginUrl,
		method: 'POST',
		data: data,
		silent: silent,
		success: q.resolve,
		error: q.reject
	});

	return q.promise;
}
exports.autocomplete = function(opt) {
	_.defaults(opt, {
		silent: true,
		ttl: CACHE_TTL
	});

	if (opt.ttl > CACHE_TTL) {
		Ti.API.error('Geo: cache TTL cannot exceed 30 days. Defaulting to ' + CACHE_TTL + ' seconds');
		opt.ttl = CACHE_TTL;
	}

	var key = exports.config.googleApiKey;
	if (!key) {
		throw new Error('This method needs a Google Maps API key to work');
	}

	if (!opt.input) {
		Ti.API.error('Geo: Missing required parameter "input"');
		if (_.isFunction(opt.error)) opt.error();
		return;
	}

	var data = _.pick(opt, 'input', 'offset', 'location', 'radius', 'language', 'types');
	if (_.isObject(opt.components)) {
		_.extend(data, {
			components: parseComponents(opt.components)
		});
	}
	_.extend(data, {
		key: key
	});

	HTTP.send({
		url: 'https://maps.googleapis.com/maps/api/place/autocomplete/json',
		data: data,
		silent: opt.silent,
		ttl: opt.ttl,
		format: 'json',
		success: function(res) {
			if (!res.predictions) {
				if (_.isFunction(opt.error)) opt.error();
				return;
			}

			opt.success(res.predictions);
		},
		error: opt.error
	});
};
Example #7
0
exports.unsubscribe = function(opt) {
	if (exports.config.unsubscribeEndpoint == null) {
		throw new Error("Notifications.HTTP: Invalid HTTP endpoint");
	}

	HTTP.send({
		url: exports.config.unsubscribeEndpoint + '/' + opt.deviceToken,
		method: 'POST',
		data: _.extend({}, opt.data, {
			channel: opt.channel,
		}),
		success: opt.success,
		error: opt.error,
		suppressFilters: opt.suppressFilters,
		errorAlert: false,
		silent: true
	});
};
exports.getPlaceDetails = function(opt) {
	_.defaults(opt, {
		silent: true,
		ttl: CACHE_TTL
	});

	if (opt.ttl > CACHE_TTL) {
		Ti.API.error('Geo: cache TTL cannot exceed 30 days. Defaulting to ' + CACHE_TTL + ' seconds');
		opt.ttl = CACHE_TTL;
	}

	var key = exports.config.googleApiKey;
	if (!key) {
		throw new Error('This method needs a Google Maps API key to work');
	}

	if (!opt.placeid) {
		Ti.API.error('Geo: Missing required parameter "placeid"');
		if (_.isFunction(opt.error)) opt.error();
		return;
	}

	var data = _.pick(opt, 'placeid', 'extensions', 'language');
	_.extend(data, {
		key: key
	});

	HTTP.send({
		url: 'https://maps.googleapis.com/maps/api/place/details/json',
		data: data,
		silent: opt.silent,
		ttl: opt.ttl,
		format: 'json',
		success: function(res) {
			if (res.status !== 'OK' || _.isEmpty(res.result)) {
				if (_.isFunction(opt.error)) opt.error();
				return;
			}

			opt.success(res.result);
		},
		error: opt.error
	});
};
Example #9
0
exports.subscribe = function(opt) {
	if (exports.config.subscribeEndpoint == null) {
		throw new Error("Notifications.HTTP: Invalid HTTP endpoint");
	}

	HTTP.send({
		url: exports.config.subscribeEndpoint,
		method: 'POST',
		data: _.extend({}, opt.data, {
			device_token: opt.deviceToken,
			channel: opt.channel,
			app_id: Ti.App.id,
			app_version: Ti.App.version,
			app_deploytype: Util.getDeployType(),
			os: Util.getOS(),
		}),
		success: opt.success,
		error: opt.error,
		suppressFilters: opt.suppressFilters,
		errorAlert: false,
		silent: true
	});
};
exports.sync = function(method, model, opt) {
	var adapter_cfg = _.extend({}, exports.config, model.config.adapter);
	var url = adapter_cfg.base + adapter_cfg.name;

	if (model instanceof Backbone.Model) {
		if (opt.id != null) {
			url += '/' + opt.id;
		} else if (model.id != null) {
			url += '/' + model.id;
		}
	}

	if (opt.query != null) {
		if (_.isObject(opt.query) || _.isArray(opt.query)) {
			url += Util.buildQuery(opt.query);
		} else if (_.isString(opt.query)) {
			url += opt.query.substr(0,1) === '?' ? opt.query : ('?'+opt.query);
		}
	}

	if (opt.patch) method = 'patch';

	var httpOpt = _.extend({}, model.config.http, opt.http, {
		url: url,
		method: CRUD_to_REST[method],
		format: 'json'
	}, opt.httpOverride);

	switch (method) {

		case 'patch':

		httpOpt = _.extend(httpOpt, { data: _.pick(model.attributes, _.keys(opt.changes)) });

		HTTP.send(httpOpt)
		.success(function(resp) {
			if (resp != null && resp[ adapter_cfg.idAttribute ] != null) {
				opt.success(resp);
			} else {
				opt.error(resp);
			}
		})
		.error(opt.error);
		break;

		case 'update':
		case 'create':

		httpOpt = _.extend(httpOpt, { data: model.toJSON() });

		HTTP.send(httpOpt)
		.success(function(resp) {
			if (resp != null && resp[ adapter_cfg.idAttribute ] != null) {
				opt.success(resp);
			} else {
				opt.error(resp);
			}
		})
		.error(opt.error);
		break;

		case 'read':

		HTTP.send(httpOpt)
		.success(function(resp) {

			if (resp != null) {
				if (model instanceof Backbone.Collection) {

					if (_.isArray(resp)) {
						opt.success(resp);
					} else if (_.isObject(resp)){
						opt.success(resp[ adapter_cfg.collectionWrapper ]);
					} else {
						opt.error(resp);
					}

				} else {

					if (resp != null && resp[ adapter_cfg.idAttribute ] != null) {
						opt.success(resp);
					} else {
						opt.error(resp);
					}

				}
			} else {
				opt.error(resp);
			}

		})
		.error(opt.error);
		break;

		case 'delete':

		HTTP.send(httpOpt)
		.success(opt.success)
		.error(opt.error);
		break;

	}
};
exports.reverseGeocode = function(opt) {
	_.defaults(opt, {
		silent: true,
		ttl: CACHE_TTL
	});

	if (opt.ttl > CACHE_TTL) {
		Ti.API.error('Geo: cache TTL cannot exceed 30 days. Defaulting to ' + CACHE_TTL + ' seconds');
		opt.ttl = CACHE_TTL;
	}

	if (exports.config.geocodeUseGoogle) {

		var data = _.pick(opt, ['language']);

		_.extend(data, {
			latlng: opt.lat + ',' + opt.lng,
			sensor: 'false'
		});

		HTTP.send({
			url: 'http://maps.googleapis.com/maps/api/geocode/json',
			data: {
				latlng: opt.lat + ',' + opt.lng,
				sensor: 'false'
			},
			silent: opt.silent,
			ttl: opt.ttl,
			format: 'json',
			success: function(res) {
				if (res.status !== 'OK' || res.results.length === 0) {
					if (_.isFunction(opt.error)) opt.error();
					return;
				}

				opt.success({
					success: true,
					address: res.results[0].formatted_address,
					results: res.results
				});
			},
			error: opt.error
		});

	} else {

		Ti.Geolocation.reverseGeocoder(opt.lat, opt.lng, function(res) {
			if (!res.success || _.isEmpty(res.places)) {
				if (_.isFunction(opt.error))
				opt.error();
			return;
		}

		opt.success({
			success: true,
			address: res.places[0].address,
			results: res.places
		});
	});
	}
};
exports.geocode = function(opt) {
	_.defaults(opt, {
		silent: true,
		ttl: CACHE_TTL
	});

	if (opt.ttl > CACHE_TTL) {
		Ti.API.error('Geo: cache TTL cannot exceed 30 days. Defaulting to ' + CACHE_TTL + ' seconds');
		opt.ttl = CACHE_TTL;
	}

	if (exports.config.geocodeUseGoogle) {
		var data = _.pick(opt, ['address', 'language']);

		if (_.isObject(opt.components)) {
			_.extend(data, {
				components: parseComponents(opt.components)
			});
		}

		_.extend(data, {
			sensor: 'false'
		});

		HTTP.send({
			url: 'http://maps.googleapis.com/maps/api/geocode/json',
			data: data,
			silent: opt.silent,
			ttl: opt.ttl,
			format: 'json',
			success: function(res) {
				if (res.status !== 'OK' || _.isEmpty(res.results)) {
					if (_.isFunction(opt.error)) opt.error();
					return;
				}

				opt.success({
					success: true,
					latitude: res.results[0].geometry.location.lat,
					longitude: res.results[0].geometry.location.lng,
					formatted_address: res.results[0].formatted_address
				});
			},
			error: opt.error
		});

	} else {

		Ti.Geolocation.forwardGeocoder(opt.address, function(res) {
			if (!res.success) {
				if (_.isFunction(opt.error))
				opt.error();
			return;
		}

		opt.success({
			success: true,
			latitude: res.latitude,
			longitude: res.longitude
		});
	});
	}
};
Example #13
0
exports.notifyUpdate = function(url, version_cb, success_cb) {
	if (!Ti.Network.online) return;

	var HTTP = require('T/http');
	var Dialog = require('T/dialog');
	var GA = require('T/ga');

	if (url == null) {
		if (OS_IOS) {
			url = 'https://itunes.apple.com/lookup?bundleId=' + Ti.App.id;
		} else {
			return null;
		}
	}

	version_cb = version_cb || function(response) {
		if (OS_IOS) {
			return (response.results && response.results[0]) ? response.results[0].version : null;
		} else {
			return null;
		}
	};

	success_cb = success_cb || function(response) {
		Util.openInStore((function() {
			if (OS_IOS) return response.results[0].trackId;
			else return null;
		})() );
	};

	HTTP.send({
		url: url,
		cache: false,
		format: 'json',
		success: function(response) {
			if (response == null || !_.isObject(response)) return;

			var new_version = version_cb(response);
			var version_compare = Util.compareVersions(new_version, Ti.App.version);

			Ti.API.info('Util: App store version is ' + new_version);
			Ti.API.info('Util: Current version is ' + Ti.App.version);

			if (version_compare > 0) {
				var title = L('app_new_version_title', 'Update available');
				var message = String.format(L('app_new_version_message', 'A new version of %s is available: %s'), Ti.App.name, new_version);

				Dialog.confirm(title, message, [
				{
					title: L('app_new_version_button_later', 'Later'),
					callback: function() {
						GA.trackEvent('updatedialog', 'later');
					}
				},
				{
					title: L('app_new_version_button_update', 'Update'),
					selected: true,
					callback: function() {
						GA.trackEvent('updatedialog', 'doit');
						success_cb(response);
					}
				}
				]);
			}
		}
	});
};
Example #14
0
exports.sync = function(method, model, opt) {
	var isCollection;
	var url = (model.config.adapter.baseUrl || '/') + model.config.adapter.name;

	if (model.id) {
		isCollection = false;
		url += '/' + model.id;
	} else {
		isCollection = true;
	}

	if (opt.patch) method = 'patch';

	var httpOptions = _.extend({}, opt.http, {
		url: url,
		method: CRUD_to_REST[method],
		format: 'json'
	});

	if (Alloy.Backbone.emulateHTTP) {
		if (['DELETE','PUT','PATCH'].indexOf(httpOptions.method)!==-1) {
			httpOptions.method = 'POST';
			httpOptions.headers = _.extend({}, httpOptions.headers, {
				'X-HTTP-Method-Override': httpOptions.method
			});
		}
	}

	switch (method) {

		case 'create':
		HTTP.send(_.extend({}, httpOptions, {
			data: model.toJSON(),
			success: function(resp) {

				if (resp != null && resp.id != null) {
					opt.success(resp);
				} else {
					opt.error();
				}

				model.trigger('fetch');
			},
			error: opt.error
		}));
		break;

		case 'read':
		HTTP.send(_.extend({}, httpOptions, {
			data: opt.args || {},
			success: function(resp) {

				if (resp != null) {
					if (isCollection === true) {
						if (_.isObject(resp) && resp.data != null) opt.success(resp.data);
						else if (_.isArray(resp)) opt.success(resp);
						else opt.error();
					} else {
						opt.success(resp);
					}
				} else {
					opt.error();
				}

				model.trigger('fetch');
			},
			error: opt.error
		}));
		break;

		case 'update':
		HTTP.send(_.extend({}, httpOptions, {
			data: _.pick(model.attributes, _.keys(opt.changes)),
			success: function(resp) {

				if (resp != null) {
					opt.success();
				} else {
					opt.error();
				}

				model.trigger('fetch');
			},
			error: opt.error
		}));
		break;

		case 'delete':
		HTTP.send(_.extend({}, httpOptions, {
			data: opt.args || {},
			success: function(resp) {

				if (resp != null) {
					opt.success();
				} else {
					opt.error();
				}

				model.trigger('fetch');
			},
			error: opt.error
		}));
		break;

	}
};
exports.sync = function(method, model, opt) {
	var url = (model.config.adapter.baseUrl || '/') + model.config.adapter.name;
	var query = null;

	if (model instanceof Backbone.Model) {
		url += model.id != null ? ('/' + model.id) : '';
		query = model.get('query');
	} else if (model.first() != null) {
		query = model.first().get('query');
	}

	query = query || opt.query;

	if (query != null) {
		if (_.isObject(query) || _.isArray(query)) {
			url += Util.buildQuery(query);
		} else if (_.isString(query)) {
			url += query.substr(0,1) === '?' ? query : ('?'+query);
		}
	}

	var httpOpt = _.extend({}, model.config.http, opt.http, {
		url: url,
		method: CRUD_to_REST[method] || 'GET',
		format: 'json'
	});

	if (Alloy.Backbone.emulateHTTP) {
		if ([ 'DELETE', 'PUT', 'PATCH' ].indexOf(httpOpt.method) !== -1) {
			httpOpt.method = 'POST';
			httpOpt.headers = _.extend({}, httpOpt.headers, {
				'X-HTTP-Method-Override': httpOpt.method
			});
		}
	}

	switch (method) {

		case 'create':

		_.extend(httpOpt, { data: JSON.stringify(model.toJSON()) });
		HTTP.send(httpOpt).success(function(resp) {

			if (resp != null && resp.id != null) {
				opt.success(resp);
			} else {
				opt.error();
			}

		}).error(opt.error);
		break;

		case 'read':

		HTTP.send(httpOpt).success(function(resp) {

			if (resp != null && _.isObject(resp)) {
				if (resp[ATTRIBUTES] && resp[ATTRIBUTES].type && resp[ATTRIBUTES].type == ERROR_TYPE) {
					opt.error();
				}

				if (resp[CONTENT] != null) {
					var content = resp[CONTENT];

					if (_.isArray(content)){
						if (model instanceof Backbone.Collection) {
							opt.success(content);
						} else {
							opt.success(_.first(content));
						}
					} else {
						opt.error();
					}
				}
			} else {
				opt.error();
			}

		}).error(function(err) {
			opt.error(err);
		});
		break;

	}
};