This commit is contained in:
zeroth 2020-01-16 16:54:13 +00:00
parent 093dd28cf9
commit a60bc7b3a7
3 changed files with 125 additions and 74 deletions

View File

@ -1,4 +1,12 @@
from flask import Flask, Response, url_for, render_template, Markup, jsonify, redirect, request, flash, session, make_response
# encoding=utf8
import sys
import pypandoc
import PyPDF2
from PyPDF2 import PdfFileMerger, PdfFileReader
from weasyprint import HTML, CSS
from weasyprint.fonts import FontConfiguration
from flask import send_file, Flask, Response, url_for, render_template, Markup, jsonify, redirect, request, flash, session, make_response
from config import Config
import json
import os
@ -34,11 +42,6 @@ listofdicts=[] #to be able to import and use json content
datafromjson = []
max_wordpath_items = 500 # limit the nr. of items, as to prevent possible glitches with bots
# #test getting json file from id
# id = "17"
# jsonfilefordescription = "files/"+id+"/"+id+".json"
#arrays with the user path of words and numbers
pathofwords = []
pathofnumbers = []
@ -83,18 +86,6 @@ index_dict = {}
with open('wordlist.json', 'r', encoding='utf8') as f:
wordlist_dict = json.load(f)
#listing paths and files, not in order but well...
# for path, subdirs, files in os.walk(path):
# for name in files:
# if not name.endswith(".json") and not name.endswith(".DS_Store"):
# fullpath = os.path.join(path, name)
# listingdirectories.append(path)
# listingfiles.append(fullpath[7:]) #fullpaths minus static/
#
# if name.endswith(".json"):
# fullpath = os.path.join(path, name)
# jsonfiles.append(fullpath[7:])
#listing the json paths simultaneously generating a new index.json for the navbar
for path, subdirs, files in os.walk('./static/files/'):
@ -108,11 +99,6 @@ for path, subdirs, files in os.walk('./static/files/'):
index_dict[temp_dict["id"]] = temp_dict["title"]
# with open("static/"+jsonfiles[4], 'r') as f:
# data_dict = json.load(f)
# datafromjson = data_dict["files"]
######################################################################################
#NOW THE REAL DEAL
######################################################################################
@ -135,7 +121,6 @@ def context_processor():
@app.route('/about/')
def about():
setupSession()
return render_template('about.html')
@app.route('/clear')
@ -145,12 +130,6 @@ def clear():
clearSession()
return redirect(return_url)
# @app.route('/all/')
# def all():
# thefile = listingfiles[positioninarray]
# counter2=0
# return render_template('all.html', file=thefile, listingfiles=listingfiles, jsonfiles=jsonfiles, listofdicts=listofdicts, counter2=counter2)
@app.route('/description')
def description():
setupSession()
@ -201,15 +180,6 @@ def diverge():
session['clicktime'] = list(clicktime)
return render_template('diverge.html', wordlist_dict=wordlist_dict, searchterm=searchterm, index_dict=index_dict)
# @app.route('/listofwords')
# def listofwords():
# # r = jsonify(session)
# r = str(session)
# r0w = session["wordpath"][0]
# r0c = session["clicktime"][0]
# r0id = session["id"][0]
# return render_template('listofwords.html', r=r, r0c=r0c, r0w=r0w, r0id=r0id)
######################################################################################
#THE SCORE STUFF
######################################################################################
@ -218,11 +188,10 @@ def diverge():
### to be printed to the text document
@app.route("/get-file")
def get_file():
setupSession()
fullscore = None
wordpath = session["wordpath"]
idlist = session["id"]
timelist = session["clicktime"]
@ -231,7 +200,7 @@ def get_file():
tadam = None
initialtime = None
# USER IP ADDRESS OBTENTION
# # USER IP ADDRESS OBTENTION
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
userip = request.environ['REMOTE_ADDR']
else:
@ -241,7 +210,7 @@ def get_file():
if ',' in userip:
userip = userip.split(',')[0]
# CALCULATION OF INITIAL TIME BEFORE FIRST CLICK
# # CALCULATION OF INITIAL TIME BEFORE FIRST CLICK
if len(timelist) and not (timelist[0] is None):
thetime = timelist[0]
thetime = str(thetime)
@ -254,7 +223,7 @@ def get_file():
initialtime = "."*initialtime
print(initialtime)
#CALCULATE FILE NUMBER
# #CALCULATE FILE NUMBER
dirListing = os.listdir("scores/")
scorenumber = len(dirListing)
@ -277,13 +246,6 @@ def get_file():
# WEAVING DELAYS AND WORDS TOGETHER AS A HUGE STRING OF CHARACTERS
for (word, time) in zip(wordpath,timelistforoperations):
# for (word, time, uniqueid) in zip(wordpath,timelistforoperations, idlist):
# print("word : "+word+"\n")
# print("timeofclick : "+str(time)+"\n")
# print("============")
# print(wordpath)
# print("============")
# filler = int(uniqueid)
upperword = word.upper()
#get previous time for substraction
@ -301,9 +263,7 @@ def get_file():
difftime = int(difftime)
test = difftime
prev = time
diffpattern = test * '.'
stringy = diffpattern + upperword
@ -314,17 +274,6 @@ def get_file():
wholestringy = upperword
fullscore = wholestringy
# #If fullscore length superior 60 characters, insert linebreak
# # Defining splitting point
# n = 60
# # Using list comprehension
# out = [(fullscore[i:i+n]) for i in range(0, len(fullscore), n)]
# #joining the strings with linebreaks
# tadam = '\n'.join(out)
if not (fullscore is None):
# outside of the loop calculate seconds from "clickongetfiletime" minus the last "time" from the loop
lastdifftime = clickongetfiletime - prev
@ -339,25 +288,100 @@ def get_file():
# Using list comprehension
out = [(fullscore[i:i+n]) for i in range(0, len(fullscore), n)]
#joining the strings with linebreaks
tadam = '\n'.join(out) +"\n\nScore number : "+str(scorenumber)+ "\nGenerated at : "+str(clickongetfiletime)+"\nBy author : "+ userip
# tadam = '\n'.join(out) +"\n\n\n\nScore number : "+str(scorenumber)+ "\nGenerated at : "+str(clickongetfiletime)+"\nBy author : "+ userip
tadam = '\n'.join(out)
# have a message in file if no nav has been recorded so it's less dull than error page
if tadam is None:
tadam = "This score is Null"
# print("verylastnow : "+str(clickongetfilefime)+"\n")
uniquename = str(clickongetfiletime)
with open('scores/'+uniquename+'.txt', 'a+') as f:
f.write(tadam)
# with open('scores/'+uniquename+'.txt', 'a+') as f:
# f.write(tadam)
print(tadam)
# print(tadam)
return Response(tadam,
mimetype="text/plain",
headers={"Content-Disposition":
"attachment;filename=yourveryspecialscore.txt"})
###### SCORE FIST PAGE
globalname = "Pushing scores"
scorefirstpage = '''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="static/css/stylepandoc.css">
</head>
<body>
<style>
body{background-color:yellow;}
</style>
<div id="coverpage">
<div>'''+globalname+'''</div>
<div>'''+str(scorenumber)+'''</div>
<div>'''+str(clickongetfiletime)+'''</div>
<div>'''+userip+'''</div>
</div>
</body>
</html>
'''
scorecontentpage = '''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="static/css/stylepandoc.css">
</head>
<body>
<div id="scorecontentpage">
{}
</div>
</body>
</html>
'''.format(tadam)
############# GENERATE SCORE PDF
pathnamefilepdf = "pandoc/"+uniquename+"test.pdf"
font_config = FontConfiguration()
HTML(string=scorecontentpage, base_url='./').write_pdf(pathnamefilepdf, stylesheets=[CSS('static/css/stylepandoc.css', font_config=font_config)], font_config=font_config)
############# GENERATE FIRST PAGE PDF
pathnamefilecoverpdf = "pandoc/"+uniquename+"testcover.pdf"
font_config = FontConfiguration()
HTML(string=scorefirstpage, base_url='./').write_pdf(pathnamefilecoverpdf, stylesheets=[CSS('static/css/stylepandoc.css', font_config=font_config)], font_config=font_config)
############# ASSEMBLE PDFS
merger = PdfFileMerger()
file1 = open(pathnamefilecoverpdf,"rb")
file2 = open(pathnamefilepdf,"rb")
pdf1 = PyPDF2.PdfFileReader(file1)
pdf2 = PyPDF2.PdfFileReader(file2)
pdf1_pages = pdf1.getNumPages()
pdf2_pages = pdf2.getNumPages()
outputfile = open("pandoc/"+uniquename+"document-output.pdf", "wb")
writer = PyPDF2.PdfFileWriter()
for i in range(pdf1_pages):
writer.addPage(pdf1.getPage(i))
for j in range(pdf2_pages):
writer.addPage(pdf2.getPage(j))
writer.write(outputfile)
file1.close()
file2.close()
outputfile.close()
try:
return send_file("pandoc/"+uniquename+"document-output.pdf", attachment_filename="olala.pdf")
except Exception as e:
return str(e)
######################################################################################

0
pandoc/blabla.txt Normal file
View File

View File

@ -0,0 +1,27 @@
@page {
/*size: 8.5in 11in !important;*/
bleed: 0 !important;
padding: 0 !important;
margin: 0 !important;
}
html,body{
margin: 0 !important;
padding: 0 !important;
font-family: monospace;
font-size: 14px;
/*background-color: silver;*/
text-align: center;
}
div#coverpage{
/*background-color: red;*/
height: 100%;
width: 100%;
margin: 0
}
div#scorecontentpage{
margin:auto;
color: black;
/*text-align: left;*/
}