Skip to content

Instantly share code, notes, and snippets.

@gesslar
Last active March 17, 2022 10:33
Show Gist options
  • Save gesslar/5d428b3cfdafb9c8cbd7faf32cf5bef1 to your computer and use it in GitHub Desktop.
Save gesslar/5d428b3cfdafb9c8cbd7faf32cf5bef1 to your computer and use it in GitHub Desktop.
FluffOS - Script to use external_start() to integrate with IP-API.com for Geolocation
// /adm/daemons/geo.c
// Daemon to get and store GeoLocation
//
// Created: 2022/03/17: Gesslar
// Last Change: 2022/03/17: Gesslar
//
// 2022/03/17: Gesslar - Created
#include <config.h>
inherit STD_DAEMON ;
private mapping geos = ([ ]) ;
private nosave mapping fds = ([ ]) ;
void read_call_back(int fd, mixed mess) ;
void write_call_back(int fd) ;
void close_call_back(int fd) ;
private nosave string program = NODE_PATH "geo/index.js" ;
void fetch_geo(string ip)
{
int fd ;
fd = external_start(1,
({ program, sprintf("--ip=%s", ip) }),
(: read_call_back :),
(: write_call_back :),
(: close_call_back :)
);
if(fd < 0) return ;
fds[fd] = ([
"ip" : ip,
"data" : "",
]) ;
}
void read_call_back(int fd, mixed mess)
{
fds[fd]["data"] += mess ;
}
void write_call_back(int fd)
{
// n/a
}
void close_call_back(int fd)
{
string ip = fds[fd]["ip"] ;
mapping results = json_decode(fds[fd]["data"]) ;
map_delete(fds, fd) ;
if(results["status"] != "success")
{
map_delete(results, ip) ;
return ;
}
map_delete(results, "status") ;
map_delete(results, "query") ;
geos[ip] = results ;
}
void debug_info()
{
printf("%O\n", geos) ;
}
const args = require("minimist")(process.argv.slice(2))
const ip = args["ip"]
fetchGeo(ip)
.then(result => {
process.stdout.write(JSON.stringify(result))
})
.catch(err => {
process.stdout.write(JSON.stringify(err))
})
function fetchGeo(ip) {
return new Promise( (resolve, reject) => {
const ip_path = `http://ip-api.com/json/${ip}?fields=status,country,countryCode,city,timezone,query`
const http = require("http")
http.get(ip_path, res => {
const data = []
res.on("data", chunk => {
data.push(chunk)
})
res.on("end", () => {
resolve(JSON.parse(Buffer.concat(data).toString()))
})
res.on("error", err => {
reject(err)
})
})
})
}
@gesslar
Copy link
Author

gesslar commented Mar 17, 2022

  1. Requires npm install minimist
  2. In your runtime config, set your external command to be where your node binary is (which node)
    external_cmd_1 : /home/gesslar/.nvm/versions/node/v17.4.0/bin/node

#2 above will also allow you to run any node scripts. /shrug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment