File size: 9,990 Bytes
3943768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import json
import os
import sqlite3
import uuid

from enums import LangChainMode


def set_userid(db1s, requests_state1, get_userid_auth, guest_name=''):
    force = requests_state1 and 'username' in requests_state1
    db1 = db1s[LangChainMode.MY_DATA.value]
    assert db1 is not None and len(db1) == length_db1(), "%s %s" % (len(db1), length_db1())
    if db1[1] is None or force:
        db1[1] = get_userid_auth(requests_state1, id0=db1[1])
    if force or len(db1) == length_db1() and not db1[2]:
        username1 = None
        if 'username' in requests_state1:
            username1 = requests_state1['username']
            if username1 == guest_name:
                username1 += ':' + str(uuid.uuid4())
                requests_state1['username'] = username1
        db1[2] = username1


def set_userid_direct(db1s, userid, username):
    db1 = db1s[LangChainMode.MY_DATA.value]
    db1[1] = userid
    db1[2] = username


def get_userid_direct(db1s):
    return db1s[LangChainMode.MY_DATA.value][1] if db1s is not None else ''


def get_username_direct(db1s):
    return db1s[LangChainMode.MY_DATA.value][2] if db1s is not None else ''


def get_dbid(db1):
    return db1[1]


def set_dbid(db1):
    # can only call this after function called so for specific user, not in gr.State() that occurs during app init
    assert db1 is not None and len(db1) == length_db1()
    if db1[1] is None:
        #  uuid in db is used as user ID
        db1[1] = str(uuid.uuid4())


def length_db1():
    # For MyData:
    # 0: db
    # 1: userid and dbid
    # 2: username

    # For others:
    # 0: db
    # 1: dbid
    # 2: None
    return 3


def create_table(auth_filename):
    conn = sqlite3.connect(auth_filename)
    cursor = conn.cursor()

    # Create table if not exists
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS Users (
        username VARCHAR(255) PRIMARY KEY,
        data TEXT
    );
    """)
    conn.commit()
    conn.close()


def fetch_user(auth_filename, username, verbose=False):
    # Connect to an SQLite database (change the database path as necessary)
    if auth_filename.endswith('.json'):
        json_filename = auth_filename
        db_filename = auth_filename[:-4] + '.db'
    else:
        assert auth_filename.endswith('.db')
        db_filename = auth_filename
        json_filename = auth_filename[:-3] + '.json'

    if os.path.isfile(db_filename) and os.path.getsize(db_filename) == 0:
        os.remove(db_filename)
    if os.path.isfile(json_filename) and os.path.getsize(json_filename) == 0:
        os.remove(json_filename)

    if os.path.isfile(json_filename) and not os.path.isfile(db_filename):
        # then make, one-time migration
        with open(json_filename, 'rt') as f:
            auth_dict = json.load(f)
        create_table(db_filename)
        upsert_auth_dict(db_filename, auth_dict, verbose=verbose)
        # Slow way:
        # [upsert_user(db_filename, username1, auth_dict[username1]) for username1 in auth_dict]
    elif not os.path.isfile(db_filename):
        create_table(db_filename)

    if username in [None, '']:
        return {}

    conn = sqlite3.connect(db_filename)
    cursor = conn.cursor()

    try:
        # Prepare SQL query to fetch user data for a given username
        cursor.execute("SELECT data FROM Users WHERE username = ?", (username,))

        # Fetch the result
        result = cursor.fetchone()

        if result:
            # Deserialize the JSON string to a Python dictionary
            user_details = json.loads(result[0])
            assert isinstance(user_details, dict)
            return {username: user_details}
        else:
            return {}
    except Exception as e:
        print(f"An error occurred: {e}")
        return {}
    finally:
        # Close the database connection
        conn.close()


def upsert_user(db_filename, username, user_details, verbose=False):
    # Connect to the SQLite database
    conn = sqlite3.connect(db_filename)
    cursor = conn.cursor()

    # Serialize the user_details dictionary to a JSON string
    data_string = json.dumps(user_details)

    # Prepare the UPSERT SQL command
    sql_command = """
    INSERT INTO Users (username, data) 
    VALUES (?, ?)
    ON CONFLICT(username) 
    DO UPDATE SET data = excluded.data;
    """

    try:
        # Execute the UPSERT command
        cursor.execute(sql_command, (username, data_string))
        conn.commit()  # Commit the changes to the database
        if verbose:
            print(f"User '{username}' updated or inserted successfully.")
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # Close the database connection
        conn.close()


def upsert_auth_dict(db_filename, auth_dict, verbose=False):
    # Connect to the SQLite database
    conn = sqlite3.connect(db_filename)
    cursor = conn.cursor()

    # Serialize the user_details dictionary to a JSON string
    try:
        for username, user_details in auth_dict.items():
            data_string = json.dumps(user_details)

            # Prepare the UPSERT SQL command
            sql_command = """
            INSERT INTO Users (username, data) 
            VALUES (?, ?)
            ON CONFLICT(username) 
            DO UPDATE SET data = excluded.data;
            """

            # Execute the UPSERT command
            cursor.execute(sql_command, (username, data_string))
            if verbose:
                print(f"User '{username}' updated or inserted successfully.")
        conn.commit()  # Commit the changes to the database
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # Close the database connection
        conn.close()


def get_all_usernames(auth_filename):
    assert auth_filename.endswith('.db'), "Bad auth_filename: %s" % auth_filename
    if not os.path.isfile(auth_filename):
        return []

    conn = sqlite3.connect(auth_filename)
    cursor = conn.cursor()

    try:
        cursor.execute("SELECT username FROM Users")
        usernames = [row[0] for row in cursor.fetchall()]
        return usernames
    except Exception as e:
        print(f"An error occurred: {e}")
        return []
    finally:
        conn.close()


def merge_dicts(original, updates):
    """
    Merge updates into the original dictionary. If a key points to a list, append the values.
    If a key points to a dictionary, merge the dictionaries.
    """
    for key, value in updates.items():
        if key in original:
            if isinstance(original[key], list) and isinstance(value, list):
                original[key].extend(value)
            elif isinstance(original[key], dict) and isinstance(value, dict):
                original[key] = merge_dicts(original[key], value)
            else:
                original[key] = value
        else:
            original[key] = value
    return original


def append_to_users_data(auth_filename, updates, verbose=False):
    assert auth_filename.endswith('.db'), "Bad auth_filename: %s" % auth_filename
    db_filename = auth_filename
    assert os.path.isfile(db_filename), "Database file %s does not exist." % db_filename

    conn = sqlite3.connect(db_filename)
    cursor = conn.cursor()

    try:
        # Fetch all usernames and their data
        cursor.execute("SELECT username, data FROM Users")
        users = cursor.fetchall()

        for username, data_string in users:
            user_details = json.loads(data_string)

            # Merge updates into user details
            user_details = merge_dicts(user_details, updates)

            # Serialize the updated user_details dictionary to a JSON string
            updated_data_string = json.dumps(user_details)

            # Prepare the UPSERT SQL command
            sql_command = """
            INSERT INTO Users (username, data)
            VALUES (?, ?)
            ON CONFLICT(username)
            DO UPDATE SET data = excluded.data;
            """

            # Execute the UPSERT command
            cursor.execute(sql_command, (username, updated_data_string))
            if verbose:
                print(f"User '{username}' updated successfully.")

        conn.commit()  # Commit the changes to the database
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        conn.close()


def append_to_user_data(auth_filename, username, updates, verbose=False):
    assert auth_filename.endswith('.db'), "Bad auth_filename: %s" % auth_filename
    db_filename = auth_filename
    assert os.path.isfile(db_filename), "Database file %s does not exist." % db_filename

    conn = sqlite3.connect(db_filename)
    cursor = conn.cursor()

    try:
        # Fetch the user data for the specified username
        cursor.execute("SELECT data FROM Users WHERE username = ?", (username,))
        user_data = cursor.fetchone()

        if not user_data:
            # Create new user details if user does not exist
            user_details = updates
            if verbose:
                print(f"User '{username}' does not exist in the database. Creating new user.")
        else:
            user_details = json.loads(user_data[0])
            # Merge updates into user details
            user_details = merge_dicts(user_details, updates)

        # Serialize the updated user_details dictionary to a JSON string
        updated_data_string = json.dumps(user_details)

        # Prepare the UPSERT SQL command
        sql_command = """
        INSERT INTO Users (username, data)
        VALUES (?, ?)
        ON CONFLICT(username)
        DO UPDATE SET data = excluded.data;
        """

        # Execute the UPSERT command
        cursor.execute(sql_command, (username, updated_data_string))
        if verbose:
            print(f"User '{username}' updated successfully.")

        conn.commit()  # Commit the changes to the database
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        conn.close()