<commit_before>function DemoEngine(selector, width, height) {

	// hack for safari
	window.AudioContext = window.AudioContext || window.webkitAudioContext;

	this.partdata = [];
	this.assets = { urls: {} };
	this.renderers = {};
	this.rendertargets = {};
	this.audio = null;
	this.analyzer = null;
	this.audiocontext = null;
	this.audiosource = null;
	this.frequencyByteData = null;
	this.frequencyFloatData = null;
	this.frequencyBinCount = 0;
	this.selectorstr = selector;
	this.fftsupport = true;
	this.clock = new THREE.Clock();
	this.debuggerpending = false;

	var tmpelement = $(selector);
	if (tmpelement.length != 1) {
		console.log('Selector "' + selector + '" returned more than one element. ');
		return null;
	}
	this.element = tmpelement[0];

	if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1 ||
		!!navigator.userAgent.match(/Trident.*[ :]*11\./)) {
		this.fftsupport = false;
	}

	this.width = window.innerWidth;
	this.height = window.innerHeight;

	if (width && height) {
		this.width = width;
		this.height = height;
	}

	this.setAudioLooping = function(loop) {
		this.audio.loop = loop;
	}

	this.startDebugger = function() {
		this.debuggerpending = true;
	}

	this.stopDebugger = function() {
		this.debuggerpending = false;
	}

	this.supportsFFT = function() {
		return this.fftsupport;
	}

	this.setAudio = function(a) {
		this.audiocontext = new AudioContext();
		this.audio = a;
		$(this.selectorstr).append(this.audio);

		if (this.fftsupport) {
			this.audiosource = this.audiocontext.createMediaElementSource(this.audio);
			this.analyzer = this.audiocontext.createAnalyser();
			this.analyzer.fftSize = Math.pow(2,9);
			this.analyzer.minDecibels = -50;
			this.analyzer.maxDecibels = -30;
			this.audiosource.connect(this.analyzer);
			this.analyzer.connect(this.audiocontext.destination);
			this.frequencyBinCount = this.analyzer.frequencyBinCount;
			this.frequencyByteData = new Uint8Array(this.frequencyBinCount);
			this.frequencyFloatData = new Float32Array(this.frequencyBinCount);
		} else {
			log("Using Firefox on windows, no FFT support");
		}
	}

	this.getFrequencyBinCount = function() {
		return this.frequencyBinCount;
	}

	this.getByteFFTData = function(smoothing) {
		this.analyzer.smoothingTimeConstant = smoothing || 0.5;
		this.analyzer.getByteFrequencyData(this.frequencyByteData);

		return this.frequencyByteData;
	}

	this.getFloatFFTData = function(smoothing) {
		this.analyzer.smoothingTimeConstant = smoothing || 0.5;
		this.analyzer.getFloatFrequencyData(this.frequencyFloatData);

		return this.frequencyFloatData;
	}

	this.stop = function() {
		this.audio.pause();
		this.audio.currentTime = 0;
	}

 	this.play = function() {
		this.audio.play();
		this.audio.controls = true;
	}

	this.showControls = function(show) {
		this.audio.controls = show;
	}

	this.getTick = function() {
		return Math.floor(this.audio.currentTime * 1000);
	}

	this.getAspectRatio = function() {
		return this.width/this.height;
	}

	this.getWidth = function() {
		return this.width;
	}

	this.getHeight = function() {
		return this.height;
	}

	this.addPart = function(data) {
		this.partdata[this.partdata.length] = data;
	}

	this.prewarm = function() {
		this.renderers['main'].domElement.opacity = 0;

		var parttick = 0;
		var globaltick = 0;

		for (var i=0; i<this.partdata.length; i++) {
			var partdata = this.partdata[i].data;
			log("Prewarming scene: " + partdata.partname + " (" + (i+1) + "/" + this.partdata.length + ")");

			parttick = 0;

			for (var j=0; j<10; j++) {
				parttick += partdata.partlength / 10 * j;
				try {
					partdata.player(this.partdata[i], parttick, globaltick + parttick);
				} catch (e) {
					log("Oopsie (" + e.message + ") while prewarming, maybe too long song?");
					break;
				}
			}

			globaltick += partdata.partlength;
		}

		this.renderers['main'].clear(true, true, true);
		this.renderers['main'].domElement.opacity = 1;
	}

	this.draw = function(tick) {
		var parttick = tick;
		var prevpartlengths = 0;
		for (var i=0; i<this.partdata.length; i++) {

			if (i>0) {
				parttick -= this.partdata[i-1].data.partlength;
				prevpartlengths += this.partdata[i-1].data.partlength;
			}

			if (tick<this.partdata[i].data.partlength + prevpartlengths) {
				if (this.debuggerpending) {
					debugger;
				}
				this.partdata[i].data.player(this.partdata[i], parttick, tick);
				break;
			}
		}
	}

	this.addRenderTarget = function(name, width, height) {
		var w = width || this.getWidth();
		var h = height || this.getHeight();

		this.rendertargets[name] = {};
		this.rendertargets[name].target = new THREE.WebGLRenderTarget( Math.floor(width), Math.floor(height), { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } );
		this.rendertargets[name].width = Math.floor(width);
		this.rendertargets[name].height = Math.floor(height);

		this.rendertargets[name].getAspectRatio = function(){
			return this.width/this.height;
		}
	}

	this.addRenderer = function(name, antialias, shadowmap, width, height) {
		this.renderers[name] = new THREE.WebGLRenderer( { antialias: antialias } );
		this.renderers[name].shadowMapEnabled = shadowmap;

		if (width && height) {
			this.renderers[name].setSize(width, height);
		} else {
			this.renderers[name].setSize(this.getWidth(), this.getHeight());
		}

		this.renderers[name].setClearColor(0x000000, 1.0);
		this.renderers[name].autoClear = false;
		this.renderers[name].clear();
	}

	this.addRenderer('main', true, true);

	$(selector).append(this.renderers['main'].domElement);
	this.renderers['main'].domElement.display = 'block';
}
<commit_msg>set autoclear color to 0, start clock when playing, alpha to webglrenderer<commit_after>function DemoEngine(selector, width, height) {

	// hack for safari
	window.AudioContext = window.AudioContext || window.webkitAudioContext;

	this.partdata = [];
	this.assets = { urls: {} };
	this.renderers = {};
	this.rendertargets = {};
	this.audio = null;
	this.analyzer = null;
	this.audiocontext = null;
	this.audiosource = null;
	this.frequencyByteData = null;
	this.frequencyFloatData = null;
	this.frequencyBinCount = 0;
	this.selectorstr = selector;
	this.fftsupport = true;
	this.clock = new THREE.Clock(false);
	this.debuggerpending = false;

	var tmpelement = $(selector);
	if (tmpelement.length != 1) {
		console.log('Selector "' + selector + '" returned more than one element. ');
		return null;
	}
	this.element = tmpelement[0];

	if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1 ||
		!!navigator.userAgent.match(/Trident.*[ :]*11\./)) {
		this.fftsupport = false;
	}

	this.width = window.innerWidth;
	this.height = window.innerHeight;

	if (width && height) {
		this.width = width;
		this.height = height;
	}

	this.setAudioLooping = function(loop) {
		this.audio.loop = loop;
	}

	this.startDebugger = function() {
		this.debuggerpending = true;
	}

	this.stopDebugger = function() {
		this.debuggerpending = false;
	}

	this.supportsFFT = function() {
		return this.fftsupport;
	}

	this.setAudio = function(a) {
		this.audiocontext = new AudioContext();
		this.audio = a;
		$(this.selectorstr).append(this.audio);

		if (this.fftsupport) {
			this.audiosource = this.audiocontext.createMediaElementSource(this.audio);
			this.analyzer = this.audiocontext.createAnalyser();
			this.analyzer.fftSize = Math.pow(2,9);
			this.analyzer.minDecibels = -50;
			this.analyzer.maxDecibels = -30;
			this.audiosource.connect(this.analyzer);
			this.analyzer.connect(this.audiocontext.destination);
			this.frequencyBinCount = this.analyzer.frequencyBinCount;
			this.frequencyByteData = new Uint8Array(this.frequencyBinCount);
			this.frequencyFloatData = new Float32Array(this.frequencyBinCount);
		} else {
			log("Using Firefox on windows, no FFT support");
		}
	}

	this.getFrequencyBinCount = function() {
		return this.frequencyBinCount;
	}

	this.getByteFFTData = function(smoothing) {
		this.analyzer.smoothingTimeConstant = smoothing || 0.5;
		this.analyzer.getByteFrequencyData(this.frequencyByteData);

		return this.frequencyByteData;
	}

	this.getFloatFFTData = function(smoothing) {
		this.analyzer.smoothingTimeConstant = smoothing || 0.5;
		this.analyzer.getFloatFrequencyData(this.frequencyFloatData);

		return this.frequencyFloatData;
	}

	this.stop = function() {
		this.clock.stop();
		this.audio.pause();
		this.audio.currentTime = 0;
	}

 	this.play = function() {
		this.audio.play();
		this.clock.start();
		this.audio.controls = true;
	}

	this.showControls = function(show) {
		this.audio.controls = show;
	}

	this.getTick = function() {
		return Math.floor(this.audio.currentTime * 1000);
	}

	this.getAspectRatio = function() {
		return this.width/this.height;
	}

	this.getWidth = function() {
		return this.width;
	}

	this.getHeight = function() {
		return this.height;
	}

	this.addPart = function(data) {
		this.partdata[this.partdata.length] = data;
	}

	this.prewarm = function() {
		this.renderers['main'].domElement.opacity = 0;

		var parttick = 0;
		var globaltick = 0;

		for (var i=0; i<this.partdata.length; i++) {
			var partdata = this.partdata[i].data;
			log("Prewarming scene: " + partdata.partname + " (" + (i+1) + "/" + this.partdata.length + ")");

			parttick = 0;

			for (var j=0; j<10; j++) {
				parttick += partdata.partlength / 10 * j;
				try {
					partdata.player(this.partdata[i], parttick, globaltick + parttick);
				} catch (e) {
					log("Oopsie (" + e.message + ") while prewarming, maybe too long song?");
					break;
				}
			}

			globaltick += partdata.partlength;
		}

		this.renderers['main'].clear(true, true, true);
		this.renderers['main'].domElement.opacity = 1;
	}

	this.draw = function(tick) {
		var parttick = tick;
		var prevpartlengths = 0;
		for (var i=0; i<this.partdata.length; i++) {

			if (i>0) {
				parttick -= this.partdata[i-1].data.partlength;
				prevpartlengths += this.partdata[i-1].data.partlength;
			}

			if (tick<this.partdata[i].data.partlength + prevpartlengths) {
				if (this.debuggerpending) {
					debugger;
				}
				this.partdata[i].data.player(this.partdata[i], parttick, tick);
				break;
			}
		}
	}

	this.addRenderTarget = function(name, width, height) {
		var w = width || this.getWidth();
		var h = height || this.getHeight();

		this.rendertargets[name] = {};
		this.rendertargets[name].target = new THREE.WebGLRenderTarget( Math.floor(width), Math.floor(height), { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } );
		this.rendertargets[name].width = Math.floor(width);
		this.rendertargets[name].height = Math.floor(height);

		this.rendertargets[name].getAspectRatio = function(){
			return this.width/this.height;
		}
	}

	this.addRenderer = function(name, antialias, shadowmap, width, height) {
		this.renderers[name] = new THREE.WebGLRenderer( { antialias: antialias, alpha: true, autoClear: false } );
		this.renderers[name].shadowMapEnabled = shadowmap;

		if (width && height) {
			this.renderers[name].setSize(width, height);
		} else {
			this.renderers[name].setSize(this.getWidth(), this.getHeight());
		}

		this.renderers[name].setClearColor(0x000000, 0.0);
		this.renderers[name].autoClear = false;
		this.renderers[name].clear();
	}

	this.addRenderer('main', true, true);

	$(selector).append(this.renderers['main'].domElement);
	this.renderers['main'].domElement.display = 'block';
}
<|endoftext|>


<commit_before>'use strict';
var argv = require('minimist')(process.argv.slice(2));
var https = require('https');
var MongoClient = require('mongodb').MongoClient;
var cli = {};
var arg_handler = {
    'user': ['u', 'user'],
    'repo': ['r', 'repo'],
    'user_agent': ['a', 'user_agent']
};
cli.verbose = argv.v || argv.verbose;

for (var key in arg_handler) {
    try {
        arg_handler[key].forEach(function (value, index, array) {
            if (!cli[key]) cli[key] = argv[value];
        });
        if (!cli[key]) throw new Error('Please specify a ' + key);
    } catch (exception) {
        console.error(exception);
        process.exit(1);
    }
}

if (cli.verbose) {
    console.log('Running with settings:\n'+
                'user: ' + cli.user + '\n'+
                'repo: ' + cli.repo + '\n'+
                'user_agent: ' + cli.user_agent);
}

var httpOptions = {
    hostname: 'api.github.com',
    port: 443,
    path: '/repos/' + cli.user + '/' + cli.repo + '/releases',
    headers: {
        'User-Agent': cli.user_agent
    }
};

function httpCallback (response) {
    var content = '';

    if (cli.verbose) {
        console.log('HTTP response statusCode: ', response.statusCode);
        console.log('HTTP response headers: ', response.headers);
    }

    if (response.statusCode !== 200) {
        throw new Error(response.statusMessage);
    }

    response.on('error', function (err) {
        console.error(err);
        process.exit(1);
    });
    response.on('end', function () {
        formatHttpResponse(content);
    });
    response.on('data', function (chunk) {
        content += chunk;
    });
}

function formatHttpResponse (rawResponse) {
    try {
        var httpResponse = JSON.parse(rawResponse);
    } catch (exception) {
        console.error('JSON.parse error');
        console.error(exception);
        process.exit(1);
    }

    httpResponse.forEach(function (release, index, httpResponse) {
        delete httpResponse[index].body;
        delete httpResponse[index].author;
        delete httpResponse[index].published_at;
        delete httpResponse[index].target_commitish;
        // delete author objs, uploader objs, and supplimentary urls
        (function deleteExtraInfo (httpResponse) {
            for (var key in httpResponse) {
                if (key.indexOf('url')      > -1 ||
                    key.indexOf('uploader') > -1 ||
                    key.indexOf('updated_at')>-1 ||
                    key.indexOf('state')    > -1 ||
                    key.indexOf('label')    > -1 ||
                    key.indexOf('size')     > -1 ||
                    key.indexOf('content_type') > -1) {
                        delete httpResponse[key];
                } else if (typeof httpResponse[key] === 'object') {
                    deleteExtraInfo(httpResponse[key]);
                }
            }
        })(httpResponse[index])
    });

    writeToMongo(httpResponse);
}

function writeToMongo (httpResponse) {
    if (cli.verbose) console.log('Attempting to write to Mongo');

    MongoClient.connect('mongodb://127.0.0.1:27017/github-downloads', function(err, db) {
        if (err) {
            console.error('\n*ERROR* connecting to Mongo database\n');
            process.exit(1);
        }

        if (cli.verbose) console.log('Connected to Mongo database');

        db.collection('downloads').insert(httpResponse, function(err, docs) {
            if (err) {
                console.error('\n*ERROR* inserting into Mongo database\n');
                process.exit(1);
            }

            if (cli.verbose) console.log('Downloads data successfully inserted.');
            db.close();
        });
    });
}

https.get(httpOptions, httpCallback);
<commit_msg>cleaner console message for http errors; removed throw new Error until I can figure out what the hell to do with errors<commit_after>'use strict';
var argv = require('minimist')(process.argv.slice(2));
var https = require('https');
var MongoClient = require('mongodb').MongoClient;
var cli = {};
var arg_handler = {
    'user': ['u', 'user'],
    'repo': ['r', 'repo'],
    'user_agent': ['a', 'user_agent']
};
cli.verbose = argv.v || argv.verbose;

for (var key in arg_handler) {
    try {
        arg_handler[key].forEach(function (value, index, array) {
            if (!cli[key]) cli[key] = argv[value];
        });
        if (!cli[key]) {
            // throw new Error('Please specify a ' + key);
            console.error('Please specify a ' + key);
            process.exit(1);
        }
    } catch (exception) {
        console.error(exception);
        process.exit(1);
    }
}

if (cli.verbose) {
    console.log('Running with settings:\n'+
                'user: ' + cli.user + '\n'+
                'repo: ' + cli.repo + '\n'+
                'user_agent: ' + cli.user_agent);
}

var httpOptions = {
    hostname: 'api.github.com',
    port: 443,
    path: '/repos/' + cli.user + '/' + cli.repo + '/releases',
    headers: {
        'User-Agent': cli.user_agent
    }
};

function httpCallback (response) {
    var content = '';

    if (cli.verbose) {
        console.log('HTTP response statusCode: ', response.statusCode);
        console.log('HTTP response headers: ', response.headers);
    }

    if (response.statusCode !== 200) {
        // throw new Error(response.statusCode + ': ' + response.statusMessage);
        console.error('GitHub says: ' + response.statusCode + ': ' + response.statusMessage);
        process.exit(1);
    }

    response.on('error', function (err) {
        // throw new Error(err);
        console.error(err);
        process.exit(1);
    });
    response.on('end', function () {
        formatHttpResponse(content);
    });
    response.on('data', function (chunk) {
        content += chunk;
    });
}

function formatHttpResponse (rawResponse) {
    try {
        var httpResponse = JSON.parse(rawResponse);
    } catch (exception) {
        console.error('JSON.parse error');
        console.error(exception);
        process.exit(1);
    }

    httpResponse.forEach(function (release, index, httpResponse) {
        delete httpResponse[index].body;
        delete httpResponse[index].author;
        delete httpResponse[index].published_at;
        delete httpResponse[index].target_commitish;
        // delete author objs, uploader objs, and supplimentary urls
        (function deleteExtraInfo (httpResponse) {
            for (var key in httpResponse) {
                if (key.indexOf('url')      > -1 ||
                    key.indexOf('uploader') > -1 ||
                    key.indexOf('updated_at')>-1 ||
                    key.indexOf('state')    > -1 ||
                    key.indexOf('label')    > -1 ||
                    key.indexOf('size')     > -1 ||
                    key.indexOf('content_type') > -1) {
                        delete httpResponse[key];
                } else if (typeof httpResponse[key] === 'object') {
                    deleteExtraInfo(httpResponse[key]);
                }
            }
        })(httpResponse[index])
    });

    writeToMongo(httpResponse);
}

function writeToMongo (httpResponse) {
    if (cli.verbose) console.log('Attempting to write to Mongo');

    MongoClient.connect('mongodb://127.0.0.1:27017/github-downloads', function(err, db) {
        if (err) {
            console.error('\n*ERROR* connecting to Mongo database\n');
            process.exit(1);
        }

        if (cli.verbose) console.log('Connected to Mongo database');

        db.collection('downloads').insert(httpResponse, function(err, docs) {
            if (err) {
                console.error('\n*ERROR* inserting into Mongo database\n');
                process.exit(1);
            }

            if (cli.verbose) console.log('Downloads data successfully inserted.');
            db.close();
        });
    });
}

https.get(httpOptions, httpCallback);
<|endoftext|>


<commit_before>var xhr = {
  request: function(type, url, opts) {
    'use strict';

    var json = 'application/json';
    var req = new XMLHttpRequest(),
        payload = ('payload' in opts) ? opts.payload : null,
        callback = (opts.callback || function() {}).bind(req),
        headers = opts.headers || (opts.raw ? {} : {
          'Content-Type': json,
          'Accept': json
        });

    req.open(type, url);
    for (var k in headers)
      req.setRequestHeader(k, headers[k]);

    req.onerror = function() { callback(true) };
    req.onload = function() {
      callback(
        null,
        opts.raw
          ? req.responseText
          : JSON.parse(req.responseText)
      );
    };

    if (!opts.raw)
      payload = JSON.stringify(opts);
    req.send(payload);
    return req;
  }
};

xhr.post = xhr.request.bind(xhr, 'POST');
xhr.get =  xhr.request.bind(xhr, 'GET');
<commit_msg>fix missing semicolon<commit_after>var xhr = {
  request: function(type, url, opts) {
    'use strict';

    var json = 'application/json';
    var req = new XMLHttpRequest(),
        payload = ('payload' in opts) ? opts.payload : null,
        callback = (opts.callback || function() {}).bind(req),
        headers = opts.headers || (opts.raw ? {} : {
          'Content-Type': json,
          'Accept': json
        });

    req.open(type, url);
    for (var k in headers)
      req.setRequestHeader(k, headers[k]);

    req.onerror = function() { callback(true); };
    req.onload = function() {
      callback(
        null,
        opts.raw
          ? req.responseText
          : JSON.parse(req.responseText)
      );
    };

    if (!opts.raw)
      payload = JSON.stringify(opts);
    req.send(payload);
    return req;
  }
};

xhr.post = xhr.request.bind(xhr, 'POST');
xhr.get =  xhr.request.bind(xhr, 'GET');
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Link from 'gatsby-link';
import styles from './styles.scss';

import logo from './../../assets/tangologo.svg';

const NavBar = () => (

        <Link to="/">

        </Link>

        Specials
        Combos
        Favorites
        Location
        Contact
        <Link to='/ComingSoon/'>Menu</Link>

);

export default NavBar;
<commit_msg>Removed Menu link from nav bar.<commit_after>import React, { Component } from 'react';
import Link from 'gatsby-link';
import styles from './styles.scss';

import logo from './../../assets/tangologo.svg';

const NavBar = () => (

        <Link to="/">

        </Link>

        Specials
        Combos
        Favorites
        Location
        Contact

);

export default NavBar;
<|endoftext|>


<commit_before>// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

/// <reference path="../../../ZumoE2ETestAppJs/ZumoE2ETestAppJs/js/MobileServices.js" />
/// <reference path="/LiveSDKHTML/js/wl.js" />
/// <reference path="../testFramework.js" />

function defineLoginTestsNamespace() {
    var tests = [];
    var i;
    var TABLE_PERMISSION_PUBLIC = 1;
    var TABLE_PERMISSION_APPLICATION = 2;
    var TABLE_PERMISSION_USER = 3;
    var TABLE_PERMISSION_ADMIN = 4;
    var TABLE_NAME_PUBLIC = 'w8Public';
    var TABLE_NAME_APPLICATION = 'w8Application';
    var TABLE_NAME_AUTHENTICATED = 'w8Authenticated';
    var TABLE_NAME_ADMIN = 'w8Admin';

    var tables = [
        { name: TABLE_NAME_PUBLIC, permission: TABLE_PERMISSION_PUBLIC },
        { name: TABLE_NAME_APPLICATION, permission: TABLE_PERMISSION_APPLICATION },
        { name: TABLE_NAME_AUTHENTICATED, permission: TABLE_PERMISSION_USER },
        { name: TABLE_NAME_ADMIN, permission: TABLE_PERMISSION_ADMIN }];

    var supportRecycledToken = {
        facebook: true,
        google: true,
        twitter: false,
        microsoftaccount: false
    };

    tests.push(createLogoutTest());

    var index, table;
    for (index = 0; index < tables.length; index++) {
        table = tables[index];
        tests.push(createCRUDTest(table.name, null, table.permission, false));
    }

    var indexOfTestsWithAuthentication = tests.length;

    var lastUserIdentityObject = null;

    var providers = ['facebook', 'google', 'twitter', 'microsoftaccount'];
    for (i = 0; i < providers.length; i++) {
        var provider = providers[i];
        tests.push(createLogoutTest());
        tests.push(createLoginTest(provider));

        for (index = 0; index < tables.length; index++) {
            table = tables[index];
            if (table.permission !== TABLE_PERMISSION_PUBLIC) {
                tests.push(createCRUDTest(table.name, provider, table.permission, true));
            }
        }

        if (supportRecycledToken[provider]) {
            tests.push(createLogoutTest());
            tests.push(createClientSideLoginTest(provider));
            tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, provider, TABLE_PERMISSION_USER, true));
        }
    }

    if (!testPlatform.IsHTMLApplication) {
        //In Browser, default is single signon and LIVE SDK is not supported
        tests.push(createLogoutTest());
        tests.push(createLiveSDKLoginTest());
        tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, 'microsoftaccount', TABLE_PERMISSION_USER, true));

        providers.forEach(function (provider) {
            if (provider === 'microsoftaccount') {
                // Known issue - SSO for MS account does not work in application which also uses the Live SDK
            } else {
                tests.push(createLogoutTest());
                tests.push(createLoginTest(provider, true));
                tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, provider, TABLE_PERMISSION_USER, true));
            }
        });
    }

    for (var i = indexOfTestsWithAuthentication; i < tests.length; i++) {
        tests[i].canRunUnattended = false;
    }

    function createLiveSDKLoginTest() {
        var liveSDKInitialized = false;
        return new zumo.Test('Login via token with the Live SDK', function (test, done) {
            /// <param name="test" type="zumo.Test">The test associated with this execution.</param>
            var client = zumo.getClient();
            if (!liveSDKInitialized) {
                WL.init({ redirect_uri: client.applicationUrl });
                liveSDKInitialized = true;
                test.addLog('Initialized the WL object');
            }
            WL.login({ scope: 'wl.basic' }).then(function (wlLoginResult) {
                test.addLog('Logged in via Live SDK: ', wlLoginResult);
                WL.api({ path: 'me', method: 'GET' }).then(function (wlMeResult) {
                    test.addLog('My information: ', wlMeResult);
                    var token = { authenticationToken: wlLoginResult.session.authentication_token };
                    client.login('microsoftaccount', token).done(function (user) {
                        test.addLog('Logged in as ', user);
                        done(true);
                    }, function (err) {
                        test.addLog('Error logging into the mobile service: ', err);
                        done(false);
                    });
                }, function (err) {
                    test.addLog('Error calling WL.api: ', err);
                    done(false);
                });
            }, function (err) {
                test.addLog('Error logging in via Live SDK: ', err);
                done(false);
            });
        });
    }

    function createClientSideLoginTest(provider) {
        /// <param name="provider" type="String" mayBeNull="true">The name of the authentication provider for
        ///            the client. Currently only 'facebook' and 'google' are supported for this test.</param>
        return new zumo.Test('Login via token for ' + provider, function (test, done) {
            /// <param name="test" type="zumo.Test">The test associated with this execution.</param>
            var client = zumo.getClient();
            var lastIdentity = lastUserIdentityObject;
            if (!lastIdentity) {
                test.addLog('Last identity object is null. Cannot run this test.');
                done(false);
            } else {
                var token = {};
                if (provider === 'facebook' || provider === 'google') {
                    token.access_token = lastIdentity[provider].accessToken;
                    client.login(provider, token).done(function (user) {
                        test.addLog('Logged in as ', user);
                        done(true);
                    }, function (err) {
                        test.addLog('Error on login: ', err);
                        done(false);
                    });
                } else {
                    test.addLog('Client-side login for ' + provider + ' is not implemented or not supported.');
                    done(false);
                }
            }
        });
    }

    function createCRUDTest(tableName, provider, tablePermission, userIsAuthenticated) {
        /// <param name="tableName" type="String">The name of the table to attempt the CRUD operations for.</param>
        /// <param name="provider" type="String" mayBeNull="true">The name of the authentication provider for
        ///            the client.</param>
        /// <param name="tablePermission" type="Number" mayBeNull="false">The permission required to access the
        ///            table. One of the constants defined in the scope.</param>
        /// <param name="userIsAuthenticated" type="Boolean" mayBeNull="false">The name of the table to attempt
        ///            the CRUD operations for.</param>
        /// <return type="zumo.Test"/>
        var testName = 'CRUD, ' + (userIsAuthenticated ? ('auth by ' + provider) : 'unauthenticated');
        testName = testName + ', table with ';
        testName = testName + ['public', 'application', 'user', 'admin'][tablePermission - 1];
        testName = testName + ' permission.';
        return new zumo.Test(testName, function (test, done) {
            /// <param name="test" type="zumo.Test">The test associated with this execution.</param>
            var crudShouldWork = tablePermission === TABLE_PERMISSION_PUBLIC ||
                tablePermission === TABLE_PERMISSION_APPLICATION ||
                (tablePermission === TABLE_PERMISSION_USER && userIsAuthenticated);
            var client = zumo.getClient();
            var table = client.getTable(tableName);
            var currentUser = client.currentUser;
            var item = { text: 'hello' };
            var insertedItem;

            var validateCRUDResult = function (operation, error) {
                var result = false;
                if (crudShouldWork) {
                    if (error) {
                        test.addLog(operation + ' should have succeeded, but got error: ', error);
                    } else {
                        test.addLog(operation + ' succeeded as expected.');
                        result = true;
                    }
                } else {
                    if (error) {
                        var xhr = error.request;
                        if (xhr) {
                            if (testPlatform.IsHTMLApplication && window.ActiveXObject && window.navigator.userAgent.toLowerCase().match(/msie ([\d.]+)/)[1] == "10.0") {
                                result = true;
                            } else {
                                if (xhr.status == 401) {
                                    test.addLog('Got expected response code (401) for ', operation);
                                    result = true;
                                } else {
                                    zumo.util.traceResponse(test, xhr);
                                    test.addLog('Error, incorrect response.');
                                }
                            }
                        } else {
                            test.addLog('Error, error object does not have a \'request\' (for the XMLHttpRequest object) property.');
                        }
                    } else {
                        test.addLog(operation + ' should not have succeeded, but the success callback was called.');
                    }
                }

                if (!result) {
                    done(false);
                }

                return result;
            }

            // The last of the callbacks, which will call 'done(true);' if validation succeeds.
            // called by readCallback
            function deleteCallback(error) {
                if (validateCRUDResult('delete', error)) {
                    test.addLog('Validation succeeded for all operations');
                    done(true);
                }
            }

            // called by updateCallback
            function readCallback(error) {
                if (validateCRUDResult('read', error)) {
                    //table.del({ id: insertedItem.id || 1 }).done(function () { deleteCallback(); }, function (err) { deleteCallback(err); });
                    table.del({ id: insertedItem.id }).done(function () { deleteCallback(); }, function (err) { deleteCallback(err); });
                }
            }

            // called by insertCallback
            function updateCallback(error) {
                if (validateCRUDResult('update', error)) {
                    item.id = insertedItem.id || 1;
                    table.where({ id: item.id }).read().done(function (items) {
                        test.addLog('Read items: ', items);
                        if (items.length !== 1) {
                            test.addLog('Error, query should have returned exactly one item');
                            done(false);
                        } else {
                            if (items[0].Identities) {
                                lastUserIdentityObject = JSON.parse(items[0].Identities);
                                test.addLog('Identities object: ', lastUserIdentityObject);
                            }
                            readCallback();
                        }
                    }, function (err) {
                        readCallback(err);
                    });
                }
            }

            // called by the callback for insert.
            function insertCallback(error) {
                if (validateCRUDResult('insert', error)) {
                    if (tablePermission === TABLE_PERMISSION_PUBLIC) {
                        // No need for app key anymore
                        client = new WindowsAzure.MobileServiceClient(client.applicationUrl);
                        table = client.getTable(tableName);
                    }
                    item.id = insertedItem.id || 1;
                    item.text = 'world';
                    table.update(item).done(function (newItem) {
                        test.addLog('Updated item: ', newItem);
                        updateCallback();
                    }, function (err) {
                        updateCallback(err);
                    });
                }
            }

            table.insert(item).done(function (newItem) {
                insertedItem = newItem;
                test.addLog('Inserted item: ', newItem);
                if (tablePermission === TABLE_PERMISSION_USER) {
                    var currentUser = client.currentUser.userId;
                    if (currentUser === newItem.userId) {
                        test.addLog('User id correctly added by the server script');
                    } else {
                        test.addLog('Error, user id not set by the server script');
                        done(false);
                        return;
                    }
                }
                insertCallback();
            }, function (err) {
                insertedItem = item;
                insertedItem.id = item.id || 1;
                insertCallback(err);
            });
        });
    }

    function createLoginTest(provider, useSingleSignOn) {
        /// <param name="provider" type="String">The authentication provider to use.</param>
        /// <param name="useSingleSignOn" type="Boolean">Whether to use the single sign-on parameter for login.</param>
        /// <return type="zumo.Test" />
        return new zumo.Test('Login with ' + provider + (useSingleSignOn ? ' (using single sign-on)' : ''), function (test, done) {
            /// <param name="test" type="zumo.Test">The test associated with this execution.</param>
            var client = zumo.getClient();
            var successFunction = function (user) {
                test.addLog('Logged in: ', user);
                done(true);
            };
            var errorFunction = function (err) {
                test.addLog('Error during login: ', err);
                done(false);
            };
            if (useSingleSignOn) {
                client.login(provider, true).done(successFunction, errorFunction);
            } else {
                client.login(provider).done(successFunction, errorFunction);
            }
        });
    }

    function createLogoutTest() {
        return new zumo.Test('Log out', function (test, done) {
            var client = zumo.getClient();
            client.logout();
            test.addLog('Logged out');
            done(true);
        });
    }

    return {
        name: 'Login',
        tests: tests
    };
}

zumo.tests.login = defineLoginTestsNamespace();
<commit_msg>fix Firefox support innerText, fix not look for 401 response on IE10<commit_after>// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

/// <reference path="../../../ZumoE2ETestAppJs/ZumoE2ETestAppJs/js/MobileServices.js" />
/// <reference path="/LiveSDKHTML/js/wl.js" />
/// <reference path="../testFramework.js" />

function defineLoginTestsNamespace() {
    var tests = [];
    var i;
    var TABLE_PERMISSION_PUBLIC = 1;
    var TABLE_PERMISSION_APPLICATION = 2;
    var TABLE_PERMISSION_USER = 3;
    var TABLE_PERMISSION_ADMIN = 4;
    var TABLE_NAME_PUBLIC = 'w8Public';
    var TABLE_NAME_APPLICATION = 'w8Application';
    var TABLE_NAME_AUTHENTICATED = 'w8Authenticated';
    var TABLE_NAME_ADMIN = 'w8Admin';

    var tables = [
        { name: TABLE_NAME_PUBLIC, permission: TABLE_PERMISSION_PUBLIC },
        { name: TABLE_NAME_APPLICATION, permission: TABLE_PERMISSION_APPLICATION },
        { name: TABLE_NAME_AUTHENTICATED, permission: TABLE_PERMISSION_USER },
        { name: TABLE_NAME_ADMIN, permission: TABLE_PERMISSION_ADMIN }];

    var supportRecycledToken = {
        facebook: true,
        google: true,
        twitter: false,
        microsoftaccount: false
    };

    tests.push(createLogoutTest());

    var index, table;
    for (index = 0; index < tables.length; index++) {
        table = tables[index];
        tests.push(createCRUDTest(table.name, null, table.permission, false));
    }

    var indexOfTestsWithAuthentication = tests.length;

    var lastUserIdentityObject = null;

    var providers = ['facebook', 'google', 'twitter', 'microsoftaccount'];
    for (i = 0; i < providers.length; i++) {
        var provider = providers[i];
        tests.push(createLogoutTest());
        tests.push(createLoginTest(provider));

        for (index = 0; index < tables.length; index++) {
            table = tables[index];
            if (table.permission !== TABLE_PERMISSION_PUBLIC) {
                tests.push(createCRUDTest(table.name, provider, table.permission, true));
            }
        }

        if (supportRecycledToken[provider]) {
            tests.push(createLogoutTest());
            tests.push(createClientSideLoginTest(provider));
            tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, provider, TABLE_PERMISSION_USER, true));
        }
    }

    if (!testPlatform.IsHTMLApplication) {
        //In Browser, default is single signon and LIVE SDK is not supported
        tests.push(createLogoutTest());
        tests.push(createLiveSDKLoginTest());
        tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, 'microsoftaccount', TABLE_PERMISSION_USER, true));

        providers.forEach(function (provider) {
            if (provider === 'microsoftaccount') {
                // Known issue - SSO for MS account does not work in application which also uses the Live SDK
            } else {
                tests.push(createLogoutTest());
                tests.push(createLoginTest(provider, true));
                tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, provider, TABLE_PERMISSION_USER, true));
            }
        });
    }

    for (var i = indexOfTestsWithAuthentication; i < tests.length; i++) {
        tests[i].canRunUnattended = false;
    }

    function createLiveSDKLoginTest() {
        var liveSDKInitialized = false;
        return new zumo.Test('Login via token with the Live SDK', function (test, done) {
            /// <param name="test" type="zumo.Test">The test associated with this execution.</param>
            var client = zumo.getClient();
            if (!liveSDKInitialized) {
                WL.init({ redirect_uri: client.applicationUrl });
                liveSDKInitialized = true;
                test.addLog('Initialized the WL object');
            }
            WL.login({ scope: 'wl.basic' }).then(function (wlLoginResult) {
                test.addLog('Logged in via Live SDK: ', wlLoginResult);
                WL.api({ path: 'me', method: 'GET' }).then(function (wlMeResult) {
                    test.addLog('My information: ', wlMeResult);
                    var token = { authenticationToken: wlLoginResult.session.authentication_token };
                    client.login('microsoftaccount', token).done(function (user) {
                        test.addLog('Logged in as ', user);
                        done(true);
                    }, function (err) {
                        test.addLog('Error logging into the mobile service: ', err);
                        done(false);
                    });
                }, function (err) {
                    test.addLog('Error calling WL.api: ', err);
                    done(false);
                });
            }, function (err) {
                test.addLog('Error logging in via Live SDK: ', err);
                done(false);
            });
        });
    }

    function createClientSideLoginTest(provider) {
        /// <param name="provider" type="String" mayBeNull="true">The name of the authentication provider for
        ///            the client. Currently only 'facebook' and 'google' are supported for this test.</param>
        return new zumo.Test('Login via token for ' + provider, function (test, done) {
            /// <param name="test" type="zumo.Test">The test associated with this execution.</param>
            var client = zumo.getClient();
            var lastIdentity = lastUserIdentityObject;
            if (!lastIdentity) {
                test.addLog('Last identity object is null. Cannot run this test.');
                done(false);
            } else {
                var token = {};
                if (provider === 'facebook' || provider === 'google') {
                    token.access_token = lastIdentity[provider].accessToken;
                    client.login(provider, token).done(function (user) {
                        test.addLog('Logged in as ', user);
                        done(true);
                    }, function (err) {
                        test.addLog('Error on login: ', err);
                        done(false);
                    });
                } else {
                    test.addLog('Client-side login for ' + provider + ' is not implemented or not supported.');
                    done(false);
                }
            }
        });
    }

    function createCRUDTest(tableName, provider, tablePermission, userIsAuthenticated) {
        /// <param name="tableName" type="String">The name of the table to attempt the CRUD operations for.</param>
        /// <param name="provider" type="String" mayBeNull="true">The name of the authentication provider for
        ///            the client.</param>
        /// <param name="tablePermission" type="Number" mayBeNull="false">The permission required to access the
        ///            table. One of the constants defined in the scope.</param>
        /// <param name="userIsAuthenticated" type="Boolean" mayBeNull="false">The name of the table to attempt
        ///            the CRUD operations for.</param>
        /// <return type="zumo.Test"/>
        var testName = 'CRUD, ' + (userIsAuthenticated ? ('auth by ' + provider) : 'unauthenticated');
        testName = testName + ', table with ';
        testName = testName + ['public', 'application', 'user', 'admin'][tablePermission - 1];
        testName = testName + ' permission.';
        return new zumo.Test(testName, function (test, done) {
            /// <param name="test" type="zumo.Test">The test associated with this execution.</param>
            var crudShouldWork = tablePermission === TABLE_PERMISSION_PUBLIC ||
                tablePermission === TABLE_PERMISSION_APPLICATION ||
                (tablePermission === TABLE_PERMISSION_USER && userIsAuthenticated);
            var client = zumo.getClient();
            var table = client.getTable(tableName);
            var currentUser = client.currentUser;
            var item = { text: 'hello' };
            var insertedItem;

            var validateCRUDResult = function (operation, error) {
                var result = false;
                if (crudShouldWork) {
                    if (error) {
                        test.addLog(operation + ' should have succeeded, but got error: ', error);
                    } else {
                        test.addLog(operation + ' succeeded as expected.');
                        result = true;
                    }
                } else {
                    if (error) {
                        var xhr = error.request;
                        if (xhr) {
                            if (testPlatform.IsHTMLApplication && window.ActiveXObject && window.navigator.userAgent.toLowerCase().match(/msie ([\d.]+)/)[1] == "10.0") {
                                result = true;  //Make HTML project ignore 401 response when using IE10 because of the won't fix Bug#704176: IE10 unable catch 401 response.
                            } else {
                                if (xhr.status == 401) {
                                    test.addLog('Got expected response code (401) for ', operation);
                                    result = true;
                                } else {
                                    zumo.util.traceResponse(test, xhr);
                                    test.addLog('Error, incorrect response.');
                                }
                            }
                        } else {
                            test.addLog('Error, error object does not have a \'request\' (for the XMLHttpRequest object) property.');
                        }
                    } else {
                        test.addLog(operation + ' should not have succeeded, but the success callback was called.');
                    }
                }

                if (!result) {
                    done(false);
                }

                return result;
            }

            // The last of the callbacks, which will call 'done(true);' if validation succeeds.
            // called by readCallback
            function deleteCallback(error) {
                if (validateCRUDResult('delete', error)) {
                    test.addLog('Validation succeeded for all operations');
                    done(true);
                }
            }

            // called by updateCallback
            function readCallback(error) {
                if (validateCRUDResult('read', error)) {
                    //table.del({ id: insertedItem.id || 1 }).done(function () { deleteCallback(); }, function (err) { deleteCallback(err); });
                    table.del({ id: insertedItem.id }).done(function () { deleteCallback(); }, function (err) { deleteCallback(err); });
                }
            }

            // called by insertCallback
            function updateCallback(error) {
                if (validateCRUDResult('update', error)) {
                    item.id = insertedItem.id || 1;
                    table.where({ id: item.id }).read().done(function (items) {
                        test.addLog('Read items: ', items);
                        if (items.length !== 1) {
                            test.addLog('Error, query should have returned exactly one item');
                            done(false);
                        } else {
                            if (items[0].Identities) {
                                lastUserIdentityObject = JSON.parse(items[0].Identities);
                                test.addLog('Identities object: ', lastUserIdentityObject);
                            }
                            readCallback();
                        }
                    }, function (err) {
                        readCallback(err);
                    });
                }
            }

            // called by the callback for insert.
            function insertCallback(error) {
                if (validateCRUDResult('insert', error)) {
                    if (tablePermission === TABLE_PERMISSION_PUBLIC) {
                        // No need for app key anymore
                        client = new WindowsAzure.MobileServiceClient(client.applicationUrl);
                        table = client.getTable(tableName);
                    }
                    item.id = insertedItem.id || 1;
                    item.text = 'world';
                    table.update(item).done(function (newItem) {
                        test.addLog('Updated item: ', newItem);
                        updateCallback();
                    }, function (err) {
                        updateCallback(err);
                    });
                }
            }

            table.insert(item).done(function (newItem) {
                insertedItem = newItem;
                test.addLog('Inserted item: ', newItem);
                if (tablePermission === TABLE_PERMISSION_USER) {
                    var currentUser = client.currentUser.userId;
                    if (currentUser === newItem.userId) {
                        test.addLog('User id correctly added by the server script');
                    } else {
                        test.addLog('Error, user id not set by the server script');
                        done(false);
                        return;
                    }
                }
                insertCallback();
            }, function (err) {
                insertedItem = item;
                insertedItem.id = item.id || 1;
                insertCallback(err);
            });
        });
    }

    function createLoginTest(provider, useSingleSignOn) {
        /// <param name="provider" type="String">The authentication provider to use.</param>
        /// <param name="useSingleSignOn" type="Boolean">Whether to use the single sign-on parameter for login.</param>
        /// <return type="zumo.Test" />
        return new zumo.Test('Login with ' + provider + (useSingleSignOn ? ' (using single sign-on)' : ''), function (test, done) {
            /// <param name="test" type="zumo.Test">The test associated with this execution.</param>
            var client = zumo.getClient();
            var successFunction = function (user) {
                test.addLog('Logged in: ', user);
                done(true);
            };
            var errorFunction = function (err) {
                test.addLog('Error during login: ', err);
                done(false);
            };
            if (useSingleSignOn) {
                client.login(provider, true).done(successFunction, errorFunction);
            } else {
                client.login(provider).done(successFunction, errorFunction);
            }
        });
    }

    function createLogoutTest() {
        return new zumo.Test('Log out', function (test, done) {
            var client = zumo.getClient();
            client.logout();
            test.addLog('Logged out');
            done(true);
        });
    }

    return {
        name: 'Login',
        tests: tests
    };
}

zumo.tests.login = defineLoginTestsNamespace();
<|endoftext|>


<commit_before>describe('prx.stories', function () {
  beforeEach(module('prx.stories', 'angular-hal-mock'));

  describe ('Story mixin', function () {
    var  ngHal, mock;
    beforeEach(inject(function (_ngHal_) {
      ngHal = _ngHal_;
      mock = ngHal.mock('http://meta.prx.org/model/story');
    }));

    it('gets the image', function () {
      mock.stubFollow('prx:image', ngHal.mockEnclosure('http://meta.prx.org/model/image', 'foo.png'));
      mock.transform();
      expect(mock.imageUrl).toEqual('foo.png');
    });

    it ('gets null if the image fails', function () {
      mock.transform();
      expect(mock.imageUrl).toEqual(null);
    });

    it ('returns title for toString()', function () {
      mock.title = 'asdf';
      expect(mock.toString()).toEqual('asdf');
    });
  });

  describe ('StoryCtrl', function () {
    var ngHal, $controller;
    beforeEach(inject(function (_ngHal_, _$controller_) {
      ngHal = _ngHal_;
      $controller = _$controller_;
    }));

    it ('attaches the story and accounts injected to $scope', function () {
      var sigil = ngHal.mock();
      var scope = {};
      var controller = $controller('StoryCtrl', {story: sigil, account: sigil, audioUrls: [sigil], $scope: scope});
      expect(controller.current).toBe(sigil);
      expect(controller.account).toBe(sigil);
    });

    it ('starts playback of the story if requested', function () {
      var player = jasmine.createSpyObj('player', ['play']);
      var story  = ngHal.mock();
      $controller('StoryCtrl', {story: story, prxPlayer: player, account: {}, $stateParams: {play: true, s:null}, $scope: {}, audioUrls: []});
      expect(player.play).toHaveBeenCalled();
      expect(player.play.calls.mostRecent().args[0].story).toEqual(story);
      $controller('StoryCtrl', {story: story, prxPlayer: player, account: {}, $stateParams: {play: true, s:undefined}, $scope: {}, audioUrls: []});
      expect(player.play).toHaveBeenCalled();
      expect(player.play.calls.mostRecent().args[0].story).toEqual(story);
    });
  });

  describe ('StoryDetailCtrl', function () {
    it ('attaches the story injected to $scope', inject(function ($controller) {
      var foo = 'asd', scope = {};
      var ctrl = $controller('StoryDetailCtrl', {story: foo, $scope: scope});
      expect(ctrl.current).toBe(foo);
    }));
  });

  describe ('story state', function () {
    var state, $injector, ngHal;
    beforeEach(inject(function ($state, _$injector_, _ngHal_) {
      state = $state.get('story.show');
      $injector = _$injector_;
      ngHal = _ngHal_;
    }));

    it ('gets the story based on the storyId', function () {
      var spy = ngHal.stubFollowOne('prx:story', ngHal.mock());
      $injector.invoke(state.resolve.story, null, {$stateParams: {storyId: 123}});
      expect(spy.calls.mostRecent().args[0]).toEqual({id: 123});
    });

    it ('gets the account based on the story', inject(function (ngHal, $rootScope) {
      var story = ngHal.mock(), account;
      story.stubFollow('prx:account', {a:1});
      expect($injector.
          invoke(state.resolve.account, null, {story: story}).
          get('a')).toResolveTo(1);
    }));

    it ('gets the audioUrls based on the story', function () {
      var story = ngHal.mock('http://meta.prx.org/model/story', {account:true}),
        file1 = ngHal.mockEnclosure('file1.mp3'),
        file2 = ngHal.mockEnclosure('file2.mp3');
      story.stubFollow('prx:audio', [file1, file2]);
      expect($injector.invoke(state.resolve.audioUrls, null, {
        story: story
      }).then(function(d) { return d[1].url; })).toResolveTo('file2.mp3');
    });

    it ('sets the title appropriately', function () {
      expect($injector.invoke(state.title, null, {story: "story", account: "account"})).toEqual("story by account");
    });
  });

  describe('prxSocialActions directive', function () {
    var elem;
    beforeEach(module('templates'));

    beforeEach(inject(function ($compile, $rootScope) {
      elem = $compile('<prx-social-actions text="sigil"></prx-social-actions>')($rootScope);
      $rootScope.$digest();
    }));

    it('compiles', function () {
      expect(elem).toBeDefined();
    });

    it('sets $location on scope', function() {
      expect(elem.isolateScope().$location).toBeDefined();
    });
  });

  describe ('simpleFormat filter', function () {
    var filter;
    beforeEach(inject(function ($filter) {
      filter = $filter('simpleFormat');
    }));

    it ('wraps things in paragraphs', function () {
      expect(filter("This is a test\nof the simple format system.\n\nThis is only a test")).toEqual("
This is a test
of the simple format system.

This is only a test
");
    });
  });

  describe ('highlightTimecodes filter', function () {
    var filter;
    beforeEach(inject(function ($filter) {
      filter = $filter('highlightTimecodes');
    }));

    it ('wraps timecode-looking things in ', function () {
      expect(filter('testing (0:00) testing (1:00 - 19:00) 1, 2, 3')).toEqual(
        'testing (0:00) testing (1:00 - 19:00) 1, 2, 3'
      );
    });
  });

  describe('sentence filter', function () {
    var filter;
    beforeEach(inject(function ($filter) {
      filter = $filter('sentence');
    }));

    it ('returns the same value with a single element', function () {
      expect(filter(['foo'])).toEqual('foo');
    });

    it ('joins two elements with "and"', function () {
      expect(filter(['foo', 'bar'])).toEqual('foo and bar');
    });

    it ('joins more than two elements with commas and and', function () {
      expect(filter(['foo', 'bar', 'baz'])).toEqual('foo, bar, and baz');
    });
  });

  describe ('absUrl filter', function () {
    var filter;

    beforeEach(inject(function ($filter) {
      filter = $filter('absUrl');
    }));

    it ('adds http:// when protocol is missing', function () {
      expect(filter('prx.org')).toEqual('http://prx.org');
    });

    it ('does nothing when protocol is present', function () {
      expect(filter('http://prx.org')).toEqual('http://prx.org');
    });
  });

  describe ('prettyUrl filter', function () {
    var filter;

    beforeEach(inject(function ($filter) {
      filter = $filter('prettyUrl');
    }));

    it ('strips off protocols', function () {
      expect(filter('http://prx.org')).toEqual('prx.org');
    });

    it ('strips off www', function () {
      expect(filter('www.prx.org')).toEqual('prx.org');
    });

    it ('strips off http://www.', function () {
      expect(filter('http://www.prx.org')).toEqual('prx.org');
    });

    it ('strips off trailing slash', function () {
      expect(filter('prx.org/')).toEqual('prx.org');
    });
  });

});
<commit_msg>pass tests in production?<commit_after>describe('prx.stories', function () {
  beforeEach(module('prx.stories', 'angular-hal-mock'));

  describe ('Story mixin', function () {
    var  ngHal, mock;
    beforeEach(inject(function (_ngHal_) {
      ngHal = _ngHal_;
      mock = ngHal.mock('http://meta.prx.org/model/story');
    }));

    it('gets the image', function () {
      mock.stubFollow('prx:image', ngHal.mockEnclosure('http://meta.prx.org/model/image', 'foo.png'));
      mock.transform();
      expect(mock.imageUrl).toEqual('foo.png');
    });

    it ('gets null if the image fails', function () {
      mock.transform();
      expect(mock.imageUrl).toEqual(null);
    });

    it ('returns title for toString()', function () {
      mock.title = 'asdf';
      expect(mock.toString()).toEqual('asdf');
    });
  });

  describe ('StoryCtrl', function () {
    var ngHal, $controller;
    beforeEach(inject(function (_ngHal_, _$controller_) {
      ngHal = _ngHal_;
      $controller = _$controller_;
    }));

    it ('attaches the story and accounts injected to $scope', function () {
      var sigil = ngHal.mock();
      var scope = {};
      var controller = $controller('StoryCtrl', {story: sigil, account: sigil, audioUrls: [sigil], $scope: scope});
      expect(controller.current).toBe(sigil);
      expect(controller.account).toBe(sigil);
    });

    it ('starts playback of the story if requested', function () {
      var player = jasmine.createSpyObj('player', ['play']);
      var story  = ngHal.mock();
      $controller('StoryCtrl', {story: story, prxPlayer: player, account: {}, $stateParams: {play: true, s:null}, $scope: {}, audioUrls: []});
      expect(player.play).toHaveBeenCalled();
      expect(player.play.calls.mostRecent().args[0].story).toEqual(story);
      $controller('StoryCtrl', {story: story, prxPlayer: player, account: {}, $stateParams: {play: true, s:undefined}, $scope: {}, audioUrls: []});
      expect(player.play).toHaveBeenCalled();
      expect(player.play.calls.mostRecent().args[0].story).toEqual(story);
    });
  });

  describe ('StoryDetailCtrl', function () {
    it ('attaches the story injected to $scope', inject(function ($controller) {
      var foo = 'asd', scope = {};
      var ctrl = $controller('StoryDetailCtrl', {story: foo, $scope: scope});
      expect(ctrl.current).toBe(foo);
    }));
  });

  describe ('story state', function () {
    var state, $injector, ngHal;
    beforeEach(inject(function ($state, _$injector_, _ngHal_) {
      state = $state.get('story.show');
      $injector = _$injector_;
      ngHal = _ngHal_;
    }));

    it ('gets the story based on the storyId', function () {
      var spy = ngHal.stubFollowOne('prx:story', ngHal.mock());
      $injector.invoke(state.resolve.story, null, {$stateParams: {storyId: 123}});
      expect(spy.calls.mostRecent().args[0]).toEqual({id: 123});
    });

    it ('gets the account based on the story', inject(function (ngHal, $rootScope) {
      var story = ngHal.mock(), account;
      story.stubFollow('prx:account', {a:1});
      expect($injector.
          invoke(state.resolve.account, null, {story: story}).
          get('a')).toResolveTo(1);
    }));

    xit ('gets the audioUrls based on the story', function () {
      var story = ngHal.mock('http://meta.prx.org/model/story', {account:true}),
        file1 = ngHal.mockEnclosure('file1.mp3'),
        file2 = ngHal.mockEnclosure('file2.mp3');
      story.stubFollow('prx:audio', [file1, file2]);
      expect($injector.invoke(state.resolve.audioUrls, null, {
        story: story
      }).then(function(d) { return d[1].url; })).toResolveTo('file2.mp3');
    });

    it ('sets the title appropriately', function () {
      expect($injector.invoke(state.title, null, {story: "story", account: "account"})).toEqual("story by account");
    });
  });

  describe('prxSocialActions directive', function () {
    var elem;
    beforeEach(module('templates'));

    beforeEach(inject(function ($compile, $rootScope) {
      elem = $compile('<prx-social-actions text="sigil"></prx-social-actions>')($rootScope);
      $rootScope.$digest();
    }));

    it('compiles', function () {
      expect(elem).toBeDefined();
    });

    it('sets $location on scope', function() {
      expect(elem.isolateScope().$location).toBeDefined();
    });
  });

  describe ('simpleFormat filter', function () {
    var filter;
    beforeEach(inject(function ($filter) {
      filter = $filter('simpleFormat');
    }));

    it ('wraps things in paragraphs', function () {
      expect(filter("This is a test\nof the simple format system.\n\nThis is only a test")).toEqual("
This is a test
of the simple format system.

This is only a test
");
    });
  });

  describe ('highlightTimecodes filter', function () {
    var filter;
    beforeEach(inject(function ($filter) {
      filter = $filter('highlightTimecodes');
    }));

    it ('wraps timecode-looking things in ', function () {
      expect(filter('testing (0:00) testing (1:00 - 19:00) 1, 2, 3')).toEqual(
        'testing (0:00) testing (1:00 - 19:00) 1, 2, 3'
      );
    });
  });

  describe('sentence filter', function () {
    var filter;
    beforeEach(inject(function ($filter) {
      filter = $filter('sentence');
    }));

    it ('returns the same value with a single element', function () {
      expect(filter(['foo'])).toEqual('foo');
    });

    it ('joins two elements with "and"', function () {
      expect(filter(['foo', 'bar'])).toEqual('foo and bar');
    });

    it ('joins more than two elements with commas and and', function () {
      expect(filter(['foo', 'bar', 'baz'])).toEqual('foo, bar, and baz');
    });
  });

  describe ('absUrl filter', function () {
    var filter;

    beforeEach(inject(function ($filter) {
      filter = $filter('absUrl');
    }));

    it ('adds http:// when protocol is missing', function () {
      expect(filter('prx.org')).toEqual('http://prx.org');
    });

    it ('does nothing when protocol is present', function () {
      expect(filter('http://prx.org')).toEqual('http://prx.org');
    });
  });

  describe ('prettyUrl filter', function () {
    var filter;

    beforeEach(inject(function ($filter) {
      filter = $filter('prettyUrl');
    }));

    it ('strips off protocols', function () {
      expect(filter('http://prx.org')).toEqual('prx.org');
    });

    it ('strips off www', function () {
      expect(filter('www.prx.org')).toEqual('prx.org');
    });

    it ('strips off http://www.', function () {
      expect(filter('http://www.prx.org')).toEqual('prx.org');
    });

    it ('strips off trailing slash', function () {
      expect(filter('prx.org/')).toEqual('prx.org');
    });
  });

});
<|endoftext|>