<commit_before>/*
Copyright 2020 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import * as React from "react";
import BaseDialog from '../../views/dialogs/BaseDialog';
import EMSElementProConfirmCloseDialog from './EMSElementProConfirmCloseDialog';
import EMSElementProDataConfirmDialog from './EMSElementProDataConfirmDialog';
import Modal from "../../../Modal";
import SdkConfig from "../../../SdkConfig";
import {_t} from "../../../languageHandler";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import {OwnProfileStore} from "../../../stores/OwnProfileStore";
import {IPostmessage, IPostmessageResponseData, PostmessageAction} from "./EMSElementProDialogTypes";

interface IProps {
    requestClose(): void;
}

interface IState {
    completed: boolean;
    error: string;
}

export default class EMSElementProDialog extends React.PureComponent<IProps, IState> {
    private iframeRef: React.RefObject<HTMLIFrameElement> = React.createRef();
    private readonly elementProSetupUrl: string;

    constructor(props: IProps) {
        super(props);

        this.state = {
            completed: false,
            error: null,
        };

        this.elementProSetupUrl = SdkConfig.get().ems_element_pro.url;
    }

    private messageHandler = (message: IPostmessage) => {
        if (!this.elementProSetupUrl.startsWith(message.origin)) {
            return;
        }
        switch (message.data.action) {
            case PostmessageAction.ElementProAccountDetailsRequest:
                Modal.createDialog(
                    EMSElementProDataConfirmDialog,
                    {
                        onFinished: result => {
                            if (result) {
                                return this.sendAccountDetails();
                            }
                        },
                    },
                );
                break;
            case PostmessageAction.SetupComplete:
                // Set as completed but let the user close the modal themselves
                // so they have time to finish reading any information
                this.setState({
                    completed: true,
                });
                break;
            case PostmessageAction.CloseDialog:
                this.onFinished(true);
                break;
        }
    }

    private onFinished = (result: boolean) => {
        if (result || this.state.completed) {
            // We're done, close
            this.props.requestClose();
        } else {
            Modal.createDialog(
                EMSElementProConfirmCloseDialog,
                {
                    onFinished: result => {
                        if (result) {
                            this.props.requestClose();
                        }
                    },
                },
            );
        }
    }

    private sendMessage = (message: IPostmessageResponseData) => {
        this.iframeRef.current.contentWindow.postMessage(message, this.elementProSetupUrl);
    }

    private async sendAccountDetails() {
        const openIdToken = await MatrixClientPeg.get().getOpenIdToken();
        if (!openIdToken || !openIdToken.access_token) {
            this.setState({
                completed: true,
                error: _t("Failed to connect to your homeserver. Please close this dialog and try again."),
            });
            return;
        }
        this.sendMessage({
            action: PostmessageAction.ElementProAccountDetails,
            account: {
                accessToken: await MatrixClientPeg.get().getAccessToken(),
                name: OwnProfileStore.instance.displayName,
                openIdToken: openIdToken.access_token,
                serverName: await MatrixClientPeg.get().getDomain(),
                userLocalpart: await MatrixClientPeg.get().getUserIdLocalpart(),
            },
        });
    }

    public componentDidMount() {
        window.addEventListener("message", this.messageHandler);
    }

    public componentWillUnmount() {
        window.removeEventListener("message", this.messageHandler);
    }

    public render(): React.ReactNode {
        return (
            <BaseDialog
                className="mx_EMSElementProBaseDialog"
                onFinished={this.onFinished}
                title={_t("Set up your own personal Element host")}
                hasCancel={true}
                fixedWidth={false}
            >
                <div className="mx_EMSElementProDialog_container">
                    <iframe
                        src={this.elementProSetupUrl}
                        ref={this.iframeRef}
                        sandbox="allow-forms allow-scripts"
                    />
                    {this.state.error &&
                        <div>
                            {this.state.error}
                        </div>
                    }
                </div><commit_msg>Add allow-same-origin to Element Pro dialog<commit_after>/*
Copyright 2020 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import * as React from "react";
import BaseDialog from '../../views/dialogs/BaseDialog';
import EMSElementProConfirmCloseDialog from './EMSElementProConfirmCloseDialog';
import EMSElementProDataConfirmDialog from './EMSElementProDataConfirmDialog';
import Modal from "../../../Modal";
import SdkConfig from "../../../SdkConfig";
import {_t} from "../../../languageHandler";
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import {OwnProfileStore} from "../../../stores/OwnProfileStore";
import {IPostmessage, IPostmessageResponseData, PostmessageAction} from "./EMSElementProDialogTypes";

interface IProps {
    requestClose(): void;
}

interface IState {
    completed: boolean;
    error: string;
}

export default class EMSElementProDialog extends React.PureComponent<IProps, IState> {
    private iframeRef: React.RefObject<HTMLIFrameElement> = React.createRef();
    private readonly elementProSetupUrl: string;

    constructor(props: IProps) {
        super(props);

        this.state = {
            completed: false,
            error: null,
        };

        this.elementProSetupUrl = SdkConfig.get().ems_element_pro.url;
    }

    private messageHandler = (message: IPostmessage) => {
        if (!this.elementProSetupUrl.startsWith(message.origin)) {
            return;
        }
        switch (message.data.action) {
            case PostmessageAction.ElementProAccountDetailsRequest:
                Modal.createDialog(
                    EMSElementProDataConfirmDialog,
                    {
                        onFinished: result => {
                            if (result) {
                                return this.sendAccountDetails();
                            }
                        },
                    },
                );
                break;
            case PostmessageAction.SetupComplete:
                // Set as completed but let the user close the modal themselves
                // so they have time to finish reading any information
                this.setState({
                    completed: true,
                });
                break;
            case PostmessageAction.CloseDialog:
                this.onFinished(true);
                break;
        }
    }

    private onFinished = (result: boolean) => {
        if (result || this.state.completed) {
            // We're done, close
            this.props.requestClose();
        } else {
            Modal.createDialog(
                EMSElementProConfirmCloseDialog,
                {
                    onFinished: result => {
                        if (result) {
                            this.props.requestClose();
                        }
                    },
                },
            );
        }
    }

    private sendMessage = (message: IPostmessageResponseData) => {
        this.iframeRef.current.contentWindow.postMessage(message, this.elementProSetupUrl);
    }

    private async sendAccountDetails() {
        const openIdToken = await MatrixClientPeg.get().getOpenIdToken();
        if (!openIdToken || !openIdToken.access_token) {
            this.setState({
                completed: true,
                error: _t("Failed to connect to your homeserver. Please close this dialog and try again."),
            });
            return;
        }
        this.sendMessage({
            action: PostmessageAction.ElementProAccountDetails,
            account: {
                accessToken: await MatrixClientPeg.get().getAccessToken(),
                name: OwnProfileStore.instance.displayName,
                openIdToken: openIdToken.access_token,
                serverName: await MatrixClientPeg.get().getDomain(),
                userLocalpart: await MatrixClientPeg.get().getUserIdLocalpart(),
            },
        });
    }

    public componentDidMount() {
        window.addEventListener("message", this.messageHandler);
    }

    public componentWillUnmount() {
        window.removeEventListener("message", this.messageHandler);
    }

    public render(): React.ReactNode {
        return (
            <BaseDialog
                className="mx_EMSElementProBaseDialog"
                onFinished={this.onFinished}
                title={_t("Set up your own personal Element host")}
                hasCancel={true}
                fixedWidth={false}
            >
                <div className="mx_EMSElementProDialog_container">
                    <iframe
                        src={this.elementProSetupUrl}
                        ref={this.iframeRef}
                        sandbox="allow-forms allow-scripts allow-same-origin"
                    />
                    {this.state.error &&
                        <div>
                            {this.state.error}
                        </div>
                    }
                </div>
{'fraction_non_alphanumeric': 0.09229357798165137, 'fraction_numerical': 0.0014678899082568807, 'mean_word_length': 1.7016109045848822, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '367624', 'n_tokens_mistral': 2672, 'n_tokens_neox': 2541, 'n_words': 643}