<commit_before>/* gpgme.js - Javascript integration for gpgme
 * Copyright (C) 2018 Bundesamt für Sicherheit in der Informationstechnik
 *
 * This file is part of GPGME.
 *
 * GPGME is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * GPGME is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
 * SPDX-License-Identifier: LGPL-2.1+
 *
 * Author(s):
 *     Maximilian Krambach <mkrambach@intevation.de>
 */

import { createMessage } from './Message';
import { createKey } from './Key';
import { isFingerprint } from './Helpers';
import { gpgme_error } from './Errors';

/**
 * This class offers access to the gnupg keyring
 */
export class GPGME_Keyring {

    /**
     * Queries Keys (all Keys or a subset) from gnupg.
     *
     * @param {Object} options:
     * @param {String | Array<String>} options.pattern (optional) A pattern to
     * search for in userIds or KeyIds.
     * @param {Boolean} options.prepare_sync (optional) if set to true, most
     * data (with the exception of armored Key blocks) will be cached for the
     * Keys. This enables direct, synchronous use of these properties for
     * all keys. It does not check for changes on the backend. The cached
     * information can be updated with the {@link Key.refresh} method.
     * @param {Boolean} options.search (optional) retrieve Keys from external
     * servers with the method(s) defined in gnupg (e.g. WKD/HKP lookup)
     * @returns {Promise<GPGME_Key[]>}
     * @static
     * @async
     */
    getKeys ({ pattern, prepare_sync = false, search = false } = {}){
        if (typeof arguments[0] !== 'object') {
            return Promise.reject(gpgme_error('PARAM_WRONG'));
        }
        if (arguments.length && typeof arguments[0] !== 'object') {
            return Promise.reject(gpgme_error('PARAM_WRONG'));
        }
        return new Promise(function (resolve, reject) {
            let msg = createMessage('keylist');
            if (pattern) {
                msg.setParameter('keys', pattern);
            }
            msg.setParameter('sigs', true);
            if (search === true){
                msg.setParameter('locate', true);
            }
            msg.post().then(function (result){
                let resultset = [];
                if (result.keys.length === 0){
                    resolve([]);
                } else {
                    let secondrequest;
                    if (prepare_sync === true) {
                        secondrequest = function () {
                            let msg2 = createMessage('keylist');
                            if (pattern){
                                msg2.setParameter('keys', pattern);
                            }
                            msg2.setParameter('secret', true);
                            return msg2.post();
                        };
                    } else {
                        secondrequest = function () {
                            return Promise.resolve(true);
                        };
                    }
                    secondrequest().then(function (answer) {
                        for (let i=0; i < result.keys.length; i++){
                            if (prepare_sync === true){
                                if (answer && answer.keys) {
                                    for (let j=0;
                                        j < answer.keys.length; j++ ){
                                        const a = answer.keys[j];
                                        const b = result.keys[i];
                                        if (
                                            a.fingerprint === b.fingerprint
                                        ) {
                                            if (a.secret === true){
                                                b.hasSecret = true;
                                            } else {
                                                b.hasSecret = false;
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                            let k = createKey(result.keys[i].fingerprint,
                                !prepare_sync, result.keys[i]);
                            resultset.push(k);
                        }
                        resolve(resultset);
                    }, function (error){
                        reject(error);
                    });
                }
            });
        });
    }

    /**
     * @typedef {Object} exportResult The result of a getKeysArmored
     * operation.
     * @property {String} armored The public Key(s) as armored block. Note
     * that the result is one armored block, and not a block per key.
     * @property {Array<String>} secret_fprs (optional) list of
     * fingerprints for those Keys that also have a secret Key available in
     * gnupg. The secret key will not be exported, but the fingerprint can
     * be used in operations needing a secret key.
     */

    /**
     * Fetches the armored public Key blocks for all Keys matching the
     * pattern (if no pattern is given, fetches all keys known to gnupg).
     * @param {Object} options (optional)
     * @param {String|Array<String>} options.pattern The Pattern to
     * search for
     * @param {Boolean} options.with_secret_fpr also return a list of
     * fingerprints for the keys that have a secret key available
     * @returns {Promise<exportResult>} Object containing the
     * armored Key(s) and additional information.
     * @static
     * @async
     */
    getKeysArmored ({ pattern, with_secret_fpr }) {
        return new Promise(function (resolve, reject) {
            let msg = createMessage('export');
            msg.setParameter('armor', true);
            if (with_secret_fpr === true) {
                msg.setParameter('with-sec-fprs', true);
            }
            if (pattern){
                msg.setParameter('keys', pattern);
            }
            msg.post().then(function (answer){
                const result = { armored: answer.data };
                if (with_secret_fpr === true){
                    if (answer.hasOwnProperty('sec-fprs')){
                        result.secret_fprs = answer['sec-fprs'];
                    } else {
                        result.secret_fprs = [];
                    }
                }
                resolve(result);
            }, function (error){
                reject(error);
            });
        });
    }

    /**
     * Returns the Key used by default in gnupg.
     * (a.k.a. 'primary Key or 'main key').
     * It looks up the gpg configuration if set, or the first key that
     * contains a secret key.
     *
     * @returns {Promise<GPGME_Key>}
     * @async
     * @static
     */
    getDefaultKey (prepare_sync = false) {
        let me = this;
        return new Promise(function (resolve, reject){
            let msg = createMessage('config_opt');
            msg.setParameter('component', 'gpg');
            msg.setParameter('option', 'default-key');
            msg.post().then(function (resp){
                if (resp.option !== undefined
                    && resp.option.hasOwnProperty('value')
                    && resp.option.value.length === 1
                    && resp.option.value[0].hasOwnProperty('string')
                    && typeof (resp.option.value[0].string) === 'string'){
                    me.getKeys({ pattern: resp.option.value[0].string,
                        prepare_sync: true }).then(
                        function (keys){
                            if (keys.length === 1){
                                resolve(keys[0]);
                            } else {
                                reject(gpgme_error('KEY_NO_DEFAULT'));
                            }
                        }, function (error){
                            reject(error);
                        });
                } else {
                    let msg = createMessage('keylist');
                    msg.setParameter('secret', true);
                    msg.post().then(function (result){
                        if (result.keys.length === 0){
                            reject(gpgme_error('KEY_NO_DEFAULT'));
                        } else {
                            for (let i=0; i< result.keys.length; i++ ) {
                                if (
                                    result.keys[i].invalid === false &&
                                    result.keys[i].expired === false &&
                                    result.keys[i].revoked === false &&
                                    result.keys[i].can_sign === true
                                ) {
                                    let k = createKey(
                                        result.keys[i].fingerprint,
                                        !prepare_sync,
                                        result.keys[i]);
                                    resolve(k);
                                    break;
                                } else if (i === result.keys.length - 1){
                                    reject(gpgme_error('KEY_NO_DEFAULT'));
                                }
                            }
                        }
                    }, function (error){
                        reject(error);
                    });
                }
            }, function (error){
                reject(error);
            });
        });
    }

    /**
     * @typedef {Object} importResult The result of a Key update
     * @property {Object} summary Numerical summary of the result. See the
     * feedbackValues variable for available Keys values and the gnupg
     * documentation.
     * https://www.gnupg.org/documentation/manuals/gpgme/Importing-Keys.html
     * for details on their meaning.
     * @property {Array<importedKeyResult>} Keys Array of Object containing
     * GPGME_Keys with additional import information
     *
     */

    /**
     * @typedef {Object} importedKeyResult
     * @property {GPGME_Key} key The resulting key
     * @property {String} status:
     *  'nochange' if the Key was not changed,
     *  'newkey' if the Key was imported in gpg, and did not exist
     *    previously,
     *  'change' if the key existed, but details were updated. For details,
     *    Key.changes is available.
     * @property {Boolean} changes.userId Changes in userIds
     * @property {Boolean} changes.signature Changes in signatures
     * @property {Boolean} changes.subkey Changes in subkeys
     */

    /**
     * Import an armored Key block into gnupg. Note that this currently
     * will not succeed on private Key blocks.
     * @param {String} armored Armored Key block of the Key(s) to be
     * imported into gnupg
     * @param {Boolean} prepare_sync prepare the keys for synched use
     * (see {@link getKeys}).
     * @returns {Promise<importResult>} A summary and Keys considered.
     * @async
     * @static
     */
    importKey (armored, prepare_sync) {
        let feedbackValues = ['considered', 'no_user_id', 'imported',
            'imported_rsa', 'unchanged', 'new_user_ids', 'new_sub_keys',
            'new_signatures', 'new_revocations', 'secret_read',
            'secret_imported', 'secret_unchanged', 'skipped_new_keys',
            'not_imported', 'skipped_v3_keys'];
        if (!armored || typeof (armored) !== 'string'){
            return Promise.reject(gpgme_error('PARAM_WRONG'));
        }
        let me = this;
        return new Promise(function (resolve, reject){
            let msg = createMessage('import');
            msg.setParameter('data', armored);
            msg.post().then(function (response){
                let infos = {};
                let fprs = [];
                let summary = {};
                for (let i=0; i < feedbackValues.length; i++ ){
                    summary[feedbackValues[i]] =
                        response.result[feedbackValues[i]];
                }
                if (!response.result.hasOwnProperty('imports') ||
                    response.result.imports.length === 0
                ){
                    resolve({ Keys:[],summary: summary });
                    return;
                }
                for (let res=0; res<response.result.imports.length; res++){
                    let result = response.result.imports[res];
                    let status = '';
                    if (result.status === 0){
                        status = 'nochange';
                    } else if ((result.status & 1) === 1){
                        status = 'newkey';
                    } else {
                        status = 'change';
                    }
                    let changes = {};
                    changes.userId = (result.status & 2) === 2;
                    changes.signature = (result.status & 4) === 4;
                    changes.subkey = (result.status & 8) === 8;
                    // 16 new secret key: not implemented
                    fprs.push(result.fingerprint);
                    infos[result.fingerprint] = {
                        changes: changes,
                        status: status
                    };
                }
                let resultset = [];
                if (prepare_sync === true){
                    me.getKeys({ pattern: fprs, prepare_sync: true })
                        .then(function (result){
                            for (let i=0; i < result.length; i++) {
                                resultset.push({
                                    key: result[i],
                                    changes:
                                        infos[result[i].fingerprint].changes,
                                    status: infos[result[i].fingerprint].status
                                });
                            }
                            resolve({ Keys:resultset,summary: summary });
                        }, function (error){
                            reject(error);
                        });
                } else {
                    for (let i=0; i < fprs.length; i++) {
                        resultset.push({
                            key: createKey(fprs[i]),
                            changes: infos[fprs[i]].changes,
                            status: infos[fprs[i]].status
                        });
                    }
                    resolve({ Keys:resultset,summary:summary });
                }

            }, function (error){
                reject(error);
            });

        });

    }

    /**
     * Convenience function for deleting a Key. See {@link Key#delete} for
     * further information about the return values.
     * @param {String} fingerprint
     * @returns {Promise<Boolean>}
     * @async
     * @static
     */
    deleteKey (fingerprint){
        if (isFingerprint(fingerprint) === true) {
            let key = createKey(fingerprint);
            return key.delete();
        } else {
            return Promise.reject(gpgme_error('KEY_INVALID'));
        }
    }

    /**
     * Generates a new Key pair directly in gpg, and returns a GPGME_Key
     * representing that Key. Please note that due to security concerns,
     * secret Keys can not be deleted or exported from inside gpgme.js.
     * @param {Object} options
     * @param {String} option.userId The user Id, e.g. 'Foo Bar <foo@bar.baz>'
     * @param {String} option.algo (optional) algorithm (and optionally key
     * size) to be used. See {@link supportedKeyAlgos} below for supported
     * values. If ommitted, 'default' is used.
     * @param {Number} option.expires (optional) Expiration time in seconds
     * from now. If not set or set to 0, expiration will be 'never'
     *
     * @return {Promise<Key|GPGME_Error>}
     * @async
     */
    generateKey ({ userId, algo = 'default', expires= 0 } = {}){
        if (typeof userId !== 'string'
            // eslint-disable-next-line no-use-before-define
            || (algo && supportedKeyAlgos.indexOf(algo) < 0 )
            || (!Number.isInteger(expires) || expires < 0 )
        ){
            return Promise.reject(gpgme_error('PARAM_WRONG'));
        }
        // eslint-disable-next-line no-use-before-define
        let me = this;
        return new Promise(function (resolve, reject){
            let msg = createMessage('createkey');
            msg.setParameter('userid', userId);
            msg.setParameter('algo', algo);
            msg.setParameter('expires', expires);
            msg.post().then(function (response){
                me.getKeys({
                    pattern: response.fingerprint,
                    prepare_sync: true
                }).then(function (result){
                    resolve(result);
                }, function (error){
                    reject(error);
                });
            }, function (error) {
                reject(error);
            });
        });
    }
}

/**
 * List of algorithms supported for key generation. Please refer to the gnupg
 * documentation for details
 */
const supportedKeyAlgos = [
    'default',
    'rsa', 'rsa2048', 'rsa3072', 'rsa4096',
    'dsa', 'dsa2048', 'dsa3072', 'dsa4096',
    'elg', 'elg2048', 'elg3072', 'elg4096',
    'ed25519',
    'cv25519',
    'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1',
    'NIST P-256', 'NIST P-384', 'NIST P-521'
];<commit_msg>js: add 'default-future' as createKey option<commit_after>/* gpgme.js - Javascript integration for gpgme
 * Copyright (C) 2018 Bundesamt für Sicherheit in der Informationstechnik
 *
 * This file is part of GPGME.
 *
 * GPGME is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * GPGME is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
 * SPDX-License-Identifier: LGPL-2.1+
 *
 * Author(s):
 *     Maximilian Krambach <mkrambach@intevation.de>
 */

import { createMessage } from './Message';
import { createKey } from './Key';
import { isFingerprint } from './Helpers';
import { gpgme_error } from './Errors';

/**
 * This class offers access to the gnupg keyring
 */
export class GPGME_Keyring {

    /**
     * Queries Keys (all Keys or a subset) from gnupg.
     *
     * @param {Object} options:
     * @param {String | Array<String>} options.pattern (optional) A pattern to
     * search for in userIds or KeyIds.
     * @param {Boolean} options.prepare_sync (optional) if set to true, most
     * data (with the exception of armored Key blocks) will be cached for the
     * Keys. This enables direct, synchronous use of these properties for
     * all keys. It does not check for changes on the backend. The cached
     * information can be updated with the {@link Key.refresh} method.
     * @param {Boolean} options.search (optional) retrieve Keys from external
     * servers with the method(s) defined in gnupg (e.g. WKD/HKP lookup)
     * @returns {Promise<GPGME_Key[]>}
     * @static
     * @async
     */
    getKeys ({ pattern, prepare_sync = false, search = false } = {}){
        if (typeof arguments[0] !== 'object') {
            return Promise.reject(gpgme_error('PARAM_WRONG'));
        }
        if (arguments.length && typeof arguments[0] !== 'object') {
            return Promise.reject(gpgme_error('PARAM_WRONG'));
        }
        return new Promise(function (resolve, reject) {
            let msg = createMessage('keylist');
            if (pattern) {
                msg.setParameter('keys', pattern);
            }
            msg.setParameter('sigs', true);
            if (search === true){
                msg.setParameter('locate', true);
            }
            msg.post().then(function (result){
                let resultset = [];
                if (result.keys.length === 0){
                    resolve([]);
                } else {
                    let secondrequest;
                    if (prepare_sync === true) {
                        secondrequest = function () {
                            let msg2 = createMessage('keylist');
                            if (pattern){
                                msg2.setParameter('keys', pattern);
                            }
                            msg2.setParameter('secret', true);
                            return msg2.post();
                        };
                    } else {
                        secondrequest = function () {
                            return Promise.resolve(true);
                        };
                    }
                    secondrequest().then(function (answer) {
                        for (let i=0; i < result.keys.length; i++){
                            if (prepare_sync === true){
                                if (answer && answer.keys) {
                                    for (let j=0;
                                        j < answer.keys.length; j++ ){
                                        const a = answer.keys[j];
                                        const b = result.keys[i];
                                        if (
                                            a.fingerprint === b.fingerprint
                                        ) {
                                            if (a.secret === true){
                                                b.hasSecret = true;
                                            } else {
                                                b.hasSecret = false;
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                            let k = createKey(result.keys[i].fingerprint,
                                !prepare_sync, result.keys[i]);
                            resultset.push(k);
                        }
                        resolve(resultset);
                    }, function (error){
                        reject(error);
                    });
                }
            });
        });
    }

    /**
     * @typedef {Object} exportResult The result of a getKeysArmored
     * operation.
     * @property {String} armored The public Key(s) as armored block. Note
     * that the result is one armored block, and not a block per key.
     * @property {Array<String>} secret_fprs (optional) list of
     * fingerprints for those Keys that also have a secret Key available in
     * gnupg. The secret key will not be exported, but the fingerprint can
     * be used in operations needing a secret key.
     */

    /**
     * Fetches the armored public Key blocks for all Keys matching the
     * pattern (if no pattern is given, fetches all keys known to gnupg).
     * @param {Object} options (optional)
     * @param {String|Array<String>} options.pattern The Pattern to
     * search for
     * @param {Boolean} options.with_secret_fpr also return a list of
     * fingerprints for the keys that have a secret key available
     * @returns {Promise<exportResult>} Object containing the
     * armored Key(s) and additional information.
     * @static
     * @async
     */
    getKeysArmored ({ pattern, with_secret_fpr }) {
        return new Promise(function (resolve, reject) {
            let msg = createMessage('export');
            msg.setParameter('armor', true);
            if (with_secret_fpr === true) {
                msg.setParameter('with-sec-fprs', true);
            }
            if (pattern){
                msg.setParameter('keys', pattern);
            }
            msg.post().then(function (answer){
                const result = { armored: answer.data };
                if (with_secret_fpr === true){
                    if (answer.hasOwnProperty('sec-fprs')){
                        result.secret_fprs = answer['sec-fprs'];
                    } else {
                        result.secret_fprs = [];
                    }
                }
                resolve(result);
            }, function (error){
                reject(error);
            });
        });
    }

    /**
     * Returns the Key used by default in gnupg.
     * (a.k.a. 'primary Key or 'main key').
     * It looks up the gpg configuration if set, or the first key that
     * contains a secret key.
     *
     * @returns {Promise<GPGME_Key>}
     * @async
     * @static
     */
    getDefaultKey (prepare_sync = false) {
        let me = this;
        return new Promise(function (resolve, reject){
            let msg = createMessage('config_opt');
            msg.setParameter('component', 'gpg');
            msg.setParameter('option', 'default-key');
            msg.post().then(function (resp){
                if (resp.option !== undefined
                    && resp.option.hasOwnProperty('value')
                    && resp.option.value.length === 1
                    && resp.option.value[0].hasOwnProperty('string')
                    && typeof (resp.option.value[0].string) === 'string'){
                    me.getKeys({ pattern: resp.option.value[0].string,
                        prepare_sync: true }).then(
                        function (keys){
                            if (keys.length === 1){
                                resolve(keys[0]);
                            } else {
                                reject(gpgme_error('KEY_NO_DEFAULT'));
                            }
                        }, function (error){
                            reject(error);
                        });
                } else {
                    let msg = createMessage('keylist');
                    msg.setParameter('secret', true);
                    msg.post().then(function (result){
                        if (result.keys.length === 0){
                            reject(gpgme_error('KEY_NO_DEFAULT'));
                        } else {
                            for (let i=0; i< result.keys.length; i++ ) {
                                if (
                                    result.keys[i].invalid === false &&
                                    result.keys[i].expired === false &&
                                    result.keys[i].revoked === false &&
                                    result.keys[i].can_sign === true
                                ) {
                                    let k = createKey(
                                        result.keys[i].fingerprint,
                                        !prepare_sync,
                                        result.keys[i]);
                                    resolve(k);
                                    break;
                                } else if (i === result.keys.length - 1){
                                    reject(gpgme_error('KEY_NO_DEFAULT'));
                                }
                            }
                        }
                    }, function (error){
                        reject(error);
                    });
                }
            }, function (error){
                reject(error);
            });
        });
    }

    /**
     * @typedef {Object} importResult The result of a Key update
     * @property {Object} summary Numerical summary of the result. See the
     * feedbackValues variable for available Keys values and the gnupg
     * documentation.
     * https://www.gnupg.org/documentation/manuals/gpgme/Importing-Keys.html
     * for details on their meaning.
     * @property {Array<importedKeyResult>} Keys Array of Object containing
     * GPGME_Keys with additional import information
     *
     */

    /**
     * @typedef {Object} importedKeyResult
     * @property {GPGME_Key} key The resulting key
     * @property {String} status:
     *  'nochange' if the Key was not changed,
     *  'newkey' if the Key was imported in gpg, and did not exist
     *    previously,
     *  'change' if the key existed, but details were updated. For details,
     *    Key.changes is available.
     * @property {Boolean} changes.userId Changes in userIds
     * @property {Boolean} changes.signature Changes in signatures
     * @property {Boolean} changes.subkey Changes in subkeys
     */

    /**
     * Import an armored Key block into gnupg. Note that this currently
     * will not succeed on private Key blocks.
     * @param {String} armored Armored Key block of the Key(s) to be
     * imported into gnupg
     * @param {Boolean} prepare_sync prepare the keys for synched use
     * (see {@link getKeys}).
     * @returns {Promise<importResult>} A summary and Keys considered.
     * @async
     * @static
     */
    importKey (armored, prepare_sync) {
        let feedbackValues = ['considered', 'no_user_id', 'imported',
            'imported_rsa', 'unchanged', 'new_user_ids', 'new_sub_keys',
            'new_signatures', 'new_revocations', 'secret_read',
            'secret_imported', 'secret_unchanged', 'skipped_new_keys',
            'not_imported', 'skipped_v3_keys'];
        if (!armored || typeof (armored) !== 'string'){
            return Promise.reject(gpgme_error('PARAM_WRONG'));
        }
        let me = this;
        return new Promise(function (resolve, reject){
            let msg = createMessage('import');
            msg.setParameter('data', armored);
            msg.post().then(function (response){
                let infos = {};
                let fprs = [];
                let summary = {};
                for (let i=0; i < feedbackValues.length; i++ ){
                    summary[feedbackValues[i]] =
                        response.result[feedbackValues[i]];
                }
                if (!response.result.hasOwnProperty('imports') ||
                    response.result.imports.length === 0
                ){
                    resolve({ Keys:[],summary: summary });
                    return;
                }
                for (let res=0; res<response.result.imports.length; res++){
                    let result = response.result.imports[res];
                    let status = '';
                    if (result.status === 0){
                        status = 'nochange';
                    } else if ((result.status & 1) === 1){
                        status = 'newkey';
                    } else {
                        status = 'change';
                    }
                    let changes = {};
                    changes.userId = (result.status & 2) === 2;
                    changes.signature = (result.status & 4) === 4;
                    changes.subkey = (result.status & 8) === 8;
                    // 16 new secret key: not implemented
                    fprs.push(result.fingerprint);
                    infos[result.fingerprint] = {
                        changes: changes,
                        status: status
                    };
                }
                let resultset = [];
                if (prepare_sync === true){
                    me.getKeys({ pattern: fprs, prepare_sync: true })
                        .then(function (result){
                            for (let i=0; i < result.length; i++) {
                                resultset.push({
                                    key: result[i],
                                    changes:
                                        infos[result[i].fingerprint].changes,
                                    status: infos[result[i].fingerprint].status
                                });
                            }
                            resolve({ Keys:resultset,summary: summary });
                        }, function (error){
                            reject(error);
                        });
                } else {
                    for (let i=0; i < fprs.length; i++) {
                        resultset.push({
                            key: createKey(fprs[i]),
                            changes: infos[fprs[i]].changes,
                            status: infos[fprs[i]].status
                        });
                    }
                    resolve({ Keys:resultset,summary:summary });
                }

            }, function (error){
                reject(error);
            });

        });

    }

    /**
     * Convenience function for deleting a Key. See {@link Key#delete} for
     * further information about the return values.
     * @param {String} fingerprint
     * @returns {Promise<Boolean>}
     * @async
     * @static
     */
    deleteKey (fingerprint){
        if (isFingerprint(fingerprint) === true) {
            let key = createKey(fingerprint);
            return key.delete();
        } else {
            return Promise.reject(gpgme_error('KEY_INVALID'));
        }
    }

    /**
     * Generates a new Key pair directly in gpg, and returns a GPGME_Key
     * representing that Key. Please note that due to security concerns,
     * secret Keys can not be deleted or exported from inside gpgme.js.
     * @param {Object} options
     * @param {String} option.userId The user Id, e.g. 'Foo Bar <foo@bar.baz>'
     * @param {String} option.algo (optional) algorithm (and optionally key
     * size) to be used. See {@link supportedKeyAlgos} below for supported
     * values. If ommitted, 'default' is used.
     * @param {Number} option.expires (optional) Expiration time in seconds
     * from now. If not set or set to 0, expiration will be 'never'
     *
     * @return {Promise<Key|GPGME_Error>}
     * @async
     */
    generateKey ({ userId, algo = 'default', expires= 0 } = {}){
        if (typeof userId !== 'string'
            // eslint-disable-next-line no-use-before-define
            || (algo && supportedKeyAlgos.indexOf(algo) < 0 )
            || (!Number.isInteger(expires) || expires < 0 )
        ){
            return Promise.reject(gpgme_error('PARAM_WRONG'));
        }
        // eslint-disable-next-line no-use-before-define
        let me = this;
        return new Promise(function (resolve, reject){
            let msg = createMessage('createkey');
            msg.setParameter('userid', userId);
            msg.setParameter('algo', algo);
            msg.setParameter('expires', expires);
            msg.post().then(function (response){
                me.getKeys({
                    pattern: response.fingerprint,
                    prepare_sync: true
                }).then(function (result){
                    resolve(result);
                }, function (error){
                    reject(error);
                });
            }, function (error) {
                reject(error);
            });
        });
    }
}

/**
 * List of algorithms supported for key generation. Please refer to the gnupg
 * documentation for details
 */
const supportedKeyAlgos = [
    'default', 'default-future',
    'rsa', 'rsa2048', 'rsa3072', 'rsa4096',
    'dsa', 'dsa2048', 'dsa3072', 'dsa4096',
    'elg', 'elg2048', 'elg3072', 'elg4096',
    'ed25519',
    'cv25519',
    'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1',
    'NIST P-256', 'NIST P-384', 'NIST P-521'
];<|endoftext|>


<commit_before>// @flow

import * as React from 'react';
import { Trans } from 'react-i18next';
import Illustration from '@salesforce/design-system-react/components/illustration';

import svgPath from 'images/broken.svg';
import { logError } from 'utils/logging';

type Props = { children: React.Node };

class ErrorBoundary extends React.Component<
  Props,
  { hasError: boolean, info: {} },
> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false, info: {} };
  }

  /* istanbul ignore next */
  componentDidCatch(error: Error, info: {}) {
    this.setState({ hasError: true, info });
    logError(error, info);
  }

  render(): React.Node {
    if (this.state.hasError) {
      return (
        <EmptyIllustration
          message={
            <>
              <Trans i18nKey="anErrorOccurred">
                Unless you pasted a URL incorrectly, it is probably a bug in the
                code or a networking problem.

                Our top minds have been alerted.

                You may need to rebuild your query from
                scratch. Sorry about that.

              </Trans>
            </>
          }
        />
      );
    }
    return this.props.children;
  }
}

export const EmptyIllustration = ({ message }: { message: React.Node }) => (
  <Illustration
    heading="Yikes! An error occurred!  :("
    messageBody={message}
    name="Broken"
    path={`${svgPath}#broken`}
    size="large"
  />
);

export default ErrorBoundary;
<commit_msg>Remove references to unused info state.<commit_after>// @flow

import * as React from 'react';
import { Trans } from 'react-i18next';
import Illustration from '@salesforce/design-system-react/components/illustration';

import svgPath from 'images/broken.svg';
import { logError } from 'utils/logging';

type Props = { children: React.Node };

class ErrorBoundary extends React.Component<Props, { hasError: boolean }> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  /* istanbul ignore next */
  componentDidCatch(error: Error, info: {}) {
    this.setState({ hasError: true });
    logError(error, info);
  }

  render(): React.Node {
    if (this.state.hasError) {
      return (
        <EmptyIllustration
          message={
            <>
              <Trans i18nKey="anErrorOccurred">
                Unless you pasted a URL incorrectly, it is probably a bug in the
                code or a networking problem.

                Our top minds have been alerted.

                You may need to rebuild your query from
                scratch. Sorry about that.

              </Trans>
            </>
          }
        />
      );
    }
    return this.props.children;
  }
}

export const EmptyIllustration = ({ message }: { message: React.Node }) => (
  <Illustration
    heading="Yikes! An error occurred!  :("
    messageBody={message}
    name="Broken"
    path={`${svgPath}#broken`}
    size="large"
  />
);

export default ErrorBoundary;
<|endoftext|>


<commit_before>/*======================================================
************   Pages   ************
======================================================*/
// Page Callbacks API
app.pageCallbacks = {};

app.onPage = function (callbackName, pageName, callback) {
    if (pageName && pageName.split(' ').length > 1) {
        var pageNames = pageName.split(' ');
        var returnCallbacks = [];
        for (var i = 0; i < pageNames.length; i++) {
            returnCallbacks.push(app.onPage(callbackName, pageNames[i], callback));
        }
        returnCallbacks.remove = function () {
            for (var i = 0; i < returnCallbacks.length; i++) {
                returnCallbacks[i].remove();
            }
        };
        returnCallbacks.trigger = function () {
            for (var i = 0; i < returnCallbacks.length; i++) {
                returnCallbacks[i].trigger();
            }
        };
        return returnCallbacks;
    }
    var callbacks = app.pageCallbacks[callbackName][pageName];
    if (!callbacks) {
        callbacks = app.pageCallbacks[callbackName][pageName] = [];
    }
    app.pageCallbacks[callbackName][pageName].push(callback);
    return {
        remove: function () {
            var removeIndex;
            for (var i = 0; i < callbacks.length; i++) {
                if (callbacks[i].toString() === callback.toString()) {
                    removeIndex = i;
                }
            }
            if (typeof removeIndex !== 'undefined') callbacks.splice(removeIndex, 1);
        },
        trigger: callback
    };
};

//Create callbacks methods dynamically
function createPageCallback(callbackName) {
    var capitalized = callbackName.replace(/^./, function (match) {
        return match.toUpperCase();
    });
    app['onPage' + capitalized] = function (pageName, callback) {
        return app.onPage(callbackName, pageName, callback);
    };
}

var pageCallbacksNames = ('beforeInit init reinit beforeAnimation afterAnimation back afterBack beforeRemove').split(' ');
for (var i = 0; i < pageCallbacksNames.length; i++) {
    app.pageCallbacks[pageCallbacksNames[i]] = {};
    createPageCallback(pageCallbacksNames[i]);
}

app.triggerPageCallbacks = function (callbackName, pageName, pageData) {
    var allPagesCallbacks = app.pageCallbacks[callbackName]['*'];
    if (allPagesCallbacks) {
        for (var j = 0; j < allPagesCallbacks.length; j++) {
            allPagesCallbacks[j](pageData);
        }
    }
    var callbacks = app.pageCallbacks[callbackName][pageName];
    if (!callbacks || callbacks.length === 0) return;
    for (var i = 0; i < callbacks.length; i++) {
        callbacks[i](pageData);
    }
};

// On Page Init Callback
app.pageInitCallback = function (view, params) {
    var pageContainer = params.pageContainer;
    if (!pageContainer) return;
    if (pageContainer.f7PageInitialized && view && !view.params.domCache) return;

    var pageQuery = params.query;
    if (!pageQuery) {
        if (params.url && params.url.indexOf('?') > 0) {
            pageQuery = $.parseUrlQuery(params.url || '');
        }
        else if (pageContainer.f7PageData && pageContainer.f7PageData.query) {
            pageQuery = pageContainer.f7PageData.query;
        }
        else {
            pageQuery = {};
        }
    }

    // Page Data
    var pageData = {
        container: pageContainer,
        url: params.url,
        query: pageQuery,
        name: $(pageContainer).attr('data-page'),
        view: view,
        from: params.position,
        context: params.context,
        navbarInnerContainer: params.navbarInnerContainer,
        fromPage: params.fromPage
    };
    if (params.fromPage && !params.fromPage.navbarInnerContainer && params.oldNavbarInnerContainer) {
        params.fromPage.navbarInnerContainer = params.oldNavbarInnerContainer;
    }

    if (pageContainer.f7PageInitialized && ((view && view.params.domCache) || (!view && $(pageContainer).parents('.popup, .popover, .login-screen, .modal, .actions-modal, .picker-modal').length > 0))) {
        // Reinit Page
        app.reinitPage(pageContainer);

        // Callbacks
        app.pluginHook('pageReinit', pageData);
        if (app.params.onPageReinit) app.params.onPageReinit(app, pageData);
        app.triggerPageCallbacks('reinit', pageData.name, pageData);
        $(pageData.container).trigger('pageReinit page:reinit', {page: pageData});
        return;
    }
    pageContainer.f7PageInitialized = true;

    // Store pagedata in page
    pageContainer.f7PageData = pageData;

    // Update View's activePage
    if (view && !params.preloadOnly && !params.reloadPrevious) {
        // Add data-page on view
        $(view.container).attr('data-page', pageData.name);
        // Update View active page data
        view.activePage = pageData;
    }

    // Before Init Callbacks
    app.pluginHook('pageBeforeInit', pageData);
    if (app.params.onPageBeforeInit) app.params.onPageBeforeInit(app, pageData);
    app.triggerPageCallbacks('beforeInit', pageData.name, pageData);
    $(pageData.container).trigger('pageBeforeInit page:beforeinit', {page: pageData});

    // Init page
    app.initPage(pageContainer);

    // Init Callback
    app.pluginHook('pageInit', pageData);
    if (app.params.onPageInit) app.params.onPageInit(app, pageData);
    app.triggerPageCallbacks('init', pageData.name, pageData);
    $(pageData.container).trigger('pageInit page:init', {page: pageData});
};
app.pageRemoveCallback = function (view, pageContainer, position) {
    var pageContext;
    if (!pageContainer) return;
    if (pageContainer.f7PageData) pageContext = pageContainer.f7PageData.context;
    // Page Data
    var pageData = {
        container: pageContainer,
        name: $(pageContainer).attr('data-page'),
        view: view,
        url: pageContainer.f7PageData && pageContainer.f7PageData.url,
        query: pageContainer.f7PageData && pageContainer.f7PageData.query,
        navbarInnerContainer: pageContainer.f7PageData && pageContainer.f7PageData.navbarInnerContainer,
        from: position,
        context: pageContext
    };
    // Before Init Callback
    app.pluginHook('pageBeforeRemove', pageData);
    if (app.params.onPageBeforeRemove) app.params.onPageBeforeRemove(app, pageData);
    app.triggerPageCallbacks('beforeRemove', pageData.name, pageData);
    $(pageData.container).trigger('pageBeforeRemove page:beforeremove', {page: pageData});
    pageData = null;
};
app.pageBackCallback = function (callback, view, params) {
    // Page Data
    var pageContainer = params.pageContainer;
    var pageContext;
    if (!pageContainer) return;
    if (pageContainer.f7PageData) pageContext = pageContainer.f7PageData.context;

    var pageData = {
        container: pageContainer,
        name: $(pageContainer).attr('data-page'),
        url: pageContainer.f7PageData && pageContainer.f7PageData.url,
        query: pageContainer.f7PageData && pageContainer.f7PageData.query,
        view: view,
        from: params.position,
        context: pageContext,
        navbarInnerContainer: pageContainer.f7PageData && pageContainer.f7PageData.navbarInnerContainer,
        swipeBack: params.swipeBack
    };

    if (callback === 'after') {
        app.pluginHook('pageAfterBack', pageData);
        if (app.params.onPageAfterBack) app.params.onPageAfterBack(app, pageData);
        app.triggerPageCallbacks('afterBack', pageData.name, pageData);
        $(pageContainer).trigger('pageAfterBack page:afterback', {page: pageData});

    }
    if (callback === 'before') {
        app.pluginHook('pageBack', pageData);
        if (app.params.onPageBack) app.params.onPageBack(app, pageData);
        app.triggerPageCallbacks('back', pageData.name, pageData);
        $(pageData.container).trigger('pageBack page:back', {page: pageData});
    }
};
app.pageAnimCallback = function (callback, view, params) {
    var pageContainer = params.pageContainer;
    var pageContext;
    if (!pageContainer) return;
    if (pageContainer.f7PageData) pageContext = pageContainer.f7PageData.context;

    var pageQuery = params.query;
    if (!pageQuery) {
        if (params.url && params.url.indexOf('?') > 0) {
            pageQuery = $.parseUrlQuery(params.url || '');
        }
        else if (pageContainer.f7PageData && pageContainer.f7PageData.query) {
            pageQuery = pageContainer.f7PageData.query;
        }
        else {
            pageQuery = {};
        }
    }
    // Page Data
    var pageData = {
        container: pageContainer,
        url: params.url,
        query: pageQuery,
        name: $(pageContainer).attr('data-page'),
        view: view,
        from: params.position,
        context: pageContext,
        swipeBack: params.swipeBack,
        navbarInnerContainer: pageContainer.f7PageData && pageContainer.f7PageData.navbarInnerContainer,
        fromPage: params.fromPage
    };
    var oldPage = params.oldPage,
        newPage = params.newPage;

    // Update page date
    pageContainer.f7PageData = pageData;

    if (callback === 'after') {
        app.pluginHook('pageAfterAnimation', pageData);
        if (app.params.onPageAfterAnimation) app.params.onPageAfterAnimation(app, pageData);
        app.triggerPageCallbacks('afterAnimation', pageData.name, pageData);
        $(pageData.container).trigger('pageAfterAnimation page:afteranimation', {page: pageData});

    }
    if (callback === 'before') {
        // Add data-page on view
        $(view.container).attr('data-page', pageData.name);

        // Update View's activePage
        if (view) view.activePage = pageData;

        // Hide/show navbar dynamically
        if (newPage.hasClass('no-navbar') && !oldPage.hasClass('no-navbar')) {
            view.hideNavbar();
        }
        if (!newPage.hasClass('no-navbar') && (oldPage.hasClass('no-navbar') || oldPage.hasClass('no-navbar-by-scroll'))) {
            view.showNavbar();
        }
        // Hide/show navbar toolbar
        if (newPage.hasClass('no-toolbar') && !oldPage.hasClass('no-toolbar')) {
            view.hideToolbar();
        }
        if (!newPage.hasClass('no-toolbar') && (oldPage.hasClass('no-toolbar') || oldPage.hasClass('no-toolbar-by-scroll'))) {
            view.showToolbar();
        }
        // Hide/show tabbar
        var tabBar;
        if (newPage.hasClass('no-tabbar') && !oldPage.hasClass('no-tabbar')) {
            tabBar = $(view.container).find('.tabbar');
            if (tabBar.length === 0) tabBar = $(view.container).parents('.' + app.params.viewsClass).find('.tabbar');
            app.hideToolbar(tabBar);
        }
        if (!newPage.hasClass('no-tabbar') && (oldPage.hasClass('no-tabbar') || oldPage.hasClass('no-tabbar-by-scroll'))) {
            tabBar = $(view.container).find('.tabbar');
            if (tabBar.length === 0) tabBar = $(view.container).parents('.' + app.params.viewsClass).find('.tabbar');
            app.showToolbar(tabBar);
        }

        oldPage.removeClass('no-navbar-by-scroll no-toolbar-by-scroll');
        // Callbacks
        app.pluginHook('pageBeforeAnimation', pageData);
        if (app.params.onPageBeforeAnimation) app.params.onPageBeforeAnimation(app, pageData);
        app.triggerPageCallbacks('beforeAnimation', pageData.name, pageData);
        $(pageData.container).trigger('pageBeforeAnimation page:beforeanimation', {page: pageData});
    }
};

// Init Page Events and Manipulations
app.initPage = function (pageContainer) {
    pageContainer = $(pageContainer);
    if (pageContainer.length === 0) return;
    // Size navbars on page load
    if (app.sizeNavbars) app.sizeNavbars(pageContainer.parents('.' + app.params.viewClass)[0]);
    // Init messages
    if (app.initPageMessages) app.initPageMessages(pageContainer);
    // Init forms storage
    if (app.initFormsStorage) app.initFormsStorage(pageContainer);
    // Init smart select
    if (app.initSmartSelects) app.initSmartSelects(pageContainer);
    // Init slider
    if (app.initPageSwiper) app.initPageSwiper(pageContainer);
    // Init pull to refres
    if (app.initPullToRefresh) app.initPullToRefresh(pageContainer);
    // Init infinite scroll
    if (app.initPageInfiniteScroll) app.initPageInfiniteScroll(pageContainer);
    // Init searchbar
    if (app.initSearchbar) app.initSearchbar(pageContainer);
    // Init message bar
    if (app.initPageMessagebar) app.initPageMessagebar(pageContainer);
    // Init scroll toolbars
    if (app.initPageScrollToolbars) app.initPageScrollToolbars(pageContainer);
    // Init lazy images
    if (app.initImagesLazyLoad) app.initImagesLazyLoad(pageContainer);
    // Init progress bars
    if (app.initPageProgressbar) app.initPageProgressbar(pageContainer);
    // Init resizeable textareas
    if (app.initPageResizableTextarea) app.initPageResizableTextarea(pageContainer);
    // Init Material Preloader
    if (app.params.material && app.initPageMaterialPreloader) app.initPageMaterialPreloader(pageContainer);
    // Init Material Inputs
    if (app.params.material && app.initPageMaterialInputs) app.initPageMaterialInputs(pageContainer);
    // Init Material Tabbar
    if (app.params.material && app.initPageMaterialTabbar) app.initPageMaterialTabbar(pageContainer);
};
app.reinitPage = function (pageContainer) {
    pageContainer = $(pageContainer);
    if (pageContainer.length === 0) return;
    // Size navbars on page reinit
    if (app.sizeNavbars) app.sizeNavbars(pageContainer.parents('.' + app.params.viewClass)[0]);
    // Reinit slider
    if (app.reinitPageSwiper) app.reinitPageSwiper(pageContainer);
    // Reinit lazy load
    if (app.reinitLazyLoad) app.reinitLazyLoad(pageContainer);
};
app.initPageWithCallback = function (pageContainer) {
    pageContainer = $(pageContainer);
    var viewContainer = pageContainer.parents('.' + app.params.viewClass);
    if (viewContainer.length === 0) return;
    var view = viewContainer[0].f7View || undefined;
    var url = view && view.url ? view.url : undefined;
    if (viewContainer && pageContainer.attr('data-page')) {
        viewContainer.attr('data-page', pageContainer.attr('data-page'));
    }
    app.pageInitCallback(view, {pageContainer: pageContainer[0], url: url, position: 'center'});
};<commit_msg>Init data tables on page init<commit_after>/*======================================================
************   Pages   ************
======================================================*/
// Page Callbacks API
app.pageCallbacks = {};

app.onPage = function (callbackName, pageName, callback) {
    if (pageName && pageName.split(' ').length > 1) {
        var pageNames = pageName.split(' ');
        var returnCallbacks = [];
        for (var i = 0; i < pageNames.length; i++) {
            returnCallbacks.push(app.onPage(callbackName, pageNames[i], callback));
        }
        returnCallbacks.remove = function () {
            for (var i = 0; i < returnCallbacks.length; i++) {
                returnCallbacks[i].remove();
            }
        };
        returnCallbacks.trigger = function () {
            for (var i = 0; i < returnCallbacks.length; i++) {
                returnCallbacks[i].trigger();
            }
        };
        return returnCallbacks;
    }
    var callbacks = app.pageCallbacks[callbackName][pageName];
    if (!callbacks) {
        callbacks = app.pageCallbacks[callbackName][pageName] = [];
    }
    app.pageCallbacks[callbackName][pageName].push(callback);
    return {
        remove: function () {
            var removeIndex;
            for (var i = 0; i < callbacks.length; i++) {
                if (callbacks[i].toString() === callback.toString()) {
                    removeIndex = i;
                }
            }
            if (typeof removeIndex !== 'undefined') callbacks.splice(removeIndex, 1);
        },
        trigger: callback
    };
};

//Create callbacks methods dynamically
function createPageCallback(callbackName) {
    var capitalized = callbackName.replace(/^./, function (match) {
        return match.toUpperCase();
    });
    app['onPage' + capitalized] = function (pageName, callback) {
        return app.onPage(callbackName, pageName, callback);
    };
}

var pageCallbacksNames = ('beforeInit init reinit beforeAnimation afterAnimation back afterBack beforeRemove').split(' ');
for (var i = 0; i < pageCallbacksNames.length; i++) {
    app.pageCallbacks[pageCallbacksNames[i]] = {};
    createPageCallback(pageCallbacksNames[i]);
}

app.triggerPageCallbacks = function (callbackName, pageName, pageData) {
    var allPagesCallbacks = app.pageCallbacks[callbackName]['*'];
    if (allPagesCallbacks) {
        for (var j = 0; j < allPagesCallbacks.length; j++) {
            allPagesCallbacks[j](pageData);
        }
    }
    var callbacks = app.pageCallbacks[callbackName][pageName];
    if (!callbacks || callbacks.length === 0) return;
    for (var i = 0; i < callbacks.length; i++) {
        callbacks[i](pageData);
    }
};

// On Page Init Callback
app.pageInitCallback = function (view, params) {
    var pageContainer = params.pageContainer;
    if (!pageContainer) return;
    if (pageContainer.f7PageInitialized && view && !view.params.domCache) return;

    var pageQuery = params.query;
    if (!pageQuery) {
        if (params.url && params.url.indexOf('?') > 0) {
            pageQuery = $.parseUrlQuery(params.url || '');
        }
        else if (pageContainer.f7PageData && pageContainer.f7PageData.query) {
            pageQuery = pageContainer.f7PageData.query;
        }
        else {
            pageQuery = {};
        }
    }

    // Page Data
    var pageData = {
        container: pageContainer,
        url: params.url,
        query: pageQuery,
        name: $(pageContainer).attr('data-page'),
        view: view,
        from: params.position,
        context: params.context,
        navbarInnerContainer: params.navbarInnerContainer,
        fromPage: params.fromPage
    };
    if (params.fromPage && !params.fromPage.navbarInnerContainer && params.oldNavbarInnerContainer) {
        params.fromPage.navbarInnerContainer = params.oldNavbarInnerContainer;
    }

    if (pageContainer.f7PageInitialized && ((view && view.params.domCache) || (!view && $(pageContainer).parents('.popup, .popover, .login-screen, .modal, .actions-modal, .picker-modal').length > 0))) {
        // Reinit Page
        app.reinitPage(pageContainer);

        // Callbacks
        app.pluginHook('pageReinit', pageData);
        if (app.params.onPageReinit) app.params.onPageReinit(app, pageData);
        app.triggerPageCallbacks('reinit', pageData.name, pageData);
        $(pageData.container).trigger('pageReinit page:reinit', {page: pageData});
        return;
    }
    pageContainer.f7PageInitialized = true;

    // Store pagedata in page
    pageContainer.f7PageData = pageData;

    // Update View's activePage
    if (view && !params.preloadOnly && !params.reloadPrevious) {
        // Add data-page on view
        $(view.container).attr('data-page', pageData.name);
        // Update View active page data
        view.activePage = pageData;
    }

    // Before Init Callbacks
    app.pluginHook('pageBeforeInit', pageData);
    if (app.params.onPageBeforeInit) app.params.onPageBeforeInit(app, pageData);
    app.triggerPageCallbacks('beforeInit', pageData.name, pageData);
    $(pageData.container).trigger('pageBeforeInit page:beforeinit', {page: pageData});

    // Init page
    app.initPage(pageContainer);

    // Init Callback
    app.pluginHook('pageInit', pageData);
    if (app.params.onPageInit) app.params.onPageInit(app, pageData);
    app.triggerPageCallbacks('init', pageData.name, pageData);
    $(pageData.container).trigger('pageInit page:init', {page: pageData});
};
app.pageRemoveCallback = function (view, pageContainer, position) {
    var pageContext;
    if (!pageContainer) return;
    if (pageContainer.f7PageData) pageContext = pageContainer.f7PageData.context;
    // Page Data
    var pageData = {
        container: pageContainer,
        name: $(pageContainer).attr('data-page'),
        view: view,
        url: pageContainer.f7PageData && pageContainer.f7PageData.url,
        query: pageContainer.f7PageData && pageContainer.f7PageData.query,
        navbarInnerContainer: pageContainer.f7PageData && pageContainer.f7PageData.navbarInnerContainer,
        from: position,
        context: pageContext
    };
    // Before Init Callback
    app.pluginHook('pageBeforeRemove', pageData);
    if (app.params.onPageBeforeRemove) app.params.onPageBeforeRemove(app, pageData);
    app.triggerPageCallbacks('beforeRemove', pageData.name, pageData);
    $(pageData.container).trigger('pageBeforeRemove page:beforeremove', {page: pageData});
    pageData = null;
};
app.pageBackCallback = function (callback, view, params) {
    // Page Data
    var pageContainer = params.pageContainer;
    var pageContext;
    if (!pageContainer) return;
    if (pageContainer.f7PageData) pageContext = pageContainer.f7PageData.context;

    var pageData = {
        container: pageContainer,
        name: $(pageContainer).attr('data-page'),
        url: pageContainer.f7PageData && pageContainer.f7PageData.url,
        query: pageContainer.f7PageData && pageContainer.f7PageData.query,
        view: view,
        from: params.position,
        context: pageContext,
        navbarInnerContainer: pageContainer.f7PageData && pageContainer.f7PageData.navbarInnerContainer,
        swipeBack: params.swipeBack
    };

    if (callback === 'after') {
        app.pluginHook('pageAfterBack', pageData);
        if (app.params.onPageAfterBack) app.params.onPageAfterBack(app, pageData);
        app.triggerPageCallbacks('afterBack', pageData.name, pageData);
        $(pageContainer).trigger('pageAfterBack page:afterback', {page: pageData});

    }
    if (callback === 'before') {
        app.pluginHook('pageBack', pageData);
        if (app.params.onPageBack) app.params.onPageBack(app, pageData);
        app.triggerPageCallbacks('back', pageData.name, pageData);
        $(pageData.container).trigger('pageBack page:back', {page: pageData});
    }
};
app.pageAnimCallback = function (callback, view, params) {
    var pageContainer = params.pageContainer;
    var pageContext;
    if (!pageContainer) return;
    if (pageContainer.f7PageData) pageContext = pageContainer.f7PageData.context;

    var pageQuery = params.query;
    if (!pageQuery) {
        if (params.url && params.url.indexOf('?') > 0) {
            pageQuery = $.parseUrlQuery(params.url || '');
        }
        else if (pageContainer.f7PageData && pageContainer.f7PageData.query) {
            pageQuery = pageContainer.f7PageData.query;
        }
        else {
            pageQuery = {};
        }
    }
    // Page Data
    var pageData = {
        container: pageContainer,
        url: params.url,
        query: pageQuery,
        name: $(pageContainer).attr('data-page'),
        view: view,
        from: params.position,
        context: pageContext,
        swipeBack: params.swipeBack,
        navbarInnerContainer: pageContainer.f7PageData && pageContainer.f7PageData.navbarInnerContainer,
        fromPage: params.fromPage
    };
    var oldPage = params.oldPage,
        newPage = params.newPage;

    // Update page date
    pageContainer.f7PageData = pageData;

    if (callback === 'after') {
        app.pluginHook('pageAfterAnimation', pageData);
        if (app.params.onPageAfterAnimation) app.params.onPageAfterAnimation(app, pageData);
        app.triggerPageCallbacks('afterAnimation', pageData.name, pageData);
        $(pageData.container).trigger('pageAfterAnimation page:afteranimation', {page: pageData});

    }
    if (callback === 'before') {
        // Add data-page on view
        $(view.container).attr('data-page', pageData.name);

        // Update View's activePage
        if (view) view.activePage = pageData;

        // Hide/show navbar dynamically
        if (newPage.hasClass('no-navbar') && !oldPage.hasClass('no-navbar')) {
            view.hideNavbar();
        }
        if (!newPage.hasClass('no-navbar') && (oldPage.hasClass('no-navbar') || oldPage.hasClass('no-navbar-by-scroll'))) {
            view.showNavbar();
        }
        // Hide/show navbar toolbar
        if (newPage.hasClass('no-toolbar') && !oldPage.hasClass('no-toolbar')) {
            view.hideToolbar();
        }
        if (!newPage.hasClass('no-toolbar') && (oldPage.hasClass('no-toolbar') || oldPage.hasClass('no-toolbar-by-scroll'))) {
            view.showToolbar();
        }
        // Hide/show tabbar
        var tabBar;
        if (newPage.hasClass('no-tabbar') && !oldPage.hasClass('no-tabbar')) {
            tabBar = $(view.container).find('.tabbar');
            if (tabBar.length === 0) tabBar = $(view.container).parents('.' + app.params.viewsClass).find('.tabbar');
            app.hideToolbar(tabBar);
        }
        if (!newPage.hasClass('no-tabbar') && (oldPage.hasClass('no-tabbar') || oldPage.hasClass('no-tabbar-by-scroll'))) {
            tabBar = $(view.container).find('.tabbar');
            if (tabBar.length === 0) tabBar = $(view.container).parents('.' + app.params.viewsClass).find('.tabbar');
            app.showToolbar(tabBar);
        }

        oldPage.removeClass('no-navbar-by-scroll no-toolbar-by-scroll');
        // Callbacks
        app.pluginHook('pageBeforeAnimation', pageData);
        if (app.params.onPageBeforeAnimation) app.params.onPageBeforeAnimation(app, pageData);
        app.triggerPageCallbacks('beforeAnimation', pageData.name, pageData);
        $(pageData.container).trigger('pageBeforeAnimation page:beforeanimation', {page: pageData});
    }
};

// Init Page Events and Manipulations
app.initPage = function (pageContainer) {
    pageContainer = $(pageContainer);
    if (pageContainer.length === 0) return;
    // Size navbars on page load
    if (app.sizeNavbars) app.sizeNavbars(pageContainer.parents('.' + app.params.viewClass)[0]);
    // Init messages
    if (app.initPageMessages) app.initPageMessages(pageContainer);
    // Init forms storage
    if (app.initFormsStorage) app.initFormsStorage(pageContainer);
    // Init smart select
    if (app.initSmartSelects) app.initSmartSelects(pageContainer);
    // Init slider
    if (app.initPageSwiper) app.initPageSwiper(pageContainer);
    // Init pull to refres
    if (app.initPullToRefresh) app.initPullToRefresh(pageContainer);
    // Init infinite scroll
    if (app.initPageInfiniteScroll) app.initPageInfiniteScroll(pageContainer);
    // Init searchbar
    if (app.initSearchbar) app.initSearchbar(pageContainer);
    // Init message bar
    if (app.initPageMessagebar) app.initPageMessagebar(pageContainer);
    // Init scroll toolbars
    if (app.initPageScrollToolbars) app.initPageScrollToolbars(pageContainer);
    // Init lazy images
    if (app.initImagesLazyLoad) app.initImagesLazyLoad(pageContainer);
    // Init progress bars
    if (app.initPageProgressbar) app.initPageProgressbar(pageContainer);
    // Init resizeable textareas
    if (app.initPageResizableTextarea) app.initPageResizableTextarea(pageContainer);
    // Init Material Preloader
    if (app.params.material && app.initPageMaterialPreloader) app.initPageMaterialPreloader(pageContainer);
    // Init Material Inputs
    if (app.params.material && app.initPageMaterialInputs) app.initPageMaterialInputs(pageContainer);
    // Init Material Tabbar
    if (app.params.material && app.initPageMaterialTabbar) app.initPageMaterialTabbar(pageContainer);
    // Init Data Table
    if (app.initPageDataTables) app.initPageDataTables(pageContainer);
};
app.reinitPage = function (pageContainer) {
    pageContainer = $(pageContainer);
    if (pageContainer.length === 0) return;
    // Size navbars on page reinit
    if (app.sizeNavbars) app.sizeNavbars(pageContainer.parents('.' + app.params.viewClass)[0]);
    // Reinit slider
    if (app.reinitPageSwiper) app.reinitPageSwiper(pageContainer);
    // Reinit lazy load
    if (app.reinitLazyLoad) app.reinitLazyLoad(pageContainer);
};
app.initPageWithCallback = function (pageContainer) {
    pageContainer = $(pageContainer);
    var viewContainer = pageContainer.parents('.' + app.params.viewClass);
    if (viewContainer.length === 0) return;
    var view = viewContainer[0].f7View || undefined;
    var url = view && view.url ? view.url : undefined;
    if (viewContainer && pageContainer.attr('data-page')) {
        viewContainer.attr('data-page', pageContainer.attr('data-page'));
    }
    app.pageInitCallback(view, {pageContainer: pageContainer[0], url: url, position: 'center'});
};
<|endoftext|>


<commit_before>/* global Storage, Utils, Logger, JSONF $ */
/*eslint no-unused-vars:0 */
var Workflows = {
  all: function() {
    return new Promise(function (resolve) {
      Promise.all([Storage.load(Utils.keys.workflows), Storage.load(Utils.keys.shadowStorage)]).then(function prWfLoad(workflowsAndShadow) {
        if (typeof workflowsAndShadow === "undefined") {
          resolve([]);
        } else {
          var workflows = workflowsAndShadow[0];

          // No workflows in active rule set?
          if (typeof workflows === "undefined") {
            workflows = [];
          }

          // Do we have shadow workflows?
          if (typeof workflowsAndShadow[1] !== "undefined" && typeof workflowsAndShadow[1].workflows !== "undefined") {
            workflows = workflows.concat(workflowsAndShadow[1].workflows.map(function(workflow) {
              workflow.shadow = true;
              return workflow;
            }));
          }

          resolve(workflows);
        }
      });
    });
  },
  findById: function(id) {
    return new Promise(function (resolve) {
      Workflows.all().then(function prFindById(wfs) {
        resolve(wfs.filter(function (wf) {
          /*eslint-disable eqeqeq*/
          return wf.id == id;
          /*eslint-enable eqeqeq*/
        })[0]);
      });
    });
  },
  save: function(workflowData) {
    Logger.info("[g/workflow.js] Saving " + workflowData.length + " workflows");
    return Storage.save(workflowData, Utils.keys.workflows);
  },
  delete: function(workflowId) {
    this.load().then(function(workflows) {
      var newWfs = workflows.filter(function wfFilterDel(wf) {
        /*eslint-disable eqeqeq*/
        return wf.id != workflowId;
        /*eslint-enable eqeqeq*/
      });
      Workflows.save(newWfs);
    });
  },
  matchesForRules: function(rules) {
    return new Promise(function (resolve) {
      // Find workflows that match those rules (start only)
      var matchingRuleNames = rules.map(function cbStepsMap(rule) {
        return rule.name;
      });

      Workflows.all().then(function prMatchesForRules(workflows) {
        var matchingWorkflows = [];
        if (typeof workflows !== "undefined") {
          matchingWorkflows = workflows.filter(function cbWfFilter(workflow) {
            return matchingRuleNames.indexOf(workflow.steps[0]) > -1;
          });
        }
        resolve(matchingWorkflows);
      });
    });
  },
  saveMatches: function(workflows) {
    return Storage.save(JSONF.stringify(workflows), Utils.keys.lastMatchingWorkflows);
  },
  loadMatches: function() {
    return new Promise(function (resolve) {
      Storage.load(Utils.keys.lastMatchingWorkflows).then(function (rawMatches) {
        resolve(JSONF.parse(rawMatches));
      });
    });
  },
  exportDataJson: function() {
    return new Promise(function (resolve) {
      Storage.load(Utils.keys.workflows).then(function(workflowData) {

        // Not workflow saved yet.
        if (typeof workflowData === "undefined") {
          resolve([]);
        }

        workflowData = workflowData.map(function cbWfDataMap(workflow) {
          workflow.steps = $.makeArray(workflow.steps);
          return workflow;
        });

        resolve(workflowData);
      });
    });
  }
};

<commit_msg>safeguard<commit_after>/* global Storage, Utils, Logger, JSONF $ */
/*eslint no-unused-vars:0 */
var Workflows = {
  all: function() {
    return new Promise(function (resolve) {
      Promise.all([Storage.load(Utils.keys.workflows), Storage.load(Utils.keys.shadowStorage)]).then(function prWfLoad(workflowsAndShadow) {
        if (typeof workflowsAndShadow === "undefined") {
          resolve([]);
        } else {
          var workflows = workflowsAndShadow[0];

          // No workflows in active rule set?
          if (typeof workflows === "undefined") {
            workflows = [];
          }

          // Do we have shadow workflows?
          if (typeof workflowsAndShadow[1] !== "undefined" && typeof workflowsAndShadow[1].workflows !== "undefined") {
            workflows = workflows.concat(workflowsAndShadow[1].workflows.map(function(workflow) {
              workflow.shadow = true;
              return workflow;
            }));
          }

          resolve(workflows);
        }
      });
    });
  },
  findById: function(id) {
    return new Promise(function (resolve) {
      Workflows.all().then(function prFindById(wfs) {
        resolve(wfs.filter(function (wf) {
          /*eslint-disable eqeqeq*/
          return wf.id == id;
          /*eslint-enable eqeqeq*/
        })[0]);
      });
    });
  },
  save: function(workflowData) {
    Logger.info("[g/workflow.js] Saving " + workflowData.length + " workflows");
    return Storage.save(workflowData, Utils.keys.workflows);
  },
  delete: function(workflowId) {
    this.load().then(function(workflows) {
      var newWfs = workflows.filter(function wfFilterDel(wf) {
        /*eslint-disable eqeqeq*/
        return wf.id != workflowId;
        /*eslint-enable eqeqeq*/
      });
      Workflows.save(newWfs);
    });
  },
  matchesForRules: function(rules) {
    return new Promise(function (resolve) {
      // Find workflows that match those rules (start only)
      var matchingRuleNames = rules.map(function cbStepsMap(rule) {
        return rule.name;
      });

      Workflows.all().then(function prMatchesForRules(workflows) {
        var matchingWorkflows = [];
        if (typeof workflows !== "undefined") {
          matchingWorkflows = workflows.filter(function cbWfFilter(workflow) {
            return matchingRuleNames.indexOf(workflow.steps[0]) > -1;
          });
        }
        resolve(matchingWorkflows);
      });
    });
  },
  saveMatches: function(workflows) {
    return Storage.save(JSONF.stringify(workflows), Utils.keys.lastMatchingWorkflows);
  },
  loadMatches: function() {
    return new Promise(function (resolve) {
      Storage.load(Utils.keys.lastMatchingWorkflows).then(function (rawMatches) {
        resolve(JSONF.parse(rawMatches));
      });
    });
  },
  exportDataJson: function() {
    return new Promise(function (resolve) {
      Storage.load(Utils.keys.workflows).then(function(workflowData) {

        // Not workflow saved yet.
        if (typeof workflowData === "undefined" || typeof workflowData.map !== "function") {
          resolve([]);
        }

        workflowData = workflowData.map(function cbWfDataMap(workflow) {
          workflow.steps = $.makeArray(workflow.steps);
          return workflow;
        });

        resolve(workflowData);
      });
    });
  }
};

<|endoftext|>


<commit_before>/*
 *  Majiang.Dev.Game
 */
"use strict";

const Majiang = require('../../majiang');

const assert = require('assert');

function make_shan(log) {

    function set_qipai(paistr) {
        for (let suitstr of paistr.match(/[mpsz]\d+/g)) {
            let s = suitstr[0];
            for (let n of suitstr.match(/\d/g)) { shan._pai[--zimo_idx] = s+n }
        }
    }

    const shan = new Majiang.Shan();
    for (let i = 0; i < shan._pai.length; i++) { shan._pai[i] = '_' }

    let zimo_idx = shan._pai.length;
    let gang_idx = 0;
    let baopai   = [];
    let fubaopai = [];

    for (let data of log) {
        if (data.qipai) {
            for (let l = 0; l < 4; l++) { set_qipai(data.qipai.shoupai[l]) }
            baopai.push(data.qipai.baopai);
        }
        else if (data.zimo)     shan._pai[--zimo_idx] = data.zimo.p;
        else if (data.gangzimo) shan._pai[gang_idx++] = data.gangzimo.p;
        else if (data.kaigang)  baopai.push(data.kaigang.baopai);
        else if (data.hule && data.hule.fubaopai)
                                fubaopai = data.hule.fubaopai;
    }

    for (let i = 0; i < baopai.length; i++)   { shan._pai[4 + i] = baopai[i] }
    for (let i = 0; i < fubaopai.length; i++) { shan._pai[9 + i] = fubaopai[i] }

    shan._baopai   = [ shan._pai[4] ];
    shan._fubaopai = [ shan._pai[9] ];

    return shan;
}

function make_reply(l, log) {

    const reply = [];

    for (let data of log) {
        if (data.zimo || data.gangzimo) reply.push({});
        else if (data.dapai)
            reply.push(l == data.dapai.l ? { dapai: data.dapai.p } : {});
        else if (data.fulou)
            reply.push(l == data.fulou.l ? { fulou: data.fulou.m } : {});
        else if (data.gang)
            reply.push(l == data.gang.l  ? { gang:  data.gang.m  } : {});
        else if (data.pingju) {
            if      (data.pingju.name == '九種九牌') reply.push({ pingju: '-' });
            else if (data.pingju.name.match(/^三家和/)
                    && data.pingju.shoupai[l])     reply.push({ hule: '-' });
        }
        else if (data.hule)
            if (l == data.hule.l) reply.push({ hule: '-' });
    }
    reply.shift();

    return reply;
}

class Player {
    constructor(id)       { this._reply = [] }
    action(msg, callback) { if (callback) callback(this._reply.shift()) }
}

module.exports = class Game extends Majiang.Game {
    constructor(paipu) {
        super();
        this._model.title = paipu.title;
        this._model.qijia = paipu.qijia;
        this._script = paipu;
        for (let id = 0; id < 4; id++) { this._player[id] = new Player(id) }
        this._speed = 0;
    }
    qipai() {
        const log = this._script.log.shift();
        for (let l = 0; l < 4; l++) {
            let id = (this._model.qijia + this._model.jushu + l) % 4;
            this._player[id]._reply = make_reply(l, log);
        }
        super.qipai(make_shan(log));
    }
    do_test() {
        this._stop = false;
        this._no_wait = true;
        this.kaiju();
        while (this._status != 'jieju') {
            if      (this._status == 'zimo')     this.reply_zimo();
            else if (this._status == 'dapai')    this.reply_dapai();
            else if (this._status == 'fulou')    this.reply_fulou();
            else if (this._status == 'gang')     this.reply_gang();
            else if (this._status == 'gangzimo') this.reply_zimo();
            else if (this._status == 'hule')     this.reply_hule();
            else if (this._status == 'pingju')   this.reply_pingju();
        }
        this.reply_jieju();
        return this;
    }
    stop()  { if (! this._no_wait) super.stop()  }
    start() { if (! this._no_wait) super.start() }
    delay(callback, timeout) {
        if (this._no_wait) callback();
        else super.delay(callback, timeout);
    }
    notify_players(type, msg) {
        if (this._no_wait) {
            for (let l = 0; l < 4; l++) {
                this ._player[this._model.player_id[l]].action(msg[l]);
            }
        }
        else super.notify_players(type, msg);
    }
    call_players(type, msg, timeout) {
        if (this._no_wait) {
            this._status = type;
            this._reply  = [];
            for (let l = 0; l < 4; l++) {
                let id = this._model.player_id[l];
                this._player[id].action(msg[l], reply => this.reply(id, reply));
            }
        }
        else super.call_players(type, msg, timeout);
    }
    reply(id, reply = {}) {
        if (this._no_wait) this._reply[id] = reply;
        else super.reply(id, reply);
    }
}
<commit_msg>#24 Majiang.Dev.Game を牌譜なしでも動作するよう修正<commit_after>/*
 *  Majiang.Dev.Game
 */
"use strict";

const Majiang = require('../../majiang');

const assert = require('assert');

function make_shan(log) {

    function set_qipai(paistr) {
        for (let suitstr of paistr.match(/[mpsz]\d+/g)) {
            let s = suitstr[0];
            for (let n of suitstr.match(/\d/g)) { shan._pai[--zimo_idx] = s+n }
        }
    }

    const shan = new Majiang.Shan();
    for (let i = 0; i < shan._pai.length; i++) { shan._pai[i] = '_' }

    let zimo_idx = shan._pai.length;
    let gang_idx = 0;
    let baopai   = [];
    let fubaopai = [];

    for (let data of log) {
        if (data.qipai) {
            for (let l = 0; l < 4; l++) { set_qipai(data.qipai.shoupai[l]) }
            baopai.push(data.qipai.baopai);
        }
        else if (data.zimo)     shan._pai[--zimo_idx] = data.zimo.p;
        else if (data.gangzimo) shan._pai[gang_idx++] = data.gangzimo.p;
        else if (data.kaigang)  baopai.push(data.kaigang.baopai);
        else if (data.hule && data.hule.fubaopai)
                                fubaopai = data.hule.fubaopai;
    }

    for (let i = 0; i < baopai.length; i++)   { shan._pai[4 + i] = baopai[i] }
    for (let i = 0; i < fubaopai.length; i++) { shan._pai[9 + i] = fubaopai[i] }

    shan._baopai   = [ shan._pai[4] ];
    shan._fubaopai = [ shan._pai[9] ];

    return shan;
}

function make_reply(l, log) {

    const reply = [];

    for (let data of log) {
        if (data.zimo || data.gangzimo) reply.push({});
        else if (data.dapai)
            reply.push(l == data.dapai.l ? { dapai: data.dapai.p } : {});
        else if (data.fulou)
            reply.push(l == data.fulou.l ? { fulou: data.fulou.m } : {});
        else if (data.gang)
            reply.push(l == data.gang.l  ? { gang:  data.gang.m  } : {});
        else if (data.pingju) {
            if      (data.pingju.name == '九種九牌') reply.push({ pingju: '-' });
            else if (data.pingju.name.match(/^三家和/)
                    && data.pingju.shoupai[l])     reply.push({ hule: '-' });
        }
        else if (data.hule)
            if (l == data.hule.l) reply.push({ hule: '-' });
    }
    reply.shift();

    return reply;
}

class Player {
    constructor(id)       { this._reply = [] }
    action(msg, callback) { if (callback) callback(this._reply.shift()) }
}

module.exports = class Game extends Majiang.Game {
    constructor(paipu) {
        super();
        if (paipu) {
            this._model.title = paipu.title;
            this._model.qijia = paipu.qijia;
            this._script = paipu;
            for (let id = 0; id < 4; id++) { this._player[id] = new Player(id) }
        }
        else {
            this._player = [0,1,2,3].map(id=>new Majiang.Player(id));
        }
        this._speed = 0;
    }
    qipai() {
        if (this._script) {
            const log = this._script.log.shift();
            for (let l = 0; l < 4; l++) {
                let id = (this._model.qijia + this._model.jushu + l) % 4;
                this._player[id]._reply = make_reply(l, log);
            }
            super.qipai(make_shan(log));
        }
        else {
            super.qipai();
        }
    }
    do_test() {
        this._stop = false;
        this._no_wait = true;
        this.kaiju();
        while (this._status != 'jieju') {
            if      (this._status == 'zimo')     this.reply_zimo();
            else if (this._status == 'dapai')    this.reply_dapai();
            else if (this._status == 'fulou')    this.reply_fulou();
            else if (this._status == 'gang')     this.reply_gang();
            else if (this._status == 'gangzimo') this.reply_zimo();
            else if (this._status == 'hule')     this.reply_hule();
            else if (this._status == 'pingju')   this.reply_pingju();
        }
        this.reply_jieju();
        return this;
    }
    stop()  { if (! this._no_wait) super.stop()  }
    start() { if (! this._no_wait) super.start() }
    delay(callback, timeout) {
        if (this._no_wait) callback();
        else super.delay(callback, timeout);
    }
    notify_players(type, msg) {
        if (this._no_wait) {
            for (let l = 0; l < 4; l++) {
                this ._player[this._model.player_id[l]].action(msg[l]);
            }
        }
        else super.notify_players(type, msg);
    }
    call_players(type, msg, timeout) {
        if (this._no_wait) {
            this._status = type;
            this._reply  = [];
            for (let l = 0; l < 4; l++) {
                let id = this._model.player_id[l];
                this._player[id].action(msg[l], reply => this.reply(id, reply));
            }
        }
        else super.call_players(type, msg, timeout);
    }
    reply(id, reply = {}) {
        if (this._no_wait) this._reply[id] = reply;
        else super.reply(id, reply);
    }
}
<|endoftext|>


<commit_before>
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
	pluginType: 'native',

	setCurrentTime: function (time) {
		this.currentTime = time;
	},

	setMuted: function (muted) {
		this.muted = muted;
	},

	setVolume: function (volume) {
		this.volume = volume;
	},

	// for parity with the plugin versions
	stop: function () {
		this.pause();
	},

	// This can be a url string
	// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
	setSrc: function (url) {
		if (typeof url == 'string') {
			this.src = url;
		} else {
			var i, media;

			for (i=0; i<url.length; i++) {
				media = url[i];
				if (this.canPlayType(media.type)) {
					this.src = media.src;
				}
			}
		}
	},

	setVideoSize: function (width, height) {
		this.width = width;
		this.height = height;
	}
};

/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
	this.id = pluginid;
	this.pluginType = pluginType;
	this.src = mediaUrl;
	this.events = {};
};

// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {

	// special
	pluginElement: null,
	pluginType: '',

	// not implemented :(
	playbackRate: -1,
	defaultPlaybackRate: -1,
	seekable: [],
	played: [],

	// HTML5 read-only properties
	paused: true,
	ended: false,
	seeking: false,
	duration: 0,

	// HTML5 get/set properties, but only set (updated by event handlers)
	muted: false,
	volume: 1,
	currentTime: 0,

	// HTML5 methods
	play: function () {
		if (this.pluginApi != null) {
			this.pluginApi.playMedia();
			this.paused = false;
		}
	},
	load: function () {
		if (this.pluginApi != null) {
			this.pluginApi.loadMedia();
			this.paused = false;
		}
	},
	pause: function () {
		if (this.pluginApi != null) {
			this.pluginApi.pauseMedia();
			this.paused = true;
		}
	},
	stop: function () {
		if (this.pluginApi != null) {
			this.pluginApi.stopMedia();
			this.paused = true;
		}
	},
	canPlayType: function(type) {
		var i,
			j,
			pluginInfo,
			pluginVersions = mejs.plugins[this.pluginType];

		for (i=0; i<pluginVersions.length; i++) {
			pluginInfo = pluginVersions[i];

			// test if user has the correct plugin version
			if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {

				// test for plugin playback types
				for (j=0; j<pluginInfo.types.length; j++) {
					// find plugin that can play the type
					if (type == pluginInfo.types[j]) {
						return true;
					}
				}
			}
		}

		return false;
	},

	// custom methods since not all JavaScript implementations support get/set

	// This can be a url string
	// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
	setSrc: function (url) {
		if (typeof url == 'string') {
			this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
			this.src = mejs.Utility.absolutizeUrl(url);
		} else {
			var i, media;

			for (i=0; i<url.length; i++) {
				media = url[i];
				if (this.canPlayType(media.type)) {
					this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
					this.src = mejs.Utility.absolutizeUrl(url);
				}
			}
		}

	},
	setCurrentTime: function (time) {
		if (this.pluginApi != null) {
			this.pluginApi.setCurrentTime(time);
			this.currentTime = time;
		}
	},
	setVolume: function (volume) {
		if (this.pluginApi != null) {
			this.pluginApi.setVolume(volume);
			this.volume = volume;
		}
	},
	setMuted: function (muted) {
		if (this.pluginApi != null) {
			this.pluginApi.setMuted(muted);
			this.muted = muted;
		}
	},

	// additional non-HTML5 methods
	setVideoSize: function (width, height) {
		if ( this.pluginElement.style) {
			this.pluginElement.style.width = width + 'px';
			this.pluginElement.style.height = height + 'px';
		}
		if (this.pluginApi != null) {
			this.pluginApi.setVideoSize(width, height);
		}
	},

	setFullscreen: function (fullscreen) {
		if (this.pluginApi != null) {
			this.pluginApi.setFullscreen(fullscreen);
		}
	},

	// start: fake events
	addEventListener: function (eventName, callback, bubble) {
		this.events[eventName] = this.events[eventName] || [];
		this.events[eventName].push(callback);
	},
	dispatchEvent: function (eventName) {
		var i,
			args,
			callbacks = this.events[eventName];

		if (callbacks) {
			args = Array.prototype.slice.call(arguments, 1);
			for (i = 0; i < callbacks.length; i++) {
				callbacks[i].apply(null, args);
			}
		}
	}
	// end: fake events
};
<commit_msg>- added error object to shim for future use.<commit_after>
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
	pluginType: 'native',

	setCurrentTime: function (time) {
		this.currentTime = time;
	},

	setMuted: function (muted) {
		this.muted = muted;
	},

	setVolume: function (volume) {
		this.volume = volume;
	},

	// for parity with the plugin versions
	stop: function () {
		this.pause();
	},

	// This can be a url string
	// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
	setSrc: function (url) {
		if (typeof url == 'string') {
			this.src = url;
		} else {
			var i, media;

			for (i=0; i<url.length; i++) {
				media = url[i];
				if (this.canPlayType(media.type)) {
					this.src = media.src;
				}
			}
		}
	},

	setVideoSize: function (width, height) {
		this.width = width;
		this.height = height;
	}
};

/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
	this.id = pluginid;
	this.pluginType = pluginType;
	this.src = mediaUrl;
	this.events = {};
};

// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {

	// special
	pluginElement: null,
	pluginType: '',

	// not implemented :(
	playbackRate: -1,
	defaultPlaybackRate: -1,
	seekable: [],
	played: [],

	// HTML5 read-only properties
	paused: true,
	ended: false,
	seeking: false,
	duration: 0,
	error: null,

	// HTML5 get/set properties, but only set (updated by event handlers)
	muted: false,
	volume: 1,
	currentTime: 0,

	// HTML5 methods
	play: function () {
		if (this.pluginApi != null) {
			this.pluginApi.playMedia();
			this.paused = false;
		}
	},
	load: function () {
		if (this.pluginApi != null) {
			this.pluginApi.loadMedia();
			this.paused = false;
		}
	},
	pause: function () {
		if (this.pluginApi != null) {
			this.pluginApi.pauseMedia();
			this.paused = true;
		}
	},
	stop: function () {
		if (this.pluginApi != null) {
			this.pluginApi.stopMedia();
			this.paused = true;
		}
	},
	canPlayType: function(type) {
		var i,
			j,
			pluginInfo,
			pluginVersions = mejs.plugins[this.pluginType];

		for (i=0; i<pluginVersions.length; i++) {
			pluginInfo = pluginVersions[i];

			// test if user has the correct plugin version
			if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {

				// test for plugin playback types
				for (j=0; j<pluginInfo.types.length; j++) {
					// find plugin that can play the type
					if (type == pluginInfo.types[j]) {
						return true;
					}
				}
			}
		}

		return false;
	},

	// custom methods since not all JavaScript implementations support get/set

	// This can be a url string
	// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
	setSrc: function (url) {
		if (typeof url == 'string') {
			this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
			this.src = mejs.Utility.absolutizeUrl(url);
		} else {
			var i, media;

			for (i=0; i<url.length; i++) {
				media = url[i];
				if (this.canPlayType(media.type)) {
					this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
					this.src = mejs.Utility.absolutizeUrl(url);
				}
			}
		}

	},
	setCurrentTime: function (time) {
		if (this.pluginApi != null) {
			this.pluginApi.setCurrentTime(time);
			this.currentTime = time;
		}
	},
	setVolume: function (volume) {
		if (this.pluginApi != null) {
			this.pluginApi.setVolume(volume);
			this.volume = volume;
		}
	},
	setMuted: function (muted) {
		if (this.pluginApi != null) {
			this.pluginApi.setMuted(muted);
			this.muted = muted;
		}
	},

	// additional non-HTML5 methods
	setVideoSize: function (width, height) {
		if ( this.pluginElement.style) {
			this.pluginElement.style.width = width + 'px';
			this.pluginElement.style.height = height + 'px';
		}
		if (this.pluginApi != null) {
			this.pluginApi.setVideoSize(width, height);
		}
	},

	setFullscreen: function (fullscreen) {
		if (this.pluginApi != null) {
			this.pluginApi.setFullscreen(fullscreen);
		}
	},

	// start: fake events
	addEventListener: function (eventName, callback, bubble) {
		this.events[eventName] = this.events[eventName] || [];
		this.events[eventName].push(callback);
	},
	dispatchEvent: function (eventName) {
		var i,
			args,
			callbacks = this.events[eventName];

		if (callbacks) {
			args = Array.prototype.slice.call(arguments, 1);
			for (i = 0; i < callbacks.length; i++) {
				callbacks[i].apply(null, args);
			}
		}
	}
	// end: fake events
};
<|endoftext|>