evolution-api icon indicating copy to clipboard operation
evolution-api copied to clipboard

[PT][BUG] Como descriptografar o arquivo de audio .ENC que recebemos por API?

Open davidalpa opened this issue 2 years ago • 6 comments

Título: Como descriptografar o arquivo de audio .ENC que recebemos por API?

Descrição:

Estou tendo dificuldade pra entender como descritografa o arquivo de audio .ENC que recebemos por API. Estou tentando pelo N8N.

davidalpa avatar Mar 10 '24 14:03 davidalpa

@davidalpa tem um endpoint no postman que você obtém o base64 do arquivo, só enviar o ID da mensagem, da uma procurada la que vai encontrar

judsonjuniorr avatar Mar 12 '24 12:03 judsonjuniorr

Muito obrigado, não tinha visto ! Se alguem estiver lendo isso aqui com a mesma dúvida é só procurar por 'Get Base64 From Media Message' no postman

davidalpa avatar Mar 16 '24 20:03 davidalpa

@davidalpa @judsonjuniorr olhei no postman o POST mas não consegui reproduzir aqui.. podem me ajudar?

No postman diz:

{{baseUrl}}/chat/getBase64FromMediaMessage/{instanceName}
{
  "message": {
    "key": {}
  },
  "convertToMp4": "<boolean>"
} 

Mas não estou certo de como deve ir o valor em "key". Enviando {"message":{"key":"021F8080D2C85E061F...BD"},"convertToMp4":true} obtenho um 400 - Bad Request.

Podem me ajudar por favor com esse parametro?

Obrigado!

TiagoGouvea avatar Apr 10 '24 16:04 TiagoGouvea

Consegui botar pra funcionar... dai pra quem precisar, segue o código:

async function audioToText(messageId) {
   const __dirname = path.resolve();
   const filePath = path.join(__dirname, 'audio_'+messageId+'.m4a');
   const msg = { id: messageId, description: messageId };
   const b64 = await getBase64FromMediaMessage(msg);
   saveBase64ToFile(b64.base64, filePath);
   return text;
}


export async function getBase64FromMediaMessage(
   message,
) {
    const url = `${evolutionBaseUrl}/chat/getBase64FromMediaMessage/${instanceName}`;
    const options = {
        method: 'POST',
        headers: {
            accept: 'application/json',
            'content-type': 'application/json',
            apiKey,
        },
        body: JSON.stringify({
            "message": {
                "key": message
            },
            convertToMp4: true,
        }),
    };

    try {
        const response = await fetch(url, options);
        if (response.ok) {
            const data = await response.json();
            return data; 
        } else {
            console.log(`Error with status code: ${response.status}`);
            return false;
        }
    } catch (error) {
        console.log('Error converting message', error);
        return false;
    }
}

export function saveBase64ToFile(base64Data, filePath) {
    const bufferData = Buffer.from(base64Data, 'base64');
    fs.writeFileSync(filePath, bufferData);
}

Se tiver alguma dúvida me pergunte ai!

TiagoGouvea avatar Apr 11 '24 09:04 TiagoGouvea

E como pegar você está pegando o id da mensagem, @TiagoGouvea ?

otaviolube avatar Jun 09 '24 18:06 otaviolube

@otaviolube o id da mensagem você já deve ter.. toda mensagem tem um id. Seja recebendo por rabbit, websocket, webhook.

Um exemplo de uma mensagem, o id está em data.key.id.

{
  event: 'messages.upsert',
  instance: 'rafael-santos',
  data: {
    key: {
      remoteJid: '[email protected]',
      fromMe: false,
      id: '795FC975E03071654F24175885AD9C70'
    },
    pushName: 'Carol',
    message: {
      messageContextInfo: {
        deviceListMetadata: {
          senderKeyHash: 'ZU2iQuvdwaY1gA==',
          senderTimestamp: '1717777496',
          recipientKeyHash: 'OCuSZOKpngIYqw==',
          recipientTimestamp: '1717932050'
        },
        deviceListMetadataVersion: 2
      },
      reactionMessage: {
        key: {
          remoteJid: '[email protected]',
          fromMe: true,
          id: 'BAE5497C685E6147'
        },
        text: '❤️',
        senderTimestampMs: '1717980660558'
      }
    },
    messageType: 'reactionMessage',
    messageTimestamp: 1717980660,
    owner: 'rafael-santos',
    source: 'android'
  },
  server_url: 'http://localhost:8080',
  date_time: '2024-06-09T21:51:00.841Z',
  sender: '[email protected]',
  apikey: 'zg08v6q0iqtvjyarbhig'
}

Me diga se conseguiu achar ai.

TiagoGouvea avatar Jun 10 '24 11:06 TiagoGouvea