Files
old-slucajna-televizija/backend/app.js

374 lines
9.7 KiB
JavaScript
Raw Normal View History

2017-10-16 12:12:20 +02:00
const express = require('express')
2017-10-16 20:21:19 +02:00
const bodyParser = require("body-parser");
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
2017-10-16 12:12:20 +02:00
const app = express()
2017-10-16 12:36:23 +02:00
const router = express.Router();
2017-10-16 12:12:20 +02:00
2017-10-16 20:21:19 +02:00
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
2017-10-18 14:48:50 +02:00
require('dotenv').config()
const PEOPLE_DB = process.env.PEOPLE_DB.split('/')[5];
const PAIRS_LIST = process.env.PAIRS_LIST.split('/')[5];
2017-10-16 12:12:20 +02:00
2017-10-18 14:48:50 +02:00
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
2017-10-16 20:21:19 +02:00
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
2017-10-18 14:48:50 +02:00
var oauth2Client = null;
var pairsForSave = [];
var lastRow = null; //last row with names
2017-10-16 20:21:19 +02:00
2017-10-18 14:48:50 +02:00
function executeAPI(callback1,callback2){
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
console.log("reading client secret");
2017-10-16 20:21:19 +02:00
if (err) {
2017-10-18 14:48:50 +02:00
console.log('Error loading client secret file: ' + err);
return;
2017-10-16 20:21:19 +02:00
}
2017-10-18 14:48:50 +02:00
// Authorize a client with the loaded credentials, then call the
// Google Sheets API.
authorize(JSON.parse(content), callback1, callback2);
2017-10-16 20:21:19 +02:00
});
}
2017-10-18 14:48:50 +02:00
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);
2017-10-16 20:21:19 +02:00
if (err) {
2017-10-18 14:48:50 +02:00
getNewToken(callback1, callback2);
} else {
oauth2Client.credentials = JSON.parse(token);
callback1(callback2);
2017-10-16 20:21:19 +02:00
}
});
2017-10-18 14:48:50 +02:00
}
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);
});
});
2017-10-16 20:21:19 +02:00
}
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
2017-10-29 13:42:15 +01:00
if (err.code !== 'EEXIST') {
2017-10-16 20:21:19 +02:00
throw err;
}
}
console.log(JSON.stringify(token));
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
2017-10-18 14:48:50 +02:00
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 = [];
2017-10-25 00:28:31 +02:00
try{
lastRow = result.valueRanges[0].values.length;
}catch(err){
lastRow = 0;
}
2017-10-18 14:48:50 +02:00
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
2017-10-16 20:21:19 +02:00
var sheets = google.sheets('v4');
sheets.spreadsheets.values.batchGet({
auth: auth,
2017-10-18 14:48:50 +02:00
spreadsheetId: PEOPLE_DB,
2017-10-16 20:21:19 +02:00
ranges: ranges
}, function(err, result) {
if(err) {
// Handle error
console.log(err);
2017-10-18 14:48:50 +02:00
return null;
2017-10-16 20:21:19 +02:00
} else {
2017-10-18 14:48:50 +02:00
const names = [];
for (let i=0;i<result.valueRanges[0].values.length;i++){
2017-10-25 00:28:31 +02:00
try{
let name = result.valueRanges[0].values[i][0];
let available = result.valueRanges[1].values[i][0];
2017-10-29 13:42:15 +01:00
if (name && (available==='x')){
2017-10-25 00:28:31 +02:00
names.push(name);
}
}catch(err){
}
2017-10-18 14:48:50 +02:00
}
callback(names);
2017-10-16 20:21:19 +02:00
}
});
}
2017-10-18 14:48:50 +02:00
2017-10-29 13:18:00 +01:00
var matrix = [];
var tree = [];
let done = false;
function count_pairs(row, col, cntr){
if (done) return;
matrix[row][col] = 2;
2017-10-29 13:42:15 +01:00
//mark all fields in matrix related to row and col names
2017-10-29 13:18:00 +01:00
for(let i=0;i<row;i++) matrix[row][i] = (matrix[row][i]===0)? cntr: matrix[row][i];
for(let i=0;i<col;i++) matrix[col][i] = (matrix[col][i]===0)? cntr: matrix[col][i];
for(let i=row;i<matrix.length;i++) matrix[i][row] = (matrix[i][row]===0)? cntr: matrix[i][row];
for(let i=col;i<matrix.length;i++) matrix[i][col] = (matrix[i][col]===0)? cntr: matrix[i][col];
2017-10-29 13:42:15 +01:00
//find next pair
2017-10-29 13:18:00 +01:00
let found = false;
for (let i=0;i<matrix.length;i++){
for (let j=0;j<=i;j++){
2017-10-29 13:42:15 +01:00
if (matrix[i][j]===0){
2017-10-29 13:18:00 +01:00
count_pairs(i,j,cntr+1);
found=true;
}
}
}
if (!found){
let inner_tree = [];
for (let i=0;i<matrix.length;i++){
for (let j=0;j<=i;j++){
2017-10-29 13:42:15 +01:00
if (matrix[i][j]===2){
2017-10-29 13:18:00 +01:00
inner_tree.push({row: i, col:j});
}
}
}
2017-10-29 13:42:15 +01:00
if (inner_tree.length === max_pairs) {
2017-10-29 13:18:00 +01:00
done=true;
tree.push(inner_tree);
}
}
2017-10-29 13:42:15 +01:00
//remove marks from matrix
2017-10-29 13:18:00 +01:00
for(let i=0;i<row;i++) matrix[row][i] = (matrix[row][i]===cntr)? 0: matrix[row][i];
for(let i=0;i<col;i++) matrix[col][i] = (matrix[col][i]===cntr)? 0: matrix[col][i];
for(let i=row;i<matrix.length;i++) matrix[i][row] = (matrix[i][row]===cntr)? 0: matrix[i][row];
for(let i=col;i<matrix.length;i++) matrix[i][col] = (matrix[i][col]===cntr)? 0: matrix[i][col];
matrix[row][col] = 0;
}
function MakePairsV3(callback){
executeAPI(getAvailableNames,function(names){
executeAPI(getPairs, function(pairs){
max_pairs = Math.floor(names.length/2);
matrix=[];
for (let i=0;i<names.length;i++){
let matrix_row = [];
2017-10-29 13:42:15 +01:00
for (let j=0;j<=i;j++) (i===j)? matrix_row.push(1):matrix_row.push(0);
2017-10-29 13:18:00 +01:00
matrix.push(matrix_row);
}
2017-10-29 13:42:15 +01:00
//Mark existing pairs, put 3 in matrix fields
2017-10-29 13:18:00 +01:00
pairs.filter((pair)=>{
let name1_id = names.indexOf(pair.name1);
let name2_id = names.indexOf(pair.name2);
2017-10-29 13:42:15 +01:00
if (name1_id !== -1 && name2_id !== -1){
2017-10-29 13:18:00 +01:00
if (name1_id > name2_id){
matrix[name1_id][name2_id] = 3;
}else{
matrix[name2_id][name1_id] = 3;
}
}
});
tree = [];
done=false;
for (let i=0;i<names.length;i++){
for (let j=0;j<=i;j++){
if (matrix[i][j] === 0){
count_pairs(i,j,5);
if (done) break;
}
}
if (done) break;
}
let max_count_index = 0;
for (let i=0;i<tree.length;i++){
if (tree[i].length > tree[max_count_index].length)
max_count_index = i;
}
let result_pairs = [];
if (tree.length > 0){
for (let i=0;i<tree[max_count_index].length;i++){
result_pairs.push({name1: names[tree[max_count_index][i].row],name2: names[tree[max_count_index][i].col] });
}
let indexToRemove = [];
for (let i=0;i<tree[max_count_index].length;i++){
indexToRemove.push(tree[max_count_index][i].row);
indexToRemove.push(tree[max_count_index][i].col);
}
indexToRemove.sort((a,b)=>{
if (a>b) return -1; else return 1;
});
for (let i=0;i<indexToRemove.length;i++)
names.splice(indexToRemove[i],1);
}
2017-10-29 13:42:15 +01:00
if (names.length === 0) names=null;
2017-10-29 13:18:00 +01:00
pairsForSave = result_pairs;
callback.send({pairs: result_pairs, left: names});
});
});
}
2017-10-18 14:48:50 +02:00
function SavePairs(callback){
2017-10-29 13:42:15 +01:00
if (lastRow=== null) {
2017-10-25 00:28:31 +02:00
callback.send({result:true});
return;
}
2017-10-18 14:48:50 +02:00
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 = [];
2017-10-29 13:42:15 +01:00
if (lastRow === 0) lastRow=-1;
2017-10-18 14:48:50 +02:00
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"
};
2017-10-16 20:21:19 +02:00
var sheets = google.sheets('v4');
2017-10-18 14:48:50 +02:00
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});
2017-10-16 20:21:19 +02:00
} else {
2017-10-18 14:48:50 +02:00
lastRow=null;
pairsForSave=[];
callback.send({result:true});
2017-10-16 20:21:19 +02:00
}
});
2017-10-18 14:48:50 +02:00
}
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();
});
2017-10-16 20:21:19 +02:00
2017-10-18 14:48:50 +02:00
app.get('/getPairs',(req,resp)=>{
pairsForSave=[];
lastRow=null;
2017-10-29 13:18:00 +01:00
MakePairsV3(resp);
2017-10-25 20:39:14 +02:00
});
2017-10-18 14:48:50 +02:00
app.get('/savePairs', (req,resp)=>{
SavePairs(resp);
});
2017-10-16 12:36:23 +02:00
app.listen(3005, function () {
2017-10-25 20:39:14 +02:00
console.log("Server running - Port 3005");
2017-10-16 12:12:20 +02:00
})