Skip to content

Commit

Permalink
Merge pull request #10 from joaovitoriasilva/backend_revamp
Browse files Browse the repository at this point in the history
Backend revamp | Strava gear | User password change
  • Loading branch information
joaovitoriasilva authored Feb 10, 2024
2 parents 23bdc5f + c0f516c commit 3824f34
Show file tree
Hide file tree
Showing 100 changed files with 8,339 additions and 8,067 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Python
backend/__pycache__/
backend/*/__pycache__/
backend/*/*/__pycache__/
backend/*.pyc

# Logs
Expand Down
6 changes: 6 additions & 0 deletions Dockerfile_frontend
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,18 @@ WORKDIR /var/www/html
# Copy the current directory contents into the container at /var/www/html
COPY frontend/ /var/www/html

# Copy custom php.ini
COPY custom_php.ini /usr/local/etc/php/php.ini

# Install any dependencies your application needs
RUN apt-get update

# Change ownership of the directory to www-data:www-data
RUN chown -R www-data:www-data /var/www/html

# Change permissions of the directory to 755
RUN chmod -R 755 /var/www/html

# Expose port 80 to the outside world
EXPOSE 80

Expand Down
64 changes: 35 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@

# Endurain

A self-hosted fitness tracking service
A self-hosted fitness tracking service • Endurain <a href="https://fosstodon.org/@endurain">Mastodon</a> profile

<img src="screenshot_01.png">
</div>

> [!WARNING]
> This project is currently in **Alpha** state. You can try it out at your own risk, but be aware that things might break and **DATA LOSS** may occur.
Endurain is a self-hosted fitness tracking service that operates much like Strava but allows users to have complete control over their data and the hosting environment. The application's frontend is built using a combination of PHP, HTML, basic JavaScript, and Bootstrap CSS. On the backend, it leverages Python FastAPI and stravalib for seamless integration with Strava. The MariaDB database engine is employed to efficiently store and manage user data, while Jaeger is used for basic observability.
Endurain is a self-hosted fitness tracking service that operates much like Strava but allows users to have complete control over their data and the hosting environment. The application's frontend is built using a combination of PHP, HTML, basic JavaScript, and Bootstrap CSS. On the backend, it leverages Python FastAPI, Alembic, SQLAlchemy, stravalib and gpxpy for seamless integration with Strava and .gpx file import. The MariaDB database engine is employed to efficiently store and manage user data, while Jaeger is used for basic observability.

To deploy Endurain, Docker images are readily available, and a comprehensive example can be found in the "docker-compose.yml" file provided. Configuration is facilitated through environment variables, ensuring flexibility and ease of customization.
To deploy Endurain, Docker images are available, and a comprehensive example can be found in the "docker-compose.yml" file provided. Configuration is facilitated through environment variables, ensuring flexibility and ease of customization.

As a non-professional developer, my journey with Endurain involved learning and implementing new technologies and concepts, with invaluable assistance from ChatGPT. The primary motivation behind this project was to gain hands-on experience and expand my understanding of modern development practices.
As a non-professional developer, my journey with Endurain involved learning and implementing new technologies and concepts, with invaluable assistance from ChatGPT. The primary motivation behind this project was to gain hands-on experience and expand my understanding of modern development practices. Second motivation is that I'm an amateur triathlete and I want to keep track of my gear and gear components usage.

If you have any recommendations or insights on improving any aspect of Endurain, whether related to technology choices, user experience, or any other relevant area, I would greatly appreciate your input. The goal is to create a reliable and user-friendly fitness tracking solution that caters to the needs of individuals who prefer self-hosted applications. Your constructive feedback will undoubtedly contribute to the refinement of Endurain.

Expand All @@ -28,7 +28,7 @@ Currently the service supports:
- Create/edit/delete users
- Basic admin and regular users profiles that adapt the interface
- Import activities using .gpx files
- Connect with Strava and retrieve activities from Strava
- Connect with Strava and retrieve activities and gear from Strava
- Feed with user activities, current user week stats and month stats
- Feed with followers activities
- Basic activity privacy
Expand All @@ -39,25 +39,29 @@ Currently the service supports:
- User page with user stats and user activities per week
- Follow user basic implementation
- Multi-language support, but currently only English is available
- Basic gear tracking usage

To do features (not by order):
- Retrieve gear from Strava
- Support import of .fit files
- Default gear for activity type
- Track gear usage
- Gear components logic for component usage tracking
- Comments and likes logic for activities
- Notifications logic
- Activity Pub integration?

More screenshots: https://imgur.com/a/lDR0sBf

---
# Frontend
Table bellow shows supported environemnt variables. Variables marked with optional "No" should be set to avoid errors.

Environemnt variable | Default value | Optional
--- | --- | ---
BACKEND_PROTOCOL | http | Yes
BACKEND_HOST | backend | Yes
BACKEND_PROTOCOL* | http | Yes
BACKEND_HOST** | backend | Yes

*BACKEND_PROTOCOL needs to be https if you want to enable Strava integration
**BACKEND_HOST needs to be set and be Internet faced/resolved if you want to enable Strava integration. Strava callback relies on this.

Frontend dependencies:
- php:8.3-apache
Expand All @@ -66,11 +70,9 @@ Frontend dependencies:
- leaflet v1.7.1
- fontawesome icons free version
- Logo created using Canvas
- https://geocode.maps.co/ for reverse Geocode logic on activity parsing

---
# Backend
Everytime the backend starts it will check if the user with the username "admin" is created. If not the user is created. Because of this if you want to create another admin user and not use the default one, I suggest to disable the default one. A better approach to this will be assessed in the future.

Table bellow shows supported environemnt variables. Variables marked with optional "No" should be set to avoid errors.

Environemnt variable | Default value | Optional
Expand All @@ -91,9 +93,11 @@ JAEGER_PROTOCOL | http | Yes
JAEGER_HOST | jaeger | Yes
JAGGER_PORT | 4317 | Yes
STRAVA_DAYS_ACTIVITIES_ONLINK | 30 | Yes
API_ENDPOINT* | changeme | Yes
FRONTEND_HOST* | frontend | Yes
GEOCODES_MAPS_API** | changeme | `No`

*API_ENDPOINT needs to be set if you want to enable Strava integration
*FRONTEND_HOST needs to be set if you want to enable Strava integration
**<a href="https://geocode.maps.co/">Geocode maps</a> offers a free plan consisting of 1 Request/Second. Registration necessary.

Table bellow shows the obligatory environemnt variables for mariadb container. You should set them based on what was also set for backend container.

Expand All @@ -106,21 +110,23 @@ MYSQL_PASSWORD | changeme | `No`

Python backend dependencies used:
- python:3.11
- fastapi
- pydantic
- uvicorn
- python-dotenv
- sqlalchemy
- mysqlclient
- python-jose[cryptography]
- passlib[bcrypt]
- apscheduler
- requests
- stravalib
- opentelemetry-sdk
- opentelemetry-instrumentation-fastapi
- opentelemetry.exporter.otlp
- https://geocode.maps.co/ for reverse Geocode logic on activity parsing
- fastapi==0.108.0
- pydantic==1.10.9
- uvicorn==0.25.0
- python-dotenv==1.0.0
- sqlalchemy==2.0.25
- mysqlclient==2.2.1
- python-jose[cryptography]==3.3.0
- passlib[bcrypt]==1.7.4
- apscheduler==3.10.4
- requests==2.31.0
- stravalib==1.5
- opentelemetry-sdk==1.22.0
- opentelemetry-instrumentation-fastapi==0.43b0
- opentelemetry.exporter.otlp==1.22.0
- python-multipart==0.0.6
- gpxpy==1.6.2
- alembic==1.13.1

---
# Strava integration
Expand Down
5 changes: 3 additions & 2 deletions backend/.env
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ DB_PORT=3306
DB_USER=endurain
DB_PASSWORD=changeme
DB_DATABASE=endurain
SECRET_KEY=changeme
SECRET_KEY=changeme # openssl rand -hex 32
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
STRAVA_CLIENT_ID=changeme
Expand All @@ -15,4 +15,5 @@ JAEGER_PROTOCOL=http
JAEGER_HOST=jaeger
JAGGER_PORT=4317
STRAVA_DAYS_ACTIVITIES_ONLINK=30
API_ENDPOINT=changeme
FRONTEND_HOST=frontend
GEOCODES_MAPS_API=changeme
1 change: 0 additions & 1 deletion backend/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@

116 changes: 116 additions & 0 deletions backend/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions

# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = driver://user:pass@localhost/dbname


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix REVISION_SCRIPT_FILENAME

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
1 change: 1 addition & 0 deletions backend/alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
88 changes: 88 additions & 0 deletions backend/alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

import models

# import Base and engine from database file
from database import Base, engine

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
""" connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
) """

# Here, instead of creating a new engine, we use the existing engine
# from database configuration.
connectable = engine

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
Loading

0 comments on commit 3824f34

Please sign in to comment.