def report_incident(): if request.method == "POST": inc_id = generate_id() incident_type = request.form['incident_type'] situation_type = request.form['situation_type'] incident_priority = calculate_priority(situation_type, incident_type) data = { "user_fname": request.form['fname'], "user_lname": request.form['lname'], "user_phone": request.form['phone'], "user_email": request.form['email'], "user_address": request.form['address'], "animal": request.form['animal'], "incident_id": inc_id, "incident_type": incident_type, "incident_priority": incident_priority, "situation_type": situation_type, "incident_location": request.form['incident_location'], # Make one for long_lat and one for address "incident_city": request.form['incident_city'], "incident_country": request.form['incident_country'], "incident_zipcode": request.form['incident_zipcode'], "incident_date": request.form['incident_date'], "incident_time":request.form['incident_time'], "image_url": request.form['url'], "incident_description": request.form['description'], "assigned_to": "No one", "incident_result": '', "source": "WebApp" } db.child("incident").push(data) return render_template('layouts/default.html', content=render_template( 'pages/user.html') )
def home(): if 'userToken' not in session: return redirect(url_for('account')) print(session['userToken']) uemail = session['userToken']['email'] user = db.child('Users/').order_by_child('email').equal_to( uemail).get().val() print('current user\n') for username, uinfo in user.items(): uname = username #upids = [pid for pid in uinfo['posts']] #utoken= uinfo['id'] # redundent #uemail=uinfo['email'] #redundent session['username'] = uname app.logger.debug('Enter home') pform = PostPushForm() post_ids=db.child('Users/{}/posts'.format(uname))\ .order_by_key().limit_to_last(3).get().val() print(post_ids) myposts = [] if post_ids: for pid in reversed(post_ids): p = db.child('Posts/{}/'.format(pid)).get().val() p["avtar_url"] = db.child('Users/{}/avtar'.format( p['author'])).get().val() myposts.append(p) print('Myposts:\n') print(myposts) return render_template('home.html', pform=pform, posts=myposts)
def help(): url = 'https://ipapi.co/json/' data = requests.get(url).json() lat = data['latitude'] lon = data['longitude'] timestamp = calendar.timegm(time.gmtime()) db.child('help').child(timestamp).set({'lat': lat, 'long': lon}) return redirect(url_for('home'))
def admin_panel(): help_data = db.child('help').get() pdna_data = db.child('pdna').get() print(help_data.val()) print(pdna_data.val()) return render_template('admin.html', help_data=help_data.val(), pdna_data=pdna_data.val())
def delete_screen(): if request.method == "POST": project_name = session.get('project_name') data = request.get_json() screen_id = data["screen_id"] print("screen_id", screen_id) db.child(project_name + "/" + screen_id).remove() return Response(response=json.dumps(data), status=200)
def close_position(): form = OpenPosition() print("close_position") if form.validate_on_submit(): print("validated") now = str(datetime.datetime.now()) userID = current_user.localId ticker = form.ticker.data dt = form.datetime_added.data quant = form.quantity.data assett = form.assett.data cost = form.cost.data start = dt - datetime.timedelta(days=5) end = dt + datetime.timedelta(days=5) data = yf.download(ticker, start=start, end=end) indexes = "^AXJO ^GSPC" index_data = yf.download(indexes, start=start, end=end) t = yf.Ticker(ticker) d = t.info if assett == '2': d['sector'] = "cryptocurrency" if assett == '3': d['sector'] = "ETF" idx = np.argmin(np.abs((data.index - dt).values.astype(float))) idx = np.argmin(np.abs((data.index - dt).values.astype(float))) idx_index = np.argmin( np.abs((index_data['Close'].dropna().index - dt).values.astype(float))) index_value = index_data['Close'].dropna().values[idx_index, :] if form.price.data is None: purch_price = data['Close'].values[idx] else: purch_price = form.price.data position = { "ticker": ticker, "open": False, "assett": assett, "name": d['shortName'], "sector": d['sector'], "market": d['market'], "currency": d["currency"], "open_price": 0, "open_quant": 0, "open_value": 0, "open_cost": 0, "date": str(dt), "close_price": purch_price, "close_quant": quant, "close_value": purch_price * quant, "close_cost": cost, "au_index": index_value[0], "us_index": index_value[1] } print(position) db.child("portfolio").child(userID).push(position, current_user.idToken) return redirect(url_for('portfolio.portfolio_view')) return render_template('open_position.html', form=form)
def sms(): global counter animal = '' incident_type = '' situation_type = '' incident_location = '' inc_id = generate_id() number = request.form['From'] message_body = request.form['Body'] resp = MessagingResponse() boolean=False if message_body.lower()=='wildsosalert' or message_body.lower()=='wildsos alert': resp.message('Hello {}, please send us the following details in this format:<Animal_Name> <Incident Type Eg. Poaching ,Human Wildlife Conflict etc> <Situation Type Eg.critical ,significant or minor > <Location>'.format(number)) counter=counter+1 elif counter==0: resp.message('Invalid input! Please send WILDSOS if you would like to report any incident.') else: l=message_body.split(' ') if len(l)>2: animal = l[0] incident_type = l[1] situation_type = l[2] incident_location = l[3] + " " + l[-1] counter=0 resp.message('Thank you! All the details have been recorded by us. We will notify the nearest officer and get back to you as soon as possible') incident_priority = calculate_priority(situation_type, incident_type) data = { "user_fname": 'anon', "user_lname": '', "user_phone": number, "user_email": '', "user_address": '', "animal": animal, "incident_id": inc_id, "incident_type": incident_type, "incident_priority": incident_priority, "situation_type": situation_type, "incident_location": incident_location, # Make one for long_lat and one for address "incident_city": '', "incident_country": '', "incident_zipcode": '', "incident_date": '', "incident_time": '', "image_url": '', "incident_description": '', "assigned_to": "No one", "incident_result": '', "source": 'SMS' } db.child("incident").push(data) else: resp.message('All details are not entered by the user and try again.') counter=0 return str(resp)
def end_call(): global call_location # Start our TwiML response resp = VoiceResponse() call_location=request.values['SpeechResult'] # Start our TwiML response resp = VoiceResponse() global call_recstr resp.say("Thanks for reporting the crime.") resp.hangup() print(resp) client = Client(account_sid, auth_token) recordings = client.recordings.list(limit=20) l=[] for record in recordings: l.append(record.sid) rec = l[0] call_recstr = 'https://api.twilio.com/2010-04-01/Accounts/ACfa7fe832b6a75655a5ec2bcde267f231/Recordings/' + str(rec) + '.mp3' inc_id = generate_id() incident_priority = calculate_priority(call_situation_type, call_incident_type) print(call_incident_type) print(incident_priority) print(call_situation_type) print(call_location) data = { "user_fname": 'anon', "user_lname": '', "user_phone": '', "user_email": '', "user_address": '', "animal": '', "incident_id": inc_id, "incident_type": call_incident_type, "incident_priority": incident_priority, "situation_type": call_situation_type, "incident_location": call_location, # Make one for long_lat and one for address "incident_city": '', "incident_country": '', "incident_zipcode": '', "incident_date": '', "incident_time": '', "image_url": '', "incident_description": '', "assigned_to": "No one", "incident_result": '' , "recording": call_recstr, "source": 'Phone Call' } db.child("incident").push(data) return str(resp)
def update_log_cursor(): if request.method == "POST": project_name = session.get('project_name') data = request.get_json() screen_id = data["screen_id"] log_id = data["log_id"] x = data["x"] y = data["y"] log_cursor = {"x": x, "y": y} db.child(project_name + "/" + screen_id + "/log/" + log_id + "/log_cursor").set(log_cursor) return Response(response=json.dumps(log_cursor), status=200)
def search(): keywords = list(map(str.lower, request.args.get("keyword").split(" "))) ref = f"{db_name}/index" mapping = {kw: {} for kw in keywords} entrys = set() for kw in keywords: items = db.child(ref).child(kw).get().val() if not items: return jsonify([]) for item in items: tmp = item["table"] + "/" + item["pk"] entrys.add(tmp) mapping[kw.lower()][tmp] = True result = [] for entry in entrys: weight = 0 for kw in keywords: weight += 1 if entry in mapping[kw] else 0 table, pk = entry.split("/") link = f"/api/{entry}.json" result.append({"table": table, "pk": pk, "_link": link, "weight": weight}) result = sorted(result, key=lambda d: d["weight"], reverse=True) return jsonify(result)
def notifications(): incident_data = db.child('incident').get() incident_data = incident_data.val() keys_list = list(incident_data.keys()) print(keys_list) return render_template('layouts/default.html', content=render_template( 'pages/notifications.html', incident_data = incident_data, keys_list = keys_list) )
def get_statisic_list(): ref = f"{db_name}/{date}" pagination = Pagination(ref, **request.args)() items = (db.child(ref).order_by_key().start_at( pagination.start).limit_to_first(pagination.page_size).get()) last = next(reversed(items.val())) response = ResultSet(items.val(), pagination, last).response() return response
def signup(): app.logger.debug('Enter signup function') sform = SignUpForm() if sform.validate_on_submit(): print('valid signup form') username = sform.username.data email = sform.email.data password = sform.password.data repeatpassword = sform.repeatpassword.data f = sform.avtar.data if password == repeatpassword: # cache file print('cache file') filename = secure_filename(f.filename) filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) f.save(filepath) # upload avtar print('upload avtar') storage.child("Avtars/{}".format(username)).put(filepath) avtar_url = storage.child( "Avtars/{}".format(username)).get_url(None) # create user print('create user') fuser = auth.create_user_with_email_and_password(email, password) #avtar_url=storage.child("Avtar/defaultAvtar.jpg").get_url(None) put_data = { 'password': password, 'email': email, 'username': username, 'id': fuser['idToken'], 'posts': {}, 'avtar': avtar_url } db.child('Users').child(username).set(put_data) app.logger.debug('Sign up {} success... '.format(username)) return redirect('home') for e in sform.errors: print(e) return redirect('account')
def feed(): if "userToken" not in session: return redirect(url_for('account')) username = session['username'] post_ids = db.child('Posts/').order_by_key().limit_to_last(6).get() print(post_ids) print(post_ids.val()) feedposts = [] if post_ids: for pid in post_ids.each(): p = pid.val() if p['author'] == username: continue p["avtar_url"] = db.child('Users/{}/avtar'.format( p['author'])).get().val() feedposts.append(p) if len(feedposts): feedposts.reverse() return render_template('feed.html', posts=feedposts)
def submit_survey(): survey_result = { 'q1': request.form.get('question-0'), 'q2': request.form.get('question-1'), 'q3': request.form.get('question-2'), 'q4': request.form.get('question-3'), 'q5': request.form.get('question-4'), 'q6': request.form.get('question-5'), 'q7': request.form.get('question-6'), 'q8': request.form.get('question-7'), 'q9': request.form.get('question-8'), 'q10': request.form.get('question-9'), 'q11': request.form.get('question-10'), 'q12': request.form.get('question-11'), 'q13': request.form.get('question-12'), 'q14': request.form.get('question-13'), 'q15': request.form.get('question-14'), } timestamp = calendar.timegm(time.gmtime()) db.child('pdna').child(timestamp).set(survey_result) return redirect(url_for('home'))
def upload(): #check session project_name = session.get('project_name') print("project_name", project_name) if project_name in beta_project: pass else: flash("現在テストユーザーしか使えません") return redirect(url_for('project')) if request.method == "POST": print("check") if request.form: data = request.form screen_id = str(uuid.uuid4()) screen_name = data["screen_name"] screen_category = data["screen_category"] image = request.files["screen_image_name"] image.filename = screen_id log = [] d = datetime.datetime.now() created_at = json.dumps({"unixtime": d.timestamp()}) screen = { "screen_id": screen_id, "screen_name": screen_name, "screen_category": screen_category, "created_at": created_at, "log": [] } db.child(project_name + "/" + screen_id).set(screen) storage.child("image/" + screen_id).put(image) flash("新しいスクリーンが追加されました") return render_template("upload.html")
def pushpost(): pform = PostPushForm() app.logger.debug('Pushpost request') if pform.validate_on_submit(): username = session['username'] # recieve post app.logger.debug('Valid post push') context = pform.context.data print('get context:\n{}'.format(context)) f = pform.photo.data filename = secure_filename(f.filename) print('get filename:\n{}'.format(filename)) filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) f.save(filepath ) # TODO either implement my put or delete file after upload #push post new_post = { 'pic_url': "", 'context': context, 'author': username, 'liker': {}, 'time': datetime.now().strftime('%Y-%m-%d %H:%M') } post_id = db.child('Posts/').push(new_post) storage.child("Posts/{}".format(post_id['name'])).put(filepath) pic_url = storage.child("Posts/{}".format( post_id['name'])).get_url(None) db.child('Posts/{}'.format(post_id['name'])).update( {"pic_url": pic_url}) db.child('Users/{}/posts/{}'.format(username, post_id['name'])).set(True) return redirect(url_for('home'))
def get_train(id): return jsonify(db.child(db_name).child(train).child(id).get().val())
from flask import Flask, request, jsonify from firebase_admin import credentials, firestore, initialize_app from flask import Blueprint, request, render_template, \ flash, g, session, redirect, url_for from app.mod_admin.forms import UserForm import os from .. import app from app import db, auth # db = firestore.client() # OLD WAY # db = firebase.database() # user_ref = db.collection('users') # OLD WAY user_ref = db.child("users") mod_admin = Blueprint('admin', __name__, url_prefix='/admin') @mod_admin.route('/', methods=['GET', 'POST']) def admin_index(): return render_template("admin/index.html") @mod_admin.route('/users', methods=['GET', 'POST']) def admin_users(): form = UserForm(request.form) if form.validate_on_submit(): print(form) my_id = form.id.data
def get_station(id): return jsonify(db.child(db_name).child(station).child(id).get().val())
def get_countrylanguage(id): return jsonify(db.child(db_name).child(countrylanguage).child(id).get().val())
def get_city(id): return jsonify(db.child(db_name).child(city).child(id).get().val())
def get_area(id): return jsonify(db.child(db_name).child(area).child(id).get().val())
def get_daily_release(id): return jsonify(db.child(db_name).child(daily).child(id).get().val())
def screen(): #check session project_name = session.get('project_name') if project_name in beta_project: pass else: flash("現在テストユーザーしか使えません") return redirect(url_for('project')) searchbar = request.args.get('searchbar', '') if searchbar == "": try: data = db.child(project_name).get() if data.each() is None: render_all_screen_sorted = "" else: render_all_screens = [] for screen in data.each(): render_screen = { "screen_id": screen.val()["screen_id"], "screen_name": screen.val()["screen_name"], "created_at": screen.val()["created_at"], "screen_image_name": storage.child("image/" + screen.val()["screen_id"]).get_url(None) } render_all_screens.append(render_screen) render_all_screen_sorted = sorted( render_all_screens, key=lambda x: x['created_at'], reverse=True) except ConnectionError: abort(404) flash("Unexpected error contact Yuki") else: print(searchbar) try: data = db.child(project_name).get() if data.each() is None: render_all_screen_sorted = "" else: render_all_screens = [] for screen in data.each(): if re.search(searchbar, screen.val()["screen_name"], re.IGNORECASE): render_screen = { "screen_id": screen.val()["screen_id"], "screen_name": screen.val()["screen_name"], "created_at": screen.val()["created_at"], "screen_image_name": storage.child("image/" + screen.val()["screen_id"]).get_url( None) } render_all_screens.append(render_screen) render_all_screen_sorted = sorted( render_all_screens, key=lambda x: x['created_at'], reverse=True) except ConnectionError: abort(404) flash("Unexpected error contact Yuki") return render_template("screen.html", screens=render_all_screen_sorted)
def get_prov(id): return jsonify(db.child(db_name).child(prov).child(id).get().val())
def portfolio_view(): userID = current_user.localId # retrieve portfolio object transactions = db.child("portfolio").child(userID).get( current_user.idToken) transactions = transactions.val() portfolio, tickers, update, totals = None, None, None, None m_dict_long, m_dict_short = None, None if transactions is not None: # convert to list of objects/transactions trans_list = [] for key in transactions: trans_list.append(transactions[key]) # sort list by opening date trans_list.sort( key=lambda x: datetime.datetime.fromisoformat(x['date']), reverse=False) tickers = list(set([d['ticker'] for d in trans_list])) # combine multiple transactions/tickers into one portfolio item portfolio = [] closed = [] for t in tickers: subset = [d for d in trans_list if d['ticker'] == t] if len(subset) == 1: portfolio.append(subset[0]) else: avg_price = 0 cum_quant = 0 open_us_idx = 0 open_au_idx = 0 total_take = 0 date = "replace" for doc in subset: if doc['open']: value = doc['open_quant'] * doc['open_price'] cum_value = (avg_price * cum_quant) + value us_index_value = doc['open_quant'] * doc['us_index'] au_index_value = doc['open_quant'] * doc['au_index'] cum_us_index_value = (open_us_idx * cum_quant) + us_index_value cum_au_index_value = (open_au_idx * cum_quant) + au_index_value cum_quant += doc['open_quant'] avg_price = value / cum_quant open_us_idx = cum_us_index_value / cum_quant open_au_idx = cum_au_index_value / cum_quant date = str(doc['date']) else: take = (doc['close_quant'] * doc['close_price'])\ - (avg_price * doc['close_quant']) cum_quant -= doc['close_quant'] closed_pozzy = { "ticker": t, "assett": subset[0]["assett"], "name": subset[0]["name"], "sector": subset[0]["sector"], "market": subset[0]["market"], "currency": subset[0]["currency"], "date": str(doc['date']), "open_price": avg_price, "open_quant": cum_quant, "open_value": avg_price * doc['close_quant'], "close_price": doc['close_price'], "close_quant": doc['close_quant'], "close_value": doc['close_quant'] * doc['close_price'], "au_index": open_au_idx, "us_index": open_us_idx, "take": take } closed.append(closed_pozzy) if cum_quant > 0: position = { "ticker": t, "open": True, "assett": subset[0]["assett"], "name": subset[0]["name"], "sector": subset[0]["sector"], "market": subset[0]["market"], "currency": subset[0]["currency"], "date": date, "open_price": avg_price, "open_quant": cum_quant, "open_value": avg_price * cum_quant, "close_price": 0, "close_quant": 0, "close_value": 0, "au_index": open_au_idx, "us_index": open_us_idx } portfolio.append(position) # find most recent price for each item tickers_string = ' '.join(tickers) start_long = datetime.datetime.now() - datetime.timedelta(days=180) start_short = datetime.datetime.now() - datetime.timedelta(days=14) data_long = yf.download(tickers_string, start=start_long) data_short = yf.download(tickers_string, start=start_short, interval='15m') indexes = "^AXJO ^GSPC" index_data = yf.download(indexes, start=start_long) m_dict_long, _ = metrics(data_long['Close']) m_dict_short, _ = metrics(data_short['Close']) update = {} tickers = [d['ticker'] for d in portfolio] for t in tickers: subset = [d for d in portfolio if d['ticker'] == t] data_source = data_short if len(tickers) > 1: cv = data_source['Close'][t].dropna().values[-1], update[t] = { "close_price": cv[0], "open_quant": subset[0]["open_quant"], "volume": data_source['Volume'][t].dropna().values[-1], "close_value": cv[0] * subset[0]["open_quant"], "market": subset[0]["market"], "sector": subset[0]["sector"], "assett": subset[0]["assett"], "au_index": index_data['Close']["^AXJO"].dropna().values[-1], "us_index": index_data['Close']["^GSPC"].dropna().values[-1] } else: cv = data_source['Close'].dropna().values[-1], update[t] = { "close_price": cv[0], "volume": data_source['Volume'].dropna().values[-1], "close_value": cv * subset[0]["open_quant"], "market": subset[0]["market"], "sector": subset[0]["sector"], "assett": subset[0]["assett"], "au_index": index_data['Close']["^AXJO"].dropna().values[-1], "us_index": index_data['Close']["^GSPC"].dropna().values[-1] } # work out sector totals by market and assett # aus equity totals = {} totals["aus_equity_open"] = np.sum([ d["open_value"] for d in portfolio if (d["assett"] == "1") and (d["market"] == "au_market") ]) totals["aus_equity_close"] = np.sum([ update[key]["close_value"] for key in update if (update[key]["assett"] == "1") and ( update[key]["market"] == "au_market") ]) totals["us_equity_open"] = np.sum([ d["open_value"] for d in portfolio if (d["assett"] == "1") and (d["market"] == "us_market") ]) totals["us_equity_close"] = np.sum([ update[key]["close_value"] for key in update if (update[key]["assett"] == "1") and ( update[key]["market"] == "us_market") ]) totals["aus_etf_open"] = np.sum([ d["open_value"] for d in portfolio if (d["assett"] == "3") and (d["market"] == "au_market") ]) totals["aus_etf_close"] = np.sum([ update[key]["close_value"] for key in update if (update[key]["assett"] == "3") and ( update[key]["market"] == "au_market") ]) totals["us_etf_open"] = np.sum([ d["open_value"] for d in portfolio if (d["assett"] == "3") and (d["market"] == "us_market") ]) totals["us_etf_close"] = np.sum([ update[key]["close_value"] for key in update if (update[key]["assett"] == "3") and ( update[key]["market"] == "us_market") ]) totals["crypto_open"] = np.sum( [d["open_value"] for d in portfolio if (d["assett"] == "2")]) totals["crypto_close"] = np.sum([ update[key]["close_value"] for key in update if (update[key]["assett"] == "2") ]) # get transaction deletion input if request.method == 'POST': for key in request.form: if request.form[key] == "delete": db.child("portfolio").child(userID).child(key)\ .remove(current_user.idToken) return redirect(url_for('portfolio.portfolio_view')) portfolio.sort( key=lambda d: update[d["ticker"]]["close_value"] / d["open_value"], reverse=True) tickers = [d['ticker'] for d in portfolio] # print(transactions) # print(tickers) return render_template('portfolio.html', transactions=transactions, portfolio=portfolio, tickers=tickers, update=update, totals=totals, closed=closed, metrics_long=m_dict_long, metrics_short=m_dict_short)
def get_statisc(id): return jsonify(db.child(db_name).child(date).child(id).get().val())
def _get_pages(self, ref): # Firebase returns unordered resultset return sorted(list(db.child(ref).shallow().get().val()))
def log(screen_id): #no check session project_name = session.get('project_name') if project_name is None: return redirect(url_for('signin', screen_id=screen_id)) # check if other screen if screen_id == "project": return redirect(url_for('project')) elif screen_id == "screen": return redirect(url_for('screen')) elif screen_id == "upload": return redirect(url_for('upload')) if request.method == "POST": data = request.get_json() screen_id = data.pop("screen_id") d = datetime.datetime.now() data["created_at"] = json.dumps({"unixtime": d.timestamp()}) db.child(project_name + "/" + screen_id + "/log").push(data) return Response(response=json.dumps(data), status=200) #redirect(request.url) render_logs = [] data = db.child(project_name + "/" + screen_id + "/log").get().val() if data is None: logs = [] else: logs = db.child(project_name + "/" + screen_id + "/log").get() for log in logs.each(): key = log.key() val = log.val() val["log_id"] = key if "log_cursor" not in val: val["log_cursor"] = {"x": 430, "y": 150} render_logs.append(val) image = storage.child("image/" + screen_id).get_url(None) render_logs_sorted = sorted(render_logs, key=lambda x: x['created_at']) count = 0 render_logs_sorted_with_id = [] for log in render_logs_sorted: count = count + 1 log["log_num"] = count render_logs_sorted_with_id.append(log) #get screen name and add it to the log screen_data = db.child(project_name + "/" + screen_id).get().val() if screen_data is None: flash("You jumped into a different project please sign in again") session.pop('project_name', None) return redirect(url_for('project')) screen_name = screen_data["screen_name"] return render_template('log.html', logs=render_logs_sorted_with_id, image=image, screen_id=screen_id, screen_name=screen_name)