def index(request): '''I Have created a static user as I dont have any logged in user in my app right now''' U = User( username = '******', firstname= 'Bla Bla', lastname= 'Bla Bla', email = '*****@*****.**' ) U.save() #This is a class created by google to save the credentials automatically in the database storage = Storage(CredentialsModel, 'id', U, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, U) authorize_url = FLOW.step1_get_authorize_url() print(authorize_url) return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('drive', 'v3', http=http) #GOOGLE DRIVE FUNCTION CALLS id = creatingNewFolder(service) id1 = creatingFolderInsideAFolder(service, id) print("Successful") return HttpResponse("Folder Id: "+id+" Subfolder Id: "+id1)
def events_get(request): REDIRECT_URI = "https://%s%s" % (request.get_host(), reverse("scheduler:events_return")) # FLOW = flow_from_clientsecrets( # CLIENT_SECRETS, # scope=SCOPES, # redirect_uri=REDIRECT_URI # ) FLOW = OAuth2WebServerFlow( client_id= '323423619559-orlpuuiaalb7sp3ooblt4mjmp32ffq1t.apps.googleusercontent.com', client_secret=os.environ['CLIENT_SECRET'], scope=SCOPES, redirect_uri=REDIRECT_URI) user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential is None or credential.invalid is True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=user, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('calendar', 'v3', http=http) events = service.events().list(calendarId='primary').execute() return Response(events)
def run_subs(ffu): storage = Storage(CredentialsModel, 'id', ffu.credentials, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise Exception("invalid credentials") http = httplib2.Http() http = credential.authorize(http) service = discovery.build('gmail', 'v1', http) output = ListRecentMessagesMatchingQuery(service, "me", '"has subscribed to you"') added = 0 for item in output: if SubEvent.objects.filter(external_id=item['id'], updater=ffu).count(): break message = GetMessage(service, "me", item['id']) headers = message['payload']['headers'] f, s, d = '', '', '' for header in headers: if header['name'] == "From": f = header['value'] if header['name'] == "Subject": s = header['value'] if header['name'] == "Date": d = header['value'] if '*****@*****.**' in f: s = s.strip().replace(" has subscribed to you on YouTube!", "") try: e = SubEvent(external_id=item['id'], details = s, updater=ffu) e.save() added += 1 except Exception, E: print "Failed to create specific subevent for %s: \n %s: %s" % (ffu.id, type(E), E)
def events_get(request): REDIRECT_URI = "https://%s%s" % ( request.get_host(), reverse("scheduler:events_return")) # FLOW = flow_from_clientsecrets( # CLIENT_SECRETS, # scope=SCOPES, # redirect_uri=REDIRECT_URI # ) FLOW = OAuth2WebServerFlow( client_id='323423619559-orlpuuiaalb7sp3ooblt4mjmp32ffq1t.apps.googleusercontent.com', client_secret=os.environ['CLIENT_SECRET'], scope=SCOPES, redirect_uri=REDIRECT_URI ) user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential is None or credential.invalid is True: FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=user, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('calendar', 'v3', http=http) events = service.events().list(calendarId='primary').execute() return Response(events)
def run_fan_funding(ffu): added = 0 storage = Storage(CredentialsModel, 'id', ffu.credentials, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise Exception("bad creds") return added http = httplib2.Http() http = credential.authorize(http) resp, data = http.request("%sfanFundingEvents?part=snippet&maxResults=5" % BASE_URL) data = json.loads(data) events = [] if 'items' in data: for i in data['items']: if FanFundingEvent.objects.filter(external_id=i['id'], updater=ffu).count() > 0: break details = json.dumps(i) try: ffe = FanFundingEvent(external_id=i['id'], updater=ffu, details=details) ffe.save() except Exception, E: print "Failed in individual fan funding run: %s\nData:\n%s" % ( E, details) added += 1
def auth(request): # use the first REDIRECT_URI if you are developing your app locally, and the second in production #REDIRECT_URI = 'http://localhost:8000/gmail_setup/callback' REDIRECT_URI = "http://%s%s" % (BASE_URL, reverse("oauth2:return")) #REDIRECT_URI = 'https://' + BASE_URL + '/gmail_setup/callback' print "ACCESSING CLIENT SECRETS" with open(CLIENT_SECRETS) as json_data: d = json.load(json_data) print "DATA:", d FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.settings.basic https://www.googleapis.com/auth/gmail.modify', redirect_uri=REDIRECT_URI ) FLOW.params['access_type'] = 'offline' user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if not credential or credential.invalid: if 'group' in request.GET: group_name = request.GET['group'] FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) + '___' + group_name authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=user, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: return HttpResponseRedirect("/gmail_setup") else: return HttpResponseRedirect("/gmail_setup")
def run_fan_funding(ffu): added = 0 storage = Storage(CredentialsModel, 'id', ffu.credentials, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise Exception("bad creds") return added http = httplib2.Http() http = credential.authorize(http) resp, data = http.request("%sfanFundingEvents?part=snippet&maxResults=5" % BASE_URL) data = json.loads(data) if 'error' in data: raise Exception("Error fetching fanfunding: %s" % json.dumps(data['error'])) events = [] if 'items' in data: for i in data['items']: if FanFundingEvent.objects.filter(external_id=i['id'], updater=ffu).count() > 0: break details = json.dumps(i) try: ffe = FanFundingEvent(external_id=i['id'], updater=ffu, details=details) ffe.save() except Exception, E: print "Failed in individual fan funding run: %s\nData:\n%s" % (E, details) added += 1
def run_subs(ffu): storage = Storage(CredentialsModel, 'id', ffu.credentials, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise Exception("invalid credentials") http = httplib2.Http() http = credential.authorize(http) service = discovery.build('gmail', 'v1', http) output = ListRecentMessagesMatchingQuery(service, "me", '"has subscribed to you"') added = 0 for item in output: if SubEvent.objects.filter(external_id=item['id'], updater=ffu).count(): break message = GetMessage(service, "me", item['id']) headers = message['payload']['headers'] f, s, d = '', '', '' for header in headers: if header['name'] == "From": f = header['value'] if header['name'] == "Subject": s = header['value'] if header['name'] == "Date": d = header['value'] if '*****@*****.**' in f: s = s.strip().replace(" has subscribed to you on YouTube!", "") try: e = SubEvent(external_id=item['id'], details=s, updater=ffu) e.save() added += 1 except Exception, E: print "Failed to create specific subevent for %s: \n %s: %s" % ( ffu.id, type(E), E)
def run_youtubesubs(ffu): added = 0 storage = Storage(CredentialsModel, 'id', ffu.credentials, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise Exception("bad creds") return added http = httplib2.Http() http = credential.authorize(http) resp, data = http.request("%ssubscriptions?part=subscriberSnippet&myRecentSubscribers=true&maxResults=25" % BASE_URL) data = json.loads(data) if 'error' in data: raise Exception("Error fetching youtubesubs: %s" % json.dumps(data['error'])) events = [] if 'items' in data: for i in data['items']: unique_id = i['subscriberSnippet']['channelId'] if YoutubeSubEvent.objects.filter(external_id=i['id'], updater=ffu).count() > 0: break details = json.dumps(i) try: ffe = YoutubeSubEvent(external_id=i['id'], updater=ffu, details=details) events.append(ffe) except Exception, E: print "Failed in individual youtubesubs run: %s\nData:\n%s" % (E, details) added += 1 for event in reversed(events): try: event.save() added += 1 except Exception, E: print "Failed in individual sponsor run: %s\nData:\n%s" % (E, ffe.details)
def get_credentials(gmail_account): """ Get the credentials for the given EmailAccount, what should be a Gmail account. If there are no valid credentials for the account, is_authorized is set to False and there will be an InvalidCredentialsError raised. Arguments: gmail_account (instance): EmailAccount instance Returns: credentials for the EmailAccount Raises: InvalidCredentialsError, if there are no valid credentials for the account. """ storage = Storage(GmailCredentialsModel, 'id', gmail_account, 'credentials') credentials = storage.get() if credentials is not None and credentials.invalid is False: return credentials else: gmail_account.is_authorized = False gmail_account.save() logger.error('No or invalid credentials for account %s' % gmail_account) raise InvalidCredentialsError('No or invalid credentials for account %s' % gmail_account)
def index(request): '''I Have created a static user as I dont have any logged in user in my app right now''' U = User( username = '******', firstname= 'Bla Bla', lastname= 'Bla Bla', email = '*****@*****.**' ) U.save() #This is a class created by google to save the credentials automatically in the database storage = Storage(CredentialsModel, 'id', U, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, U) authorize_url = FLOW.step1_get_authorize_url() print(authorize_url) return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('drive', 'v3', http=http) #GOOGLE DRIVE FUNCTION CALLS id = getFolderID(service) #id1 = creatingFolderInsideAFolder(service, id) print("Successful") return id
def test_storage(self): storage = Storage(CredentialsModel, 'user', self.user_with_analytics, 'credential') credential = storage.get() self.assertIsInstance(storage, Storage) self.assertIsInstance(credential, OAuth2Credentials) self.assertEqual(credential.access_token, self.credential.access_token)
def get_google_contacts_service(self, user): if self.contact_service is None: storage = Storage(CredentialsModel, 'id', user, 'credential') auth_token = OAuth2TokenFromCredentials(storage.get()) self.contact_service = gdata.contacts.client.ContactsClient() auth_token.authorize(self.contact_service) return self.contact_service
def index(request): '''I Have created a static user as I dont have any logged in user in my app right now''' U = User(username='******', firstname='Bla Bla', lastname='Bla Bla', email='*****@*****.**') U.save() #This is a class created by google to save the credentials automatically in the database storage = Storage(CredentialsModel, 'id', U, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, U) authorize_url = FLOW.step1_get_authorize_url() print(authorize_url) return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('calendar', 'v3', http=http) listEvents(service) '''Just For Testing''' event = { 'summary': 'Google I/O 2015', 'location': '800 Howard St., San Francisco, CA 94103', 'description': 'A chance to hear more about Google\'s developer products.', 'start': { 'dateTime': '2016-04-07T09:00:00-07:00', 'timeZone': 'America/Los_Angeles', }, 'end': { 'dateTime': '2016-04-08T17:00:00-07:00', 'timeZone': 'America/Los_Angeles', }, 'recurrence': ['RRULE:FREQ=DAILY'], 'attendees': [{ 'email': '*****@*****.**' }], 'reminders': { 'useDefault': False, 'overrides': [ { 'method': 'email', 'minutes': 24 * 60 }, { 'method': 'popup', 'minutes': 10 }, ], }, } link = addEvent(service, event) print("Successful") return HttpResponse(link)
def index(request): '''I Have created a static user as I dont have any logged in user in my app right now''' U = User( username = '******', firstname= 'Bla Bla', lastname= 'Bla Bla', email = '*****@*****.**' ) U.save() #This is a class created by google to save the credentials automatically in the database storage = Storage(CredentialsModel, 'id', U, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, U) authorize_url = FLOW.step1_get_authorize_url() print(authorize_url) return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("gmail", "v1", http=http) '''results = service.users().labels().list(userId='me').execute() labels = results.get('labels', [])''' #GMAIL CHECK '''if not labels: print('No labels found.') else: print('Labels:') for label in labels: print(label['name']) ''''activities = service.activities()''' #GOOGLE PLUS CHECK '''activitylist = activities.list(collection='public', userId='me').execute() logging.info(activitylist)''' '''return render(request, 'plus/welcome.html', { 'activitylist': activitylist, })''' #print("1") #message_text = request.GET.get("message_text","i am default") message_text = request.GET['message_text'] sender = "" to = request.GET['to'] subject = request.GET['subject'] #print("2") #print(request.POST['message_text']+" "+request.POST.get['message_text']) message = CreateMessage(sender, to, subject, message_text,service) message = SendMessage(service,"me",message) print(message) print("Successful") return HttpResponse("Mail Sent Successfully <script type='text/javascript'> function Redirect() { window.location.href='http://localhost/OnCourse/student/communique/mailbox.html'; } document.write('You will be redirected to a new page in 5 seconds'); setTimeout('Redirect()', 5000); </script> ")
def update_gmail_filter(user, group_name, whitelist_emails, filter_hash): storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() http = httplib2.Http() http = credential.authorize(http) service_mail = build('gmail', 'v1', http=http) forward_address = '%s@%s' % (group_name, BASE_URL) return True
def index(request): '''I Have created a static user as I dont have any logged in user in my app right now''' U = User( username = '******', firstname= 'Bla Bla', lastname= 'Bla Bla', email = '*****@*****.**' ) U.save() #This is a class created by google to save the credentials automatically in the database storage = Storage(CredentialsModel, 'id', U, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, U) authorize_url = FLOW.step1_get_authorize_url() print(authorize_url) return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('calendar', 'v3', http=http) listEvents(service) '''Just For Testing''' event = { 'summary': 'Google I/O 2015', 'location': '800 Howard St., San Francisco, CA 94103', 'description': 'A chance to hear more about Google\'s developer products.', 'start': { 'dateTime': '2016-04-07T09:00:00-07:00', 'timeZone': 'America/Los_Angeles', }, 'end': { 'dateTime': '2016-04-08T17:00:00-07:00', 'timeZone': 'America/Los_Angeles', }, 'recurrence': [ 'RRULE:FREQ=DAILY' ], 'attendees': [ {'email': '*****@*****.**'} ], 'reminders': { 'useDefault': False, 'overrides': [ {'method': 'email', 'minutes': 24 * 60}, {'method': 'popup', 'minutes': 10}, ], }, } link = addEvent(service,event) print("Successful") return HttpResponse(link)
def build_services(user): storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential and not credential.invalid: http = httplib2.Http() http = credential.authorize(http) credential.refresh(http) service_people = build('people', 'v1', http=http) service_mail = build('gmail', 'v1', http=http) return {'mail' : service_mail, 'people' : service_people}
def _get_google_credential(request): token = None if request.user.is_authenticated(): storage = Storage(TokenStorageModel, 'id', request.user, 'credential') credential = storage.get() elif request.session.get('access_token'): credential = google_client.OAuth2Credentials.from_json(token) return credential or HttpResponseRedirect( google_flow.step1_get_authorize_url())
def load_sponsor_data(updater): storage = Storage(CredentialsModel, 'id', updater.credentials, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise Exception("bad creds") http = httplib2.Http() http = credential.authorize(http) resp, data = http.request("%ssponsors?part=snippet&maxResults=5&filter=all" % BASE_URL) data = json.loads(data) if 'error' in data: raise Exception("Error fetching sponsors: %s" % json.dumps(data['error'])) return data
def ytapicall(appcreds, url): storage = Storage(CredentialsModel, 'id', appcreds, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise Exception("bad creds") http = httplib2.Http() http = credential.authorize(http) resp, data = http.request(url) data = json.loads(data) if 'error' in data: raise Exception("YouTube API Error: %s" % data['error']) return data
def import_gsheet(request, id): gsheet_endpoint = None silo = None read_url = request.GET.get('link', None) file_id = request.GET.get('resource_id', None) file_name = request.GET.get("name", "Google Sheet Import") if read_url == None or file_id == None: messages.error(request, "A Google Spreadsheet is not selected to import data from.") return HttpResponseRedirect(reverse('index')) storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() #FLOW.params.update({'redirect_uri_after_step2': "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id)}) request.session['redirect_uri_after_step2'] = "/import_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id) return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) user = User.objects.get(username__exact=request.user) gsheet_endpoint = None read_type = ReadType.objects.get(read_type="GSheet Import") try: silo = Silo.objects.get(id=id) if silo.unique_fields.exists() == False: messages.error(request, "A unique column must be specfied when importing to an existing table. <a href='%s'>Specify Unique Column</a>" % reverse_lazy('siloDetail', kwargs={"id": silo.id})) return HttpResponseRedirect(request.META['HTTP_REFERER']) except Silo.DoesNotExist: silo = Silo(name=file_name, owner=request.user, public=False, description="Google Sheet Import") silo.save() try: gsheet_endpoint = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, resource_id=file_id, read_name='GSheet Import') except Read.MultipleObjectsReturned: messages.error(request, "There should not be multiple records for the same gsheet, silo, and owner") except Read.DoesNotExist: gsheet_endpoint = Read(read_name="GSheet Import", type=read_type, resource_id=file_id, owner=user) gsheet_endpoint.read_url = read_url gsheet_endpoint.save() silo.reads.add(gsheet_endpoint) silo.save() except Exception as e: messages.error(request, "An error occured: %" % e.message) #print("about to export to gsheet: %s" % gsheet_endpoint.resource_id) if import_from_google_spreadsheet(credential_json, silo, gsheet_endpoint.resource_id) == True: link = "Your imported data is available at here. <a href='%s'>See the table</a>" % reverse_lazy('siloDetail', kwargs={"id": silo.id}) messages.success(request, link) else: messages.error(request, 'Something went wrong.') #messages.success(request, "Now, it should import data from GSheet") return HttpResponseRedirect(reverse('index'))
def _get_calendar_service(self, user): if self.calendar_service: self.calendar_service else: storage = Storage(CredentialsModel, 'id', user, 'credential') credentials = storage.get() http = credentials.authorize(httplib2.Http()) self.calendar_service = discovery.build('calendar', 'v3', http=http) return self.calendar_service
def import_gsheet(request, id): gsheet_endpoint = None silo = None read_url = request.GET.get('link', None) file_id = request.GET.get('resource_id', None) file_name = request.GET.get("name", "Google Sheet Import") if read_url == None or file_id == None: messages.error(request, "A Google Spreadsheet is not selected to import data from.") return HttpResponseRedirect(reverse('index')) storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() #FLOW.params.update({'redirect_uri_after_step2': "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id)}) request.session['redirect_uri_after_step2'] = "/import_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id) return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) user = User.objects.get(username__exact=request.user) gsheet_endpoint = None read_type = ReadType.objects.get(read_type="GSheet Import") try: silo = Silo.objects.get(id=id) if silo.unique_fields.exists() == False: messages.error(request, "A unique column must be specfied when importing to an existing table. <a href='%s'>Specify Unique Column</a>" % reverse_lazy('silo_detail', kwargs={"id": silo.id})) return HttpResponseRedirect(request.META['HTTP_REFERER']) except Silo.DoesNotExist: silo = Silo(name=file_name, owner=request.user, public=False, description="Google Sheet Import") silo.save() try: gsheet_endpoint = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, resource_id=file_id, read_name='GSheet Import') except Read.MultipleObjectsReturned: messages.error(request, "There should not be multiple records for the same gsheet, silo, and owner") except Read.DoesNotExist: gsheet_endpoint = Read(read_name="GSheet Import", type=read_type, resource_id=file_id, owner=user) gsheet_endpoint.read_url = read_url gsheet_endpoint.save() silo.reads.add(gsheet_endpoint) silo.save() except Exception as e: messages.error(request, "An error occured: %" % e.message) #print("about to export to gsheet: %s" % gsheet_endpoint.resource_id) if import_from_google_spreadsheet(credential_json, silo, gsheet_endpoint.resource_id) == True: link = "Your imported data is available at here. <a href='%s'>See the table</a>" % reverse_lazy('silo_detail', kwargs={"id": silo.id}) messages.success(request, link) else: messages.error(request, 'Something went wrong.') #messages.success(request, "Now, it should import data from GSheet") return HttpResponseRedirect(reverse('index'))
def get_credential_object(user, prompt=None): storage = Storage(GoogleCredentialsModel, 'id', user, 'credential') credential_obj = storage.get() if credential_obj is None or credential_obj.invalid == True or prompt: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) FLOW.params['access_type'] = 'offline' FLOW.params['approval_prompt'] = 'force' authorize_url = FLOW.step1_get_authorize_url() return {"level": messages.ERROR, "msg": "Requires Google Authorization Setup", "redirect": authorize_url, "redirect_uri_after_step2": True} #print(json.loads(credential_obj.to_json())) return credential_obj
def check_google_authenticated(request): storage = Storage(CredentialsModel, 'id', request.user, 'credential') credentials = storage.get() if credentials is None or credentials.invalid is True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) FLOW.params['access_type'] = 'offline' authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: return HttpResponseRedirect('/main')
def export_gsheet(request, id): gsheet_endpoint = None read_url = request.GET.get('link', None) file_id = request.GET.get('resource_id', None) if read_url == None or file_id == None: messages.error(request, "A Google Spreadsheet is not selected to import data to it.") return HttpResponseRedirect(reverse('listSilos')) storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() #FLOW.params.update({'redirect_uri_after_step2': "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id)}) request.session['redirect_uri_after_step2'] = "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id) return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) user = User.objects.get(username__exact=request.user) gsheet_endpoint = None read_type = ReadType.objects.get(read_type="Google Spreadsheet") try: gsheet_endpoint = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, read_name='Google') except Read.MultipleObjectsReturned: gsheet_endpoints = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, read_name='Google') for endpoint in gsheet_endpoints: if endpoint.resource_id: gsheet_endpoint = endpoint except Read.DoesNotExist: gsheet_endpoint = Read(read_name="Google", type=read_type, owner=user) gsheet_endpoint.save() silo = Silo.objects.get(id=id) silo.reads.add(gsheet_endpoint) silo.save() except Exception as e: messages.error(request, "An error occured: %" % e.message) if gsheet_endpoint.resource_id == "None" or gsheet_endpoint.resource_id == None: gsheet_endpoint.resource_id = file_id gsheet_endpoint.read_url = read_url gsheet_endpoint.save() #print("about to export to gsheet: %s" % gsheet_endpoint.resource_id) if export_to_google_spreadsheet(credential_json, id, gsheet_endpoint.resource_id) == True: link = "Your exported data is available at <a href=" + gsheet_endpoint.read_url + " target='_blank'>Google Spreadsheet</a>" messages.success(request, link) else: messages.error(request, 'Something went wrong.') return HttpResponseRedirect(reverse('listSilos'))
def sync_gcalendar(request): gcalservice = GoogleService() if request.GET.get("appointment_id"): if request.GET.get("refferrer"): request.session["refferrer"] = request.GET.get("refferrer") customer_factory = CustomerServicesFactory() dealer_factory = DealerShipServicesFactory() dealer_service = dealer_factory.get_instance("dealership") # dealer = dealer_service.get_dealer_by(dealer_code) uservice = customer_factory.get_instance("user") #CUserService() appt_service = dealer_factory.get_instance( "appointment") #AppointmentService() appointment = appt_service.get_appointment( request.GET.get("appointment_id")) #,dealer) # REDIRECT_URI = 'http://127.0.0.1:8000/customer/oauth2callback/'#?appointment_id='+request.GET.get("appointment_id") request.session["oauth_appointment"] = request.GET.get( "appointment_id") #REDIRECT_URI = "https://%s%s" % ( # get_current_site(request).domain, reverse("customer:return")) REDIRECT_URI = settings.SITE_MAIN_URL + reverse("customer:return") CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), gcalservice.CLIENT_SECRET_FILE) FLOW = flow_from_clientsecrets(CLIENT_SECRETS, scope=gcalservice.SCOPES, redirect_uri=REDIRECT_URI) storage = Storage(CredentialsModel, 'id', appointment, 'credential') credential = storage.get() if credential is None or credential.invalid is True: FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, appointment) authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=appointment, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: resp = gcalservice.create_event(appointment, credential) messages.success( request, "Your appointment has been added to Google Calendars") if request.session.get("refferrer"): refferrer = request.session["refferrer"] del request.session["refferrer"] return HttpResponseRedirect(refferrer) else: return JsonResponse({"success": resp}, safe=False)
def index(request): '''I Have created a static user as I dont have any logged in user in my app right now''' U = User( username = '******', firstname= 'Bla Bla', lastname= 'Bla Bla', email = '*****@*****.**' ) U.save() #This is a class created by google to save the credentials automatically in the database storage = Storage(CredentialsModel, 'id', U, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, U) authorize_url = FLOW.step1_get_authorize_url() print(authorize_url) return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("gmail", "v1", http=http) '''results = service.users().labels().list(userId='me').execute() labels = results.get('labels', [])''' #GMAIL CHECK '''if not labels: print('No labels found.') else: print('Labels:') for label in labels: print(label['name']) ''''activities = service.activities()''' #FUNCTION CALL TO FIRST CREATE MESSAGE AND THEN SEND IT '''message_text = "Hello How are? Khana Khake Jana Hah!!" sender = "" to = "*****@*****.**" subject = "Invitation" message = CreateMessage(sender, to, subject, message_text,service) message = SendMessage(service,"me",message) print(message) print("Successful") return HttpResponse("Successful")''' message = ListMessagesMatchingQuery(service, 'me')
def create_calendar_event(self, user): """Create a calendar event for the expected delivery date """ storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) response = service.calendarList.list().execute() calendar_summaries = [cal['summary'].lower() for cal in response['items']] # Check if user does not already has account payables if 'account payables' not in calendar_summaries: # Get calendar cal_id = '*****@*****.**' calendar = service.calendars().get(calendarId=cal_id).execute() # Add calendar to user's calendarList service.calendarList().insert(body={ 'id': calendar['id'] }).execute() else: # Get calendar is already in calendarList for cal in response['items']: if cal['summary'].lower() == 'account payables': calendar = cal evt = { 'summary': "Purchase Order {0}".format(self.id), 'start': { 'date': '2016-1-6' }, 'end': { 'date': '2016-1-6' }, 'reminders': { 'useDefault': False, 'overrides': [ {'method': 'email', 'minutes': 24 * 60}, {'method': 'email', 'minutes': 10}, ] } } response = service.events().insert(calendarId=ap_cal['id'], body=evt).execute()
def export_gsheet(request, id): gsheet_endpoint = None read_url = request.GET.get('link', None) file_id = request.GET.get('resource_id', None) if read_url == None or file_id == None: messages.error(request, "A Google Spreadsheet is not selected to import data to it.") return HttpResponseRedirect(reverse('list_silos')) storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() #FLOW.params.update({'redirect_uri_after_step2': "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id)}) request.session['redirect_uri_after_step2'] = "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id) return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) user = User.objects.get(username__exact=request.user) gsheet_endpoint = None read_type = ReadType.objects.get(read_type="Google Spreadsheet") try: gsheet_endpoint = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, read_name='Google') except Read.MultipleObjectsReturned: gsheet_endpoints = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, read_name='Google') for endpoint in gsheet_endpoints: if endpoint.resource_id: gsheet_endpoint = endpoint except Read.DoesNotExist: gsheet_endpoint = Read(read_name="Google", type=read_type, owner=user) gsheet_endpoint.save() silo = Silo.objects.get(id=id) silo.reads.add(gsheet_endpoint) silo.save() except Exception as e: messages.error(request, "An error occured: %" % e.message) if gsheet_endpoint.resource_id == "None" or gsheet_endpoint.resource_id == None: gsheet_endpoint.resource_id = file_id gsheet_endpoint.read_url = read_url gsheet_endpoint.save() #print("about to export to gsheet: %s" % gsheet_endpoint.resource_id) if export_to_google_spreadsheet(credential_json, id, gsheet_endpoint.resource_id) == True: link = "Your exported data is available at <a href=" + gsheet_endpoint.read_url + " target='_blank'>Google Spreadsheet</a>" messages.success(request, link) else: messages.error(request, 'Something went wrong.') return HttpResponseRedirect(reverse('list_silos'))
def inner(request, *args, **kwargs): # Try grabbing credential from storage storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() # Begin process of getting a new credential if credential is None or credential.invalid: request.session['next_view'] = request.path request.session['gauth_scope'] = scope return (HttpResponse('Unauthorized', status=401) if ajax else redirect('gauth_index')) # Everything went well, call wrapped view and give credential to it kwargs['credential'] = credential return func(request, *args, **kwargs)
def get_service(user): service = None storage = Storage(CredentialsModel, 'user', user, 'credential') credentials = storage.get() if credentials: authorized_http = credentials.authorize(Http()) credentials.refresh(authorized_http) service = discovery \ .build( 'analytics', 'v3', http=authorized_http, requestBuilder=AddnowHttpRequest, credentials=credentials, cache=cache ) return service
def ytapicall(appcreds, url, post_json=None): storage = Storage(CredentialsModel, 'id', appcreds, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise CredentialsException("bad creds") http = httplib2.Http() http = credential.authorize(http) if post_json: resp, data = http.request(url, "POST", json.dumps(post_json), headers = {'content-type': 'application/json'}) else: resp, data = http.request(url) data = json.loads(data) if 'error' in data: e = YouTubeAPIException("YouTube API Error: %s" % data['error']['message']) e.data = data raise e return data
def get_channel(appcreds, force=False): if force == False and appcreds.channel_id: return appcreds.channel_id storage = Storage(CredentialsModel, 'id', appcreds, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise Exception("bad creds") http = httplib2.Http() http = credential.authorize(http) resp, data = http.request("%schannels?part=id&mine=true" % BASE_URL) data = json.loads(data) if data['pageInfo']['totalResults'] != 1: raise Exception("Bad returned channel list: %s" % data) channel_id = data['items'][0]['id'] appcreds.channel_id = channel_id appcreds.save() return channel_id
def get_credential_object(user, prompt=None): storage = Storage(GoogleCredentialsModel, 'id', user, 'credential') credential_obj = storage.get() if credential_obj is None or credential_obj.invalid == True or prompt: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user) FLOW.params['access_type'] = 'offline' FLOW.params['approval_prompt'] = 'force' authorize_url = FLOW.step1_get_authorize_url() return { "level": messages.ERROR, "msg": "Requires Google Authorization Setup", "redirect": authorize_url, "redirect_uri_after_step2": True } #print(json.loads(credential_obj.to_json())) return credential_obj
def post(self, request): client_id = request.POST.get('client_id') client_secret = request.POST.get('client_secret') errors = {} if not client_id: errors.update({ 'client_id': ['Please enter a valid client ID'], }) if not client_secret: errors.update({ 'client_secret': ['Please enter a valid client secret'], }) if errors: return HttpResponseBadRequest(anyjson.serialize(errors), content_type='application/json') params = { 'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': request.build_absolute_uri(), 'scope': 'read+write', 'response_type': 'code', } details, created = IntegrationDetails.objects.get_or_create(type=IntegrationDetails.PANDADOC) storage = Storage(IntegrationCredentials, 'details', details, 'credentials') credentials = storage.get() if not credentials: credentials = LilyOAuthCredentials( client_id=client_id, client_secret=client_secret, ) storage.put(credentials) auth_url = 'https://app.pandadoc.com/oauth2/authorize?' + urllib.urlencode(params) response = anyjson.serialize({'url': auth_url}) return HttpResponse(response, content_type='application/json')
def export_new_gsheet(request, id): storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() #FLOW.params.update({'redirect_uri_after_step2': "/export_new_gsheet/%s/" % id}) request.session[ 'redirect_uri_after_step2'] = "/export_new_gsheet/%s/" % id return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) silo_id = id silo_name = Silo.objects.get(pk=silo_id).name http = httplib2.Http() # Authorize the http object to be used with "Drive API" service object http = credential.authorize(http) # Build the Google Drive API service object service = build("drive", "v2", http=http) # The body of "insert" API call for creating a blank Google Spreadsheet body = { 'title': silo_name, 'description': "Exported Data from Mercy Corps TolaData", 'mimeType': "application/vnd.google-apps.spreadsheet" } # Create a new blank Google Spreadsheet file in user's Google Drive google_spreadsheet = service.files().insert(body=body).execute() # Get the spreadsheet_key of the newly created Spreadsheet spreadsheet_key = google_spreadsheet['id'] #print(spreadsheet_key) if export_to_google_spreadsheet(credential_json, silo_id, spreadsheet_key) == True: link = "Your exported data is available at <a href=" + google_spreadsheet[ 'alternateLink'] + " target='_blank'>Google Spreadsheet</a>" messages.success(request, link) else: messages.error(request, 'Something went wrong; try again.') return HttpResponseRedirect(reverse('list_silos'))
def get_api_data(): all_data = {} for doctor in Doctor.objects.all(): storage = Storage(CredentialsModel, 'doctor_id', doctor.id, 'credential') credentials = storage.get() http = httplib2.Http() http = credentials.authorize(http) storage.put(credentials) (resp, content) = http.request("https://drchrono.com/api/patients", "GET") data = json.loads(content.decode("utf-8")) all_data[doctor.id] = data return all_data
def index(request): storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("plus", "v1", http=http) activities = service.activities() activitylist = activities.list(collection='public', userId='me').execute() logging.info(activitylist) return render(request, 'plus/welcome.html', { 'activitylist': activitylist, })
def get(self, request): storage = Storage(CredentialsModel, 'user', request.user, 'credential') credential = storage.get() key = analytics_settings.FLOW_CACHE_KEY_PLACEHOLDER % request.user.id logger.debug('Deleting OAuth2 Web server Flow to cache with key: %s', key) cache.delete(key) if credential: http = httplib2.Http() http = credential.authorize(http) try: credential.revoke(http) except TokenRevokeError: pass storage.delete() return Response({}, status=status.HTTP_200_OK)
def export_new_gsheet(request, id): storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() #FLOW.params.update({'redirect_uri_after_step2': "/export_new_gsheet/%s/" % id}) request.session['redirect_uri_after_step2'] = "/export_new_gsheet/%s/" % id return HttpResponseRedirect(authorize_url) credential_json = json.loads(credential.to_json()) silo_id = id silo_name = Silo.objects.get(pk=silo_id).name http = httplib2.Http() # Authorize the http object to be used with "Drive API" service object http = credential.authorize(http) # Build the Google Drive API service object service = build("drive", "v2", http=http) # The body of "insert" API call for creating a blank Google Spreadsheet body = { 'title': silo_name, 'description': "Exported Data from Mercy Corps TolaData", 'mimeType': "application/vnd.google-apps.spreadsheet" } # Create a new blank Google Spreadsheet file in user's Google Drive google_spreadsheet = service.files().insert(body=body).execute() # Get the spreadsheet_key of the newly created Spreadsheet spreadsheet_key = google_spreadsheet['id'] #print(spreadsheet_key) if export_to_google_spreadsheet(credential_json, silo_id, spreadsheet_key) == True: link = "Your exported data is available at <a href=" + google_spreadsheet['alternateLink'] + " target='_blank'>Google Spreadsheet</a>" messages.success(request, link) else: messages.error(request, 'Something went wrong; try again.') return HttpResponseRedirect(reverse('listSilos'))
def run_youtubesubs(ffu): added = 0 storage = Storage(CredentialsModel, 'id', ffu.credentials, 'credential') credential = storage.get() if credential is None or credential.invalid == True: raise Exception("bad creds") return added http = httplib2.Http() http = credential.authorize(http) resp, data = http.request( "%ssubscriptions?part=subscriberSnippet&myRecentSubscribers=true&maxResults=25" % BASE_URL) data = json.loads(data) if 'error' in data: raise Exception("Error fetching youtubesubs: %s" % json.dumps(data['error'])) events = [] if 'items' in data: for i in data['items']: unique_id = i['subscriberSnippet']['channelId'] if YoutubeSubEvent.objects.filter(external_id=i['id'], updater=ffu).count() > 0: break details = json.dumps(i) try: ffe = YoutubeSubEvent(external_id=i['id'], updater=ffu, details=details) events.append(ffe) except Exception, E: print "Failed in individual youtubesubs run: %s\nData:\n%s" % ( E, details) added += 1 for event in reversed(events): try: event.save() added += 1 except Exception, E: print "Failed in individual sponsor run: %s\nData:\n%s" % ( E, ffe.details)
def get_credentials(integration_type): """ Get the credentials for the given integration type. Arguments: tenant (instance): Tenant instance. type (integer): Type of the integration. Returns: Credentials for the given type. """ details = IntegrationDetails.objects.get(type=integration_type) storage = Storage(IntegrationCredentials, 'details', details, 'credentials') credentials = storage.get() if credentials.expires and timezone.now() > credentials.expires: # Credentials have expired, so refresh the token. credentials = authenticate_pandadoc(credentials, integration_type) return credentials
def index(request): print "DATA_SET", DATA_SET storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("fitness", "v1", http=http) result = service.users().dataSources().datasets().get( userId='me', dataSourceId=DATA_SOURCE, datasetId=DATA_SET).execute() #print json.loads(result) json_string = json.dumps(result, encoding='utf-8') print json_string, "?" #logging.info(activitylist) return render(request, 'plus/welcome.html', {'fitpoint': update_total_fitPoint})
def _get_google_credential(request): token = None credential = None if request.user.is_authenticated(): storage = Storage(TokenStorageModel, 'id', request.user, 'credential') credential = storage.get() elif request.session.get('access_token'): credential = google_client.OAuth2Credentials.from_json(token) if credential: try: credential.get_access_token() except HttpAccessTokenRefreshError: try: credential.revoke(httplib2.Http()) except TokenRevokeError: storage.delete() if not credential or credential.invalid: google_flow = generate_google_web_flow(request) return HttpResponseRedirect(google_flow.step1_get_authorize_url()) return credential
def auth_view(request): REDIRECT_URI = 'http://localhost:8000/oauth2/oauth2callback' FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope = 'https://www.googleapis.com/auth/calendar', redirect_uri=REDIRECT_URI ) user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential is None or credential.invalid is True: FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=user, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('calendar', 'v3', http=http) now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Get the last 150 events') eventsResult = service.events().list( calendarId='primary', timeMax=now, maxResults=150, singleEvents=False).execute() events = eventsResult.get('items', []) pprintpp.pprint(events) return render(request, 'oauth/index.html', {'events': events})
def get(self, request): file_id = request.GET.get('fileid') user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential is None or credential.invalid is True: return HttpResponse(json.dumps({'authorize_url':reverse("oauth2:index"), 'recall_url':"%s?fileid=%s"%(reverse("library:upload"),file_id)}),content_type="application/json") http = httplib2.Http() http = credential.authorize(http) drive_service = build('drive', 'v2', http=http) books_service = build('books', 'v1', http=http) bookfile = get_object_or_404(BookFile, id=file_id) # Insert a file media_body = MediaFileUpload(bookfile.fileLocation.path, mimetype='application/epub+zip') body = { 'title': bookfile.book.title, } file = drive_service.files().insert(body=body, media_body=media_body).execute() # Add a book to the shelf book = books_service.cloudloading().addBook(drive_document_id=file['id']).execute() return HttpResponse(json.dumps(book))
def get_credentials(integration_type, tenant=None): """ Get the credentials for the given integration type. Args: integration_type (str): Name of the integration for which the credentials should be retrieved. Returns: credentials (obj): Credentials for the given type. """ try: integration_type = IntegrationType.objects.get(name__iexact=integration_type) except IntegrationType.DoesNotExist: details = None else: try: if tenant: # Calling from an 'anonymous' views (e.g. tasks). So add tenant filter. details = IntegrationDetails.objects.get(type=integration_type.id, tenant=tenant.id) else: # Logged in user is making the call, so TenantMixin is applied. details = IntegrationDetails.objects.get(type=integration_type.id) except IntegrationDetails.DoesNotExist: details = None if details: storage = Storage(IntegrationCredentials, 'details', details, 'credentials') credentials = storage.get() expiry_date = timezone.now() + timedelta(days=7) if credentials.expires and expiry_date > credentials.expires: # Credentials have expired, so refresh the token. credentials = get_access_token(credentials, integration_type) else: credentials = None return credentials
def index(request): # use the first REDIRECT_URI if you are developing your app # locally, and the second in production # REDIRECT_URI = 'http://localhost:8000/oauth2/oauth2callback' REDIRECT_URI = "https://%s%s" % ( get_current_site(request).domain, reverse("oauth2:return")) FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/books', redirect_uri=REDIRECT_URI ) user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') credential = storage.get() if credential is None or credential.invalid is True: FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, user) FLOW.params['next'] = request.GET.get('next') authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=user, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: return HttpResponse('<html><head><title>Close</title></head><body onload="window.close();">Thank you for authorizing the app. Please close this window</body></html>')
def xiaomi(request): storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("fitness", "v1", http=http) # get today today = datetime.date.today() # get yesterday yesterday = today - datetime.timedelta(1) # test #yesterday = today - datetime.timedelta(60) yesterday = yesterday.strftime('%Y-%m-%d') # variable setting update_total_step = 0 update_total_fitPoint = 0 fitPoint = 0 # setting user id fit_user_id = request.user.id fit_profile = Profile.objects.get(user_id=fit_user_id) old_fitPoint = fit_profile.fitPoint old_sync_date = fit_profile.last_sync_date #base_date = old_sync_date end_date = yesterday base_date = old_sync_date #test base_date = datetime.date.today() - datetime.timedelta(60) #base_date = old_sync_date - datetime.timedelta(days=9) json_string = "" # compare and sync #DATA_SET = "1483491600000000000-1483574399000000000" #DATA_SOURCE = "raw:com.google.step_count.delta:com.xiaomi.hm.health:" #result = service.users().dataSources().datasets().get(userId='me', dataSourceId=DATA_SOURCE, datasetId=DATA_SET).execute() #print "result : ",result print "cmp date : ", str(base_date), str(yesterday) + " 00:00:00+00:00" while str(base_date) != str(yesterday) + " 00:00:00+00:00": #setting the date year = int(str(base_date)[:4]) month = int(str(base_date)[5:7]) day = int(str(base_date)[8:10]) form_year = str(base_date)[:4] form_month = str(base_date)[5:7] form_day = str(base_date)[8:10] time_tuple_start = (year, month, day, 0, 0, 0, 0, 0, 0) time_tuple_end = (year, month, day, 23, 59, 59, 0, 0, 0) timestamp_start = time.mktime(time_tuple_start) timestamp_end = time.mktime(time_tuple_end) print year, month, day DATA_SET = str(timestamp_start)[:-2] + "000000000" + "-" + str( timestamp_end)[:-2] + "000000000" #print "DATA_SET",DATA_SET #DATA_SET = "1483228800000000000-1483315199000000000" DATA_SOURCE = "raw:com.google.step_count.delta:com.xiaomi.hm.health:" result = service.users().dataSources().datasets().get( userId='me', dataSourceId=DATA_SOURCE, datasetId=DATA_SET).execute() #print "result : ",result json_string = json.dumps(result, encoding='utf-8') #print "result : ",json_string[154:165] empty_day = json_string[154:165] # Check the directory is exist user = str(request.user) directory = "./fitapp/static/data/" + user if not os.path.exists(directory): os.makedirs(directory) # save file name = directory + "/" + str( base_date)[:10] + "_" + "steps_xiomi" + ".json" f = open(name, 'w') f.write(json_string) f.close() print "convert" # conver data #while str(base_date) != str(yesterday)+" 00:00:00+00:00": total_step = 0 print "empty_day", empty_day if (empty_day != "\"point\": []"): try: total_step = convert(form_year, form_month, form_day, "steps", user) print "total_step", total_step except: pass fitPoint = int(total_step) / 500 update_total_fitPoint = update_total_fitPoint + fitPoint print "convert done!" # increase a day base_date = base_date + datetime.timedelta(days=1) print "************* start update ***************" Profile.objects.filter(user_id=fit_user_id).update( last_sync_date=base_date) Profile.objects.filter(user_id=fit_user_id).update( fitPoint=old_fitPoint + update_total_fitPoint) #logging.info(activitylist) return render(request, 'plus/welcome.html', { 'activitylist': json_string, 'fitpoint': update_total_fitPoint, })
def submit_to_googlesheets(request,post_data): log.debug("made it to submit_to_googlesheets") # search through validated posted data from form # convert any non-None, non-String value to a String for key, value in post_data.iteritems(): if value is not None: if (key == 'state'): # if state object then submit the abbreviation for the state log.debug("state value type: ") log.debug(type(value)) log.debug("state value.abbr type: ") log.debug(type(value.abbr)) #post_data[key] = str(value) elif not isinstance(value, basestring): # if any other python object or int, etc. then convert to string for submission to spreadsheet post_data[key] = str(value) storage = Storage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: log.debug("submit_to_googlesheets: credential is None or credential.invalid == True") FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: log.debug("submit_to_googlesheets: else") http = httplib2.Http() http = credential.authorize(http) service = build(API, API_VERSION, http=http) spreadsheetId = '1j2_ZjzoMGzR2e6m-UbscK1xJiV58vX92rupEiRwQvD4' sheetId = get_sheetId_by_sheetLabel(service,spreadsheetId, 'Fulfillment Spreadsheet') rangeName = 'Fulfillment Spreadsheet!A2:E' current_row_num = get_firstEmptyRow(service, spreadsheetId, 'Fulfillment Spreadsheet') insert_row_data = { "requests": [ { "insertDimension": { "range": { "sheetId": sheetId, "dimension": "ROWS", "startIndex": "%d" % (current_row_num-1), "endIndex": "%d" % (current_row_num) }, "inheritFromBefore": True } } ] } test_input_data = { "majorDimension": "ROWS", "values": [ [ "=COUNTIFS($D$3:$D$3022,$D%s)" % (current_row_num), ## Units in Order "{:%Y-%m-%d %H:%M:%S}".format(datetime.datetime.now()), ## Timestamp post_data['order_date'], ## Date of Order post_data['order_number'], ## Order Number post_data['dealer_name'], ## Dealer Name post_data['customer_name'], ## Customer Name post_data['street_address'], ## Shipping Address post_data['city'], ## City post_data['state'].abbr, ## State post_data['zip'], ## Zip post_data['country'], ## Country post_data['customer_phone'], ## Customer Phone post_data['customer_email'], ## Customer Email post_data['sku_number'], ## SKU post_data['model_type'], ## Model post_data['item_condition'], ## Item condition post_data['unit_number'], ## Number of Units post_data['po_number'], ## PO # post_data['slate_invoice_number'], ## Slate Invoice # post_data['priority'], ## Priority post_data['order_notes'], ## Notes post_data['promised_date'], ## Is there a promised date? post_data['ship_number'], ## Ship Number - Sales "", ## Proj. Ship Week "", ## Proj. Ship Week Notes "", ## Actual Ship Number post_data['billing_address'], ## Billing address post_data['addtl_ship_info'], ## Add additional shipping info if you like. post_data['addtl_notes'], ## Additional notes post_data['warranty_date'], ## Warranty Exp Date "", ## Serial Number "", ## Tracking "", ## NAILED IT "", ## OK to ship? '=if(AG%s="x",D%s,"")' % (current_row_num, current_row_num) ## Order Counter Formula ] ], } service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetId, body=insert_row_data).execute() service.spreadsheets().values().append(spreadsheetId=spreadsheetId, range='Fulfillment Spreadsheet', body=test_input_data, valueInputOption='USER_ENTERED').execute() return None
def event_post(request): REDIRECT_URI = "https://%s%s" % ( request.get_host(), reverse("scheduler:post_event_return")) # FLOW = flow_from_clientsecrets( # CLIENT_SECRETS, # scope=SCOPES, # redirect_uri=REDIRECT_URI # ) FLOW = OAuth2WebServerFlow( client_id='323423619559-orlpuuiaalb7sp3ooblt4mjmp32ffq1t.apps.googleusercontent.com', client_secret=os.environ['CLIENT_SECRET'], scope=SCOPES, redirect_uri=REDIRECT_URI ) user = request.user storage = Storage(CredentialsModel, 'id', user, 'credential') # credential = request. credential = storage.get() if credential is None or credential.invalid is True: FLOW.params['state'] = xsrfutil.generate_token( settings.SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() f = FlowModel(id=user, flow=FLOW) f.save() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('calendar', 'v3', http=http) data = request.data event = { 'location': '5127 Sheridan Blvd, Broomfield, CO 80020', 'start': { 'timeZone': 'America/Denver', }, 'end' : { 'timeZone': 'America/Denver', }, } if 'event_id' in data: event['summary']= 'Event' + data['event_id'] else: event['summary']= 'Event w/o ID' if 'description' in data: event['description']= data['description'] else: event['summary']= 'Test for event w/o ID' #MANDATORY ARGUMENT if 'start_datetime' in data: event['start']['dateTime']= data['start_datetime'] else: event['start']['dateTime']='2016-05-28T20:00:00-07:00' #MANDATORY ARGUMENT if 'end_datetime' in data: event['end']['dateTime']= data['end_datetime'] else: event['end']['dateTime']= '2016-05-28T21:00:00-07:00'#str(datetime.datetime.now() + datetime.timedelta(hours=1))#str(timezone.now() +timezone.timedelta(hours=1))#'2016-05-28T14:00:00-07:00' if 'recurrence' in data: event['recurrence'] = data['recurrence'] else: event['recurrence'] ='RRULE:FREQ=DAILY;COUNT=2' if 'reminders' in data: event['reminders']= data['reminders'] else: event['reminders']= { 'useDefault': False, 'overrides': [ {'method': 'email', 'minutes': 24 * 60}, {'method': 'popup', 'minutes': 10}, ], } e = service.events().insert(calendarId='primary', body=event).execute()