index.js (1785B)
1 #!/usr/bin/env node 2 3 const tls = require('tls') 4 const execFile = require('child_process').execFile 5 6 const args = process.argv; 7 const user = args[2] || process.env.IMAP_NOTIFY_USER 8 const pass = args[3] || process.env.IMAP_NOTIFY_PASS 9 const cmd = args[4] || process.env.IMAP_NOTIFY_CMD 10 const host = args[5] || process.env.IMAP_NOTIFY_HOST || "imap.gmail.com" 11 const port = args[6] || process.env.IMAP_NOTIFY_PORT || 993 12 const use_tls = (args[7] || process.env.IMAP_NOTIFY_TLS || 'yes') === 'yes' 13 const allow = process.env.IMAP_ALLOW_UNAUTHORIZED == null? false : !!process.env.IMAP_ALLOW_UNAUTHORIZED 14 const timeout = process.env.IMAP_IDLE_TIMEOUT || 300000; // 5 mins 15 const verbose = !!process.env.IMAP_VERBOSE; 16 17 function usage() { 18 console.error("usage: imap-notify USER PASS CMD [HOST] [PORT]") 19 process.exit(1) 20 } 21 22 if (!user || !pass || !cmd) { 23 usage(); 24 } 25 26 var ready = false; 27 28 const net = use_tls ? require('tls') : require('net') 29 30 const socket = net.connect({host: host, port: port, rejectUnauthorized: !allow}, () => { 31 function handleNotifications() { 32 socket.on("data", (data) => { 33 var str = data.toString(); 34 if (verbose) 35 console.error(str) 36 37 const res = /\* (\d+) EXISTS/.exec(str); 38 39 if (ready && res && res[1]) { 40 execFile(cmd, [res[1]], (error, stdout, stderr) => { 41 if (error) { 42 console.log(stdout) 43 console.error(stderr) 44 process.exit(3) 45 } 46 }) 47 } 48 49 if (/\+ idling/.test(str)) 50 ready = true; 51 }) 52 } 53 54 socket.write(`tag login ${user} ${pass}\r\ntag SELECT INBOX\r\ntag IDLE\r\n`) 55 56 handleNotifications() 57 58 setInterval(() => { 59 socket.write("DONE\r\ntag IDLE\r\n"); 60 }, timeout); 61 62 socket.on("close", () => process.exit(2)) 63 })