import.js 6.14 KB
Newer Older
1
define([
2 3 4
    'domReady', 'js/views/import', 'jquery', 'gettext', 'jquery.fileupload', 'jquery.cookie'
], function(domReady, Import, $, gettext) {

5
    'use strict';
6

7
    return function (feedbackUrl, library) {
8 9 10 11 12 13 14 15
        var dbError;

        if (library) {
            dbError = gettext('There was an error while importing the new library to our database.');
        } else {
            dbError = gettext('There was an error while importing the new course to our database.');
        }

16 17 18
        var bar = $('.progress-bar'),
            fill = $('.progress-fill'),
            submitBtn = $('.submit-button'),
19
            chooseBtn = $('.view-import .choose-file-button'),
20 21 22 23
            defaults = [
                gettext('There was an error during the upload process.') + '\n',
                gettext('There was an error while unpacking the file.') + '\n',
                gettext('There was an error while verifying the file you submitted.') + '\n',
24
                dbError + '\n'
25
            ],
26
            unloading = false,
27
            previousImport = Import.storedImport(),
28 29
            file;

Alessandro Verdura committed
30
        var onComplete = function () {
31 32 33 34
            bar.hide();
            chooseBtn
                .find('.copy').html(gettext("Choose new file")).end()
                .show();
Alessandro Verdura committed
35 36
        }

37
        $(window).on('beforeunload', function (event) { unloading = true; });
38 39 40 41 42 43 44 45 46 47 48

        // Display the status of last file upload on page load
        if (previousImport) {
            $('.file-name-block')
                .find('.file-name').html(previousImport.file.name).end()
                .show();

            if (previousImport.completed !== true) {
                chooseBtn.hide();
            }

Alessandro Verdura committed
49
            Import.resume().then(onComplete);
50 51 52 53 54 55 56 57
        }

        $('#fileupload').fileupload({
            dataType: 'json',
            type: 'POST',
            maxChunkSize: 20 * 1000000, // 20 MB
            autoUpload: false,
            add: function(e, data) {
58
                Import.reset();
59
                submitBtn.unbind('click');
60

61
                file = data.files[0];
62

63
                if (file.name.match(/tar\.gz$/)) {
64
                    submitBtn.click(function(event) {
65
                        event.preventDefault();
66 67 68 69

                        Import.start(
                            file.name,
                            feedbackUrl.replace('fillerName', file.name)
Alessandro Verdura committed
70
                        ).then(onComplete);
71

72
                        submitBtn.hide();
73 74
                        data.submit().complete(function (result, textStatus, xhr) {
                            if (xhr.status !== 200) {
75
                                var serverMsg, errMsg, stage;
76

77
                                try{
Alessandro Verdura committed
78
                                    serverMsg = $.parseJSON(result.responseText) || {};
79 80 81
                                } catch (e) {
                                    return;
                                }
82

Alessandro Verdura committed
83
                                errMsg = serverMsg.hasOwnProperty('ErrMsg') ? serverMsg.ErrMsg : '';
84

85 86
                                if (serverMsg.hasOwnProperty('Stage')) {
                                    stage = Math.abs(serverMsg.Stage);
87
                                    Import.cancel(defaults[stage] + errMsg, stage);
88 89 90 91 92 93 94 95 96 97 98
                                }
                                // It could be that the user is simply refreshing the page
                                // so we need to be sure this is an actual error from the server
                                else if (!unloading) {
                                    $(window).off('beforeunload.import');

                                    Import.reset();
                                    onComplete();

                                    alert(gettext('Your import has failed.') + '\n\n' + errMsg);
                                }
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
                            }
                        });
                    });
                } else {
                    data.files = [];
                }
            },

            progressall: function(e, data){
                var percentInt = data.loaded / data.total * 100,
                    percentVal = parseInt(percentInt, 10) + '%',
                    doneAt;
                // Firefox makes ProgressEvent.loaded equal ProgressEvent.total only
                // after receiving a response from the server (see Mozilla bug 637002),
                // so for Firefox we jump the gun a little.
                if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
                    doneAt = 95;
                } else {
                    doneAt = 99;
                }
                if (percentInt >= doneAt) {
                    bar.hide();
121 122 123 124

                    // Start feedback with delay so that current stage of
                    // import properly updates in session
                    setTimeout(function () { Import.pollStatus(); }, 3000);
125 126 127 128 129 130 131 132
                } else {
                    bar.show();
                    fill.width(percentVal).html(percentVal);
                }
            },
            sequentialUploads: true,
            notifyOnError: false
        });
133 134 135 136 137 138 139 140 141 142 143 144 145


        var showImportSubmit = function (e) {
            var filepath = $(this).val();

            if (filepath.substr(filepath.length - 6, 6) === 'tar.gz') {
                $('.error-block').hide();
                $('.file-name').html($(this).val().replace('C:\\fakepath\\', ''));
                $('.file-name-block').show();
                chooseBtn.hide();
                submitBtn.show();
                $('.progress').show();
            } else {
146 147 148 149
                var msg = gettext('File format not supported. Please upload a file with a {file_extension} extension.')
                    .replace('{file_extension}', '<code>tar.gz</code>');

                $('.error-block').html(msg).show();
150 151 152 153 154 155 156 157 158 159 160
            }
        };

        domReady(function () {
            // import form setup
            $('.view-import .file-input').bind('change', showImportSubmit);
            $('.view-import .choose-file-button, .view-import .choose-file-button-inline').bind('click', function (e) {
                e.preventDefault();
                $('.view-import .file-input').click();
            });
        });
161 162
    };
});