Skip to content

Commit

Permalink
feat: adding a settings saver
Browse files Browse the repository at this point in the history
  • Loading branch information
TheAveron committed Sep 1, 2024
1 parent 8faf4a3 commit 28c4d47
Show file tree
Hide file tree
Showing 6 changed files with 190 additions and 7 deletions.
47 changes: 42 additions & 5 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
url_for)
from werkzeug import Response

from modules import ( fetch_tle_data, get_current_position,
from modules import (fetch_tle_data, get_current_position,
get_future_positions, get_iss_crew, get_iss_info,
get_logged_in_user, get_next_passes, init_db, login_user,
logout_user, register_user,
verify_user)
get_logged_in_user, get_next_passes, init_db,
load_specific_map_settings, login_user, logout_user,
register_user, save_specific_map_settings, verify_user)

# Load environment variables
load_dotenv()
Expand Down Expand Up @@ -161,5 +161,42 @@ def next_passes() -> Tuple[Response, int]:
passes = get_next_passes(TLE, lat, lon, num_passes=3)
return jsonify(passes), 200


@app.route("/save-map-settings", methods=["POST"])
def save_map_settings():
user_id = request.json["userId"] # type:ignore
if not user_id:
return jsonify({"error": "User not logged in"}), 401

data = request.json
save_specific_map_settings(user_id, data["toggle_iss"], data["toggle_trajectory"], data["trajectory_time"], data["zoom_level"]) # type: ignore

return jsonify({"status": "success"}), 200


@app.route("/load-map-settings", methods=["GET", "POST"])
def load_map_settings():
print("eeeeee")
user_id = request.form["user_id"]
if not user_id:
return jsonify({"error": "User not logged in"}), 401

settings = load_specific_map_settings(user_id)
if settings:
return (
jsonify(
{
"toggle_iss": settings[0],
"toggle_trajectory": settings[1],
"trajectory_time": settings[2],
"zoom_level": settings[3],
}
),
200,
)
else:
return jsonify({"error": "No settings found"}), 404


if __name__ == "__main__":
app.run(debug=False)
app.run(debug=False)
Binary file modified database.db
Binary file not shown.
2 changes: 1 addition & 1 deletion modules/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
from .iss_info import *
from .iss_tracker import *
from .tle_fetcher import *
from .user_service import *
from .user_service import *
17 changes: 16 additions & 1 deletion modules/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def init_db() -> None:
"""
Initializes the database by creating the necessary tables if they do not exist.
This function creates the `users` table if it's not already present.
This function creates the `users` and the `users_settings` table if it's not already present.
"""
with sqlite3.connect(DATABASE_FILE) as conn:
cursor = conn.cursor()
Expand All @@ -24,6 +24,21 @@ def init_db() -> None:
"""
)

# create the users_settings table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS user_settings (
user_id INTEGER PRIMARY KEY,
toggle_iss BOOLEAN,
toggle_trajectory BOOLEAN,
trajectory_time INTEGER,
zoom_level INTEGER,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(user_id) REFERENCES users(id)
);
"""
)

conn.commit()


Expand Down
41 changes: 41 additions & 0 deletions modules/user_service.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import sqlite3
from datetime import datetime
from typing import Optional

from flask import session
Expand Down Expand Up @@ -76,3 +77,43 @@ def get_logged_in_user() -> Optional[int]:
Optional[int]: The user ID if logged in, None otherwise.
"""
return session.get("user_id")


def save_specific_map_settings(
user_id, toggle_iss, toggle_trajectory, trajectory_time, zoom_level
):
with get_db_connection() as con:
cur = con.cursor()
cur.execute(
"""
INSERT INTO user_settings (user_id, toggle_iss, toggle_trajectory, trajectory_time, zoom_level, timestamp)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
toggle_iss = excluded.toggle_iss,
toggle_trajectory = excluded.toggle_trajectory,
trajectory_time = excluded.trajectory_time,
zoom_level = excluded.zoom_level,
timestamp = excluded.timestamp
""",
(
user_id,
toggle_iss,
toggle_trajectory,
trajectory_time,
zoom_level,
datetime.now(),
),
)
con.commit()


def load_specific_map_settings(user_id):
with get_db_connection() as con:
data = con.execute(
"""
SELECT toggle_iss, toggle_trajectory, trajectory_time, zoom_level
FROM user_settings WHERE user_id = ?
""",
(user_id,),
)
return data.fetchone()
90 changes: 90 additions & 0 deletions static/js/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,93 @@ var issIcon = L.icon({

var issMarker = L.marker([0, 0], {icon: issIcon}).addTo(map);
var trajectoryPolylines = [];

function saveMapSettings() {
const mapSettings = {
userId: document.getElementById('user-id').value,
toggle_iss: document.getElementById('toggle-iss').checked,
toggle_trajectory: document.getElementById('toggle-trajectory').checked,
trajectory_time: document.getElementById('trajectory-time-slider').value,
zoom_level: map.getZoom()
};

fetch('/save-map-settings', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(mapSettings)
})
.then(response => response.json())
.then(data => {
if (data.status !== 'success') {
console.error('Failed to save map settings:', data);
}
});
}

// Attach saveMapSettings to relevant events like zoom, toggle, and slider change events
document.getElementById('toggle-iss').addEventListener('change', saveMapSettings);
document.getElementById('toggle-trajectory').addEventListener('change', saveMapSettings);
document.getElementById('trajectory-time-slider').addEventListener('input', saveMapSettings);
map.on('zoomend', saveMapSettings);

function loadMapSettings() {
fetch('/load-map-settings', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `user_id=${document.getElementById('user-id').value}`,
})
.then(response => response.json())
.then(settings => {
if (!settings.error) {
document.getElementById('toggle-iss').checked = settings.toggle_iss;
document.getElementById('toggle-trajectory').checked = settings.toggle_trajectory;
document.getElementById('trajectory-time-slider').value = settings.trajectory_time;
map.setZoom(settings.zoom_level);

// Apply the settings (e.g., show/hide ISS, trajectory based on toggles)
applySettings(settings);
}
})
.catch(error => console.error('Error loading map settings:', error));
}

function applySettings(settings) {
// Toggle ISS and trajectory visibility
toggleVisibility(issMarker, settings.toggle_iss);
toggleVisibility(trajectoryPath, settings.toggle_trajectory);

// Adjust trajectory time
adjustTrajectoryTime(settings.trajectory_time);

// Set map zoom level
if (map) {
map.setZoom(settings.zoom_level);
}
}

// Generic function to toggle visibility for markers or paths
function toggleVisibility(object, isVisible) {
if (object) {
object.setVisible(isVisible);
}
}

// Adjust the trajectory time based on the saved slider value
function adjustTrajectoryTime(time) {
fetch(`/future-trajectory?duration=${time}`)
.then(response => response.json())
.then(data => {
if (trajectoryPath) {
trajectoryPath.setPath(data);
}
})
.catch(error => console.error('Error fetching future trajectory:', error));
}


// Call this function on page load
document.addEventListener('DOMContentLoaded', loadMapSettings);

0 comments on commit 28c4d47

Please sign in to comment.