File size: 2,035 Bytes
29009fc
 
 
6cab6c6
29009fc
 
 
 
 
 
 
 
 
6cab6c6
 
 
 
29009fc
 
6cab6c6
29009fc
 
 
 
6cab6c6
29009fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os
import json
from datetime import datetime

SCOPE = [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive.file"
]

def get_sheet():
    try:
        # Read the credentials from the environment variable (Hugging Face Secret)
        creds_json_str = os.getenv("GOOGLE_CREDENTIALS_JSON")
        if not creds_json_str:
            print("Error: GOOGLE_CREDENTIALS_JSON secret is not set in Hugging Face.")
            return None
            
        creds_dict = json.loads(creds_json_str)
        creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, SCOPE)
        client = gspread.authorize(creds)
        sheet_id = os.getenv("GOOGLE_SHEET_ID")
        if not sheet_id:
            print("Error: GOOGLE_SHEET_ID secret is not set.")
            return None
        sheet = client.open_by_key(sheet_id).sheet1
        return sheet
    except Exception as e:
        print(f"Error connecting to Google Sheets: {e}")
        return None

def add_subscriber_to_sheet(email: str, fav_destinations: list, origin: str, dob: str):
    sheet = get_sheet()
    if sheet is None:
        return False, "Could not connect to the subscribers sheet."
    
    try:
        all_values = sheet.get_all_values()
        if not all_values or all_values[0] != ["timestamp", "email", "favorite_destinations", "usual_origin", "dob"]:
             sheet.insert_row(["timestamp", "email", "favorite_destinations", "usual_origin", "dob"], 1)

        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        destinations_str = ", ".join(fav_destinations)
        
        email_list = sheet.col_values(2)
        if email in email_list:
             return False, "This email is already subscribed."

        sheet.append_row([timestamp, email, destinations_str, origin, dob])
        return True, "Successfully subscribed!"
    except Exception as e:
        return False, f"An error occurred: {e}"