471 lines
13 KiB
JavaScript
471 lines
13 KiB
JavaScript
const express = require('express')
|
|
const bodyParser = require("body-parser");
|
|
var fs = require('fs');
|
|
var readline = require('readline');
|
|
var google = require('googleapis');
|
|
var googleAuth = require('google-auth-library');
|
|
|
|
const app = express()
|
|
const router = express.Router();
|
|
|
|
router.use(bodyParser.urlencoded({ extended: false }));
|
|
router.use(bodyParser.json());
|
|
|
|
require('dotenv').config()
|
|
|
|
const PEOPLE_DB = process.env.PEOPLE_DB.split('/')[5];
|
|
const PAIRS_LIST = process.env.PAIRS_LIST.split('/')[5];
|
|
|
|
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
|
|
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
|
|
process.env.USERPROFILE) + '/.credentials/';
|
|
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
|
|
|
|
var oauth2Client = null;
|
|
|
|
var pairsForSave = [];
|
|
var lastRow = null; //last row with names
|
|
|
|
|
|
function executeAPI(callback1,callback2){
|
|
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
|
|
console.log("reading client secret");
|
|
if (err) {
|
|
console.log('Error loading client secret file: ' + err);
|
|
return;
|
|
}
|
|
// Authorize a client with the loaded credentials, then call the
|
|
// Google Sheets API.
|
|
authorize(JSON.parse(content), callback1, callback2);
|
|
});
|
|
}
|
|
|
|
function authorize(credentials, callback1, callback2){
|
|
var clientSecret = credentials.installed.client_secret;
|
|
var clientId = credentials.installed.client_id;
|
|
var redirectUrl = credentials.installed.redirect_uris[0];
|
|
var auth = new googleAuth();
|
|
|
|
oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
|
|
|
|
// Check if we have previously stored a token.
|
|
fs.readFile(TOKEN_PATH, function(err, token) {
|
|
console.log(TOKEN_PATH);
|
|
if (err) {
|
|
getNewToken(callback1, callback2);
|
|
} else {
|
|
oauth2Client.credentials = JSON.parse(token);
|
|
callback1(callback2);
|
|
}
|
|
});
|
|
}
|
|
|
|
function getNewToken(callback1, callback2) {
|
|
var authUrl = oauth2Client.generateAuthUrl({
|
|
access_type: 'offline',
|
|
scope: SCOPES
|
|
});
|
|
console.log('Authorize this app by visiting this url: ', authUrl);
|
|
var rl = readline.createInterface({
|
|
input: process.stdin,
|
|
output: process.stdout
|
|
});
|
|
rl.question('Enter the code from that page here: ', function(code) {
|
|
rl.close();
|
|
oauth2Client.getToken(code, function(err, token) {
|
|
if (err) {
|
|
console.log('Error while trying to retrieve access token', err);
|
|
return;
|
|
}
|
|
oauth2Client.credentials = token;
|
|
storeToken(token);
|
|
callback1(callback2);
|
|
});
|
|
});
|
|
}
|
|
|
|
function storeToken(token) {
|
|
try {
|
|
fs.mkdirSync(TOKEN_DIR);
|
|
} catch (err) {
|
|
if (err.code != 'EEXIST') {
|
|
throw err;
|
|
}
|
|
}
|
|
console.log(JSON.stringify(token));
|
|
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
|
|
console.log('Token stored to ' + TOKEN_PATH);
|
|
}
|
|
|
|
function getPairs(callback){
|
|
auth=oauth2Client;
|
|
ranges = ['2017!A:A','2017!B:B']; //get all rows with names
|
|
var sheets = google.sheets('v4');
|
|
sheets.spreadsheets.values.batchGet({
|
|
auth: auth,
|
|
spreadsheetId: PAIRS_LIST,
|
|
ranges: ranges
|
|
}, function(err, result) {
|
|
if(err) {
|
|
// Handle error
|
|
console.log(err);
|
|
return null;
|
|
} else {
|
|
const pairs = [];
|
|
|
|
try{
|
|
lastRow = result.valueRanges[0].values.length;
|
|
}catch(err){
|
|
lastRow = 0;
|
|
}
|
|
|
|
for (let i=0;i<lastRow;i++){
|
|
let name1 = result.valueRanges[0].values[i][0];
|
|
if (name1){
|
|
let name2 = result.valueRanges[1].values[i][0];
|
|
pairs.push({name1:name1,name2:name2});
|
|
}
|
|
}
|
|
callback(pairs);
|
|
}
|
|
});
|
|
}
|
|
|
|
function getAvailableNames(callback){
|
|
auth=oauth2Client;
|
|
ranges = ['\'Other preferences\'!A2:A','\'Other preferences\'!E2:E']; //get all rows with names
|
|
var sheets = google.sheets('v4');
|
|
sheets.spreadsheets.values.batchGet({
|
|
auth: auth,
|
|
spreadsheetId: PEOPLE_DB,
|
|
ranges: ranges
|
|
}, function(err, result) {
|
|
if(err) {
|
|
// Handle error
|
|
console.log(err);
|
|
return null;
|
|
} else {
|
|
const names = [];
|
|
|
|
for (let i=0;i<result.valueRanges[0].values.length;i++){
|
|
|
|
try{
|
|
let name = result.valueRanges[0].values[i][0];
|
|
let available = result.valueRanges[1].values[i][0];
|
|
if (name && (available=='x')){
|
|
names.push(name);
|
|
}
|
|
}catch(err){
|
|
}
|
|
|
|
}
|
|
callback(names);
|
|
}
|
|
});
|
|
}
|
|
|
|
function getRandomInt(min, max) {
|
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
}
|
|
|
|
function MakePairs(callback){
|
|
executeAPI(getAvailableNames,function(names){
|
|
executeAPI(getPairs, function(pairs){
|
|
const numOfPairs = Math.floor(names.length / 2);
|
|
const left_side = [];
|
|
const right_side = [];
|
|
|
|
const newPairs = [];
|
|
|
|
for (let i=0;i<numOfPairs;i++){
|
|
|
|
let id1 = getRandomInt(0,names.length-1);
|
|
left_side.push(names[id1]);
|
|
names.splice(id1,1);
|
|
let id2 = getRandomInt(0,names.length-1);
|
|
right_side.push(names[id2]);
|
|
names.splice(id2,1);
|
|
}
|
|
|
|
//make pairs using both sides
|
|
|
|
for (let i=0;i<left_side.length;i++){
|
|
if (i==left_side.length) break;
|
|
for (let j=0;j<right_side.length;j++){
|
|
let tmpName1 = left_side[i];
|
|
let tmpName2 = right_side[j];
|
|
let exist=false;
|
|
pairs.filter((pair)=>{
|
|
if (((pair.name1 == tmpName1)&&(pair.name2==tmpName2))||((pair.name1==tmpName2)&&(pair.name2==tmpName1))){
|
|
exist = true;
|
|
return;
|
|
}
|
|
});
|
|
if (!exist){
|
|
newPairs.push({name1:tmpName1, name2:tmpName2});
|
|
left_side.splice(i,1);
|
|
right_side.splice(j,1);
|
|
i=-1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
//make pairs from names on left side
|
|
for (let i=0;i<left_side.length;i++){
|
|
for (let j=0;j<left_side.length;j++){
|
|
if (i==j) continue;
|
|
let tmpName1 = left_side[i];
|
|
let tmpName2 = left_side[j];
|
|
let exist=false;
|
|
pairs.filter((pair)=>{
|
|
if (((pair.name1 == tmpName1)&&(pair.name2==tmpName2))||((pair.name1==tmpName2)&&(pair.name2==tmpName1))){
|
|
exist = true;
|
|
return;
|
|
}
|
|
});
|
|
if (!exist){
|
|
newPairs.push({name1:tmpName1, name2:tmpName2});
|
|
left_side.splice(i,1);
|
|
if (i>j)
|
|
left_side.splice(j,1);
|
|
else
|
|
left_side.splice(j-1,1);
|
|
i=-1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
//make pairs from names on right side
|
|
for (let i=0;i<right_side.length;i++){
|
|
for (let j=0;j<right_side.length;j++){
|
|
if (i==j) continue;
|
|
let tmpName1 = right_side[i];
|
|
let tmpName2 = right_side[j];
|
|
let exist=false;
|
|
pairs.filter((pair)=>{
|
|
if (((pair.name1 == tmpName1)&&(pair.name2==tmpName2))||((pair.name1==tmpName2)&&(pair.name2==tmpName1))){
|
|
exist = true;
|
|
return;
|
|
}
|
|
});
|
|
if (!exist){
|
|
newPairs.push({name1:tmpName1, name2:tmpName2});
|
|
right_side.splice(i,1);
|
|
if (i>j)
|
|
right_side.splice(j,1);
|
|
else
|
|
right_side.splice(j-1,1);
|
|
i=-1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
//try to make pair using unused name from list of names and names on left side
|
|
if (names.length>0){
|
|
let tmpName1 = names[0];
|
|
for (let i=0;i<left_side.length;i++){
|
|
let tmpName2 = left_side[i];
|
|
let exist=false;
|
|
pairs.filter((pair)=>{
|
|
if (((pair.name1 == tmpName1)&&(pair.name2==tmpName2))||((pair.name1==tmpName2)&&(pair.name2==tmpName1))){
|
|
exist = true;
|
|
return;
|
|
}
|
|
});
|
|
if (!exist){
|
|
newPairs.push({name1:tmpName1, name2:tmpName2});
|
|
names=[];
|
|
left_side.splice(i,1);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
//try to make pair using unused name from list of names and names on right side
|
|
if (names.length>0){
|
|
let tmpName1 = names[0];
|
|
for (let i=0;i<right_side.length;i++){
|
|
let tmpName2 = right_side[i];
|
|
let exist=false;
|
|
pairs.filter((pair)=>{
|
|
if (((pair.name1 == tmpName1)&&(pair.name2==tmpName2))||((pair.name1==tmpName2)&&(pair.name2==tmpName1))){
|
|
exist = true;
|
|
return;
|
|
}
|
|
});
|
|
if (!exist){
|
|
newPairs.push({name1:tmpName1, name2:tmpName2});
|
|
names=[];
|
|
right_side.splice(i,1);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
pairsForSave = newPairs;
|
|
|
|
let withoutPair = [];
|
|
for (let i=0;i<left_side.length;i++)
|
|
withoutPair.push(left_side[i]);
|
|
for (let i=0;i<right_side.length;i++)
|
|
withoutPair.push(right_side[i]);
|
|
if (names.length>0)
|
|
withoutPair.push(names[0]);
|
|
|
|
if (withoutPair.length==0) withoutPair=null;
|
|
|
|
callback.send({pairs: newPairs, left: withoutPair });
|
|
});
|
|
});
|
|
}
|
|
|
|
function MakePairsV2(callback){
|
|
executeAPI(getAvailableNames, function(names){
|
|
executeAPI(getPairs, function(pairs){
|
|
const AllPairs = [];
|
|
const BatchPairs = [];
|
|
|
|
for(let i=0;i<names.length;i++){
|
|
for (let j=i+1;j<names.length;j++){
|
|
let exist = false;
|
|
pairs.filter((pair)=>{
|
|
if (((pair.name1 == names[i])&&(pair.name2 == names[j]))||((pair.name1==names[j])&&(pair.name2==names[i]))){
|
|
exist=true;
|
|
return;
|
|
}
|
|
});
|
|
if (!exist){
|
|
AllPairs.push({name1: names[i], name2: names[j]});
|
|
}
|
|
}
|
|
}
|
|
|
|
while(AllPairs.length>0){
|
|
|
|
BatchPairs.push(AllPairs[0]);
|
|
|
|
let tmpNames = [];
|
|
let indexToRemove = [];
|
|
|
|
tmpNames.push(AllPairs[0].name1);
|
|
tmpNames.push(AllPairs[0].name2);
|
|
|
|
for (let i=0;i<AllPairs.length;i++){
|
|
if ((tmpNames.indexOf(AllPairs[i].name1)!=-1)||(tmpNames.indexOf(AllPairs[i].name2)!=-1)){
|
|
indexToRemove.push(i);
|
|
}
|
|
}
|
|
|
|
|
|
for(let i=indexToRemove.length-1; i>=0;i--){
|
|
AllPairs.splice(indexToRemove[i],1);
|
|
}
|
|
|
|
}
|
|
|
|
|
|
for(let i=0;i<BatchPairs.length;i++){
|
|
let index = names.indexOf(BatchPairs[i].name1);
|
|
if (index!=-1)
|
|
names.splice(index,1);
|
|
index = names.indexOf(BatchPairs[i].name2);
|
|
if (index!=-1)
|
|
names.splice(index,1);
|
|
}
|
|
|
|
if (names.length==0) names=null;
|
|
|
|
|
|
pairsForSave=BatchPairs;
|
|
|
|
callback.send({pairs: BatchPairs, left:names});
|
|
});
|
|
});
|
|
}
|
|
|
|
function SavePairs(callback){
|
|
if (lastRow== null) {
|
|
callback.send({result:true});
|
|
return;
|
|
}
|
|
|
|
auth=oauth2Client;
|
|
|
|
const values_column1 = [];
|
|
const values_column2 = [];
|
|
|
|
for (let i=0;i<pairsForSave.length;i++){
|
|
values_column1.push([pairsForSave[i].name1]);
|
|
values_column2.push([pairsForSave[i].name2]);
|
|
}
|
|
|
|
const data = [];
|
|
|
|
if (lastRow == 0) lastRow=-1;
|
|
let range1= '2017!A'+(lastRow+2)+':A'+(lastRow+2+pairsForSave.length);
|
|
let range2= '2017!B'+(lastRow+2)+':B'+(lastRow+2+pairsForSave.length);
|
|
|
|
|
|
data.push({
|
|
range:range1,
|
|
values: values_column1
|
|
});
|
|
|
|
data.push({
|
|
range:range2,
|
|
values: values_column2
|
|
});
|
|
|
|
var body = {
|
|
data: data,
|
|
valueInputOption:"RAW"
|
|
};
|
|
var sheets = google.sheets('v4');
|
|
sheets.spreadsheets.values.batchUpdate({
|
|
spreadsheetId: PAIRS_LIST,
|
|
auth:auth,
|
|
resource: body
|
|
}, function(err, result) {
|
|
if(err) {
|
|
// Handle error
|
|
console.log(err);
|
|
callback.send({result:false});
|
|
} else {
|
|
lastRow=null;
|
|
pairsForSave=[];
|
|
callback.send({result:true});
|
|
}
|
|
});
|
|
|
|
}
|
|
|
|
app.use(function(req, res, next) {
|
|
res.header("Access-Control-Allow-Origin", "*");
|
|
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Last-Record-Id, X-Total-Count");
|
|
res.header("Access-Control-Expose-Headers", "X-Last-Record-Id, X-Total-Count");
|
|
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
res.header('Access-Control-Allow-Credentials', 'true');
|
|
next();
|
|
});
|
|
|
|
app.get('/getPairs',(req,resp)=>{
|
|
pairsForSave=[];
|
|
lastRow=null;
|
|
MakePairsV2(resp);
|
|
});
|
|
|
|
app.get('/getAllPairs',(req,resp)=>{
|
|
MakePairsV2(resp);
|
|
});
|
|
|
|
app.get('/savePairs', (req,resp)=>{
|
|
SavePairs(resp);
|
|
//resp.send({result:true});
|
|
});
|
|
|
|
app.listen(3005, function () {
|
|
console.log("Server running - Port 3005");
|
|
}) |