Skip to content

Commit

Permalink
publish functionality #24
Browse files Browse the repository at this point in the history
  • Loading branch information
mondoboia committed Jul 27, 2022
1 parent 49842cb commit 0354c61
Show file tree
Hide file tree
Showing 5 changed files with 153 additions and 97 deletions.
19 changes: 18 additions & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,26 @@ def datastory(section_name, datastory_name):
section_name, datastory_name, 'config.json')
template_mode = datastory_data['template_mode']
if datastory_data:
return render_template('datastory_'+template_mode+'.html', datastory_data=datastory_data, general_data=general_data)
return render_template('datastory_'+template_mode+'.html', datastory_data=datastory_data, general_data=general_data, section_name=section_name, datastory_name=datastory_name)
else:
return render_template('page-404.html')
elif request.method == 'POST':
r = requests.get('http://localhost:5000/'+section_name +
'/'+datastory_name)
# open and create html file
data_methods.create_html(r, datastory_name, section_name)

# commit json and html to repo
github_sync.push('static/temp/config_'+section_name+'.json', branch='main', gituser='melodyeditor',
email='[email protected]', bearer_token=conf.melody_token, action='')
github_sync.push('static/temp/'+datastory_name+'_'+section_name+'.html', branch='main', gituser='melodyeditor',
email='[email protected]', bearer_token=conf.melody_token, action='')

# remove both files
os.remove('static/temp/config_'+section_name+'.json')
os.remove('static/temp/'+datastory_name+'_'+section_name+'.html')

return redirect('https://github.com/melody-data/stories')


@app.route("/setup", methods=['POST', 'GET'])
Expand Down
17 changes: 17 additions & 0 deletions data_methods.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
from flask import request
from datetime import datetime
import requests


def read_json(file_name):
Expand Down Expand Up @@ -133,3 +134,19 @@ def manage_datastory_data(general_data, file, section_name):
update_json(file, general_data)
datastory_name = datastory_title.lower().replace(" ", "_")
return (datastory_name)


def create_html(r, datastory_name, section_name):
'''
This function creates an html file out of a data story data.
Args:
r: the requested html page.
datastory_name (str): a string that identifies the data story name.
section_name (str): a string that identify the name of the section.
'''
html = r.text.replace('/static', 'static') # replace
temp_html_file = open('static/temp/'+datastory_name+'_'+section_name+'.html', 'w')
# print(temp_html_file)
temp_html_file.write(html)
temp_html_file.close()
69 changes: 39 additions & 30 deletions github_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,36 +59,45 @@ def get_github_users(userlogin):


def push(local_file_path, branch='main', gituser=None, email=None, bearer_token=None, action=''):
""" create a new file or update an existing file.
the remote file has the same relative path of the local one"""
token = conf.token if bearer_token is None else bearer_token
user = conf.author if gituser is None else gituser
usermail = conf.author_email if email is None else email
owner = conf.owner
repo_name = conf.repo_name
g = Github(token)
repo = g.get_repo(owner+"/"+repo_name)
author = InputGitAuthor(user,usermail) # commit author

try:
contents = repo.get_contents(local_file_path) # Retrieve the online file to get its SHA and path
update=True
message = "updated file "+local_file_path+' '+action
except:
update=False
message = "created file "+local_file_path

with open(local_file_path) as f: # Both create/update file replace the file with the local one
data = f.read() # could be done in a smarter way

if update == True: # If file already exists, update it
repo.update_file(contents.path, message, data, contents.sha, author=author) # Add, commit and push branch
else:
try:
# If file doesn't exist, create it in the same relative path of the local file
repo.create_file(local_file_path, message, data, branch=branch, author=author) # Add, commit and push branch
except Exception as e:
print(e)
""" create a new file or update an existing file.
the remote file has the same relative path of the local one"""
token = conf.token if bearer_token is None else bearer_token # dell'editor
user = conf.author if gituser is None else gituser # editor
usermail = conf.author_email if email is None else email
owner = conf.melody_owner # questo va cambiato melody-data
repo_name = conf.melody_repo_name # questo va cambiato stories
g = Github(token)
repo = g.get_repo(owner+"/"+repo_name)
author = InputGitAuthor(user, usermail) #  commit author
# necessary to commit filename without path
absolute_file_path = os.path.basename(local_file_path)

try:
# Retrieve the online file to get its SHA and path
contents = repo.get_contents(
conf.melody_sub_dir+'/'+absolute_file_path)
update = True
message = "updated file "+absolute_file_path+" "+action
except:
update = False
message = "created file "+absolute_file_path

# Both create/update file replace the file with the local one
with open(local_file_path) as f:
data = f.read() # could be done in a smarter way

if update == True: # If file already exists, update it
# Add, commit and push branch
repo.update_file(contents.path, message, data,
contents.sha, author=author)
else:
try:
# If file doesn't exist, create it in the same relative path of the local file
# Add, commit and push branch
repo.create_file(conf.melody_sub_dir+'/'+absolute_file_path, message, data,
branch=branch, author=author)
except Exception as e:
print(e)


def delete_file(local_file_path, branch, gituser=None, email=None, bearer_token=None):
Expand Down
138 changes: 73 additions & 65 deletions static/js/main.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
addEventListener("DOMContentLoaded", function() {
if (Object.getOwnPropertyNames(datastory_data).length > 0)
{colorSwitch(datastory_data.color_code[0], datastory_data.color_code[1]);}
addEventListener("DOMContentLoaded", function () {
if (Object.getOwnPropertyNames(datastory_data).length > 0) { colorSwitch(datastory_data.color_code[0], datastory_data.color_code[1]); }
});

window.onload = function () {
if (Object.getOwnPropertyNames(datastory_data).length > 0) {queryCounter();}
if (Object.getOwnPropertyNames(datastory_data).length > 0) { queryCounter(); }
chartViz();
disableKeypress();
saveHTML(datastory_data.name);
}

// disable selection of templates other than statistics
$( document ).ready(function() {
$("#exampleFormControlSelect1 option[value='statistics']").removeAttr('disabled');
$(".navbar-toggler.sidenav-toggler.ml-auto").attr('aria-expanded','false');
if (Object.getOwnPropertyNames(datastory_data).length > 0) {
getBrightness(datastory_data.color_code[1]);
}
$(document).ready(function () {
$("#exampleFormControlSelect1 option[value='statistics']").removeAttr('disabled');
$(".navbar-toggler.sidenav-toggler.ml-auto").attr('aria-expanded', 'false');
if (Object.getOwnPropertyNames(datastory_data).length > 0) {
getBrightness(datastory_data.color_code[1]);
}
});

//// WYSIWYG FORM FUNCTIONS ////
Expand Down Expand Up @@ -445,12 +445,11 @@ function colorSwitch(color_1, color_2) {
var gradientEl = document.querySelector(".secondarymenuinner");
var counters = document.querySelectorAll(".count_result");
//gradientEl.classList.remove("bg-primary-gradient");
if (gradientEl !== undefined)
{gradientEl.style.background = 'linear-gradient(-45deg,' + color_1 + ',' + color_2 + ')';}
if (gradientEl !== undefined) { gradientEl.style.background = 'linear-gradient(-45deg,' + color_1 + ',' + color_2 + ')'; }

function borders(el) {
el.style.border = "solid 2px "+color_1;
el.style.color = color_1;
el.style.border = "solid 2px " + color_1;
el.style.color = color_1;
}
counters.forEach(borders);
}
Expand Down Expand Up @@ -1089,62 +1088,71 @@ function auto_grow(element) {
}

function getPDF(elem_id) {
var element = document.getElementById(elem_id);
var opt = {
margin: 1,
filename: 'story.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 1 },
pagebreak: { mode:'avoid-all', after:'pagebreak'},
jsPDF: { unit: 'mm', format: 'letter', orientation: 'portrait' }
};
html2pdf(element, opt);
var element = document.getElementById(elem_id);
var opt = {
margin: 1,
filename: 'story.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 1 },
pagebreak: { mode: 'avoid-all', after: 'pagebreak' },
jsPDF: { unit: 'mm', format: 'letter', orientation: 'portrait' }
};
html2pdf(element, opt);
}

function getHTML(el) {
var html = document.documentElement.outerHTML;
var htmlcopy = html.replaceAll('/static', 'static');

// remove elements
// var div = document.createElement('div');
// div.innerHTML = htmlcopy;
// var elements = div.getElementsByClassName('sidebar');
// while (elements[0])
// elements[0].parentNode.removeChild(elements[0])
// var elements2 = div.getElementsByClassName('main-header');
// while (elements2[0])
// elements2[0].parentNode.removeChild(elements2[0])

// reassemble html
//var repl = div.innerHTML;
//console.log(repl);
// download html and zip file
var thishtml = encodeURIComponent(htmlcopy);
el.href='data:text/html;charset=UTF-8,'+thishtml;
window.open('../static/static.zip');
var html = document.documentElement.outerHTML;
var htmlcopy = html.replaceAll('/static', 'static');

// remove elements
// var div = document.createElement('div');
// div.innerHTML = htmlcopy;
// var elements = div.getElementsByClassName('sidebar');
// while (elements[0])
// elements[0].parentNode.removeChild(elements[0])
// var elements2 = div.getElementsByClassName('main-header');
// while (elements2[0])
// elements2[0].parentNode.removeChild(elements2[0])

// reassemble html
//var repl = div.innerHTML;
//console.log(repl);
// download html and zip file
var thishtml = encodeURIComponent(htmlcopy);
el.href = 'data:text/html;charset=UTF-8,' + thishtml;
window.open('../static/static.zip');
}

function saveHTML(name) {
var html = document.documentElement.outerHTML;
var htmlcopy = html.replaceAll('/static', 'static');
var thishtml = encodeURIComponent(htmlcopy);
saveAs(thishtml, name + '.html');
}

// change color of secondary menu in datastory
function getBrightness(c) {
var c = c.substring(1); // strip #
var rgb = parseInt(c, 16); // convert rrggbb to decimal
var r = (rgb >> 16) & 0xff; // extract red
var g = (rgb >> 8) & 0xff; // extract green
var b = (rgb >> 0) & 0xff; // extract blue
var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709

var nodes = document.getElementById('secondarymenuinner').children;
for (var i=0; i<nodes.length; i++) {
if (luma < 45) {
nodes[i].setAttribute('style', 'color:#ffffff !important');
$('.exportbutton').css('border','solid 1px #ffffff');
} else {
nodes[i].setAttribute('style', 'color: black !important');}

for (var j=0; j<nodes[i].children.length; j++) {
if (luma < 45) { nodes[i].children[j].setAttribute('style', 'color:#ffffff !important');
} else {nodes[i].children[j].setAttribute('style', 'color: black !important');}
}
};
var c = c.substring(1); // strip #
var rgb = parseInt(c, 16); // convert rrggbb to decimal
var r = (rgb >> 16) & 0xff; // extract red
var g = (rgb >> 8) & 0xff; // extract green
var b = (rgb >> 0) & 0xff; // extract blue
var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709

var nodes = document.getElementById('secondarymenuinner').children;
for (var i = 0; i < nodes.length; i++) {
if (luma < 45) {
nodes[i].setAttribute('style', 'color:#ffffff !important');
$('.exportbutton').css('border', 'solid 1px #ffffff');
} else {
nodes[i].setAttribute('style', 'color: black !important');
}

}
for (var j = 0; j < nodes[i].children.length; j++) {
if (luma < 45) {
nodes[i].children[j].setAttribute('style', 'color:#ffffff !important');
} else { nodes[i].children[j].setAttribute('style', 'color: black !important'); }
}
};

}
7 changes: 6 additions & 1 deletion templates/datastory_statistics.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ <h4>About</h4>
<button class="exportbutton" type="button"><a onclick="getHTML(this)" href="#"
download="{{datastory_data.title}}.html">HTML</a></button>
</section>

<!-- publish button -->
{% if session['user_type'] == 'extra' %}
<form method="post">
<button type="submit" method="post" class="btn btn-success">Publish</button>
</form>
{% endif %}
<!-- modify button -->
{% if session['user_type'] != 'polifonia' %}
{% set name = (datastory_data.name).split('_') %}
Expand Down

0 comments on commit 0354c61

Please sign in to comment.