Take screen shot , upload and tweet on titanium - titanium

I am making application on iOS and Android on Titanium.
What I want to do is
1) take screen shot
2) upload pics
3) post tweet including pics link
What I have done so far is.
1)I can take screenshot like this and save the photo in camera folder
Ti.Media.takeScreenshot(function(e){
Ti.Media.saveToPhotoGallery(e.media);
});
2)I have no idea about that
3)I can tweet with social.js
var social = require('social');
var twitter = social.create({
site : 'Twitter',
consumerKey : '*',
consumerSecret : '*'
});
twitter.share({
message : data,
success : function() {
Ti.API.info('Tweeted!');
},
error : function(error) {
Ti.API.info('You have already shared this app on Twitter.');
}
});
Currently I am trying to do on twitter however I would like to make for android version.
Thank you for the comment of #turtle.
I found I need to use Social_plus.js.
I have changed the code like this below
var social = require('/myfunc/social_plus');
var data = new Object();
Ti.Media.takeScreenshot(function(e){
Ti.Media.saveToPhotoGallery(e.media);
data['image'] = e.media;
});
data['text'] = 'lets tweet!!';
var twitter = social.create({
site : 'Twitter',
consumerKey : '*',
consumerSecret : '*'
});
twitter.shareImage({
message : data['text'],
image : data['image'],
success : function() {
Ti.API.info('Tweeted!');
},
error : function(error) {
Ti.API.info('Somehow error!.');
}
});
However, I got the error like this .
[ERROR] : Social.js: FAILED to send a request!
[INFO] : You have already shared this app on Twitter.
[ERROR] : {"errors":[{"code":195,"message":"Missing or invalid url parameter."}]}
c
I guess there is something wrong with the sentene
data['image'] = e.media;
But I can't find good information around here.

Related

Successful Login to API; Unsuccessful at accessing any data due to being unauthorized

I am attempting to come up with a live leaderboard for my local club using the PDGA's (Professional Disc Golf Association) API. I am writing a Google Apps Script intending to auto populate a Google Sheet with a Club Ranking that can be refreshed as needed.
Right now, all I am trying to do is make pull of data to ensure I am able to begin using the API, but I can't seem to do even that.
For reference, here are the only two resources I have to work with regarding this specific API:
PDGA REST API Authentication
PDGA REST API Services
I have got the original login to work using this code:
function apiLogin() {
var LoginUrl = 'https://api.pdga.com/services/json/user/login';
var LoginDetails = {
'username' : Username,
'password' : Password
};
var LoginRequest = {
'method' : 'post',
'Content-Type' : 'application/json',
'payload' : LoginDetails
};
var LoginResponse = UrlFetchApp.fetch(LoginUrl, LoginRequest);
var json = LoginResponse.getContentText();
var LoginData = JSON.parse(json);
Logger.log(LoginData);
var SessionID = LoginData['sessid'];
var SessionName = LoginData['session_name'];
var Tok = LoginData['token'];
var playerFetchPar = {
'method' : 'get',
'Cookie' : SessionID + '=' + SessionName
};
var PlayerResponse = UrlFetchApp.fetch('https://api.pdga.com/services/json/players?pdga_number=1',playerFetchPar); //ERROR
Logger.log(PlayerResponse);
};
It's the last part when I am trying to call on data from a player that I get the following error message:
Exception: Request failed for https://api.pdga.com returned code 403. Truncated server response: ["Access denied for user anonymous"] (use muteHttpExceptions option to examine full response)
I am guessing that my screw up is in my interpretion of the parameter Cookie from that second link. In the initial response to make sure I was logging in properly, I received a session_name and sessid but I can't seem to figure out what is expected from Cookie. I am sorry if the answer is obvious, but any help would be greatly appreciated!
The documentation says
Cookie: session_name=sessid
You've used
Cookie: sessid=session_name
Reverse it:
'Cookie' : `${SessionName}=${SessionID}`
And you need to send it as a header:
const playerFetchPar = {
method : 'get',
headers: {'Cookie' : `${SessionName}=${SessionID}`}
};

How To Retrieve Data From Rest API In Appcelerator

I have the misfortune of further developing an existing mobile application in Appcelerator. The app uses a Rest API on a remote server to read and write data. The API works well in test environments and in production. I need to post data to the API and read the output. Here is an example of what the output of the API looks like after a POST command:
{
"equipment":
{
"result": "create",
"id": 419213
},
"_meta":
{
"offset": 0,
"limit": -1,
"total_results": 1,
"url": "http://localhost:8080/api/v1/equipment",
"utc_start_time": 1459449461115,
"nano_total_time": 74771
}
}
I am able to successfully post the data in Appcelerator. I have verified this in the database that the CRUD operation is acting on. However, I am unable to get the aforementioned data from the httpClient object that makes the call, despite following the directions in the outdated Titanium documentation.
Here is my Appcelerator code:
var payload = "name=atad&asset_number=adtasd&department_id=185080&property_id=10086&designator_id=379828&is_leased=N&is_assignable_asset=N&status=A";
var url = "http://localhost:8080/api/v1/equipment";
var client = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.API.info(e); // {}
Ti.API.info(e.source); // []
Ti.API.info(JSON.stringify(e.source)); // {}
Ti.API.info(JSON.stringify(e.source.reponseText)); // null
Ti.API.info(JSON.stringify(e.source.reponseData)); // null
Ti.API.info(this); // []
console.log(JSON.stringify(this)); // {}
Ti.API.info(JSON.stringify(this.reponseText)); // null
Ti.API.info(this.reponseData); // null
}
,onerror : function(e){
Ti.API.info(e);
alert("error");
}
});
var auth = 'Basic ' + Ti.App.Properties.getString('auth');
client.open("POST", apiUrl);
client.setRequestHeader('Authorization', auth);
client.setRequestHeader('Content-Type', 'text/plain');
client.send(payload);
Here is the console output:
[INFO] : {
[INFO] : code = 0;
[INFO] : source = "[object TiNetworkHTTPClient]";
[INFO] : success = 1;
[INFO] : type = load;
[INFO] : }
[INFO] : [object TiNetworkHTTPClient]
[INFO] : {"method":"POST","url":"http://localhost:8080/api/v1/equipment"}
[INFO] : <null>
[INFO] : <null>
[INFO] : [object TiNetworkHTTPClient]
[INFO] : {"method":"POST","url":"http://localhost:8080/api/v1/equipment"}
[INFO] : <null>
[INFO] : <null>
The documentation here http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network.HTTPClient explicitly says to use this.responseText, but that is clearly not giving me the results I need. I need that "id" that is being returned from the server.
How do I read the data that is returned from the server after a post API call?
There is just a typo in this.responseText
Have a look at this module: https://github.com/jasonkneen/RESTe
It makes your life easier and gives you a great way to the same syntax for future projects!
If you want to keep your syntax (which is fine too):
have a look at this example: https://github.com/m1ga/titanium-libraries/blob/master/api.js#L49
and the following lines. It shows you how to read the JSON. Basically you have to wait for if (this.readyState === 4) {} inside the onload and then read the this.responseText or JSON.parse() it.
It looks like the apiUrl variable is not defined?
Which could explain a lot or your current frustration.

What should I consider when I am doing an authentication process with a titanium app?

Hello it's my first time doing a sign in process in a mobile app with Titanium and I wonder what information should I save and the best practice to do it?
My server is configured in this way:
The server requires I send a user and password and if the information match it will provide a token session.
This is the code I use for signing in:
function signIn(e) {
//function to use HTTP to connect to a web server and transfer the data.
var sendit = Ti.Network.createHTTPClient({
onerror : function(e) {
Ti.API.debug(e.error);
alert('There was an error during the connection');
},
timeout : 100000,
});
//Here you have to change it for your local ip
sendit.open('POST', 'http://myserver');
var params = {
user : $.txtUsuario.value,
password : $.txtPassword.value
};
sendit.send(params);
//Function to be called upon a successful response
sendit.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
if (response.success == "true")
{
var landing = Alloy.createController("menu").getView();
$.index.close();
landing.open();
}
else
{
alert(response);
}
};
};
the code above is working, however I do not know how to manage the sign out. I would like my application works like the most apps do, e.g:
You sign in once and after that if you do not close the app you are able to continues using it and even making a request.
Thank you for any explanation.
It depends on your app requirements. for exemple if you will use the token in your app later you can save it as an AppProperty :
Ti.App.Properties.setString('token',yourTokenGoHere);
and in the app starting you can get it back :
var myToken = Ti.App.Properties.getString('token');
and then you can make a test for example if the token is still valid or not :
if(myToken === 'invalidtoken')
youSholdLogin();
else
youCanGoFurther();
and when the user disconnect rest the token to be invalid :
Ti.App.Properties.setString('token', 'invalidtoken');

angular fullstack generator can not send iamge stored in mongodb

What a want to achieve is simple. I am using angular fullstack generator to produce the skeleton. User should be able to upload a profile picture along with their name, email etc. I am using angular-file-uplpoad to send the multipart form request. And according to its wiki, I also used code below.
// Requires multiparty
multiparty = require('connect-multiparty'),
multipartyMiddleware = multiparty(),
// Requires controller
UserController = require('./controllers/UserController');
// Example endpoint
router.post('/api/user/uploads', multipartyMiddleware, UserController.uploadFile);
I am also using gridfs-stream to stream the profile image into mongo gridfs. Everything seems fine here. Because if I stream the profile image into server local file, I can actually open and view the image. The problem is that, now I want to send the image back to the browser. I wrote code below
var Grid = require('gridfs-stream');
var GridFS = Grid(mongoose.connection.db, mongoose.mongo);
var fs = require('fs');
/*
var UserSchema = new Schema({
first_name: String,
last_name: String,
email: { type: String, lowercase: true },
role: {
type: String,
default: 'user'
},
hashedPassword: String,
provider: String,
salt: String,
phone: String,
projects: [{
type : Schema.Types.ObjectId,
ref : 'Project'
}],
profile_picture: Schema.Types.ObjectId
});
*/
// each user has a _id for a image file in mongodb
getFile : function() {
var readstream = GridFS.createReadStream({
_id : this.profile_picture,
});
response.writeHead(200, {'Content-Type': 'iamge/png' });
readstream.pipe(response);
},
But this does not work. To test it. I even use fs.createReadStream(filename) to load a static image stored in the server side. The image is actually sent but the it's a broken image received in the browser. I also tried response.download('filename'); still does not work. Any suggestions?
Thanks!
You wrote: {'Content-Type': 'iamge/png' }
Fix it to: {'Content-Type': 'image/png' }
Let me know if that solves it because I am also having problems and have similar code.

Facebook FB.api post how to specify a target

I am using FB.api OpenGraph to post a message on the user's wall. I would like the link target to be equal to '_blank' so it opens in a new tab. Is it possible ? The Facebook documentation doesn't give much details.
var params = {};
params['message'] = 'message';
params['name'] = 'name';
params['link'] = 'http://link';
params['picture'] = 'http://picture';
params['description'] = 'description';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});
that's something they manage themselves. there's nothing you can do. Still, AFAIK, that's the default behavior.
I think it has something to do with your Apps Url in the app settings.
Im witnessing that , when the apps url was app.com
all links i shared on my users feed with the link app.com/results.php would open on the same tab and links i shared with the link www.app.com/results.php would open in a new link.
The problem there , was , that from www.app.com , i couldnot authorize api access for some reason.
I'll try to register both urls , and see what happens.