Skip to content

Commit

Permalink
Added stylesheet, adduser page and able to show user behaviour loggin…
Browse files Browse the repository at this point in the history
…g in profile page
  • Loading branch information
susravan committed Sep 7, 2017
1 parent a2b1aec commit 37f0e92
Show file tree
Hide file tree
Showing 10 changed files with 393 additions and 116 deletions.
98 changes: 49 additions & 49 deletions Page-tracking-extension/content.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,36 @@

// Get number of votes, answers and views for each question
var question_summary = $(".question-summary")
var question_stats_arr = []

// Get to know clearly about the html parsering using javascript

for (var i=0; i < question_summary.length-13; i++) {
question_stats = {
"object_id": question_summary.get(i).id.split('-')[2],
"votes": question_summary[i].getElementsByClassName("vote-count-post")[0].childNodes[0].innerHTML,
"answers": question_summary[i].getElementsByClassName("status answered-accepted")[0].childNodes[1].innerHTML,
"views": question_summary[i].getElementsByClassName("views supernova")[0].innerHTML.trim().split(' ')[0]
};
question_stats_arr.push(question_stats);
}


// Logging time spent on a page
$(document).ready(function() {
var ques_id = document.URL.split('/')[4];
var user_id = "dummy";

var start = new Date().getTime();
var start;
var end;
var time_spent;

window.addEventListener('focus', function() {
start = Date.now();
});

console.log("start = ", start)

$(window).on('blur', function() {
end = new Date().getTime();
});

$(window).on('unload', function() {
end = new Date().getTime();
});
console.log("end = ", end);

var time_spent = parseInt(end - start)
console.log(time_spent)
time_spent = end - start;
console.log(time_spent/1000)

var evtData = {
"userId": user_id,
"evt_type": "Time Spent",
"pageHTML": document.URL,
"object_id": 0,
"evt_datetime": time_spent
"evt_datetime": (time_spent/1000).toString()
};

console.log(evtData);
// console.log(evtData);

// Sending data to background.js
chrome.runtime.sendMessage({'evtData': evtData, 'quesData': null}, function(response) {
Expand All @@ -52,25 +43,17 @@ $(document).ready(function() {
$(document).ready(function(evt) {
var ques_id = document.URL.split('/')[4];
var user_id = "dummy";

// console.log($(".subheader.answers-subheader"));
// console.log($(".subheader.answers-subheader")[0]);
// console.log($(".subheader.answers-subheader")[0].childNodes);
// console.log($(".subheader.answers-subheader")[0].childNodes[1]);
// console.log($(".subheader.answers-subheader")[0].childNodes[1].childNodes[1].innerHTML);

// console.log($(".subheader.answers-subheader"));
// console.log($(".subheader.answers-subheader").eq(0));
// console.log($(".subheader.answers-subheader").eq(0).children('h2').eq(0).children('span').eq(0));
// console.log($(".subheader.answers-subheader")[0].childNodes[1]);
// console.log($(".subheader.answers-subheader")[0].childNodes[1].childNodes[1].innerHTML);

var today = new Date();
var date = (today.getMonth() + 1) + '-' + (today.getDate()) + '-' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

var evtData = {
"userId": user_id,
"evt_type": "Visit",
"evt_type": "Visited",
"pageHTML": document.URL,
"object_id": ques_id,
"evt_datetime": Date.now()
"evt_datetime": date + ' ' + time
};

var tagListChildren = document.getElementsByClassName("post-taglist")[0].children;
Expand Down Expand Up @@ -105,17 +88,20 @@ $(document).ready(function(evt) {

// Post answer tracking
$('#submit-button').on('click', function() {
setTimeout(function() {}, 500);

var ques_id = document.URL.split('/')[4];
var user_id = "dummy";

var today = new Date();
var date = (today.getMonth() + 1) + '-' + (today.getDate()) + '-' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

var evtData = {
"userId": user_id,
"evt_type": "Post Answer",
"evt_type": "Posted Answer to",
"pageHTML": document.URL,
"object_id": ques_id,
"evt_datetime": Date.now()
"evt_datetime": date + ' ' + time
};

var tagListChildren = document.getElementsByClassName("post-taglist")[0].children;
Expand Down Expand Up @@ -169,12 +155,16 @@ $('.short-link').eq(0).on('click', function() {
var ques_id = document.URL.split('/')[4];
var user_id = "dummy";

var today = new Date();
var date = (today.getMonth() + 1) + '-' + (today.getDate()) + '-' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

var evtData = {
"userId": user_id,
"evt_type": "Share Question",
"evt_type": "Shared Question",
"pageHTML": document.URL,
"object_id": ques_id,
"evt_datetime": Date.now()
"evt_datetime": date + ' ' + time
};

// Question details
Expand Down Expand Up @@ -212,13 +202,18 @@ $(".vote-up-off").on('click', function() {
var ques_id = document.URL.split('/')[4];
var user_id = "dummy";

var today = new Date();
var date = (today.getMonth() + 1) + '-' + (today.getDate()) + '-' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

var evtData = {
"userId": user_id,
"evt_type": "UpVote",
"evt_type": "UpVoted",
"pageHTML": document.URL,
"object_id": this.previousElementSibling.getAttribute('value'),
"evt_datetime": Date.now()
"evt_datetime": date + ' ' + time
};

console.log(evtData);
// Sending data to background.js
chrome.runtime.sendMessage({'evtData': evtData, 'quesData': null}, function(response) {
Expand All @@ -232,13 +227,18 @@ $(".vote-down-off").on('click', function() {
var ques_id = document.URL.split('/')[4];
var user_id = "dummy";

var today = new Date();
var date = (today.getMonth() + 1) + '-' + (today.getDate()) + '-' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

var evtData = {
"userId": user_id,
"evt_type": "DownVote",
"evt_type": "DownVoted",
"pageHTML": document.URL,
"object_id": this.previousElementSibling.previousElementSibling.previousElementSibling.getAttribute('value'),
"evt_datetime": Date.now()
"evt_datetime": date + ' ' + time
};

console.log(evtData);
// Sending data to background.js
chrome.runtime.sendMessage({'evtData': evtData, 'quesData': null}, function(response) {
Expand Down
Binary file modified UserTracking.db
Binary file not shown.
100 changes: 76 additions & 24 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
from flask import Flask, request, render_template, redirect,\
url_for, session, flash
url_for, session, flash, jsonify
from flask_sqlalchemy import SQLAlchemy
from functools import wraps
from flask_cors import CORS
import simplejson as json
import sqlite3 as sql
import datetime as dt
import time
import os


app = Flask(__name__)
CORS(app)
Expand Down Expand Up @@ -32,17 +36,83 @@ def wrap(*args, **kwargs):
@app.route('/') #Main URL
@login_required
def home():
# posts = db.session.query(BlogPost).all()
print "At homepage"
return render_template("index.html", posts=[]) # Reder a template
userDetails = []

with sql.connect("UserTracking.db") as connection:
print "inside db connection"
c = connection.cursor()
c.execute('SELECT evt_type, pageHTML, evt_datetime FROM UserActions where userId = "dummy" and evt_datetime != "NaN" ')
userDetails = c.fetchall()

posts = []
for info in userDetails:

post = info[0] + " --> " + info[1] + " --> " + info[2]
# print post
posts.append(post)

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


# By default, flask assumes GET method
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None

if request.method == 'POST':
if request.form['username'] != "admin" or request.form['password'] != "admin":
error = "Invalid credentials. Please try again"
else:
loginStartTime = time.time()
print "curr time = ", str(loginStartTime)

session['logged_in'] = True
with sql.connect("UserTracking.db") as connection:
c = connection.cursor()
c.execute('SELECT * FROM UserActions where userId = "admin"')
loginInfo = c.fetchall()

print "from login", request.form['username']
return redirect(url_for('home', userId=request.form['username']))

return render_template("login.html", error=error)


@app.route('/adduser', methods=['GET', 'POST'])
def adduser():
info = None

# Post request
if request.method == 'POST':

if request.form['username'] == "" or request.form['password'] == "":
info = "Login credentials cannot be empty"
else:
loginStartTime = dt.datetime.now()
print str(loginStartTime)

# session['logged_in'] = True
with sql.connect("UserTracking.db") as connection:
c = connection.cursor()
c.execute('INSERT INTO UserDetails VALUES(?,?)', [request.form['username'], request.form['password']])
loginInfo = c.fetchall()

info = "User created"
print info
print loginInfo
return render_template("adduser.html", info=info)

# Get request
else:
return render_template("adduser.html")


@app.route('/TrackingData', methods=["POST"])
def TrackingData():
req_json = request.get_json()
evtData = req_json['evtData']
quesData = req_json['quesData']
print evtData
# print evtData

with sql.connect("UserTracking.db") as connection:
c = connection.cursor()
Expand All @@ -58,32 +128,14 @@ def TrackingData():
return ""


@app.route('/welcome') #Main URL
def welcome():
return render_template("welcome.html")


# By default, flask assumes GET method
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != "admin" or request.form['password'] != "admin":
error = "Invalid credentials. Please try again"
else:
session['logged_in'] = True
flash("You just logged in")
return redirect(url_for('home'))

return render_template("login.html", error=error)


@app.route('/logout')
@login_required
def logout():
session.pop('logged_in', None)
flash("You just logged out")
return redirect(url_for('welcome'))
return redirect(url_for('login'))


if __name__ == '__main__':
Expand Down
10 changes: 8 additions & 2 deletions sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@
c.execute("CREATE TABLE UserActions(userId TEXT, evt_type TEXT, pageHTML TEXT, object_id INT, evt_datetime TEXT)")
# c.execute("DROP TABLE ObjectDetails")
c.execute("CREATE TABLE ObjectDetails(object_type TEXT, object_id INT, pageHTML TEXT, votes INT, answers INT, views INT, create_datetime TEXT, tags TEXT)")
# c.execute("DROP TABLE UserHistory")
c.execute("CREATE TABLE UserHistory(userId TEXT, loginDataTime TEXT, logoutDateTime)")
# c.execute("DROP TABLE UserDetails")
c.execute("CREATE TABLE UserDetails(userId TEXT, password TEXT)")



# c.execute("INSERT INTO UserDetails VALUES ('sss', 'qqq')")
# c.execute("INSERT INTO UserDetails VALUES ('aaa', 'bbb')")
# c.execute("INSERT INTO UserDetails VALUES ('ccc', 'ddd')")


Loading

0 comments on commit 37f0e92

Please sign in to comment.