127.0.0.1:8000 smart-home-server / master server / utils / ifttt.js
master

Tree @master (Download .tar.gz)

ifttt.js @masterraw · history · blame

const utils = require('.');
const axios = require('axios');

// Sometimes messages get broadcast at the same time for multiple
// actions (for example arriving at home triggers many things)
// Message queue consolidates these into a single notification
// at the expense of a slight dispatch delay
// TODO

module.exports = function(options) {
    let data = {};
    if ("string" === typeof options.data) {
        data.value1 = options.data;
    } else {
        for (let i = 0; i < options.data; i++) {
            const arg = arguments[i];
            data[`value${i+1}`] = arg;
        }
    }

    (options.user_id ? utils.query("SELECT ifttt_key, name FROM users WHERE ?", {
        user_id: options.user_id
    }) : utils.query("SELECT ifttt_key, name FROM users")).then(function(rows) {
        for (const row of rows) {
            if (row.ifttt_key) {
                ifttt(row.name, row.ifttt_key, options.event, data);
            }
        }
    }).catch(console.error);
};

function ifttt(name, ifttt_key, event, data) {
    axios.post(
        `https://maker.ifttt.com/trigger/${event}/with/key/${ifttt_key}`, data
    ).then(function(response) {
        if (response.status !== 200) {
            console.error("IFTTT request to", name, "failed. Status", response.status);
            setTimeout(function() {
                ifttt(name, ifttt_key, event, data);
            }, 60 * 1000);
        } else {
            console.log("IFTTT request to", name, "successful");
        }
    }).catch(function(error) {
        console.error(error);
        setTimeout(function() {
            ifttt(name, ifttt_key, event, data);
        }, 60 * 1000);
    });
}