diff --git a/src/WAConnection/4.Events.ts b/src/WAConnection/4.Events.ts index e441f61..9c1b1d4 100644 --- a/src/WAConnection/4.Events.ts +++ b/src/WAConnection/4.Events.ts @@ -7,7 +7,6 @@ export class WAConnection extends Base { constructor () { super () - // new messages this.registerCallback(['action', 'add:relay', 'message'], json => { const message = json[2][0][2] as WAMessage diff --git a/src/WAConnection/6.MessagesSend.ts b/src/WAConnection/6.MessagesSend.ts index 4f3495e..f2812eb 100644 --- a/src/WAConnection/6.MessagesSend.ts +++ b/src/WAConnection/6.MessagesSend.ts @@ -109,20 +109,30 @@ export class WAConnection extends Base { // send a query JSON to obtain the url & auth token to upload our media const json = await this.refreshMediaConn () const auth = json.auth // the auth token - const hostname = `https://${json.hosts[0].hostname}${MediaPathMap[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}` - - const urlFetch = await fetch(hostname, { - method: 'POST', - body: body, - headers: { Origin: 'https://web.whatsapp.com' }, - }) - const responseJSON = await urlFetch.json() - if (!responseJSON.url) { - throw new Error('Upload failed got: ' + JSON.stringify(responseJSON)) + + let mediaUrl: string + for (let host of json.hosts) { + const hostname = `https://${host.hostname}${MediaPathMap[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}` + try { + const urlFetch = await fetch(hostname, { + method: 'POST', + body: body, + headers: { Origin: 'https://web.whatsapp.com' }, + }) + mediaUrl = (await urlFetch.json())?.url + + if (mediaUrl) break + else throw new Error (`upload failed`) + } catch (error) { + const isLast = host.hostname === json.hosts[json.hosts.length-1].hostname + this.log (`Error in uploading to ${host}${isLast ? '' : ', retrying...'}`, MessageLogLevel.info) + } } + if (!mediaUrl) throw new Error('Media upload failed on all hosts') + const message = {} message[mediaType] = { - url: responseJSON.url, + url: mediaUrl, mediaKey: mediaKey.toString('base64'), mimetype: options.mimetype, fileEncSha256: fileEncSha256B64,