Skip to content

Commit

Permalink
Initial code commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nikdoof committed Nov 28, 2023
1 parent c885b0e commit 7f86756
Show file tree
Hide file tree
Showing 7 changed files with 555 additions and 0 deletions.
1 change: 1 addition & 0 deletions local_spaces/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VERSION = '0.0.1'
42 changes: 42 additions & 0 deletions local_spaces/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@

import secrets

from flask import Flask
from prometheus_flask_exporter import PrometheusMetrics

from local_spaces import VERSION
from local_spaces.local import local


def create_app():
app = Flask("local-spaces")
app.config.update(
{
"SECRET_KEY": secrets.token_hex(64),
"TESTING": False,
"DEBUG": False,
"LOCALSPACES_SPACEAPI_ENDPOINT": "https://api.spaceapi.io",
"LOCALSPACES_LOCAL_ENDPOINT": "https://api.leighhack.org/space.json",
"LOCALSPACES_DISTANCE": 300,
}
)
app.config.from_prefixed_env()
register_extensions(app)
register_blueprints(app)

@app.context_processor
def inject_app_info():
return {"app_version": VERSION}

return app


def register_extensions(app):
# Prometheus Metrics
metrics = PrometheusMetrics.for_app_factory()
metrics.info("local_spaces_info", "Information about Local-Spaces", version=VERSION)
metrics.init_app(app)


def register_blueprints(app):
app.register_blueprint(local)
66 changes: 66 additions & 0 deletions local_spaces/local.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from flask import Blueprint, render_template, current_app
from math import radians, cos, sin, asin, sqrt
import requests

local = Blueprint(
"local", __name__, template_folder="templates", static_folder="static"
)


def calculate_distance(src: tuple, dest: tuple) -> float:
# https://stackoverflow.com/a/4913653
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(radians, [src[0], src[1], dest[0], dest[1]])

# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles. Determines return value units.
return c * r


@local.route("/")
def index():
return render_template("index.html")


@local.route("/local_spaces.json")
def spaces():
# Get the local hackspace Space JSON
resp = requests.get(current_app.config.get("LOCALSPACES_LOCAL_ENDPOINT"))

if resp.ok:
data = resp.json()
source = data["location"]["lat"], data["location"]["lon"]

# Iterate through hackspaces
spaces = []
resp = requests.get(current_app.config.get("LOCALSPACES_SPACEAPI_ENDPOINT"))
if resp.ok:
data = resp.json()

for space in data:
# If the SpaceAPI hasn't had a valid response, skip
if not space["valid"]:
continue
# If the hackspace is the source, skip
if space["url"] == current_app.config.get("LOCALSPACES_LOCAL_ENDPOINT"):
continue

# Check if the hackspace has a lat/lon
if "location" in space["data"] and "lat" in space["data"]["location"]:
dest = (
space["data"]["location"]["lat"],
space["data"]["location"]["lon"],
)

# If its within the radius, add it to the list
distance = calculate_distance(source, dest)
if distance <= float(current_app.config.get("LOCALSPACES_DISTANCE")):
print("Added {0}".format(space["data"]["space"]))
space['distance'] = distance
spaces.append(space)

return spaces
Empty file added local_spaces/static/style.css
Empty file.
57 changes: 57 additions & 0 deletions local_spaces/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Local Spaces</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.7.1.min.js" crossorigin="anonymous"></script>
<link rel=stylesheet
href=https://web-test.leighhack.org/css/leighhack.min.4d84caa1fa6de0b3253d5ffdde20e14609fa2683b065b0abca10fe2a24719839.css
integrity="sha256-TYTKofpt4LMlPV/93iDhRgn6JoOwZbCryhD+KiRxmDk=" crossorigin=anonymous>
<style>

img#space-logo {
max-height: 200px;
}
div.space-box {
min-height: 300px;
}
</style>
</head>

<body>
<template id="space-block">
<div class="column is-one-quarter">
<div class="box space-box">
<h4 id="space-name"></h3>
<img id="space-logo" class="is-centered" src="">
<p>Distance: <span id="space-distance"></span>km</p>
</div>
</div>
</template>
<section class="section">
<h1>Other Local Hackspaces</h1>
<div class="container content">
<div class="columns is-centered is-multiline" id="spaces"></div>
</div>
</section>
<script>
$(document).ready(function () {
$.getJSON('/local_spaces.json', function (data) {
const spaces = Array.from(data).sort((a, b) => a['data']['distance'] - b['data']['distance']);
spaces.forEach(function (val, indx) {
var obj = $($("template#space-block").html());
obj.find('#space-name').html(val['data']['space']);
obj.find('#space-distance').html(val['distance']);
obj.find('#space-logo').attr('src', val['data']['logo']);
$('div#spaces').append(obj);
});
});
});
</script>
</body>

</html>
Loading

0 comments on commit 7f86756

Please sign in to comment.