Skip to content

Commit

Permalink
fixed date issue
Browse files Browse the repository at this point in the history
  • Loading branch information
techwithtim committed Feb 5, 2020
1 parent e5941ff commit b88647c
Show file tree
Hide file tree
Showing 17 changed files with 140 additions and 73 deletions.
3 changes: 0 additions & 3 deletions .env

This file was deleted.

Binary file removed server/__pycache__/person.cpython-37.pyc
Binary file not shown.
4 changes: 4 additions & 0 deletions website/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
TESTING=False
DEBUG=True
SECRET_KEY=youwontguessthiskey
SERVER=0.0.0.0
Binary file added website/__pycache__/config.cpython-37.pyc
Binary file not shown.
3 changes: 1 addition & 2 deletions website/application/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from flask import Flask
from os import environ


def create_app():
"""Construct the core application."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object('config.Config')
app.secret_key = "no"


with app.app_context():
# Imports
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
2 changes: 1 addition & 1 deletion website/application/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,6 @@ def save_message(self, name, msg):
:return: None
"""
query = f"INSERT INTO {PLAYLIST_TABLE} VALUES (?, ?, ?, ?)"
self.cursor.execute(query, (name, msg,datetime.now(), None))
self.cursor.execute(query, (name, msg, datetime.now(), None))
self.conn.commit()

145 changes: 104 additions & 41 deletions website/application/static/index.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,77 @@
$(function()
{
$('#messages') .css({'height': (($(window).height()) * 0.8)+'px'});

$(window).bind('resize', function(){
$('#messages') .css({'height': (($(window).height()) - 200)+'px'});
});
});

function scrollSmoothToBottom (id) {
var div = document.getElementById(id);
$('#' + id).animate({
scrollTop: div.scrollHeight - div.clientHeight
}, 500);
}

async function load_name(){
return await fetch('/get_name')
.then(async function (response) {
return await response.json();
}).then(function (text) {
return text["name"]
});
return await fetch('/get_name')
.then(async function (response) {
return await response.json();
}).then(function (text) {
return text["name"]
});
};

async function load_messages() {
return await fetch('/get_messages')
.then(async function (response) {
return await response.json();
}).then(function (text) {
console.log(text)
return text
});
return await fetch('/get_messages')
.then(async function (response) {
return await response.json();
}).then(function (text) {
console.log(text)
return text
});
}

function dateNow() {
var date = new Date();
var aaaa = date.getFullYear();
var gg = date.getDate();
var mm = (date.getMonth() + 1);

if (gg < 10)
gg = "0" + gg;

if (mm < 10)
mm = "0" + mm;

var cur_day = aaaa + "-" + mm + "-" + gg;

var hours = date.getHours()
var minutes = date.getMinutes()
var seconds = date.getSeconds();

if (hours < 10)
hours = "0" + hours;

if (minutes < 10)
minutes = "0" + minutes;

if (seconds < 10)
seconds = "0" + seconds;

return cur_day + " " + hours + ":" + minutes;
}

var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on( 'connect', function() {
socket.emit( 'event', {
data: 'User Connected'
} )
socket.on( 'connect', async function() {
var usr_name = await load_name()
if (usr_name != ""){
socket.emit( 'event', {
message: usr_name + ' just connected to the server!',
connect: true
} )
}
var form = $( 'form#msgForm' ).on( 'submit', async function( e ) {
e.preventDefault()

Expand All @@ -40,35 +90,48 @@ var socket = io.connect('http://' + document.domain + ':' + location.port);
} )
} )
} )
socket.on( 'disconnect', async function( msg ) {
var usr_name = await load_name()
socket.emit( 'event', {
message: usr_name + ' just left the server...',
name: usr_name
} )
})
socket.on( 'message response', function( msg ) {
add_messages(msg)
add_messages(msg, true)
})

window.onload = async function() {
var msgs = await load_messages()
for (msg of msgs){
add_messages(msg)
}
var msgs = await load_messages()
for (i = 0; i < msgs.length; i++){
scroll = false
if (i == msgs.length-1) {scroll = true}
add_messages(msgs[i], scroll)
}

}

async function add_messages(msg){
if( typeof msg.name !== 'undefined' ) {
var arr = " yyyy-mm-dd hh:mm:ss".split(/-|\s|:/);// split string and create array.
var date = new Date(arr[0], arr[1] -1, arr[2], arr[3], arr[4], arr[5]);

if ( typeof msg.time !== "undefined") {
var n = msg.time
}else{
var n = date
}
var global_name = await load_name()

var content = '<div class="container">' + '<b style="color:#000" class="right">'+msg.name+'</b><p>' + msg.message +'</p><span class="time-right">' + n + '</span></div>'
if (global_name == msg.name){
content = '<div class="container darker">' + '<b style="color:#000" class="left">'+msg.name+'</b><p>' + msg.message +'</p><span class="time-left">' + n + '</span></div>'
}
// update div
var messageDiv = document.getElementById("messages")
messageDiv.innerHTML += content
async function add_messages(msg, scroll){
if( typeof msg.name !== 'undefined' ) {
var date = dateNow()

if ( typeof msg.time !== "undefined") {
var n = msg.time
}else{
var n = date
}
var global_name = await load_name()

var content = '<div class="container">' + '<b style="color:#000" class="right">'+msg.name+'</b><p>' + msg.message +'</p><span class="time-right">' + n + '</span></div>'
if (global_name == msg.name){
content = '<div class="container darker">' + '<b style="color:#000" class="left">'+msg.name+'</b><p>' + msg.message +'</p><span class="time-left">' + n + '</span></div>'
}
// update div
var messageDiv = document.getElementById("messages")
messageDiv.innerHTML += content
}

if (scroll){
scrollSmoothToBottom("messages");
}
}
17 changes: 15 additions & 2 deletions website/application/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

# GLOBAL CONSTANTS
NAME_KEY = 'name'
MSG_LIMIT = 5
MSG_LIMIT = 20

# GLOBAL VARS
client = None
Expand Down Expand Up @@ -75,4 +75,17 @@ def get_messages():
"""
db = DataBase()
msgs = db.get_all_messages(MSG_LIMIT)
return jsonify(msgs)
messages = []
for msg in msgs:
message = msg
message["time"] = remove_seconds(message["time"])
messages.append(message)

return jsonify(msgs)


def remove_seconds(msg):
"""
removes the seconds off of a date time string
"""
return msg.split(".")[0][:-3]
Binary file removed website/client/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file removed website/client/__pycache__/client.cpython-37.pyc
Binary file not shown.
17 changes: 12 additions & 5 deletions website/config.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
from os import environ
from dotenv import load_dotenv
from pathlib import Path # python3 only
import os

# load enviornment variables
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)


class Config:
"""Set Flask configuration vars from .env file."""

# General
TESTING = environ.get('TESTING')
FLASK_DEBUG = environ.get('FLASK_DEBUG')
SECRET_KEY = environ.get('SECRET_KEY')
# Load in enviornemnt variables
TESTING = os.getenv('TESTING')
FLASK_DEBUG = os.getenv('FLASK_DEBUG')
SECRET_KEY = os.getenv('SECRET_KEY')
SERVER = os.getenv('SERVER')
22 changes: 3 additions & 19 deletions website/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import time
from application import create_app
from application.database import DataBase
import config

# setup flask application
app = create_app()
Expand All @@ -24,27 +25,10 @@ def handle_my_custom_event(json, methods=['GET', 'POST']):
if "name" in data:
db = DataBase()
db.save_message(data["name"], data["message"])
socketio.emit('message response', json)


'''
@socketio.on('join')
def on_join(data):
username = data['username']
room = data['room']
join_room(room)
send(username + ' has entered the room.', room=room)

@socketio.on('leave')
def on_leave(data):
username = data['username']
room = data['room']
leave_room(room)
send(username + ' has left the room.', room=room)
'''
socketio.emit('message response', json)

# MAINLINE

if __name__ == "__main__":
socketio.run(app, debug=True, host="192.168.0.21")
socketio.run(app, debug=True, host=str(config.Config.SERVER))
Binary file added website/messages.db
Binary file not shown.

0 comments on commit b88647c

Please sign in to comment.