File size: 2,137 Bytes
557d2ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from google_auth_oauthlib.flow import Flow, InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from googleapiclient.errors import HttpError
import streamlit as st

def Create_Service(client_secret_file, api_name, api_version, *scopes):
    CLIENT_SECRET_FILE = client_secret_file
    API_SERVICE_NAME = api_name
    API_VERSION = api_version
    SCOPES = [scope for scope in scopes[0]]


    cred = None
    client_id = st.secrets["AuthToken_client_id"]
    client_secret = st.secrets["AuthToken_client_secret"]
    refresh_token = st.secrets["AuthToken_refresh_token"]
    token_uri = "https://oauth2.googleapis.com/token"  # Default token URI for Google

    # Create a Credentials object
    cred = Credentials.from_authorized_user_info({
        "client_id": client_id,
        "client_secret": client_secret,
        "refresh_token": refresh_token,
        "token_uri": token_uri
    }, SCOPES)

    print(f"Cred Object: {cred}")
    print(f"Credentials valid: {cred.valid}")
    print(f"Credentials expired: {cred.expired}")


    if not cred or not cred.valid:
        if cred and cred.expired and cred.refresh_token:
            print("refreshing token")
            cred.refresh(Request())
            print("token refreshed")
        else:
            print("recreating token")
            flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
            cred = flow.run_local_server()
            print("token recreated")
            # cred1 = flow.redirect_uri()

        # with open(pickle_file, 'wb') as token:
            # pickle.dump(cred, token)
        with open("token.json", "w") as token:
            token.write(cred.to_json())
    try:
        service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)
        print(API_SERVICE_NAME, 'Cred valid. Service created successfully')
        return service
    except Exception as e:
        print('Unable to connect.')
        print(e)
        return None