Passed
Push — main ( 55bb28...245da3 )
by Bartosz
02:31 queued 01:14
created

handle_creds()   A

Complexity

Conditions 5

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 10
rs 9.3333
c 0
b 0
f 0
cc 5
nop 2
1
import pandas as pd
2
import os.path
3
from googleapiclient.discovery import build
4
from google_auth_oauthlib.flow import InstalledAppFlow
5
from google.auth.transport.requests import Request
6
from google.oauth2.credentials import Credentials
7
import json
8
from modules import get_settings
9
10
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
11
SAMPLE_RANGE_NAME = 'A1:AA68'
12
CREDENTIALS_FILE = 'pull_config/credentials/client_secret.com.json '
13
14
SAMPLE_SPREADSHEET_ID_input = get_settings.get_settings("EXCEL_ID")
15
16
17
def handle_creds(creds, token):
18
    if creds and creds.expired and creds.refresh_token:
19
        creds.refresh(Request())
20
    else:
21
        flow = InstalledAppFlow.from_client_secrets_file(
22
            CREDENTIALS_FILE, SCOPES)
23
        creds = flow.run_local_server(port=0)
24
    # Save the credentials for the next run
25
    with open(token, 'w') as token:
26
        token.write(creds.to_json())
27
28
29
def import_from_sheets():
30
    """
31
32
    :return:
33
    :rtype:
34
    """
35
    token = "token.json"
36
    creds = None
37
    # The file token.json stores the user's access and refresh tokens, and is
38
    # created automatically when the authorization flow completes for the first time
39
    if os.path.exists(token):
40
        creds = Credentials.from_authorized_user_file(token, SCOPES)
41
    # If there are no (valid) credentials available, let the user log in
42
    if not creds or not creds.valid:
43
        handle_creds(creds, token)
44
45
    service = build('sheets', 'v4', credentials=creds)
46
47
    # Call the Sheets API
48
    sheet = service.spreadsheets()
49
    result_input = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID_input, range=SAMPLE_RANGE_NAME).execute()
50
    values_input = result_input.get('values', [])
51
52
    if not values_input:
53
        print(f"[{get_config.__name__}]: No data found.")
54
    return values_input
55
56
57
def create_trigger_list(triggers) -> list:
58
    triggers_list = []
59
    for row in triggers.itertuples(index=False):
60
        help_ser = pd.Series(row)
61
        help_ser = help_ser[~help_ser.isna()]
62
        # Drop empty strings
63
        help_ser = pd.Series(filter(None, help_ser))
64
        # Copy strings with spaces without keeping them
65
        for trigger in help_ser:
66
            trigger_nospace = trigger.replace(' ', '')
67
            help_ser = help_ser.append(pd.Series(trigger_nospace))
68
        help_ser = help_ser.drop_duplicates()
69
        triggers_list.append(help_ser)
70
    return triggers_list
71
72
73
def create_output(monsters_df) -> dict:
74
    types = {'id': [4, 3, 2, 1, 0], 'label': ["Common", "Event0", "Event1", "Legendary", "Rare"]}
75
    types_df = pd.DataFrame(data=types)
76
    total_milestones = {"Rare Spotter": [150], "tescior": [151], "Pepega Spotter": [1000], "Pog Spotter": [2000],
77
                        "Pogmare Spotter": [3000],
78
                        "Legendary Spotter": [4000], "Mythic Spotter": [5000]}
79
    total_milestones_df = pd.DataFrame(data=total_milestones)
80
    common_milestones = {"Common Killer": [100], "Common Slayer": [150]}
81
    common_milestones_df = pd.DataFrame(data=common_milestones)
82
    json_final = {'total_milestones': total_milestones_df, 'common_milestones': common_milestones_df,
83
                  'types': types_df, 'commands': monsters_df}
84
    # convert dataframes into dictionaries
85
    data_dict = {
86
        key: json_final[key].to_dict(orient='records')
87
        for key in json_final
88
    }
89
    return data_dict
90
91
92
def create_trigger_structure(triggers_list):
93
    triggers_def = []
94
    for i in triggers_list:
95
        triggers_def.append(list(i))
96
    triggers_def_series = pd.Series(triggers_def)
97
    return triggers_def_series
98
99
100
def get_config():
101
    pd.set_option('mode.chained_assignment', None)
102
    print(f"[{get_config.__name__}]: Loading data")
103
    values_input = import_from_sheets()
104
    df = pd.DataFrame(values_input[1:], columns=values_input[0])
105
106
    print(f"[{get_config.__name__}]: Transforming data")
107
    monsters_df = df[["name", "type"]]
108
    monsters_df["type"] = pd.to_numeric(df["type"])
109
110
    triggers = df.drop(['name', 'role', 'type', 'id'], axis=1)
111
    triggers = triggers.applymap(lambda s: s.lower() if type(s) == str else s)
112
113
    triggers_list = create_trigger_list(triggers)
114
115
    print(f"[{get_config.__name__}]: Creating trigger structure")
116
    triggers_def = create_trigger_structure(triggers_list)
117
    monsters_df.insert(loc=0, column='triggers', value=triggers_def)
118
119
    print(f"[{get_config.__name__}]: Creating output")
120
    data_dict = create_output(monsters_df)
121
122
    # write to disk
123
    with open('server_files/config.json', 'w', encoding='utf8') as f:
124
        json.dump(data_dict, f, indent=4, ensure_ascii=False, sort_keys=False)
125
    print(f"[{get_config.__name__}]: .json saved")
126
127
128
def main():
129
    get_config()
130
131
132
if __name__ == "__main__":
133
    main()
134