Post push notification to C2DM (android) using Django - android

I found how to send push notification to Android device using Django here (here is the code).
So adopted that and my code looks like this:
def sendAndroidPushNotification(registration_id, collapse_key, a, b) :
try:
auth = getNewAndroidAuthorizationToken() # this works I'm fetching new token so this is up to date (its length is 267 characters)
push_request = urllib2.Request("https://android.apis.google.com/c2dm/send")
data = urllib.urlencode({'data.testA' : a,
'data.testB' : b,
'collapse_key' : collapse_key,
'registration_id': registration_id
})
push_request.add_data( data )
push_request.add_header('Authorization', 'GoogleLogin auth=' + auth)
push_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
push_request.add_header('Content-Length', len(data))
urllib2.build_opener().open(push_request)
except urllib2.HTTPError as e:
print 'got exception during push notification'
print 'Reason: "{0}" code: {1}'.format(e.reason, e.code)
pass
this give me error: "Reason: "Unauthorized" code: 401" (at some point it was 403). Version which uses httplib.HTTPSConnection instead of urllib2.Request has same problem.
It looks almost the same as code shown here so I'm totally confused. What I'm doing wrong?
Edit:
Just in case, here is how I fetch authorization token (it looks like that it works fine), maybe my parsing is wrong:
def getNewAndroidAuthorizationToken() :
request = urllib2.Request("https://www.google.com/accounts/ClientLogin")
data = urllib.urlencode({'accountType' : 'HOSTED_OR_GOOGLE',
'Email' : 'someaccount#gmail.com',
'Passwd' : 'asdjsdfa',
'service' : 'ac2dm',
'source' : 'com.mycompany.mypackage',})
request.add_data(data)
content = urllib2.build_opener().open(request)
lines = content.readlines()
for line in lines :
if line.find("Auth=")==0 :
return line[5:]
return

C2DM is deprecated. Developers are encouraged to switch to GCM, C2DM will be supported for a short time. Simple API instead of ClientLogin and oAuth2 which are not supported.
http://developer.android.com/guide/google/gcm/index.html

Related

Parse platform object not found getting _Installation/null

We are adding push notifications to an Android app using Parse backend.
It has standard initialisation code like this:
Parse.initialize(Parse.Configuration.Builder(this)
.applicationId("...")
.clientKey("...")
.server("...")
.build()
)
val installation = ParseInstallation.getCurrentInstallation()
installation.put("GCMSenderId", "...")
installation.saveInBackground()
When this changes go to production, we started seeing random "Object not found" error in the backend like this:
app/web.1 verbose: REQUEST for [GET]
/parse/classes/_Installation/null: {} method=GET,
url=/parse/classes/_Installation/null, host=..., connection=close,
x-parse-application-id=..., x-parse-app-build-version=...,
x-parse-app-display-version=..., x-parse-os-version=11,
user-agent=Parse Android SDK API Level 30,
x-parse-installation-id=..., x-parse-client-key=...,
accept-encoding=gzip, x-request-id=..., x-forwarded-for=...,
x-forwarded-proto=https, x-forwarded-port=443, via=1.1 vegur,
connect-time=0, x-request-start=1676010960572, total-route-time=0,
app/web.1 error: Object not found. message=Object not found.,
stack=Error: Object not found. at
/app/node_modules/parse-server/lib/Routers/ClassesRouter.js:70:15
This error appears to happen only on a small group of users. For all our test devices, push notifications work correctly.
It is unclear if these particular users will have problem in receiving push notifications eventually.
Why is Android app getting _Installation/null?

Connection between Android and AWS SageMaker with AWS Lambda

I set up a connection between Android and AWS Lambda which has the endpoint set to SageMaker. I am using the REST API during the connection, the AWS Cognito plug is set to be accessed without authorization.
I make a connection as described here:
https://aws.amazon.com/blogs/machine-learning/call-an-amazon-sagemaker-model-endpoint-using-amazon-api-gateway-and-aws-lambda/
My question is how to send this data:
{"data":"13.49,22.3,86.91,561.0,0.08752,0.07697999999999999,0.047510000000000004,0.033839999999999995,0.1809,0.057179999999999995,0.2338,1.3530000000000002,1.735,20.2,0.004455,0.013819999999999999,0.02095,0.01184,0.01641,0.001956,15.15,31.82,99.0,698.8,0.1162,0.1711,0.2282,0.1282,0.2871,0.06917000000000001"}
And how to view the received response later. Anyone know how to do it or where I can find tips on how to do it?
If I understand correctly, this is your system flow:
POST some data from your Android device
It gets received by API Gateway
And continues through to AWS Lambda
In AWS Lambda the data is extracted, and passed to Sage Maker
Creating a POST using AWS Amplify
To POST data form the Android device, follow the Amplify API (REST) category documentation.
Specifically, you can do something like:
val options = RestOptions.builder()
.addPath("/prod/predictbreastcancer")
.addBody("{\"data\":\"13.49,22.3,86.91,561.0,0.08752,0.07697999999999999,0.047510000000000004,0.033839999999999995,0.1809,0.057179999999999995,0.2338,1.3530000000000002,1.735,20.2,0.004455,0.013819999999999999,0.02095,0.01184,0.01641,0.001956,15.15,31.82,99.0,698.8,0.1162,0.1711,0.2282,0.1282,0.2871,0.06917000000000001\"}".toByteArray())
.build()
Amplify.API.post(options,
{ Log.i("Demo", "POST response = $it") },
{ Log.e("Demo", "POST failed", it) }
)
Creating POST body from EditText content
You mentioned you're using an EditText widget to gather the input data. I assume a user can enter a comma-separated list of values like 0.44, 6.11, etc.
To extract it's content and build the POST body, you can do:
val input = findViewById(R.id.input) as EditText
val body = JSONObject()
.put("data", input.text)
.toString()
.replaceAll("\"", "\\\"")
Displaying response in another Activity
Skimming the blog you referenced, I can't see an example of the response body content. But, here's how you can retrieve response JSON and pass it to a new activity.
Amplify.API.post(options,
{ response ->
val intent = Intent(this, YourOtherActivity::class.java)
intent.putExtra("json", response.data.asString())
runOnUiThread { startActivity(intent) }
},
{ /* handle error ... */ }
)
In YourOtherActivity, access the extra data in onCreate() like so:
val json = intent.getStringExtra("json")

OTP Verification unknown keyword error in Twilio with Rails

want to send android app hash along with the otp with the help of twillio but not getting proper tutorails in rails. i tried in this way
require 'twilio-ruby'
#client = Twilio::REST::Client.new("XXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXX")
verification = #client.verify.services('VXXXXXXXXXXXXXXXXX').verifications.create(app_hash: "HXXXXXXX", to: '+91XXXXXXXXX', channel: 'sms')
But getting againg and again error
unknown keyword: app_hash
I followed this tutorial https://www.twilio.com/docs/verify/api/verification
Your app's hash string is the first 11 characters of the base64-encoded hash.
Try to pass 11 characters: Ex: 'He42w354ol9'.
verification = #client.verify
.services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.verifications
.create(to: '+15017122661', channel:'sms', app_hash:'He42w354ol9')
Source: https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string
The Twilio Ruby API excerpt goes like:
#client = Twilio::REST::Client.new(account_sid, auth_token)
verification = #client.verify
.services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.verifications
.create(to: '+15017122661', channel: 'sms')
I don't see any app_hash parameter, where did you get that from? Try removing it and see what's going on.

Python gcm and Django : response is always empty

I am using python gcm for Django.response=json.dumps(gcm.json_request(registration_ids=reg_ids,data=data)).response is always NULL. But message is sent
Their documentation suggested:
response=json.dumps(gcm.json_request(registration_ids=reg_ids,data=data))
Well! Message is received to mobile successfully. But the problem is response value is always empty.
My code:
def sendNotification(request):
gcm = GCM('AIzXXXXXXXXXXXXXXXXXXX')
reg_ids=[]
devices=Devices.objects.all()
for device in devices:
reg_ids.append(device.gcm_reg_id)
data = {'sender': "someone",'message':"Cool!",}
response=json.dumps(gcm.json_request(registration_ids=reg_ids,data=data))
return HttpResponse(response)

Can I open my email thread in Gmail App If I have id or threadId?

I am using gmail APIs in my android app and I am able to get id and threadId.So is there any way I can populate gmail using these ids.
Once you have the messageId representing the message you want, you can simply use the Users.messages: get-operation to get the email. You could either do the request manually
GET https://www.googleapis.com/gmail/v1/users/me/messages/<MESSAGE_ID>
or with the help of a library:
Message message = service.users().messages().get('me', messageId).execute();
If you want to get all the mails in the thread, it is just as easy to do that also.
Look at code examples and explore the API in the links I provided.
You can get the raw message in following way This is in python but in Java it would be similar. I hope I answered what you are looking for.
def GetMimeMessage(service, user_id, msg_id):
"""Get a Message and use it to create a MIME Message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
msg_id: The ID of the Message required.
Returns:
A MIME Message, consisting of data from Message. """
try:
message = service.users().messages().get(userId=user_id, id=msg_id, format = 'raw').execute()
print 'Message snippet: %s' % message['snippet']
print 'keys ', message.keys()
msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
mime_msg = email.message_from_string(msg_str)
return mime_msg
except errors.HttpError, error:
print 'An error occurred: %s' % error
for i in range(0,len(th['messages'])):
print 'snippent --- ', th['messages'][i]['snippet']
id = th['messages'][i]['id']
print 'id---', id
msg = GetMimeMessage(service, 'me', id )
pay = msg.get_payload()
pay1 = pay[0]
print 'msg --- ', pay1.get_payload()

Categories

Resources