273 lines
8.7 KiB
JavaScript
273 lines
8.7 KiB
JavaScript
let currentPostData = {};
|
|
let authToken = null;
|
|
let negocios_id = null;
|
|
let negocios_nome = null;
|
|
let user_id = null;
|
|
let expires = null;
|
|
|
|
// URL base da API do Bubble no Launchr
|
|
const API_URL = 'https://launchr.com.br/api/1.1/wf';
|
|
|
|
// Recuperar o token e informações armazenadas ao iniciar a extensão
|
|
chrome.storage.local.get(['authToken', 'negocios_id', 'negocios_nome', 'user_id', 'expires'], (result) => {
|
|
if (result.authToken) {
|
|
authToken = result.authToken;
|
|
negocios_id = result.negocios_id;
|
|
negocios_nome = result.negocios_nome;
|
|
user_id = result.user_id;
|
|
expires = result.expires;
|
|
}
|
|
});
|
|
|
|
// Função para lidar com erros de autenticação
|
|
function handleAuthError() {
|
|
authToken = null;
|
|
chrome.storage.local.remove(
|
|
['authToken', 'negocios_id', 'negocios_nome', 'user_id', 'expires'],
|
|
() => {
|
|
console.log('Token removido devido a erro de autenticação');
|
|
}
|
|
);
|
|
}
|
|
|
|
// Listener para mensagens
|
|
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|
if (request.action === 'storePostData') {
|
|
currentPostData = request.data || {};
|
|
sendResponse({ success: true });
|
|
} else if (request.action === 'getPostData') {
|
|
sendResponse({ data: currentPostData });
|
|
} else if (request.action === 'savePost') {
|
|
const postDataToSave = request.data;
|
|
let responseSent = false;
|
|
|
|
if (!postDataToSave) {
|
|
sendResponse({ success: false, error: 'Dados do post não fornecidos.' });
|
|
return;
|
|
}
|
|
|
|
if (!authToken) {
|
|
handleAuthError();
|
|
sendResponse({ success: false, error: 'Usuário não autenticado. Faça login novamente.' });
|
|
return true;
|
|
}
|
|
|
|
const dataToSend = {
|
|
content: postDataToSave.content,
|
|
author: postDataToSave.author,
|
|
authorProfileLink: postDataToSave.authorProfileLink,
|
|
date: postDataToSave.date,
|
|
postLink: postDataToSave.postLink,
|
|
category: postDataToSave.category,
|
|
user_id: user_id,
|
|
negocios_id: negocios_id
|
|
};
|
|
|
|
fetch(`${API_URL}/novo_swipe_file`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': authToken
|
|
},
|
|
body: JSON.stringify(dataToSend)
|
|
})
|
|
.then(response => {
|
|
if (response.ok) {
|
|
return response.json();
|
|
} else if (response.status === 401) {
|
|
handleAuthError();
|
|
if (!responseSent) {
|
|
sendResponse({ success: false, error: 'Token expirado ou inválido. Faça login novamente.' });
|
|
responseSent = true;
|
|
}
|
|
throw new Error('Token inválido ou expirado.');
|
|
} else {
|
|
return response.json().then(data => {
|
|
if (!responseSent) {
|
|
sendResponse({ success: false, error: data.message || 'Erro ao salvar o post.' });
|
|
responseSent = true;
|
|
}
|
|
throw new Error(data.message || 'Erro na requisição.');
|
|
});
|
|
}
|
|
})
|
|
.then(data => {
|
|
console.log('Post salvo com sucesso:', data);
|
|
if (!responseSent) {
|
|
sendResponse({ success: true });
|
|
responseSent = true;
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Erro ao salvar o post:', error);
|
|
if (!responseSent) {
|
|
sendResponse({ success: false, error: 'Erro ao salvar o post.' });
|
|
responseSent = true;
|
|
}
|
|
});
|
|
|
|
return true;
|
|
} else if (request.action === 'login') {
|
|
console.log('Iniciando o processo de login...');
|
|
const { email, password } = request.data || {};
|
|
let responseSent = false;
|
|
|
|
if (!email || !password) {
|
|
sendResponse({ success: false, error: 'E-mail ou senha não fornecidos.' });
|
|
console.log('Email ou senha não fornecidos');
|
|
return;
|
|
}
|
|
|
|
fetch(`${API_URL}/login`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify({
|
|
email: email,
|
|
password: password
|
|
})
|
|
})
|
|
.then(response => {
|
|
if (response.ok) {
|
|
return response.json();
|
|
} else {
|
|
if (!responseSent) {
|
|
sendResponse({ success: false, error: 'Erro na autenticação. Verifique suas credenciais.' });
|
|
responseSent = true;
|
|
}
|
|
throw new Error('Erro na autenticação.');
|
|
}
|
|
})
|
|
.then(data => {
|
|
if (data.status === 'success' && data.response && data.response.token) {
|
|
authToken = 'Bearer ' + data.response.token;
|
|
negocios_id = data.response.negocios_id;
|
|
negocios_nome = data.response.negocios_nome;
|
|
user_id = data.response.user_id;
|
|
expires = data.response.expires;
|
|
|
|
chrome.storage.local.set({ authToken, negocios_id, negocios_nome, user_id, expires }, () => {
|
|
console.log('Usuário autenticado com sucesso.');
|
|
if (!responseSent) {
|
|
sendResponse({ success: true });
|
|
responseSent = true;
|
|
}
|
|
});
|
|
} else {
|
|
console.error('Erro na autenticação:', data);
|
|
if (!responseSent) {
|
|
sendResponse({ success: false, error: 'Falha na autenticação. Verifique suas credenciais.' });
|
|
responseSent = true;
|
|
}
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Erro na autenticação:', error);
|
|
if (!responseSent) {
|
|
sendResponse({ success: false, error: 'Erro ao realizar o login. Por favor, tente novamente.' });
|
|
responseSent = true;
|
|
}
|
|
});
|
|
|
|
return true;
|
|
} else if (request.action === 'logout') {
|
|
authToken = null;
|
|
chrome.storage.local.remove(['authToken', 'negocios_id', 'negocios_nome', 'user_id', 'expires'], () => {
|
|
console.log('Usuário deslogado com sucesso.');
|
|
sendResponse({ success: true });
|
|
});
|
|
return true;
|
|
} else if (request.action === 'getUserData') {
|
|
fetch(`${API_URL}/user/data`, {
|
|
headers: {
|
|
'Authorization': authToken
|
|
}
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
sendResponse({ success: true, data });
|
|
})
|
|
.catch(error => {
|
|
console.error('Erro ao buscar dados do usuário:', error);
|
|
sendResponse({ success: false, error: 'Erro ao buscar dados do usuário' });
|
|
});
|
|
|
|
return true;
|
|
} else if (request.action === 'saveSwipeFile') {
|
|
// Verificar se temos um token válido
|
|
if (!authToken) {
|
|
sendResponse({
|
|
success: false,
|
|
error: 'Usuário não autenticado. Por favor, faça login novamente.'
|
|
});
|
|
return true;
|
|
}
|
|
|
|
fetch(`${API_URL}/novo_swipe_file`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': authToken // Garantir que o token está no formato correto
|
|
},
|
|
body: JSON.stringify({
|
|
negocio_id: request.data.negocio_id,
|
|
conteudo: request.data.conteudo,
|
|
nome_autor: request.data.nome_autor,
|
|
link_autor: request.data.link_autor,
|
|
link_post: request.data.link_post
|
|
})
|
|
})
|
|
.then(response => {
|
|
if (response.status === 401) {
|
|
// Token expirado ou inválido
|
|
handleAuthError(); // Função que limpa o token e força novo login
|
|
throw new Error('Sessão expirada. Por favor, faça login novamente.');
|
|
}
|
|
if (!response.ok) {
|
|
throw new Error('Erro na requisição: ' + response.status);
|
|
}
|
|
return response.json();
|
|
})
|
|
.then(data => {
|
|
if (data.response && data.response.swipe_file_id) {
|
|
chrome.storage.local.set({
|
|
lastSwipeFileId: data.response.swipe_file_id
|
|
});
|
|
sendResponse({
|
|
success: true,
|
|
swipeFileId: data.response.swipe_file_id
|
|
});
|
|
} else {
|
|
throw new Error('Resposta inválida da API');
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Erro ao salvar swipe file:', error);
|
|
sendResponse({
|
|
success: false,
|
|
error: error.message || 'Erro ao salvar o swipe file'
|
|
});
|
|
|
|
// Se for erro de autenticação, redirecionar para login
|
|
if (error.message.includes('401') || error.message.includes('expirada')) {
|
|
chrome.runtime.sendMessage({ action: 'showLogin' });
|
|
}
|
|
});
|
|
|
|
return true;
|
|
} else if (request.action === 'openPopupWithData') {
|
|
// Armazenar os dados temporariamente
|
|
chrome.storage.local.set({ currentPostData: request.data }, () => {
|
|
// Criar uma nova janela popup
|
|
chrome.windows.create({
|
|
url: 'popup.html',
|
|
type: 'popup',
|
|
width: 400,
|
|
height: 600,
|
|
focused: true
|
|
});
|
|
});
|
|
return true;
|
|
}
|
|
}); |