|
| 1 | +package ogcl.fun; |
| 2 | + |
| 3 | +import org.bukkit.Bukkit; |
| 4 | +import org.bukkit.entity.Player; |
| 5 | +import com.google.gson.JsonObject; |
| 6 | +import com.google.gson.JsonParser; |
| 7 | + |
| 8 | +import java.io.BufferedReader; |
| 9 | +import java.io.InputStreamReader; |
| 10 | +import java.net.HttpURLConnection; |
| 11 | +import java.net.URL; |
| 12 | + |
| 13 | +public class PlayerIPadminAPI { |
| 14 | + private final PlayerIPadmin plugin; |
| 15 | + |
| 16 | + public PlayerIPadminAPI(PlayerIPadmin plugin) { |
| 17 | + this.plugin = plugin; |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * 获取指定玩家的IP地址。 |
| 22 | + * |
| 23 | + * @param player 目标玩家 |
| 24 | + * @return 返回玩家的IP地址,如果无法获取则返回"未知"。 |
| 25 | + */ |
| 26 | + public String getPlayerIP(Player player) { |
| 27 | + if (player.getAddress() != null) { |
| 28 | + return player.getAddress().getAddress().getHostAddress(); |
| 29 | + } |
| 30 | + return "未知"; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * 异步方式获取指定IP的地理位置信息。 |
| 35 | + * |
| 36 | + * @param ip 目标IP地址 |
| 37 | + * @param callback 当获取到地理位置信息后将通过这个回调返回 |
| 38 | + */ |
| 39 | + public void getPlayerLocationAsync(String ip, LocationInfoCallback callback) { |
| 40 | + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { |
| 41 | + String locationInfo = getLocationInfo(ip); |
| 42 | + // 确保回调在主线程执行 |
| 43 | + Bukkit.getScheduler().runTask(plugin, () -> callback.onLocationInfoReceived(locationInfo)); |
| 44 | + }); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * 从外部API获取IP地址对应的地理位置信息。 |
| 49 | + * |
| 50 | + * @param ip 目标IP地址 |
| 51 | + * @return 返回地理位置信息,如果失败则返回"未知"。 |
| 52 | + */ |
| 53 | + private String getLocationInfo(String ip) { |
| 54 | + String apiUrl = "https://www.ip.cn/api/index?ip=" + ip + "&type=1"; |
| 55 | + try { |
| 56 | + URL url = new URL(apiUrl); |
| 57 | + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); |
| 58 | + conn.setRequestMethod("GET"); |
| 59 | + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); |
| 60 | + StringBuilder response = new StringBuilder(); |
| 61 | + String inputLine; |
| 62 | + while ((inputLine = in.readLine()) != null) { |
| 63 | + response.append(inputLine); |
| 64 | + } |
| 65 | + in.close(); |
| 66 | + JsonObject jsonResponse = JsonParser.parseString(response.toString()).getAsJsonObject(); |
| 67 | + if (jsonResponse.get("code").getAsInt() == 0) { |
| 68 | + return jsonResponse.get("address").getAsString(); |
| 69 | + } |
| 70 | + } catch (Exception e) { |
| 71 | + Bukkit.getLogger().warning("[PlayerIPadmin] Failed to fetch location for IP: " + ip + " - " + e.getMessage()); |
| 72 | + } |
| 73 | + return "未知"; |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * 地理位置信息获取完成后的回调接口。 |
| 78 | + */ |
| 79 | + public interface LocationInfoCallback { |
| 80 | + void onLocationInfoReceived(String locationInfo); |
| 81 | + } |
| 82 | +} |
0 commit comments