AviKeinan

Emergency location tracker

Oct 15th, 2019
730
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.48 KB | None | 0 0
  1. import json
  2. import boto3
  3. import os
  4. import random
  5. import string
  6. import botocore.vendored.requests as requests
  7. from botocore.exceptions import ClientError
  8. from urllib.parse import urlparse, parse_qs
  9.  
  10.  
  11. def send_sms(number, message):
  12.     client = boto3.client('sns')
  13.     try:
  14.         client.publish(PhoneNumber=number, Message=message)
  15.     except Exception as e:
  16.         print(e)
  17.         return False
  18.     return True
  19.  
  20.  
  21. def lambda_handler(event, context):
  22.     if 'httpMethod' in event:
  23.         http_method = event['httpMethod']
  24.  
  25.         if 'queryStringParameters' in event:
  26.             query_string = event['queryStringParameters']
  27.         else:
  28.             query_string = ''
  29.         path = event['path']
  30.         print(' my path is: ' + path)
  31.         if http_method == 'GET':
  32.             if path == '':
  33.                 html = 'Nothing to see here'
  34.             if path == '/t':
  35.                 html = '''
  36.                            <form action="" method="post">
  37.                              Phone number:<br>
  38.                              <input type="text" name="number" value="332-">
  39.                              <br>
  40.                              <input type="submit" value="Submit">
  41.                            </form>
  42.        
  43.                            </body>
  44.                        </html>
  45.                    '''
  46.             # emergency client landing page
  47.             elif '/test' in path:
  48.                 html = '''
  49.            <html>
  50.            <body>
  51.            
  52.            <center><p><h2><b>EMERGENCY TRACKER</h2></b></p></center>
  53.            
  54.            <center><button style="height:1400px;width:900px" onclick="getLocation()"><h1><b>CLICK TO SHAERE LOCATION</h1></b></button></center>
  55.            
  56.            <p id="demo"></p>
  57.            
  58.            <script>
  59.            var x = document.getElementById("demo");
  60.            var xhttp = new XMLHttpRequest();
  61.            var urlParams = new URLSearchParams(window.location.search);
  62.  
  63.  
  64.            function getLocation() {
  65.              if (navigator.geolocation) {
  66.                navigator.geolocation.watchPosition(showPosition);
  67.              } else {
  68.                x.innerHTML = "Geolocation is not supported by this browser.";
  69.              }
  70.            }
  71.                
  72.            function showPosition(position) {
  73.                xhttp.open("GET", "https://gps.yoyo.co.il/location=true&id=" + urlParams.get('id') + "&latitude=" + position.coords.latitude + "&longitude=" + position.coords.longitude, true);
  74.                xhttp.send();
  75.            }
  76.            </script>
  77.            
  78.            </body>
  79.            </html>
  80.  
  81.                '''
  82.             # push location to s3
  83.             elif '/location' in path:
  84.                 parse_post_body = parse_qs(path)
  85.                 s3 = boto3.resource('s3')
  86.                 print(parse_post_body)
  87.                 if 'latitude' in parse_post_body:
  88.                     print(1)
  89.                     latitude = parse_post_body['latitude'][0]
  90.                     longitude = parse_post_body['longitude'][0]
  91.                     id = parse_post_body['id'][0]
  92.                     content=str({'latitude': latitude, 'longitude': longitude})
  93.                     s3.Object('gps-super-secret', id + '.txt').put(Body=content)
  94.                 html = '''
  95.                ok
  96.                '''
  97.             # show location to rep
  98.             elif '/get_location' in path:
  99.                 parse_post_body = parse_qs(path)
  100.                 s3 = boto3.resource('s3')
  101.                 id = query_string['id']
  102.                 if id:
  103.                     obj = s3.Object('gps-super-secret', id + '.txt')
  104.                     try:
  105.                         location = json.loads(obj.get()['Body'].read().decode('utf-8').replace('\'', '"'))
  106.                     except ClientError as ex:
  107.                         if ex.response['Error']['Code'] == 'NoSuchKey':
  108.                             return {'statusCode': 200,
  109.                                     'headers': {
  110.                                         'Content-Type': 'text/html',
  111.                                     },
  112.                                     'body': '<b><h1>No results yet</b></h1> <meta http-equiv="refresh" content="5" />'
  113.                             }
  114.                     lat = location['latitude']
  115.                     lng = location['longitude']
  116.                 html =  '''<html>
  117.  <head>
  118.    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  119.    <meta charset="utf-8">
  120.    <title>Simple Markers</title>
  121.    <style>
  122.      #map {
  123.        height: 100%;
  124.      }
  125.      html, body {
  126.        height: 100%;
  127.        margin: 0;
  128.        padding: 0;
  129.      }
  130.    </style>
  131.  </head>
  132.  <body>
  133.    <div id="map"></div>
  134.    <script>
  135.  
  136.      function initMap() {
  137.        var myLatLng = {lat: ''' + lat + ''', lng: ''' + lng + '''};
  138.  
  139.        var map = new google.maps.Map(document.getElementById('map'), {
  140.          zoom: 18,
  141.          center: myLatLng
  142.        });
  143.  
  144.        var marker = new google.maps.Marker({
  145.          position: myLatLng,
  146.          map: map,
  147.          title: 'Hello World!'
  148.        });
  149.      }
  150.    </script>
  151.    <script async defer
  152.    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&callback=initMap">
  153.    </script>
  154.  </body>
  155. </html>
  156. '''
  157.             else:
  158.                 html = path
  159.                 print(event)
  160.             return {
  161.                 'statusCode': 200,
  162.                 'headers': {
  163.                     'Content-Type': 'text/html',
  164.                 },
  165.                 'body': html
  166.             }
  167.         elif http_method == 'POST':
  168.             random_string = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
  169.             phone_number = event['body'].split('=')[1]
  170.             send_sms(phone_number, f'Locaiton tracker - go to https://gps.yoyo.co.il/test?id={random_string}')
  171.             html = f'sent sms to {phone_number}, go to: <a href="https://gps.yoyo.co.il/get_location?t=1&id={random_string}">here</a> to watch location'
  172.             return {
  173.                 'statusCode': 200,
  174.                 'headers': {
  175.                     'Content-Type': 'text/html',
  176.                 },
  177.                 'body': html
  178.             }
  179.         else:
  180.             return {
  181.                 'statusCode': 200,
  182.                 'headers': {
  183.                     'Content-Type': 'application/javascript',
  184.                 },
  185.                 'body': json.dumps(event, sort_keys=True, indent=4)
  186.             }
Advertisement
Add Comment
Please, Sign In to add comment