DynDns/src/IpManager.py

74 lines
1.7 KiB
Python

#!/usr/bin/env python
import requests
import logging
import os
logger = logging.getLogger(__file__)
class IpManager():
ipFile = None
def __init__(self, ipFile):
logger.debug('Initialozing IpManager')
self.ipFile = ipFile
def _getLastIp(self):
"""
Extracts the ip from the ipFile, and creates the file if it does not exist
"""
logger.debug('getLastIp called')
try:
with open(self.ipFile, 'r') as f:
ip = f.read()
logger.info(f'Found ip {ip}')
return ip
except FileNotFoundError:
logger.info('IP File not found, creating new one')
open(self.ipFile, 'a').close()
return None
except Exception as e:
logger.error(f'Error: {str(e)}')
return None
def _storeNewIp(self, ip):
"""
Stores the ip in the ipFile
"""
logger.debug(f'Store {ip} to file')
with open(self.ipFile, 'w') as f:
f.write(ip)
def _fetchCurrentIp(self):
logger.debug('Fetching current ip')
current = requests.get('https://api.ipify.org').text.strip()
logger.debug(f'current ip is {current}')
return current
def hasIpChanged(self):
"""
Checks if the ip has changed and returns it if so, else return False
"""
last = self._getLastIp()
current = self._fetchCurrentIp()
if last is None or last != current:
logger.debug(f'Ip has changed from {last} to {current}')
self._storeNewIp(current)
return current
return None