Skip to content

Commit

Permalink
feat: added travels view
Browse files Browse the repository at this point in the history
  • Loading branch information
elblogbruno committed Aug 1, 2021
1 parent 292e6dc commit 6c84fc7
Show file tree
Hide file tree
Showing 19 changed files with 837 additions and 134 deletions.
57 changes: 54 additions & 3 deletions controller/models/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from werkzeug.security import generate_password_hash, check_password_hash
import db
from sqlalchemy import Column, Integer, String, Float, DateTime, Text
from sqlalchemy import Column, Integer, String, Float, DateTime, Text, Date
from datetime import datetime

class Wanderpi(db.Base):
Expand All @@ -11,7 +11,7 @@ class Wanderpi(db.Base):
long = Column(String(256), nullable=False)
thumbnail_url = Column(String(256), nullable=False)
created_date = Column(DateTime, default=datetime.utcnow)

travel_id = Column(String(256), nullable=False)

def __repr__(self):
return f'<User {self.id}>'
Expand Down Expand Up @@ -39,4 +39,55 @@ def get_by_id(id):

@staticmethod
def get_all():
return db.session.query(Wanderpi).all()
return db.session.query(Wanderpi).all()


class Travel(db.Base):
__tablename__ = 'travel'
id = Column(String(256), primary_key=True)
name = Column(String(256), nullable=False)
lat = Column(String(256), nullable=False)
long = Column(String(256), nullable=False)
destination = Column(String(256), nullable=False)
created_date = Column(DateTime, default=datetime.utcnow)
start_date = Column(Date)
end_date = Column(Date)


def __repr__(self):
return f'<User {self.id}>'

def set_id(self, id):
self.id = id

def set_name(self, id):
self.id = id

def save(self):
print(self.start_date)
db.session.add(self)
db.session.commit()

def delete_all_wanderpis(self):
video = db.session.query(Wanderpi).filter(Wanderpi.travel_id == self.id).all()
for v in video:
db.session.delete(v)
db.session.commit()
return True

def get_all_wanderpis(self):
return db.session.query(Wanderpi).filter(Wanderpi.travel_id == self.id).all()

@staticmethod
def delete(id):
db.session.query(Travel).filter(Travel.id == id).delete()
db.session.commit()
return True

@staticmethod
def get_by_id(id):
return db.session.query(Travel).get(id)

@staticmethod
def get_all():
return db.session.query(Travel).all()
27 changes: 27 additions & 0 deletions controller/modules/home/geocode_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import json
import urllib

import geopy
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter

class GeoCodeUtils:

@staticmethod
def reverse_latlong(lat,long):
"""Function that having a lat and long translates it to a posiblea ddress"
"""
locator = Nominatim(user_agent="openmapquest")
coordinates = "{0}, {1}".format(lat, long)
location = locator.reverse(coordinates)

return location.address

@staticmethod
def reverse_adress(adress):
"""Function that having an adress translates it to a lat and long values"
"""
locator = Nominatim(user_agent="openmapquest")
location = locator.geocode(adress)
print(location)
return location.latitude, location.longitude
129 changes: 109 additions & 20 deletions controller/modules/home/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@
from flask import json, session, render_template, redirect, url_for, Response,request, jsonify,send_from_directory
from controller.modules.home import home_blu
from controller.utils.camera import VideoCamera
from controller.models.models import Wanderpi
from controller.models.models import Wanderpi, Travel

from controller.modules.home.geocode_utils import GeoCodeUtils
from controller.utils.video_editor import VideoEditor

from datetime import *
import os
import uuid

video_camera_ids = [{"deviceId" : 0, "deviceLabel" : "Webcam"}, {"deviceId" : 1, "deviceLabel" : "Webcam1"}]

Expand All @@ -19,19 +25,52 @@ def index():
session["initialized"] = False
return redirect(url_for("user.login"))

wanderpis = Wanderpi.get_all()
return render_template("index.html", wanderpis=wanderpis)
travels = Travel.get_all()

return render_template("index.html", travels=travels)

@home_blu.route('/travel/<string:travel_id>')
def travel(travel_id):
print(travel_id)
username = session.get("username")
if not username:
session["initialized"] = False
return redirect(url_for("user.login"))

travel = Travel.get_by_id(travel_id)
wanderpis = travel.get_all_wanderpis()

return render_template("travel_view.html", wanderpis=wanderpis, travel=travel)

@home_blu.route('/global_map/<string:travel_id>')
def global_map(travel_id):
# 模板渲染
username = session.get("username")
if not username:
session["initialized"] = False
return redirect(url_for("user.login"))

print(travel_id)
travel = Travel.get_by_id(travel_id)
wanderpis = travel.get_all_wanderpis()
return render_template("global_map.html", wanderpis=wanderpis, travel=travel)

@home_blu.route('/delete_travel/<string:id>')
def delete_travel(id):
print(id)
travel = Travel.get_by_id(id)
travel.delete_all_wanderpis()
Travel.delete(id)
return redirect("/", code=302)

@home_blu.route('/delete_video/<string:id>')
def delete_video(id):
print(id)
Wanderpi.delete(id)
return redirect("/", code=302)


@home_blu.route('/<path:id>')
@home_blu.route('/video/<path:id>')
def single_video(id):
# 模板渲染
username = session.get("username")
if not username:
session["initialized"] = False
Expand All @@ -40,15 +79,16 @@ def single_video(id):
wanderpi = Wanderpi.get_by_id(id)
return render_template("single-video-view.html", video=wanderpi)

# 主页
@home_blu.route('/record')
def record():
@home_blu.route('/record/<string:travel_id>')
def record(travel_id):
# 模板渲染
username = session.get("username")
if not username:
session["initialized"] = False
return redirect(url_for("user.login"))
return render_template("record.html")

travel = Travel.get_by_id(travel_id)
return render_template("record.html", travel=travel)

def init_camera(camera_id):
global video_camera
Expand All @@ -68,9 +108,7 @@ def init_camera(camera_id):
# video_camera.stop_record()

return video_camera


# 获取视频流
def video_stream(camera_id):
global video_camera
global global_frame
Expand All @@ -88,18 +126,14 @@ def video_stream(camera_id):
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + global_frame + b'\r\n\r\n')


# 视频流
@home_blu.route('/video_feed/<string:camera_id>/')
def video_feed(camera_id):
# 模板渲染
username = session.get("username")
if not username:
return redirect(url_for("user.login"))
return Response(video_stream(camera_id),
mimetype='multipart/x-mixed-replace; boundary=frame')

# 录制状态
@home_blu.route('/record_status', methods=['POST'])
def record_status():
global video_camera
Expand All @@ -109,22 +143,39 @@ def record_status():

json = request.get_json()

print(json)

status = json['status']

if status == "true":
print("Start recording...")
video_id_1 = request.args.get('video_id', default=None)

if video_id_1:
print("Deleting video that was not saved on database with id: {0}".format(video_id_1))
p = VIDEOS_FOLDER + "/" + video_id_1 + ".mp4"
if os.path.exists(p):
os.remove(p)

video_id = video_camera.start_record()
return jsonify(result="started", video_id=video_id)
else:
print("Stop recording...")
lat = json['lat']
lng = json['long']

video_id = video_camera.stop_record()
return jsonify(result="stopped", video_id=video_id)

video_name = str(datetime.now()) + " at " + GeoCodeUtils.reverse_latlong(lat, lng)

VideoEditor.AddTitleToVideo(video_camera.recordingThread.path_rel, video_name)

return jsonify(result="stopped", video_id=video_id, video_name=video_name)

@home_blu.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download_file(filename):
return send_from_directory(VIDEOS_FOLDER, filename, as_attachment=True)


@home_blu.route('/get_available_video_sources', methods=['GET', 'POST'])
def get_available_video_sources(): #todo get available video sources from database
return jsonify(devices = video_camera_ids)
Expand All @@ -138,13 +189,51 @@ def save_video(video_id): #todo get available video sources from database
name = video_id
lat_coord = request.args.get('lat')
long_coord = request.args.get('long')
travel_id = request.args.get('travel_id')
thumbnail_url = "thumbnail-%s.jpg" % str(video_id)

print(name, lat_coord, long_coord, thumbnail_url)

wanderpi = Wanderpi(id=video_id, name=name, lat=lat_coord, long=long_coord, thumbnail_url=thumbnail_url)
wanderpi = Wanderpi(id=video_id, name=name, lat=lat_coord, long=long_coord, thumbnail_url=thumbnail_url, travel_id=travel_id)
wanderpi.save()

return jsonify(devices = video_camera_ids)
return jsonify(status_code = 200, message = "OK")

def toDate(dateString):
print(dateString)
return datetime.strptime(dateString, "%Y-%m-%dT%H:%M") #example datetime input 2021-07-01T13:45

@home_blu.route('/save_travel/', methods=['GET', 'POST'])
def save_travel(): #todo get available video sources from database
print("Saving travel")

name = request.args.get('name')
destination = request.args.get('destination')
start_date = request.args.get('start_date', type=toDate)
end_date = request.args.get('end_date', type=toDate)
travel_id = str(uuid.uuid4())

travel = Travel(id=travel_id, name=name, lat="0", long="0", destination=destination, start_date=start_date, end_date=end_date)
travel.save()

return jsonify(status_code = 200, message = "OK")

@home_blu.route('/latlong/<string:adress>', methods=['GET', 'POST'])
def latlong(adress):
travel_id = request.args.get('travel_id')
if travel_id:
travel = Travel.get_by_id(travel_id)
print(travel.lat, travel.long)
if travel.lat != "0" and travel.long != "0":
print("Found travel with id {0} and cached lat and long".format(travel_id))
return jsonify(lat=travel.lat, long=travel.long, status_code = 200, message = "OK")
else:
print("Travel with id {0} found in database but lat and long is not cached".format(travel_id))
lat, lng = GeoCodeUtils.reverse_adress(adress)
travel.lat = lat
travel.long = lng
travel.save()
return jsonify(lat=lat, long=lng, status_code = 200, message = "OK")
else:
print("No travel id found")
return jsonify(status_code = 400, message = "No travel id found")
14 changes: 14 additions & 0 deletions controller/static/css/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,17 @@ body {
width: 200px;
}

@media (max-width: 768px) {
.btn-responsive {
width: 30px;
height: 30px;
}
}

@media (min-width: 769px) and (max-width: 992px) {
.btn-responsive {
width: 60px;
height: 60px;
}
}

4 changes: 2 additions & 2 deletions controller/static/css/recording-screen-style.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
}


@media (max-width: 768px) {
/* @media (max-width: 768px) {
.btn-responsive {
padding:2px 4px;
font-size:80%;
Expand All @@ -21,7 +21,7 @@
line-height: 1.2;
}
}

*/


.map-responsive{
Expand Down
22 changes: 22 additions & 0 deletions controller/static/images/add-more-icon-circle.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 6c84fc7

Please sign in to comment.