A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal
blob: db3adb435d51df77f262fa8a781d73e3503d8b49 (3909 bytes)[doc][blame][raw]
1
import {state, TOKEN_NAME, ROUTES} from './main.js';3
const 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
}12
export 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
body56
});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
}76
export 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
}84
export function $route(path, { update = true, reload = false } = {}) {85
for(const [key, value] of Object.entries(ROUTES)) {86
const regex = new RegExp(key);87
const match = regex.exec(path);88
if(match !== null) {89
if(!reload) {90
state.tab = value;91
if(value === 'detail') {92
if(state.app.$refs.detail) {93
state.app.$refs.detail.show({ id: match[1] });94
}95
}96
}97
if(update) {98
window.history.pushState(null, null, path);99
}100
if(reload) {101
window.location.reload();102
}103
return;104
}105
}106
state.tab = 'not-found';107
}109
export function duration(time) {110
let seconds = time * 10;111
const hours = Math.floor(seconds / 3600);112
const minutes = Math.floor((seconds - (hours * 3600)) / 60);113
seconds = seconds - (hours * 3600) - (minutes * 60);114
return `${hours > 0 ? hours + ' h ' : ''}${minutes > 0 ? minutes + ' min' : ''}`;115
}