File size: 4,610 Bytes
c0aeb3b
09ac17b
 
 
c0aeb3b
09ac17b
 
 
 
 
 
 
 
 
 
 
 
 
2892732
 
 
09ac17b
2892732
09ac17b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2892732
09ac17b
 
 
 
 
 
 
2892732
09ac17b
 
 
 
 
 
 
 
 
 
 
 
2892732
 
 
09ac17b
 
 
 
 
2892732
 
09ac17b
 
 
 
 
2892732
09ac17b
 
 
 
 
2892732
 
 
 
09ac17b
 
 
2892732
09ac17b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2892732
09ac17b
 
 
 
 
 
 
 
 
2892732
09ac17b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2892732
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
import streamlit as st
import datetime
import uuid
import os

from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
import gspread

# ==========================================================
# CONFIG
# ==========================================================

APP_NAME = "UnreadGbox ✨"
SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1j_uDxzWfp2PiZyJXDbFPz5Pa8HLg8zFTuJAYq1XiTDo/edit?usp=drivesdk"
SHEET_NAME = "UnreadGbox"

SCOPES = [
    "openid",
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/userinfo.profile",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/spreadsheets",
]

CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID")
CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET")
PROJECT_ID = os.environ.get("GOOGLE_PROJECT_ID")
BASE_URL = os.environ.get("BASE_URL")

# ==========================================================
# PAGE SETUP
# ==========================================================

st.set_page_config(
    page_title="UnreadGbox ✨",
    page_icon="✨",
    layout="centered"
)

st.markdown("# ✨ UnreadGbox")
st.caption("Minimal Gmail Cleanup Tool")
st.divider()

if not CLIENT_ID or not CLIENT_SECRET or not PROJECT_ID or not BASE_URL:
    st.error("Missing Hugging Face Secrets.")
    st.stop()

# ==========================================================
# OAUTH FLOW
# ==========================================================

def create_flow():
    flow = Flow.from_client_config(
        {
            "web": {
                "client_id": CLIENT_ID,
                "project_id": PROJECT_ID,
                "auth_uri": "https://accounts.google.com/o/oauth2/auth",
                "token_uri": "https://oauth2.googleapis.com/token",
                "client_secret": CLIENT_SECRET,
                "redirect_uris": [BASE_URL],
            }
        },
        scopes=SCOPES,
    )
    flow.redirect_uri = BASE_URL
    return flow


def login():
    flow = create_flow()
    auth_url, state = flow.authorization_url(
        access_type="offline",
        include_granted_scopes="true",
        prompt="consent",
    )
    st.session_state["state"] = state
    st.markdown(f"[πŸ” Login with Google]({auth_url})")
    st.stop()


def fetch_token():
    if "code" not in st.query_params:
        login()

    flow = create_flow()
    flow.fetch_token(
        code=st.query_params["code"],
        include_client_id=True,
    )

    return flow.credentials


# ==========================================================
# AUTHENTICATION
# ==========================================================

if "credentials" not in st.session_state:
    credentials = fetch_token()
    st.session_state["credentials"] = credentials

creds = st.session_state["credentials"]

# ==========================================================
# BUILD GOOGLE SERVICES
# ==========================================================

gmail_service = build("gmail", "v1", credentials=creds)
gc = gspread.authorize(creds)
sheet = gc.open_by_url(SPREADSHEET_URL).worksheet(SHEET_NAME)

# ==========================================================
# GET USER INFO
# ==========================================================

profile = gmail_service.users().getProfile(userId="me").execute()
user_email = profile.get("emailAddress")

st.success(f"Logged in as: {user_email}")
st.divider()

# ==========================================================
# CLEAN UNREAD EMAILS
# ==========================================================

if st.button("✨ Clean Unread Emails"):

    with st.spinner("Scanning unread emails..."):

        results = gmail_service.users().messages().list(
            userId="me",
            q="is:unread"
        ).execute()

        messages = results.get("messages", [])
        unread_count = len(messages)

        if unread_count == 0:
            st.success("No unread emails πŸŽ‰")
        else:
            for msg in messages:
                gmail_service.users().messages().trash(
                    userId="me",
                    id=msg["id"]
                ).execute()

            now = datetime.datetime.now()

            sheet.append_row([
                str(uuid.uuid4()),
                now.strftime("%Y-%m-%d"),
                now.strftime("%H:%M:%S"),
                user_email.split("@")[0],
                user_email,
                unread_count
            ])

            st.success(f"{unread_count} unread emails moved to Trash βœ…")

st.divider()
st.caption("UnreadGbox ✨ β€” Secure Micro SaaS")