summaryrefslogtreecommitdiff
path: root/public/src/util.tsx
blob: f083d9f3114b8dc8847c40e9821e75fa3333b166 (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
export function escapeHtml( html: string ) {
  const entityMap = {
    '&': '&',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
    '/': '&#x2F;',
    '`': '&#x60;',
    '=': '&#x3D;'
  };

  return String( html ).replace( /[&<>"'`=\/]/g, ( s ) => {
    return entityMap[s];
  } );
}

export function parseJWT( token: string ) : any {
  const parts = token.split( '.' );
  let encoded = parts[1];
  encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');
  const pad = encoded.length % 4;
  if( pad === 1 )
    throw new Error( 'what the fuck' );
  if( pad > 1 )
    encoded += new Array( 5 - pad ).join( '=' );

  const payload = JSON.parse( atob( encoded ) );
  return payload;
}

export function sizeHumanReadable( size: number, short: boolean = false ) {
  if( size < 1024 )
    return size + (short? 'B' : ' B');
  else if( size < 1024 * 1024 )
    return ( size / 1024 ).toFixed( short? 1: 2 ) + (short? 'K' : ' KB');
  else if( size < 1024 * 1024 * 1024 )
    return ( size / 1024 / 1024 ).toFixed( short? 1 : 2 ) + (short? 'M' : ' MB');
  else
    return ( size / 1024 / 1024 / 1024 ).toFixed( short? 1 : 2 ) + (short? 'G':' GB');
}

export function monthToNumber( month: string ) {
  const months = [
    '',
    'jan',
    'feb',
    'mar',
    'apr',
    'may',
    'jun',
    'jul',
    'aug',
    'sep',
    'oct',
    'nov',
    'dec'
  ];
  return months.indexOf( month.toLowerCase() );
};