lacona-ifttt
Version:
Lacona Addon for integrating with anything on IFTTT (via the Maker Channel)
221 lines (187 loc) • 8.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hooks = exports.extensions = undefined;
// const VALID_ARGUMENTS = {
// none: '',
// string: 'a String',
// integer: 'an Integer',
// decimal: 'a Decimal',
// url: 'a URL',
// email: 'an Email Address',
// phone: 'a Phone Number',
// time: 'a Time',
// date: 'a Date',
// datetime: 'a Date and Time'
// }
let onURLCommand = (() => {
var _ref = _asyncToGenerator(function* (command, query, { config, setConfig }) {
if (command !== 'add') {
console.error('lacona-ifttt command not recognized. URL should be in the form https://lacona-ifttt/add?event=x&command=y');
return;
}
if (!query.event) {
console.error('lacona-ifttt/add event was not provided. URL should be in the form https://lacona-ifttt/add?event=x&command=y');
return;
}
if (!query.command) {
console.error('lacona-ifttt/add invalid command. URL should be in the form https://lacona-ifttt/add?event=x&command=y');
return;
}
if (_lodash2.default.find(config.triggers, function (trigger) {
return trigger.event === query.event && trigger.command === query.command;
})) {
const text = `This IFTTT command is already set up in Lacona.`;
const textEscaped = text.replace(/"/g, '\\"');
yield (0, _laconaApi.runApplescript)({ script: `display dialog "${textEscaped}" buttons {"OK"}` });
return;
}
// if we made it this far
// const argumentText = (query.argument && query.argument !== 'none')
// ? ` with ${VALID_ARGUMENTS[query.argument]} argument?`
// : '?'
const newEntry = `Would you like to create a Lacona IFTTT command "${query.command}" which triggers the "${query.event}" event?`;
const newEntryEscaped = newEntry.replace(/"/g, '\\"');
const response = yield (0, _laconaApi.runApplescript)({ script: `
set question to display dialog "${newEntryEscaped}" buttons {"Yes", "No"} default button 2
return button returned of question
` });
if (response === 'Yes') {
const newConfig = _lodash2.default.cloneDeep(config);
newConfig.commands.push({ event: query.event, command: query.command });
setConfig(newConfig);
}
});
return function onURLCommand(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
})();
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
var _elliptical = require('elliptical');
var _laconaPhrases = require('lacona-phrases');
var _laconaApi = require('lacona-api');
var _path = require('path');
var _nodeFetch = require('node-fetch');
var _nodeFetch2 = _interopRequireDefault(_nodeFetch);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /** @jsx createElement */
const IFTTT_IMG = (0, _path.join)(__dirname, '../img/IFTTT Logo.png');
function getElement(type, id) {
switch (type) {
case 'string':
return (0, _elliptical.createElement)(_laconaPhrases.String, { splitOn: /\s/, limit: 1, id: id });
case 'integer':
return (0, _elliptical.createElement)(_laconaPhrases.Integer, { limit: 1, id: id });
case 'decimal':
return (0, _elliptical.createElement)(_laconaPhrases.Decimal, { limit: 1, id: id });
case 'url':
return (0, _elliptical.createElement)(_laconaPhrases.URL, { id: id });
case 'phone':
return (0, _elliptical.createElement)(_laconaPhrases.PhoneNumber, { id: id });
case 'email':
return (0, _elliptical.createElement)(_laconaPhrases.EmailAddress, { id: id });
case 'date':
return (0, _elliptical.createElement)(_laconaPhrases.Date, { past: false, id: id });
case 'time':
return (0, _elliptical.createElement)(_laconaPhrases.Time, { past: false, id: id });
case 'datetime':
return (0, _elliptical.createElement)(_laconaPhrases.DateTime, { past: false, id: id });
}
}
function commandToElement({ command, event }) {
const tokenRegex = /(\{string\}|\{integer\}|\{decimal\}|\{url\}|\{phone\}|\{email\}|\{date\}|\{time\}|\{datetime\}|\[.*?,.*?\])/;
const tokenized = command.split(tokenRegex);
let eventNumber = 1;
const elements = _lodash2.default.map(tokenized, token => {
if (!token) return null;
if (_lodash2.default.startsWith(token, '{') && _lodash2.default.endsWith(token, '}')) {
const type = token.slice(1, -1);
const id = `value${eventNumber}`;
const element = getElement(type, id);
eventNumber += 1;
return element;
} else if (_lodash2.default.startsWith(token, '[') && _lodash2.default.endsWith(token, ']')) {
const csv = token.slice(1, -1);
const items = _lodash2.default.chain(csv).split(',').filter().map(text => ({ text, value: text })).value();
const id = `value${eventNumber}`;
eventNumber += 1;
return (0, _elliptical.createElement)(
'placeholder',
{ suppressEmpty: false, argument: 'option', id: id },
(0, _elliptical.createElement)('list', { items: items })
);
} else {
return (0, _elliptical.createElement)('literal', { text: token });
}
});
return (0, _elliptical.createElement)(
'sequence',
null,
(0, _elliptical.createElement)('literal', { text: '', id: 'event', value: event }),
elements
);
}
const IFTTTCommand = {
extends: [_laconaPhrases.Command],
execute(result, { config }) {
const event = encodeURIComponent(result.event);
console.log(`https://maker.ifttt.com/trigger/${event}/with/key/${config.key}`);
(0, _nodeFetch2.default)(`https://maker.ifttt.com/trigger/${event}/with/key/${config.key}`, {
method: 'POST',
body: JSON.stringify({
value1: result.value1,
value2: result.value2,
value3: result.value3
}),
headers: { 'Content-Type': 'application/json' }
}).then(res => {
if (res.ok) {
(0, _laconaApi.showNotification)({ title: 'IFTTT', subtitle: `${result.event} event triggered successfully` });
} else {
(0, _laconaApi.showNotification)({ title: 'IFTTT Error', subtitle: `An error occurred triggering ${result.event}`, content: 'Check your IFTTT Key setting' });
console.error('IFTTT returned error', res.status, res.statusText);
}
}).catch(err => {
(0, _laconaApi.showNotification)({ title: 'IFTTT Error', subtitle: 'IFTTT could not be reached', content: 'Check your network settings' });
console.error('IFTTT network error', err);
});
},
describe({ config }) {
if (config.key) {
const commands = _lodash2.default.chain(config.commands).filter(command => command.command && command.event).map(commandToElement).value();
return (0, _elliptical.createElement)(
'choice',
null,
commands
);
// const triggers = _.chain(config.triggers)
// .filter('event')
// .map(({event, argument}) => {
// let ArgumentElement = argumentTypeMap[argument]
// let argumentAddition = ArgumentElement
// ? [<literal text=' with ' />, (
// <placeholder label='argument' suppressEmpty={false} id='argument'>
// <ArgumentElement />
// </placeholder>
// )] : null
// return (
// <sequence>
// <placeholder argument='IFTTT event' id='event' suppressEmpty={false} annotation={{type: 'image', value: IFTTT_IMG}}>
// <literal text={event} value={event} />
// </placeholder>
// {argumentAddition}
// </sequence>
// )
// }).value()
// return (
// <sequence>
// <list items={['trigger ', 'do ', 'activate ']} limit={1} />
// <choice merge>{triggers}</choice>
// </sequence>
// )
}
}
};const extensions = exports.extensions = [IFTTTCommand];
const hooks = exports.hooks = { onURLCommand };