How to successfully receive Google Drive v3 Push Notifications using python? - python

I have completed the steps provided by Google to implement push notifications using the Drive API. Everything goes as described except I do not receive any notifications from Google whenever a change occurs (listed as Step 4 below).
Below is a summary of the steps I followed and the results at each stage:
Step 1 (Success): Verify that you own the domain
I went to Search Console as directed and successfully verified the site.
Step 2 (Success): Register your domain
I visited the Domain Verification page and added my domain in the API Console. Google API Console updated to show the list with my desired domain.
I have a valid SSL certificate from GoDaddy for my domain and have verified that as well.
Step 3 (Success): Created my notification channel
Using the python SDK, I created the channel and got back a response from Google. The python code below shows how I did this. Note: The address included in my request directs Google to send notifications to my Flask website that I am hosting in Google's App Engine. I am showing the domain as my_domain.com here for privacy as I am in the process of bringing up the site.
channel_id = str(uuid.uuid4())
body = {
'kind': 'api#channel',
'id': channel_id,
'type': 'web_hook',
'address': "https://my_domain.com/notifications"
}
try:
start_page_token = service.changes().getStartPageToken().execute().get('startPageToken');
print(service.changes().watch(pageToken=start_page_token, body=body).execute())
except Exception as e:
print('Exception: {}'.format(e))
And here is the response from Google:
{u'resourceId': u'vTMwJWl7a23Af1LK1TpJZ38eO_0', u'kind': u'api#channel', u'expiration': u'1538433975000', u'id': u'dce14225-95c8-42a7-9945-4fed1604c848', u'resourceUri': u'https://www.googleapis.com/drive/v3/changes?alt=json&includeCorpusRemovals=false&includeRemoved=true&includeTeamDriveItems=false&pageSize=100&pageToken=4919&restrictToMyDrive=false&spaces=drive&supportsTeamDrives=false&alt=json'}
Step 4 (Failed): Process a notification from Google
I am running a Flask website on App Engine and created an app.route to receive notifications from Google. I've included the code below. I never receive anything at this URL.
#app.route('/notifications')
def notifications():
print('in notifications()')
try:
chan_id = request.args.get('X-Goog-Channel-ID', 'empty')
msg_num = request.args.get('X-Goog-Message-Number', 'empty')
rid = request.args.get('X-Goog-Resource-ID', 'empty')
state = request.args.get('X-Goog-Resource-State', 'empty')
resource_uri = request.args.get('X-Goog-Resource-URI', 'empty')
goog_changed = request.args.get('X-Goog-Changed', 'empty')
goog_chan_exp = request.args.get('X-Goog-Channel-Expiration', 'empty')
goog_chan_token = request.args.get('X-Goog-Channel-Token', 'empty')
print('chan_id: {}'.format(chan_id))
print('msg_num: {}'.format(msg_num))
print('rid: {}'.format(rid))
print('state: {}'.format(state))
print('resource_uri: {}'.format(resource_uri))
print('goog_changed: {}'.format(goog_changed))
print('goog_chan_exp: {}'.format(goog_chan_exp))
print('goog_chan_token: {}'.format(goog_chan_token))
except Exception as e:
print('notifications() exception: {}'.format(e))
print('leaving notifications()')
return jsonify(result='done')

I'm not sure if this is the problem but, when I tried Google Drive push notifications, I didn't use the SDK. I only made a POST request as it shows in the documentation.
Could you try to make a POST request to "https://www.googleapis.com/drive/v3/changes/watch" instead of using service.changes().watch()?
You will need an access_token for the request, but I believe you wont need to send a startPageToken as they don't use it in their example:
I hope it helps!

Related

Instagram APINotAllowed Error

I'm learning APIs and was testing with Instagram's API.
Currently, I have an client in sandbox mode and an access token with public_content scope. I created another instagram account that is set to private profile. This new account is a sandbox user for the client.
This is my code.
import requests
import json
parameters = {'ACCESS_TOKEN':'4831128049.31d6072.13cfcadf494344cba7d7f47f18f8ba97'} #modified fake access for question sake
response = requests.get('https://api.instagram.com/v1/{i-put-the-user-id-here}/self/media/recent?access_token='+parameters['ACCESS_TOKEN'])
json_data = response.json()
print(response.status_code)
print(json_data)
But I keep getting this.
{
'meta':{
'code':400,
'error_type':'APINotAllowedError',
'error_message':'you cannot view this resource'
}
}
Edit 1: But this works if the user is the owner of the access token, that is it works perfectly for my own account but not for other private profiles that is also a sandbox account.
Am I doing something wrong?
If this is not possible, then how are there other 3rd party apps doing it? like Flume for Mac?
You cannot get private user via API even if you are following that user, this behavior changed last year with API policy. APINotAllowedError is expected response when trying to access a private user.

CMIS PermissionDeniedException

I'm trying to get service(SAP mobile document) via CMIS.
In service web client i can create folder and add file.
Via CMIS I can auth and get repo's list, but that's all.
For other methods I get cmislib.exceptions.PermissionDeniedException: Error 403
I used this doca http://chemistry.apache.org/python/docs/
from cmislib import *
client = CmisClient('https://service/mcm/b/atom', 'user', 'pwd')
print client.getRepositories()
#REPO
#repo = client.defaultRepository
repo = client.getRepository('573f7fc4-2c76-49a2-b63c-d39e370edfde')
print repo.name
#FOLDER
rFolder = repo.rootFolder
print rFolder.id
#denied
#rFolder.getChildren()
#acl = rFolder.getACL()
#print rFolder.getName()
#newFolder = rFolder.createFolder('testfolder')
denied returns
cmislib.exceptions.PermissionDeniedException: Error 403 at https://url/mcm/b/atom/573f7fc4-2c76-49a2-b63c-d39e370edfde/id?id=906f3ae3-a4c9-3210-7292-c840e0cff769&filter=&includeAllowableActions=false&includeACL=false&includePolicyIds=false&includeRelationships=&renditionFilter=
*the same error for default repo
#repo = client.defaultRepository
SAP Mobile Documents requires cookies. Turn cookies on on the client side and those exceptions will disappear.
See http://help.sap.com/saphelp_mdocs10/helpdata/en/0e/432781e0c646a09602a4aab786734d/content.htm?frameset=/en/d5/476115e8264a33a52fd59d260892cb/frameset.htm&current_toc=/en/69/ec44f07b34409a8b65005f51315f1a/plain.htm&node_id=105 how to the authentication works.

how can i update an alfresco share site?

I am trying to update a website (just change its name) I have created with the Share script in Alfresco, but I am getting a 401 response. I'm sure my login and password are correct.
Code:
s = requests.Session()
data = {'username':"admin", 'password':"admin"}
url = "http://127.0.0.1:8080/share/page/dologin"
r = s.post(url, data=data)
if (r.status_code != 200) :
print "Incorrect login or password "
url1 = "http://127.0.0.1:8080/alfresco/service/api/sites/OdooSite50"
print url_alfresco
jsonString = JSONEncoder().encode({
"title" : name
})
headers = {'content-type': 'application/json',"Accept":"application/json"}
site = s.put(url1,headers=headers,data=data)
if (site.status_code != 200) :
print " Error while creating site"
print site.status_code
I am getting the error on the second part. The login part works without any problems.
Can you tell me what I do wrong?
This is because you are using different contexts to make your queries.
The Alfresco stack is made of multiples parts :
alfresco.war
share.war
solr.war
If we forget the solr part and focus on your problem, you have :
a content repository (alfresco) which contains the core services of alfresco
a web application (share) which contains the web ui of your application and communicate the content repository to do some actions
They don't share the same context and have different lives. One can be on a server, the other one can be in another one server.
So this mean, when you are authenticating, you are doing it on the share context :
http://127.0.0.1:8080/share/page/dologin
and when you are trying to update your website, you are doing it on the alfresco context (on which you are not authenticated yet) :
http://127.0.0.1:8080/alfresco/service/api/sites/OdooSite50
I see two solutions then :
You do your authentication on the alfresco context (webservice alfresco/s/api/login) and then you will be authenticated for calling your alfresco site services
You pass through the share proxy : /alfresco/service/api/sites becomes /share/proxy/alfresco/api/sites

Im using python (django framework) to gain a request token from google api, but the request token always comes back empty

Here is sample code that I'm working with.
def index(request):
flow = OAuth2WebServerFlow(
client_id='xyz.apps.googleusercontent.com',
client_secret='xyz',
scope='https://www.googleapis.com/auth/plus.me',
user_agent='sample/1.0')
callback = 'http://%s/oauth2callback' % request.META[ 'HTTP_HOST' ]
authorize_url = flow.step1_get_authorize_url(callback)
return HttpResponse(flow)
For some reason 'flow' is always set to " " or empty instead of a request token. I have searched for days on this issue.
Can anyone tell me why I can't get a request token from google using this method?
fyi: I know that I should be redirecting the user to the authorize url, but I want to see if flow is set before I do since Google will provide the authorize url even if a request token wasn't returned.
Before you can use OAuth 2.0, you must register your application using
the Google APIs Console. After you've registered, go to the API Access
tab and copy the "Client ID" and "Client secret" values, which you'll
need later.
http://code.google.com/p/google-api-python-client/wiki/OAuth2#Registering
If this answer actually helps with your problem then I must bid an R.I.P. to S.O.

Update status Facebook using Python

I'm trying the solve problem update status using facebook API with pyfacebook. So I look at here Update Facebook Page's status using pyfacebook and I think doesn't work anymore.
Well, finally I solve the problem:
#!/usr/bin/python
import facebook
# Replace these with your app's credentials
api_key = 'YOUR_API_KEY'
secret_key = 'YOUR_SECRET_KEY'
client = facebook.Facebook(api_key, secret_key)
client.auth.createToken()
client.login()
print '[*] Please login / give permission application to access you . Then press enter key to continue...',
raw_input()
try:
client.auth.getSession()
client.request_extended_permission("publish_stream", popup=False)
raw_input()
cek = client.status.set("Testing update status using facebook API with pyfacebook")
except facebook.FacebookError, e:
print "ERROR", e

Categories