Skip to content

Commit

Permalink
Created docker image
Browse files Browse the repository at this point in the history
  • Loading branch information
sthivaios committed Apr 21, 2024
1 parent 9e739f6 commit f5c9954
Show file tree
Hide file tree
Showing 20 changed files with 306 additions and 144 deletions.
15 changes: 15 additions & 0 deletions Docker/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM python:latest

WORKDIR /ciscapps/

ARG fullHostname
ARG hostname
ARG alphavantageKey
ARG serverPort

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .

CMD python3 api.py
216 changes: 94 additions & 122 deletions Docker/api.py
Original file line number Diff line number Diff line change
@@ -1,70 +1,99 @@
from flask import Flask, request, jsonify, Response
from datetime import datetime
from flask import Flask, request, Response, render_template
import requests
import random
# import ast
import openmeteo_requests
import requests_cache
import pandas as pd
import time
from retry_requests import retry
from unidecode import unidecode
import os

app = Flask(__name__)

apisrv = 236
stock_apikey = os.environ.get("stocks_api_key")
api_hostname = os.environ.get("api_hostname")
app = Flask(__name__, template_folder="./static/templates/")

import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)

stock_apikey = os.environ['alphavantageKey']
api_hostname = os.environ['hostname']
pfHostname = os.environ['fullHostname']
serverPort = os.environ['serverPort']
fullHostname = f'{pfHostname}:{serverPort}'

@app.route("/homepage/")
def homepage():
code = render_template("cisco.xml", hostname=fullHostname)
return Response(code, mimetype='text/xml')

@app.route("/scrOff/")
def scrOff():
code = render_template("scr-off.xml")
return Response(code, mimetype='text/xml')

@app.route("/getStock/")
def getStock():
code = render_template("get_stock.xml", hostname=fullHostname)
return Response(code, mimetype='text/xml')

@app.route("/getWeather/")
def getWeather():
code = render_template("geocode_weather.xml",hostname=fullHostname)
return Response(code, mimetype='text/xml')

@app.route("/info/")
def getInfo():
code = render_template("info.xml")
return Response(code, mimetype='text/xml')

@app.route("/playRps/")
def playRps():
code = render_template("rps.xml",hostname=fullHostname)
return Response(code, mimetype='text/xml')

@app.route("/getAqi/")
def getAqi():
code = render_template("geocode_aqi.xml",hostname=fullHostname)
return Response(code, mimetype='text/xml')

@app.route("/getGamesList/")
def getGamesList():
code = render_template("games.xml",hostname=fullHostname)
return Response(code, mimetype='text/xml')

@app.route("/getEnvApps/")
def getEnvApps():
code = render_template("environmental.xml",hostname=fullHostname)
return Response(code, mimetype='text/xml')

# backend calls

@app.route("/stock-price/")
def get_stock():
nsymb = request.args.get("symbol")
out = requests.get(f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={nsymb}&apikey={stock_apikey}")
out = out.json()
# out = "{'Global Quote': {'01. symbol': 'MSFT', '02. open': '371.0400', '03. high': '371.9500', '04. low': '367.3454', '05. price': '370.2700', '06. volume': '26816841', '07. latest trading day': '2023-11-14', '08. previous close': '366.6800', '09. change': '-3.5900', '10. change percent': '0.9791%'}}"
# out = ast.literal_eval(out)
# print(out)
price = round(float(out['Global Quote']['05. price']),2)
change = round(float(out['Global Quote']['09. change']),2)
price = round(float(out['Global Quote']['05. price']), 2)
change = round(float(out['Global Quote']['09. change']), 2)
change_percent = out['Global Quote']['10. change percent']
# print(type(price))

# print(price)

if change > 0:
up_or_down = "UP ^"
else:
up_or_down = "DOWN"

output = f"<CiscoIPPhoneText>\n"
output += f"<Title>Stock value for {nsymb.upper()}</Title>\n"
output += f"<Text>\n"
output += f"Symbol : {nsymb.upper()}\n"
output += f"Value : {price}$\n"
output += f"Change : {change}$ ({up_or_down})\n"
output += f"Change (%) : {change_percent}\n"
output += f"</Text>\n"
output += f"</CiscoIPPhoneText>"

return Response(output, mimetype='text/xml')

sResp = render_template("stock_value.xml", symbol=nsymb.upper(), price=price,
change=change, up_or_down=up_or_down, change_percent=change_percent)
return Response(sResp, mimetype='text/xml')

@app.route("/geocode-aqi/")
def geocode_aqi():
try:
name = request.args.get("name").upper()
out = requests.get(f"https://geocoding-api.open-meteo.com/v1/search?name={name}&count=10&language=en&format=json")
out = out.json()
print(out)
cities_data = out['results']
city_info_list = [{'name': city['name'], 'admin1': city.get('admin1', ''), 'latitude': city['latitude'],
'longitude': city['longitude'], 'country_code': city['country_code']} for city in cities_data]


# Print the result
for city_info in city_info_list:
print(
f"{city_info['name']}, {city_info['admin1']}, {city_info['latitude']}, {city_info['longitude']}, {city_info['country_code']}")
'longitude': city['longitude'], 'country_code': city['country_code']} for city in cities_data]

output = f"<CiscoIPPhoneMenu>\n"
output += f"<Title>Results for your search</Title>\n"
Expand All @@ -76,37 +105,25 @@ def geocode_aqi():
output += f" <Name>{city_name}, {city_info['admin1']}, {city_info['country_code']}</Name>"
city_name = city_name.replace(" ", "_")
city_region = city_region.replace(" ", "_")
output += f" <URL>http://{api_hostname}/air-quality/?latitude={city_info['latitude']}&amp;longtitude={city_info['longitude']}&amp;name={city_name}&amp;region={city_region}&amp;country={city_info['country_code']}</URL>"
output += f" <URL>{fullHostname}/air-quality/?latitude={city_info['latitude']}&amp;longtitude={city_info['longitude']}&amp;name={city_name}&amp;region={city_region}&amp;country={city_info['country_code']}</URL>"
output += f"</MenuItem>"
output += f"</CiscoIPPhoneMenu>"

return Response(output, mimetype='text/xml')
except:
output = f"<CiscoIPPhoneText>\n"
output += f"<Title>No results were found</Title>\n"
output += f"<Text>\n"
output += f"No results could be returned for your search.\nPerhaps you made a typo?</Text>\n"
output += f"</CiscoIPPhoneText>\n"
return Response(output, mimetype='text/xml')
return Response(render_template("no_results.xml"), mimetype='text/xml')
# return out, 200


@app.route("/geocode-weather/")
def geocode_weather():
try:
name = request.args.get("name").upper()
out = requests.get(f"https://geocoding-api.open-meteo.com/v1/search?name={name}&count=10&language=en&format=json")
out = out.json()
print(out)
cities_data = out['results']
city_info_list = [{'name': city['name'], 'admin1': city.get('admin1', ''), 'latitude': city['latitude'],
'longitude': city['longitude'], 'country_code': city['country_code']} for city in cities_data]

# Print the result
for city_info in city_info_list:
print(
f"{city_info['name']}, {city_info['admin1']}, {city_info['latitude']}, {city_info['longitude']}, {city_info['country_code']}")

output = f"<CiscoIPPhoneMenu>\n"
output += f"<Title>Results for your search</Title>\n"
for city_info in city_info_list:
Expand All @@ -117,21 +134,15 @@ def geocode_weather():
output += f" <Name>{city_name}, {city_info['admin1']}, {city_info['country_code']}</Name>"
city_name = city_name.replace(" ", "_")
city_region = city_region.replace(" ", "_")
output += f" <URL>http://{api_hostname}/weather/?latitude={city_info['latitude']}&amp;longtitude={city_info['longitude']}&amp;name={city_name}&amp;region={city_region}&amp;country={city_info['country_code']}</URL>"
output += f" <URL>{fullHostname}/weather/?latitude={city_info['latitude']}&amp;longtitude={city_info['longitude']}&amp;name={city_name}&amp;region={city_region}&amp;country={city_info['country_code']}</URL>"
output += f"</MenuItem>"
output += f"</CiscoIPPhoneMenu>"

return Response(output, mimetype='text/xml')
except:
output = f"<CiscoIPPhoneText>\n"
output += f"<Title>No results were found</Title>\n"
output += f"<Text>\n"
output += f"No results could be returned for your search.\nPerhaps you made a typo?</Text>\n"
output += f"</CiscoIPPhoneText>\n"
return Response(output, mimetype='text/xml')
return Response(render_template("no_results.xml"), mimetype='text/xml')
# return out, 200


@app.route("/air-quality/")
def get_air_quality():
latitude = float(request.args.get("latitude"))
Expand All @@ -141,43 +152,30 @@ def get_air_quality():
country = request.args.get("country")
out = requests.get(f"https://air-quality-api.open-meteo.com/v1/air-quality?latitude={latitude}&longitude={longtitude}&current=us_aqi,dust")
out = out.json()
print(out)
current = out['current']

dust = current['dust']
air_quality = current['us_aqi']
date = (f'{datetime.now().year}-{datetime.now().month}-{datetime.now().day} ' +
f'{datetime.now().hour}:{datetime.now().minute}:{datetime.now().second}')

print(dust)
print(air_quality)

output = f"<CiscoIPPhoneText>\n"
output += f"<Title>Air Quality</Title>\n"
output += f"<Text>\n"
output += f"{name}, {region}, {country}\n\n"
output += f"Dust : {dust}\n"
output += f"Air Quality (US AQI) : {air_quality}"
output += f"</Text>\n"
output += f"</CiscoIPPhoneText>"

aqResp = render_template("air_quality.xml", city=name, region=region, country=country,
dust=dust, air_quality=air_quality, last_update=date)

return Response(output, mimetype='text/xml')
return Response(aqResp, mimetype='text/xml')
# return out, 200


@app.route("/weather/")
def weather():
latitude = float(request.args.get("latitude"))
longtitude = float(request.args.get("longtitude"))
name = request.args.get("name").replace("_", " ")
region = request.args.get("region").replace("_", " ")
country = request.args.get("country")

# Setup the Open-Meteo backend client with cache and retry on error
cache_session = requests_cache.CachedSession('.cache', expire_after = 3600)
retry_session = retry(cache_session, retries = 5, backoff_factor = 0.2)
openmeteo = openmeteo_requests.Client(session = retry_session)

# Make sure all required weather variables are listed here
# Make sure all required weather variables are listed here
# The order of variables in hourly or daily is important to assign them correctly below
url = "https://api.open-meteo.com/v1/forecast"
params = {
Expand All @@ -197,71 +195,45 @@ def weather():
current_wind_speed_10m = current.Variables(2).Value()
current_wind_gusts_10m = current.Variables(3).Value()
current_relative_humidity_2m = current.Variables(4).Value()
date = (f'{datetime.now().year}-{datetime.now().month}-{datetime.now().day} '+
f'{datetime.now().hour}:{datetime.now().minute}:{datetime.now().second}')

wResp = render_template("weather.xml", city=name, region=region, country=country,
temperature=round(current_temperature_2m, 2), precipitation=current_precipitation,
w_speed=round(current_wind_speed_10m, 2), wg_speed=round(current_wind_gusts_10m, 2),
humidity=round(current_relative_humidity_2m, 2), last_update=date)

xml = f"<CiscoIPPhoneText>\n"
xml += "<Title>Current Weather</Title>\n"
xml += "<Text>\n"
xml += f"{name}, {region}, {country}\n\n"
xml += f"Temperature : {round(current_temperature_2m, 2)}C\n"
xml += f"Precipitation : {current_precipitation}mm\n"
xml += f"Wind speed : {round(current_wind_speed_10m, 2)}m/s\n"
xml += f"Wind gusts : {round(current_wind_gusts_10m, 2)}m/s\n"
xml += f"Humidity : {round(current_relative_humidity_2m, 2)}%"
xml += f"</Text>\n"
xml += f"</CiscoIPPhoneText>"

return Response(xml, mimetype='text/xml')

return Response(wResp, mimetype='text/xml')

@app.route("/rps/")
def rock_paper_scissors():
user_input = request.args.get("user_input")
global computer

possible = ['rock','paper','scissors']
computer = random.choice(possible)
print(computer)

if user_input == 'rock' and computer == 'paper':
output = f"{computer}\n"
output += "You loose!"
return output, 200
lWin = "You loose!"
elif user_input == 'rock' and computer == 'scissors':
output = f"{computer}\n"
output += "You win!"
return output, 200
lWin = "You win!"
elif user_input == 'rock' and computer == 'rock':
output = f"{computer}\n"
output += "Tie"
return output, 200
lWin = "Tie"
elif user_input == 'paper' and computer == 'rock':
output = f"{computer}\n"
output += "You win!"
return output, 200
lWin = "You win!"
elif user_input == 'paper' and computer == 'scissors':
output = f"{computer}\n"
output += "You loose!"
return output, 200
lWin = "You loose!"
elif user_input == 'paper' and computer == 'paper':
output = f"{computer}\n"
output += "Tie"
return output, 200
lWin = "Tie"
elif user_input == 'scissors' and computer == 'rock':
output = f"{computer}\n"
output += "You loose!"
return output, 200
lWin = "You loose!"
elif user_input == 'scissors' and computer == 'paper':
output = f"{computer}\n"
output += "You win"
return output, 200
lWin = "You win"
if user_input == 'scissors' and computer == 'scissors':
output = f"{computer}\n"
output += "Tie"
return output, 200
lWin = "Tie"

return 'knag', 200
rpsResp = render_template("rps_out.xml", computer=computer.capitalize(), result=lWin, hostname=fullHostname)

return Response(rpsResp, mimetype='text/xml')


if __name__ == "__main__":
Expand Down
18 changes: 9 additions & 9 deletions Docker/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
version: "3"

version: '3'
services:
api:
build: .
ports:
- "80:80"
ciscapps:
image: sthivaios/ciscapps:latest
environment:
- stocks_api_key="YOUR_ALPHAVANTAGE_API_KEY_HERE"
- api_hostname="YOUR_IP_OR_DOMAIN_THAT_THE_API_IS_HOSTED_ON"
# the variable above can either be an IP or a domain. it CANNOT be changed later. Keep in mind that the backend listens on port 80.
fullHostname: "" # full hostname with http/https here. eg. : https://ciscapps.com or http://192.168.1.150
hostname: "" # the ip or domain of the server
alphavantageKey: "XXXXXXXXXX" # your AlphaVantage API key
serverPort: "80"
ports:
- 80:80
11 changes: 0 additions & 11 deletions Docker/dockerfile

This file was deleted.

Loading

0 comments on commit f5c9954

Please sign in to comment.