Skip to content
Snippets Groups Projects
file-sink.js 15.8 KiB
Newer Older
import {i18n} from './i18n';
import {css, html} from 'lit-element';
import {ScopedElementsMixin} from '@open-wc/scoped-elements';
import DBPLitElement from '@dbp-toolkit/common/dbp-lit-element';
import * as commonUtils from "@dbp-toolkit/common/utils";
import {Icon, MiniSpinner} from '@dbp-toolkit/common';
import * as commonStyles from '@dbp-toolkit/common/styles';
import {NextcloudFilePicker} from "./dbp-nextcloud-file-picker";
import {classMap} from 'lit-html/directives/class-map.js';
import FileSaver from 'file-saver';
import { send } from '@dbp-toolkit/common/notification';
import {Clipboard} from "@dbp-toolkit/file-handling/src/clipboard";
export class FileSink extends ScopedElementsMixin(DBPLitElement) {
        this.lang = 'de';
        this.nextcloudAuthUrl = '';
        this.nextcloudWebDavUrl = '';
        this.nextcloudPath = '';
        this.nextcloudFileURL = '';
        this.buttonLabel = '';
        this.filename = "files.zip";
        this.files = [];
        this.activeTarget = 'local';
        this.enabledTargets = 'local';
        this.firstOpen = true;
        this.fullsizeModal = false;
        this.nextcloudAuthInfo = '';

        this.initialFileHandlingState = {target: '', path: ''};
            'dbp-icon': Icon,
            'dbp-mini-spinner': MiniSpinner,
            'dbp-nextcloud-file-picker': NextcloudFilePicker,
            'dbp-clipboard': Clipboard,
        };
    }

    /**
     * See: https://lit-element.polymer-project.org/guide/properties#initialize
     */
    static get properties() {
        return {
            ...super.properties,
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            context: {type: String, attribute: 'context'},
            lang: {type: String},
            filename: {type: String},
            files: {type: Array, attribute: false},
            enabledTargets: {type: String, attribute: 'enabled-targets'},
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            nextcloudAuthUrl: {type: String, attribute: 'nextcloud-auth-url'},
            nextcloudWebDavUrl: {type: String, attribute: 'nextcloud-web-dav-url'},
            nextcloudName: {type: String, attribute: 'nextcloud-name'},
            nextcloudFileURL: {type: String, attribute: 'nextcloud-file-url'},
            nextcloudAuthInfo: {type: String, attribute: 'nextcloud-auth-info'},
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            buttonLabel: {type: String, attribute: 'button-label'},
            isDialogOpen: {type: Boolean, attribute: false},
            activeTarget: {type: String, attribute: 'active-target'},
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            firstOpen: {type: Boolean, attribute: false},
            nextcloudPath: {type: String, attribute: false},
            fullsizeModal: { type: Boolean, attribute: 'fullsize-modal' },
            initialFileHandlingState: {type: Object, attribute: 'initial-file-handling-state'},
Steinwender, Tamara's avatar
Steinwender, Tamara committed

    connectedCallback() {
        super.connectedCallback();

        this.updateComplete.then(() => {
        });
    }

        // see: https://stuk.github.io/jszip/
        let JSZip = (await import('jszip/dist/jszip.js')).default;
        let zip = new JSZip();
        let fileNames = [];

        // download one file not compressed!
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (this.files.length === 1) {
            FileSaver.saveAs(this.files[0], this.files[0].filename);
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            this.closeDialog();
            return;
        }

        // download all files compressed
            let fileName = file.name;

            // add pseudo-random string on duplicate file name
            if (fileNames.indexOf(fileName) !== -1) {
                fileName = commonUtils.getBaseName(fileName) + "-" + Math.random().toString(36).substring(7) + "." +
                    commonUtils.getFileExtension(fileName);
            }

            fileNames.push(fileName);
            zip.file(fileName, file);
        });

        let content = await zip.generateAsync({type:"blob"});

        // see: https://github.com/eligrey/FileSaver.js#readme
        FileSaver.saveAs(content, this.filename || "files.zip");
Steinwender, Tamara's avatar
Steinwender, Tamara committed

        this.closeDialog();
    }

    update(changedProperties) {
        changedProperties.forEach((oldValue, propName) => {
            switch (propName) {
                case "lang":
                    i18n.changeLanguage(this.lang);
                    break;
                case "enabledTargets":
                    if (!this.hasEnabledDestination(this.activeTargets)) {
                        this.activeTargets = this.enabledTargets.split(",")[0];
                    if (this.files.length !== 0) {
                        if (this.enabledTargets.includes("clipboard")) {
                            const clipboardSink = this._("#clipboard-file-picker");
                                this._("#clipboard-file-picker").filesToSave = [...this.files];
                case "initialFileHandlingState":
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    //check if default destination is set
                    if (this.firstOpen) {
                        this.nextcloudPath = this.initialFileHandlingState.path;
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    }
                    break;
        return this.enabledTargets.split(',').includes(source);
    async uploadToNextcloud(directory) {
        let that = this;
        const element = that._('#nextcloud-file-picker');
        await element.uploadFiles(that.files, directory);
        this.sendDestination();
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (event.detail > 0) {
            send({
                "summary": i18n.t('file-sink.upload-success-title'),
                "body": i18n.t('file-sink.upload-success-body', {name: this.nextcloudName, count: event.detail}),
                "type": "success",
                "timeout": 5,
            });
        }
    sendDestination() {
        let data = {};
Bekerle, Patrizio's avatar
Bekerle, Patrizio committed
        if (this.activeTarget === 'nextcloud') {
            data = {"target": this.activeTarget, "path": this._("#nextcloud-file-picker").directoryPath};
            data = {"target": this.activeTarget};
        this.sendSetPropertyEvent('initial-file-handling-state', data);
    preventDefaults (e) {
        e.preventDefault();
        e.stopPropagation();
    }

Steinwender, Tamara's avatar
Steinwender, Tamara committed
    loadWebdavDirectory() {
        const filePicker = this._('#nextcloud-file-picker');
        if (filePicker) {
            filePicker.checkSessionStorage().then(contents => {
                if (filePicker.webDavClient !== null) {
                    filePicker.loadDirectory(filePicker.directoryPath);
                }
            });
        if (this.enabledTargets.includes('nextcloud')) {
            this.loadWebdavDirectory();
        }
        if (this.enabledTargets.includes('clipboard')) {
            if (this._('#clipboard-file-picker')._("#select_all")) {
                this._('#clipboard-file-picker')._("#select_all").checked = false;
            }
        }
        const filePicker = this._('#modal-picker');
        if (filePicker) {
            MicroModal.show(filePicker, {
                disableScroll: true,
                onClose: modal => { this.isDialogOpen = false; },
            });
        }

        //check if default destination is set
        if (this.initialFileHandlingState.target !== '' && typeof this.initialFileHandlingState.target !== 'undefined'  && this.firstOpen) {
            this.activeTarget = this.initialFileHandlingState.target;
            this.nextcloudPath = this.initialFileHandlingState.path;
            const filePicker = this._('#nextcloud-file-picker');

            if (filePicker && filePicker.webDavClient !== null) {
                filePicker.loadDirectory(this.initialFileHandlingState.path);
            this.firstOpen = false;
        }
        this.isDialogOpen = true;
    }
    closeDialog(e) {
        this.sendDestination();
        MicroModal.close(this._('#modal-picker'));
        this.isDialogOpen = false;
        if (this.enabledTargets.includes('clipboard')) {
                   id="clipboard-file-picker"
                   subscribe="clipboard-files:clipboard-files"
                   show-additional-buttons
                   mode="file-sink"
                   lang="${this.lang}"
                   auth-url="${this.nextcloudAuthUrl}"
                   enabled-targets="${this.enabledTargets}"
                   nextcloud-auth-url="${this.nextcloudAuthUrl}"
                   nextcloud-web-dav-url="${this.nextcloudWebDavUrl}"
                   nextcloud-name="${this.nextcloudName}"
                   nextcloud-file-url="${this.nextcloudFileURL}"
                   @dbp-clipboard-file-picker-file-uploaded="${(event) => {
                this.closeDialog(event);}}">
    getNextcloudHtml() {
        if (this.enabledTargets.includes('nextcloud') && this.nextcloudWebDavUrl !== "" && this.nextcloudAuthUrl !== "") {
            return html`
                <dbp-nextcloud-file-picker id="nextcloud-file-picker"
                   class="${classMap({hidden: this.nextcloudWebDavUrl === "" || this.nextcloudAuthUrl === ""})}"
                   directories-only
                   max-selected-items="1"
                   select-button-text="${i18n.t('file-sink.select-directory')}"
                   ?disabled="${this.disabled}"
                   lang="${this.lang}"
                   auth-url="${this.nextcloudAuthUrl}"
                   web-dav-url="${this.nextcloudWebDavUrl}"
                   nextcloud-name="${this.nextcloudName}"
                   auth-info="${this.nextcloudAuthInfo}"
                   directory-path="${this.nextcloudPath}"
                   nextcloud-file-url="${this.nextcloudFileURL}"
                   @dbp-nextcloud-file-picker-file-uploaded="${(event) => {
                       this.uploadToNextcloud(event.detail);
                   }}"
                   @dbp-nextcloud-file-picker-file-uploaded-finished="${(event) => {
                       this.finishedFileUpload(event);
                   }}">
                </dbp-nextcloud-file-picker>`;
        }
        return html``;
            ${commonStyles.getThemeCSS()}
            ${commonStyles.getGeneralCSS()}
            ${commonStyles.getButtonCSS()}
            .modal-container-full-size{
                min-width: 100%;
                min-height: 100%;
            }
            
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
            }

            .block {
                margin-bottom: 10px;
            }
            <vpu-notification lang="de" client-id="my-client-id"></vpu-notification>
            <div class="modal micromodal-slide" id="modal-picker" aria-hidden="true">
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                <div class="modal-overlay" tabindex="-1">
                    <div class="modal-container ${classMap({"modal-container-full-size": this.fullsizeModal})}" role="dialog" aria-modal="true" aria-labelledby="modal-picker-title">
                        <nav class="modal-nav">
                            <div title="${i18n.t('file-sink.nav-local')}"
                                 @click="${() => { this.activeTarget = "local"; }}"
                                 class="${classMap({"active": this.activeTarget === "local", hidden: !this.hasEnabledDestination("local")})}">
                                <dbp-icon class="nav-icon" name="laptop"></dbp-icon>
                                 @click="${() => { this.activeTarget = "nextcloud"; this.loadWebdavDirectory();}}"
                                 class="${classMap({"active": this.activeTarget === "nextcloud", hidden: !this.hasEnabledDestination("nextcloud") || this.nextcloudWebDavUrl === "" || this.nextcloudAuthUrl === ""})}">
                                <dbp-icon class="nav-icon" name="cloud"></dbp-icon>
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                            <div title="${i18n.t('file-sink.clipboard')}"
                                 @click="${() => { this.activeTarget = "clipboard"; }}"
                                 class="${classMap({"active": this.activeTarget === "clipboard", hidden: (!this.hasEnabledDestination("clipboard")) })}">
                                <dbp-icon class="nav-icon" name="clipboard"></dbp-icon>
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                                <p>${i18n.t('file-sink.clipboard')}</p>
                                <button title="${i18n.t('file-sink.modal-close')}" class="modal-close"  aria-label="Close modal" @click="${() => { this.closeDialog();}}">
                                        <dbp-icon title="${i18n.t('file-sink.modal-close')}" name="close" class="close-icon"></dbp-icon>
                                </button> 
                                <p class="modal-context"> ${this.context}</p>
                        </div>
                            
                        
                        <main class="modal-content" id="modal-picker-content">
                            <div class="source-main ${classMap({"hidden": this.activeTarget !== "local"})}">
                                        ${i18n.t('file-sink.local-intro', {'count': this.files.length})}
                                    </div>
                                    <button class="button is-primary"
                                            ?disabled="${this.disabled}"
                                            @click="${() => { this.downloadCompressedFiles(); }}">
                                        ${i18n.t('file-sink.local-button', {'count': this.files.length})}
                            <div class="source-main ${classMap({"hidden": this.activeTarget !== "nextcloud" || this.nextcloudWebDavUrl === "" || this.nextcloudAuthUrl === ""})}">
                            <div class="source-main ${classMap({"hidden": this.activeTarget !== "clipboard"})}">