0

I've been following the quickstart using google tasks with node.js here: https://developers.google.com/tasks/quickstart/nodejs and have got it working getting the task lists and then the tasks within them. However I'd like to check the task list(s) every set interval and retrieve any new ones, then send them to my webpage to update it with the new task(s). I'm not entirely sure how to do this though.

const express = require('express');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const {google} = require('googleapis');

const app = express();
const directoryToServe = 'client';
const port = 3443;

app.use('/', express.static(path.join(__dirname, '..', directoryToServe)));
const httpsOptions = {
  cert: fs.readFileSync(path.join(__dirname, 'ssl', 'server.crt')),
  key: fs.readFileSync(path.join(__dirname, 'ssl', 'server.key'))
};


var inputs;

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/tasks'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Tasks API.
  authorize(JSON.parse(content), listTaskLists);

});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Lists the user's first 10 task lists.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listTaskLists(auth) {
  const service = google.tasks({version: 'v1', auth});
  service.tasklists.list({
    maxResults: 10,
  }, (err, res) => {
    if (err) return console.error('The API returned an error: ' + err);
    const taskLists = res.data.items;
    if (taskLists) {
      console.log('Task lists:');
      taskLists.forEach((taskList) => {
        console.log(`${taskList.title} (${taskList.id})`);

        getTasksFromTaskList(taskList.id, auth);
        //updateListTaskLists(taskList.title, taskList.id, auth);
      });
    } else {
      console.log('No task lists found.');
    }
  });
}

function getTasksFromTaskList(tasklistid, auth) {
  const service = google.tasks({version: 'v1', auth});
  service.tasks.list({
    tasklist: tasklistid,
  }, (err, res) => {
    if (err) return console.error('The API returned an error: ' + err);
    const tasks = res.data.items;
    if (tasks) {
      console.log(`Tasks from ${tasklistid}:`);
      tasks.forEach((task) => {
        inputs = {name: task.title};


        console.log(inputs);
        console.log(`${task.title} (${task.id})`);
      });
    } else {
      console.log('No tasks found.');
    }
  });
}


// Express route for incoming requests for a customer name
app.get('/inputs/', function(req, res) {
  console.log("send inputs: " + inputs);
  res.status(200).send(inputs);


});


// Express route for any other unrecognised incoming requests
app.get('*', function(req, res) {
  res.status(404).send('Unrecognised API call');
});

// Express route to handle errors
app.use(function(err, req, res, next) {
  if (req.xhr) {
    res.status(500).send('Oops, Something went wrong!');
  } else {
    next(err);
  }
});


var server = https.createServer(httpsOptions, app).listen(port, function () {
  console.log('Serving the ' + directoryToServe + '/ directory at https://localhost:' + port);
});

const io = require('socket.io').listen(server)

io.on('connection', function(socket) {
  // Here I want send the new tasks when a new one has been added
});

Update:

So I tried wrapping authorize(JSON.parse(content), listTaskLists); with setInterval(authorize(JSON.parse(content), listTaskLists), 60000); to see if I could get it to execute every minute, as a way for it to poll Google Tasks for newly added tasks, however I got this error: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Whats causing this? Also is this a good approach, to use setInterval?

  • Is there anything you have tried so far? If yes, please add that to your question. Users on stackoverflow are much more inclined to help you if they see you have put in effort yourself but got stuck at a specific point. – sobek Aug 09 '19 at 19:24
  • I'm quite new to node js so I'm not entirely sure how to implement this. I know how I'd do it, try poll the google tasks every so often to see if there is a new task added by checking the date or something. Then if there is, emit the data back to the webpage using socket.io. That sound like a solid plan? – BlackBruceLee Aug 09 '19 at 20:28
  • Unfortunately I can't help you with node.js, but i can try to help you formulate a question that people on SO will be happy to answer. Just start somewhere, doesn't matter if you get stuck after just 3 lines of code, but at that point you will be able to ask a very specific question that people can help you with. – sobek Aug 09 '19 at 20:33

0 Answers0