Why do I get a connection timeout for facebook api-video? - api

This is the API call Im attempting:
http://developers.facebook.com/docs/reference/rest/video.upload
(Video upload is not available in the new Graph API.)
I have tried many variations on the parameters. The code below is my best guess. If I modify the params to be obviously incorrect, change to http (not https) or try to use api.facebook.com for video, I get proper errors back.
However, my code below just waits a few minutes before reporting:
ETIMEDOUT: Connection timed out
Also included is working code to upload a photo - which is almost identical.
Ruby:
# Facebook Old-API method - testing only - this works.
def post_photo
url = "https://api.facebook.com/method/photos.upload"
body = {
nil => File.new(self.media.media_files.first.source_file, 'rb'),
:access_token => self.session.auth_data[:access_token],
:callback => "none",
:aid => "Test Photos",
:caption => "Test",
:uid => self.session.auth_data[:uid],
}
response = RestClient.post url, body
end
# Facebook Old-API method - doesn't work - connection timeout.
def post_video
url = "https://api-video.facebook.com/method/video.upload"
body = {
:nil => File.new(self.media.media_files.first.source_file, 'rb'),
:access_token => self.session.auth_data[:access_token],
:callback => "none",
:title => "Test title",
:description => "Test description",
:privacy => "{ value: 'EVERYONE' }",
:uid => self.session.auth_data[:uid],
}
response = RestClient.post url, body
end
PS: Im in Australia - is the API limited to eg the USA?
Thanks

Related

Devise Token Auth / Angular2-Token, update password, Completed 401 Unauthorized

I'm having troubles restoring password with devise_token_auth. and Angular2-Token. I'm successfully receiving the email with the link to update my password. But I'm getting an 401 Unauthorized response when submiting the new password.
Front end. I'm getting the token from the URL with urlParams.get('token')
onPasswordUpdate() {
let token = this.urlParams.get('token');
var obj = Object.assign(this._updatePasswordData, { reset_password_token: token })
this._tokenService.patch('auth/password/', obj ).subscribe(
res => res,
error => error
);
}
Back end response.
Started PATCH "/api/auth/password/" for 127.0.0.1 at 2016-12-01 21:17:48 +0100
Processing by DeviseTokenAuth::PasswordsController#update as JSON
Parameters: {"reset_password_token"=>"[FILTERED]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}
Completed 401 Unauthorized in 1ms (Views: 0.4ms | ActiveRecord: 0.0ms)
In the link of the email I get the following token : reset_password_token=HneZDoKTMCLF3_SLfnxy
When I visit the link, the user record gets updated with the following attributes :
reset_password_token: "aa3cba76c7b1d8f78cde6856f43e1cce57f5fc8e5301842733de677eff909bc1"
tokens: {}
Then in the browser URL I get the following token=agejaip2SqOp9nvwE1GAHQ&uid
And then the user record get updated with the following attribues :
...
reset_password_token: "HneZDoKTMCLF3_SLfnxy",
tokens: {"pv9i1BDTM29ezep0KSPzpA"=>{"token"=>"$2a$10$cS9gbe9UBICcgphZHRAENOMS6NlEe0Em1cNufY3LSRTPE.hRMabvi", "expiry"=>1481834221}}
...
It seems to me that the token I get back in URL is not correct.
Those anyone have an idea ?
Sorry It's a bit hard to explain.
Many thanks.
rails (4.2.4)
devise_token_auth (0.1.34)
devise (= 3.5.1)
angular2-token: 0.2.0-beta.1
I faced similar challenges recently, and this was how I solved it.
Expose the 'access-token', 'expiry', 'token-type', 'uid', 'client' for your backend. Check here and here
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
:expose => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
:methods => => [:get, :post, :options, :delete, :put, :patch]
end
end
Set your redirect_url of path: /password, method: POST. Check info here
We need to modify the reset_password_instructions.html.erb to point it to the api GET /auth/password/edit. More information provided here.
E.g. if your API is under the api namespaces:
<%= link_to 'Change my password', edit_api_user_password_url(reset_password_token: #token, config: message['client-config'].to_s, redirect_url: message['redirect-url'].to_s) %>

eBay API in Perl - can't use SetShipmentTrackingInfoRequest to update tracking information

I'm trying to figure out why I can't seem to update a tracking number using the eBay API. Here is the page I'm referencing:
http://developer.ebay.com/DevZone/merchant-data/CallRef/SetShipmentTrackingInfo.html
Based on that, I've got the following code in Perl:
use Net::eBay;
my $ebay = new Net::eBay( {
SiteLevel => 'prod',
DeveloperKey => 'x',
ApplicationKey => 'xxxx',
CertificateKey => 'xxx',
Token => 'xxxx',
} );
$ebay->setDefaults( { API => 2, compatibility => 900 } );
my $result = $ebay->submitRequest( "SetShipmentTrackingInfoRequest",
{
DetailLevel => "ReturnAll",
ErrorLevel => "1",
SiteId => "1",
OrderID => 1234546, # not the real order ID I'm using :)
ShipmentTrackingDetails => {
ShipmentTrackingNumber => "12345",
ShippingCarrierUsed => "Hermes"
}
});
print $IN->header;
use Data::Dumper;
print Dumper($result);
When running it, I get an error in $result:
$VAR1 = {
'Errors' => {
'ErrorClassification' => 'RequestError',
'SeverityCode' => 'Error',
'ShortMessage' => 'Unsupported API call.',
'ErrorCode' => '2',
'LongMessage' => 'The API call "SetShipmentTrackingInfoRequest" is invalid or not supported in this release.'
},
'xmlns' => 'urn:ebay:apis:eBLBaseComponents',
'Timestamp' => '2016-10-21 07:03:04',
'Build' => '18007281',
'Version' => '900',
'Ack' => 'Failure'
};
I'm a bit confused, as it looks like SetShipmentTrackingInfoRequest is the API call I need to be making? I've not really done much with the eBay API, so it's possible I'm missing something stupid.
UPDATE: As per feedback below, I'm now using the CompleteSale API call:
http://developer.ebay.com/Devzone/XML/docs/Reference/eBay/CompleteSale.html
my $result = $ebay->submitRequest( "CompleteSale ",
{
DetailLevel => "ReturnAll",
ErrorLevel => "1",
SiteId => "1",
OrderID => 1933420817015,
Shipment => {
ShipmentTrackingDetails => {
ShipmentTrackingNumber => "77293124902615",
ShippingCarrierUsed => "Hermes"
}
}
});
When I run it, I now get the error:
'LongMessage' => 'XML Error Text: "; nested exception is:
org.xml.sax.SAXParseException: Attribute name "Request" associated with an element type "CompleteSale" must be followed by the
\' = \' character.".',
Enabling debugging, the XML being sent is:
<?xml version='1.0' encoding='utf-8'?>
<CompleteSale Request xmlns="urn:ebay:apis:eBLBaseComponents">
<RequesterCredentials>
<eBayAuthToken>xxxx</eBayAuthToken>
</RequesterCredentials>
<DetailLevel>ReturnAll</DetailLevel>
<ErrorLevel>1</ErrorLevel>
<OrderID>xxxxx</OrderID>
<Shipment>
<ShipmentTrackingDetails>
<ShipmentTrackingNumber>xxxx</ShipmentTrackingNumber>
<ShippingCarrierUsed>Hermes</ShippingCarrierUsed>
</ShipmentTrackingDetails>
</Shipment>
<SiteId>1</SiteId>
</CompleteSale Request>
From looking at the eBay API doc link you posted doesn't the second 'Note' entirely explain why it doesn't work as a single API call?
Note: SetShipmentTrackingInfo cannot be issued on its own like an ordinary API call, using an endpoint
It then goes on to say:
In the Trading API, the CompleteSale call provides similar functionality that you can invoke directly
So perhaps looking there should be the next step

Getting 'undefined method batch' for Google Directory API with service account

So I'm writing a script to batch delete users from a Google Apps for Education domain. The code looks like this:
#! /usr/bin/env ruby
require 'google/api_client'
require 'csv'
service_account_email = 'XXXXXXX#developer.gserviceaccount.com'
key_file = 'key.p12'
key_secret = 'notasecret'
admin_email = 'XXX#xxx'
# Build the API Client object
client = Google::APIClient.new(
:application_name => 'XXX',
:application_version => '0.1'
)
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/admin.directory.user',
:issuer => service_account_email,
:signing_key => key,
:person => admin_email,
)
client.authorization.fetch_access_token!
directory = client.discovered_api('admin', 'directory_v1')
# Reads and parses CSV input into a hash
# Takes file path as an argument
def import_csv(file)
csv = CSV.new(
File.open(file).read,
:headers => true,
:header_converters => :symbol
)
return csv.to_a.map {|row| row.to_hash}
end
users_to_delete = import_csv('accounts.csv')
puts 'Preparing to delete users...'
users_to_delete.each_slice(1000) do |chunk|
directory.batch do |directory|
chunk.each do |user|
client.execute!(
:api_method => directory.users.delete,
:parameters => { :userKey => user[:emailaddress].downcase }
)
end
end
end
puts 'Users successfully deleted!'
When I run the script without the two outer batch blocks, the script runs perfectly (although incredibly slowly).
What I want to know is what I need to change to stop giving me the undefined method error on the 'batch' method for the directory API. In examples in Google's documentation, I've noticed that they call the API differently (zoo = Google::Apis::ZooV1::ZooService.new instead of zoo = client.discovered_api('zoo', 'v1')). I don't see how that would make a difference though.
You can do achieve it this way:
client = Google::APIClient.new(
:application_name => 'XXX',
:application_version => '0.1'
)
directory = client.discovered_api('admin', 'directory_v1')
batch = Google::APIClient::BatchRequest.new do |result|
puts result.data
end
batch.add(:api_method => directory.users.delete,:parameters => { :userKey => user[:emailaddress].downcase })
client.execute(batch)

How do I properly set the request header of a Rhomobile API call?

Environment:
Windows Server 2012 Standard
rhodes-3.5.1.13 - MotorolaRhoMobileSuite2.2.1.13
jQuery Mobile 1.6.4
Java jdk1.6.0_24
Description:
After making this call..
Rho::AsyncHttp.get(
:url => url,
:headers => {
'Accept'=>'application/json',
'Accept-Encoding'=>'gzip,deflate,sdch',
'Accept-Language'=>'en-US,en;q=0.8'
},
:callback => callback,
:callback_param => callback_param
)
...the result of this request returns the following:
"Rho::AsyncHttp....callback_param)" {"rho_callback"=>"1", "status"=>"error", "error_code"=>"1", "headers"=>{"Accept"=>"application/json", "Accept-Encoding"=>"gzip,deflate,sdch", "Accept-Language"=>"en-US,en;q=0.8", "User-Agent"=>"Mozilla-5.0 (ANDROID; Win32; 4.0.3)"}, "body"=>""}
Question:
Is there a Rhomobile limitation on the headers that I am allowed to pass to this call? It seems to work if I paste the url, with the headers, into Fiddler. When I remove 'Accept-Encoding'=>'gzip,deflate,sdch', the response is the same.
Thanks in advance.
Rhodes uses libcURL for implementing the AsyncHTTP API in v3.5 of the framework as is possible to see in the sourcecode.
So whatever is possible to do in libcURL, the same is possible to do in ASyncHTTP.
In your particular case I'll probably use the "Content-Type" instead of the "Accept" header:
Rho::AsyncHttp.get(
:url => url,
:headers => {
'Content-Type'=>'application/json',
'Accept-Encoding'=>'gzip,deflate,sdch',
'Accept-Language'=>'en-US,en;q=0.8'
},
:callback => callback,
:callback_param => callback_param
)
If you want to test this in Rhodes v4.0, there now the Network API that you can use in the same way:
getProps = Hash.new
getProps['url'] = url
getProps['headers'] = {"Content-Type" => "application/json",
"Accept-Encoding"=>"gzip,deflate,sdch",
"Accept-Language"=>"en-US,en;q=0.8"}
Rho::Network.get(getProps, url_for(:action => :callback))

How do I test my JSON API with Sinatra + rspec

I have a post method that accepts JSON:
post '/channel/create' do
content_type :json
#data = JSON.parse(env['rack.input'].gets)
if #data.nil? or !#data.has_key?('api_key')
status 400
body({ :error => "JSON corrupt" }.to_json)
else
status 200
body({ :error => "Channel created" }.to_json)
end
As a newbie to rspec I am bewildered trying to figure out how to write a test against that POST with an acceptable JSON payload. The closest I got to is this which is woefully inaccurate but I don't seem to be asking the Google god the right questions to help me out here.
it "accepts create channel" do
h = {'Content-Type' => 'application/json'}
body = { :key => "abcdef" }.to_json
post '/channel/create', body, h
last_response.should be_ok
end
Any best practice guidance for testing APIs in Sinatra will be most appreciated also.
The code you've used is fine, although I would structure it slightly differently as I don't like to use it blocks the way you normally see them, I think it encourages testing of more than one aspect of a system at a time:
let(:body) { { :key => "abcdef" }.to_json }
before do
post '/channel/create', body, {'CONTENT_TYPE' => 'application/json'}
end
subject { last_response }
it { should be_ok }
I've used let because it's better than an instance variable in a before block (kudos to you for not doing that). The post is in a before block because it's not really part of the spec, but a side effect that occurs prior to what you're speccing. The subject is the response and that makes the it a simple call.
Because checking the response is ok is needed so often I put it in a shared example:
shared_examples_for "Any route" do
subject { last_response }
it { should be_ok }
end
and then call it as such:
describe "Creating a new channel" do
let(:body) { { :key => "abcdef" }.to_json }
before do
post '/channel/create', body, {'CONTENT_TYPE' => 'application/json'}
end
it_should_behave_like "Any route"
# now spec some other, more complicated stuff…
subject { JSON.parse(last_response.body) }
it { should == "" }
and because the content type changes so often, I put that in a helper:
module Helpers
def env( *methods )
methods.each_with_object({}) do |meth, obj|
obj.merge! __send__(meth)
end
end
def accepts_html
{"HTTP_ACCEPT" => "text/html" }
end
def accepts_json
{"HTTP_ACCEPT" => "application/json" }
end
def via_xhr
{"HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"}
end
It's easy to add this in where it's needed by including it via the RSpec config:
RSpec.configure do |config|
config.include Helpers, :type => :request
then:
describe "Creating a new channel", :type => :request do
let(:body) { { :key => "abcdef" }.to_json }
before do
post '/channel/create', body, env(:accepts_json)
end
Having said all that, personally, I wouldn't post using JSON. HTTP POST is simple to handle, and every form and javascript library does it easily and well. Respond with JSON by all means, but don't post JSON, HTTP is a lot easier.
Edit: after writing out the Helpers bit above I realised it would be more helpful as a gem.
Looks like the ability to do post :update, '{"some": "json"}' was added to the internal ActionPack test_case.rb used by rspec in this commit:
https://github.com/rails/rails/commit/5b9708840f4cc1d5414c64be43c5fc6b51d4ecbf
Since you're using Sinatra I'm not sure the best way to get those changes—you might be able to upgrade ActionPack directly, or patch from the above commit.
If you want to look at last_response as JSON, you could try rack-test-json which makes this trivial:
expect(last_response).to be_json
expect(last_response.as_json['key']).to be == 'value'