summaryrefslogtreecommitdiff
path: root/moneyjsx/src/user.tsx
blob: 775567021b5ebce1a9a33ba975cfa27620c0aa0d (plain)
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
import $ from 'jquery';

import * as JSX from './jsx';
import * as api from './api';

export interface ChatFile {
  id: string,
  name: string
}

export interface UserSettings {
  uuid: string,
  nickname: string,
  site_prefs: {
    font: string,
    model?: string
  },
  prompt_data: {
    system?: string
  },
  chat_files?: {
    files?: ChatFile[]
  },
  plan: {
    endTime: number,
    plan: string
  }
};

export let is_loggedin = false;
export let settings: UserSettings = null;

let on_prefs_updated: Function = () => {};

export async function onPrefsUpdated( fn: Function ) {
  on_prefs_updated = fn;
}

/**
 * polls settings from the server
**/
export async function updatePrefs() {
  if( !is_loggedin ) {
    return;
  }

  let res = null;
  try {
    res = await fetch( `${api.url}/settings`, {
      method: 'POST',
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify( {
        token: localStorage.getItem( 'session' ),
      } )
    } );

    if( !res.ok ) {
      try {
        const json = await res.json();
        if( json.status == 'nodata' ) {
          localStorage.setItem( 'needs-setup', 'true' );
          if( window.location.pathname != '/first-landing' )
            return JSX.navigate( '/first-landing' );
          else {
            settings = null;
            localStorage.setItem( 'settings', '{}' );
          }
        } else if( json.status != 'ok' ) {
          is_loggedin = false;
          localStorage.clear();
        }

        throw new Error( json.msg );
      } catch( e: any ) {
        throw new Error( "error contacting server" );
      }
    }

    res = await res.json();
  } catch( e: any ) {
    throw new Error( e.message );
  }

  settings = res.userprefs;
  localStorage.setItem( 'settings', JSON.stringify( settings ) );
  on_prefs_updated();
}

/**
 * saves prefs on the server
**/
export async function savePrefs( prefs: any ) {
  const res = await api.post( `update-settings`, { token: localStorage.getItem( 'session' ), prefs } );
  settings = res.userprefs;
  localStorage.setItem( 'settings', JSON.stringify( settings ) );
}

export async function getNotes() {
  const res = await api.post( `get-notes`, { token: localStorage.getItem( 'session' ) } );
  return res.notes;
}

export async function deleteNote( note_id: string ) {
  await api.post( `delete-note`, { token: localStorage.getItem( 'session' ), noteId: note_id } );
}

export async function deleteAllNotes() {
  await api.post( `delete-notes`, { token: localStorage.getItem( 'session' ) } );
}

export async function getTokens() {
  const res = await api.post( `get-tokens`, { token: localStorage.getItem( 'session' ) } );
  return res.tokens;
}

export async function createToken() {
  const res = await api.post( `create-token`, { token: localStorage.getItem( 'session' ) } );
  return res.token;
}

export async function deleteToken( token_id: number ) {
  await api.post( `delete-token`, { id: token_id, token: localStorage.getItem( 'session' ) } );
}

export async function deleteAllTokens() {
  await api.post( `delete-tokens`, { token: localStorage.getItem( 'session' ) } );
}

export async function createChat() {
  const res = await api.post( `create-chat`, { token: localStorage.getItem( 'session' ) } );
  return res;
}

export async function deleteChat( chatId: string ) {
  await api.post( `delete-chat`, { chatId, token: localStorage.getItem( 'session' ) } );
}

export async function downloadAllData() {
  let res = await fetch( `${api.url}/getalldata`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify( { token: localStorage.getItem( 'session' ) } )
  } );

  let contentType = res.headers.get( 'content-type' );
  if( contentType && contentType.includes( 'application/zip' ) ) {
    let blob = await res.blob();
    let url = window.URL.createObjectURL( blob );
    const a = <a style="display:none" href={url} download="userdata.zip"/>;
    $( 'body' ).append( a );
    a.onclick = ( e: Event ) => { e.stopPropagation(); };
    a.click();
    window.URL.revokeObjectURL( url );
  }
  else {
    let json = null;
    try {
      json = await res.json();
    } catch( e: any ) {
      throw new Error( "Error contacting server" );
    }

    if( json.status != 'ok' )
      throw new Error( json.msg );
  }
}

export async function invalidateAllSessions() {
  const res = await api.post( `invalidate-all-sessions`, { token: localStorage.getItem( 'session' ) } );
  localStorage.setItem( 'session', res.session );
}

function updateFont() {
  const style = document.documentElement.style;
  if( settings.site_prefs && settings.site_prefs.font != null )
    style.setProperty( "--site-font", settings.site_prefs.font );
}

async function onNavigateAsync() {
  try {
    if( is_loggedin ) {
      if( localStorage.getItem( 'needs-setup' ) && window.location.pathname !== "/first-landing" )
        setTimeout( () => JSX.navigate( "/first-landing" ) );
      else
        await updatePrefs();
      // update it again in case it changed in prefs
      updateFont();
    }

    await api.updateModels();
  } catch( e: any ) {
    // todo: display message box w error
    console.log( e );
  }
}

export function onNavigate() {
  settings = JSON.parse( localStorage.getItem( 'settings' ) || '{}' ) as UserSettings;
  api.parseModels();
  if( localStorage.getItem( 'session' ) )
    is_loggedin = true;

  if( is_loggedin )
    updateFont();

  onNavigateAsync();
}

/**
 * returns true on success, error message on failure
**/
export async function sendLoginLink( email: string ) {
  let res = null;
  try {
    res = await api.post( `send-login-link`, { email } );
  } catch( e: any ) {
    return e.message;
  }

  return true;
}

export async function onLogin( code: string ) {
  let json = null;
  try {
    const res = await fetch( `${api.url}/login?token=${code}` );
    json = await res.json();
  } catch( e: any ) {
    throw new Error( "error contacting server" );
  }

  if( json.status != 'ok' )
    throw new Error( json.msg );

  localStorage.setItem( 'session', json.session );
  is_loggedin = true;

  try {
    await updatePrefs();
  } catch( e: any ) {
    throw new Error( e.msg );
  }
}

export async function logout() {
  if( !is_loggedin )
    return;

  try {
    await api.post( 'invalidate-session', { token: localStorage.getItem( 'session' ) } );
  } catch( e: any ) {}

  localStorage.clear();
  is_loggedin = false;
  JSX.navigate( '/' );
  window.location.reload();
}