From d8620ccda26b2c1a39fb97d47b73698dd9e2d1cd Mon Sep 17 00:00:00 2001 From: elblogbruno Date: Fri, 10 Sep 2021 13:02:56 +0100 Subject: [PATCH] Fixed bugs and option to enter stop address --- controller/models/models.py | 33 +++- controller/modules/files/views.py | 149 +++++++++++++----- controller/modules/home/geocode_utils.py | 15 +- controller/modules/home/views.py | 10 +- controller/modules/travel/views.py | 31 +++- .../static/js/calendar_notes_handler.js | 115 +++++++++----- controller/static/js/card_map_handler.js | 96 +++++------ controller/static/js/edit_files.js | 19 +-- controller/static/js/file_handler.js | 7 + controller/static/js/global_map.js | 21 +-- controller/static/js/jquery.repeatable.js | 2 +- controller/static/js/map_utils.js | 51 +++++- controller/static/js/single_file_view.js | 32 ++++ controller/static/js/single_video_view.js | 57 ------- controller/static/js/stops_handler.js | 20 ++- controller/templates/global_map.html | 5 +- controller/templates/index.html | 2 +- ..._video_view.html => single_file_view.html} | 54 ++----- controller/templates/stop_card.html | 42 +++++ controller/templates/stops_view.html | 1 + controller/templates/travel_card.html | 15 +- controller/templates/travel_view.html | 52 ++---- .../templates/wanderpi_more_info_modal.html | 129 ++------------- .../templates/wanderpi_placeholder_card.html | 79 ++++++++++ .../templates/wanderpi_text_info_card.html | 55 +++++++ controller/utils/image_editor.py | 15 +- 26 files changed, 651 insertions(+), 456 deletions(-) create mode 100644 controller/static/js/single_file_view.js delete mode 100644 controller/static/js/single_video_view.js rename controller/templates/{single_video_view.html => single_file_view.html} (78%) create mode 100644 controller/templates/stop_card.html create mode 100644 controller/templates/wanderpi_placeholder_card.html create mode 100644 controller/templates/wanderpi_text_info_card.html diff --git a/controller/models/models.py b/controller/models/models.py index b6d6893..8e6f5d5 100644 --- a/controller/models/models.py +++ b/controller/models/models.py @@ -1,6 +1,6 @@ from werkzeug.security import generate_password_hash, check_password_hash import db -from sqlalchemy import Column, Boolean, String, Float, DateTime, Text, Date, Time, desc, func +from sqlalchemy import Column, Boolean, String, Float, DateTime, Text, Date, Time, asc, func # from datetime import datetime import os import json @@ -28,6 +28,7 @@ class Wanderpi(db.Base): stop_id = Column(String(256), nullable=False) is_image = Column(Boolean) is_360 = Column(Boolean) + has_original_lat_long = Column(Boolean) has_been_edited = Column(Boolean, default=False) def __repr__(self): @@ -150,9 +151,9 @@ def get_total_price(self): def get_all_wanderpis(self, filter=None): if filter: is_image = (filter == 'image') - return db.session.query(Wanderpi).filter(Wanderpi.travel_id == self.id, Wanderpi.is_image == is_image).all() + return db.session.query(Wanderpi).filter(Wanderpi.travel_id == self.id, Wanderpi.is_image == is_image).order_by(asc(Wanderpi.created_date)).all() else: - return db.session.query(Wanderpi).filter(Wanderpi.travel_id == self.id).all() + return db.session.query(Wanderpi).filter(Wanderpi.travel_id == self.id).order_by(asc(Wanderpi.created_date)).all() def get_all_stops(self): return db.session.query(Stop).filter(Stop.travel_id == self.id).all() @@ -232,7 +233,7 @@ class Stop(db.Base): lat = Column(String(256), nullable=False) long = Column(String(256), nullable=False) name = Column(String(256), nullable=False) - + address = Column(String(256), nullable=False) def __repr__(self): return f'' @@ -258,9 +259,9 @@ def as_dict(self): def get_all_wanderpis(self, filter=None): if filter: is_image = (filter == 'image') - return db.session.query(Wanderpi).filter(Wanderpi.stop_id == self.id, Wanderpi.is_image == is_image).all() + return db.session.query(Wanderpi).filter(Wanderpi.stop_id == self.id, Wanderpi.is_image == is_image).order_by(asc(Wanderpi.created_date)).all() else: - return db.session.query(Wanderpi).filter(Wanderpi.stop_id == self.id).all() + return db.session.query(Wanderpi).filter(Wanderpi.stop_id == self.id).order_by(asc(Wanderpi.created_date)).all() def get_random_thumbnail(self): wanderpis = self.get_all_wanderpis() @@ -287,7 +288,25 @@ def rename_all_wanderpi_paths(new_path, old_path): synchronize_session=False) ) print("Updated {} rows".format(updated_rows)) - + + def fix_all_wanderpi_coordenates(self, lat, long, address): + print(lat, long, address) + updated_rows = ( + db.session.query(Wanderpi).filter(Wanderpi.has_original_lat_long == False, Wanderpi.stop_id == self.id).update({Wanderpi.lat: func.replace(Wanderpi.lat, Wanderpi.lat, lat)}, + synchronize_session=False) + ) + print("Updated {} rows".format(updated_rows)) + updated_rows = ( + db.session.query(Wanderpi).filter(Wanderpi.has_original_lat_long == False, Wanderpi.stop_id == self.id).update({Wanderpi.long: func.replace(Wanderpi.long, Wanderpi.long, long)}, + synchronize_session=False) + ) + print("Updated {} rows".format(updated_rows)) + updated_rows = ( + db.session.query(Wanderpi).filter(Wanderpi.has_original_lat_long == False, Wanderpi.stop_id == self.id).update({Wanderpi.address: func.replace(Wanderpi.address, Wanderpi.address, address)}, + synchronize_session=False) + ) + print("Updated {} rows".format(updated_rows)) + @staticmethod def get_by_id(id): return db.session.query(Stop).get(id) diff --git a/controller/modules/files/views.py b/controller/modules/files/views.py index 033fe52..002c53e 100644 --- a/controller/modules/files/views.py +++ b/controller/modules/files/views.py @@ -75,32 +75,35 @@ def create_folder_structure_for_stop(travel_id, name=None, stop_id=None): #get_travel_folder_path_static #get_travel_folder_path -def get_file_path(travel_id, stop_id, filename_or_file_id= None, file_type = 'images', static = False): +def get_file_path(travel_id, stop_id = None, filename_or_file_id= None, file_type = 'images', static = False): CUSTOM_STATIC_FOLDER, VIDEOS_FOLDER, UPLOAD_FOLDER = load_custom_video_folder() root = STATIC_FOLDER if static else VIDEOS_FOLDER stop = Stop.get_by_id(stop_id) + init_path = root + str(travel_id) + if stop_id: + init_path = init_path + '/' + stop.name + if filename_or_file_id and stop_id: + if file_type == 'images': + return init_path + '/images/' + str(filename_or_file_id) + elif file_type == 'videos': + if '.mp4' in filename_or_file_id: + return init_path + '/videos/'+ str(filename_or_file_id) + else: + return init_path + '/videos/'+ str(filename_or_file_id) + '.mp4' + elif file_type == 'thumbnails': + return init_path + '/thumbnails/thumbnail-%s.jpg' % str(filename_or_file_id) - init_path = root + str(travel_id) + '/' + stop.name - if filename_or_file_id and stop_id: - if file_type == 'images': - return init_path + '/images/' + str(filename_or_file_id) - elif file_type == 'videos': - if '.mp4' in filename_or_file_id: - return init_path + '/videos/'+ str(filename_or_file_id) - else: - return init_path + '/videos/'+ str(filename_or_file_id) + '.mp4' - elif file_type == 'thumbnails': - return init_path + '/thumbnails/thumbnail-%s.jpg' % str(filename_or_file_id) - + else: + if file_type == 'images': + return init_path + '/images' + elif file_type == 'videos': + return init_path + '/videos' + elif file_type == 'thumbnails': + return init_path + '/thumbnails' else: - if file_type == 'images': - return init_path + '/images' - elif file_type == 'videos': - return init_path + '/videos' - elif file_type == 'thumbnails': - return init_path + '/thumbnails' - + return init_path + def get_stop_upload_path(stop_name, stop_id=None): CUSTOM_STATIC_FOLDER, VIDEOS_FOLDER, UPLOAD_FOLDER = load_custom_video_folder() if stop_id: @@ -165,20 +168,25 @@ def save_file_to_database(is_image, travel_id, stop_id, name, lat_coord, long_co else: time_duration = VideoUtils.get_video_info(video_file_path) + has_original_lat_long = True + stop = Stop.get_by_id(stop_id) if lat_coord == 0 and long_coord == 0: lat_coord = stop.lat long_coord = stop.long - address = stop.name + address = stop.address + has_original_lat_long = False else: #address = GeoCodeUtils.reverse_latlong(lat_coord, long_coord) #In the future will make a bot thtat does this on background. - address = stop.name + address = stop.address + has_original_lat_long = False + #remove everything till it reaches the word wanderpi cdn_path = '/wanderpi/'+file_path.split('/wanderpi/')[-1] - video = Wanderpi(id=file_id, name=name, lat=lat_coord, long=long_coord, file_thumbnail_path=file_thumbnail_path, travel_id=travel_id, stop_id=stop_id, address=address, time_duration=time_duration, file_path=file_path, cdn_path=cdn_path, is_image=is_image, has_been_edited=edit_video, created_date=created_date, is_360=is_360) + video = Wanderpi(id=file_id, name=name, lat=lat_coord, long=long_coord, file_thumbnail_path=file_thumbnail_path, travel_id=travel_id, stop_id=stop_id, address=address, time_duration=time_duration, file_path=file_path, cdn_path=cdn_path, is_image=is_image,has_original_lat_long=has_original_lat_long, has_been_edited=edit_video, created_date=created_date, is_360=is_360) video.save() return "ok" @@ -456,7 +464,7 @@ def process_recreate_thumbnails(stop_id): recreate_stops_thumbnail(stop_id=stop_id, emit_key="process_upload_folder_update") -def process_stop_files(stop_id,emit_key): +def process_stop_files(stop_id, emit_key, single_one = True): global latest_message global latest_message_counter @@ -469,16 +477,16 @@ def process_stop_files(stop_id,emit_key): final_folder_path = UPLOAD_FOLDER + stop_name + "/" create_folder_structure_for_stop(travel_id=travel_id, stop_id=stop_id) - + print("Final stop folder upload path: " + final_folder_path) try: upload_files = [f for f in listdir(final_folder_path) if isfile(join(final_folder_path, f))] total_files = len(upload_files) counter = 0 if len(upload_files) > 0: for file in upload_files: - emit(emit_key, 'Uploading file {0}'.format(file)) - print('Uploading file {0}'.format(file)) - latest_message = 'Uploading file {0}'.format(file) + emit(emit_key, 'Uploading file {0} to {1}'.format(file,stop_name)) + print('Uploading file {0} to {1}'.format(file,stop_name)) + latest_message = 'Uploading file {0} to {1}'.format(file,stop_name) path_to_move_file = final_folder_path+file if (get_file_extension(file) in IMAGE_EXTENSIONS): #move file to images folder @@ -514,9 +522,10 @@ def process_stop_files(stop_id,emit_key): print("Done") sleep(0.1) - emit(emit_key, "200") - latest_message = "200" - uploading_files = False + if single_one: + emit(emit_key, "200") + latest_message = "200" + uploading_files = False else: emit(emit_key, "No files on the uploads folder") print('No files on the uploads folder') @@ -524,17 +533,19 @@ def process_stop_files(stop_id,emit_key): sleep(2) emit(emit_key, "") latest_message = "" - emit(emit_key, "200") - latest_message = "200" - uploading_files = False + if single_one: + emit(emit_key, "200") + latest_message = "200" + uploading_files = False return "200" except OSError as e: emit(emit_key, str(e)) latest_message = str(e) sleep(2) - emit(emit_key, "200") - latest_message = "200" + if single_one: + emit(emit_key, "200") + latest_message = "200" return "200" @@ -572,11 +583,71 @@ def process_travel_upload(travel_id): emit('process_travel_upload_folder_update', 'Processing stop {0}'.format(stop_name)) print('Processing stop {0}'.format(stop_name)) latest_message = 'Processing stop {0}'.format(stop_name) - status = process_stop_files(stop_id=stop_id, emit_key="process_travel_upload_folder_update") + status = process_stop_files(stop_id=stop_id, emit_key="process_travel_upload_folder_update", single_one=False) if status == "200": emit('process_travel_upload_folder_update', 'Finished processing stop {0}'.format(stop_name)) print('Finished processing stop {0}'.format(stop_name)) latest_message = 'Finished processing stop {0}'.format(stop_name) - - +def recalculate_stop_coordenates(stop_id, emit_key): + global latest_message + global latest_message_counter + + stop = Stop.get_by_id(stop_id) + + try: + lat, lng = GeoCodeUtils.reverse_address(stop.address,original_lat= stop.lat,original_long= stop.long) + + stop.lat = lat + stop.long = lng + + stop.fix_all_wanderpi_coordenates(lat, lng, stop.address) + stop.save() + + emit(emit_key, "Stop {0} has correct coordenates now.".format(stop.name)) + latest_message = "Stop {0} has correct coordenates now.".format(stop.name) + + sleep(0.1) + emit(emit_key, "200") + latest_message = "200" + uploading_files = False + + return "200" + except OSError as e: + emit(emit_key, str(e)) + latest_message = str(e) + sleep(2) + emit(emit_key, "200") + latest_message = "200" + return "200" + + +@socketio.on("process_recalculate_stops_coordenates") +def process_recalculate_stops_coordenates(travel_id): + #for every file in the uploads folder, upload it to the database + global latest_message + global latest_message_counter + if travel_id == 'ok': + print("user conected again") + emit('process_travel_upload_folder_update', latest_message) + emit('process_upload_folder_update_counter', latest_message_counter) + else: + global uploading_files + uploading_files = True + travel = Travel.get_by_id(travel_id) + for stop in travel.get_all_stops(): + stop_name = stop.name + stop_id = stop.id + emit('process_travel_upload_folder_update', 'Processing stop {0}'.format(stop_name)) + print('Processing stop {0}'.format(stop_name)) + latest_message = 'Processing stop {0}'.format(stop_name) + status = recalculate_stop_coordenates(stop_id=stop_id, emit_key="process_travel_upload_folder_update") + if status == "200": + emit('process_travel_upload_folder_update', 'Finished processing stop {0}'.format(stop_name)) + print('Finished processing stop {0}'.format(stop_name)) + latest_message = 'Finished processing stop {0}'.format(stop_name) + + emit('process_travel_upload_folder_update', 'Finished processing stops') + latest_message = 'Finished processing stops' + + \ No newline at end of file diff --git a/controller/modules/home/geocode_utils.py b/controller/modules/home/geocode_utils.py index e147ed9..b39c9b0 100644 --- a/controller/modules/home/geocode_utils.py +++ b/controller/modules/home/geocode_utils.py @@ -46,7 +46,7 @@ def reverse_latlong(lat,long): @staticmethod - def reverse_address(address): + def reverse_address(address, original_lat = None, original_long = None): """Function that having an adress translates it to a lat and long values" """ locator = Nominatim(user_agent="openmapquest") @@ -56,9 +56,18 @@ def reverse_address(address): if location: return location.latitude, location.longitude else: - return 0,0 + if original_lat and original_long: + print("Returning original lat and long") + return original_lat,original_long + else: + return 0,0 except geopy.exc.GeocoderUnavailable as e: - return 0,0 + if original_lat and original_long: + print("Returning original lat and long") + + return original_lat,original_long + else: + return 0,0 @staticmethod diff --git a/controller/modules/home/views.py b/controller/modules/home/views.py index f499fd0..5ae5896 100644 --- a/controller/modules/home/views.py +++ b/controller/modules/home/views.py @@ -63,7 +63,7 @@ def travel_calendar(travel_id): travel = Travel.get_by_id(travel_id) if travel: notes = travel.get_all_notes() - total_price = travel.get_total_price() + total_price = round(travel.get_total_price(), 3) else: notes = [] session["current_travel_id"] = travel_id @@ -103,7 +103,7 @@ def stop(stop_id, page): total_count = len(wanderpis) #sort wanderpis by date - wanderpis = sorted(wanderpis, key=lambda x: x.created_date) + #wanderpis = sorted(wanderpis, key=lambda x: x.created_date) pagination = Pagination(page, per_page=per_page, total_count=total_count) current_count = page*per_page @@ -139,7 +139,7 @@ def slide_view(stop_id, page): total_count = len(wanderpis) #sort wanderpis by date - wanderpis = sorted(wanderpis, key=lambda x: x.created_date) + #wanderpis = sorted(wanderpis, key=lambda x: x.created_date) pagination = Pagination(page, per_page=per_page, total_count=total_count) @@ -174,7 +174,7 @@ def global_map(id, page): total_count = len(wanderpis) #sort wanderpis by date - wanderpis = sorted(wanderpis, key=lambda x: x.created_date) + #wanderpis = sorted(wanderpis, key=lambda x: x.created_date) pagination = Pagination(page, per_page=per_page, total_count=total_count) @@ -199,7 +199,7 @@ def single_file(id): # if wanderpi.is_image: # wanderpi.file_path = wanderpi.file_path.replace('/mnt', '') - return render_template("single_video_view.html", file=wanderpi, stop=stop, travel=travel) + return render_template("single_file_view.html", file=wanderpi, stop=stop, travel=travel) except jinja2.exceptions.UndefinedError as e: print(str(e)) return redirect(url_for("home.index")) diff --git a/controller/modules/travel/views.py b/controller/modules/travel/views.py index 31073cd..b027759 100644 --- a/controller/modules/travel/views.py +++ b/controller/modules/travel/views.py @@ -133,7 +133,9 @@ def save_travel(): #todo get available video sources from database travel_folder_path = get_file_path(travel_id=travel_id, file_type='root') - travel = Travel(id=travel_id, name=name, lat="0", long="0", travel_folder_path=travel_folder_path, destination=destination, start_date=start_date, end_date=end_date) + lat, lng = GeoCodeUtils.reverse_address(address) + + travel = Travel(id=travel_id, name=name, lat=lat, long=lng, travel_folder_path=travel_folder_path, destination=destination, start_date=start_date, end_date=end_date) travel.save() travel.init_calendar() return jsonify(status_code = 200, message = "OK") @@ -143,25 +145,44 @@ def add_stop(travel_id): #todo get available video sources from database print("Adding stop") name = request.args.get('name') + address = request.args.get('address') + + print(address) + stop_id = str(uuid.uuid4()) - create_folder_structure_for_stop(travel_id=travel_id,name=name) + create_folder_structure_for_stop(travel_id=travel_id, name=name) - stop = Stop(id=stop_id, travel_id=travel_id, name=name, lat="0", long="0") + lat, lng = GeoCodeUtils.reverse_address(address) + + stop = Stop(id=stop_id, address=address, travel_id=travel_id, name=name, lat=lat, long=lng) stop.save() return jsonify(status_code = 200, message = "OK") @travel_blu.route('/edit_stop/', methods=['GET', 'POST']) def edit_stop(stop_id): #todo get available video sources from database - print("Editing stop") + print("Editing stop {0}".format(stop_id)) name = request.args.get('name') + address = request.args.get('address') stop = Stop.get_by_id(stop_id) + + old_address = stop.address + stop.address = address + old_name = stop.name stop.name = name - stop.save() + lat, long = GeoCodeUtils.reverse_address(address, original_lat=stop.lat,original_long=stop.long) + + stop.lat = lat + stop.long = long + + stop.fix_all_wanderpi_coordenates(lat, long, address) + + stop.save() + rename_stop_folder(stop.travel_id, old_name, name) return jsonify(status_code = 200, message = "OK", travel_id=stop.travel_id) diff --git a/controller/static/js/calendar_notes_handler.js b/controller/static/js/calendar_notes_handler.js index bae048d..5041b7b 100644 --- a/controller/static/js/calendar_notes_handler.js +++ b/controller/static/js/calendar_notes_handler.js @@ -18,11 +18,20 @@ $('#addNoteModal').on('show.bs.modal', function (event) { var cost_container = document.querySelector(".repeatable"); costs = []; //field-group-{?} - for (let index = 0; index < cost_container.children.length; index++) { - var input_name = document.getElementById('input-price-name-new'+index) //input-price-name-new0 + if (cost_container.children.length >= 1) + { + var id = cost_container.children[0].id; + start_index = id.split("-")[id.split("-").length-1]; + // start_index = id.charAt(id.length-1); + + console.log("STARTING INDEX: " + start_index); + } + + for (let index = start_index; index < cost_container.children.length; index++) { + var input_name = document.getElementById('input-price-name-new-'+index) //input-price-name-new0 var name = input_name.value; - var price = document.getElementById('input-price-value-new'+index).value; - var id = document.getElementById('input-price-id-new'+index).value; + var price = document.getElementById('input-price-value-new-'+index).value; + var id = document.getElementById('input-price-id-new-'+index).value; console.log(id); if (id){ @@ -44,9 +53,18 @@ $('#addNoteModal').on('show.bs.modal', function (event) { } addNote(travel_id, note_content, costs, note_id); }; - }) +}) +$('#addNoteModal').on('shown.bs.modal', function (event) { + console.log("MODAL HAS BEEN SHOWN"); +}) +$(".input-money .repeatable").repeatable({ + addTrigger: ".add", + deleteTrigger: ".delete", + template: '#input-money', + itemContainer: ".field-group", +}); function addNote(travel_id, note_content, costs, note_id){ var data = { @@ -80,17 +98,15 @@ function addNote(travel_id, note_content, costs, note_id){ } -$(".input-money .repeatable").repeatable({ - addTrigger: ".add", - deleteTrigger: ".delete", - template: '#input-money', - itemContainer: ".field-group", -}); + +var start_index = 0; var next = 0; -function clone(name, value, id){ +function clone(name, value, id) +{ let button = document.querySelector(".add"); button.click(); + next = next + 1; nextBefore = next-1; @@ -98,36 +114,19 @@ function clone(name, value, id){ // $("#add-more-"+nextBefore).attr('id', 'add-more-'+next) // $("#input-price-name-"+nextBefore).attr('id', 'input-price-name-'+next) - $("#input-price-name-new"+nextBefore).val(name) + $("#input-price-name-new-"+nextBefore).val(name) // $("#input-price-value-"+nextBefore).attr('id', 'input-price-value-'+next) - $("#input-price-value-new"+nextBefore).val(value) + $("#input-price-value-new-"+nextBefore).val(value) // $("#input-price-id-"+nextBefore).attr('id', 'input-price-id-'+next) - $("#input-price-id-new"+nextBefore).val(id) + $("#input-price-id-new-"+nextBefore).val(id) // $(".input-money .repeatable").repeatable.addOne(); - - console.log("added new clone: " + next); } -function remove(id){ - console.log(id); - fields = document.getElementById("fields") - console.log(fields.children.length); - console.log(fields.children); - if(fields.children.length > 1){ - for (let index = 0; index < fields.children.length; index++) { - const element = fields.children[index]; - if (element.id = id){ - fields.removeChild(fields.children[index]); - break; - } - } - } -} - -function get_costs(note_id){ +function get_costs(note_id) +{ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { @@ -149,12 +148,46 @@ function get_costs(note_id){ xhr.send(); } -function instantiateCosts(note_input_prices){ - console.log(note_input_prices); +function removeAllChilds() +{ + // var cost_container = document.querySelector(".repeatable"); + + + // console.log(cost_container.children.length); + // console.log(cost_container.children); + + // for (let index = 0; index < cost_container.children.length; index++) + // { + // console.log(index); + // let input = document.getElementById('field-group-new'+index); + // console.log(input); + // let button = input.querySelector(".delete"); + // console.log(button); + // button.click(); + // } + var cost_container = document.querySelector(".repeatable"); - cost_container.innerHTML = '' - if (note_input_prices.length >= 1){ - console.log("We need to add existing costs"); + + // start_index = cost_container.children.length; + // console.log("STARTING INDEX: " + start_index); + + + + cost_container.innerHTML = ''; +} + +function instantiateCosts(note_input_prices) +{ + console.log(note_input_prices); + + // last_total_count_of_inputs = note_input_prices.length; + + removeAllChilds(); + + if (note_input_prices.length >= 1) + { + console.log("We need to add existing costs"); + for (let index = 0; index < note_input_prices.length; index++) { const element = note_input_prices[index]; var name = element.name; @@ -163,7 +196,7 @@ function instantiateCosts(note_input_prices){ clone(name, value,id); } }else{ - + next = 0; console.log("Adding no costs") } -} \ No newline at end of file +} diff --git a/controller/static/js/card_map_handler.js b/controller/static/js/card_map_handler.js index 4e18333..f8e956d 100644 --- a/controller/static/js/card_map_handler.js +++ b/controller/static/js/card_map_handler.js @@ -1,20 +1,27 @@ var pathCoords = []; +var map; +var map_initialized = false; -function initializeStopsList(sLat, sLong){ +function initializeMap(travel_id) +{ + if (!map_initialized) + { + map = create_map(`map-container-google-${travel_id}`, true); + map_initialized = true; + } +} + +function initializeStopsList(sLat, sLong, sAddress){ pathCoords.push(new L.LatLng(sLat,sLong)) + + var marker_html = ` ${sAddress} `; + var marker = L.marker([sLat, sLong]).bindPopup(marker_html).addTo(map); } + //function that inits leaflet map but shows text that says start recording to show map //https://gis.stackexchange.com/questions/53394/select-two-markers-draw-line-between-them-in-leaflet -function initializeMapAndLocator(travel_id, travel_destination) +function initializeMapAndLocator(travel_lat, travel_long) { - var map = L.map(`map-container-google-${travel_id}`); - map.addControl(new L.Control.Fullscreen()); - - googleStreets = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{ - maxZoom: 20, - subdomains:['mt0','mt1','mt2','mt3'] - }).addTo(map); - function locate() { map.locate({setView: true, maxZoom: 16}); } @@ -26,20 +33,12 @@ function initializeMapAndLocator(travel_id, travel_destination) var pathLine = L.polyline(pathCoords, {color: 'red'}).addTo(map); - + console.log(pathCoords); + + sortByDistance(pathCoords, e.latlng); + + console.log(pathCoords); - // var pathLine = L.motion.polyline(pathCoords, { - // color: "transparent" - // }, { - // auto: true, - // speed: 5, - // duration: 10000, - // easing: L.Motion.Ease.easeInOutQuart - // }, { - // removeOnEnd: false, - // showMarker: true, - // icon: L.divIcon({html: "", iconSize: L.point(27.5, 24)}) - // }).addTo(map); map.fitBounds(pathLine.getBounds()); @@ -48,38 +47,41 @@ function initializeMapAndLocator(travel_id, travel_destination) map.on('locationfound', onLocationFound); - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange = function () { - if (xhr.readyState == 4 && xhr.status == 200) { - var response = JSON.parse(xhr.responseText); + pathCoords.push(new L.LatLng(travel_lat, travel_long)) - if (response.status_code == 200) { - var lat = response.lat; - var long = response.long; + locate(); + // var xhr = new XMLHttpRequest(); + // xhr.onreadystatechange = function () { + // if (xhr.readyState == 4 && xhr.status == 200) { + // var response = JSON.parse(xhr.responseText); - // console.log(lat, long); + // if (response.status_code == 200) { + // var lat = response.lat; + // var long = response.long; + + // // console.log(lat, long); - // call locate every 3 seconds... forever - locate(); + // // call locate every 3 seconds... forever + // locate(); - pathCoords.push(new L.LatLng(lat, long)); - } - else - { - console.log(response.status_code); - } - } + // pathCoords.push(new L.LatLng(lat, long)); + // } + // else + // { + // console.log(response.status_code); + // } + // } - } + // } - var base_url = window.location.origin; - var url = new URL(base_url+"/latlong/"+ travel_destination); - url.searchParams.append('travel_id', travel_id); + // var base_url = window.location.origin; + // var url = new URL(base_url+"/latlong/"+ travel_destination); + // url.searchParams.append('travel_id', travel_id); - xhr.open("POST", url.toString()); - xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); - xhr.send(); + // xhr.open("POST", url.toString()); + // xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); + // xhr.send(); } diff --git a/controller/static/js/edit_files.js b/controller/static/js/edit_files.js index 7f32acb..dcc788c 100644 --- a/controller/static/js/edit_files.js +++ b/controller/static/js/edit_files.js @@ -6,18 +6,11 @@ function init_map_for_editing() { if (map_initiated == false) { - console.log("initialized map to edit"); - - map = L.map('map-container-global'); - map.addControl(new L.Control.Fullscreen()); - - googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{ - maxZoom: 15, - subdomains:['mt0','mt1','mt2','mt3'] - }).addTo(map); - - map.setView([46.244553376495,-9.43842451847176], 2); + console.log("Initialized map to edit"); + map = create_map('map-container-global', true); + map.setView([46.244553376495,-9.43842451847176], 2); + map.on('click', function(e){ var coord = e.latlng; var lat = coord.lat; @@ -33,7 +26,7 @@ function init_map_for_editing() map.setView(e.latlng, 15); map_modified = true; - }); + }); map_initiated = true; @@ -190,5 +183,5 @@ bulkEditModal.addEventListener('shown.bs.modal', function (event) { init_map_for_editing(); setTimeout(function() { map.invalidateSize(); - }, 1); + }, 1); }); \ No newline at end of file diff --git a/controller/static/js/file_handler.js b/controller/static/js/file_handler.js index 9f4bb21..e3085e3 100644 --- a/controller/static/js/file_handler.js +++ b/controller/static/js/file_handler.js @@ -52,6 +52,13 @@ function startProcessingUploadFolderForTravel(travel_id) socket.emit('process_travel_upload_folder_update', travel_id) } +function recalculateStopsCoordenates(travel_id) +{ + downloading_file = true; + disableButtons() + socket.emit('process_recalculate_stops_coordenates', travel_id) +} + function get_upload_status() { socket.emit('get_upload_status', 'data') diff --git a/controller/static/js/global_map.js b/controller/static/js/global_map.js index 54b8fef..3567c9e 100644 --- a/controller/static/js/global_map.js +++ b/controller/static/js/global_map.js @@ -6,18 +6,11 @@ var markers; var gps = document.getElementById("gps_text"); var oms; -const OverlappingMarkerSpiderfier = window.OverlappingMarkerSpiderfier; +// const OverlappingMarkerSpiderfier = window.OverlappingMarkerSpiderfier; function init_map() { - map = L.map('map-container-global'); - - googleStreets = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{ - maxZoom: 20, - subdomains:['mt0','mt1','mt2','mt3'] - }).addTo(map); - - map.addControl(new L.Control.Fullscreen()); + map = create_map('map-container-global', true); markers = new L.MarkerClusterGroup({ spiderfyOnMaxZoom: true, @@ -29,7 +22,8 @@ function init_map() } //function that checks if a point is already on the map -function is_point_on_map(lat, long) { +function is_point_on_map(lat, long) +{ for (var i = 0; i < list_of_points.length; i++) { console.log(lat,list_of_points[i].lat, long, list_of_points[i].lng); if (list_of_points[i].lat == lat && list_of_points[i].lng == long) { @@ -41,14 +35,13 @@ function is_point_on_map(lat, long) { function plot_map_from_list(list) { console.log(list); - for (var i = 0; i < list.length; i++) { + + for (var i = 0; i < list.length; i++) + { plot_map(list[i].lat, list[i].long, list[i].name, list[i].thumbnail_path, list[i].id); } } - - - function plot_map(lat, long, name, thumbnail_path, id) { if (!map_initiated) { init_map(); diff --git a/controller/static/js/jquery.repeatable.js b/controller/static/js/jquery.repeatable.js index e01a303..6fe6c7a 100644 --- a/controller/static/js/jquery.repeatable.js +++ b/controller/static/js/jquery.repeatable.js @@ -99,7 +99,7 @@ */ var getUniqueTemplate = function () { var template = $(settings.template).html(); - template = template.replace(/{\?}/g, "new" + i++); // {?} => iterated placeholder + template = template.replace(/{\?}/g, "new-" + i++); // {?} => iterated placeholder template = template.replace(/\{[^\?\}]*\}/g, ""); // {valuePlaceholder} => "" return $(template); }; diff --git a/controller/static/js/map_utils.js b/controller/static/js/map_utils.js index 97dd4b1..7379726 100644 --- a/controller/static/js/map_utils.js +++ b/controller/static/js/map_utils.js @@ -1,5 +1,6 @@ //having a list of coordenates, calculates total distance -function calculateDistance(list_of_points) { +function calculateDistance(list_of_points) +{ var distance = 0; for (var i = 0; i < list_of_points.length - 1; i++) { distance += getDistanceBetweenPoints(list_of_points[i].lat, list_of_points[i].lng, list_of_points[i + 1].lat, list_of_points[i + 1].lng); @@ -28,6 +29,16 @@ function deg2rad(p){ var singlePointsList = []; var acLatlong = {}; +function is_point_on_map(lat, long, travel_id) +{ + for (var i = 0; i < acLatlong[travel_id].length; i++) { + if (acLatlong[travel_id][i].lat == lat && acLatlong[travel_id][i].lng == long) { + return true; + } + } + return false; +} + function loadDistanceListFromWanderpis(lat, long, travel_id) { // if keys are not set, then we are starting a new map @@ -35,8 +46,9 @@ function loadDistanceListFromWanderpis(lat, long, travel_id) { acLatlong[travel_id] = [] } - - acLatlong[travel_id].push(new L.LatLng(lat, long)); + + if (!is_point_on_map(lat, long, travel_id) && (lat != 0 && long != 0)) + acLatlong[travel_id].push(new L.LatLng(lat, long)); } function loadDistanceListFromPoints(lat, long) @@ -52,7 +64,8 @@ function getDistance(){ return distance; } -function getDistanceByList(list_points){ +function getDistanceByList(list_points) +{ var distance = calculateDistance(list_points); return distance; @@ -69,3 +82,33 @@ function getDistanceByTravelId(travel_id){ } +const distance = (coor1, coor2) => { + console.log(coor1, coor2); + var d = getDistanceBetweenPoints(coor1.lat, coor1.lng, coor2.lat, coor2.lng); + console.log(d); + return d; +}; + +const sortByDistance = (coordinates, point) => { + const sorter = (a, b) => distance(a, point) - distance(b, point); + coordinates.sort(sorter); +}; + + +function create_map(map_id, add_fullscreen) +{ + console.log("Initializing map with id: " + map_id); + map = L.map(map_id); //file-map + + googleStreets = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{ + maxZoom: 20, + subdomains:['mt0','mt1','mt2','mt3'] + }).addTo(map); + + if (add_fullscreen) + { + map.addControl(new L.Control.Fullscreen()); + } + + return map; +} \ No newline at end of file diff --git a/controller/static/js/single_file_view.js b/controller/static/js/single_file_view.js new file mode 100644 index 0000000..c4f21a4 --- /dev/null +++ b/controller/static/js/single_file_view.js @@ -0,0 +1,32 @@ +var list_of_points = []; +var map; + +function init_map_for_file(file_id) +{ + console.log("Initializing map for file"); + + map = create_map('file-map-'+file_id); +} + +function showPosition(lat, long, address, file_id, show_map = true) { + if (show_map) + { + init_map_for_file(file_id); + + setTimeout(function() { + map.invalidateSize(); + map.setView([lat,long], 13); + var marker_html = ` ${address} `; + var marker = L.marker([lat, long]).bindPopup(marker_html).addTo(map); + + }, 1); + } +} + +function loadPoints(lat, long) { + list_of_points.push(new L.LatLng(lat, long)); + + var pathLine = L.polyline(list_of_points, {color: 'red'}).addTo(map); + + map.fitBounds(pathLine.getBounds()); +} \ No newline at end of file diff --git a/controller/static/js/single_video_view.js b/controller/static/js/single_video_view.js deleted file mode 100644 index 1eda683..0000000 --- a/controller/static/js/single_video_view.js +++ /dev/null @@ -1,57 +0,0 @@ -var list_of_points = []; -var map; -var map_initiated = false; - -function init_map_for_file(file_id) -{ - console.log("Initializing map for file"); - map = L.map('file-map-'+file_id); //file-map - - googleStreets = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{ - maxZoom: 20, - subdomains:['mt0','mt1','mt2','mt3'] - }).addTo(map); - - map_initiated = true; -} - -function showPosition(lat, long, address, file_id, show_map = true) { - if (map_initiated == false && show_map) { - init_map_for_file(file_id); - setTimeout(function() { - map.invalidateSize(); - map.setView([lat,long], 13); - var marker_html = ` ${address} `; - var marker = L.marker([lat, long]).bindPopup(marker_html).addTo(map); - - }, 1); - } - - // var latitude_text = document.getElementById("latitude_text"); - - // latitude_text.textContent = "Latitude: " + lat; - - // var longitude_text = document.getElementById("longitude_text"); - // longitude_text.textContent = "Longitude: " + long; - - // var address_text = document.getElementById("address_text"); - - // address_text.textContent = "Address: " + address; - - - - //add marker -} - -function loadPoints(lat, long) { - if (map_initiated == false) { - - init_map_for_file(); - } - - list_of_points.push(new L.LatLng(lat, long)); - - var pathLine = L.polyline(list_of_points, {color: 'red'}).addTo(map); - - map.fitBounds(pathLine.getBounds()); -} \ No newline at end of file diff --git a/controller/static/js/stops_handler.js b/controller/static/js/stops_handler.js index 590c276..9f69061 100644 --- a/controller/static/js/stops_handler.js +++ b/controller/static/js/stops_handler.js @@ -1,6 +1,8 @@ function add_stop(travel_id) { var name = document.getElementById("name_input").value; + var address_input = document.getElementById("address_input").value; + var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { @@ -18,6 +20,7 @@ function add_stop(travel_id) var url = new URL(base_url+"/add_stop/"+travel_id); url.searchParams.append('name', name); + url.searchParams.append('address', address_input) xhr.open("POST", url.toString()); xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); @@ -27,7 +30,7 @@ function add_stop(travel_id) -function editStop(stop_id, name) +function editStop(stop_id, name, address) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { @@ -48,6 +51,7 @@ function editStop(stop_id, name) var url = new URL(base_url+"/edit_stop/"+stop_id); url.searchParams.append('name', name); + url.searchParams.append('address', address); xhr.open("POST", url.toString()); xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); @@ -63,14 +67,20 @@ editStopModal.addEventListener('show.bs.modal', function (event) { console.log("Initializing modal"); var button = event.relatedTarget // Button that triggered the modal var stop_id = button.getAttribute('data-bs-stop-id') - var name = button.getAttribute('data-bs-name') - console.log(stop_id, name); + var original_name = button.getAttribute('data-bs-name') + var original_address = button.getAttribute('data-bs-address') + + console.log(stop_id, original_name, original_address); // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. var modal = $(this) - modal.find('.modal-body input').val(name) + modal.find('#new_name_input').val(original_name) + modal.find('#new_address_input').val(original_address) + + var new_name = modal.find('#new_name_input').val(); + var new_address = modal.find('#new_address_input').val(); document.getElementById('edit_stop_button').onclick = function () { - editStop(stop_id, modal.find('.modal-body input').val()); + editStop(stop_id, new_name, new_address); }; }); diff --git a/controller/templates/global_map.html b/controller/templates/global_map.html index 4dca57d..666e519 100644 --- a/controller/templates/global_map.html +++ b/controller/templates/global_map.html @@ -31,10 +31,9 @@ + + - - - diff --git a/controller/templates/index.html b/controller/templates/index.html index 5db8eaf..4474b53 100644 --- a/controller/templates/index.html +++ b/controller/templates/index.html @@ -37,8 +37,8 @@ - + diff --git a/controller/templates/single_video_view.html b/controller/templates/single_file_view.html similarity index 78% rename from controller/templates/single_video_view.html rename to controller/templates/single_file_view.html index 4120d3f..b51c753 100644 --- a/controller/templates/single_video_view.html +++ b/controller/templates/single_file_view.html @@ -1,3 +1,6 @@ +{% from "wanderpi_text_info_card.html" import render_wanderpi_info_card with context %} +{% from "wanderpi_placeholder_card.html" import render_wanderpi_placeholder with context %} + @@ -26,7 +29,7 @@ - + {% if not file.is_image %} @@ -75,8 +78,6 @@

Edit file location:

- -