#!/usr/bin/python
# -*- coding: utf-8 -*-

# --------------------------------------------------------------------------- #
#                                                                             #
#    Plugin for iSida Jabber Bot                                              #
#    Copyright (C) diSabler <dsy@dsy.name>                                    #
#    Modified: uses free ip-api.com instead of local DB                      #
#                                                                             #
#    This program is free software: you can redistribute it and/or modify     #
#    it under the terms of the GNU General Public License as published by     #
#    the Free Software Foundation, either version 3 of the License, or        #
#    (at your option) any later version.                                      #
#                                                                             #
#    This program is distributed in the hope that it will be useful,          #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
#    GNU General Public License for more details.                             #
#                                                                             #
#    You should have received a copy of the GNU General Public License        #
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.    #
#                                                                             #
# --------------------------------------------------------------------------- #

import socket
import urllib.request
import json

def geoip(type, jid, nick, text):
    text = text.strip().lower()
    is_ip = None

    # Проверяем, является ли текст IP-адресом
    if text.count('.') == 3:
        is_ip = True
        for ii in text:
            if ii not in nmbrs:
                is_ip = None
                break

    # Получаем IP
    if is_ip:
        IP = text
    else:
        try:
            IP = socket.gethostbyname_ex(text.encode('idna'))[2][0]
        except:
            IP = None

    if not IP:
        send_msg(type, jid, nick, L('I can\'t resolve it', '%s/%s' % (jid, nick)))
        return

    # Запрос к бесплатному API
    try:
        url = f'http://ip-api.com/json/{IP}?fields=status,message,country,regionName,city,zip,lat,lon,isp,org,as,query'
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        with urllib.request.urlopen(req, timeout=10) as resp:
            data = json.loads(resp.read().decode('utf-8'))

        if data.get('status') != 'success':
            send_msg(type, jid, nick, L('GEO info not found!', '%s/%s' % (jid, nick)))
            return

        msg = L('IP: %s\nCountry: %s\nRegion: %s\nCity: %s\nZIP: %s\nLat/Lon: %s/%s\nISP: %s\nOrg: %s\nAS: %s',
                '%s/%s' % (jid, nick)) % (
            data.get('query', '?'),
            data.get('country', '?'),
            data.get('regionName', '?'),
            data.get('city', '?'),
            data.get('zip', '?'),
            data.get('lat', '?'),
            data.get('lon', '?'),
            data.get('isp', '?'),
            data.get('org', '?'),
            data.get('as', '?')
        )
        send_msg(type, jid, nick, msg)

    except Exception as e:
        send_msg(type, jid, nick, L('GEO info not found!', '%s/%s' % (jid, nick)))

global execute

if base_type in ['pgsql', 'sqlite3']:
    execute = [(4, 'geo', geoip, 2, 'GEOIP information about IP or domain')]
