// Minimal voip.ms REST client. Docs: https://voip.ms/m/apidocs.php import type { Credentials, Did } from '@shared/types' const ENDPOINT = 'https://voip.ms/api/v1/rest.php' export interface RawSms { id: string date: string // "YYYY-MM-DD HH:MM:SS" in the requested timezone (we ask for UTC) type: string // "1" received, "0" sent did: string contact: string message: string } const FRIENDLY_ERRORS: Record = { invalid_credentials: 'Invalid API username or password. Use the API password set under Main Menu → SOAP & REST/JSON API, not your login password.', missing_credentials: 'Missing API username or password.', ip_not_enabled: "This computer's IP address isn't allowed. Add it under Main Menu → SOAP & REST/JSON API → Enable IP Addresses.", api_not_enabled: 'The API is not enabled on your voip.ms account. Enable it under Main Menu → SOAP & REST/JSON API.', sms_toolong: 'Message is too long.', invalid_dst: 'Invalid destination number.', invalid_did: 'That DID is not valid on your account.', sms_failed: 'voip.ms failed to send the message.' } export class VoipMsError extends Error { constructor(public status: string) { super(FRIENDLY_ERRORS[status] ?? `voip.ms error: ${status}`) } } export class VoipMs { constructor(private creds: Credentials) {} private async call(method: string, params: Record = {}): Promise { const url = new URL(ENDPOINT) url.searchParams.set('api_username', this.creds.username) url.searchParams.set('api_password', this.creds.password) url.searchParams.set('method', method) for (const [k, v] of Object.entries(params)) { if (v !== undefined && v !== '') url.searchParams.set(k, String(v)) } const res = await fetch(url, { signal: AbortSignal.timeout(60_000) }) if (!res.ok) throw new Error(`voip.ms HTTP ${res.status}`) const json = (await res.json()) as { status: string } & T if (json.status !== 'success') throw new VoipMsError(json.status) return json } async getDids(): Promise { const r = await this.call<{ dids: Array> }>('getDIDsInfo') return r.dids.map((d) => ({ did: d.did, description: d.description ?? '', smsEnabled: d.sms_enabled === '1' })) } // Returns [] when voip.ms reports no messages for the range. async getSms(opts: { from: string; to: string; did?: string; limit?: number }): Promise { try { const r = await this.call<{ sms: RawSms[] }>('getSMS', { from: opts.from, to: opts.to, did: opts.did, limit: opts.limit ?? 10000, timezone: 0 }) return r.sms ?? [] } catch (e) { if (e instanceof VoipMsError && e.status === 'no_sms') return [] throw e } } async sendSms(did: string, dst: string, message: string): Promise { const r = await this.call<{ sms: number | string }>('sendSMS', { did, dst, message }) return Number(r.sms) } } // "2024-01-02 03:04:05" (UTC) -> epoch ms export function parseVoipDate(s: string): number { return Date.parse(s.replace(' ', 'T') + 'Z') }