1/**
2 * check if the dl is ready
3 *
4 * @param key file key
5 */
6jQuery(function handleDOMReady() {
7    'use strict';
8
9    let $form = jQuery('form.plugin_nsexport__form');
10    if ($form.length === 0) return;
11    $form = $form.first();
12
13    const INTERVAL_MAX = 10000;
14    const INTERVAL_STEP = 1000;
15    let intervalId = null;
16    let interval = 500;
17
18    window.nsexport_check = function nsexportCheck(key) {
19        const url = DOKU_BASE + 'lib/exe/ajax.php';
20        const data = {
21            call: 'nsexport_check',
22            key: key,
23        };
24
25        jQuery.post(url, data).done(function handleCheckResult(response) {
26            clearInterval(intervalId);
27
28            if (response === '1') {
29                // download is ready - get it
30                const $throb = jQuery('#plugin_nsexport__throbber');
31                $throb.replaceWith(LANG.plugins.nsexport.done);
32                window.location = DOKU_BASE + 'lib/plugins/nsexport/export.php?key=' + key;
33                return false;
34            }
35
36            if (interval < INTERVAL_MAX) {
37                interval += INTERVAL_STEP;
38            }
39            intervalId = setInterval(window.nsexport_check, interval, response);
40
41            // download not ready - wait
42            return false;
43        });
44    };
45
46    function startExport() {
47        const data = {
48            call: 'nsexport_start',
49            pages: [],
50        };
51
52        $form.find('[name="export[]"]:checked').each(function extractPageID(index, element) {
53            data.pages.push(element.value);
54        });
55
56        const url = DOKU_BASE + 'lib/exe/ajax.php';
57
58        jQuery.post(url, data).done(
59            function packagingStarted(response) {
60                if (response === '') {
61                    return;
62                }
63                // start waiting for dl
64                intervalId = setInterval(window.nsexport_check, interval, response);
65            }
66        );
67
68        const $msg = jQuery('<div>').addClass('level1').html('<p>' + LANG.plugins.nsexport.loading
69            + '<img id="plugin_nsexport__throbber" src="' + DOKU_BASE + 'lib/images/throbber.gif" alt="…"></p>');
70
71        $form.replaceWith($msg);
72    }
73
74    if ($form.hasClass('plugin_nsexport__started')) {
75        // Autostart
76        startExport();
77        return;
78    }
79
80    $form.submit(function handleFormSubmit(e) {
81        $form.removeClass().addClass('plugin_nsexport__started');
82
83        startExport();
84
85        e.preventDefault();
86        e.stopPropagation();
87        return false;
88    });
89});
90