From 91386bcc67b51147c26d4df513d7fe03a290c218 Mon Sep 17 00:00:00 2001 From: boyska Date: Sun, 16 Feb 2020 00:52:11 +0100 Subject: [PATCH] initial --- .agignore | 1 + app.py | 163 +++++++++++++++++ requirements.txt | 11 ++ static/jquery-ui/AUTHORS.txt | 333 +++++++++++++++++++++++++++++++++++ static/js/addmap.js | 69 ++++++++ static/js/viewmap.js | 55 ++++++ templates/add.html | 33 ++++ templates/base.html | 63 +++++++ templates/index.html | 12 ++ 9 files changed, 740 insertions(+) create mode 100644 .agignore create mode 100644 app.py create mode 100644 requirements.txt create mode 100644 static/jquery-ui/AUTHORS.txt create mode 100644 static/js/addmap.js create mode 100644 static/js/viewmap.js create mode 100644 templates/add.html create mode 100644 templates/base.html create mode 100644 templates/index.html diff --git a/.agignore b/.agignore new file mode 100644 index 0000000..2b4a1ce --- /dev/null +++ b/.agignore @@ -0,0 +1 @@ +static/jquery-ui/ diff --git a/app.py b/app.py new file mode 100644 index 0000000..f72bb3e --- /dev/null +++ b/app.py @@ -0,0 +1,163 @@ +import flask +import sqlite3 +from datetime import datetime + +from flask import Flask, render_template, redirect, url_for, request, jsonify +from flask_sqlalchemy import SQLAlchemy + +import sqlalchemy.exc +from sqlalchemy_utils import PasswordType + +# from sqlalchemy import Column, Integer, String +# from sqlalchemy.ext.declarative import declarative_base + +# TODO: sqlalchemy? + +# schema: +# Utente: uid, username, password +# TipoRadio: trid, tipo +# Avvistamento: aid, uid, tipo_radio, data, commento + +app = Flask(__name__) +app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///map.db" +db = SQLAlchemy(app) + + +class User(db.Model): + __tablename__ = "user" + + uid = db.Column(db.Integer, primary_key=True, nullable=False) + username = db.Column(db.String, unique=True) + password = db.Column(PasswordType(schemes=["pbkdf2_sha512"])) + + rapporti = db.relationship("RapportoRicezione") + + +class TipoRadio(db.Model): + __tablename__ = "tiporadio" + tid = db.Column(db.Integer, primary_key=True, nullable=False) + nome = db.Column(db.Unicode) + descrizione = db.Column(db.Unicode) + + rapporti = db.relationship("RapportoRicezione") + + +class RapportoRicezione(db.Model): + __tablename__ = "rapporto" + + rid = db.Column(db.Integer, primary_key=True) + uid = db.Column(db.Integer, db.ForeignKey("user.uid")) + tid = db.Column(db.Integer, db.ForeignKey("tiporadio.tid")) + + date = db.Column(db.Date, default=lambda: datetime.now()) + + lat = db.Column(db.Float) + lng = db.Column(db.Float) + + comprensibile = db.Column(db.Integer) # TODO: >= 0 <= 5 + stabilita = db.Column(db.Integer) # TODO: >= 0 <= 5 + + author = db.relationship(User, back_populates="rapporti") + tipo_radio = db.relationship(TipoRadio, back_populates="rapporti") + + def serialize(self): + d = {k:v for k,v in self.__dict__.items() if not k.startswith('_')} + d['colore'] = self.colore + d['radius'] = self.radius + d['explaination'] = self.explaination + return d + + @property + def colore(self): + c = self.comprensibile + if c > 3: + return 'green' + if c > 1: + return 'yellow' + return 'red' + + @property + def radius(self): + return self.stabilita * 70 + + @property + def explaination(self): + return 'Aggiunto il %s da %s' % (self.date, self.author.username) + + def __repr__(self): + return "" % (self.rid, self.date) + + +@app.before_first_request +def init_db(): + db.create_all() + + try: + anon = User(username="anonymous", password="antani") + db.session.add(anon) + db.session.commit() + except sqlalchemy.exc.IntegrityError: + db.session.rollback() + + for nome in ["radiolina portatile", "autoradio", "stereo fisso dentro casa"]: + try: + t = TipoRadio(nome=nome) + db.session.add(t) + db.session.commit() + except sqlalchemy.exc.IntegrityError: + db.session.rollback() + + cnt = int(RapportoRicezione.query.count()) + if cnt == 0: + for i in range(6): + r = RapportoRicezione( + uid=User.query.filter(User.username == "anonymous")[0].uid, + tid=TipoRadio.query.all()[0].tid, + stabilita=i, + comprensibile=i, + lat=43.8199 - i * 0.01, + lng=11.22185 + i * 0.03, + ) + db.session.add(r) + db.session.commit() + + +@app.route("/") +def home(): + return render_template("index.html") + +@app.route("/add") +def add(): + return render_template("add.html") + + +@app.route("/api/rapporti/get") +def get_rapporti(): + query = RapportoRicezione.query.all() + # TODO: usa query params per filtrare in base a $cose + return jsonify(dict(rapporti=[r.serialize() for r in query])) + +@app.route("/api/rapporti/add", methods=['POST']) +def add_rapporto(): + anon = User.query.filter(User.username=='anonymous')[0].uid + r = RapportoRicezione( + uid=anon, + lat=request.form['lat'], + lng=request.form['lng'], + stabilita=request.form['stabilita'], + comprensibile=request.form['comprensibile'], + + ) + db.session.add(r) + db.session.commit() + + r = RapportoRicezione.query.get(r.rid) + return jsonify(r.serialize()) + +@app.route("/api/rapporti/delete", methods=['POST']) +def delete_rapporto(): + r = RapportoRicezione.query.get(int(request.form['rid'])) + db.session.delete(r) + db.session.commit() + + return jsonify(True) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a4cfbbe --- /dev/null +++ b/requirements.txt @@ -0,0 +1,11 @@ +Click==7.0 +Flask-SQLAlchemy==2.4.1 +Flask==1.1.1 +Jinja2==2.11.1 +MarkupSafe==1.1.1 +SQLAlchemy-Utils==0.36.1 +SQLAlchemy==1.3.13 +Werkzeug==1.0.0 +itsdangerous==1.1.0 +passlib==1.7.2 +six==1.14.0 diff --git a/static/jquery-ui/AUTHORS.txt b/static/jquery-ui/AUTHORS.txt new file mode 100644 index 0000000..a75056b --- /dev/null +++ b/static/jquery-ui/AUTHORS.txt @@ -0,0 +1,333 @@ +Authors ordered by first contribution +A list of current team members is available at http://jqueryui.com/about + +Paul Bakaus +Richard Worth +Yehuda Katz +Sean Catchpole +John Resig +Tane Piper +Dmitri Gaskin +Klaus Hartl +Stefan Petre +Gilles van den Hoven +Micheil Bryan Smith +Jörn Zaefferer +Marc Grabanski +Keith Wood +Brandon Aaron +Scott González +Eduardo Lundgren +Aaron Eisenberger +Joan Piedra +Bruno Basto +Remy Sharp +Bohdan Ganicky +David Bolter +Chi Cheng +Ca-Phun Ung +Ariel Flesler +Maggie Wachs +Scott Jehl +Todd Parker +Andrew Powell +Brant Burnett +Douglas Neiner +Paul Irish +Ralph Whitbeck +Thibault Duplessis +Dominique Vincent +Jack Hsu +Adam Sontag +Carl Fürstenberg +Kevin Dalman +Alberto Fernández Capel +Jacek Jędrzejewski (http://jacek.jedrzejewski.name) +Ting Kuei +Samuel Cormier-Iijima +Jon Palmer +Ben Hollis +Justin MacCarthy +Eyal Kobrigo +Tiago Freire +Diego Tres +Holger Rüprich +Ziling Zhao +Mike Alsup +Robson Braga Araujo +Pierre-Henri Ausseil +Christopher McCulloh +Andrew Newcomb +Lim Chee Aun +Jorge Barreiro +Daniel Steigerwald +John Firebaugh +John Enters +Andrey Kapitcyn +Dmitry Petrov +Eric Hynds +Chairat Sunthornwiphat +Josh Varner +Stéphane Raimbault +Jay Merrifield +J. Ryan Stinnett +Peter Heiberg +Alex Dovenmuehle +Jamie Gegerson +Raymond Schwartz +Phillip Barnes +Kyle Wilkinson +Khaled AlHourani +Marian Rudzynski +Jean-Francois Remy +Doug Blood +Filippo Cavallarin +Heiko Henning +Aliaksandr Rahalevich +Mario Visic +Xavi Ramirez +Max Schnur +Saji Nediyanchath +Corey Frang +Aaron Peterson +Ivan Peters +Mohamed Cherif Bouchelaghem +Marcos Sousa +Michael DellaNoce +George Marshall +Tobias Brunner +Martin Solli +David Petersen +Dan Heberden +William Kevin Manire +Gilmore Davidson +Michael Wu +Adam Parod +Guillaume Gautreau +Marcel Toele +Dan Streetman +Matt Hoskins +Giovanni Giacobbi +Kyle Florence +Pavol Hluchý +Hans Hillen +Mark Johnson +Trey Hunner +Shane Whittet +Edward A Faulkner +Adam Baratz +Kato Kazuyoshi +Eike Send +Kris Borchers +Eddie Monge +Israel Tsadok +Carson McDonald +Jason Davies +Garrison Locke +David Murdoch +Benjamin Scott Boyle +Jesse Baird +Jonathan Vingiano +Dylan Just +Hiroshi Tomita +Glenn Goodrich +Tarafder Ashek-E-Elahi +Ryan Neufeld +Marc Neuwirth +Philip Graham +Benjamin Sterling +Wesley Walser +Kouhei Sutou +Karl Kirch +Chris Kelly +Jason Oster +Felix Nagel +Alexander Polomoshnov +David Leal +Igor Milla +Dave Methvin +Florian Gutmann +Marwan Al Jubeh +Milan Broum +Sebastian Sauer +Gaëtan Muller +Michel Weimerskirch +William Griffiths +Stojce Slavkovski +David Soms +David De Sloovere +Michael P. Jung +Shannon Pekary +Dan Wellman +Matthew Edward Hutton +James Khoury +Rob Loach +Alberto Monteiro +Alex Rhea +Krzysztof Rosiński +Ryan Olton +Genie <386@mail.com> +Rick Waldron +Ian Simpson +Lev Kitsis +TJ VanToll +Justin Domnitz +Douglas Cerna +Bert ter Heide +Jasvir Nagra +Yuriy Khabarov <13real008@gmail.com> +Harri Kilpiö +Lado Lomidze +Amir E. Aharoni +Simon Sattes +Jo Liss +Guntupalli Karunakar +Shahyar Ghobadpour +Lukasz Lipinski +Timo Tijhof +Jason Moon +Martin Frost +Eneko Illarramendi +EungJun Yi +Courtland Allen +Viktar Varvanovich +Danny Trunk +Pavel Stetina +Michael Stay +Steven Roussey +Michael Hollis +Lee Rowlands +Timmy Willison +Karl Swedberg +Baoju Yuan +Maciej Mroziński +Luis Dalmolin +Mark Aaron Shirley +Martin Hoch +Jiayi Yang +Philipp Benjamin Köppchen +Sindre Sorhus +Bernhard Sirlinger +Jared A. Scheel +Rafael Xavier de Souza +John Chen +Robert Beuligmann +Dale Kocian +Mike Sherov +Andrew Couch +Marc-Andre Lafortune +Nate Eagle +David Souther +Mathias Stenbom +Sergey Kartashov +Avinash R +Ethan Romba +Cory Gackenheimer +Juan Pablo Kaniefsky +Roman Salnikov +Anika Henke +Samuel Bovée +Fabrício Matté +Viktor Kojouharov +Pawel Maruszczyk (http://hrabstwo.net) +Pavel Selitskas +Bjørn Johansen +Matthieu Penant +Dominic Barnes +David Sullivan +Thomas Jaggi +Vahid Sohrabloo +Travis Carden +Bruno M. Custódio +Nathanael Silverman +Christian Wenz +Steve Urmston +Zaven Muradyan +Woody Gilk +Zbigniew Motyka +Suhail Alkowaileet +Toshi MARUYAMA +David Hansen +Brian Grinstead +Christian Klammer +Steven Luscher +Gan Eng Chin +Gabriel Schulhof +Alexander Schmitz +Vilhjálmur Skúlason +Siebrand Mazeland +Mohsen Ekhtiari +Pere Orga +Jasper de Groot +Stephane Deschamps +Jyoti Deka +Andrei Picus +Ondrej Novy +Jacob McCutcheon +Monika Piotrowicz +Imants Horsts +Eric Dahl +Dave Stein +Dylan Barrell +Daniel DeGroff +Michael Wiencek +Thomas Meyer +Ruslan Yakhyaev +Brian J. Dowling +Ben Higgins +Yermo Lamers +Patrick Stapleton +Trisha Crowley +Usman Akeju +Rodrigo Menezes +Jacques Perrault +Frederik Elvhage +Will Holley +Uri Gilad +Richard Gibson +Simen Bekkhus +Chen Eshchar +Bruno Pérel +Mohammed Alshehri +Lisa Seacat DeLuca +Anne-Gaelle Colom +Adam Foster +Luke Page +Daniel Owens +Michael Orchard +Marcus Warren +Nils Heuermann +Marco Ziech +Patricia Juarez +Ben Mosher +Ablay Keldibek +Thomas Applencourt +Jiabao Wu +Eric Lee Carraway +Victor Homyakov +Myeongjin Lee +Liran Sharir +Weston Ruter +Mani Mishra +Hannah Methvin +Leonardo Balter +Benjamin Albert +Michał Gołębiowski +Alyosha Pushak +Fahad Ahmad +Matt Brundage +Francesc Baeta +Piotr Baran +Mukul Hase +Konstantin Dinev +Rand Scullard +Dan Strohl +Maksim Ryzhikov +Amine HADDAD +Amanpreet Singh +Alexey Balchunas +Peter Kehl +Peter Dave Hello +Johannes Schäfer +Ville Skyttä +Ryan Oriecuia diff --git a/static/js/addmap.js b/static/js/addmap.js new file mode 100644 index 0000000..8631db9 --- /dev/null +++ b/static/js/addmap.js @@ -0,0 +1,69 @@ +function viewMap() { + var map = L.map('mapid').setView([43.797, 11.2400], 11); + // Set up the OSM layer + L.tileLayer( +'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' + ).addTo(map); + + $.getJSON('/api/rapporti/get', function(data) { + for(var i in data.rapporti) { + var p = data.rapporti[i] + L.circle([p.lat, p.lng], { + color: p.colore, + fillColor:p.colore, + fillOpacity: 0.2, + opacity: 0.7, + radius: p.radius, + }).addTo(map) + } + }) + + function addPointToDb(dati) { + $.post('/api/rapporti/add', dati + , function(p) { + console.log(p) + L.circle([p.lat, p.lng], { + color: p.colore, + fillColor:p.colore, + fillOpacity: 0.5, + radius: p.radius, + }).addTo(map) + }) + } + + function onFormSubmit() { + addPointToDb({ + lat: $('#pointform input[name=lat]').val(), + lng: $('#pointform input[name=lng]').val(), + stabilita: $('#pointform select[name=stabilita]').val(), + comprensibile: $('#pointform select[name=comprensibile]').val(), + }) + $('#pointform').addClass('hidden') + return false; + } + + function onMapClick(e) { + console.log('click', e) + console.log(e.latlng) + var stabilita = 3 + console.log(map.getZoom()) + if(map.getZoom() > 15) { + stabilita = 19 - map.getZoom() + } + console.log('st', stabilita) + $('#pointform input[name=lat]').val(e.latlng.lat) + $('#pointform input[name=lng]').val(e.latlng.lng) + $('#pointform select[name=stabilita]').val(stabilita) + $('#pointform').removeClass('hidden') + // TODO: aggiungi punto temporaneo, ma poi va rimosso + + } + + map.on('click', onMapClick) + $('#addPoint').on('click', onFormSubmit) +} +jQuery(function($) { + $('#mapid').css('height', $(window).height() - 200) + viewMap() +}) + diff --git a/static/js/viewmap.js b/static/js/viewmap.js new file mode 100644 index 0000000..64816a0 --- /dev/null +++ b/static/js/viewmap.js @@ -0,0 +1,55 @@ +RapportoMarker = L.Circle.extend({ options: { originalData: 0 } }); + +function viewMap() { + var map = L.map('mapid').setView([43.797, 11.2400], 11); + // Set up the OSM layer + L.tileLayer( +'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' + ).addTo(map); + $.getJSON('/api/rapporti/get', function(data) { + for(var i in data.rapporti) { + var p = data.rapporti[i] + var marker = new RapportoMarker([p.lat, p.lng], { + color: p.colore, + fillColor:p.colore, + fillOpacity: 0.3, + radius: p.radius, + originalData: p, + }) + marker.addTo(map).bindPopup(p.explaination) + marker.off('click') + marker.on('click', onMarkerClicked) + } + }) + function onMarkerClicked(evt) { + console.log('T', this) + var data = evt.target.options.originalData + var rid = data.rid + $('#dialog').html('
') + $('#dialog .explaination').text(data.explaination) + $('#dialog .actions').html('') + $('#dialog').attr('title', rid) + $('#dialog').data('rid', rid) + $('#dialog').data('marker', this) + $('#dialog').dialog({ + modal: true, + beforeClose: function(event, ui) { + $('#dialog').dialog('destroy') + $('#dialog')[0].outerHTML = '
' + } + }) + } + + $('body').on('click', '.btn-elimina', function onCancella(evt) { + var rid = $('#dialog').data('rid') + console.log('cancelliamo?', rid) + $.post('/api/rapporti/delete', {rid: rid}, function() { + map.removeLayer($('#dialog').data('marker')) + $('#dialog').dialog('close') + }) + }) +} +jQuery(function($) { + $('#mapid').css('height', $(window).height() - 200) + viewMap() +}) diff --git a/templates/add.html b/templates/add.html new file mode 100644 index 0000000..fea216e --- /dev/null +++ b/templates/add.html @@ -0,0 +1,33 @@ +{% extends 'base.html' %} +{% block extra_scripts %} + +{% endblock extra_scripts %} + + +{% block content %} + +{% endblock content %} + diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..88f7945 --- /dev/null +++ b/templates/base.html @@ -0,0 +1,63 @@ + + + + + {% block all_css %} + + {% block extra_css %} + {% endblock extra_css %} + {% endblock all_css %} + + + + + {% block main %} +
+
+ {% block content %} + {% endblock content %} +
+
+
+ {% endblock main %} + + {% block all_scripts %} + + + + {% block extra_scripts %} + {% endblock extra_scripts %} + {% endblock %} + + + diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..bd8ec80 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,12 @@ +{% extends 'base.html' %} +{% block extra_css %} + +{% endblock extra_css %} +{% block extra_scripts %} + + +{% endblock extra_scripts %} + +{% block content %} +
+{% endblock content %}