Skip to content

Instantly share code, notes, and snippets.

@TheNewHEROBRINEX
Last active March 30, 2021 12:37
Show Gist options
  • Save TheNewHEROBRINEX/f9c0a356beb1ef3b552469d826b6e4cf to your computer and use it in GitHub Desktop.
Save TheNewHEROBRINEX/f9c0a356beb1ef3b552469d826b6e4cf to your computer and use it in GitHub Desktop.
<?php
declare(strict_types = 1);
namespace EssentialsPE\Tasks;
use EssentialsPE\Loader;
use pocketmine\Player;
use pocketmine\scheduler\AsyncTask;
use pocketmine\Server;
use pocketmine\utils\Utils;
class GeoLocation extends AsyncTask{
/** @var \Threaded|null */
private $ip = null;
/**
* @param Player|Player[]|null $player
*/
public function __construct($player){
if($player !== null){
if(!is_array($player)) {
$player = [$player];
}
$this->ip = new \Threaded();
$players = [];
foreach($player as $p){
$spl = spl_object_hash($p);
$players[$spl] = $p;
$this->ip[$spl] = $p->getAddress();
}
$this->storeLocal($players);
}
}
public function onRun(): void{
if($this->ip === null){
$data = Utils::getURL("http://ip-api.com/json/");
$this->setResult(json_decode($data, true)["country"] ?? "Unknown");
}else{
$list = [];
foreach($this->ip as $spl => $ip){
$data = Utils::getURL("http://ip-api.com/json/" . $ip);
$data = json_decode($data, true);
if(isset($data["message"]) && $data["message"] === "private range"){
$data["country"] = "server";
}
if(isset($data["country"])){
$list[$spl] = $data["country"] ?? "Unknown";
}
}
$this->setResult($list);
}
}
/**
* @param Server $server
*/
public function onCompletion(Server $server): void{
/** @var Loader $plugin */
$plugin = $server->getPluginManager()->getPlugin("EssentialsPE");
if(!is_array($this->getResult())){
$plugin->getAPI()->setServerGeoLocation($this->getResult());
}else{
$players = $this->fetchLocal();
foreach($this->getResult() as $spl => $loc){
$plugin->getAPI()->updateGeoLocation($players[$spl], ($loc !== "server" ? $loc : $plugin->getAPI()->getServerGeoLocation()));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment