Omkar008 commited on
Commit
2e0507d
1 Parent(s): 66185d4

Update test.py

Browse files
Files changed (1) hide show
  1. test.py +122 -72
test.py CHANGED
@@ -149,85 +149,135 @@ async def auth_google(request: Request):
149
  # print(len(data_new))
150
  return {"attachment_count":attachment_no,"attachment_content":data_new}
151
 
152
- @app.get("/auth1/google")
153
- async def auth_google(request: Request):
154
  #This code is basically the authorization code and this authorization code helps us to get the access token with the required scopes that we have set .
155
  #We require the gmail.readonly scopes that requires verification of our application and all.
156
-
157
- filter_query = None
158
- if state:
159
- state_params = state.split('&')
160
- for param in state_params:
161
- if param.startswith('filter_query='):
162
- filter_query = param.split('=')[1]
163
-
164
-
165
- token_url = "https://accounts.google.com/o/oauth2/token"
166
- print(code)
167
- data = {
168
- "code": code,
169
- "client_id": GOOGLE_CLIENT_ID,
170
- "client_secret": GOOGLE_CLIENT_SECRET,
171
- "redirect_uri": GOOGLE_REDIRECT_URI,
172
- "grant_type": "authorization_code",
173
- }
174
- response = requests.post(token_url, data=data)
175
- access_token = response.json().get("access_token")
176
- print(response.json())
177
- user_info = requests.get("https://www.googleapis.com/oauth2/v1/userinfo", headers={"Authorization": f"Bearer {access_token}"})
178
-
179
- gmail_url = "https://www.googleapis.com/gmail/v1/users/me/messages?q=subject:receipt&maxResults=2"
180
- gmail_response = requests.get(gmail_url, headers={"Authorization": f"Bearer {access_token}"})
181
- messages = gmail_response.json().get("messages", [])
182
- print(messages)
183
- print("Printing gmail response")
184
- print(gmail_response.json())
185
- attachment_no = 0
186
- data_new = [[]]
187
-
188
- for i,message in enumerate(messages) :
189
-
190
-
191
- if message:
192
- message_id = message.get("id")
193
- print(message_id)
194
- if message_id:
195
- message_url = f"https://www.googleapis.com/gmail/v1/users/me/messages/{message_id}"
196
- message_response = requests.get(message_url, headers={"Authorization": f"Bearer {access_token}"})
197
- message_data = message_response.json()
198
-
199
- # Check for parts in the message payload
200
- if "payload" in message_data and "parts" in message_data["payload"]:
201
- for part in message_data["payload"]["parts"]:
202
- if "body" in part and "attachmentId" in part["body"]:
203
- attachment_id = part["body"]["attachmentId"]
204
- attachment_url = f"https://www.googleapis.com/gmail/v1/users/me/messages/{message_id}/attachments/{attachment_id}"
205
- attachment_response = requests.get(attachment_url, headers={"Authorization": f"Bearer {access_token}"})
206
- attachment_data = attachment_response.json()
207
- data = attachment_data.get("data")
208
- filename = part.get("filename", "untitled.txt")
209
-
210
- if data:
211
- data_new.append([data.encode("utf-8")])
212
- # Decode base64-encoded attachment data
213
- attachment_content = base64.urlsafe_b64decode(data.encode("UTF-8"))
214
- # print(attachment_content)
215
- print("yo")
216
- print(data_new)
217
- attachment_no+=1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
 
220
- # Save the attachment to a file
221
- #Here add the function or class to save the attachments to Google Cloud
222
- # save_path = f"/Users/omkarmalpure/Desktop/Current Work/fastapi_gmail/attachments/{filename}"
223
- # with open(save_path, "wb") as file:
224
- # file.write(attachment_content)
225
 
226
-
227
-
228
 
229
- return {"user_info": user_info.json(), "query": filter_query , "data":attachment_no , "attachment_content":data_new , "attachment_count":attachment_no}
230
 
 
231
  @app.get("/token")
232
  async def get_token(token: str = Depends(oauth2_scheme)):
233
  return jwt.decode(token, GOOGLE_CLIENT_SECRET, algorithms=["HS256"])
 
149
  # print(len(data_new))
150
  return {"attachment_count":attachment_no,"attachment_content":data_new}
151
 
152
+ @app.websocket("/ws")
153
+ async def auth_google(websocket: WebSocket):
154
  #This code is basically the authorization code and this authorization code helps us to get the access token with the required scopes that we have set .
155
  #We require the gmail.readonly scopes that requires verification of our application and all.
156
+ # raw_body = await request.body()
157
+ # return {"data":Yo Yo"}
158
+ # data = await request.json()
159
+ # code = data.get("access_token")
160
+ code = await websocket.receive_json()
161
+ # code = raw_body.decode()
162
+ def get_messages():
163
+ print()
164
+ # print(code)
165
+ access_token = code
166
+ print("printing access_token")
167
+ print(access_token)
168
+ page_token = None
169
+ messages = []
170
+ jobs_query = "subject:receipt OR subject:receipts has:attachment"
171
+
172
+ while True:
173
+ # Construct Gmail API request with pageToken
174
+ print("into the gmail")
175
+ gmail_url = f"https://www.googleapis.com/gmail/v1/users/me/messages?q={jobs_query}"
176
+
177
+ if page_token:
178
+ gmail_url += f"&pageToken={page_token}"
179
+
180
+ gmail_response = requests.get(gmail_url, headers={"Authorization": f"Bearer {access_token}"})
181
+ print(gmail_response)
182
+ gmail_data = gmail_response.json()
183
+
184
+ # Check if there are messages in the response
185
+ if "messages" in gmail_data:
186
+ messages.extend(gmail_data["messages"])
187
+
188
+ # Check if there are more pages
189
+ if "nextPageToken" in gmail_data:
190
+ page_token = gmail_data["nextPageToken"]
191
+ else:
192
+ break # No more pages, exit the loop
193
+ print("returning the messages")
194
+
195
+ unique_thread_ids = set()
196
+
197
+ filtered_data_list = []
198
+
199
+ for entry in messages:
200
+ thread_id = entry['threadId']
201
+ if thread_id not in unique_thread_ids:
202
+ unique_thread_ids.add(thread_id)
203
+ filtered_data_list.append(entry)
204
+
205
+
206
+ print(messages)
207
+ print(filtered_data_list)
208
+ return filtered_data_list
209
+
210
+ async def event_generator():
211
+ print(code)
212
+ access_token = code
213
+ messages=get_messages()
214
+ print(len(messages))
215
+ await websocket.send(json.dumps({"total_messages": len(messages)}))
216
+
217
+
218
+ attachments = []
219
+ prev_data=""
220
+ data_new={}
221
+ attachment_no=0
222
+ batch_size = 5
223
+ prev_filename = None
224
+
225
+ for i,message in enumerate(messages) :
226
+ print(i)
227
+ print(message)
228
+
229
+ if message:
230
+ message_id = message.get("id")
231
+ thread_id = message.get("threadId")
232
+ print(message_id)
233
+ if message_id:
234
+ message_url = f"https://www.googleapis.com/gmail/v1/users/me/messages/{message_id}"
235
+ message_response = requests.get(message_url, headers={"Authorization": f"Bearer {access_token}"})
236
+ message_data = message_response.json()
237
+
238
+ # Check for parts in the message payload
239
+ if "payload" in message_data and "parts" in message_data["payload"]:
240
+ for part in message_data["payload"]["parts"]:
241
+ if "body" in part and "attachmentId" in part["body"]:
242
+ attachment_id = part["body"]["attachmentId"]
243
+ print(attachment_id)
244
+ attachment_url = f"https://www.googleapis.com/gmail/v1/users/me/messages/{message_id}/attachments/{attachment_id}"
245
+ attachment_response = requests.get(attachment_url, headers={"Authorization": f"Bearer {access_token}"})
246
+ attachment_data = attachment_response.json()
247
+ data = attachment_data.get("data",{})
248
+ filename = part.get("filename", "untitled.txt")
249
+
250
+ # print("Print the data json response for that gmail")
251
+ print(filename)
252
+
253
+
254
+ # print(attachment_data)
255
+ # json_str = json.dumps(attachment_data, indent=2)
256
+
257
+ # with subprocess.Popen(["less"], stdin=subprocess.PIPE) as less_process:
258
+ # less_process.communicate(input=json_str.encode("utf-8"))
259
+ if data:
260
+ data_new[filename]=str(data[:10])
261
+ # data_new.append({filename:data.encode("UTF-8")})
262
+ # Decode base64-encodattaed attachment data
263
+ # print(filename)s
264
+ attachment_content = base64.urlsafe_b64decode(data.encode("UTF-8"))
265
+ # print(attachment_content)
266
+ print("yo")
267
+ # print(data_new)
268
+ attachment_no+=1
269
+ await websocket.send_json({filename:data[:10]})
270
+
271
+ # yield f"data: {str(data_new)}\n\n"
272
+
273
+ # data_new={}
274
 
275
 
276
+
 
 
 
 
277
 
 
 
278
 
 
279
 
280
+ await websocket.send_text("Successfully sent all the Data !")
281
  @app.get("/token")
282
  async def get_token(token: str = Depends(oauth2_scheme)):
283
  return jwt.decode(token, GOOGLE_CLIENT_SECRET, algorithms=["HS256"])