$cordovaFileTransfer can not work - angularjs

use $cordovaFileTransfer to upload images,but it stop at 99%, $_FILES is empty in PHP;
and i get evt object.
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"16656","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"33040","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"98576","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"131344","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"147728","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"164112","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"180496","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"213264","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"229648","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"65808","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"82192","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"114960","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"295184","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"262416","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"311568","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"327952","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"344336","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"360720","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"377104","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"409872","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"442640","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"393488","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"426256","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"459024","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"475408","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"491163","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"196880","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"246032","total":"491176"}
what's wrong with the property loaded;why it increase repeatly;
upload code
$scope.upload = function(imageURI) {
$scope.dangerList[$scope.setting.num][$scope.setting.imageType + '1pic'] = imageURI;
var server = 'http://localhost/test.php';
var dirName = 'check';
var desName = 'test';
var options = {
'httpMethod': 'POST',
'params': {
'dirName': dirName,
'desName': desName
}
};
var promise = $cordovaFileTransfer.upload(server, imageURI, options, true);
promise.then(function(data) {
console.log(data);
}, function(data) {}, function(evt) {
$ionicLoading.show({
template: '<p>upload:' + parseInt(100.0 * evt.loaded / evt.total) + '%</p>',
//duration: 1000,
});
});
return promise;
};
and ngCordova\src\plugins\fileTransfer.js
angular.module('ngCordova.plugins.fileTransfer', [])
.factory('$cordovaFileTransfer', ['$q', '$timeout', function($q, $timeout) {
return {
download: function(source, filePath, options, trustAllHosts) {
var q = $q.defer();
var ft = new FileTransfer();
var uri = (options && options.encodeURI === false) ? source : encodeURI(source);
if (options && options.timeout !== undefined && options.timeout !== null) {
$timeout(function() {
ft.abort();
}, options.timeout);
options.timeout = null;
}
ft.onprogress = function(progress) {
q.notify(progress);
};
q.promise.abort = function() {
ft.abort();
};
ft.download(uri, filePath, q.resolve, q.reject, trustAllHosts, options);
return q.promise;
},
upload: function(server, filePath, options, trustAllHosts) {
var q = $q.defer();
var ft = new FileTransfer();
var uri = (options && options.encodeURI === false) ? server : encodeURI(server);
if (options && options.timeout !== undefined && options.timeout !== null) {
$timeout(function() {
ft.abort();
}, options.timeout);
options.timeout = null;
}
ft.onprogress = function(progress) {
q.notify(progress);
};
q.promise.abort = function() {
ft.abort();
};
ft.upload(filePath, uri, q.resolve, q.reject, options, trustAllHosts);
return q.promise;
}
};
}]);
and push interceptor
.factory('UserInterceptor', function ($q, $rootScope) {
return {
request:function(config){
config.headers = config.headers || {};
config.headers.UID = $rootScope.user.id || 0;
return config;
},
requestError: function(err){
return $q.reject(err);
},
response: function (response) {
return response;
},
};
})
it could work few days ago.
during the time,
add plaform with android#5.1.1 instead of android#4.1.1;
update cordova;
use ionic 1.7.3 now;
and here is the download code,it can works,but will download file twice
$scope.down = function(fname) {
var fileTransfer = new FileTransfer();
var uri = encodeURI($rootScope.rootUrl + fname);
var fileURL = cordova.file.externalRootDirectory + fname;
fileTransfer.download(
uri,
fileURL,
function(entry) {
console.log(entry);
},
function(error) {
console.log(error);
},
false, {
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
};

This is actually the response from progress event of cordovaFileTransfer.
On success it'll give response something like this:
Object {bytesSent: 3228135, responseCode: 200, response: "<!-- Served from 80.251.0.59 / test.talia.net, as …imited↵</p>↵↵</td></tr></table>↵↵</body>↵</html>↵", objectId: ""}
But as per the output you are getting,I think the function is getting interrupted by the same method from another instance because your whole file was almost uploaded in the 3rd last line.
"cancelable":"false","lengthComputable":"true","loaded":"491163","total":"491176"}
And then it picked up from some another point.
Please provide the code so I can try to assist you further.
Thank you

Related

Angular File Upload upload all in one request

I use this plugin https://github.com/nervgh/angular-file-upload to use multiple file upload in my project.
However, I know that in jQuery File upload plugin you can choose to upload all files in one query, or not.
Is it possible to do this with this plugin ? I found nothing in their docs, and I took a look to the code, it seems not native option.
It is not possible using options or default behaviour, I have edited the file and function uploadAll() :
/**
* Uploads all not uploaded items of queue
*/
FileUploader.prototype.uploadAll = function() {
var items = this.getNotUploadedItems().filter(function(item) {
return !item.isUploading;
});
if (!items.length) return;
var that = this;
angular.forEach(items, function(item) {
item._prepareToUploading();
});
if (this.isHTML5) {
//FILL FormData WITH FILE DETAILS.
var data = new FormData();
var first = true;
angular.forEach(items, function(item) {
console.log(item);
data.append("files", item._file, item.file.name);
// get formData
that._onBeforeUploadItem(item);
// add formData
if (first) {
angular.forEach(item.formData, function(obj) {
angular.forEach(obj, function(value, key) {
data.append(key, value);
});
});
first = false;
}
});
// ADD LISTENERS.
var objXhr = new XMLHttpRequest();
objXhr.addEventListener('load', this.onCompleteAll, false);
objXhr.upload.onprogress = function(event) {
var progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);
angular.forEach(items, function(item) {
item._onProgress(progress);
});
};
objXhr.onerror = function() {
var headers = that._parseHeaders(objXhr.getAllResponseHeaders());
var response = that._transformResponse(objXhr.response, headers);
angular.forEach(items, function(item) {
that._onErrorItem(item, response, objXhr.status, headers);
that._onCompleteItem(item, response, objXhr.status, headers);
});
};
objXhr.open("POST", this.url);
angular.forEach(this.headers, function(value, name) {
objXhr.setRequestHeader(name, value);
});
// SEND FILE DETAILS TO THE API.
objXhr.send(data);
} else {
items[0].upload();
}
};
I made a new function UploadAllAtOnce() & is working for me. Thanks to #Vincent Decaux. I've modified some code as below -
FileUploader.prototype.uploadAllAtOnce = function uploadAllAtOnce() {
var items = this.getNotUploadedItems().filter(item => !item.isUploading);
if (!items.length) return;
forEach(items, item => item._prepareToUploading());
var that = this;
forEach(items, function (item) {
return item._prepareToUploading();
});
if (this.isHTML5) {
var sendable = new FormData();
var first = true;
forEach(items, (item) => {
sendable.append(item.alias, item._file, item.file.name);
// get formData
that._onBeforeUploadItem(item);
// add formData
if (first) {
angular.forEach(item.formData, function (obj) {
angular.forEach(obj, function (value, key) {
sendable.append(key, value);
});
});
first = false;
}
});
// ADD LISTENERS.
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', this.onCompleteAll, false);
xhr.upload.onprogress = (event) => {
var progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);
angular.forEach(items, function (item) {
item._onProgress(progress);
});
};
xhr.onerror = () => {
var headers = this._parseHeaders(xhr.getAllResponseHeaders());
var response = this._transformResponse(xhr.response, headers);
angular.forEach(items, function (item) {
that._onErrorItem(item, response, xhr.status, headers);
that._onCompleteItem(item, response, xhr.status, headers);
});
};
xhr.onload = () => {
var headers = this._parseHeaders(xhr.getAllResponseHeaders());
var response = this._transformResponse(xhr.response, headers);
angular.forEach(items, function (item) {
var gist = that._isSuccessCode(xhr.status) ? 'Success' : 'Error';
var method = '_on' + gist + 'Item';
that[method](item, response, xhr.status, headers);
// that._onCompleteItem(item, response, xhr.status, headers);
});
};
xhr.onabort = () => {
var headers = this._parseHeaders(xhr.getAllResponseHeaders());
var response = this._transformResponse(xhr.response, headers);
angular.forEach(items, function (item) {
his._onCancelItem(item, response, xhr.status, headers);
this._onCompleteItem(item, response, xhr.status, headers);
});
};
xhr.open("POST", this.url, true);
forEach(this.headers, (value, name) => {
xhr.setRequestHeader(name, value);
});
xhr.send(sendable);
} else {
items[0].upload();
}
};

Angular resolve promise and update existing scope

I am trying to understand Angular's promises and scopes. Actually I implemented the directive bellow. The thing that I want to do is to receive images from server and store locally in order to cache them for next times. Also I want to show a spinner before the load of image is completed and show it after the completion.
How can update variable newUrl into directive when completed all of these promises?
Do you have any idea?
My HTML code is:
<div style="text-align: center;"
cache-src
url="https://upload.wikimedia.org/wikipedia/commons/c/c0/Aix_galericulata_(Male),_Richmond_Park,_UK_-_May_2013.jpg">
</div>
My directive is:
.directive('cacheSrc', [function () {
return {
restrict: 'A',
scope: {
url: '#'
},
controller: 'cacheSrcCtrl',
template: '<img width="100%" ng-if="newUrl!=null" src="{{newUrl}}"><ion-spinner ng-if="newUrl==null" icon="spiral"></ion-spinner>',
};
}])
And the controller of directive has the function bellow:
document.addEventListener('deviceready', function () {
$scope.updateUrl = function (newUrl) {
$scope.newUrl = newUrl;
};
var tmp = $scope.url;
$cordovaSQLite.execute(db, 'SELECT * FROM images where url = (?)', [tmp])
.then(function (result) {
if (result.rows.length > 0) {
$scope.exists = true;
for (var i = 0; i < res.rows.length; i++) {
var image = {
id: res.rows.item(i).id,
url: res.rows.item(i).url,
uri: res.rows.item(i).uri
};
$scope.updateUrl(image.uri);
}
} else {
$scope.exists = false;
var fileTransfer = new FileTransfer();
var uri = encodeURI(tmp);
var uriSave = '';
var fileURL = cordova.file.dataDirectory + uri;//'kaloudiaImages';// + getUUID();// + "DCIM/myFile";
fileTransfer.download(
uri, fileURL, function (entry) {
uriSave = entry.toURL();
KaloudiaDB.add(tmp, fileURL);
$scope.newUrl = fileURL;
$scope.updateUrl(fileURL);
},
function (error) {
console.log("download error code" + error.code);
},
false, {
headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
).then(function (data) {
$scope.newUrl = fileURL;
});
}
}, function (error) {
$scope.statusMessage = "Error on saving: " + error.message;
})
.then(function (data) {
$scope.$apply(function () {
$scope.newUrl = fileURL;
});
});
});

How to get email address from twitter

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.

How to Use Factory Service in AngularJS?

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");
}

IE10 - Page Blank when window.open(trustedURL) - PDF ANGULAR JS

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

Resources