so://phie

verbal

A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal

blob: 5e87242e5849092eebd0867769f0cdc3733ee898 (3118 bytes)[doc][blame][raw]

1import {state, TOKEN_NAME} from './main.js';

2

3const ltr = (parts, values) => {

4 let string = '';

5 for(let i = 0; i < parts.length; i++) {

6 string += parts[i];

7 string += values[i] ?? '';

8 }

9 return string;

10}

11

12export function http(parts, ...values) {

13 const line = ltr(parts, values).trim();

14 const regex = /^(\w+)::([\w\/.]*)$/;

15 const [, method, path] = line.match(regex) ?? [];

16 return (query) => {

17 if(query !== undefined) {

18 query = JSON.parse(JSON.stringify(query));

19 }

20 return new Promise(async (resolve, reject) => {

21 try {

22 const headers = {

23 'content-type': 'application/json',

24 }

25 const token = localStorage.getItem(TOKEN_NAME);

26 if(token) {

27 headers['verbal-token'] = token;

28 }

29 let body = null;

30 let params = '';

31 if(method === 'get' || method === 'head') {

32 if(query !== undefined && query !== null) {

33 for(const [key, value] of Object.entries(query)) {

34 if(Array.isArray(value)) {

35 delete query[key];

36 for(let i = 0; i < value.length; i++) {

37 query[`${key}[${i}]`] = value[i];

38 }

39 }

40 else if(value === null) {

41 delete query[key];

42 }

43 }

44 }

45 params = '?' + new URLSearchParams(query).toString();

46 params = params.replaceAll(/%5B/g, '[');

47 params = params.replaceAll(/%5D/g, ']');

48 }

49 else {

50 body = JSON.stringify(query);

51 }

52 const response = await fetch(window.location.origin + path + params, {

53 method,

54 headers,

55 body

56 });

57 const json = await response.json();

58 const {ok, data, error} = json;

59 if(ok === undefined) {

60 resolve(json);

61 return;

62 }

63 if(!ok) {

64 reject(error.message);

65 return;

66 }

67 resolve(data);

68 }

69 catch(error) {

70 reject(error);

71 }

72 });

73 };

74}

75

76export function $lang(id, ...args) {

77 let message = state.locale[state.account?.language ?? 'en'][id];

78 for(const i in args) {

79 message = message.replaceAll(`{${i}}`, args[i]);

80 }

81 return message;

82}

83

84export function duration(time) {

85 let seconds = time * 10;

86 const hours = Math.floor(seconds / 3600);

87 const minutes = Math.floor((seconds - (hours * 3600)) / 60);

88 seconds = seconds - (hours * 3600) - (minutes * 60);

89 return `${hours > 0 ? hours + ' h ' : ''}${minutes} min`;

90}