127.0.0.1:8000 smart-home-server / master server / routes / reminders.js
master

Tree @master (Download .tar.gz)

reminders.js @masterraw · history · blame

const utils = require('../utils');
const actions = require('../utils/actions');
const location = require('../utils/location');
const ifttt = require('../utils/ifttt');

function registerReminder(user_id, target_location, message) {
    console.log("Register reminder for", user_id, "when user is at", target_location);
    actions.register(function(invoke) {
        location.check(user_id, target_location).then(function(is_there) {
            if (is_there) {
                invoke();
            }
        }).catch(console.error);
    }, function() {
        console.log("Dispatch reminder for user", user_id);
        ifttt({
            user_id: user_id,
            event: "notification",
            data: `Don't forget to ${message.split(" my ").join(" your ")}`
        });
        return true;
    }, {
        type: "location"
    });
}

module.exports = {
    post: {
        "create": {
            "at-location": function(req, res) {
                console.log(req.body);
                location.check(req.body.user_id, req.body.location).then(function(is_there) {
                    console.log(`User ${req.body.user_id} is${is_there ? "" : " not"} at ${req.body.location}`);
                    if (is_there) {
                        actions.register(function(invoke) {
                            location.check(req.body.user_id, req.body.location).then(function(is_there) {
                                if (!is_there) {
                                    invoke();
                                }
                            }).catch(console.error);
                        }, function() {
                            console.log(`Now that user ${req.body.user_id} is not at ${req.body.location}, register the reminder`);
                            registerReminder(req.body.user_id, req.body.location, req.body.message);
                            return true;
                        }, {
                            type: "location"
                        });
                    } else {
                        console.log("Register the reminder immediately");
                        registerReminder(req.body.user_id, req.body.location, req.body.message);
                    }
                });
                res.send(utils.ok());
            }
        }
    }
};