Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
abhijeetpandit7 committed Feb 16, 2021
0 parents commit 3808f6a
Show file tree
Hide file tree
Showing 18 changed files with 1,962 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
*.env
*.pyc
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Abhijeet Pandit

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: node app.js
5 changes: 5 additions & 0 deletions Python-Automate-Email/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Automate sending email to subscribers with cheapest flight-deals

### Sign up [here](https://flightdeals.herokuapp.com/), We'll let you know when flights to amazing destinations go really, reaaally cheap!

<img src= 'https://user-images.githubusercontent.com/65078610/108055938-a6b0f980-7076-11eb-971c-41370a14bfb8.PNG' width="700">
35 changes: 35 additions & 0 deletions Python-Automate-Email/data_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#This class is responsible for talking to the Google Sheet.
import os
import json
from pprint import pprint
import requests
from dotenv import load_dotenv
load_dotenv()

class DataManager:

def __init__(self):
self.sheety_endpoint = "https://api.sheety.co/126f9e38bb1fc18f122cb26e242ee654/flightDeals"
self.headers = {
'Authorization': os.getenv('AUTH_TOKEN')
}

def get_data(self):
response = requests.get(url=self.sheety_endpoint+'/prices', headers=self.headers)
data = json.loads(response.text)['prices']
return data

def update_data(self, row_id, new_price):
sheety_update_endpoint = f"{self.sheety_endpoint+'/prices'}/{row_id}"
price_config = {
'price': {
"lowestPrice": round(new_price)
}
}
response = requests.put(url=sheety_update_endpoint, json=price_config , headers=self.headers)
print(response.text)

def get_users(self):
response = requests.get(url=self.sheety_endpoint+'/users', headers=self.headers)
data = json.loads(response.text)['users']
return data
32 changes: 32 additions & 0 deletions Python-Automate-Email/flight_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#This class is responsible for structuring the flight data.
class FlightData:

def compare(self, price_data, lowest_price):
# Normalize API price hike
lowest_price += lowest_price*14.8/100
self.price_data = price_data
self.price_array = []
self.date_array = []
for data in self.price_data:
self.price_array.append(int(data['price']))
self.date_array.append((data['route'][0]['local_arrival'])[:10])
self.min_price = min(self.price_array)
return self.min_price < lowest_price

def get_data(self):
low_limit = self.price_array.index(self.min_price)
self.price_array.reverse()
high_limit = self.price_array.index(self.min_price)
self.min_price -= self.min_price*13/100
flight_details = {
'price': round(self.min_price),
'cityFrom': self.price_data[0]['route'][0]['cityFrom'],
'cityCodeFrom': self.price_data[0]['route'][0]['cityCodeFrom'],
'cityTo': self.price_data[0]['route'][0]['cityTo'],
'cityCodeTo': self.price_data[0]['route'][0]['cityCodeTo'],
'dateFrom': self.date_array[low_limit],
'dateTo': ''
}
self.date_array.reverse()
flight_details['dateTo'] = self.date_array[high_limit]
return flight_details
44 changes: 44 additions & 0 deletions Python-Automate-Email/flight_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#This class is responsible for talking to the Flight Search API.
from dotenv import load_dotenv
from pprint import pprint
from datetime import *
import requests
import os

load_dotenv()
FLY_FROM = 'BOM'
CURRENCY = 'INR'
FLIGHT_TYPE = 'oneway'
SORT_BY = 'date'

class FlightSearch:

def __init__(self):
self.from_date =(datetime.now()+timedelta(days=1)).strftime('%d/%m/%Y')
self.to_date =(datetime.now()+timedelta(days=180)).strftime('%d/%m/%Y')
self.kiwi_endpoint = "https://tequila-api.kiwi.com/v2/search/"
self.headers = {
'apikey': os.getenv('API_KEY')
}
self.parameters = {
'fly_from': FLY_FROM,
'fly_to': '',
'date_from': self.from_date,
'date_to': self.to_date,
'curr': CURRENCY,
'flight_type': FLIGHT_TYPE,
'one_per_date': 1,
'sort': SORT_BY
}

def get_data(self, fly_to):
self.parameters['fly_to'] = fly_to
response = requests.get(url=self.kiwi_endpoint, params=self.parameters, headers=self.headers)
try:
data = response.json()['data']
except KeyError:
print(f"No flights available to {fly_to}")
return []
else:
# pprint(data[0])
return data
26 changes: 26 additions & 0 deletions Python-Automate-Email/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#This file will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements.
from notification_manager import NotificationManager
from flight_search import FlightSearch
from flight_data import FlightData
from data_manager import DataManager

notification_manager = NotificationManager()
flight_search = FlightSearch()
flight_data = FlightData()
data_manger = DataManager()
user_list = data_manger.get_users()
destination_list = data_manger.get_data()

for city in destination_list:
city_id = city['id']
lowest_price = city['lowestPrice']
fly_to = city['iataCode']
price_data = flight_search.get_data(fly_to)
# Check if no flights available
if not price_data:
continue
is_cheap_deal = flight_data.compare(price_data, lowest_price)
if is_cheap_deal:
flight_details = flight_data.get_data()
data_manger.update_data(city_id, flight_data.min_price)
notification_manager.send_alert(flight_details, user_list)
39 changes: 39 additions & 0 deletions Python-Automate-Email/notification_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# This class is responsible for sending notifications with the deal flight details.
from calendar import month_name
from dotenv import load_dotenv
import smtplib
import os

load_dotenv()
my_email = os.getenv('EMAIL')
my_password = os.getenv('PASSWORD')

class NotificationManager:

def send_alert(self, data, users):
link = (f"https://www.google.co.in/flights?hl=en#flt={data['cityCodeFrom']}.{data['cityCodeTo']}."+
f"{data['dateFrom']}*{data['cityCodeTo']}.{data['cityCodeFrom']}.{data['dateTo']}")
with smtplib.SMTP(host="smtp.gmail.com", port=587) as connection:
connection.starttls()
connection.login(my_email, my_password)
for user in users:
to_email = user['email']
fName = user['firstName']
connection.sendmail(
from_addr=my_email,
to_addrs=to_email,
msg=("Subject:Flight Deals Alert!✈️\n\n"+
f"Hi, {fName},\n"
f"Super cheap fares to {data['cityTo']}. Get in. On this!\n"+
f"This is the cheapest deal to {data['cityTo']} in the upcoming 6 months.\n\n"
f"Only ₹{data['price']:,} to fly from, \n"+
f"{data['cityFrom']} ({data['cityCodeFrom']}) "+
f"to {data['cityTo']} ({data['cityCodeTo']}).\n"+
f"Tickets available from {self.dateFormat(data['dateFrom'])} to {self.dateFormat(data['dateTo'])}\n"+
f"{link}\n\n"+
"Cheers, \nAbhijeet").encode('utf-8')
)

def dateFormat(self, str):
arr = str.split('-')
return (f"{arr[2]} {month_name[int(arr[1].strip('0'))]}, {arr[0]}")
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Flight Club Subscription

### Sign up [here](https://flightdeals.herokuapp.com/), We'll let you know when flights to amazing destinations go really, reaaally cheap!

### Here's is How It Works
- ExpressJS handles new subscriber data.
- Stores the user data.
- Python searches cheapest flights to popular destination within 6 months.
- Send emails with flight details to subscribers.

Deployed link -> https://flightdeals.herokuapp.com/
61 changes: 61 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const https = require('https');
const app = express();

app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended : true}));

app.get("/",function(req,res){
res.sendFile(__dirname+"/signup.html");
});

app.post("/",function(req,res){
var firstName = req.body.fname;
var lastName = req.body.lname;
var email = req.body.email;
const data = {
members : [
{
email_address : email,
status : "subscribed",
merge_fields : {
FNAME : firstName,
LNAME : lastName,
}
}
]
};
const jsonData = JSON.stringify(data);

const api_key = process.env.API;
const list_id = process.env.LIST;
const url = "https://us1.api.mailchimp.com/3.0/lists/"+list_id;
const options = {
method : "POST",
auth : "abhijeet:"+api_key
};
const request = https.request(url, options, function(response){
var statusCode = response.statusCode;
if(statusCode=='200'){
res.sendFile(__dirname+"/success.html");
}
else{
res.sendFile(__dirname+"/failure.html");
}
response.on("data",function(data){
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end();
});

app.post("/failure",function(req,res){
res.redirect("/");
});

app.listen(process.env.PORT || 3000,function(){
console.log("Server started");
});
24 changes: 24 additions & 0 deletions failure.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no">
<meta name="description" content="Flight Club: Get cheapest flight deals!">
<meta name="author" content="Abhijeet Pandit">
<title>Try again!</title>
<link rel="icon" href="image/newsletter.png">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- Custom styles -->
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<div class="jumbotron centered">
<h1 class="display-4">Uh Oh!</h1>
<p class="lead">Looks like there was some problem on our side. Please try again later.</p>
<form action="/failure" method="post">
<button class="btn btn-warning btn-lg" type="submit" name="button">Try again</button>
</form>
</div>
</body>
</html>
Loading

0 comments on commit 3808f6a

Please sign in to comment.