Skip to content

Commit

Permalink
api done
Browse files Browse the repository at this point in the history
  • Loading branch information
lucastozo committed Mar 9, 2024
1 parent 079ff25 commit 44b142d
Show file tree
Hide file tree
Showing 6 changed files with 195 additions and 93 deletions.
27 changes: 22 additions & 5 deletions api/send-level-changes.js → api/send-changes-api.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
const axios = require('axios');
module.exports = async (req, res) =>
{
const { key, tokenHash, changes } = req.body;
const { userKey, tokenHash, changelog, changes, dataMode } = req.body;
// userKey: unique key for each user
// tokenHash: hash of the DLBRauto github token
// changelog: description of the changes
// changes: JSON
// dataMode: 1 = level, 2 = records

const adminData = process.env.USERS_KEYS;
const token = process.env.DLBR_AUTO_GITHUB_TOKEN;
Expand All @@ -11,19 +16,31 @@ module.exports = async (req, res) =>

let userName;
for (let i = 0; i < adminDataSplit.length; i++) {
if (adminDataSplit[i] === key) {
if (adminDataSplit[i] === userKey) {
userName = adminDataSplit[i].split('@')[0];
break;
}
}
if (!userName || tokenHash !== hash) {
res.status(403).json({ message: 'Acesso negado' });
res.status(403).json({ message: 'Acesso negado. Chave de usuário ou token inválidos' });
return;
}

const owner = 'lucastozo';
const repo = 'VercelAlvo';
const path = 'data/leveldata.json';
let path;
switch (dataMode)
{
case 1:
path = 'data/leveldata.json';
break;
case 2:
path = 'data/playerdata.json';
break;
default:
res.status(400).json({ message: 'Modo de dados inválido' });
return;
}
const message = 'List Changes';
const content = Buffer.from(changes).toString('base64');
const branch = 'copy';
Expand Down Expand Up @@ -85,7 +102,7 @@ module.exports = async (req, res) =>

const horario = new Date().toLocaleString('pt-BR', { timeZone: 'America/Sao_Paulo' });
const title = 'List Changes';
const bodyPR = `Gerado automaticamente por DLBRauto em ${horario} (SP).\nAlterações feitas por: ${userName}\n\n${changes}`;
const bodyPR = `Gerado automaticamente por DLBRauto em ${horario} (SP).\nAlterações feitas por: ${userName}\n\n${changelog}`;
const head = 'copy';
const base = 'main';
const url = `https://api.github.com/repos/${owner}/${repo}/pulls`;
Expand Down
19 changes: 1 addition & 18 deletions assets/script/LevelData.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,16 +274,8 @@ function BotoesManipuladoresLevel()
sendButton.innerHTML = '<i class="fa-solid fa-upload"></i> Enviar Alterações';
sendButton.className = 'btn btn-primary';
sendButton.style.margin = '5px';

sendButton.setAttribute('data-bs-toggle', 'modal');
sendButton.setAttribute('data-bs-target', '#sendChanges-modal');
/*
sendButton.onclick = function() {
var table = document.getElementById('level-table');
var json = ExportarLevel(table);
DownloadLevelJSON(json);
}
*/
sendButton.setAttribute('data-bs-target', '#send-changes-modal');
buttonsManip.appendChild(sendButton);

var refreshButton = document.createElement('button');
Expand Down Expand Up @@ -410,15 +402,6 @@ async function AdicionarLevel(position, id, name, creator, verifier, video, publ
modalBS.hide();
}

function DownloadLevelJSON(json)
{
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(json, null, 2));
var dlAnchorElem = document.createElement('a');
dlAnchorElem.setAttribute("href", dataStr);
dlAnchorElem.setAttribute("download", "NEWleveldata.json");
dlAnchorElem.click();
}

async function RefreshAll()
{
var confirmMessage = "Tem certeza que deseja atualizar todos os nomes e criadores?\n\n" +
Expand Down
59 changes: 10 additions & 49 deletions assets/script/PlayerData.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,15 +143,15 @@ function DeletarLinhaPlayerTable(tr) {

function BotoesManipuladoresRecord()
{
var addRemoveContainer = document.getElementById('botoes-manipuladores-container');
var buttonsManip = document.getElementById('botoes-manipuladores-container');

var addButton = document.createElement('button');
addButton.innerHTML = '<i class="fas fa-plus"></i> Adicionar Record';
addButton.className = 'btn btn-success';
addButton.style.margin = '5px';
addButton.setAttribute('data-bs-toggle', 'modal');
addButton.setAttribute('data-bs-target', '#addRecord-modal');
addRemoveContainer.appendChild(addButton);
buttonsManip.appendChild(addButton);
var addRecordButton = document.querySelector('#addRecord');
addRecordButton.onclick = function() {
var level = document.querySelector('#level').value;
Expand All @@ -161,16 +161,14 @@ function BotoesManipuladoresRecord()
AdicionarRecord(level, player, progress, video);
}

var exportButton = document.createElement('button');
exportButton.innerHTML = '<i class="fas fa-file-export"></i> Exportar JSON';
exportButton.className = 'btn btn-primary';
exportButton.style.margin = '5px';
exportButton.onclick = function() {
var table = document.getElementById('player-table');
var json = ExportarRecord(table);
DownloadRecordJSON(json);
}
addRemoveContainer.appendChild(exportButton);
var sendButton = document.createElement('button');
sendButton.innerHTML = '<i class="fa-solid fa-upload"></i> Enviar Alterações';
sendButton.className = 'btn btn-primary';
sendButton.style.margin = '5px';
sendButton.setAttribute('data-bs-toggle', 'modal');
sendButton.setAttribute('data-bs-target', '#send-changes-modal');
buttonsManip.appendChild(sendButton);
buttonsManip.appendChild(sendButton);
}

function AdicionarRecord(level, player, progress, video)
Expand Down Expand Up @@ -347,41 +345,4 @@ function criarBotaoSubir(tr) {
}
}
return upButton;
}

//exportar tabela para json
function ExportarRecord(table)
{
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1; //January is 0
var year = date.getFullYear();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
var generatedAt = day + '/' + month + '/' + year + ' ' + hour + ':' + minute + ':' + second;
var json = {GeradoEm: generatedAt, TipoData: "record", Data: []};
for(var i = 1; i < table.rows.length; i++)
{
var record = {};
record.level_name = table.rows[i].cells[1].textContent;
record.player_name = table.rows[i].cells[2].textContent;
record.progress = parseInt(table.rows[i].cells[3].textContent);
var video = table.rows[i].cells[4].textContent;
if(video && video.trim() !== '')
{
record.video = video;
}
json.Data.push(record);
}
return json;
}

function DownloadRecordJSON(json)
{
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(json, null, 2));
var dlAnchorElem = document.createElement('a');
dlAnchorElem.setAttribute("href", dataStr);
dlAnchorElem.setAttribute("download", "NEWplayerdata.json");
dlAnchorElem.click();
}
137 changes: 120 additions & 17 deletions assets/script/sendChanges.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
function sendLevelChanges()
{
const userKey = document.getElementById('level-pr-user-key').value;
const tokenHash = document.getElementById('level-pr-token').value;
errorMsgHandler('', 1);
sendButtonHandler(2);
const userKey = document.querySelector('#level-pr-user-key').value;
const tokenHash = document.querySelector('#level-pr-token').value;
const changelog = document.querySelector('#level-pr-changelog').value;
const dataMode = 1;

if(!checkInputs(userKey, tokenHash, changelog))
{
return;
}

//exportar tabela para json
function ExportarLevel(table)
Expand Down Expand Up @@ -39,39 +48,133 @@ function sendLevelChanges()
return json;
}

/*
function DownloadLevelJSON(json)
const json = ExportarLevel(document.getElementById('level-table'));
const changes = JSON.stringify(json, null, 2);

fetchAPI(userKey, tokenHash, changelog, changes, dataMode);
}

function sendRecordsChanges()
{
errorMsgHandler('', 1);
sendButtonHandler(2);
const userKey = document.querySelector('#record-pr-user-key').value;
const tokenHash = document.querySelector('#record-pr-token').value;
const changelog = document.querySelector('#record-pr-changelog').value;
const dataMode = 2;

if(!checkInputs(userKey, tokenHash, changelog))
{
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(json, null, 2));
var dlAnchorElem = document.createElement('a');
dlAnchorElem.setAttribute("href", dataStr);
dlAnchorElem.setAttribute("download", "NEWleveldata.json");
dlAnchorElem.click();
return;
}
*/

const json = ExportarLevel(document.getElementById('level-table'));
const changes = "placeholder for changes";
//exportar tabela para json
function ExportarRecord(table)
{
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1; //January is 0
var year = date.getFullYear();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
var generatedAt = day + '/' + month + '/' + year + ' ' + hour + ':' + minute + ':' + second;
var json = {GeradoEm: generatedAt, TipoData: "record", Data: []};
for(var i = 1; i < table.rows.length; i++)
{
var record = {};
record.level_name = table.rows[i].cells[1].textContent;
record.player_name = table.rows[i].cells[2].textContent;
record.progress = parseInt(table.rows[i].cells[3].textContent);
var video = table.rows[i].cells[4].textContent;
if(video && video.trim() !== '')
{
record.video = video;
}
json.Data.push(record);
}
return json;
}

fetch('/api/send-level-changes', {
const json = ExportarRecord(document.getElementById('player-table'));
const changes = JSON.stringify(json, null, 2);

fetchAPI(userKey, tokenHash, changelog, changes, dataMode);
}

function fetchAPI(userKey, tokenHash, changelog, changes, dataMode)
{
fetch('/api/send-changes-api', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({userKey, tokenHash, changes}),
body: JSON.stringify({userKey, tokenHash, changelog, changes, dataMode}),
})
.then(response => {
if (!response.ok) {
return response.json().then(errorData => {
return response.json().then(errorData => {
throw new Error(errorData.message);
});
}
return response.json();
})
.then(data => {
alert("Alterações enviadas com sucesso!");
sendButtonHandler(1);
errorMsgHandler("Alterações enviadas com sucesso!", 3);
})
.catch(error => {
alert("Erro ao enviar alterações: " + error.message);
sendButtonHandler(1);
errorMsgHandler(error.message, 2);
});
}

function checkInputs(userKey, tokenHash, changelog)
{
if(!userKey || !tokenHash || !changelog)
{
alert("Preencha todos os campos!");
sendButtonHandler(1);
return false;
}
return true;
}

function sendButtonHandler(mode)
{
var sendButton = document.querySelector('#send-changes-button');

if(mode == 1)
{
sendButton.disabled = false;
sendButton.innerHTML = "Enviar";
}
else
{
sendButton.disabled = true;
sendButton.innerHTML = "<i class='fas fa-circle-notch fa-spin'></i> Enviando...";
}
}

function errorMsgHandler(msg, mode)
{
var errorDiv = document.querySelector('#send-changes-error-div');
var errorMsg = document.querySelector('#send-changes-error-msg');
switch(mode)
{
case 1: // hide error
errorDiv.style.display = 'none';
break;
case 2: // show error
errorDiv.style.backgroundColor = 'rgba(173, 41, 53, 0.5)';
errorDiv.style.display = 'block';
errorMsg.innerHTML = "Erro: " + msg;
break;
case 3: // show success
errorDiv.style.backgroundColor = 'rgba(40, 167, 69, 0.5)';
errorDiv.style.display = 'block';
errorMsg.innerHTML = msg;
break;

}
}
14 changes: 10 additions & 4 deletions pages/leveldata.html
Original file line number Diff line number Diff line change
Expand Up @@ -71,24 +71,30 @@ <h1 class="modal-title fs-5" id="addLevelLabel">Adicionar level</h1>
</div>

<!-- create pr modal -->
<div class="modal fade" id="sendChanges-modal" tabindex="-1" aria-labelledby="sendChangesLabel" aria-hidden="true">
<div class="modal fade" id="send-changes-modal" tabindex="-1" aria-labelledby="send-changesLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="sendChangesLabel">Enviar mudanças</h1>
<h1 class="modal-title fs-5" id="send-changesLabel">Enviar mudanças</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<input type="text" class="form-control" id="level-pr-user-key" placeholder="Chave de usuário">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="level-pr-token" placeholder="Token">
<textarea class="form-control" id="level-pr-token" placeholder="Token" style="height: 5em"></textarea>
</div>
<div class="mb-3">
<textarea class="form-control" id="level-pr-changelog" placeholder="Changelog" style="height: 10em"></textarea>
</div>
</div>
<div id="send-changes-error-div" class="text-center align-items-center" style="display: none; padding: 10px; margin: 10px; margin-top: 0; border-radius: 5px;">
<p id="send-changes-error-msg" style="margin-bottom: 0;">Mensagem de erro</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
<button type="button" id="sendChanges" class="btn btn-primary" onclick="sendLevelChanges();">Enviar</button>
<button type="button" id="send-changes-button" class="btn btn-primary" onclick="sendLevelChanges();">Enviar</button>
</div>
</div>
</div>
Expand Down
Loading

0 comments on commit 44b142d

Please sign in to comment.