File size: 12,550 Bytes
dd9d069 e7a3196 dd9d069 e7a3196 dd9d069 e7a3196 dd9d069 e7a3196 dd9d069 e7a3196 dd9d069 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | import json
from oauth2client import client
from apiclient import discovery
from httplib2 import Http
import pandas as pd
import dateutil.parser as parser
from dateutil import tz
import base64
import re
import time
import math
from data.sample import (
LABEL_COLS, LABEL_DB,
EMAIL_COLS, EMAIL_DB,
EMAIL_SUMMARY_COLS, EMAIL_SUMMARY_DB, SENDER_SUMMARY_DB,
UNSUB_COLS, UNSUB_DB,
PROCESSING_ERRORS_COLS, PROCESSING_ERRORS_DB,
ANALYSIS_TYPES, FILE_PATHS)
from components.gradio.api import checkDB_api
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] # we are using modify and not readonly, as we will be marking the messages Read
A_TAG_REGEX = r'<a\s+(?:[^>]*?\s+)?href=["\']([^"\']*)["\']([^>]*)>(.*?)<\/a>'
def authenticate_gmail(userinfo:dict=None, refresh:bool=False):
""" Authenticates with Gmail API and returns the service object """
print("Initiating Gmail authentication flow....")
curr_user = userinfo.get('user','')
curr_user_email = curr_user.get('email','')
creds_json = None
response = checkDB_api(row_id_value=curr_user_email, column="gmail_token", table="users", row_id_type="email")
if response:
creds_json = response
if creds_json:
_missing_scopes = []
for _scope in SCOPES:
if _scope not in creds_json['scopes']:
_missing_scopes.append(_scope)
if len(_missing_scopes) > 0:
print(f"Required Scopes {_missing_scopes} are not present. Skipping..")
# TODO - Trigger new signin with updated scopes
else:
creds = client.OAuth2Credentials.from_json(json.dumps(creds_json))
if not creds or creds.invalid or refresh:
print("Credentials are invalid or force-refresh is triggered, attempting to refresh.")
try:
creds.refresh(Http())
if not creds.invalid:
print("Credentials refreshed successfully.")
creds_json = creds.to_json()
# TODO - Update auth_response in the database
except client.AccessTokenRefreshError:
print("Failed to refresh access token.")
return None
service = discovery.build('gmail', 'v1', http=creds.authorize(Http()))
return service
return None
def parse_email(service, msg_id, label_id):
email = {
'id': msg_id,
'label':label_id,
'date': None,
'from': None,
'email': None,
'domain': None,
'subject': None,
'unsub_links': []}
message_details = service.users().messages().get(userId='me', id=email['id']).execute()
# pretty_print_blueprint(message_details)
payload = message_details['payload']
headers = payload.get('headers', [])
for header in headers:
if header['name'] == 'From':
from_ = header['value']
email['email'], email['domain'], email['from'] = extract_email_and_domain(from_)
if header['name'] == 'Subject':
email['subject'] = header['value']
if header['name'] == 'Date':
# Valid date format: Tue, 04 Jun 2024 19:31:16 +0000 = "%a, %d %b %Y %H:%M:%S %z"
date_ = header['value']
date_ = (parser.parse(date_,))
# print("Gmail Date: ", date_)
date_ = date_.astimezone(tz.tzlocal())
# print("Local TimeZone Date: ", date_)
date_ = date_.replace(tzinfo=None)
# print("TimeZone Naive Date: ", date_)
date_ = date_.strftime('%Y-%m-%dT%H:%M:%S')
# print("JSON Serializable Date: ", date_)
email['date'] = (date_)
# email['snippet'] = message_details['snippet']
msg_parts = payload.get('parts', [])
unsubscribe_links = []
for m_i, part in enumerate(msg_parts):
part_body = part['body']
# pretty_print_blueprint(part_body)
if 'data' in part_body:
part_data = part_body['data'] # fetching data from the body
# pretty_print_blueprint(part_data)
clean_one = part_data.replace("-", "+") # decoding from Base64 to UTF-8
# pretty_print_blueprint(clean_one)
clean_one = clean_one.replace("_", "/") # decoding from Base64 to UTF-8
# pretty_print_blueprint(clean_one)
clean_two = base64.b64decode(bytes(clean_one, 'UTF-8')) # decoding from Base64 to UTF-8
# print(m_i, clean_two)
a_tags = re.findall(A_TAG_REGEX, str(clean_two))
for tag in a_tags:
href, attributes, link_text = tag
# print(f'{link_text} Link: {href}')
if 'unsubscribe' in link_text.lower():
# print(f'{link_text} Link: {href}')
unsubscribe_links.append(href)
email['unsub_links'] = list(set(unsubscribe_links))
return email
# Function to extract email from the sender field
def extract_email(sender):
match = re.search(r'<(.+?)>|([^<>\s]+@[^<>\s]+)', sender)
if match:
email = match.group(1) if match.group(1) else match.group(2)
return email
return None
# Function to extract domain from the sender field
def extract_domain(sender):
email = extract_email(sender)
domain = email.split('@')[1] if email else None
return domain
def extract_email_and_domain(sender):
email = extract_email(sender)
domain = email.split('@')[1] if email else None
sender_name = sender.replace(email,'')
sender_name = sender_name.replace(' <','')
sender_name = sender_name.replace('>','')
return email, domain, sender_name
def get_emails(label_id = 'INBOX', num_emails = 20, max_results = 10, userinfo = None):
""" Fetches unread emails for a specific label """
print(f"Fetching '{num_emails}' unread emails for label '{label_id}'....")
emails = []
emails_with_error = []
sender_counts = SENDER_SUMMARY_DB
domain_counts = EMAIL_SUMMARY_DB
df = EMAIL_DB
unsub_db = UNSUB_DB
error_db = PROCESSING_ERRORS_DB
total_batches = math.ceil(num_emails/max_results)
curr_batch = 1
start_time = time.time()
rem_emails = num_emails
update = f"π π Analysis initiated... for the selected label with id '{label_id}'"
print(update)
yield update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
service = authenticate_gmail(userinfo)
if service:
page_token = True
while page_token and rem_emails > 0:
if rem_emails < max_results:
max_results = rem_emails
if type(page_token) == str:
if num_emails > 250:
mini_update = update+f""" - Initializing auto-reconnect to Gmail API"""
print(mini_update)
yield mini_update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
service = authenticate_gmail(userinfo,refresh=True)
mini_update = update+f""" - Completed auto-reconnect to Gmail API"""
print(mini_update)
yield mini_update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
response = service.users().messages().list(
userId='me',
maxResults=max_results,
pageToken=page_token
).execute()
else:
response = service.users().messages().list(
userId='me',
labelIds=[label_id, 'UNREAD'],
maxResults=max_results
).execute()
messages = response.get('messages', []) # Handle case where no unread emails exist
# print(page_token, len(messages))
for idx_, message in enumerate(messages):
# print(len(emails))
email = {
'id': None,
'label':label_id,
'date': None,
'from': None,
'email': None,
'domain': None,
'subject': None,
'unsub_links': []}
try:
email = parse_email(service, message['id'], label_id)
except Exception as error:
emails_with_error.append({'error': error, **email})
update = f"""π΄ Error '{error}' while processing email having id '{email['id']}' with subject '{email['subject']}' received from '{email['from']}' on '{email['date']}'"""
print(update)
yield update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
emails.append(email)
if len(emails) % 10 == 0:
elapsed_time = time.time() - start_time
update = f"π‘ β³ Loading, please wait... Analysis in progress [#Emails Processed - {len(emails)}/{num_emails}] [Elapsed time: {int(elapsed_time // 60):02d}:{(elapsed_time % 60):05.2f} mins] [{curr_batch}/{total_batches}] [Current Batch-size - {max_results}]"
print(update)
yield update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
page_token = response.get('nextPageToken', False)
rem_emails = num_emails - len(emails)
elapsed_time = time.time() - start_time
if rem_emails > 0:
curr_batch += 1
update = f"π‘ β³ Loading, please wait... Analysis in progress [#Emails Processed - {len(emails)}/{num_emails}] [Elapsed time: {int(elapsed_time // 60):02d}:{(elapsed_time % 60):05.2f} mins] [{curr_batch}/{total_batches}] [Current Batch-size - {max_results}]"
print(update)
yield update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
# Create analyses - Sender-wise, Domain-wise, Unsubscribe links
df = pd.DataFrame(emails)
sender_counts = df.groupby(['label','email'])['id'].count().reset_index(name='emailCount')
sender_counts = sender_counts.sort_values(by='emailCount', ascending=False)
sender_counts.columns = EMAIL_SUMMARY_COLS
domain_counts = df.groupby(['label','domain'])['id'].count().reset_index(name='emailCount')
domain_counts = domain_counts.sort_values(by='emailCount', ascending=False)
domain_counts.columns = EMAIL_SUMMARY_COLS
total_count = pd.DataFrame([['ALL', 'ALL', sender_counts['emailCount'].sum()]], columns=EMAIL_SUMMARY_COLS)
sender_counts = pd.concat([total_count, sender_counts]).reset_index(drop=True)
total_count = pd.DataFrame([['ALL', 'ALL', domain_counts['emailCount'].sum()]], columns=EMAIL_SUMMARY_COLS)
domain_counts = pd.concat([total_count, domain_counts]).reset_index(drop=True)
unsub_db_ = df.copy(deep=True)
unsub_db_['unsub_link'] = unsub_db_['unsub_links'].apply(lambda x: x[0] if len(x) > 0 else None)
unsub_db = unsub_db_.groupby(['label','domain','email','from']).size().reset_index(name='emailCount')
unsub_db_ = unsub_db_.groupby(['label','domain', 'email', 'from']).first().reset_index()
unsub_db = pd.merge(unsub_db, unsub_db_[['label','domain', 'email', 'from', 'unsub_link']], on=['label','domain', 'email', 'from'], how='left')
unsub_db = unsub_db.sort_values(by='emailCount', ascending=False)
# TODO: unsub_link validation - Add "Suspicious Unsubscription Link" if invalid & "Unsubscription Link - Not Found" if empty
error_db = pd.DataFrame(emails_with_error, columns=PROCESSING_ERRORS_COLS)
# print(error_db)
update = f"""π’ π Success! {len(emails)}/{num_emails} emails processed for the selected label with id '{label_id}' [Elapsed time: {int(elapsed_time // 60):02d}:{(elapsed_time % 60):05.2f} mins]"""
print(update)
yield update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
else:
yield "π΄ Error! No connection with GmailAPI. Please reconnect & try again.", sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25)
|