Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changed api request #48

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/src/gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
SCORE_OFFSET = 150;
PAGE_NUMBER_X_OFFSET = 40;
PAGE_NUMBER_Y_OFFSET = 20;
MAX_INPUT_CHARACTERS = 50;
MAX_INPUT_CHARACTERS = 200;
MAX_TITLE_LENGTH = 20;
GUIDE_LINE_WIDTH = 5;
FIRST_CHARACTER_ROW_Y = PAGE_SIZE[1]-HEADER_PADDING-GRID_OFFSET/2;
Expand Down
59 changes: 21 additions & 38 deletions backend/src/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@
error_lock = Lock();

class GenerateInfos(Resource):
def get(self):
characters = request.args.get('characters');
def post(self):
characters = request.args.get('characters')
data = request.get_json()
characters = data['characters']
if characters == None or len(characters) == 0:
return jsonpify({'error': 'No characters provided'});
characters = characters.replace(' ', '');
Expand All @@ -50,10 +52,11 @@ def get(self):
return jsonpify(result);

class GenerateSheet(Resource):
def get(self):
def post(self):
temp_path = request.args.get('id');
guide = request.args.get('guide');
title = request.args.get('title');
data = request.get_json()
if temp_path == None or len(temp_path) == 0 or \
guide == None or len(guide) == 0 or \
title == None:
Expand All @@ -63,8 +66,8 @@ def get(self):
except GenException as e:
return jsonpify({'error': str(e)});

update_characters_file(temp_path, request.args);
update_words_file(temp_path, request.args);
update_characters_file(temp_path, data);
update_words_file(temp_path, data);

error_msg = 'generate_sheet ' + title + ' ' + str(guide) + '\n';
try:
Expand Down Expand Up @@ -110,17 +113,8 @@ def get(self):
finally:
count_lock.release();

def update_characters_file(working_directory, request_args):
pinyins = [];
definitions = [];
i = 0;
while ('pinyin' + str(i)) in request_args:
pinyins.append(request_args.get('pinyin' + str(i)));
definitions.append(request_args.get('definition' + str(i)));
i += 1;

def update_characters_file(working_directory, request_body):
file_path = os.path.join(working_directory, CHARACTERS_FILE);

new_file_name = 'new_' + CHARACTERS_FILE;
new_file_path = os.path.join(working_directory, new_file_name);
with open(file_path, 'r') as f_orig:
Expand All @@ -131,32 +125,21 @@ def update_characters_file(working_directory, request_args):
if line == '':
break;
info = json.loads(line);
info['pinyin'] = [pinyins[i]];
info['definition'] = definitions[i];
pinyin = request_body['characters'][info["character"]]['pinyin']
definition = request_body['characters'][info["character"]]['definition']
info['pinyin'] = [pinyin];
info['definition'] = definition;
f_new.write(json.dumps(info) + '\n');
i += 1;
shutil.copy(new_file_path, file_path);

def update_words_file(working_directory, request_args):
def update_words_file(working_directory, request_body):
try:
words_definitions = request_body['words']
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If words parameter is not provided, no words should be generated (to match current logic). Also, this method now throws, if the number of words in words_definitions does not match the number of words in WORDS_FILE. Again, to match the current logic, we should use an empty array at words_definitions[i], for which we do not have the data in words_definitions.

except:
# no words in this file
return
file_path = os.path.join(working_directory, WORDS_FILE);
word_cnt = 0;
with open(file_path, 'r') as f_orig:
while 1:
line = f_orig.readline();
if line == '':
break;
word_cnt += 1;

# TODO: may throw if len(words_definitions) < number of words in WORDS_FILE
words_definitions = [];
for i in range(word_cnt):
j = 0;
definitions = [];
while ('word' + str(i) + 'definition' + str(j)) in request_args:
definitions.append(request_args.get('word' + str(i) + 'definition' + str(j)));
j += 1;
words_definitions.append(definitions);

new_file_name = 'new_' + WORDS_FILE;
new_file_path = os.path.join(working_directory, new_file_name);
with open(file_path, 'r') as f_orig:
Expand Down Expand Up @@ -242,8 +225,8 @@ def main(argv):
cors = CORS(app);
app.config['CORS_HEADERS'] = 'Content-Type';
api = Api(app);
api.add_resource(GenerateInfos, '/generate_infos');
api.add_resource(GenerateSheet, '/generate_sheet');
api.add_resource(GenerateInfos, '/generate_infos', methods=['POST']);
api.add_resource(GenerateSheet, '/generate_sheet', methods=['POST']);
api.add_resource(RetrieveSheet, '/retrieve_sheet');
api.add_resource(RetrieveCount, '/retrieve_count');
app.run(port='5002', threaded=True);
Expand Down
82 changes: 43 additions & 39 deletions frontend/script.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
var id;

const BASE_URL = "http://127.0.0.1"
const URL = BASE_URL + ":5002";
const GENERATOR_UNAVAILABLE_MSG = "Generator is unavailable. Please try again later.";
Expand Down Expand Up @@ -38,25 +39,27 @@ function generateInfos()
var title = getWorksheetTitle();
var guide = document.getElementById("guide").value;

var url = URL + "/generate_infos?characters=" + characters;
var url = URL + "/generate_infos";
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.onload = function (e) {
if ( req.readyState === 4 ) {
if ( req.status === 200 ) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/json");

req.onreadystatechange = function () { //Call a function when the state changes.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove the unnecessary comment.


if (req.readyState === 4 && req.status === 200) {
response = JSON.parse(req.responseText);
onInfosGenerated(response);
} else {
showError("infos_error", SERVER_FUCKED_UP_MSG);
}
document.getElementById("infos_loading").style.display = "none";
}
}

document.getElementById("infos_loading").style.display = "none";
}
scharacters = { "characters": characters }
req.onerror = function (e) {
document.getElementById("infos_loading").style.display = "none";
showError("infos_error", GENERATOR_UNAVAILABLE_MSG);
showError("sheet_error", GENERATOR_UNAVAILABLE_MSG + ": " + e) ;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why sheet_error? Also, I don't think we want to show to a user message like:

Error: Generator is unavailable. Please try again later.: [object ProgressEvent]

}
req.send(null);
document.getElementById("infos_loading").style.display = "inline";
req.send(JSON.stringify(scharacters));
}

function onInfosGenerated(response)
Expand All @@ -70,14 +73,15 @@ function onInfosGenerated(response)
createWordsTable(response["words"]);
document.getElementById("confirm").style.display = "inline";
id = response["id"];
// console.log("id: " + id)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove it.

}

function createCharactersTable(infos)
{
var table = '<div class="table-responsive"><table class="table" id="actual_characters_table"><thead><tr><th>Character</th><th>Pinyin</th><th>Definition</th></tr></thead><tbody>';
for (i = 0 ; i < infos.length ; i++)
{
row = '<tr><td class="narrow"><input type="text" class="form-control input-lg" value="' + infos[i].character + '" disabled></td>' +
row = '<tr><td class="narrow"><input type="text" id="character' + i + '" class="form-control input-lg" value="' + infos[i].character + '" disabled></td>' +
'<td class="narrow"><input type="text" id="pinyin' + i + '" class="form-control input-lg" value="' + infos[i].pinyin + '"></td>' +
'<td class="wide"><input type="text" id="definition' + i + '" class="form-control input-lg" value="' + infos[i].definition + '"></td></tr>';
table += row;
Expand Down Expand Up @@ -118,6 +122,7 @@ function generateSheet()
document.getElementById("download").style.display = "none";
var title = getWorksheetTitle();
var guide = document.getElementById("guide").value;
var payload = {};
if ( guide == 0 )
guide = "none";
else if ( guide == 1 )
Expand All @@ -134,58 +139,57 @@ function generateSheet()
var url = URL + "/generate_sheet?id=" + id +
"&guide=" + guide +
"&title=" + title;

url += get_character_parameters();
url += get_words_parameters();

payload.id = id;
payload.guide = guide;
payload.title = title;

payload.characters = get_character_parameters();
payload.words = get_words_parameters();
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.onload = function (e) {
if ( req.readyState === 4 ) {
if ( req.status === 200 ) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/json");
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
response = JSON.parse(req.responseText);
onSheetGenerated(response);
} else {
showError("sheet_error", SERVER_FUCKED_UP_MSG);
}
document.getElementById("sheet_loading").style.display = "none";
}
}
document.getElementById("sheet_loading").style.display = "none";
}
req.onerror = function (e) {
document.getElementById("sheet_loading").style.display = "none";
showError("sheet_error", GENERATOR_UNAVAILABLE_MSG);
showError("sheet_error", GENERATOR_UNAVAILABLE_MSG) ;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Revert.

}
document.getElementById("sheet_loading").style.display = "inline";
req.send(null);
req.send(JSON.stringify(payload));
}

function get_character_parameters() {
var url = "";
var charparams = {};
var n = document.getElementById("actual_characters_table").rows.length-1;
for ( i = 0 ; i < n ; i++ )
{
var character = document.getElementById("character" + i).value;
var pinyin = document.getElementById("pinyin" + i).value;
var definition = document.getElementById("definition" + i).value;
url += "&pinyin" + i + "=" + pinyin;
url += "&definition" + i + "=" + definition;
charparams[character] = {};
charparams[character].pinyin = pinyin;
charparams[character].definition = definition;
}
return url;
return charparams;
}

function get_words_parameters() {
var url = "";
var worddefs = [];
var wt = document.getElementById("actual_words_table");
if ( wt == null ) return url;
if ( wt == null ) return worddefs;
n = wt.rows.length-1;
for ( i = 0 ; i < n ; i++ )
{
var tags = $("#word_definition" + i).tagsManager('tags');
for ( j = 0 ; j < tags.length ; j++ )
{
url += "&word" + i + "definition" + j + "=" + tags[j];
}
worddefs.push(tags);

}
return url;
return worddefs;
}

function download(filename, text) {
Expand Down