Funkcionalna radna verzija

This commit is contained in:
GotPPay
2017-10-18 14:48:50 +02:00
parent a75ea978f9
commit 67dd77c632
127 changed files with 2436 additions and 163 deletions

View File

@@ -5,81 +5,83 @@ var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
require('dotenv').config()
const PEOPLE_DB = process.env.PEOPLE_DB;
const PAIRS_LIST = process.env.PAIRS_LIST;
const app = express()
const router = express.Router();
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
/*
app.get('/', function (req, res) {
res.send('Hello World!')
})
*/
require('dotenv').config()
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
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';
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), listPairs);
});
var oauth2Client = null;
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
var pairsForSave = [];
var lastRow = null; //last row with names
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
console.log(TOKEN_PATH);
function executeAPI(callback1,callback2){
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
console.log("reading client secret");
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
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 getNewToken(oauth2Client, callback) {
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) {
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) {
console.log('Error while trying to retrieve access token', err);
return;
getNewToken(callback1, callback2);
} else {
oauth2Client.credentials = JSON.parse(token);
callback1(callback2);
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
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) {
@@ -95,55 +97,190 @@ function storeToken(token) {
console.log('Token stored to ' + TOKEN_PATH);
}
function listPairs(auth){
ranges = ['2017!A:A','2017!B:B'];
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 = [];
lastRow = result.valueRanges[0].values.length;
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: '1gPuRhTry3YoJ_ibI2BfL1ue2_YLlhtW56OP39ADJY_4',
spreadsheetId: PEOPLE_DB,
ranges: ranges
}, function(err, result) {
if(err) {
// Handle error
console.log(err);
return null;
} else {
console.log('%d ranges retrieved.', result.valueRanges.length);
console.log(result.valueRanges[0].values[0]);
const names = [];
for (let i=0;i<result.valueRanges[0].values.length;i++){
let name = result.valueRanges[0].values[i][0];
let available = result.valueRanges[1].values[i][0];
if (name && (available=='x')){
names.push(name);
}
}
callback(names);
}
});
}
/*
function listPairs(auth) {
var sheets = google.sheets('v4');
sheets.spreadsheets.values.get({
auth: auth,
spreadsheetId: '1gPuRhTry3YoJ_ibI2BfL1ue2_YLlhtW56OP39ADJY_4',
range: '2017!A:A',
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var rows = response.values;
if (rows.length == 0) {
console.log('No data found.');
} else {
console.log('Name, Major:');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
// Print columns A and E, which correspond to indices 0 and 4.
console.log('%s, %s', row[0], row[4]);
function MakePairs(callback){
executeAPI(getAvailableNames,function(names){
executeAPI(getPairs, function(pairs){
let next_i=false;
const newPairs = [];
const usedNames = [];
for (let i=0;i<names.length;i++){
next_i=false;
for (let j=0;j<names.length;j++){
if (i!=j){
let found=false;
pairs.filter((pair)=>{
if ((pair.name1==names[i] && pair.name2==names[j])||(pair.name1==names[j] && pair.name2==names[i])){
console.log("Par pronaden !");
console.log(names[i] + " i " + names[j]);
found=true;
return;
}
});
if (!found){
usedNames.filter((name)=>{
if (names[i] === name || names[j] === name){
console.log("Ime vec koristeno");
found=true;
return;
}
});
}
if (!found){
next_i=true;
newPairs.push({name1:names[i], name2:names[j]});
usedNames.push(names[i]);
usedNames.push(names[j]);
break;
}
}
}
if (next_i) continue;
}
pairsForSave=newPairs;
callback.send(newPairs);
});
});
//Napravi par -> Provjeri da li postoji -> Snimi ili ponovi postupak
}
function SavePairs(callback){
if (lastRow== null) 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 = [];
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});
}
});
}*/
router.post('/getPairs',(req,resp)=>{
//resp.send({ime:'Bilal',prezime:'Catic'});
// Load client secrets from a local file.
}
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;
MakePairs(resp);
});
app.get('/savePairs', (req,resp)=>{
SavePairs(resp);
//resp.send({result:true});
});
app.listen(3005, function () {
console.log('server na portu 3005');
})