Skip to content
Snippets Groups Projects
dbp-nextcloud-file-picker.js 61.5 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 {Icon, MiniSpinner} from '@dbp-toolkit/common';
import * as commonUtils from '@dbp-toolkit/common/utils';
import * as commonStyles from '@dbp-toolkit/common/styles';
import {createClient} from 'webdav/web';
import {classMap} from 'lit-html/directives/class-map.js';
import {humanFileSize} from '@dbp-toolkit/common/i18next';
import Tabulator from 'tabulator-tables';
import MicroModal from './micromodal.es';
import {name as pkgName} from './../package.json';
import * as fileHandlingStyles from './styles';

/**
 * NextcloudFilePicker web component
 */
export class NextcloudFilePicker extends ScopedElementsMixin(DBPLitElement) {
    constructor() {
        super();
        this.lang = 'de';
        this.authUrl = '';
        this.webDavUrl = '';
        this.nextcloudName = 'Nextcloud';
        this.nextcloudFileURL = '';
        this.loginWindow = null;
        this.isPickerActive = false;
        this.statusText = '';
        this.lastDirectoryPath = '/';
        this.webDavClient = null;
        this.tabulatorTable = null;
        this.allowedMimeTypes = '*/*';
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        this.directoriesOnly = false;
        this.maxSelectedItems = true;
        this._onReceiveWindowMessage = this.onReceiveWindowMessage.bind(this);
        this.folderIsSelected = i18n.t('nextcloud-file-picker.load-in-folder');
        this.generatedFilename = '';
        this.customFilename = '';
        this.uploadFileObject = null;
        this.uploadFileDirectory = null;
        this.fileNameCounter = 1;
        this.activeDirectoryRights = 'RGDNVCK';
        this.activeDirectoryACL = '';
        this.forAll = false;
        this.selectAllButton = true;
        this.abortUploadButton = false;
        this.abortUpload = false;
    }

    static get scopedElements() {
        return {
            'dbp-icon': Icon,
            'dbp-mini-spinner': MiniSpinner,
        };
    }

    /**
     * See: https://lit-element.polymer-project.org/guide/properties#initialize
     */
    static get properties() {
        return {
            ...super.properties,
            lang: { type: String },
            authUrl: { type: String, attribute: 'auth-url' },
            webDavUrl: { type: String, attribute: 'web-dav-url' },
            nextcloudFileURL: { type: String, attribute: 'nextcloud-file-url' },
            nextcloudName: { type: String, attribute: 'nextcloud-name' },
            isPickerActive: { type: Boolean, attribute: false },
            statusText: { type: String, attribute: false },
            folderIsSelected: { type: String, attribute: false },
            authInfo: { type: String, attribute: 'auth-info' },
            directoryPath: { type: String, attribute: 'directory-path' },
            allowedMimeTypes: { type: String, attribute: 'allowed-mime-types' },
            directoriesOnly: { type: Boolean, attribute: 'directories-only' },
            maxSelectedItems: { type: Number, attribute: 'max-selected-items' },
            loading: { type: Boolean, attribute: false },
            replaceFilename: { type: String, attribute: false },
            uploadFileObject: { type: Object, attribute: false },
            uploadFileDirectory: { type: String, attribute: false },
            activeDirectoryRights: { type: String, attribute: false },
            activeDirectoryACL: { type: String, attribute: false },
            selectAllButton: { type: Boolean, attribute: false },
            abortUploadButton: { type: Boolean, attribute: false },
            isSelected: { type: Boolean, attribute: false },
    }

    update(changedProperties) {
        changedProperties.forEach((oldValue, propName) => {
            switch (propName) {
                case "lang":
                    i18n.changeLanguage(this.lang);
                    break;
            }
        });

        super.update(changedProperties);
    }

    disconnectedCallback() {
        window.removeEventListener('message', this._onReceiveWindowMessage);
        super.disconnectedCallback();

    connectedCallback() {
        super.connectedCallback();
        this.updateComplete.then(() => {
            // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
            window.addEventListener('message', this._onReceiveWindowMessage);

            // see: http://tabulator.info/docs/4.7
            this.tabulatorTable = new Tabulator(this._("#directory-content-table"), {
                selectable: this.maxSelectedItems,
                selectableRangeMode: "drag",
                placeholder:this.directoriesOnly ? i18n.t('nextcloud-file-picker.no-data') :  i18n.t('nextcloud-file-picker.no-data-type'),
                resizableColumns:false,
                    {title: "", field: "type", align:"center", headerSort:false, width:50, responsive:1, formatter: (cell, formatterParams, onRendered) => {
                            const icon_tag =  that.getScopedTagName("dbp-icon");
                            let disabled = this.directoriesOnly ? "nextcloud-picker-icon-disabled" : "";
                            let icon = `<${icon_tag} name="empty-file" class="nextcloud-picker-icon ` + disabled + `"></${icon_tag}>`;
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                            return (cell.getValue() === "directory") ? `<${icon_tag} name="folder" class="nextcloud-picker-icon"></${icon_tag}>` : icon;
                    {title: i18n.t('nextcloud-file-picker.filename'), responsive: 0, widthGrow:5,  minWidth: 150, field: "basename", sorter: "alphanum",
                        formatter: (cell) => {
                            var data = cell.getRow().getData();
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                            if (data.edit) {
                                cell.getElement().classList.add("fokus-edit");
                            }
                            return cell.getValue();
                        }},
                    {title: i18n.t('nextcloud-file-picker.size'), responsive: 4, widthGrow:1, minWidth: 50, field: "size", formatter: (cell, formatterParams, onRendered) => {
                            return cell.getRow().getData().type === "directory" ? "" : humanFileSize(cell.getValue());}},
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    {title: i18n.t('nextcloud-file-picker.mime-type'), responsive: 2, widthGrow:1, minWidth: 20, field: "mime", formatter: (cell, formatterParams, onRendered) => {
Bekerle, Patrizio's avatar
Bekerle, Patrizio committed
                            if (typeof cell.getValue() === 'undefined') {
                            const [, fileSubType] = cell.getValue().split('/');
                    {title: i18n.t('nextcloud-file-picker.last-modified'), responsive: 3, widthGrow:1, minWidth: 100, field: "lastmod",sorter: (a, b, aRow, bRow, column, dir, sorterParams) => {
                            const a_timestamp = Date.parse(a);
                            const b_timestamp = Date.parse(b);
                        }, formatter:function(cell, formatterParams, onRendered) {
                            const d = Date.parse(cell.getValue());
                            const timestamp = new Date(d);
                            const year = timestamp.getFullYear();
                            const month = ("0" + (timestamp.getMonth() + 1)).slice(-2);
                            const date = ("0" + timestamp.getDate()).slice(-2);
                            const hours = ("0" + timestamp.getHours()).slice(-2);
                            const minutes = ("0" + timestamp.getMinutes()).slice(-2);
                            return date + "." + month + "." + year + " " + hours + ":" + minutes;
                    {title: "rights", field: "props.permissions", visible: false},
                    {title: "acl", field: "props.acl-list.acl.acl-permissions", visible: false}
                    {column:"basename", dir:"asc"},
                    {column:"type", dir:"asc"},
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                rowFormatter: (row) => {
                    let data = row.getData();
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    if (!this.checkFileType(data, this.allowedMimeTypes)) {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                        row.getElement().classList.add("no-select");
                        row.getElement().classList.remove("tabulator-selectable");
                    }
                    if (this.directoriesOnly && typeof data.mime !== 'undefined') {
                        row.getElement().classList.add("no-select");
                        row.getElement().classList.remove("tabulator-selectable");
                    }
                },
                rowSelectionChanged: (data, rows) => {
Bekerle, Patrizio's avatar
Bekerle, Patrizio committed
                    if (data.length > 0  && this.directoriesOnly) {
                        this.folderIsSelected = i18n.t('nextcloud-file-picker.load-to-folder');
                    }
                    else {
                        this.folderIsSelected = i18n.t('nextcloud-file-picker.load-in-folder');
                    }
                },
                rowClick: (e, row) => {
                    const data = row.getData();

Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    if (!row.getElement().classList.contains("no-select")) {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                        if (this.directoriesOnly) {
                            // comment out if you want to navigate through folders with double click
                            const data = row.getData();
                            this.directoryClicked(e, data);
                            this.folderIsSelected = i18n.t('nextcloud-file-picker.load-in-folder');
                        }
                        else
                        {
                            switch(data.type) {
                                case "directory":
                                    this.directoryClicked(e, data);
                                    break;
                                case "file":
                                    this.isSelected = this.tabulatorTable.getSelectedRows().length > 0;
                                    if (this.tabulatorTable.getSelectedRows().length === this.tabulatorTable.getRows().filter(row => row.getData().type != 'directory' && this.checkFileType(row.getData(), this.allowedMimeTypes)).length) {
                                        this.selectAllButton = false;
                                        this.selectAllButton = true;
                                    }
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                                    break;
                            }
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    else{
                        row.deselect();
                    }
                rowDblClick: (e, row) => {
                    // comment this in for double click directory change
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                   /* if (this.directoriesOnly) {
                        const data = row.getData();
                        this.directoryClicked(e, data);
                        this.folderIsSelected = i18n.t('nextcloud-file-picker.load-in-folder');
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    }*/
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                },
                rowAdded: (row) => {
                    row.getElement().classList.toggle("addRowAnimation");

            // Strg + click select mode on desktop
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            /*if (this.tabulatorTable.browserMobile === false) {
                this.tabulatorTable.options.selectableRangeMode = "click";
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            if (typeof this.allowedMimeTypes !== 'undefined' && !this.directoriesOnly) {
                this.tabulatorTable.setFilter(this.checkFileType, this.allowedMimeTypes);
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            }
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            // comment this in to show only directories in filesink
            /*
            if (typeof this.directoriesOnly !== 'undefined' && this.directoriesOnly) {
                this.tabulatorTable.setFilter([
                    {field:"type", type:"=", value:"directory"},
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                ]);
            // add folder on enter
            this._('#new-folder').addEventListener('keydown', function(e) {
                if (e.keyCode === 13) {
                    that.addFolder();
                }
            });
    /**
     * check mime type of row
     *
     * @param data
     * @param filterParams
     */
    checkFileType(data, filterParams) {
        if (typeof data.mime === 'undefined') {
            return true;
        }
        const [fileMainType, fileSubType] = data.mime.split('/');
        const mimeTypes = filterParams.split(',');
        let deny = true;

        mimeTypes.forEach((str) => {
            const [mainType, subType] = str.split('/');
            deny = deny && ((mainType !== '*' && mainType !== fileMainType) || (subType !== '*' && subType !== fileSubType));
        });

        return !deny;
    }

    openFilePicker() {
        if (this.webDavClient === null) {
            this.statusText = i18n.t('nextcloud-file-picker.auth-progress');
            const authUrl = this.authUrl + "?target-origin=" + encodeURIComponent(window.location.href);
            this.loginWindow = window.open(authUrl, "Nextcloud Login",
                "width=400,height=400,menubar=no,scrollbars=no,status=no,titlebar=no,toolbar=no");
            console.log("open nextcloud filepicker, no webdavclient");
        } else {
            this.loadDirectory(this.directoryPath, this.webDavClient);
            console.log("load in nextcloud webcomponent");
    }

    onReceiveWindowMessage(event) {
        if (this.webDavClient === null)
        {
            const data = event.data;
            if (data.type === "webapppassword") {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                if (this.loginWindow !== null) {
                    this.loginWindow.close();
                // see https://github.com/perry-mitchell/webdav-client/blob/master/API.md#module_WebDAV.createClient
                this.webDavClient = createClient(
                    data.webdavUrl || this.webDavUrl + "/" + data.loginName,
                    {
                        username: data.loginName,
                        password: data.token
                    }
                );
                this.loadDirectory(this.directoryPath);
            }
        }
    }

    /**
     * Loads the directory from WebDAV
     *
     * @param path
     */
    loadDirectory(path) {
        if (typeof this.directoryPath === 'undefined' || this.directoryPath === undefined) {
           this.directoryPath = '';
        }
        if (path === undefined) {
        console.log("load nextcloud directory", path);
        this.selectAllButton = true;
        this.loading = true;
        this.statusText = i18n.t('nextcloud-file-picker.loadpath-nextcloud-file-picker', {name: this.nextcloudName});
        this.lastDirectoryPath = this.directoryPath;
        this.directoryPath = path;

        // see https://github.com/perry-mitchell/webdav-client#getdirectorycontents
        if (this.webDavClient === null) {
            // client is broken reload try to reset & reconnect
            this.tabulatorTable.clearData();
            this.webDavClient = null;
            let reloadButton = html`${i18n.t('nextcloud-file-picker.something-went-wrong')} <button class="button"
                            title="${i18n.t('nextcloud-file-picker.refresh-nextcloud-file-picker')}"
                            @click="${async () => { this.openFilePicker(); } }"><dbp-icon name="reload"></button>`;
            this.loading = false;
            this.statusText = reloadButton;
        this.webDavClient
            .getDirectoryContents(path, {details: true, data: "<?xml version=\"1.0\"?>" +
                    "<d:propfind  xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\"  xmlns:ocs=\"http://open-collaboration-services.org/ns\">" +
                    "  <d:prop>" +
                    "        <d:getlastmodified />" +
                    "        <d:resourcetype />" +
                    "        <d:getcontenttype />" +
                    "        <d:getcontentlength />" +
                    "        <d:getetag />" +
                    "        <oc:permissions />" +
                    "        <nc:acl-list>" +
                    "           <nc:acl>" +
                    "               <nc:acl-permissions />" +
                    "           </nc:acl>" +
                    "  </d:prop>" +
                    "</d:propfind>"})
            .then(contents => {
                //console.log("------", contents);
                this.statusText = "";
                this.tabulatorTable.setData(contents.data);
                this.isPickerActive = true;
                this._(".nextcloud-content").scrollTop = 0;
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                if (!this.activeDirectoryRights.includes("CK") && !this.activeDirectoryRights.includes("NV")) {
                    this._("#download-button").setAttribute("disabled", "true");
                }
                else {
                    this._("#download-button").removeAttribute("disabled");
                }
            }).catch(error => {
                console.error(error.message);

                // on Error: try to reload with home directory
                if ((path !== "/" && path !== "") && this.webDavClient !== null && error.message.search("401") === -1) {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    console.log("error in load directory");
                    this.directoryPath = "";
Steinwender, Tamara's avatar
Steinwender, Tamara committed

Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    this.statusText = html`<span class="error"> ${i18n.t('nextcloud-file-picker.webdav-error', {error: error.message})} </span>`;
                    this.isPickerActive = false;
                    this.tabulatorTable.clearData();
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    this.webDavClient = null;
                    let reloadButton = html`${i18n.t('nextcloud-file-picker.something-went-wrong')} <button class="button"
                                title="${i18n.t('nextcloud-file-picker.refresh-nextcloud-file-picker')}"
                                @click="${async () => { this.openFilePicker(); } }"><dbp-icon name="reload"></button>`;
                    this.loading = false;
                    this.statusText = reloadButton;
    /**
     * Event Triggered when a directory in tabulator table is clicked
     *
     * @param event
     * @param file
     */
    directoryClicked(event, file) {
        // save rights of clicked directory
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (typeof file.props !== 'undefined') {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            this.activeDirectoryRights = file.props.permissions;
            if (typeof  file.props['acl-list'] !== "undefined" &&
                typeof  file.props['acl-list']['acl']['acl-permissions'] !== "undefined" && file.props['acl-list']['acl']['acl-permissions']) {
                this.activeDirectoryACL = file.props['acl-list']['acl']['acl-permissions'];
            } else {
                this.activeDirectoryACL = '';
            }
        } else {
            this.activeDirectoryRights = 'SGDNVCK';
        this.loadDirectory(file.filename);
        event.preventDefault();
    }

    downloadFiles(files) {
        files.forEach((fileData) => this.downloadFile(fileData));
        this.tabulatorTable.deselectRow();
        const data = {"count": files.length};
        const event = new CustomEvent("dbp-nextcloud-file-picker-number-files",
            { "detail": data, bubbles: true, composed: true });
        this.dispatchEvent(event);

        if (files.length > 0) {
            this.sendSetPropertyEvent(
                'analytics-event',
                {category: 'FileHandlingNextcloud', action: 'DownloadFiles', name: files.length});
        }
    downloadFile(fileData) {
        this.statusText = "Loading " + fileData.filename + "...";

        // https://github.com/perry-mitchell/webdav-client#getfilecontents
        this.webDavClient
            .getFileContents(fileData.filename)
            .then(contents => {
                // create file to send via event
                const file = new File([contents], fileData.basename, { type: fileData.mime });
                // send event
                const data = {"file": file, "data": fileData};
                const event = new CustomEvent("dbp-nextcloud-file-picker-file-downloaded",
                    { "detail": data, bubbles: true, composed: true });
                this.dispatchEvent(event);
                this.statusText = "";
            }).catch(error => {
                console.error(error.message);
                this.statusText = html`<span class="error"> ${i18n.t('nextcloud-file-picker.webdav-error', {error: error.message})} </span>`;
    /**
     * Send the directory to filesink
     *
     * @param directory
     */
        this.tabulatorTable.deselectRow();
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (!directory[0]) {
            path = this.directoryPath;
        }
        else {
            path = directory[0].filename;
        }
        this.statusText = i18n.t('nextcloud-file-picker.upload-to', {path: path});

        const event = new CustomEvent("dbp-nextcloud-file-picker-file-uploaded",
            { "detail": path, bubbles: true, composed: true });
    /**
     * Upload Files to a directory
     *
     * @param files
     * @param directory
     */
    uploadFiles(files, directory) {
        this.loading = true;
        this.statusText = i18n.t('nextcloud-file-picker.upload-to', {path: directory});
        this.forAll = false;
        this.setRepeatForAllConflicts();

        if (files.length > 0) {
            this.sendSetPropertyEvent(
                'analytics-event',
                {category: 'FileHandlingNextcloud', action: 'UploadFiles', name: files.length});
        }
    /**
     * Upload a single file from this.filelist to given directory
     *
     * @param directory
     */
        if (this.abortUpload) {
            this.abortUpload = false;
            this.abortUploadButton = false;
            this.forAll = false;
            this.loading = false;
            this.statusText = i18n.t('nextcloud-file-picker.abort-message');
            this._("#replace_mode_all").checked = false;
            return;
        }
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (this.fileList.length !== 0) {
            let file = this.fileList[0];
            this.replaceFilename = file.name;
            let path = directory + "/" + file.name;
            // https://github.com/perry-mitchell/webdav-client#putfilecontents
            this.loading = true;
            this.statusText = i18n.t('nextcloud-file-picker.upload-to', {path: path});
            await this.webDavClient
                    .putFileContents(path, file,  { overwrite: false, onUploadProgress: progress => {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                            /* console.log(`Uploaded ${progress.loaded} bytes of ${progress.total}`);*/
                            that.uploadFile(directory);
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                            if (error.message.search("412") !== -1 || error.message.search("403") !== -1) {
                                this.generatedFilename = this.getNextFilename();
                                this._("#replace-filename").value = this.generatedFilename;
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                                if (this.forAll) {
                                    this.uploadFileObject = file;
                                    this.uploadFileDirectory = directory;
                                    this.uploadFileAfterConflict();
                                }
                                else {
                                    this.replaceModalDialog(file, directory);
                                }
            this._("#replace_mode_all").checked = false;
            this.forAll = false;
            this.customFilename = '';
            const event = new CustomEvent("dbp-nextcloud-file-picker-file-uploaded-finished",
                {  bubbles: true, composed: true , detail: this.uploadCount});
            this.uploadCount = 0;
            this.abortUpload = false;
            this.abortUploadButton = false;
    /**
     * Upload a file after a conflict happens on webdav side
     *
     */
    async uploadFileAfterConflict() {
        if (this.abortUpload) {
            this.abortUpload = false;
            this.abortUploadButton = false;
            this.forAll = false;
            this.loading = false;
            this.statusText = i18n.t('nextcloud-file-picker.abort-message');
            this._("#replace_mode_all").checked = false;
            return;
        }
        let path = "";
        let overwrite = false;
        let file = this.uploadFileObject;
        let directory = this.uploadFileDirectory;

        if (this._("input[name='replacement']:checked").value === "ignore") {
            this.forAll ? this.fileList = [] : this.fileList.shift();
        } else if (this._("input[name='replacement']:checked").value === "new-name") {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            if (this.generatedFilename !== this._("#replace-filename").value) {
                this.customFilename = this._("#replace-filename").value;
            }
            path = directory + "/" + this._("#replace-filename").value;
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            MicroModal.close(this._("#replace-modal"));
            this.replaceFilename = this._("#replace-filename").value;
        } else {
            path = directory + "/" + this.uploadFileObject.name;
        this.loading = true;
        this.statusText = i18n.t('nextcloud-file-picker.upload-to', {path: path});

        // https://github.com/perry-mitchell/webdav-client#putfilecontents
        await this.webDavClient
            .putFileContents(path, file, {
                overwrite: overwrite, onUploadProgress: progress => {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    /*console.log(`Uploaded ${progress.loaded} bytes of ${progress.total}`);*/
                }
            }).then(content => {
                MicroModal.close(this._("#replace-modal"));
                that.fileList.shift();
                that.uploadFile(directory);
            }).catch(error => {
                if (error.message.search("412") !== -1) {
                    MicroModal.close(that._("#replace-modal"));
                    this.generatedFilename = this.getNextFilename();
                    this._("#replace-filename").value = this.generatedFilename;
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                    if (this.forAll) {
                        this.uploadFileObject = file;
                        this.uploadFileDirectory = directory;
                        this.uploadFileAfterConflict();
                    }
                    else {
                        this.replaceModalDialog(file, directory);
                    }
        this.fileNameCounter = 1;
    /**
     * Check permissions of a given file in the active directory
     * no rename: if you dont have create permissions
     * no replace: if you dont have write permissions
     *
     * R = Share, S = Shared Folder, M = Group folder or external source, G = Read, D = Delete, NV / NVW = Write, CK = Create
     *
     * @param file
    checkRights(file) {

        // nextcloud permissions
        let active_directory_perm = this.activeDirectoryRights;
        let rows = this.tabulatorTable.searchRows("basename", "=", this.replaceFilename);
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (typeof rows[0] !== 'undefined' && rows[0]) {
            file_perm = rows[0].getData().props.permissions;
        /* ACL permissions: If ACL > permssions comment this in
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (this.activeDirectoryACL !== '') {
            active_directory_perm = "MG";
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            if (this.activeDirectoryACL & (1 << (3 - 1))) {
                active_directory_perm = "CK";
                console.log("ACL CREATE");
            }
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            if (this.activeDirectoryACL & (1 << (2 - 1))) {
                active_directory_perm += "NV";
                console.log("ACL WRITE");
            }
        // if file has acl rights take that
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (typeof rows[0].getData().props['acl-list'] !== 'undefined' && rows[0].getData().props['acl-list'] &&
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            rows[0].getData().props['acl-list']['acl']['acl-permissions'] !== '') {
            console.log("FILE HAS ACL");
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            if (rows[0].getData().props['acl-list']['acl']['acl-permissions'] & (1 << (3 - 1))) {
                console.log("FILE ACL CREATE");
            }
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            if (rows[0].getData().props['acl-list']['acl']['acl-permissions'] & (1 << (2 - 1))) {
                console.log("FILE ACL WRITE");
            }
        }
        */
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (active_directory_perm.includes("CK") && file_perm.includes("NV")) {
        // read only file but you can write to directory = only create and no edit
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (active_directory_perm.includes("CK") && !file_perm.includes("NV")) {
            return 1;
        }

        // only edit and no create
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (!active_directory_perm.includes("CK") && file_perm.includes("NV")) {
        // read only directory and read only file
        return 0;

     * Open the replace Modal Dialog with gui where forbidden actions are disabled
     * @param file
     * @param directory
     */
    replaceModalDialog(file, directory) {
        this.uploadFileObject = file;
        this.uploadFileDirectory = directory;
        let rights = this.checkRights(file);
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (rights === 0) {
            this.statusText = i18n.t('nextcloud-file-picker.readonly');
        // read only file but you can write to directory = only create and no edit
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        else if (rights === 1) {
            this.statusText = i18n.t('nextcloud-file-picker.onlycreate');
            this._("#replace-replace").setAttribute("disabled", "true");
            this._("#replace-new-name").removeAttribute("disabled");
            this._("#replace-replace").checked = false;
            this._("#replace-new-name").checked = true;
            this.setInputFieldVisibility();
            this._("#replace-new-name").focus();
        }
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        else if (rights === 2) {
            this.statusText = i18n.t('nextcloud-file-picker.onlyedit');
            this._("#replace-new-name").setAttribute("disabled", "true");
            this._("#replace-replace").removeAttribute("disabled");
            this._("#replace-new-name").checked = false;
            this._("#replace-replace").checked = true;
            this.setInputFieldVisibility();
            this._("#replace-replace").focus();
        }
        else {
            this._("#replace-new-name").removeAttribute("disabled");
            this._("#replace-replace").removeAttribute("disabled");
            this._("#replace-replace").checked = false;
            this._("#replace-new-name").checked = true;
            this.setInputFieldVisibility();
            this._("#replace-new-name").focus();
        }
        MicroModal.show(this._('#replace-modal'), {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            disableScroll: true,
            onClose: modal => {
                this.statusText = "";
                this.loading = false;},
        });
Steinwender, Tamara's avatar
Steinwender, Tamara committed
    closeDialog(e) {
        MicroModal.close(this._('#modal-picker'));
    }

     * Returns a filename with the next counter number.
     * @returns {string} The next filename
        let nextFilename = "";
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (this.forAll && this.customFilename !== '') {
            splitFilename = this.customFilename.split(".");
        }
        else {
            splitFilename = this.replaceFilename.split(".");
        }
        let splitBracket = splitFilename[0].split('(');
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (splitBracket.length > 1) {
            let numberString = splitBracket[1].split(')');
            if (numberString.length > 1 && !isNaN(parseInt(numberString[0]))) {
                let number = parseInt(numberString[0]);
                this.fileNameCounter = number + 1;
                nextFilename = splitBracket[0] + "(" + this.fileNameCounter + ")";
            }
            else {
                nextFilename = splitFilename[0] + "(" + this.fileNameCounter + ")";
            }
        }
        else {
            nextFilename = splitFilename[0] + "(" + this.fileNameCounter + ")";
        }
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (splitFilename.length > 1) {
            for(let i = 1; i < splitFilename.length; i++) {
                nextFilename = nextFilename + "." + splitFilename[i];
            }
        }
        this.fileNameCounter++;
     * Disables or enables the input field for the new file name
     */
    setInputFieldVisibility() {
        this._("#replace-filename").disabled = !this._("#replace-new-name").checked;
    }

    /**
     * Returns text for the cancel button depending on number of files
     * @returns {string} correct cancel text
     */
    getCancelText() {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (this.fileList.length > 1) {
            return i18n.t('nextcloud-file-picker.replace-cancel-all');
        }
        return i18n.t('nextcloud-file-picker.replace-cancel');
    }

    /**
        this.statusText = "";
        this.loading = false;
        this.fileList = [];
    setRepeatForAllConflicts() {
        this.forAll = this._("#replace_mode_all").checked;
    /**
     * Add new folder with webdav
     *
     */
    openAddFolderDialogue() {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (this._('.addRowAnimation')) {
            this._('.addRowAnimation').classList.remove('addRowAnimation');
        }
        this._('#new-folder-wrapper').classList.toggle('hidden');
        if (this._('#new-folder-wrapper').classList.contains('hidden')) {
            this._('#add-folder-button').setAttribute("name","plus");
            this._('#add-folder-button').setAttribute("title", i18n.t('nextcloud-file-picker.add-folder-open'));
        }
        else {
            this._('#add-folder-button').setAttribute("name","close");
            this._('#add-folder-button').setAttribute("title", i18n.t('nextcloud-file-picker.add-folder-close'));
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            this._('#new-folder').focus();
    /**
     * Add new folder with webdav
     *
     */
    addFolder() {
Bekerle, Patrizio's avatar
Bekerle, Patrizio committed
        if (this._('#new-folder').value !== "") {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            let folderName = this._('#new-folder').value;
            if ( typeof this.directoryPath === 'undefined' ) {
                this.directoryPath = '';
            }
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            let folderPath = this.directoryPath + "/" + folderName;
            this.webDavClient.createDirectory(folderPath).then(contents => {
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                // this.loadDirectory(this.directoryPath);
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                const d = new Date();
                let props = {permissions:'RGDNVCK'};
                this.tabulatorTable.addRow({type:"directory", filename: folderPath, basename:folderName, lastmod:d, props: props}, true);
                this.statusText = i18n.t('nextcloud-file-picker.add-folder-success', {folder: folderName});
Steinwender, Tamara's avatar
Steinwender, Tamara committed
            }).catch(error => {
                this.loading = false;
                if (error.message.search("405") !== -1) {
                    this.statusText = html`<span class="error"> ${i18n.t('nextcloud-file-picker.add-folder-error', {folder: folderName})} </span>`;
Steinwender, Tamara's avatar
Steinwender, Tamara committed
                } else {
                    this.statusText = html`<span class="error"> ${i18n.t('nextcloud-file-picker.webdav-error', {error: error.message})} </span>`;
                }
            this._('#new-folder').value = '';
            this.openAddFolderDialogue();
    /**
     * Select all files from tabulator table
     *
     */
    selectAll() {
        this.tabulatorTable.selectRow(this.tabulatorTable.getRows().filter(row => row.getData().type != 'directory' && this.checkFileType(row.getData(), this.allowedMimeTypes)));
        if (this.tabulatorTable.getSelectedRows().length > 0) {
            this.selectAllButton = false;
    }

    /**
     * Deselect files from tabulator table
     *
     */
    deselectAll() {
        this.selectAllButton = true;
        this.tabulatorTable.getSelectedRows().forEach(row => row.deselect());
    }

    /**
     * Returns the parent directory path
     *
     * @returns {string} parent directory path
     */
    getParentDirectoryPath() {
        if ( typeof this.directoryPath === 'undefined' ) {
            this.directoryPath = '';
        }
        let path = this.directoryPath.replace(/\/$/, "");
        path = path.replace(path.split("/").pop(), "").replace(/\/$/, "");

        return (path === "") ? "/" : path;
    }

    /**
     * Returns the directory path as clickable breadcrumbs
     *
     * @returns {string} clickable breadcrumb path
     */
    getBreadcrumb() {
        if ( typeof this.directoryPath === 'undefined' ) {
            this.directoryPath = '';
        }
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        htmlpath[0] =  html`<span class="breadcrumb"><a class="home-link" @click="${() => { this.loadDirectory(""); }}" title="${i18n.t('nextcloud-file-picker.folder-home')}"><dbp-icon name="home"></dbp-icon> </a></span>`;
        const directories = this.directoryPath.split('/');
Steinwender, Tamara's avatar
Steinwender, Tamara committed
        if (directories[1] === "") {
        for(let i = 1; i < directories.length; i ++)
        {
            let path = "";
            for(let j = 1; j <= i; j++)
            {
                path += "/";
                path += directories[j];
            }

            htmlpath[i] = html`<span> › </span><span class="breadcrumb"><a @click="${() => { this.loadDirectory(path); }}" title="${i18n.t('nextcloud-file-picker.load-path-link', {path: directories[i]})}">${directories[i]}</a></span>`;
     * Returns Link to Nextcloud with actual directory
     * @returns {string} actual directory Nextcloud link
        return this.nextcloudFileURL + this.directoryPath;
    static get styles() {
        // language=css
        return css`
            ${commonStyles.getGeneralCSS()}
            ${commonStyles.getButtonCSS()}