|
| 1 | +import { input } from '@inquirer/prompts' |
| 2 | +import { createLogger } from '../../../nest/app/logger/logger.js' |
| 3 | +import { promiseWithSpinner } from '../utils/utils.js' |
| 4 | +import type { RuntimeOptions } from '../types.js' |
| 5 | + |
| 6 | +const logger = createLogger('Client:Push') |
| 7 | + |
| 8 | +/** |
| 9 | + * Response from the /v1/register endpoint |
| 10 | + */ |
| 11 | +interface RegisterResponse { |
| 12 | + ucan: string |
| 13 | +} |
| 14 | + |
| 15 | +/** |
| 16 | + * Error response from push endpoints |
| 17 | + */ |
| 18 | +interface PushErrorResponse { |
| 19 | + error: string |
| 20 | + code?: string |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Type guard for RegisterResponse |
| 25 | + */ |
| 26 | +const isRegisterResponse = (data: unknown): data is RegisterResponse => |
| 27 | + typeof data === 'object' && |
| 28 | + data !== null && |
| 29 | + 'ucan' in data && |
| 30 | + typeof (data as { ucan: unknown }).ucan === 'string' |
| 31 | + |
| 32 | +/** |
| 33 | + * Type guard for PushErrorResponse |
| 34 | + */ |
| 35 | +const isPushErrorResponse = (data: unknown): data is PushErrorResponse => |
| 36 | + typeof data === 'object' && |
| 37 | + data !== null && |
| 38 | + 'error' in data && |
| 39 | + typeof (data as { error: unknown }).error === 'string' |
| 40 | + |
| 41 | +/** |
| 42 | + * Build the base URL for QPS endpoints |
| 43 | + */ |
| 44 | +const getBaseUrl = (options: RuntimeOptions): string => { |
| 45 | + const hostname = options.hostname ?? 'localhost' |
| 46 | + const port = options.port ?? '3000' |
| 47 | + return `http://${hostname}:${port}` |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Register a device and get a UCAN token |
| 52 | + */ |
| 53 | +export const registerDevice = async ( |
| 54 | + options: RuntimeOptions, |
| 55 | +): Promise<string | undefined> => { |
| 56 | + const deviceToken = await input({ |
| 57 | + message: 'Enter the FCM device token:', |
| 58 | + validate: (value: string | undefined) => { |
| 59 | + if (value == null || value === '') { |
| 60 | + return 'Device token is required' |
| 61 | + } |
| 62 | + return true |
| 63 | + }, |
| 64 | + }) |
| 65 | + |
| 66 | + const bundleId = await input({ |
| 67 | + message: 'Enter the app bundle ID:', |
| 68 | + default: 'com.tryquiet.quiet', |
| 69 | + validate: (value: string | undefined) => { |
| 70 | + if (value == null || value === '') { |
| 71 | + return 'Bundle ID is required' |
| 72 | + } |
| 73 | + return true |
| 74 | + }, |
| 75 | + }) |
| 76 | + |
| 77 | + const baseUrl = getBaseUrl(options) |
| 78 | + const url = `${baseUrl}/v1/register` |
| 79 | + |
| 80 | + const result = await promiseWithSpinner( |
| 81 | + async () => { |
| 82 | + const response = await fetch(url, { |
| 83 | + method: 'POST', |
| 84 | + headers: { |
| 85 | + 'Content-Type': 'application/json', |
| 86 | + }, |
| 87 | + body: JSON.stringify({ |
| 88 | + deviceToken, |
| 89 | + bundleId, |
| 90 | + }), |
| 91 | + }) |
| 92 | + |
| 93 | + if (!response.ok) { |
| 94 | + const errorBody: unknown = await response.json() |
| 95 | + const errorMessage = isPushErrorResponse(errorBody) |
| 96 | + ? errorBody.error |
| 97 | + : response.statusText |
| 98 | + throw new Error(`Registration failed: ${errorMessage}`) |
| 99 | + } |
| 100 | + |
| 101 | + const data: unknown = await response.json() |
| 102 | + if (!isRegisterResponse(data)) { |
| 103 | + throw new Error('Invalid response format from server') |
| 104 | + } |
| 105 | + return data.ucan |
| 106 | + }, |
| 107 | + 'Registering device...', |
| 108 | + 'Device registered successfully!', |
| 109 | + 'Failed to register device', |
| 110 | + ) |
| 111 | + |
| 112 | + if (result != null) { |
| 113 | + logger.log(`UCAN Token:\n${result}`) |
| 114 | + return result |
| 115 | + } |
| 116 | + |
| 117 | + return undefined |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Send a push notification using a UCAN token |
| 122 | + */ |
| 123 | +export const sendPushNotification = async ( |
| 124 | + options: RuntimeOptions, |
| 125 | + existingUcan?: string, |
| 126 | +): Promise<boolean> => { |
| 127 | + const ucanInput = await input({ |
| 128 | + message: 'Enter the UCAN token:', |
| 129 | + default: existingUcan, |
| 130 | + validate: (value: string | undefined) => { |
| 131 | + if (value == null || value.trim() === '') { |
| 132 | + return 'UCAN token is required' |
| 133 | + } |
| 134 | + return true |
| 135 | + }, |
| 136 | + }) |
| 137 | + // Trim whitespace and remove any newlines that might have been introduced |
| 138 | + const ucan = ucanInput.trim().replace(/\s+/g, '') |
| 139 | + |
| 140 | + const title = await input({ |
| 141 | + message: 'Enter notification title (optional, press Enter to skip):', |
| 142 | + default: undefined, |
| 143 | + }) |
| 144 | + |
| 145 | + const body = await input({ |
| 146 | + message: 'Enter notification body (optional, press Enter to skip):', |
| 147 | + default: undefined, |
| 148 | + }) |
| 149 | + |
| 150 | + const dataInput = await input({ |
| 151 | + message: |
| 152 | + 'Enter custom data as JSON (optional, press Enter to skip, e.g., {"key":"value"}):', |
| 153 | + default: undefined, |
| 154 | + validate: (value: string | undefined) => { |
| 155 | + if (value == null || value === '') { |
| 156 | + return true |
| 157 | + } |
| 158 | + try { |
| 159 | + JSON.parse(value) |
| 160 | + return true |
| 161 | + } catch { |
| 162 | + return 'Invalid JSON format' |
| 163 | + } |
| 164 | + }, |
| 165 | + }) |
| 166 | + |
| 167 | + const baseUrl = getBaseUrl(options) |
| 168 | + const url = `${baseUrl}/v1/push` |
| 169 | + |
| 170 | + // Build request body |
| 171 | + const requestBody: { |
| 172 | + ucan: string |
| 173 | + title?: string |
| 174 | + body?: string |
| 175 | + data?: Record<string, string> |
| 176 | + } = { ucan } |
| 177 | + |
| 178 | + if (title !== '') { |
| 179 | + requestBody.title = title |
| 180 | + } |
| 181 | + if (body !== '') { |
| 182 | + requestBody.body = body |
| 183 | + } |
| 184 | + if (dataInput !== '') { |
| 185 | + const parsed: unknown = JSON.parse(dataInput) |
| 186 | + requestBody.data = parsed as Record<string, string> |
| 187 | + } |
| 188 | + |
| 189 | + const result = await promiseWithSpinner( |
| 190 | + async () => { |
| 191 | + const response = await fetch(url, { |
| 192 | + method: 'POST', |
| 193 | + headers: { |
| 194 | + 'Content-Type': 'application/json', |
| 195 | + }, |
| 196 | + body: JSON.stringify(requestBody), |
| 197 | + }) |
| 198 | + |
| 199 | + if (!response.ok) { |
| 200 | + let errorMessage = response.statusText |
| 201 | + try { |
| 202 | + const errorBody: unknown = await response.json() |
| 203 | + if (isPushErrorResponse(errorBody)) { |
| 204 | + ;({ error: errorMessage } = errorBody) |
| 205 | + } |
| 206 | + } catch { |
| 207 | + // Response might not be JSON |
| 208 | + } |
| 209 | + |
| 210 | + if (response.status === 400) { |
| 211 | + throw new Error(`Invalid UCAN token: ${errorMessage}`) |
| 212 | + } else if (response.status === 410) { |
| 213 | + throw new Error(`Device token is no longer valid: ${errorMessage}`) |
| 214 | + } else { |
| 215 | + throw new Error(`Push notification failed: ${errorMessage}`) |
| 216 | + } |
| 217 | + } |
| 218 | + |
| 219 | + return true |
| 220 | + }, |
| 221 | + 'Sending push notification...', |
| 222 | + 'Push notification sent successfully!', |
| 223 | + 'Failed to send push notification', |
| 224 | + ) |
| 225 | + |
| 226 | + return result === true |
| 227 | +} |
0 commit comments