I am using index.html for displaying the feeds.
My app.js is-
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result +=chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
function twitterCallback(data){
alert(responseJson.status.text);
}
var app=angular.module('store',[]);
app.controller('indexController', function($scope, $http) {
var unixtime=Math.round((new Date()).getTime() / 1000.0),
nonce=randomString(32,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
var httpMethod = 'GET',
url = 'https://api.twitter.com/1.1/statuses/home_timeline.json',
parameters = {
oauth_consumer_key : 'AD6SEy1m3XkggNTuYw5SUl4dv',
oauth_nonce : nonce,
oauth_signature_method : 'HMAC-SHA1',
oauth_timestamp : unixtime,
oauth_token : '3131481153-I9k4ZvdnePO42lOH0EJQNQcAHoyim6XrFFzFk90',
oauth_version : '1.0',
screen_name:'twitterapi',
callback:'twitterCallback'
},
consumerSecret = 'xxxxx',
tokenSecret = 'xxxxx',
signature = oauthSignature.generate(httpMethod, url, parameters, consumerSecret, tokenSecret,
{ encodeSignature: true});
$http.jsonp(url, {
headers: {
'Authorization':
'OAuth oauth_consumer_key="AD6SEy1m3XkggNTuYw5SUl4dv",' +
'oauth_signature_method="HMAC-SHA1",' +
'oauth_timestamp='+unixtime +
'oauth_nonce='+nonce +
'oauth_version="1.0",' +
'oauth_token="3131481153-I9k4ZvdnePO42lOH0EJQNQcAHoyim6XrFFzFk90",'+
'oauth_signature='+signature
},
params:{screen_name:'twitterapi',
}
}).success(function (data)
{
$scope.tweets = data;
}).error(function(data){
console.log('error');
}) ;
});
How to connect to twitter and define twitter-callback?Please specify how to connect with twitter.
I am getting
GET home_timeline.json?screen_name=twitterapi
400 Bad Request
Related
The twitter login is used by my app using ionic framework, and i want to get email address from twitter, i have requested twitter and app is now able to get email address.
But somehow the code below is not able to get email address.
For this i have created new function named getTwitterProfileManual but still it is not working.
I have also read document provided by twitter at Doc and as suggested i am also passing include_email params as request query. But still response do not have email address in it.
serviceModule.factory('TwitterService', function ($cordovaOauth, $cordovaOauthUtility, $http, $resource, $q, AUTH_ID)
{
var twitterKey = "STORAGE.TWITTER.KEY";
var clientId = AUTH_ID.TWITTER_APP_ID;
var clientSecret = AUTH_ID.TWITTER_APP_SEC;
function storeUserToken(data)
{
window.localStorage.setItem(twitterKey, JSON.stringify(data));
}
function getStoredToken()
{
return window.localStorage.getItem(twitterKey);
}
function createTwitterSignature(method, url, params)
{
if (!params) {
params = {};
}
var token = angular.fromJson(getStoredToken());
var oauthObject = {
oauth_consumer_key: clientId,
oauth_nonce: $cordovaOauthUtility.createNonce(10),
oauth_signature_method: "HMAC-SHA1",
oauth_token: token.oauth_token,
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_version: "1.0"
};
console.log(JSON.stringify(oauthObject));
var signatureObj = $cordovaOauthUtility.createSignature(method, url, oauthObject, params, clientSecret, token.oauth_token_secret);
$http.defaults.headers.common.Authorization = signatureObj.authorization_header;
console.log(JSON.stringify(signatureObj.authorization_header));
}
return {
initialize: function ()
{
var deferred = $q.defer();
var token = getStoredToken();
if (token !== null)
{
deferred.resolve(true);
}
else
{
$cordovaOauth.twitter(clientId, clientSecret).then(function (result)
{
storeUserToken(result);
deferred.resolve(true);
}, function (error)
{
deferred.reject(false);
});
}
return deferred.promise;
},
isAuthenticated: function ()
{
return getStoredToken() !== null;
},
getHomeTimeline: function ()
{
var home_tl_url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
createTwitterSignature('GET', home_tl_url);
return $resource(home_tl_url).query();
},
getTwitterProfile: function ()
{
var tl_url = 'https://api.twitter.com/1.1/account/verify_credentials.json';
createTwitterSignature('GET', tl_url);
return $resource(tl_url, {'include_email': true}).query();
},
getTwitterProfileManual: function () {
var deferred = $q.defer();
var token = angular.fromJson(getStoredToken());
createTwitterSignature('GET', 'https://api.twitter.com/1.1/account/verify_credentials.json');
// $http.get("https://api.twitter.com/1.1/account/verify_credentials.json")
$http({
method: 'GET',
url: "https://api.twitter.com/1.1/account/verify_credentials.json",
params : { 'include_email': true }
}).success(function (result)
{
console.log(result);
alert('USER TIMELINE: ' + JSON.stringify(result));
deferred.resolve(result);
}).error(function (error)
{
alert("Error: " + JSON.stringify(error));
deferred.reject(false);
});
return deferred.promise;
},
storeUserToken: storeUserToken,
getStoredToken: getStoredToken,
createTwitterSignature: createTwitterSignature
};
});
Does anyone came across such problem and solved it, if so please provide some hint.
After days of working i finally made it working.
Below is the code for anyone who will face such issue.
Code :
serviceModule.factory('$twitterHelpers', ['$q', '$http', function ($q, $http) {
function createSignature(method, endPoint, headerParameters, bodyParameters, secretKey, tokenSecret) {
if (typeof jsSHA !== "undefined") {
var headerAndBodyParameters = angular.copy(headerParameters);
var bodyParameterKeys = Object.keys(bodyParameters);
for (var i = 0; i < bodyParameterKeys.length; i++) {
headerAndBodyParameters[bodyParameterKeys[i]] = escapeSpecialCharacters(bodyParameters[bodyParameterKeys[i]]);
}
var signatureBaseString = method + "&" + encodeURIComponent(endPoint) + "&";
var headerAndBodyParameterKeys = (Object.keys(headerAndBodyParameters)).sort();
for (i = 0; i < headerAndBodyParameterKeys.length; i++) {
if (i == headerAndBodyParameterKeys.length - 1) {
signatureBaseString += encodeURIComponent(headerAndBodyParameterKeys[i] + "=" + headerAndBodyParameters[headerAndBodyParameterKeys[i]]);
} else {
signatureBaseString += encodeURIComponent(headerAndBodyParameterKeys[i] + "=" + headerAndBodyParameters[headerAndBodyParameterKeys[i]] + "&");
}
}
var oauthSignatureObject = new jsSHA(signatureBaseString, "TEXT");
var encodedTokenSecret = '';
if (tokenSecret) {
encodedTokenSecret = encodeURIComponent(tokenSecret);
}
headerParameters.oauth_signature = encodeURIComponent(oauthSignatureObject.getHMAC(encodeURIComponent(secretKey) + "&" + encodedTokenSecret, "TEXT", "SHA-1", "B64"));
var headerParameterKeys = Object.keys(headerParameters);
var authorizationHeader = 'OAuth ';
for (i = 0; i < headerParameterKeys.length; i++) {
if (i == headerParameterKeys.length - 1) {
authorizationHeader += headerParameterKeys[i] + '="' + headerParameters[headerParameterKeys[i]] + '"';
} else {
authorizationHeader += headerParameterKeys[i] + '="' + headerParameters[headerParameterKeys[i]] + '",';
}
}
return {signature_base_string: signatureBaseString, authorization_header: authorizationHeader, signature: headerParameters.oauth_signature};
} else {
return "Missing jsSHA JavaScript library";
}
}
function createNonce(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
function escapeSpecialCharacters(string) {
var tmp = encodeURIComponent(string);
tmp = tmp.replace(/\!/g, "%21");
tmp = tmp.replace(/\'/g, "%27");
tmp = tmp.replace(/\(/g, "%28");
tmp = tmp.replace(/\)/g, "%29");
tmp = tmp.replace(/\*/g, "%2A");
return tmp;
}
function transformRequest(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + escapeSpecialCharacters(obj[p]));
console.log(str.join('&'));
return str.join('&');
}
return {
createTwitterSignature: function (method, url, bodyParameters, clientId, clientSecret, token) {
var oauthObject = {
oauth_consumer_key: clientId,
oauth_nonce: createNonce(10),
oauth_signature_method: "HMAC-SHA1",
oauth_token: token.oauth_token,
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_version: "1.0"
};
var signatureObj = createSignature(method, url, oauthObject, bodyParameters, clientSecret, token.oauth_token_secret);
$http.defaults.headers.common.Authorization = signatureObj.authorization_header;
return signatureObj;
},
transformRequest: transformRequest
};
}]);
serviceModule.factory('TwitterService', function ($cordovaOauth, $cordovaOauthUtility, $http, $resource, $q, AUTH_ID, $twitterHelpers)
{
var twitterKey = "STORAGE.TWITTER.KEY";
var clientId = AUTH_ID.TWITTER_APP_ID;
var clientSecret = AUTH_ID.TWITTER_APP_SEC;
function storeUserToken(data)
{
window.localStorage.setItem(twitterKey, JSON.stringify(data));
}
function getStoredToken()
{
return window.localStorage.getItem(twitterKey);
}
return {
initialize: function ()
{
var deferred = $q.defer();
var token = getStoredToken();
if (token !== null)
{
deferred.resolve(true);
}
else
{
$cordovaOauth.twitter(clientId, clientSecret).then(function (result)
{
storeUserToken(result);
deferred.resolve(true);
}, function (error)
{
deferred.reject(false);
});
}
return deferred.promise;
},
isAuthenticated: function ()
{
return getStoredToken() !== null;
},
getHomeTimeline: function ()
{
var home_tl_url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
createTwitterSignature('GET', home_tl_url);
return $resource(home_tl_url).query();
},
getTwitterProfileManual: function () {
var deferred = $q.defer();
var token = angular.fromJson(getStoredToken());
$twitterHelpers.createTwitterSignature('GET', 'https://api.twitter.com/1.1/account/verify_credentials.json', { 'include_email' : 'true' }, clientId, clientSecret, token);
$http({
method: 'GET',
url: "https://api.twitter.com/1.1/account/verify_credentials.json",
params: {'include_email': 'true'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (result)
{
console.log(result);
alert('USER TIMELINE: ' + JSON.stringify(result));
deferred.resolve(result);
}).error(function (error)
{
alert("Error: " + JSON.stringify(error));
deferred.reject(false);
});
return deferred.promise;
},
storeUserToken: storeUserToken,
getStoredToken: getStoredToken
};
});
From the above code use getTwitterProfileManual this function to get email address in twitter user object response.
Note : To get email address your twitter app must be whitelisted to have access to user email address.
I'm trying to create a chat app where you can log into the incontact chat api (discard the weatherApp naming.. ).
This is the API documentation for the incontact chat api:
function startAgentSession() {
var startSessionPayload = {
'stationId': 'string',
'stationPhoneNumber': 'string',
'inactivityTimeout': 'integer - 30-300, or 0 for default',
'inactivityForceLogout': 'boolean',
'asAgentId': 'integer'
}
$.ajax({
//The baseURI variable is created by the result.base_server_base_uri
//which is returned when getting a token and should be used to create the URL base
'url': baseURI + 'services/{version}/agent-sessions',
'type': 'POST',
'headers': {
//Use access_token previously retrieved from inContact token service
'Authorization': 'bearer ' + accessToken,
'content-Type': 'application/json'
},
'data': JSON.stringify(startSessionPayload),
'success': function (result) {
//Process success actions
return result;
},
'error': function (XMLHttpRequest, textStatus, errorThrown) {
//Process error actions
return false;
}
});
``}
This is my attempt to convert in angular js, but for some reason I keep getting a 404, however, I'm at a loss for what I've done wrong..
weatherApp.controller('launchedController', ['$scope', '$http', '$document', function ($scope, $http, $document) {
$scope.clientResult = {};
$document.ready(function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i < vars.length; i++) {
var pair = vars[i].split("=");
query_string[pair[0]] = pair[1];
}
if (typeof(query_string.access_token) != "undefined") {
var result = {};
result.state = query_string.state;
result.scope = query_string.scope;
result.access_token = query_string.access_token;
result.expires_in = query_string.expires_in;
result.resource_server_base_uri = query_string.resource_server_base_uri;
result.token_type = query_string.token_type;
}
$scope.clientResult = result;
});
console.log($scope.clientResult);
$scope.startSessionPayload = {
'stationPhoneNumber': '55555555555',
'inactivityTimeout': '0',
'inactivityForceLogout': 'false'
};
$http({
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}).success(function(data) {
$scope.data = data;
consoloe.log('data', $scope.data)
}).error(function(status) {
$scope.status = status;
});
}]);
400 error is bad request. My guess is
replace
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}
with
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: $scope.startSessionPayload
}
I found this service (see below) on GitHub and want to know how to use this service on > click of button. I am using this in my Ionic app for log in using Google+ OAuth.
I am new to AngularJS. Help me.
var googleLoginService = angular.module('GoogleLoginService', ['ngStorage']);
googleLoginService.factory('timeStorage', ['$localStorage', function ($localStorage) {
var timeStorage = {};
timeStorage.cleanUp = function () {
var cur_time = new Date().getTime();
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
if (key.indexOf('_expire') === -1) {
var new_key = key + "_expire";
var value = localStorage.getItem(new_key);
if (value && cur_time > value) {
localStorage.removeItem(key);
localStorage.removeItem(new_key);
}
}
}
};
timeStorage.remove = function (key) {
this.cleanUp();
var time_key = key + '_expire';
$localStorage[key] = false;
$localStorage[time_key] = false;
};
timeStorage.set = function (key, data, hours) {
this.cleanUp();
$localStorage[key] = data;
var time_key = key + '_expire';
var time = new Date().getTime();
time = time + (hours * 1 * 60 * 60 * 1000);
$localStorage[time_key] = time;
};
timeStorage.get = function (key) {
this.cleanUp();
var time_key = key + "_expire";
if (!$localStorage[time_key]) {
return false;
}
var expire = $localStorage[time_key] * 1;
if (new Date().getTime() > expire) {
$localStorage[key] = null;
$localStorage[time_key] = null;
return false;
}
return $localStorage[key];
};
return timeStorage;
}]);
googleLoginService.factory('googleLogin', [
'$http', '$q', '$interval', '$log', 'timeStorage',
function ($http, $q, $interval, $log, timeStorage) {
var service = {};
service.access_token = false;
service.redirect_url = 'http://127.0.0.1:81/google_demo/www/';
service.client_id = '1234567890';
service.secret = 'xxxxxxxxxxxxxxxxx';
service.scope = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/plus.me';
service.gulp = function (url, name) {
url = url.substring(url.indexOf('?') + 1, url.length);
return url.replace('code=', '');
};
service.authorize = function (options) {
var def = $q.defer();
var self = this;
var access_token = timeStorage.get('google_access_token');
if (access_token) {
$log.info('Direct Access Token :' + access_token);
service.getUserInfo(access_token, def);
} else {
var params = 'client_id=' + encodeURIComponent(options.client_id);
params += '&redirect_uri=' + encodeURIComponent(options.redirect_uri);
params += '&response_type=code';
params += '&scope=' + encodeURIComponent(options.scope);
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + params;
var win = window.open(authUrl, '_blank', 'location=no,toolbar=no,width=800, height=800');
var context = this;
if (ionic.Platform.isWebView()) {
console.log('using in app browser');
win.addEventListener('loadstart', function (data) {
console.log('load start');
if (data.url.indexOf(context.redirect_url) === 0) {
console.log('redirect url found ' + context.redirect_url);
console.log('window url found ' + data.url);
win.close();
var url = data.url;
var access_code = context.gulp(url, 'code');
if (access_code) {
context.validateToken(access_code, def);
} else {
def.reject({error: 'Access Code Not Found'});
}
}
});
} else {
console.log('InAppBrowser not found11');
var pollTimer = $interval(function () {
try {
console.log("google window url " + win.document.URL);
if (win.document.URL.indexOf(context.redirect_url) === 0) {
console.log('redirect url found');
win.close();
$interval.cancel(pollTimer);
pollTimer = false;
var url = win.document.URL;
$log.debug('Final URL ' + url);
var access_code = context.gulp(url, 'code');
if (access_code) {
$log.info('Access Code: ' + access_code);
context.validateToken(access_code, def);
} else {
def.reject({error: 'Access Code Not Found'});
}
}
} catch (e) {
}
}, 100);
}
}
return def.promise;
};
service.validateToken = function (token, def) {
$log.info('Code: ' + token);
var http = $http({
url: 'https://www.googleapis.com/oauth2/v3/token',
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
params: {
code: token,
client_id: this.client_id,
client_secret: this.secret,
redirect_uri: this.redirect_url,
grant_type: 'authorization_code',
scope: ''
}
});
var context = this;
http.then(function (data) {
$log.debug(data);
var access_token = data.data.access_token;
var expires_in = data.data.expires_in;
expires_in = expires_in * 1 / (60 * 60);
timeStorage.set('google_access_token', access_token, expires_in);
if (access_token) {
$log.info('Access Token :' + access_token);
context.getUserInfo(access_token, def);
} else {
def.reject({error: 'Access Token Not Found'});
}
});
};
service.getUserInfo = function (access_token, def) {
var http = $http({
url: 'https://www.googleapis.com/oauth2/v3/userinfo',
method: 'GET',
params: {
access_token: access_token
}
});
http.then(function (data) {
$log.debug(data);
var user_data = data.data;
var user = {
name: user_data.name,
gender: user_data.gender,
email: user_data.email,
google_id: user_data.sub,
picture: user_data.picture,
profile: user_data.profile
};
def.resolve(user);
});
};
service.getUserFriends = function () {
var access_token = this.access_token;
var http = $http({
url: 'https://www.googleapis.com/plus/v1/people/me/people/visible',
method: 'GET',
params: {
access_token: access_token
}
});
http.then(function (data) {
console.log(data);
});
};
service.startLogin = function () {
var def = $q.defer();
var promise = this.authorize({
client_id: this.client_id,
client_secret: this.secret,
redirect_uri: this.redirect_url,
scope: this.scope
});
promise.then(function (data) {
def.resolve(data);
}, function (data) {
$log.error(data);
def.reject(data.error);
});
return def.promise;
};
return service;
}
]);
angular
.module('GoogleLoginService')
.controller('SomeController', SomeController);
function SomeController(timeStorage, googleLogin) {
// just call timeStorage and googleLogin
// ex:
var anydata = timeStorage.get("anykey");
}
I tried to generate a PDF since data returned from API.
All working find exept for IE 10, Edge which open a blank window ! I dont know what happening...
Controller function :
(fileRequest = User.getFile($rootScope.PARAMS, 'facture', 'arraybuffer')).then(function(dataFactureFile)
{
var file = new Blob([dataFactureFile], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
$timeout(function()
{
if(action == 'view')
{
$window.open($scope.content);
}
if(action == 'download')
{
var anchor = document.createElement("a");
anchor.setAttribute('download', false);
anchor.download = 'FACTURE-' + $scope.infosFacture.type + '-' + $scope.infosFacture.date + '.pdf';
anchor.href = $scope.content;
anchor.click();
}
}, 500);
}, function(reason){
if(reason != 'aborted')
{
// REJECT
$scope.popin(reason.errorCode, reason.errorMsg);
}
});
Service :
getFile: function(user, type, type_response)
{
var deferredAbort = $q.defer();
var request = $http({
method: "post",
url: $rootScope.directory + 'api/' + type,
data: user,
headers: {
'Content-Type': 'api/downloadPDF'
},
responseType : type_response,
timeout: deferredAbort.promise
}).then(
function(response) {
return(response.data);
},
function(response) {
return($q.reject('aborted'));
}
);
request.abort = function() {
deferredAbort.resolve();
};
return(request);
},
In addition, the "anchor.click()" seems to not working with IE :/, somebody have a tip for simulate download click ?
Thank's you
I need to upload photos and videos together.
I am using the ng-file-upload
my mvc controller :
[HttpPost]
public ContentResult Add(List<HttpPostedFileBase> file, VideoViewModel item)
{
return Content(_output.ConvertToJson(), "application/json");
}
my javascript codes :
$scope.item = {
Address: '',
Name: ''
};
$scope.files = [];
$scope.file = null;
$scope.video = null;
$scope.response = {};
$scope.confirmAdd = function () {
if ($scope.add_form.$valid) {
$scope.files[0] = $scope.file;
$scope.files[1] = $scope.video;
$upload.upload({
url: 'User/Add',
method: 'POST',
data: $scope.item,
file: $scope.files,
}) .progress(function (evt) {
$scope.percent = parseInt(100.0 * evt.loaded / evt.total);
}).success(function (data, status, headers, config) {
$scope.response = data;
}).error(function (err) {
$scope.percent = 0;
});
} else {
$scope.add_form.submitted = true;
}
}
$scope.onFileSelect = function ($files) {
$scope.file = $files[0];
};
$scope.onVideoSelect = function ($files) {
$scope.video = $files[0];
};
error :
IIS 8.0 Detailed Error - 404.13 - Not Found
The request filtering module is configured to deny a request that exceeds the request content length
Most likely causes:
Request filtering is configured on the Web server to deny the request because the content length exceeds the configured value
How do I solve the problem?