<commit_before>'use strict'

const crypto = require('crypto');
const resolve = require('path').resolve;
const fs = require('fs');
const suffixTest = /\.json$/;
const root = resolve(process.argv[2] || '.') + '/';
const env_config = require(root + 'flow.json');
const path = root + 'network/';
const states = {};
const files = fs.readdirSync(path);
const rdf_syntax = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
const hashids = {};
const hashlbs = {};
const envs = {};
const fn_states = {};
const temp_index = {};

function write (subject, predicate, object) {
    process.stdout.write(subject + ' <' + predicate + '> ' + object + ' .\n');
}

function UID (len) {
    len = len || 23;
    let i = 0, random = '';
    for (; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return '_:' + crypto.createHash('md5').update(random).digest('hex');
}

function getHash (string, name, type) {
    let hash = '_:' + crypto.createHash('md5').update(string).digest('hex');
    if (!hashids[hash]) {
        hashids[hash] = 1;
        write(hash, rdf_syntax + 'string', '"' + string.replace(/"/g, '\\"') + '"');
        write(hash, rdf_syntax + 'type', '<http://schema.jillix.net/vocab/' + (type || 'Name') + '>');

        if (name) {
            write(hash, 'http://schema.org/name', getHash(name));
        }
    }

    return hash;
}

function getFnState (name) {

    if (!fn_states[name]) {

        fn_states[name] = UID();

        write(
            fn_states[name],
            rdf_syntax + 'type',
            'http://schema.jillix.net/vocab/State'
        );

        // role name
        write(
            fn_states[name],
            'http://schema.org/name',
            getHash(name)
        );
    }

    return fn_states[name];
}

// create network triple
const network_id = UID();

// network name (Service)
write(
    network_id,
    'http://schema.org/name',
    getHash(env_config.network)
);

// network type
write(
    network_id,
    rdf_syntax + 'type',
    '<http://schema.jillix.net/vocab/Network>'
);

// public role
const public_role = getHash('*');

// role type
write(
    public_role,
    rdf_syntax + 'type',
    'http://schema.jillix.net/vocab/Role'
);

// role name
write(
    public_role,
    'http://schema.org/name',
    getHash('Public Role')
);

// Convert composition files to triples
files.forEach(file => {

    if (!suffixTest.test(file)) {
        return;
    }

    let state;
    try {
        state = JSON.parse(fs.readFileSync(path + file));
    } catch (error) {
        throw new Error(path + file + '\n' + error);
    }

    //states[state.name] = state;
    states[file] = state;
});

// create env objects
if (env_config) {

    if (env_config.environments) {
        env_config.environments.forEach(env => {
            const env_uid = UID();

            // create json edge
            write(
                env_uid,
                'http://schema.jillix.net/vocab/json',
                getHash(JSON.stringify(env.vars))
            );

            // evnironment type
            write(
                env_uid,
                rdf_syntax + 'type',
                'http://schema.jillix.net/vocab/Environment'
            );

            // environment name
            write(
                env_uid,
                'http://schema.org/name',
                getHash(env.name)
            );

            envs[env.name] = env_uid;
        });
    }

    if (env_config.entrypoints) {
        env_config.entrypoints.forEach(ep => {

            const entrypoint_id = UID();

            // network entrypoint
            write(
                network_id,
                'http://schema.jillix.net/vocab/entrypoint',
                entrypoint_id
            );

            // entrypoint name
            write(
                entrypoint_id,
                'http://schema.org/name',
                getHash(ep.name)
            );

            // entrypoint type
            write(
                entrypoint_id,
                rdf_syntax + 'type',
                '<http://schema.jillix.net/vocab/Entrypoint>'
            );

            // entrypoint environment
            if (ep.env) {
                ep.env.forEach(env => {
                    if (envs[env]) {
                        write(
                            entrypoint_id,
                            'http://schema.jillix.net/vocab/environment',
                            envs[env]
                        );
                    }
                });
            }

            // entrypoint sequence
            write(
                entrypoint_id,
                'http://schema.jillix.net/vocab/sequence',
                '_:' + crypto.createHash('md5').update(ep.emit).digest('hex')
            );
        });
    }
}

// sequences
for (let name in states) {

    // sequence
    for (let sequence in states[name]) {
        let seq = states[name][sequence];
        let sequence_id = '_:' + crypto.createHash('md5').update(sequence).digest('hex');

        // name
        write(
            sequence_id,
            'http://schema.org/name',
            getHash(sequence.toUpperCase())
        );

        // type
        write(
            sequence_id,
            rdf_syntax + 'type',
            '<http://schema.jillix.net/vocab/Sequence>'
        );

        // roles
        write(
            sequence_id,
            'http://schema.jillix.net/vocab/role',
            public_role
        );

        // end event
        if (seq[2]) {
            write(
                sequence_id,
                'http://schema.jillix.net/vocab/onEnd',
                '_:' + crypto.createHash('md5').update(seq[2]).digest('hex')
            );
        }

        // error event
        if (seq[1]) {
            write(
                sequence_id,
                'http://schema.jillix.net/vocab/onError',
                '_:' + crypto.createHash('md5').update(seq[1]).digest('hex')
            );
        }

        // handlers
        let previous;

        // handler
        seq[0].forEach((handler, index) => {

            let handler_id = UID();
            let handler_name = typeof handler === 'string' ? 'Emit:' + handler : handler[1] + '/' + handler[2];

            // name
            write(
                handler_id,
                'http://schema.org/name',
                getHash(handler_name)
            );

            // sequence emit
            if (typeof handler === 'string') {

                // type Emit
                write(
                    handler_id,
                    rdf_syntax + 'type',
                    '<http://schema.jillix.net/vocab/Emit>'
                );

                // sequence
                write(
                    handler_id,
                    'http://schema.jillix.net/vocab/sequence',
                    '_:' + crypto.createHash('md5').update(handler).digest('hex')
                );

            // data handler
            } else {

                // state
                write(
                    handler_id,
                    'http://schema.jillix.net/vocab/state',
                    getFnState(handler[3])
                );

                // type data
                write(
                    handler_id,
                    rdf_syntax + 'type',
                    '<http://schema.jillix.net/vocab/Data>'
                );

                // function
                write(
                    handler_id,
                    'http://schema.jillix.net/vocab/fn',
                    '<' + handler[0] + '/' + handler[1] + '?' + handler[2] + '>'
                );
            }

            // next
            write(
                index === 0 ? sequence_id : previous,
                'http://schema.jillix.net/vocab/next',
                handler_id
            );

            previous = handler_id;

            // link back to sequence (owner)
            write(
                sequence_id,
                'http://schema.jillix.net/vocab/handler',
                handler_id
            );

            // method args
            if (typeof handler !== 'string' && handler[4]) {
                let args = JSON.stringify(handler[4]);

                // potential emits from args
                let potential_emits = args.match(/\{FLOW\:([^\}]+)\}/g);
                let emits = [];
                if (potential_emits) {
                    potential_emits.forEach(emit => {
                        let replace = emit;
                        emit = emit.slice(6, -1);
                        emit = '_:' + crypto.createHash('md5').update(emit).digest('hex');
                        args = args.replace(replace, emit);
                        emits.push(emit);
                    });
                }

                const args_uid = UID();

                // create json edge
                write(
                    args_uid,
                    'http://schema.jillix.net/vocab/json',
                    getHash(JSON.stringify(args))
                );

                // args type
                write(
                    args_uid,
                    rdf_syntax + 'type',
                    'http://schema.jillix.net/vocab/Args'
                );

                // args name
                write(
                    args_uid,
                    'http://schema.org/name',
                    getHash("Args:" + handler[2])
                );

                emits.forEach(emit => {
                    let key = args_uid + emit;
                    if (!temp_index[key]) {
                        temp_index[key] = 1;
                        write(
                            args_uid,
                            'http://schema.jillix.net/vocab/sequence',
                            emit
                        );
                    }
                });
            }
        });
    }
}
<commit_msg>fix type objects<commit_after>'use strict'

const crypto = require('crypto');
const resolve = require('path').resolve;
const fs = require('fs');
const suffixTest = /\.json$/;
const root = resolve(process.argv[2] || '.') + '/';
const env_config = require(root + 'flow.json');
const path = root + 'network/';
const states = {};
const files = fs.readdirSync(path);
const rdf_syntax = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
const hashids = {};
const hashlbs = {};
const envs = {};
const fn_states = {};
const temp_index = {};

function write (subject, predicate, object) {
    process.stdout.write(subject + ' <' + predicate + '> ' + object + ' .\n');
}

function UID (len) {
    len = len || 23;
    let i = 0, random = '';
    for (; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return '_:' + crypto.createHash('md5').update(random).digest('hex');
}

function getHash (string, name, type) {
    let hash = '_:' + crypto.createHash('md5').update(string).digest('hex');
    if (!hashids[hash]) {
        hashids[hash] = 1;
        write(hash, rdf_syntax + 'string', '"' + string.replace(/"/g, '\\"') + '"');
        write(hash, rdf_syntax + 'type', '<http://schema.jillix.net/vocab/' + (type || 'Name') + '>');

        if (name) {
            write(hash, 'http://schema.org/name', getHash(name));
        }
    }

    return hash;
}

function getFnState (name) {

    if (!fn_states[name]) {

        fn_states[name] = UID();

        write(
            fn_states[name],
            rdf_syntax + 'type',
            '<http://schema.jillix.net/vocab/State>'
        );

        // role name
        write(
            fn_states[name],
            'http://schema.org/name',
            getHash(name)
        );
    }

    return fn_states[name];
}

// create network triple
const network_id = UID();

// network name (Service)
write(
    network_id,
    'http://schema.org/name',
    getHash(env_config.network)
);

// network type
write(
    network_id,
    rdf_syntax + 'type',
    '<http://schema.jillix.net/vocab/Network>'
);

// public role
const public_role = getHash('*');

// role type
write(
    public_role,
    rdf_syntax + 'type',
    'http://schema.jillix.net/vocab/Role'
);

// role name
write(
    public_role,
    'http://schema.org/name',
    getHash('Public Role')
);

// Convert composition files to triples
files.forEach(file => {

    if (!suffixTest.test(file)) {
        return;
    }

    let state;
    try {
        state = JSON.parse(fs.readFileSync(path + file));
    } catch (error) {
        throw new Error(path + file + '\n' + error);
    }

    //states[state.name] = state;
    states[file] = state;
});

// create env objects
if (env_config) {

    if (env_config.environments) {
        env_config.environments.forEach(env => {
            const env_uid = UID();

            // create json edge
            write(
                env_uid,
                'http://schema.jillix.net/vocab/json',
                getHash(JSON.stringify(env.vars))
            );

            // evnironment type
            write(
                env_uid,
                rdf_syntax + 'type',
                '<http://schema.jillix.net/vocab/Environment>'
            );

            // environment name
            write(
                env_uid,
                'http://schema.org/name',
                getHash(env.name)
            );

            envs[env.name] = env_uid;
        });
    }

    if (env_config.entrypoints) {
        env_config.entrypoints.forEach(ep => {

            const entrypoint_id = UID();

            // network entrypoint
            write(
                network_id,
                'http://schema.jillix.net/vocab/entrypoint',
                entrypoint_id
            );

            // entrypoint name
            write(
                entrypoint_id,
                'http://schema.org/name',
                getHash(ep.name)
            );

            // entrypoint type
            write(
                entrypoint_id,
                rdf_syntax + 'type',
                '<http://schema.jillix.net/vocab/Entrypoint>'
            );

            // entrypoint environment
            if (ep.env) {
                ep.env.forEach(env => {
                    if (envs[env]) {
                        write(
                            entrypoint_id,
                            'http://schema.jillix.net/vocab/environment',
                            envs[env]
                        );
                    }
                });
            }

            // entrypoint sequence
            write(
                entrypoint_id,
                'http://schema.jillix.net/vocab/sequence',
                '_:' + crypto.createHash('md5').update(ep.emit).digest('hex')
            );
        });
    }
}

// sequences
for (let name in states) {

    // sequence
    for (let sequence in states[name]) {
        let seq = states[name][sequence];
        let sequence_id = '_:' + crypto.createHash('md5').update(sequence).digest('hex');

        // name
        write(
            sequence_id,
            'http://schema.org/name',
            getHash(sequence.toUpperCase())
        );

        // type
        write(
            sequence_id,
            rdf_syntax + 'type',
            '<http://schema.jillix.net/vocab/Sequence>'
        );

        // roles
        write(
            sequence_id,
            'http://schema.jillix.net/vocab/role',
            public_role
        );

        // end event
        if (seq[2]) {
            write(
                sequence_id,
                'http://schema.jillix.net/vocab/onEnd',
                '_:' + crypto.createHash('md5').update(seq[2]).digest('hex')
            );
        }

        // error event
        if (seq[1]) {
            write(
                sequence_id,
                'http://schema.jillix.net/vocab/onError',
                '_:' + crypto.createHash('md5').update(seq[1]).digest('hex')
            );
        }

        // handlers
        let previous;

        // handler
        seq[0].forEach((handler, index) => {

            let handler_id = UID();
            let handler_name = typeof handler === 'string' ? 'Emit:' + handler : handler[1] + '/' + handler[2];

            // name
            write(
                handler_id,
                'http://schema.org/name',
                getHash(handler_name)
            );

            // sequence emit
            if (typeof handler === 'string') {

                // type Emit
                write(
                    handler_id,
                    rdf_syntax + 'type',
                    '<http://schema.jillix.net/vocab/Emit>'
                );

                // sequence
                write(
                    handler_id,
                    'http://schema.jillix.net/vocab/sequence',
                    '_:' + crypto.createHash('md5').update(handler).digest('hex')
                );

            // data handler
            } else {

                // state
                write(
                    handler_id,
                    'http://schema.jillix.net/vocab/state',
                    getFnState(handler[3])
                );

                // type data
                write(
                    handler_id,
                    rdf_syntax + 'type',
                    '<http://schema.jillix.net/vocab/Data>'
                );

                // function
                write(
                    handler_id,
                    'http://schema.jillix.net/vocab/fn',
                    '<' + handler[0] + '/' + handler[1] + '?' + handler[2] + '>'
                );
            }

            // next
            write(
                index === 0 ? sequence_id : previous,
                'http://schema.jillix.net/vocab/next',
                handler_id
            );

            previous = handler_id;

            // link back to sequence (owner)
            write(
                sequence_id,
                'http://schema.jillix.net/vocab/handler',
                handler_id
            );

            // method args
            if (typeof handler !== 'string' && handler[4]) {
                let args = JSON.stringify(handler[4]);

                // potential emits from args
                let potential_emits = args.match(/\{FLOW\:([^\}]+)\}/g);
                let emits = [];
                if (potential_emits) {
                    potential_emits.forEach(emit => {
                        let replace = emit;
                        emit = emit.slice(6, -1);
                        emit = '_:' + crypto.createHash('md5').update(emit).digest('hex');
                        args = args.replace(replace, emit);
                        emits.push(emit);
                    });
                }

                const args_uid = UID();

                write(
                    handler_id,
                    'http://schema.jillix.net/vocab/args',
                    args_uid
                );

                // create json edge
                write(
                    args_uid,
                    'http://schema.jillix.net/vocab/json',
                    getHash(args)
                );

                // args type
                write(
                    args_uid,
                    rdf_syntax + 'type',
                    '<http://schema.jillix.net/vocab/Args>'
                );

                // args name
                write(
                    args_uid,
                    'http://schema.org/name',
                    getHash("Args:" + handler[2])
                );

                emits.forEach(emit => {
                    let key = args_uid + emit;
                    if (!temp_index[key]) {
                        temp_index[key] = 1;
                        write(
                            args_uid,
                            'http://schema.jillix.net/vocab/sequence',
                            emit
                        );
                    }
                });
            }
        });
    }
}
<|endoftext|>


<commit_before>import Ember from 'ember';

export function initialize(applicationInstance) {

	let router = applicationInstance.lookupFactory('router:main');

  router.map(function(){
	this.route('gittest');
});
}

export default {
  name: 'addroute',
  initialize
};
<commit_msg>error .lookupFactory is not a function<commit_after>import Ember from 'ember';

export function initialize(applicationInstance) {

	let router = applicationInstance.lookup('router:main');

  router.map(function(){
	this.route('gittest');
});
}

export default {
  name: 'addroute',
  initialize
};
<|endoftext|>


<commit_before>import BaseTheme from '../../base/ui/components/BaseTheme.native';

const SECONDARY_COLOR = BaseTheme.palette.border04;

export default {
    joinButton: {
        marginVertical: BaseTheme.spacing[3]
    },

    buttonStylesBorderless: {
        iconStyle: {
            color: BaseTheme.palette.icon01,
            fontSize: 24
        },
        style: {
            flexDirection: 'row',
            justifyContent: 'center',
            margin: BaseTheme.spacing[3],
            height: 24,
            width: 24
        },
        underlayColor: 'transparent'
    },

    contentWrapper: {
        flex: 1
    },

    contentWrapperWide: {
        flex: 1,
        flexDirection: 'row'
    },

    largeVideoContainer: {
        minHeight: '60%'
    },

    largeVideoContainerWide: {
        height: '100%',
        marginRight: 'auto',
        position: 'absolute',
        width: '60%'
    },

    contentContainer: {
        alignSelf: 'center',
        display: 'flex',
        justifyContent: 'center',
        minHeight: '40%',
        padding: BaseTheme.spacing[3],
        width: 400
    },

    contentContainerWide: {
        alignSelf: 'center',
        height: '100%',
        justifyContent: 'center',
        left: '60%',
        padding: BaseTheme.spacing[3],
        position: 'absolute',
        width: '40%'
    },

    toolboxContainer: {
        alignSelf: 'center',
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'center'
    },

    toolboxContainerWide: {
        flexDirection: 'row',
        justifyContent: 'center'
    },

    formWrapper: {
        alignSelf: 'stretch',
        justifyContent: 'center',
        marginHorizontal: BaseTheme.spacing[3]
    },

    field: {
        backgroundColor: BaseTheme.palette.field02,
        borderColor: SECONDARY_COLOR,
        borderRadius: BaseTheme.shape.borderRadius,
        borderWidth: 2,
        color: BaseTheme.palette.text06,
        height: BaseTheme.spacing[7],
        textAlign: 'center'
    },

    preJoinRoomName: {
        ...BaseTheme.typography.heading5,
        color: BaseTheme.palette.text01,
        textAlign: 'center'
    },

    displayRoomNameBackdrop: {
        alignSelf: 'center',
        backgroundColor: BaseTheme.palette.ui16,
        bottom: BaseTheme.spacing[3],
        borderRadius: 4,
        paddingHorizontal: BaseTheme.spacing[3],
        paddingVertical: BaseTheme.spacing[1],
        position: 'absolute'
    }
};
<commit_msg>feat(prejoin/native): adjusted room name margins<commit_after>import BaseTheme from '../../base/ui/components/BaseTheme.native';

const SECONDARY_COLOR = BaseTheme.palette.border04;

export default {
    joinButton: {
        marginVertical: BaseTheme.spacing[3]
    },

    buttonStylesBorderless: {
        iconStyle: {
            color: BaseTheme.palette.icon01,
            fontSize: 24
        },
        style: {
            flexDirection: 'row',
            justifyContent: 'center',
            margin: BaseTheme.spacing[3],
            height: 24,
            width: 24
        },
        underlayColor: 'transparent'
    },

    contentWrapper: {
        flex: 1
    },

    contentWrapperWide: {
        flex: 1,
        flexDirection: 'row'
    },

    largeVideoContainer: {
        minHeight: '60%'
    },

    largeVideoContainerWide: {
        height: '100%',
        marginRight: 'auto',
        position: 'absolute',
        width: '60%'
    },

    contentContainer: {
        alignSelf: 'center',
        display: 'flex',
        justifyContent: 'center',
        minHeight: '40%',
        padding: BaseTheme.spacing[3],
        width: 400
    },

    contentContainerWide: {
        alignSelf: 'center',
        height: '100%',
        justifyContent: 'center',
        left: '60%',
        padding: BaseTheme.spacing[3],
        position: 'absolute',
        width: '40%'
    },

    toolboxContainer: {
        alignSelf: 'center',
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'center'
    },

    toolboxContainerWide: {
        flexDirection: 'row',
        justifyContent: 'center'
    },

    formWrapper: {
        alignSelf: 'stretch',
        justifyContent: 'center',
        marginHorizontal: BaseTheme.spacing[3]
    },

    field: {
        backgroundColor: BaseTheme.palette.field02,
        borderColor: SECONDARY_COLOR,
        borderRadius: BaseTheme.shape.borderRadius,
        borderWidth: 2,
        color: BaseTheme.palette.text06,
        height: BaseTheme.spacing[7],
        textAlign: 'center'
    },

    preJoinRoomName: {
        ...BaseTheme.typography.heading5,
        color: BaseTheme.palette.text01,
        textAlign: 'center'
    },

    displayRoomNameBackdrop: {
        alignSelf: 'center',
        backgroundColor: BaseTheme.palette.ui16,
        bottom: BaseTheme.spacing[3],
        borderRadius: 4,
        margin: BaseTheme.spacing[3],
        paddingHorizontal: BaseTheme.spacing[3],
        paddingVertical: BaseTheme.spacing[1],
        position: 'absolute'
    }
};
<|endoftext|>


<commit_before>/*globals $, GOVUK, suchi */
/*jslint
 white: true,
 browser: true */

$(function() {
  "use strict";
  function browserWarning() {
    var container = $('

'),
        text = $('
Upgrade your web browser (the software you use to access the internet), it’s out of date
'),
        closeLink = $('Close');

    return container.append(text.append(closeLink));
  }

  // we don't show the message when the cookie warning is also there
  if (GOVUK.cookie('seen_cookie_message')) {
    if (suchi.isOld(navigator.userAgent)) {
      if(GOVUK.cookie('govuk_not_first_visit') !== null && GOVUK.cookie('govuk_browser_upgrade_dismissed') === null){
        var $prompt = browserWarning();
        $('#global-cookie-message').after($prompt);
        $prompt.show();
        window._gaq && _gaq.push(['_trackEvent', 'browser-check', 'prompt-shown', '', 1, true]);
        $prompt.on("click", ".dismiss", function(e) {
          $prompt.hide();
          // the warning is dismissable for 4 weeks, for users who are not in a
          // position to upgrade right now or unable to (no control of browser)
          GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 28 });
        });
      }
    }

    // We're not showing the message on first visit
    GOVUK.cookie('govuk_not_first_visit', 'yes', { days: 28 });
  }
});
<commit_msg>Track browser-check in universal analytics<commit_after>/*globals $, GOVUK, suchi */
/*jslint
 white: true,
 browser: true */

$(function() {
  "use strict";
  function browserWarning() {
    var container = $('

'),
        text = $('
Upgrade your web browser (the software you use to access the internet), it’s out of date
'),
        closeLink = $('Close');

    return container.append(text.append(closeLink));
  }

  // we don't show the message when the cookie warning is also there
  if (GOVUK.cookie('seen_cookie_message')) {
    if (suchi.isOld(navigator.userAgent)) {
      if(GOVUK.cookie('govuk_not_first_visit') !== null && GOVUK.cookie('govuk_browser_upgrade_dismissed') === null){
        var $prompt = browserWarning();
        $('#global-cookie-message').after($prompt);
        $prompt.show();
        GOVUK.analytics.trackEvent('browser-check', 'prompt-shown', '', 1, true);
        $prompt.on("click", ".dismiss", function(e) {
          $prompt.hide();
          // the warning is dismissable for 4 weeks, for users who are not in a
          // position to upgrade right now or unable to (no control of browser)
          GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 28 });
        });
      }
    }

    // We're not showing the message on first visit
    GOVUK.cookie('govuk_not_first_visit', 'yes', { days: 28 });
  }
});
<|endoftext|>


<commit_before>(function () {
    'use strict';

    define(
        [
            'page',
            'querystring',
            'util/bind'
        ],
        function (page, qs, bind) {
            var routes, types = [ 'library', 'photographs', 'museum', 'memorials' ];

            routes = function () {
                page('/', function (context) {
                    return bind('ui/pages/static/home', 'ui/pages/static/StaticPage', context);
                });

                page('/about', function (context) {
                    return bind('ui/pages/static/about', 'ui/pages/static/StaticPage', context);
                });

                page('/:type/search', function (context) {
                    if (types.indexOf(context.params.type) < 0) {
                        return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                    }
                    return bind('ui/pages/search/index', 'ui/pages/search/SearchPage', context);
                });

                page('/:type/detail/:id', function (context) {
                    if (types.indexOf(context.params.type) < 0) {
                        return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                    }
                    return bind('ui/pages/detail/' + context.params.type, 'ui/pages/detail/DetailPage', context);
                });

                page('*', function (context) {
                    return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                });

                page();
            };

            routes.searchUrlFor = function (type, query) {
                if (types.indexOf(type) < 0) {
                    throw new Error('Cannot get search URL for unknown type "' + type + '"');
                }
                return '/' + type + '/search' + (query ? '?' + qs.stringify(query) : '');
            };

            routes.detailUrlFor = function (type, id) {
                if (types.indexOf(type) < 0) {
                    throw new Error('Cannot get detail URL for unknown type "' + type + '"');
                }
                return '/' + type + '/detail/' + id;
            };

            return routes;
        }
    );
}());
<commit_msg>Remove unwanted check.<commit_after>(function () {
    'use strict';

    define(
        [
            'page',
            'querystring',
            'util/bind'
        ],
        function (page, qs, bind) {
            var routes, types = [ 'library', 'photographs', 'museum', 'memorials' ];

            routes = function () {
                page('/', function (context) {
                    return bind('ui/pages/static/home', 'ui/pages/static/StaticPage', context);
                });

                page('/about', function (context) {
                    return bind('ui/pages/static/about', 'ui/pages/static/StaticPage', context);
                });

                page('/:type/search', function (context) {
                    if (types.indexOf(context.params.type) < 0) {
                        return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                    }
                    return bind('ui/pages/search/index', 'ui/pages/search/SearchPage', context);
                });

                page('/:type/detail/:id', function (context) {
                    if (types.indexOf(context.params.type) < 0) {
                        return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                    }
                    return bind('ui/pages/detail/' + context.params.type, 'ui/pages/detail/DetailPage', context);
                });

                page('*', function (context) {
                    return bind('ui/pages/error/404', 'ui/pages/error/ErrorPage', context);
                });

                page();
            };

            routes.searchUrlFor = function (type, query) {
                return '/' + type + '/search' + (query ? '?' + qs.stringify(query) : '');
            };

            routes.detailUrlFor = function (type, id) {
                return '/' + type + '/detail/' + id;
            };

            return routes;
        }
    );
}());
<|endoftext|>


<commit_before>define([
    'angular',
    './piwik-tracking',
    './google-tracking'
], function(angular, PiwikTracking, GoogleTracking) {
    'use strict';

    function NoopTracking() {
        this.track = angular.noop;
    }

    return angular.module('superdesk.analytics', [])

        .service('analytics', ['config', function(config) {
            if (config.analytics.piwik.url) {
                PiwikTracking.call(this, config.analytics.piwik);
            } else if (config.analytics.ga.id) {
                GoogleTracking.call(this, config.analytics.ga);
            } else {
                NoopTracking.call(this);
            }
        }])

        .run(['$rootScope', 'analytics', function($rootScope, analytics) {
            $rootScope.$on('$routeChangeSuccess', function(ev, route) {
                analytics.track(route.$$route);
            });
        }]);
});
<commit_msg>analytics.js: nextRoute from $routeChangeSuccess can be undefined<commit_after>define([
    'angular',
    './piwik-tracking',
    './google-tracking'
], function(angular, PiwikTracking, GoogleTracking) {
    'use strict';

    function NoopTracking() {
        this.track = angular.noop;
    }

    return angular.module('superdesk.analytics', [])

        .service('analytics', ['config', function(config) {
            if (config.analytics.piwik.url) {
                PiwikTracking.call(this, config.analytics.piwik);
            } else if (config.analytics.ga.id) {
                GoogleTracking.call(this, config.analytics.ga);
            } else {
                NoopTracking.call(this);
            }
        }])

        .run(['$rootScope', 'analytics', function($rootScope, analytics) {
            $rootScope.$on('$routeChangeSuccess', function(ev, route) {
                if (angular.isDefined(route)) {
                    analytics.track(route.$$route);
                }
            });
        }]);
});
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
// TODO: Add correct decoded token variable below
// var decodedToken = tokenDecoder;
//----------------------------------------------------------------------------//

// Get messages for specific user
router.get('/get-all-messages', function(req, res) {
  // var userEmail = req.decodedToken.email;
  // var userType = req.headers.type,
  //     typeId = userType + '_id',
  //     userDatabase = userType + 's';
  // var userId = req.userId;

  var typeId = 'mentor_id';
  var userId = '58';

  pg.connect(connectionString, function(error, client, done){
    // connectionErrorCheck();
    if (error) {
      console.log('Database connection error: ', error);
      res.sendStatus(500);
    }

    // Query the database for the user's messages
    client.query(
      'SELECT * FROM messages where ' + typeId + ' = $1', [userId],
      function(error, result) {
        done(); // Close connection to database

        if (error) {
          console.log('Database SELECT error when searching for user messages: ', error);
          res.sendStatus(500);
        } else {
          // res.sendStatus(201).send(result.rows);
          console.log('result', result.rows);
          res.send(result.rows);
        }
      }
    );
  });
});

// // Create new message when user hits the "Send" button
// router.post('/new-message', function(req, res) {
//   var userId = req.userId; // provided by token decoder route
//   // TODO: Make sure mentor email makes it onto the request
//   var mentorEmail = req.headers.message.mentorEmail;
//   // TODO: Check where message is coming through from the client
//   var message = req.headers.message;
//
//   pg.connect(connectionString, function(error, client, done) {
//     connectionErrorCheck();
//
//     // Find mentor_id
//     client.query(
//       'SELECT id FROM mentors WHERE email = $1', [mentorEmail],
//       function(error, result) {
//         if (error) {
//           console.log('Database SELECT error when searching for mentor ID: ', error);
//           res.sendStatus(500);
//         } else {
//           var mentorId = result.rows[0].id; // TODO: Verify this value is returning correctly
//           // Create new message record
//           client.query(
//             'INSERT INTO messages' +
//             '(mentor_id, student_id, date_sent, subject, message, student_name) ' +
//             'VALUES ($1, $2, now(), $3, $4, $5)',
//             [mentorId, userId, message.subject, message.body, message.student_name],
//             function(error, result) {
//               done(); // Close connection to database
//               if (error) {
//                 console.log('Error creating new message: ', error);
//                 res.sendStatus(500);
//               } else {
//                 res.sendStatus(201);
//               }
//             }
//           );
//         }
//       }
//     );
//   });
// });

// Mark message as read
router.put('/read-message', function(req, res) {
  var messageId = req.body.message.id;

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck();

    client.query(
      'UPDATE messages SET message_read = TRUE WHERE id = $1',
      [messageId],
      function(error, result) {
        if (error) {
          console.log('Unable to mark message as read: ', error);
          res.sendStatus(500);
        } else {
          res.sendStatus(200);
        }
      }
    );
  });
});
//
// // Reply to message
// router.put('/reply', function(req, res) {
//   var messageId = req.headers.message.id;
//   var messageReply = req.headers.message.reply;
//
//   pg.connect(connectionString, function(error, client, done) {
//     connectionErrorCheck();
//
//     client.query(
//       'UPDATE messages SET reply = $1 WHERE id = $2',
//       [messageReply, messageId],
//       function(error, result) {
//         if (error) {
//           console.log('UPDATE database error: ', error);
//           res.sendStatus(500);
//         } else {
//           res.sendStatus(200);
//         }
//       }
//     );
//   });
// });

module.exports = router;

function connectionErrorCheck() {
  if (error) {
    console.log('Database connection error: ', error);
    res.sendStatus(500);
  }
}
<commit_msg>Build route for marking a messages as read<commit_after>//----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
// TODO: Add correct decoded token variable below
// var decodedToken = tokenDecoder;
//----------------------------------------------------------------------------//

// Get messages for specific user
router.get('/get-all-messages', function(req, res) {
  // var userEmail = req.decodedToken.email;
  // var userType = req.headers.type,
  //     typeId = userType + '_id',
  //     userDatabase = userType + 's';
  // var userId = req.userId;

  var typeId = 'mentor_id';
  var userId = '58';

  pg.connect(connectionString, function(error, client, done){
    connectionErrorCheck(error);
    if (error) {
      console.log('Database connection error: ', error);
      res.sendStatus(500);
    }

    // Query the database for the user's messages
    client.query(
      'SELECT * FROM messages where ' + typeId + ' = $1', [userId],
      function(error, result) {
        done(); // Close connection to database

        if (error) {
          console.log('Database SELECT error when searching for user messages: ', error);
          res.sendStatus(500);
        } else {
          // res.sendStatus(201).send(result.rows);
          console.log('result', result.rows);
          res.send(result.rows);
        }
      }
    );
  });
});

// // Create new message when user hits the "Send" button
// router.post('/new-message', function(req, res) {
//   var userId = req.userId; // provided by token decoder route
//   // TODO: Make sure mentor email makes it onto the request
//   var mentorEmail = req.headers.message.mentorEmail;
//   // TODO: Check where message is coming through from the client
//   var message = req.headers.message;
//
//   pg.connect(connectionString, function(error, client, done) {
//     connectionErrorCheck(error);
//
//     // Find mentor_id
//     client.query(
//       'SELECT id FROM mentors WHERE email = $1', [mentorEmail],
//       function(error, result) {
//         if (error) {
//           console.log('Database SELECT error when searching for mentor ID: ', error);
//           res.sendStatus(500);
//         } else {
//           var mentorId = result.rows[0].id; // TODO: Verify this value is returning correctly
//           // Create new message record
//           client.query(
//             'INSERT INTO messages' +
//             '(mentor_id, student_id, date_sent, subject, message, student_name) ' +
//             'VALUES ($1, $2, now(), $3, $4, $5)',
//             [mentorId, userId, message.subject, message.body, message.student_name],
//             function(error, result) {
//               done(); // Close connection to database
//               if (error) {
//                 console.log('Error creating new message: ', error);
//                 res.sendStatus(500);
//               } else {
//                 res.sendStatus(201);
//               }
//             }
//           );
//         }
//       }
//     );
//   });
// });

// Mark message as read
router.put('/read-message', function(req, res) {
  var messageId = req.body.message.id;

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    client.query(
      'UPDATE messages SET message_read = TRUE WHERE id = $1',
      [messageId],
      function(error, result) {
        if (error) {
          console.log('Unable to mark message as read: ', error);
          res.sendStatus(500);
        } else {
          res.sendStatus(200);
        }
      }
    );
  });
});
//
// // Reply to message
// router.put('/reply', function(req, res) {
//   var messageId = req.headers.message.id;
//   var messageReply = req.headers.message.reply;
//
//   pg.connect(connectionString, function(error, client, done) {
//     connectionErrorCheck(error);
//
//     client.query(
//       'UPDATE messages SET reply = $1 WHERE id = $2',
//       [messageReply, messageId],
//       function(error, result) {
//         if (error) {
//           console.log('UPDATE database error: ', error);
//           res.sendStatus(500);
//         } else {
//           res.sendStatus(200);
//         }
//       }
//     );
//   });
// });

module.exports = router;

function connectionErrorCheck(error) {
  if (error) {
    console.log('Database connection error: ', error);
    res.sendStatus(500);
  }
}
<|endoftext|>


<commit_before>module.config([
	'$locationProvider',
	'$routeProvider',
	'$httpProvider',
	function ($locationProvider, $routeProvider, $httpProvider) {
		$locationProvider.html5Mode(true);

		//

		$routeProvider.when('/', {
			controller: 'HomeView',
			templateUrl: 'homeView.html',
			resolve: {
				investigators: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						page.models.Party.query({
							access: page.permission.CONTRIBUTE,
							institution: false
						}, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						return deferred.promise;
					}
				],
				users: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						page.models.Party.query({
							access: page.permission.PUBLIC,
							institution: false
						}, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						return deferred.promise;
					}
				],
				volume: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						if (!page.constants.data.locked || page.auth.isAuthorized()) {
							page.models.Volume.get({
								id: 9,
								access: ''
							}, function (res) {
								deferred.resolve(res);
							}, function (res) {
								deferred.reject(res);
							});
						} else {
							deferred.resolve({});
						}

						return deferred.promise;
					}
				]
			},
			reloadOnSearch: false,
			authenticate: false
		});

		//

		$routeProvider.when('/login', {
			controller: 'LoginView',
			templateUrl: 'loginView.html',
			reloadOnSearch: false
		});

		//

		$routeProvider.when('/register', {
			controller: 'RegisterView',
			templateUrl: 'registerView.html',
			reloadOnSearch: false
		});

		//

		$routeProvider.when('/password', {
			controller: 'ResetView',
			templateUrl: 'resetView.html',
			reloadOnSearch: false
		});

		//

		$routeProvider.when('/error', {
			controller: 'ErrorView',
			templateUrl: 'errorView.html',
			reloadOnSearch: false
		});

		//

		$routeProvider.when('/asset/formats', {
			controller: 'HelpFormatsView',
			templateUrl: 'helpFormatsView.html',
			reloadOnSearch: false,
			authenticate: true,
		});

		//

		$routeProvider.when('/token/:id', {
			controller: (function () {
				return window.$play.object && window.$play.object.reset ? 'ResetView' : 'RegisterView';
			}()),
			templateUrl: function () {
				return window.$play.object && window.$play.object.reset ? 'resetView.html' : 'registerView.html';
			},
			resolve: {
				token: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						if (page.$window.$play.object && page.$window.$play.object.auth) {
							deferred.resolve(page.$window.$play.object);
						} else {
							page.$http
								.get('/api/token/' + page.$route.current.params.id + '?auth=' + page.$route.current.params.auth)
								.success(function (res) {
									page.$window.$play.object = res;
									deferred.resolve(res);
								})
								.error(function (res) {
									deferred.reject(res);
									page.$location.url('/');
								});
						}

						return deferred.promise;
					}
				]
			},
			reloadOnSearch: false
		});

		//

		$routeProvider.when('/search', {
			controller: 'SearchView',
			templateUrl: 'searchView.html',
			resolve: {
				volumes: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						page.models.Volume.query({}, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						return deferred.promise;
					}
				]
			},
			reloadOnSearch: false,
			authenticate: true
		});

		//

		var partyView = {
			controller: 'PartyView',
			templateUrl: 'partyView.html',
			resolve: {
				party: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						var req = {
							comments: '',
							access: '',
							openid: '',
							duns: '',
							parents: '',
							children: '',
						};

						if (page.$route.current.params.id) {
							req.id = page.$route.current.params.id;
						} else if (page.auth.isLoggedIn()) {
							req.id = page.auth.user.id;
						} else if (page.types.isParty(page.$window.$play.object)) {
							req.id = page.$window.$play.object.id;
						}

						if (page.$route.current.params.id) {
							page.models.Party.get(req, function (res) {
								deferred.resolve(res);
							}, function (res) {
								deferred.reject(res);
							});
						} else {
							page.models.Party.profile(req, function (res) {
								deferred.resolve(res);
							}, function (res) {
								deferred.reject(res);
							});
						}

						return deferred.promise;
					}
				],
				volumes: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						var req = {
							id: null
						};

						if (page.$route.current.params.id) {
							req.party = page.$route.current.params.id;
						} else if (page.auth.isLoggedIn()) {
							req.party = page.auth.user.id;
						} else if (page.types.isParty(page.$window.$play.object)) {
							req.party = page.$window.$play.object.id;
						}

						if (page.constants.data.locked && !page.auth.isAuthorized()) {
							return [];
						}

						page.models.Volume.query(req, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						return deferred.promise;
					}
				]
			},
			reloadOnSearch: false,
			authenticate: true
		};

		$routeProvider.when('/party/:id', partyView);
		$routeProvider.when('/profile', partyView);

		//

		var partyEditParty;

		$routeProvider.when('/party/:id/edit', {
			controller: 'PartyEditView',
			templateUrl: 'partyEditView.html',
			resolve: {
				party: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						page.models.Party.get({
							id: page.$route.current.params.id,
							duns: '',
							parents: '',
							children: '',
						}, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						partyEditParty = deferred.promise;
						return deferred.promise;
					}
				],
				partyAuth: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						var empty = {
							parents: {},
							children: {},
						};

						partyEditParty.then(function (party) {
							if (page.auth.hasAccess('ADMIN', party)) {
								page.models.PartyAuthorize.query(function (res) {
									deferred.resolve(res);
								}, function (res) {
									deferred.reject(res);
								});
							} else {
								deferred.resolve(empty);
							}
						}, function (res) {
							deferred.resolve(empty);
						});

						return deferred.promise;
					}
				],
			},
			reloadOnSearch: false,
			authenticate: true
		});

		//

		var volumeEditVolume;

		var volumeEdit = {
			controller: 'VolumeEditView',
			templateUrl: 'volumeEditView.html',
			resolve: {
				volume: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						if (!page.$route.current.params.id) {
							deferred.resolve();
						} else {
							page.models.Volume.get({
								access: '',
								citation: '',
								top: '',
								funding: '',
							}, function (res) {
								deferred.resolve(res);
							}, function (res) {
								deferred.reject(res);
							});
						}

						volumeEditVolume = deferred.promise;
						return volumeEditVolume;
					}
				],
				slot: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						if (!page.$route.current.params.id) {
							deferred.resolve();
						} else {
							volumeEditVolume.then(function (volume) {
								page.models.Slot.get({
									id: volume.top.id,
									assets: '',
								}, function (res) {
									deferred.resolve(res);
								}, function (res) {
									deferred.reject(res);
								});
							});
						}

						return deferred.promise;
					}
				],
			},
			reloadOnSearch: false,
			authenticate: true
		};

		$routeProvider.when('/volume/create', volumeEdit);
		$routeProvider.when('/volume/:id/edit', volumeEdit);

		//

		$routeProvider.when('/volume/:id', {
			controller: 'VolumeView',
			templateUrl: 'volumeView.html',
			resolve: {
				volume: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						page.models.Volume.get({
							access: '',
							citation: '',
							funding: '',
							providers: '',
							consumers: '',
							top: '',
							tags: '',
							excerpts: '',
							comments: '',
							records: '',
							summary: '',
							sessions: '',
							categories: ''
						}, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						return deferred.promise;
					}
				]
			},
			reloadOnSearch: false,
			authenticate: true
		});

		//

		$routeProvider.otherwise({
			redirectTo: '/search'
		});
	}
]);

module.run([
	'pageService', function (page) {
		if (page.constants.data.locked) {
		page.$rootScope.$on('$routeChangeStart', function (event, next) {
			if (page.auth.isLoggedIn()) {
				if (!page.auth.isAuthorized()) {
					if (!next.$$route) {
						page.$location.url(page.router.register());
					}

					var controller = angular.isFunction(next.$$route.controller) ? next.$$route.controller() : next.$$route.controller;

					if (controller !== 'RegisterView') {
						page.$location.url(page.router.register());
					}
				} else if (!next.authenticate && next.$$route.controller !== 'ErrorView' && next.$$route.originalPath !== '/profile') {
					page.$location.url(page.router.index());
				}
			} else {
				if (page.auth.isPasswordPending() && next.$$route && next.$$route.controller != 'RegisterView' && (!angular.isFunction(next.$$route.controller) || next.$$route.controller() != 'RegisterView')) {
					page.$location.url(page.router.register());
				} else if (next.authenticate) {
					page.$location.url(page.router.index());
				}
			}
		});
		}
	}
]);

<commit_msg>Don't fall over if can't load splash volume<commit_after>module.config([
	'$locationProvider',
	'$routeProvider',
	'$httpProvider',
	function ($locationProvider, $routeProvider, $httpProvider) {
		$locationProvider.html5Mode(true);

		//

		$routeProvider.when('/', {
			controller: 'HomeView',
			templateUrl: 'homeView.html',
			resolve: {
				investigators: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						page.models.Party.query({
							access: page.permission.CONTRIBUTE,
							institution: false
						}, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						return deferred.promise;
					}
				],
				users: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						page.models.Party.query({
							access: page.permission.PUBLIC,
							institution: false
						}, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						return deferred.promise;
					}
				],
				volume: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						if (!page.constants.data.locked || page.auth.isAuthorized()) {
							page.models.Volume.get({
								id: 9,
								access: ''
							}, function (res) {
								deferred.resolve(res);
							}, function (res) {
								deferred.resolve({});
							});
						} else {
							deferred.resolve({});
						}

						return deferred.promise;
					}
				]
			},
			reloadOnSearch: false,
			authenticate: false
		});

		//

		$routeProvider.when('/login', {
			controller: 'LoginView',
			templateUrl: 'loginView.html',
			reloadOnSearch: false
		});

		//

		$routeProvider.when('/register', {
			controller: 'RegisterView',
			templateUrl: 'registerView.html',
			reloadOnSearch: false
		});

		//

		$routeProvider.when('/password', {
			controller: 'ResetView',
			templateUrl: 'resetView.html',
			reloadOnSearch: false
		});

		//

		$routeProvider.when('/error', {
			controller: 'ErrorView',
			templateUrl: 'errorView.html',
			reloadOnSearch: false
		});

		//

		$routeProvider.when('/asset/formats', {
			controller: 'HelpFormatsView',
			templateUrl: 'helpFormatsView.html',
			reloadOnSearch: false,
			authenticate: true,
		});

		//

		$routeProvider.when('/token/:id', {
			controller: (function () {
				return window.$play.object && window.$play.object.reset ? 'ResetView' : 'RegisterView';
			}()),
			templateUrl: function () {
				return window.$play.object && window.$play.object.reset ? 'resetView.html' : 'registerView.html';
			},
			resolve: {
				token: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						if (page.$window.$play.object && page.$window.$play.object.auth) {
							deferred.resolve(page.$window.$play.object);
						} else {
							page.$http
								.get('/api/token/' + page.$route.current.params.id + '?auth=' + page.$route.current.params.auth)
								.success(function (res) {
									page.$window.$play.object = res;
									deferred.resolve(res);
								})
								.error(function (res) {
									deferred.reject(res);
									page.$location.url('/');
								});
						}

						return deferred.promise;
					}
				]
			},
			reloadOnSearch: false
		});

		//

		$routeProvider.when('/search', {
			controller: 'SearchView',
			templateUrl: 'searchView.html',
			resolve: {
				volumes: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						page.models.Volume.query({}, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						return deferred.promise;
					}
				]
			},
			reloadOnSearch: false,
			authenticate: true
		});

		//

		var partyView = {
			controller: 'PartyView',
			templateUrl: 'partyView.html',
			resolve: {
				party: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						var req = {
							comments: '',
							access: '',
							openid: '',
							duns: '',
							parents: '',
							children: '',
						};

						if (page.$route.current.params.id) {
							req.id = page.$route.current.params.id;
						} else if (page.auth.isLoggedIn()) {
							req.id = page.auth.user.id;
						} else if (page.types.isParty(page.$window.$play.object)) {
							req.id = page.$window.$play.object.id;
						}

						if (page.$route.current.params.id) {
							page.models.Party.get(req, function (res) {
								deferred.resolve(res);
							}, function (res) {
								deferred.reject(res);
							});
						} else {
							page.models.Party.profile(req, function (res) {
								deferred.resolve(res);
							}, function (res) {
								deferred.reject(res);
							});
						}

						return deferred.promise;
					}
				],
				volumes: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						var req = {
							id: null
						};

						if (page.$route.current.params.id) {
							req.party = page.$route.current.params.id;
						} else if (page.auth.isLoggedIn()) {
							req.party = page.auth.user.id;
						} else if (page.types.isParty(page.$window.$play.object)) {
							req.party = page.$window.$play.object.id;
						}

						if (page.constants.data.locked && !page.auth.isAuthorized()) {
							return [];
						}

						page.models.Volume.query(req, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						return deferred.promise;
					}
				]
			},
			reloadOnSearch: false,
			authenticate: true
		};

		$routeProvider.when('/party/:id', partyView);
		$routeProvider.when('/profile', partyView);

		//

		var partyEditParty;

		$routeProvider.when('/party/:id/edit', {
			controller: 'PartyEditView',
			templateUrl: 'partyEditView.html',
			resolve: {
				party: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						page.models.Party.get({
							id: page.$route.current.params.id,
							duns: '',
							parents: '',
							children: '',
						}, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						partyEditParty = deferred.promise;
						return deferred.promise;
					}
				],
				partyAuth: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						var empty = {
							parents: {},
							children: {},
						};

						partyEditParty.then(function (party) {
							if (page.auth.hasAccess('ADMIN', party)) {
								page.models.PartyAuthorize.query(function (res) {
									deferred.resolve(res);
								}, function (res) {
									deferred.reject(res);
								});
							} else {
								deferred.resolve(empty);
							}
						}, function (res) {
							deferred.resolve(empty);
						});

						return deferred.promise;
					}
				],
			},
			reloadOnSearch: false,
			authenticate: true
		});

		//

		var volumeEditVolume;

		var volumeEdit = {
			controller: 'VolumeEditView',
			templateUrl: 'volumeEditView.html',
			resolve: {
				volume: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						if (!page.$route.current.params.id) {
							deferred.resolve();
						} else {
							page.models.Volume.get({
								access: '',
								citation: '',
								top: '',
								funding: '',
							}, function (res) {
								deferred.resolve(res);
							}, function (res) {
								deferred.reject(res);
							});
						}

						volumeEditVolume = deferred.promise;
						return volumeEditVolume;
					}
				],
				slot: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						if (!page.$route.current.params.id) {
							deferred.resolve();
						} else {
							volumeEditVolume.then(function (volume) {
								page.models.Slot.get({
									id: volume.top.id,
									assets: '',
								}, function (res) {
									deferred.resolve(res);
								}, function (res) {
									deferred.reject(res);
								});
							});
						}

						return deferred.promise;
					}
				],
			},
			reloadOnSearch: false,
			authenticate: true
		};

		$routeProvider.when('/volume/create', volumeEdit);
		$routeProvider.when('/volume/:id/edit', volumeEdit);

		//

		$routeProvider.when('/volume/:id', {
			controller: 'VolumeView',
			templateUrl: 'volumeView.html',
			resolve: {
				volume: [
					'pageService', function (page) {
						var deferred = page.$q.defer();

						page.models.Volume.get({
							access: '',
							citation: '',
							funding: '',
							providers: '',
							consumers: '',
							top: '',
							tags: '',
							excerpts: '',
							comments: '',
							records: '',
							summary: '',
							sessions: '',
							categories: ''
						}, function (res) {
							deferred.resolve(res);
						}, function (res) {
							deferred.reject(res);
						});

						return deferred.promise;
					}
				]
			},
			reloadOnSearch: false,
			authenticate: true
		});

		//

		$routeProvider.otherwise({
			redirectTo: '/search'
		});
	}
]);

module.run([
	'pageService', function (page) {
		if (page.constants.data.locked) {
		page.$rootScope.$on('$routeChangeStart', function (event, next) {
			if (page.auth.isLoggedIn()) {
				if (!page.auth.isAuthorized()) {
					if (!next.$$route) {
						page.$location.url(page.router.register());
					}

					var controller = angular.isFunction(next.$$route.controller) ? next.$$route.controller() : next.$$route.controller;

					if (controller !== 'RegisterView') {
						page.$location.url(page.router.register());
					}
				} else if (!next.authenticate && next.$$route.controller !== 'ErrorView' && next.$$route.originalPath !== '/profile') {
					page.$location.url(page.router.index());
				}
			} else {
				if (page.auth.isPasswordPending() && next.$$route && next.$$route.controller != 'RegisterView' && (!angular.isFunction(next.$$route.controller) || next.$$route.controller() != 'RegisterView')) {
					page.$location.url(page.router.register());
				} else if (next.authenticate) {
					page.$location.url(page.router.index());
				}
			}
		});
		}
	}
]);

<|endoftext|>


<commit_before>cbus.audio = {
  DEFAULT_JUMP_AMOUNT_BACKWARD: -10,
  DEFAULT_JUMP_AMOUNT_FORWARD: 30,

  PLAYBACK_RATE_MIN: 0.5,
  PLAYBACK_RATE_MAX: 4,

  element: null,
  videoCanvasAnimationFrameID: null,
  state: {},

  tryRestoreProgress: function() {
    let episodeID = cbus.audio.element.dataset.id;
    if (cbus.data.episodeProgresses.hasOwnProperty(episodeID)) {
      cbus.audio.element.currentTime = Math.max(cbus.data.episodeProgresses[episodeID] - 5, 0);
    }
  },

  setElement: function(elem, disableAutomaticProgressRestore) {
    if (cbus.audio.element) {
      cbus.audio.pause();
      cbus.audio.element.onseeked = null;
      cbus.audio.element.onloadedmetadata = null;
      cbus.audio.element.onended = null;
    }

    cbus.audio.element = elem;
    if (disableAutomaticProgressRestore === true) {
      cbus.audio.element.currentTime = 0;
    } else {
      cbus.audio.tryRestoreProgress();
    }

    cbus.audio.element.onerror = function() {
      if (this.error === MediaError.MEDIA_ERR_ABORTED) {
        // cbus.ui.showSnackbar("The user canceled the audio.", "error");
      } else if (this.error === MediaError.MEDIA_ERR_NETWORK) {
        cbus.ui.showSnackbar(i18n.__("snackbar_error-media-network"), "error");
      } else if (this.error === MediaError.MEDIA_ERR_DECODE) {
        cbus.ui.showSnackbar(i18n.__("snackbar_error-media-decode"), "error");
      } else if (this.error === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED) {
        cbus.ui.showSnackbar(i18n.__("snackbar_error-media-unsupported"), "error");
      } else {
        cbus.ui.showSnackbar(i18n.__("snackbar_error-media-unknown"), "error");
      }
    };

    cbus.audio.element.onseeked = function() {
      cbus.audio.updatePlayerTime();
      if (cbus.audio.mprisPlayer) {
        cbus.audio.mprisPlayer.seeked(0);
        // MPRIS spec says argument of Seeked() should be new position, but
        // mpris-service adds argument of seeked() to position then passes
        // new position to Seeked()
      }
    };
    cbus.audio.element.onloadedmetadata = function() {
      if (disableAutomaticProgressRestore === true) {
        cbus.audio.element.currentTime = 0;
      } else {
        cbus.audio.tryRestoreProgress();
      }
      cbus.audio.updatePlayerTime();
    };
    cbus.audio.element.onended = function() {
      cbus.audio.playQueueItem(0);
    };

    cbus.audio.state.episode = cbus.data.getEpisodeData({
      audioElement: elem
    });
    cbus.audio.state.episode.urlSha1 = sha1(cbus.audio.state.episode.url);
    cbus.audio.state.feed = cbus.data.getFeedData({
      url: cbus.audio.state.episode.feedURL
    });

    if (cbus.audio.state.episode.isVideo) {
      let draw = function() {
        cbus.ui.videoCanvasContext.drawImage(
          cbus.audio.element,
          0, 0,
          cbus.ui.videoCanvasElement.width, cbus.ui.videoCanvasElement.height
        );
        cbus.audio.videoCanvasAnimationFrameID = requestAnimationFrame(draw);
      }
      cbus.audio.videoCanvasAnimationFrameID = requestAnimationFrame(draw);
    } else if (cbus.audio.videoCanvasAnimationFrameID) {
      cancelAnimationFrame(cbus.audio.videoCanvasAnimationFrameID);
    }

    cbus.broadcast.send("audioChange", cbus.audio.state.episode);

    localforage.setItem("cbus-last-audio-url", elem.dataset.id);
  },

  updatePlayerTime: function(options) {
    if (cbus.audio.element && !cbus.audio.element.paused) {
      cbus.broadcast.send("audioTick", {
        currentTime: cbus.audio.element.currentTime,
        duration: cbus.audio.element.duration
      });
      if (cbus.audio.mprisPlayer) {
        let trackID = cbus.audio.mprisPlayer.objectPath("track/" + cbus.audio.state.episode.urlSha1);
        if (
          !Number.isNaN(cbus.audio.element.duration) &&
          (
            !cbus.audio.mprisPlayer.metadata ||
            cbus.audio.mprisPlayer.metadata["mpris:trackid"] !== trackID
          )
        ) {
          if (cbus.audio.state.feed.image instanceof Blob && cbus.audio.state.updatingArtFor !== cbus.audio.state.feed.url) {
            cbus.audio.state.updatingArtFor = cbus.audio.state.feed.url;
            cbus.broadcast.send("updateFeedArtworks", {
              feedUrl: cbus.audio.state.feed.url,
              callback: function(updatedFeeds) {
                console.log(updatedFeeds)
                if (updatedFeeds[0].url === cbus.audio.state.feed.url) {
                  cbus.audio.state.feed.image = cbus.const.IMAGE_ON_DISK_PLACEHOLDER;
                  cbus.audio.mprisSetMetadata(trackID);
                  cbus.audio.state.updatingArtFor = null;
                }
              }
            });
          } else if (cbus.audio.state.updatingArtFor !== cbus.audio.state.feed.url) {
            cbus.audio.mprisSetMetadata(trackID);
          }
        }
      }
    }
  },
  sliderUpdateInterval: null,

  playQueueItem: function(index) {
    console.log("playQueueItem", index);
    if (cbus.audio.queue[index]) {
      cbus.audio.setElement(cbus.audio.queue[index]);

      cbus.audio.removeQueueItem(index);

      cbus.audio.updatePlayerTime();
      cbus.audio.play();

      cbus.broadcast.send("queueChanged");
    }
  },

  removeQueueItem: function(index) {
    console.log("removeQueueItem", index);
    if (cbus.audio.queue[index]) {
      cbus.audio.queue.splice(index, 1);
      $(".list--queue .episode").eq(index).remove();
      cbus.broadcast.send("queueChanged");
    }
  },

  play: function() {
    cbus.audio.element.play();
    $(".player_button--play").html("pause");
    cbus.broadcast.send("audio-play");
    if (cbus.audio.mprisPlayer) {
      cbus.audio.mprisPlayer.playbackStatus = "Playing";
    }
  },
  pause: function() {
    cbus.audio.element.pause();
    $(".player_button--play").html("play_arrow");
    cbus.broadcast.send("audio-pause");
    if (cbus.audio.mprisPlayer) {
      cbus.audio.mprisPlayer.playbackStatus = "Paused";
    }
  },
  stop: function() {
    cbus.audio.element.pause();
    cbus.audio.element.currentTime = 0;
    cbus.broadcast.send("audio-stop");
    if (cbus.audio.mprisPlayer) {
      cbus.audio.mprisPlayer.playbackStatus = "Stopped";
    }
  },
  jump: function(amount) {
    cbus.audio.element.currentTime += amount;
  },

  setPlaybackRate: function(rate) {
    cbus.audio.element.playbackRate = rate ? clamp(rate, cbus.audio.PLAYBACK_RATE_MIN, cbus.audio.PLAYBACK_RATE_MAX) : 1;
    if (cbus.audio.mprisPlayer) {
      cbus.audio.mprisPlayer.rate = cbus.audio.element.playbackRate;
    }
    cbus.broadcast.send("playbackRateChanged", cbus.audio.element.playbackRate);
  },

  queue: [],
  enqueue: function(audioElement, hiddenEnqueue) {
    cbus.audio.queue.push(audioElement);

    var episodeData = cbus.data.getEpisodeData({
        audioElement: audioElement
    });

    cbus.broadcast.send("episodeEnqueue", {
      episodeData: episodeData,
      hiddenEnqueue: (hiddenEnqueue === true ? true : false)
    });
    cbus.broadcast.send("queueChanged");
  },

  mprisPlayer: null,
  mprisSetMetadata: function(trackID) {
    cbus.audio.mprisPlayer.metadata = {
      "mpris:trackid": trackID,
      "mpris:length": cbus.audio.element.duration * 1000000,
      "mpris:artUrl": cbus.data.getPodcastImageURI(cbus.audio.state.feed),
      "xesam:title": cbus.audio.state.episode.title,
      // "xesam:album": cbus.audio.state.feed.title
      "xesam:artist": cbus.audio.state.feed.title
    };
    cbus.audio.mprisPlayer.position = cbus.audio.element.currentTime * 1000000;
    console.log("metadata set", cbus.audio.mprisPlayer.metadata)
  }
};

cbus.audio.sliderUpdateInterval = setInterval(cbus.audio.updatePlayerTime, 500);

if (MPRISPlayer) {
  cbus.audio.mprisPlayer = MPRISPlayer({
    name: "cumulonimbus",
    identity: "CPod",
    supportedUriSchemes: [ "file", "http", "https" ],
    supportedMimeTypes: [ "audio/*" ],
    supportedInterfaces: [ "player" ]
  });

  cbus.audio.mprisPlayer.canGoNext = false;
  cbus.audio.mprisPlayer.canGoPrevious = false;
  cbus.audio.mprisPlayer.playbackStatus = "Paused";
  cbus.audio.mprisPlayer.minimumRate = cbus.audio.PLAYBACK_RATE_MIN;
  cbus.audio.mprisPlayer.maximumRate = cbus.audio.PLAYBACK_RATE_MAX;

  cbus.audio.mprisPlayer.on("play", () => {
    cbus.audio.play();
  });
  cbus.audio.mprisPlayer.on("pause", () => {
    cbus.audio.pause();
  });
  cbus.audio.mprisPlayer.on("stop", () => {
    cbus.audio.pause();
  });
  cbus.audio.mprisPlayer.on("playpause", () => {
    if (cbus.audio.element.paused) {
      cbus.audio.play();
    } else {
      cbus.audio.pause();
    }
  });
  cbus.audio.mprisPlayer.on("next", () => {
    cbus.audio.playQueueItem(0);
  });
  cbus.audio.mprisPlayer.on("seek", (data) => {
    if (cbus.audio.element) {
      cbus.audio.element.currentTime = data.position / 1000000;
    }
  });
  cbus.audio.mprisPlayer.on("position", (data) => {
    if (cbus.audio.element) {
      cbus.audio.element.currentTime = data.position / 1000000;
    }
  });
  cbus.audio.mprisPlayer.on("volume", (data) => {
    if (cbus.audio.element) {
      cbus.audio.element.volume = clamp(data.volume, 0, 1);
    }
  });
  cbus.audio.mprisPlayer.on("rate", (data) => {
    if (cbus.audio.element) {
      cbus.audio.setPlaybackRate(data.rate);
    }
  });

  cbus.broadcast.listen("queueChanged", () => {
    if (cbus.audio.queue.length) {
      cbus.audio.mprisPlayer.canGoNext = true;
    } else {
      cbus.audio.mprisPlayer.canGoNext = false;
    }
  });
}
<commit_msg>Fix MPRIS Seeked signal<commit_after>cbus.audio = {
  DEFAULT_JUMP_AMOUNT_BACKWARD: -10,
  DEFAULT_JUMP_AMOUNT_FORWARD: 30,

  PLAYBACK_RATE_MIN: 0.5,
  PLAYBACK_RATE_MAX: 4,

  element: null,
  videoCanvasAnimationFrameID: null,
  state: {},

  tryRestoreProgress: function() {
    let episodeID = cbus.audio.element.dataset.id;
    if (cbus.data.episodeProgresses.hasOwnProperty(episodeID)) {
      cbus.audio.element.currentTime = Math.max(cbus.data.episodeProgresses[episodeID] - 5, 0);
    }
  },

  setElement: function(elem, disableAutomaticProgressRestore) {
    if (cbus.audio.element) {
      cbus.audio.pause();
      cbus.audio.element.onseeked = null;
      cbus.audio.element.onloadedmetadata = null;
      cbus.audio.element.onended = null;
    }

    cbus.audio.element = elem;
    if (disableAutomaticProgressRestore === true) {
      cbus.audio.element.currentTime = 0;
    } else {
      cbus.audio.tryRestoreProgress();
    }

    cbus.audio.element.onerror = function() {
      if (this.error === MediaError.MEDIA_ERR_ABORTED) {
        // cbus.ui.showSnackbar("The user canceled the audio.", "error");
      } else if (this.error === MediaError.MEDIA_ERR_NETWORK) {
        cbus.ui.showSnackbar(i18n.__("snackbar_error-media-network"), "error");
      } else if (this.error === MediaError.MEDIA_ERR_DECODE) {
        cbus.ui.showSnackbar(i18n.__("snackbar_error-media-decode"), "error");
      } else if (this.error === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED) {
        cbus.ui.showSnackbar(i18n.__("snackbar_error-media-unsupported"), "error");
      } else {
        cbus.ui.showSnackbar(i18n.__("snackbar_error-media-unknown"), "error");
      }
    };

    cbus.audio.element.onseeked = function() {
      cbus.audio.updatePlayerTime();
      if (cbus.audio.mprisPlayer) {
        cbus.audio.mprisPlayer.interfaces.player.emitSignal("Seeked", cbus.audio.element.currentTime * 1e6);
      }
    };
    cbus.audio.element.onloadedmetadata = function() {
      if (disableAutomaticProgressRestore === true) {
        cbus.audio.element.currentTime = 0;
      } else {
        cbus.audio.tryRestoreProgress();
      }
      cbus.audio.updatePlayerTime();
    };
    cbus.audio.element.onended = function() {
      cbus.audio.playQueueItem(0);
    };

    cbus.audio.state.episode = cbus.data.getEpisodeData({
      audioElement: elem
    });
    cbus.audio.state.episode.urlSha1 = sha1(cbus.audio.state.episode.url);
    cbus.audio.state.feed = cbus.data.getFeedData({
      url: cbus.audio.state.episode.feedURL
    });

    if (cbus.audio.state.episode.isVideo) {
      let draw = function() {
        cbus.ui.videoCanvasContext.drawImage(
          cbus.audio.element,
          0, 0,
          cbus.ui.videoCanvasElement.width, cbus.ui.videoCanvasElement.height
        );
        cbus.audio.videoCanvasAnimationFrameID = requestAnimationFrame(draw);
      }
      cbus.audio.videoCanvasAnimationFrameID = requestAnimationFrame(draw);
    } else if (cbus.audio.videoCanvasAnimationFrameID) {
      cancelAnimationFrame(cbus.audio.videoCanvasAnimationFrameID);
    }

    cbus.broadcast.send("audioChange", cbus.audio.state.episode);

    localforage.setItem("cbus-last-audio-url", elem.dataset.id);
  },

  updatePlayerTime: function(options) {
    if (cbus.audio.element && !cbus.audio.element.paused) {
      cbus.broadcast.send("audioTick", {
        currentTime: cbus.audio.element.currentTime,
        duration: cbus.audio.element.duration
      });
      if (cbus.audio.mprisPlayer) {
        let trackID = cbus.audio.mprisPlayer.objectPath("track/" + cbus.audio.state.episode.urlSha1);
        if (
          !Number.isNaN(cbus.audio.element.duration) &&
          (
            !cbus.audio.mprisPlayer.metadata ||
            cbus.audio.mprisPlayer.metadata["mpris:trackid"] !== trackID
          )
        ) {
          if (cbus.audio.state.feed.image instanceof Blob && cbus.audio.state.updatingArtFor !== cbus.audio.state.feed.url) {
            cbus.audio.state.updatingArtFor = cbus.audio.state.feed.url;
            cbus.broadcast.send("updateFeedArtworks", {
              feedUrl: cbus.audio.state.feed.url,
              callback: function(updatedFeeds) {
                console.log(updatedFeeds)
                if (updatedFeeds[0].url === cbus.audio.state.feed.url) {
                  cbus.audio.state.feed.image = cbus.const.IMAGE_ON_DISK_PLACEHOLDER;
                  cbus.audio.mprisSetMetadata(trackID);
                  cbus.audio.state.updatingArtFor = null;
                }
              }
            });
          } else if (cbus.audio.state.updatingArtFor !== cbus.audio.state.feed.url) {
            cbus.audio.mprisSetMetadata(trackID);
          }
        }
      }
    }
  },
  sliderUpdateInterval: null,

  playQueueItem: function(index) {
    console.log("playQueueItem", index);
    if (cbus.audio.queue[index]) {
      cbus.audio.setElement(cbus.audio.queue[index]);

      cbus.audio.removeQueueItem(index);

      cbus.audio.updatePlayerTime();
      cbus.audio.play();

      cbus.broadcast.send("queueChanged");
    }
  },

  removeQueueItem: function(index) {
    console.log("removeQueueItem", index);
    if (cbus.audio.queue[index]) {
      cbus.audio.queue.splice(index, 1);
      $(".list--queue .episode").eq(index).remove();
      cbus.broadcast.send("queueChanged");
    }
  },

  play: function() {
    cbus.audio.element.play();
    $(".player_button--play").html("pause");
    cbus.broadcast.send("audio-play");
    if (cbus.audio.mprisPlayer) {
      cbus.audio.mprisPlayer.playbackStatus = "Playing";
    }
  },
  pause: function() {
    cbus.audio.element.pause();
    $(".player_button--play").html("play_arrow");
    cbus.broadcast.send("audio-pause");
    if (cbus.audio.mprisPlayer) {
      cbus.audio.mprisPlayer.playbackStatus = "Paused";
    }
  },
  stop: function() {
    cbus.audio.element.pause();
    cbus.audio.element.currentTime = 0;
    cbus.broadcast.send("audio-stop");
    if (cbus.audio.mprisPlayer) {
      cbus.audio.mprisPlayer.playbackStatus = "Stopped";
    }
  },
  jump: function(amount) {
    cbus.audio.element.currentTime += amount;
  },

  setPlaybackRate: function(rate) {
    cbus.audio.element.playbackRate = rate ? clamp(rate, cbus.audio.PLAYBACK_RATE_MIN, cbus.audio.PLAYBACK_RATE_MAX) : 1;
    if (cbus.audio.mprisPlayer) {
      cbus.audio.mprisPlayer.rate = cbus.audio.element.playbackRate;
    }
    cbus.broadcast.send("playbackRateChanged", cbus.audio.element.playbackRate);
  },

  queue: [],
  enqueue: function(audioElement, hiddenEnqueue) {
    cbus.audio.queue.push(audioElement);

    var episodeData = cbus.data.getEpisodeData({
        audioElement: audioElement
    });

    cbus.broadcast.send("episodeEnqueue", {
      episodeData: episodeData,
      hiddenEnqueue: (hiddenEnqueue === true ? true : false)
    });
    cbus.broadcast.send("queueChanged");
  },

  mprisPlayer: null,
  mprisSetMetadata: function(trackID) {
    cbus.audio.mprisPlayer.metadata = {
      "mpris:trackid": trackID,
      "mpris:length": cbus.audio.element.duration * 1000000,
      "mpris:artUrl": cbus.data.getPodcastImageURI(cbus.audio.state.feed),
      "xesam:title": cbus.audio.state.episode.title,
      // "xesam:album": cbus.audio.state.feed.title
      "xesam:artist": cbus.audio.state.feed.title
    };
    cbus.audio.mprisPlayer.position = cbus.audio.element.currentTime * 1000000;
    console.log("metadata set", cbus.audio.mprisPlayer.metadata)
  }
};

cbus.audio.sliderUpdateInterval = setInterval(cbus.audio.updatePlayerTime, 500);

if (MPRISPlayer) {
  cbus.audio.mprisPlayer = MPRISPlayer({
    name: "cumulonimbus",
    identity: "CPod",
    supportedUriSchemes: [ "file", "http", "https" ],
    supportedMimeTypes: [ "audio/*" ],
    supportedInterfaces: [ "player" ]
  });

  cbus.audio.mprisPlayer.canGoNext = false;
  cbus.audio.mprisPlayer.canGoPrevious = false;
  cbus.audio.mprisPlayer.playbackStatus = "Paused";
  cbus.audio.mprisPlayer.minimumRate = cbus.audio.PLAYBACK_RATE_MIN;
  cbus.audio.mprisPlayer.maximumRate = cbus.audio.PLAYBACK_RATE_MAX;

  cbus.audio.mprisPlayer.on("play", () => {
    cbus.audio.play();
  });
  cbus.audio.mprisPlayer.on("pause", () => {
    cbus.audio.pause();
  });
  cbus.audio.mprisPlayer.on("stop", () => {
    cbus.audio.pause();
  });
  cbus.audio.mprisPlayer.on("playpause", () => {
    if (cbus.audio.element.paused) {
      cbus.audio.play();
    } else {
      cbus.audio.pause();
    }
  });
  cbus.audio.mprisPlayer.on("next", () => {
    cbus.audio.playQueueItem(0);
  });
  cbus.audio.mprisPlayer.on("seek", (data) => {
    if (cbus.audio.element) {
      cbus.audio.element.currentTime = data.position / 1000000;
    }
  });
  cbus.audio.mprisPlayer.on("position", (data) => {
    if (cbus.audio.element) {
      cbus.audio.element.currentTime = data.position / 1000000;
    }
  });
  cbus.audio.mprisPlayer.on("volume", (data) => {
    if (cbus.audio.element) {
      cbus.audio.element.volume = clamp(data.volume, 0, 1);
    }
  });
  cbus.audio.mprisPlayer.on("rate", (data) => {
    if (cbus.audio.element) {
      cbus.audio.setPlaybackRate(data.rate);
    }
  });

  cbus.broadcast.listen("queueChanged", () => {
    if (cbus.audio.queue.length) {
      cbus.audio.mprisPlayer.canGoNext = true;
    } else {
      cbus.audio.mprisPlayer.canGoNext = false;
    }
  });
}
<|endoftext|>


<commit_before>define(['modules/dc/views/apstatusitem'], function(APStatusItem) {

    return APStatusItem.extend({

        onRender: function() {
            var ps = []
            _.each({'Motion Correction': 'MC', 'CTF': 'CTF'}, function(p,n) {
                var tys = []
                var cts = _.countBy(Object.values(this.model.get(p)), function(v) { return v })
                _.each({
                    null: '',
                    1: '',
                    0: ''
                }, function(icon, state) {
                    if (cts[state]) tys.push(cts[state]+' '+icon)
                }, this)

                ps.push(''+n+': '+tys.join(' ')+'')
            }, this)

            this.ui.holder.eq(0).html(ps.join(' '))

        },

    })

})<commit_msg>show ? for unknown processing state<commit_after>define(['modules/dc/views/apstatusitem'], function(APStatusItem) {

    return APStatusItem.extend({

        onRender: function() {
            var ps = []
            _.each({'Motion Correction': 'MC', 'CTF': 'CTF'}, function(p,n) {
                var tys = []

                var cts = _.countBy(Object.values(this.model.get(p)), function(v) { return v })
                _.each({
                    null: '',
                    1: '',
                    0: ''
                }, function(icon, state) {
                    if (cts[state]) tys.push(cts[state]+' '+icon)
                }, this)

                ps.push(''+n+': '+(tys.length ? tys.join(' ') : '')+'')
            }, this)

            this.ui.holder.eq(0).html(ps.join(' '))

        },

    })

})<|endoftext|>


<commit_before>angular.module('fishTank')
.controller('MainCtrl', [
    '$scope',
    'postsFactory',
    'tagsFactory',
    'Auth',
    '$http',
    function($scope, postsFactory, tagsFactory, Auth, $http){
      var self = $scope;
      Auth.currentUser().then(function(user){
        $scope.user = user;
      });
      self.posts = postsFactory.posts;
      self.showAddPost = function(){
        $("div.addPost").toggle();
      }
      self.showAddPost = function(){$('div.addPost').toggle()}
      self.addTag = function(){$('div.tag-input').after("
 <input type='text' class='tag-inputs-" + $scope.tagInputs + " placeholder='Tag' ng-model='tags' size='19'></input>
"); $scope.tagInputs++}
      $scope.tagInputs = 1
      self.addPost = function(){
        errors()
        if(!$scope.title || $scope.title === '') {$scope.error = "Title can't be blank"; return;}
        postsFactory.create({
          title: $scope.title,
          link: $scope.link,
          upvotes: 0
        }).success(function(post){
          if ($scope.tagInputs > 1){
            var tagArray = Array.from($("input[class*='tag-inputs'").map(function(){return($(this).val())}))
            tagArray.forEach(function(item) {
              tagsFactory.create(post, {
                name: item
              })
            });
          }
          self.posts.push(post);
        });
      };

      self.incrementUpvotes = function(post) {
        postsFactory.upvote(post);
      };

      self.decrementUpvotes = function(post) {
        postsFactory.downvote(post);
      };

      var errors = function() {
        $scope.$on('devise:unauthorized', function(event, xhr, deferred) {
          $scope.error = xhr.data.error
          setTimeout(function(){ $('p.auth-error').fadeOut();}, 5000);
          setTimeout(function(){$('p.auth-error').show();}, 10);
        });
      }

    }
  ])

// $("input[class*='tag-inputs'").map(function(){return($(this).val())})

<commit_msg>jquery clears post form fields after posting<commit_after>angular.module('fishTank')
.controller('MainCtrl', [
    '$scope',
    'postsFactory',
    'tagsFactory',
    'Auth',
    '$http',
    function($scope, postsFactory, tagsFactory, Auth, $http){
      var self = $scope;
      Auth.currentUser().then(function(user){
        $scope.user = user;
      });
      self.posts = postsFactory.posts;
      self.showAddPost = function(){
        $("div.addPost").toggle();
      }
      self.showAddPost = function(){$('div.addPost').toggle()}
      self.addTag = function(){$('div.tag-input').after("
 <input type='text' class='tag-inputs-" + $scope.tagInputs + " placeholder='Tag' ng-model='tags' size='19'></input>
"); $scope.tagInputs++}
      $scope.tagInputs = 1
      self.addPost = function(){
        errors()
        if(!$scope.title || $scope.title === '') {$scope.error = "Title can't be blank"; return;}
        postsFactory.create({
          title: $scope.title,
          link: $scope.link,
          upvotes: 0
        }).success(function(post){
          if ($scope.tagInputs > 1){
            var tagArray = Array.from($("input[class*='tag-inputs'").map(function(){return($(this).val())}))
            tagArray.forEach(function(item) {
              tagsFactory.create(post, {
                name: item
              })
            });
          }
          self.posts.push(post);
        });
        setTimeout(function(){ $(".form-group > input").each(function(){$(this).val('')});}, 50);
      };

      self.incrementUpvotes = function(post) {
        postsFactory.upvote(post);
      };

      self.decrementUpvotes = function(post) {
        postsFactory.downvote(post);
      };

      var errors = function() {
        $scope.$on('devise:unauthorized', function(event, xhr, deferred) {
          $scope.error = xhr.data.error
          setTimeout(function(){ $('p.auth-error').fadeOut();}, 5000);
          setTimeout(function(){$('p.auth-error').show();}, 10);
        });
      }

    }
  ])

// $("input[class*='tag-inputs'").map(function(){return($(this).val())})

<|endoftext|>


<commit_before>/*eslint-disable max-len,quotes*/
export default {
  'Item.available': 'Ledig',
  'Item.expectedAvailable': 'Forventet {status}',
  'Items.title': 'tittel',
  'Items.language': 'språk',
  'Items.format': 'format',
  'Items.barcode': 'strekkode',
  'Items.placement': 'plassering',
  'Items.status': 'status',
  'Items.shelfmark': 'oppstilling',
  'Items.noItems': 'Vi har ingen eksemplarer',
  'Items.numberOfCopies': 'Eksemplarer ({numberOfCopies})',
  'Publications.title': 'tittel',
  'Publications.publicationYear': 'utgivelsesår',
  'Publications.language': 'språk',
  'Publications.format': 'format',
  'Publications.copies': 'eksemplarer',
  'Publications.numberOfPublications': 'Eksemplarer {numberOfPublications}',
  'SearchFilter.showAll': '+ vis alle',
  'SearchFilter.filter[work.publication.format]': 'Formater',
  'SearchFilter.filter[work.publication.language]': 'Språk',
  'SearchFilter.filter[work.publication.audience]': 'Målgruppe',
  'SearchFilters.limit': 'Begrens søket ditt',
  'SearchHeader.searchInputPlaceholder': 'Søk på noe da...',
  'SearchHeader.search': 'Søk',
  'SearchResult.allPublications': 'alle utgivelser ►',
  'SearchResult.availableAs': 'Finnes som:',
  'SearchResults.totalHits': 'Ditt søk på "{searchQuery}" ga {totalHits} treff',
  'SearchResults.searchError': 'Noe gikk galt med søket',
  'SearchResults.searchForWork': 'Søk etter verk',
  'Person.noPerson': 'Ingen person',
  'Person.nationality': 'nasjonalitet:',
  'Person.work': 'Verk',
  'Work.noWork': 'Inget verk',
  'Work.firstTimePublished': 'Første gang utgitt:',
  'Work.workInformation': 'Verksinformasjon'
}
<commit_msg>patron-client: Add missing translation string<commit_after>/*eslint-disable max-len,quotes*/
export default {
  'Item.available': 'Ledig',
  'Item.expectedAvailable': 'Forventet {status}',
  'Items.title': 'tittel',
  'Items.language': 'språk',
  'Items.format': 'format',
  'Items.barcode': 'strekkode',
  'Items.placement': 'plassering',
  'Items.status': 'status',
  'Items.shelfmark': 'oppstilling',
  'Items.noItems': 'Vi har ingen eksemplarer',
  'Items.numberOfCopies': 'Eksemplarer ({numberOfCopies})',
  'Publications.title': 'tittel',
  'Publications.publicationYear': 'utgivelsesår',
  'Publications.language': 'språk',
  'Publications.format': 'format',
  'Publications.copies': 'eksemplarer',
  'Publications.noPublications': 'Ingen publikasjoner',
  'Publications.numberOfPublications': 'Eksemplarer {numberOfPublications}',
  'SearchFilter.showAll': '+ vis alle',
  'SearchFilter.filter[work.publication.format]': 'Formater',
  'SearchFilter.filter[work.publication.language]': 'Språk',
  'SearchFilter.filter[work.publication.audience]': 'Målgruppe',
  'SearchFilters.limit': 'Begrens søket ditt',
  'SearchHeader.searchInputPlaceholder': 'Søk på noe da...',
  'SearchHeader.search': 'Søk',
  'SearchResult.allPublications': 'alle utgivelser ►',
  'SearchResult.availableAs': 'Finnes som:',
  'SearchResults.totalHits': 'Ditt søk på "{searchQuery}" ga {totalHits} treff',
  'SearchResults.searchError': 'Noe gikk galt med søket',
  'SearchResults.searchForWork': 'Søk etter verk',
  'Person.noPerson': 'Ingen person',
  'Person.nationality': 'nasjonalitet:',
  'Person.work': 'Verk',
  'Work.noWork': 'Inget verk',
  'Work.firstTimePublished': 'Første gang utgitt:',
  'Work.workInformation': 'Verksinformasjon'
}
<|endoftext|>