1
0
forked from orson/bachemap

working proto, no auth

This commit is contained in:
Orson 2024-08-21 13:38:01 -06:00
parent e566c970eb
commit e5ab135696
14 changed files with 239 additions and 196 deletions

84
app.py
View File

@ -1,6 +1,7 @@
from flask import Flask, render_template, request, redirect, url_for, flash from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory
from flask_pymongo import PyMongo from flask_pymongo import PyMongo
from werkzeug.utils import secure_filename from werkzeug.utils import secure_filename
from datetime import datetime
import os import os
app = Flask(__name__) app = Flask(__name__)
@ -10,51 +11,68 @@ app.config['SECRET_KEY'] = 'supersecretkey'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'} app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}
mongo = PyMongo(app) mongo = PyMongo(app)
#form = PinForm()
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
from wtforms import StringField, FileField, SubmitField from wtforms import StringField, FileField, SubmitField, DateTimeField, SelectField
from wtforms.validators import DataRequired from wtforms.validators import DataRequired
class PinForm(FlaskForm): class PinForm(FlaskForm):
description = StringField('Description', validators=[DataRequired()]) description = StringField('Description', validators=[DataRequired()])
photo = FileField('Photo', validators=[DataRequired()]) photo = FileField('Evidencia fotogénica', validators=[DataRequired()])
submit = SubmitField('Add Pin') timedate = DateTimeField(default=datetime.now())
typeofpin = SelectField('Tipo de cosa', choices=['bache', 'coladera', 'obra sin terminar', 'escombro', 'robo-asalto'])
submit = SubmitField('Agregar')
def allowed_file(filename): def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS'] return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
@app.route('/') @app.route('/', methods=['GET', 'POST'])
def index(): def index():
pins = mongo.db.pins.find() if request.method == 'GET':
return render_template('index.html', pins=pins) form = PinForm()
pins = mongo.db.pins.find()
@app.route('/add_pin', methods=['GET', 'POST']) return render_template('index.html', pins=pins, form=form)
def add_pin(): else:
form = PinForm() #@app.route('/add_pin')
if form.validate_on_submit(): #def add_pin():
description = form.description.data form = request.form
photo = form.photo.data # if form.validate_on_submit():
#description = form.description.data
try:
photo = request.files["photo"]
except Exception as e:
print(e)
if photo and allowed_file(photo.filename): if photo and allowed_file(photo.filename):
try: #try:
filename = secure_filename(photo.filename) filename = secure_filename(photo.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
photo.save(filepath) photo.save(filepath)
pin = { pin = {
'description': description, #'description': description,
'photo': filepath, 'time': datetime.now(),
'lat': request.form['lat'], 'photo': filepath,
'lng': request.form['lng'] 'lat': request.form['lat'],
} 'lng': request.form['lng'],
mongo.db.pins.insert_one(pin) 'typeofpin': request.form['typeofpin'],
return redirect(url_for('index')) }
except Exception as e: mongo.db.pins.insert_one(pin)
flash(f'An error occurred: {e}') flash('¡Gracias por tu aportación!')
return redirect(url_for('add_pin')) return redirect(url_for('index'))
else: else:
flash('Invalid file type. Only images are allowed.') return allowed_file(photo.filename), 404
return render_template('add_pin.html', form=form) #render_template('index.html', pins=pins, form=form)
#except Exception as e:
# flash(f'An error occurred: {e}')
#return redirect(url_for('add_pin'))
#else:
# flash('Invalid file type. Only images are allowed.')
#return render_template('index.html', form=form)
@app.route('/uploads/<name>')
def download_file(name):
return send_from_directory(app.config["UPLOAD_FOLDER"], name)
if __name__ == '__main__': if __name__ == '__main__':
app.run(debug=True) app.run(debug=True)

67
app2.py
View File

@ -1,67 +0,0 @@
from flask import Flask, render_template, request,make_response,jsonify, redirect, url_for
from pymongo import MongoClient
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, FileField, DateTimeField
from werkzeug.utils import secure_filename
class BacheForm(FlaskForm):
name = StringField('name')
photo = FileField()
class mongo_connection:
conn = None
def connect(self):
mongoclient = MongoClient("mongodb://localhost:27017/")
mongo_db = mongoclient["mapper"]
self.conn = mongo_db["baches"]
def query(self, sql):
cursor = self.conn.find(sql)
return cursor
db = mongo_connection()
db.connect()
app = Flask(__name__)
csrf = CSRFProtect(app)
#mongodb_client = MongoClient("mongodb://localhost:27017/")
#db = client['bachemap']
#collection = db['bachecitos']
@app.route("/", methods=['GET','POST'])
def index():
if request.method == 'GET':
return render_template("map.html")
if request.method == 'POST':
form=BacheForm()
if form.validate_on_submit():
post_data = {
'author': form.author.data,
'img': form.img.data,
'latitude': form.latitude.data,
'longitude': form.longitide.data,
'message': form.message.data
}
collection.insert_one(post_data)
flash('¡Gracias por tu aporte! A la ONU le gusta esto :3')
return redirect(url_for('map'))
return render_template('map.html', form=form)
if __name__ == '__main__':
app.run(host="localhost", port=5000, debug=True)
# models schema:
#{'latitude':'', 'longitude':'', 'severity':''}

94
reference.py Normal file
View File

@ -0,0 +1,94 @@
from flask import Flask, request, redirect, url_for, render_template, session
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from uuid import uuid4
import click
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SECRET_KEY'] = 'your_secret_key'
db = SQLAlchemy(app)
login_manager = LoginManager(app)
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), unique=True, nullable=False)
referral_code = db.Column(db.String(36), unique=True, nullable=False)
invited_by_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
is_admin = db.Column(db.Boolean, default=False)
invitees = db.relationship('User', backref=db.backref('inviter', remote_side=[id]))
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/register/<referral_code>', methods=['GET', 'POST'])
def register(referral_code):
inviter = User.query.filter_by(referral_code=referral_code).first_or_404()
if request.method == 'POST':
username = request.form['username']
new_user = User(username=username, referral_code=str(uuid4()), invited_by_id=inviter.id)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
user = User.query.filter_by(username=username).first()
if user:
login_user(user)
return redirect(url_for('home'))
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
@app.route('/remove_user/<int:user_id>')
@login_required
def remove_user(user_id):
if not current_user.is_admin:
return redirect(url_for('home'))
user_to_remove = User.query.get_or_404(user_id)
invitees = User.query.filter_by(invited_by_id=user_to_remove.id).all()
for invitee in invitees:
db.session.delete(invitee)
db.session.delete(user_to_remove)
db.session.commit()
return redirect(url_for('admin_dashboard'))
@app.cli.command('remove_user')
@click.argument('username')
def remove_user_cli(username):
user_to_remove = User.query.filter_by(username=username).first()
if user_to_remove:
invitees = User.query.filter_by(invited_by_id=user_to_remove.id).all()
for invitee in invitees:
db.session.delete(invitee)
db.session.delete(user_to_remove)
db.session.commit()
print(f'User {username} and their invitees have been removed.')
else:
print(f'User {username} not found.')
@app.route('/home')
@login_required
def home():
return "Home page"
@app.route('/admin_dashboard')
@login_required
def admin_dashboard():
if not current_user.is_admin:
return redirect(url_for('home'))
users = User.query.all()
return render_template('admin_dashboard.html', users=users)
if __name__ == '__main__':
db.create_all()
app.run(debug=True)

View File

View File

@ -1 +1,5 @@
body {padding: 0;margin: 0;}html, body, #map {height: 100%;width: 100vw;} body {padding: 0;margin: 0;}html, body, #map {height: 100%;width: 100vw;}
div.leaflet-popup-content {
width: 400px;
}

View File

@ -1,7 +1,8 @@
body { body {
font-family: Arial, sans-serif; font-family: Arial, sans-serif;
margin: 0; margin: 0;
padding: 20px; padding: 0px;
overflow: hidden;
} }
h1 { h1 {
@ -22,6 +23,35 @@ form p {
#map { #map {
width: 100%; width: 100%;
height: 600px; height: 100vh;
margin: 20px 0; margin: 0 0;
} }
main {
margin:0;
padding:0;
position: absolute;
}
div.leaflet-popup-content {
width: 400px;
}
div.pinner-modal {
position: absolute;
top: 10vh;
left: 0;
width: 100%;
background-color: #007BFF;
color: white;
padding: 1rem;
text-align: center;
transition: bottom 0.5s ease;
box-shadow: 0px -4px 15px rgba(0, 0, 0, 0.2);
z-index: 999;
}
div.pinner-modal.active {
bottom: 0;
}

View File

@ -1,45 +1,17 @@
{% extends 'base.html' %} <form method="post" enctype="multipart/form-data" style="background-color: rgb(205, 243, 148);">
{% block content %}
<h1>Add a New Pin</h1>
<form method="post" enctype="multipart/form-data">
{{ form.hidden_tag() }} {{ form.hidden_tag() }}
<p> <!--<p>
{{ form.description.label }}<br> {{ form.description.label }}<br>
{{ form.description(size=32) }} {{ form.description(size=32) }}
</p> </p>-->
<p>
{{ form.photo.label }}<br> {{ form.photo.label }}<br>
{{ form.photo() }} {{ form.photo() }}
</p> {{ form.typeofpin }}
<p>
<label for="lat">Latitude:</label><br> <label for="lat">Latitud:</label><br>
<input type="text" id="lat" name="lat" readonly> <input type="text" id="lat" name="lat" readonly>
</p> <label for="lng">Longitud:</label><br>
<p>
<label for="lng">Longitude:</label><br>
<input type="text" id="lng" name="lng" readonly> <input type="text" id="lng" name="lng" readonly>
</p>
<p>{{ form.submit() }}</p> <p>{{ form.submit() }}</p>
</form> </form>
<a href="{{ url_for('index') }}">Back to map</a>
<div id="map" style="height: 600px;"></div>
<script>
// Initial position of map and user pin
var map = L.map('map').setView([20.57, -100.38], 13);
var youarehere = L.marker([latlng.lat, latlng.lng]).addTo(map);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
map.on('click', function(e) {
var latlng = e.latlng;
document.getElementById('lat').value = latlng.lat;
document.getElementById('lng').value = latlng.lng;
});
</script>
{% endblock %}

View File

@ -19,23 +19,54 @@
</head> </head>
<body style="background-color: rgb(205, 243, 148); color: black;"> <body style="background-color: rgb(205, 243, 148); color: black;">
<nav> <nav style="z-index: 5; height: 7vh;">
<ul> <ul>
<li><strong>El Bachemapa</strong> <li><h2>El Bachemapa</h2>
</ul> </ul>
<ul> <ul>
<h2>El Bachemapa</h2> <li><button id="pinner-top">Agregar</button></li>
</ul>
<ul>
<li><a href="/add_pin">Agregar</a></li>
<li><a href="/quienes">Quienes somos</a></li> <li><a href="/quienes">Quienes somos</a></li>
</ul> </ul>
</nav> </nav>
<main class="container-fluid"> {% with messages = get_flashed_messages() %}
{% if messages %}
<ul class="flashes">
{% for message in messages %}
<li>{{message}}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<main class="" style="padding:0px;height: 100vh; width:100vw; z-index: 5; position: absolute;">
{% block content %} {% block content %}
{% endblock %} {% endblock %}
<div id="pinner-modal" style="z-index:999;position:absolute;top:7vh" hidden="true">
{% include 'add_pin.html' %}
</div>
</main> </main>
</body> </body>
<script>
// pin button logic
const observer = new MutationObserver((mutations) => {
const element = document.getElementById('pinner-pop');
if (element) {
element.addEventListener('click', toggleSlide);
}
})
const pinner_button_top = document.getElementById("pinner-top");
//var pinner_button_pop = document.getElementById("pinner-pop");
const modal_stat = document.getElementById("pinner-modal");
function toggleSlide() {
if (modal_stat.hidden === true) {
modal_stat.hidden = false;
} else {modal_stat.hidden = true;}
}
pinner_button_top.addEventListener('click', toggleSlide);
observer.observe(document.body, { childList: true, subtree: true });
</script>
</html> </html>

View File

@ -1,9 +1,7 @@
{% extends 'base.html' %} {% extends 'base.html' %}
{% block content %} {% block content %}
<div id="map" style="height: 100%; border-style: groove; border-radius: 22px; border-width: 4px; position: absolute;"></div>
<h3>Documentando lo que vale la pena desde 1337</h3>
<div id="map" style="height: 33rem; border-style: groove; border-radius: 22px; border-width: 4px;"></div>
<script> <script>
//setView([51.505, -0.09], 13); //setView([51.505, -0.09], 13);
var map = new L.map('map', center=([20.57, -100.38], zoom=13)); var map = new L.map('map', center=([20.57, -100.38], zoom=13));
@ -13,9 +11,9 @@
attribution: '© OpenStreetMap contributors' attribution: '© OpenStreetMap contributors'
}).addTo(map); }).addTo(map);
//{% for pin in pins %} {% for pin in pins %}
//var marker = L.marker([{{ pin.lat }}, {{ pin.lng }}]).addTo(map) var marker = L.marker([{{ pin.lat }}, {{ pin.lng }}]).addTo(map)
// .bindPopup("<b>{{ pin.description }}</b><br><img src='{{ pin.photo }}' width='100'>"); .bindPopup("<b>{{ pin.description }}</b><p>Fecha del reporte: {{pin.time}}</p><br><img src='{{ pin.photo }}'>");
//{% endfor %} //{% endfor %}
//var live_location = map.locate() //var live_location = map.locate()
@ -43,7 +41,7 @@
user_radial = L.circle(e.latlng, radius).addTo(map); user_radial = L.circle(e.latlng, radius).addTo(map);
// Center the map on the user's location // Center the map on the user's location
map.setView(e.latlng, 13); // Adjust zoom level as needed map.setView(e.latlng, 16); // Adjust zoom level as needed
//return marker, radial; //return marker, radial;
} }
@ -60,8 +58,8 @@
map.locate({setView: true, maxZoom: 16}); map.locate({setView: true, maxZoom: 16});
map.on('click', function(e) { map.on('click', function(e) {
var latlng = e.latlng; var latlng = e.latlng;
//document.getElementById('lat').value = latlng.lat; document.getElementById('lat').value = latlng.lat;
//document.getElementById('lng').value = latlng.lng; document.getElementById('lng').value = latlng.lng;
map.flyTo(e.latlng, zoom=18); map.flyTo(e.latlng, zoom=18);
//map.eachLayer( function (layer)) { //map.eachLayer( function (layer)) {
// console.log(layer); // console.log(layer);
@ -69,10 +67,13 @@
//}; //};
//marker.remove(); //marker.remove();
//radial.remove(); //radial.remove();
user_marker.setLatLng(e.latlng).bindPopup("Tenemos que hablar").openPopup();; user_marker.setLatLng(e.latlng).bindPopup('<button id="pinner-pop">Agregar bache-o-cosa</button>').openPopup();
user_radial.remove(); user_radial.remove();
//setLanLng(e.latlng); //setLanLng(e.latlng);
}); });
</script> </script>
{% endblock %} {% endblock %}

View File

@ -1,40 +0,0 @@
{% extends 'base.html' %}
{% block header %}
<h2>{% block title %}Agregar bache o algo{% endblock title %}</h2>
{% endblock header %}
{% block content %}
<section class="maps">
<h1>Mapa de urbanismo chingón</h1>
<div id="map"></div>
</section>
{% include 'form.html' %}
<script type="text/javascript">
function success(position) {
console.log(position)
}
navigator.geolocation.getCurrentPosition(success);
var lon = document.getElementById('latitude');
document.getElementById('latitude').value = lon.options[lon.selectedIndex].value;
var lat = document.getElementById('longitude');
document.getElementById('longitude').value = lat.options[lat.selectedIndex].value;
var map = L.map('map', {
center: [lat, lon],
zoom: 13
});
map.on('moveend', function() {
var center = map.getCurrentPosition();
document.getElementById('latitude').value = center.lng;
document.getElementById('longitude').value = center.lat;
})
</script>
{% endblock content %}

BIN
uploads/KPR.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
uploads/gauss.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

BIN
uploads/ignucio.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

BIN
uploads/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB