def test_api_request(): # check if pickled credential is in DB, if not redirect to /authorize creds = get_creds_from_db() if not creds: return redirect(flask.url_for('authorize')) # load pickle into creds, check if still valid if not creds.valid: if creds.expired and creds.refresh_token: try: creds.refresh(Request()) except GoogleAuthError as e: print(f'An error occured: {e}') return redirect( flask.url_for('authorize', next='test_api_request')) else: return redirect(flask.url_for('authorize', next='test_api_request')) # call Gmail API using creds credential gmail = googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=creds) msg_list = gmail.users().messages().list(userId='me', labelIds=['INBOX']).execute() # save creds to pickle in case access token is refreshed save_creds_to_db(creds) print( f'Expiry: {creds.expiry}, Refresh token: {creds.refresh_token}, Expired: {creds.expired}' ) return flask.jsonify(msg_list)
def revoke(): creds = get_creds_from_db() if not creds: return ( 'You need to <a href="/gmail/authorize">authorize</a> before testing the code to revoke credentials.' ) revoke = requests.post( 'https://oauth2.googleapis.com/revoke', params={'token': creds.token}, headers={'content-type': 'application/x-www-form-urlencoded'}) status_code = getattr(revoke, 'status_code') if status_code == 200: return ('Credentials successfully revoked.' + print_index_table()) else: return ('An error occurred.' + print_index_table())
def call_watch(): creds = get_creds_from_db() gmail = googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=creds) request_body = { 'labelIds': ['INBOX'], 'topicName': 'projects/thinking-banner-284203/topics/luminus-gmail-forward' } # save global history_id returned by watch() call history_id = gmail.users().watch(userId='me', body=request_body).execute()['historyId'] save_history_id_to_db(history_id) print( f'Expiry: {creds.expiry}, Refresh token: {creds.refresh_token}, Expired: {creds.expired}' ) return f'HistoryId = {history_id}'
def run_gmail_client_and_watch(): creds = get_creds_from_db() if creds: if not creds.valid: if creds.expired and creds.refresh_token: try: creds.refresh(Request()) except GoogleAuthError as e: print( f'{e}. Expiry: {creds.expiry}, Expired: {creds.expired}, Refresh token: {creds.refresh_token}' ) msg = ( f'{e}. Expiry: {creds.expiry}, Expired: {creds.expired}, Refresh token: {creds.refresh_token}.' + 'https://polar-ridge-56723.herokuapp.com/gmail/authorize?next=call_watch' ) bot.send_message(chat_id=test_group_chat_id, text=msg, disable_web_page_preview=True) return False else: print( f'Credential invalid. Expiry: {creds.expiry}, Expired: {creds.expired}, Refresh token: {creds.refresh_token}' ) msg = ( f'Credential invalid. Expiry: {creds.expiry}, Expired: {creds.expired}, Refresh token: {creds.refresh_token}.' + 'https://polar-ridge-56723.herokuapp.com/gmail/authorize?next=call_watch' ) bot.send_message(chat_id=test_group_chat_id, text=msg, disable_web_page_preview=True) return False gmail = googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=creds) request_body = { 'labelIds': ['INBOX'], 'topicName': 'projects/thinking-banner-284203/topics/luminus-gmail-forward' } # save global history_id returned by watch() call history_id = gmail.users().watch( userId='me', body=request_body).execute()['historyId'] # save creds to pickle in case access token is refreshed save_creds_to_db(creds) save_history_id_to_db(history_id) print( f'Expiry: {creds.expiry}, Refresh token: {creds.refresh_token}, Expired: {creds.expired}' ) print(f'Gmail client is ready. HistoryId={history_id}') return True else: print('Token not found in DB.') msg = 'Token not found in DB. https://polar-ridge-56723.herokuapp.com/gmail' bot.send_message(chat_id=test_group_chat_id, text=msg, disable_web_page_preview=True) return False
def luminus_announcement(): msg = '' creds = get_creds_from_db() history_id = get_history_id_from_db() if not creds: print('Pickle not found in db') msg = f'Pickle not found in db. {flask.url_for("authorize", next="test_api_request", _external=True)}' bot.send_message(chat_id=test_group_chat_id, text=msg, disable_web_page_preview=True) return 'Client unavailable' # load pickle into creds, check if still valid if not creds.valid: if creds.expired and creds.refresh_token: try: creds.refresh(Request()) except GoogleAuthError as e: print(f'An error occured: {e}') print( f'Credential invalid. Expiry: {creds.expiry}, Expired: {creds.expired}, Refresh token: {creds.refresh_token}' ) msg = ( f'An error occured: {e}. Expiry: {creds.expiry}, Expired: {creds.expired}, Refresh token: {creds.refresh_token}.' + f'{flask.url_for("authorize", next="test_api_request", _external=True)}' ) bot.send_message(chat_id=test_group_chat_id, text=msg, disable_web_page_preview=True) return 'Refresh error' else: print( f'Credential invalid. Expiry: {creds.expiry}, Expired: {creds.expired}, Refresh token: {creds.refresh_token}' ) msg = ( f'Credential invalid. Expiry: {creds.expiry}, Expired: {creds.expired}, Refresh token: {creds.refresh_token}.' + f'{flask.url_for("authorize", next="test_api_request", _external=True)}' ) bot.send_message(chat_id=test_group_chat_id, text=msg, disable_web_page_preview=True) return 'Client unavailable' gmail = googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=creds) history_list = gmail.users().history().list( userId='me', historyTypes=['messageAdded'], labelId='INBOX', startHistoryId=history_id).execute() if 'history' in history_list: for history in history_list['history']: if 'messagesAdded' in history: for added_message in history['messagesAdded']: id = added_message['message']['id'] message = gmail.users().messages().get( userId='me', id=id, format='raw').execute() msg_bytes = base64.urlsafe_b64decode( message['raw'].encode('ASCII')) mime_msg = email.message_from_bytes( msg_bytes, policy=email.policy.default) if list(mime_msg.iter_attachments()).__len__() > 0: attachments = list(mime_msg.iter_attachments()) for att in attachments: msg = get_msg_from_att(att) if (msg != ''): bot.send_message(chat_id=test_group_chat_id, text=msg, parse_mode='HTML', disable_web_page_preview=True) bot.send_message(chat_id=sa52_group_chat_id, text=msg, parse_mode='HTML', disable_web_page_preview=True) if msg == '': print('Non-MessageAdded webhook') history_id = history_list['historyId'] save_history_id_to_db(history_id) save_creds_to_db(creds) print( f'Expiry: {creds.expiry}, Refresh token: {creds.refresh_token}, Expired: {creds.expired}' ) return 'ok'