Skip to content

Instantly share code, notes, and snippets.

@JonnyWong16
Last active February 25, 2020 08:26
Show Gist options
  • Select an option

  • Save JonnyWong16/48d6362884b5edbf5e6d78859035183a to your computer and use it in GitHub Desktop.

Select an option

Save JonnyWong16/48d6362884b5edbf5e6d78859035183a to your computer and use it in GitHub Desktop.

Revisions

  1. JonnyWong16 revised this gist Oct 24, 2016. 1 changed file with 40 additions and 30 deletions.
    70 changes: 40 additions & 30 deletions notify_geodata.py
    Original file line number Diff line number Diff line change
    @@ -11,8 +11,13 @@
    ## EDIT THESE SETTINGS ##

    PLEXPY_APIKEY = 'XXXX' # Your PlexPy API key
    PLEXPY_URL = 'http://localhost:8181/' # Your PlexPy url
    AGENT_ID = 7 # The notification agent ID for PlexPY
    PLEXPY_URL = 'http://localhost:8181/' # Your PlexPy URL
    AGENT_ID = 7 # The notification agent ID for PlexPy

    # Replace LAN IP addresses that start with the LAN_SUBNET with a WAN IP address
    # to retrieve geolocation data. Leave REPLACEMENT_WAN_IP blank for no replacement.
    LAN_SUBNET = '192.168.0'
    REPLACEMENT_WAN_IP = ''

    # The notification subject and body
    # - Use "{p.argument}" for script arguments
    @@ -28,17 +33,18 @@
    ## CODE BELOW ##

    class GeoData(object):
    def __init__(self, data):
    self.continent = data['continent']
    self.country = data['country']
    self.region = data['region']
    self.city = data['city']
    self.postal_code = data['postal_code']
    self.timezone = data['timezone']
    self.latitude = data['latitude']
    self.longitude = data['longitude']
    self.longitude = data['longitude']
    self.accuracy = data['accuracy']
    def __init__(self, data=None):
    data = data or {}
    self.continent = data.get('continent', 'N/A')
    self.country = data.get('country', 'N/A')
    self.region = data.get('region', 'N/A')
    self.city = data.get('city', 'N/A')
    self.postal_code = data.get('postal_code', 'N/A')
    self.timezone = data.get('timezone', 'N/A')
    self.latitude = data.get('latitude', 'N/A')
    self.longitude = data.get('longitude', 'N/A')
    self.longitude = data.get('longitude', 'N/A')
    self.accuracy = data.get('accuracy', 'N/A')

    def get_geoip_info(ip_address=''):
    # Get the geo IP lookup from PlexPy
    @@ -51,15 +57,17 @@ def get_geoip_info(ip_address=''):
    response = r.json()

    if response['response']['result'] == 'success':
    sys.stdout.write("Successfully retrieved geolocation data.")
    geodata = GeoData(data=response['response']['data'])
    return geodata
    data = response['response']['data']
    if data.get('error'):
    raise Exception(data['error'])
    else:
    sys.stdout.write("Successfully retrieved geolocation data.")
    return GeoData(data=data)
    else:
    sys.stderr.write("Failed to get geolocation data from PlexPy.")
    return None
    except:
    sys.stderr.write("PlexPy API 'get_geoip_lookup' request failed.")
    return None
    raise Exception(response['response']['message'])
    except Exception as e:
    sys.stderr.write("PlexPy API 'get_geoip_lookup' request failed: {0}.".format(e))
    return GeoData()

    def send_notification(arguments=None, geodata=None):
    # Format notification text
    @@ -84,11 +92,10 @@ def send_notification(arguments=None, geodata=None):
    if response['response']['result'] == 'success':
    sys.stdout.write("Successfully sent PlexPy notification.")
    else:
    sys.stderr.write("Failed to send PlexPy notification.")
    return
    except:
    sys.stderr.write("PlexPy API 'notify' request failed.")
    return
    raise Exception(response['response']['message'])
    except Exception as e:
    sys.stderr.write("PlexPy API 'notify' request failed: {0}.".format(e))
    return None

    if __name__ == '__main__':
    # Parse arguments from PlexPy
    @@ -116,9 +123,12 @@ def send_notification(arguments=None, geodata=None):

    # Check to make sure there is an IP address before proceeding
    if p.ip_address:
    geodata = get_geoip_info(ip_address=p.ip_address)

    if geodata:
    send_notification(arguments=p, geodata=geodata)
    if p.ip_address.startswith(LAN_SUBNET) and REPLACEMENT_WAN_IP:
    ip_address = REPLACEMENT_WAN_IP
    else:
    ip_address = p.ip_address

    geodata = get_geoip_info(ip_address=ip_address)
    send_notification(arguments=p, geodata=geodata)
    else:
    sys.stdout.write("No IP address passed from PlexPy.")
  2. JonnyWong16 revised this gist Oct 23, 2016. 1 changed file with 21 additions and 14 deletions.
    35 changes: 21 additions & 14 deletions notify_geodata.py
    Original file line number Diff line number Diff line change
    @@ -40,17 +40,11 @@ def __init__(self, data):
    self.longitude = data['longitude']
    self.accuracy = data['accuracy']

    def get_geoip_info():
    # Check to make sure there is an IP address before proceeding
    if not p.ip_address:
    sys.stdout.write("No IP address passed from PlexPy.")
    return


    def get_geoip_info(ip_address=''):
    # Get the geo IP lookup from PlexPy
    payload = {'apikey': PLEXPY_APIKEY,
    'cmd': 'get_geoip_lookup',
    'ip_address': p.ip_address}
    'ip_address': ip_address}

    try:
    r = requests.get(PLEXPY_URL.rstrip('/') + '/api/v2', params=payload)
    @@ -67,13 +61,21 @@ def get_geoip_info():
    sys.stderr.write("PlexPy API 'get_geoip_lookup' request failed.")
    return None

    def send_notification(geodata=None):
    def send_notification(arguments=None, geodata=None):
    # Format notification text
    try:
    subject = SUBJECT_TEXT.format(p=arguments, g=geodata)
    body = BODY_TEXT.format(p=arguments, g=geodata)
    except LookupError as e:
    sys.stderr.write("Unable to substitute '{0}' in the notification subject or body".format(e))
    return None

    # Send the notification through PlexPy
    payload = {'apikey': PLEXPY_APIKEY,
    'cmd': 'notify',
    'agent_id': AGENT_ID,
    'subject': SUBJECT_TEXT.format(p=p, g=geodata),
    'body': BODY_TEXT.format(p=p, g=geodata)}
    'subject': subject,
    'body': body}

    try:
    r = requests.post(PLEXPY_URL.rstrip('/') + '/api/v2', params=payload)
    @@ -112,6 +114,11 @@ def send_notification(geodata=None):

    p = parser.parse_args()

    # Run functions
    geodata = get_geoip_info()
    send_notification(geodata)
    # Check to make sure there is an IP address before proceeding
    if p.ip_address:
    geodata = get_geoip_info(ip_address=p.ip_address)

    if geodata:
    send_notification(arguments=p, geodata=geodata)
    else:
    sys.stdout.write("No IP address passed from PlexPy.")
  3. JonnyWong16 created this gist Oct 23, 2016.
    117 changes: 117 additions & 0 deletions notify_geodata.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,117 @@
    # 1. Install the requests module for python.
    # pip install requests
    # 2. Add script arguments in PlexPy. The following script arguments are available by default. More can be added below.
    # -ip {ip_address} -u {user} -mt {media_type} -t {title} -pf {platform} -pl {player} -da {datestamp} -ti {timestamp}

    import argparse
    import requests
    import sys


    ## EDIT THESE SETTINGS ##

    PLEXPY_APIKEY = 'XXXX' # Your PlexPy API key
    PLEXPY_URL = 'http://localhost:8181/' # Your PlexPy url
    AGENT_ID = 7 # The notification agent ID for PlexPY

    # The notification subject and body
    # - Use "{p.argument}" for script arguments
    # - Use "{g.value}" for geolocation data
    SUBJECT_TEXT = "PlexPy Notification"
    BODY_TEXT = "User <b>{p.user}</b> has watched {p.media_type} " \
    "<font color='blue'><b>'{p.title}'</b></font> on " \
    "<font color='green'>'{p.platform}'</font> " \
    "[<font color='green'>'{p.player}'</font>] in {g.city}, {g.country} " \
    "||| {p.datestamp}-{p.timestamp}"


    ## CODE BELOW ##

    class GeoData(object):
    def __init__(self, data):
    self.continent = data['continent']
    self.country = data['country']
    self.region = data['region']
    self.city = data['city']
    self.postal_code = data['postal_code']
    self.timezone = data['timezone']
    self.latitude = data['latitude']
    self.longitude = data['longitude']
    self.longitude = data['longitude']
    self.accuracy = data['accuracy']

    def get_geoip_info():
    # Check to make sure there is an IP address before proceeding
    if not p.ip_address:
    sys.stdout.write("No IP address passed from PlexPy.")
    return


    # Get the geo IP lookup from PlexPy
    payload = {'apikey': PLEXPY_APIKEY,
    'cmd': 'get_geoip_lookup',
    'ip_address': p.ip_address}

    try:
    r = requests.get(PLEXPY_URL.rstrip('/') + '/api/v2', params=payload)
    response = r.json()

    if response['response']['result'] == 'success':
    sys.stdout.write("Successfully retrieved geolocation data.")
    geodata = GeoData(data=response['response']['data'])
    return geodata
    else:
    sys.stderr.write("Failed to get geolocation data from PlexPy.")
    return None
    except:
    sys.stderr.write("PlexPy API 'get_geoip_lookup' request failed.")
    return None

    def send_notification(geodata=None):
    # Send the notification through PlexPy
    payload = {'apikey': PLEXPY_APIKEY,
    'cmd': 'notify',
    'agent_id': AGENT_ID,
    'subject': SUBJECT_TEXT.format(p=p, g=geodata),
    'body': BODY_TEXT.format(p=p, g=geodata)}

    try:
    r = requests.post(PLEXPY_URL.rstrip('/') + '/api/v2', params=payload)
    response = r.json()

    if response['response']['result'] == 'success':
    sys.stdout.write("Successfully sent PlexPy notification.")
    else:
    sys.stderr.write("Failed to send PlexPy notification.")
    return
    except:
    sys.stderr.write("PlexPy API 'notify' request failed.")
    return

    if __name__ == '__main__':
    # Parse arguments from PlexPy
    parser = argparse.ArgumentParser()

    parser.add_argument('-ip', '--ip_address', action='store', default='',
    help='The IP address of the stream')
    parser.add_argument('-u', '--user', action='store', default='',
    help='Username of the person watching the stream')
    parser.add_argument('-mt', '--media_type', action='store', default='',
    help='The media type of the stream')
    parser.add_argument('-t', '--title', action='store', default='',
    help='The title of the media')
    parser.add_argument('-pf', '--platform', action='store', default='',
    help='The platform of the stream')
    parser.add_argument('-pl', '--player', action='store', default='',
    help='The player of the stream')
    parser.add_argument('-da', '--datestamp', action='store', default='',
    help='The date of the stream')
    parser.add_argument('-ti', '--timestamp', action='store', default='',
    help='The time of the stream')
    # Add more arguments as needed

    p = parser.parse_args()

    # Run functions
    geodata = get_geoip_info()
    send_notification(geodata)