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

Add download message #532

Merged
merged 1 commit into from
Nov 20, 2024
Merged
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
11 changes: 10 additions & 1 deletion app/ApiHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ public function handle() {
case "get_shared_note_form":
$this->getSharedNoteForm();
break;
case "get_record_count":
$this->getRecordCount();
break;
default:
$this->response_data['success'] = false;
$this->response_data['json'] = $this->json_data;
Expand Down Expand Up @@ -180,7 +183,7 @@ public function getSettings(): void
{
if (isset($this->json['settings_id']) && (ctype_alnum((string) $this->json['settings_id']) || in_array($this->json['settings_id'], [Settings::ID_ALL_SETTINGS, Settings::ID_MAIN_SETTINGS]))) {
$settings = new Settings();
// Treat loggged out users special if requesting ID_MAIN_SETTINGS
// Treat logged-out users special if requesting ID_MAIN_SETTINGS
if ($this->json['settings_id'] == Settings::ID_MAIN_SETTINGS && Auth::user()->id() == Settings::GUEST_USER_ID) {
$vars = Validator::parsedBody($this->request)->array('vars');
$form = new FormSubmission();
Expand Down Expand Up @@ -418,4 +421,10 @@ private function getSharedNoteForm()
$this->response_data['success'] = true;
$this->response_data['response'] = view($this->module->name() . '::MainPage/Appearance/TileDesign/SharedNote', ['vars' => $vars, 'tree' => $this->tree, 'module' => $this->module]);
}

private function getRecordCount()
{
$this->response_data['success'] = true;
$this->response_data['response'] = Settings::loadRecordCount($this->json['token']);
}
}
6 changes: 6 additions & 0 deletions app/FormSubmission.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ class FormSubmission
public function load($vars, $module): array
{
$settings = [];

if (isset($vars["time_token"]) && $this->isNameStringValid($vars["time_token"])) {
$settings['time_token'] = $vars["time_token"];
} else {
$settings['time_token'] = '';
}
// INDI id
if (!empty($vars["xref_list"]) && $this->isXrefListValid($vars["xref_list"])) {
$settings['xref_list'] = $vars["xref_list"];
Expand Down
47 changes: 47 additions & 0 deletions app/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use Fisharebest\Webtrees\Http\Exceptions\HttpBadRequestException;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Tree;
use Fisharebest\Webtrees\GuestUser;

Check warning on line 10 in app/Settings.php

View workflow job for this annotation

GitHub Actions / Qodana for PHP

Undefined class

Undefined class 'GuestUser'


/**
* Represents the diagram settings, regardless of context (user, admin, default)
Expand All @@ -25,6 +27,7 @@
public const PREFERENCE_PREFIX = "GVE";
public const SETTINGS_LIST_PREFERENCE_NAME = "_id_list";
public const SAVED_SETTINGS_LIST_PREFERENCE_NAME = "_shared_settings_list";
const RECORD_COUNT_PREFERENCE_NAME = 'RECORD_COUNT';
public const OPTION_STRIPE_NONE = 100;
public const OPTION_STRIPE_SEX_COLOUR = 110;
public const OPTION_STRIPE_VITAL_COLOUR = 120;
Expand Down Expand Up @@ -489,6 +492,7 @@
case 'click_action_indi_options':
case 'arrow_style_options':
case 'limit_levels':
case 'time_token':
return false;
case 'show_debug_panel':
case 'filename':
Expand Down Expand Up @@ -851,4 +855,47 @@
return $settings['limit_levels_visitor'];
}
}

/**
* Saves record count of diagram to session storage
*
* @param string $token Token used by front end to check record has been updated
* @param int $indis
* @param int $fams
* @return void
*/
public function updateRecordCount(string $token, int $indis, int $fams)
{
$data = json_encode([
'time_token' => $token,
'indis' => $indis,
'fams' => $fams
]);
$_SESSION[Settings::PREFERENCE_PREFIX . '_' . Settings::RECORD_COUNT_PREFERENCE_NAME] = $data;
}

/**
* Loads record count of diagram from session storage
*
* @param $token
* @return string
*/
static public function loadRecordCount($token): string
{
$defaults = [
'time_token' => '',
'indis' => -1,
'fams' => -1
];

$records = $_SESSION[Settings::PREFERENCE_PREFIX . '_' . Settings::RECORD_COUNT_PREFERENCE_NAME] ?? null;

$decoded = $records ? json_decode($records, true) : null;

if ($decoded && isset($decoded['time_token']) && $decoded['time_token'] === $token) {
return $records;
}

return json_encode($defaults);
}
}
1 change: 1 addition & 0 deletions module.php
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ function createGraphVizDump($tree, $vars_data, $temp_dir): string
} else {
$r = $out;
}
$settings->updateRecordCount($dot->settings['time_token'], sizeof($dot->individuals), sizeof($dot->families));
return $r;
}

Expand Down
13 changes: 13 additions & 0 deletions resources/javascript/MainPage/Data.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,19 @@ const Data = {
return Data.callAPI(request);
},

/**
* Sends API request to retrieve record count
*
* @returns {Promise<unknown>}
*/
getResourceCount(token) {
let request = {
"type": REQUEST_TYPE_GET_RECORD_COUNT,
"token": token,
};
return Data.callAPI(request);
},

decodeHTML(html) {
const textarea = document.createElement('textarea');
textarea.innerHTML = html;
Expand Down
3 changes: 2 additions & 1 deletion resources/javascript/gvexport.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const REQUEST_TYPE_ADD_MY_FAVORITE = "add_my_favorite";
const REQUEST_TYPE_ADD_TREE_FAVORITE = "add_tree_favorite";
const REQUEST_TYPE_GET_HELP = "get_help";
const REQUEST_TYPE_GET_SHARED_NOTE_FORM = "get_shared_note_form";
const REQUEST_TYPE_GET_RECORD_COUNT = "get_record_count";
let treeName = null;
let loggedIn = null;
let xrefList = [];
Expand All @@ -35,7 +36,7 @@ function loadURLXref(Url) {
let startValue = el.value;
Form.indiList.addIndiToList(xref);
if (url_xref_treatment === 'default' && xrefs.length === 1 ) {
setTimeout(function () {UI.showToast(TRANSLATE['Source individual has replaced existing individual'].replace('%s', xrefs.length.toString()))}, 100);
setTimeout(function () {UI.showToast(TRANSLATE['Source individual has replaced existing individual'])}, 100);
} else if (startValue !== el.value && (url_xref_treatment === 'default' || url_xref_treatment === 'add')) {
setTimeout(function () {UI.showToast(TRANSLATE['One new source individual added to %s existing individuals'].replace('%s', xrefs.length.toString()))}, 100);
}
Expand Down
3 changes: 2 additions & 1 deletion resources/views/MainPage/Translations.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,13 @@ use Fisharebest\Webtrees\I18N;
"Enter new setting name":"<?= I18N::translate('Enter new setting name'); ?>",
"Rename":"<?= I18N::translate('Rename'); ?>",
"No styles set based on shared notes.":"<?= I18N::translate('No styles set based on shared notes.'); ?>",
"%s shared note styles saved.":"<?= I18N::translate('%s shared note styles saved.', '%s'); ?>",
"%s shared note styles saved.":"<?= I18N::translate('%s shared note styles saved.', '%s'); ?>", // Javascript used to replace %s later
"Add individual to list of starting individuals":"<?= I18N::translate('Add individual to list of starting individuals'); ?>",
"Open individual's page":"<?= I18N::translate('Open individual\'s page'); ?>",
"Replace starting individuals with this individual":"<?= I18N::translate('Replace starting individuals with this individual'); ?>",
"Add this individual to the list of stopping individuals":"<?= I18N::translate('Add this individual to the list of stopping individuals'); ?>",
"Replace stopping individuals with this individual":"<?= I18N::translate('Replace stopping individuals with this individual'); ?>",
"Add to list of individuals to highlight":"<?= I18N::translate('Add to list of individuals to highlight'); ?>",
"Downloaded diagram with %s individuals and %s families.":"<?= I18N::translate('Downloaded diagram with %s individuals and %s families.', '%s', '%s'); ?>", // Javascript used to replace %s later
};
</script>
52 changes: 51 additions & 1 deletion resources/views/page.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ $usegraphviz = $vars['graphviz_bin'] != "";

<?= csrf_field() ?>

<input type="hidden" id="time_token" name="vars[time_token]" value="">
<div id="saved_diagrams_panel" <?php if (!$vars["show_diagram_panel"]) echo 'style="display: none"'; ?>>
<div class="d-flex">
<h3><?= I18N::translate('Saved diagrams') ?></h3>
Expand Down Expand Up @@ -153,7 +154,7 @@ $usegraphviz = $vars['graphviz_bin'] != "";
<div id="diagram_search_box_container" style="display: none"><?= view('components/select-individual', ['name' => 'diagram_search_box', 'id' => 'diagram_search_box', 'tree' => $tree, 'individual' => "", 'required'=>false]); ?></div>
</div>
</div>
<div id="context_menu">
<div id="context_menu" style="display: none">
<span id="menu-info">
<?= MainPage::addInfoButton('Context menu when individual clicked'); ?>
</span>
Expand Down Expand Up @@ -217,8 +218,57 @@ $usegraphviz = $vars['graphviz_bin'] != "";
e.preventDefault();
}
}
let timeToken = crypto?.randomUUID?.() || (Date.now()).toString(16);

document.getElementById('time_token').value = timeToken;
setTimeout(() => { getResourceCountWithMyToken(timeToken)}, 500);
});

/**
* Send request to server to get the number of individuals and families from the generated diagram
*
* @param myToken A time based token used to check that the information on record counts is from the same request we sent to the server
* @param callCount Keeps track of retries. If the server never gets updated to our token (maybe multiple requests messed this up), then we eventually give up.
*/
function getResourceCountWithMyToken(myToken, callCount = 0) {

const MAX_RETRIES = 50;
const RETRY_DELAY = 500;
if (callCount >= MAX_RETRIES) {
console.log('Max retries reached for time token');
return;
}

if (myToken === '') {
retry(myToken, callCount);
}

Data.getResourceCount(myToken).then((response) => {
let obj;
try {
obj = JSON.parse(response);
if (obj['time_token'] === myToken) {
let indis = obj['indis'];
let fams = obj['fams'];
if ('indis' in obj && 'fams' in obj) {
UI.showToast(TRANSLATE['Downloaded diagram with %s individuals and %s families.'].replace('%s', indis).replace('%s', fams))
}
} else {
retry(myToken, callCount);
}
} catch (e) {
console.log('Failed to fetch resource counts: ' + e);
retry(myToken, callCount);
}
});

function retry(myToken, callCount) {
setTimeout(() => {
getResourceCountWithMyToken(myToken, callCount);
}, RETRY_DELAY);
}
}

function updateRender(scrollX = null, scrollY = null, zoom = null, xref = null) {
// Don't overwrite browser settings with default settings
if (!firstRender) {
Expand Down
Loading