<commit_before>'use strict';

// ---------------------------------------------------------------------------

const liqui = require ('./liqui.js');
const { ExchangeError, InsufficientFunds, AuthenticationError } = require ('./base/errors');

// ---------------------------------------------------------------------------

module.exports = class yobit extends liqui {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'yobit',
            'name': 'YoBit',
            'countries': [ 'RU' ],
            'rateLimit': 3000, // responses are cached every 2 seconds
            'version': '3',
            'has': {
                'createDepositAddress': true,
                'fetchDepositAddress': true,
                'fetchDeposits': false,
                'fetchWithdrawals': false,
                'fetchTransactions': false,
                'CORS': false,
                'withdraw': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766910-cdcbfdae-5eea-11e7-9859-03fea873272d.jpg',
                'api': {
                    'public': 'https://yobit.net/api',
                    'private': 'https://yobit.net/tapi',
                },
                'www': 'https://www.yobit.net',
                'doc': 'https://www.yobit.net/en/api/',
                'fees': 'https://www.yobit.net/en/fees/',
            },
            'api': {
                'public': {
                    'get': [
                        'depth/{pair}',
                        'info',
                        'ticker/{pair}',
                        'trades/{pair}',
                    ],
                },
                'private': {
                    'post': [
                        'ActiveOrders',
                        'CancelOrder',
                        'GetDepositAddress',
                        'getInfo',
                        'OrderInfo',
                        'Trade',
                        'TradeHistory',
                        'WithdrawCoinsToAddress',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.002,
                    'taker': 0.002,
                },
                'funding': {
                    'withdraw': {},
                },
            },
            'commonCurrencies': {
                'AIR': 'AirCoin',
                'ANI': 'ANICoin',
                'ANT': 'AntsCoin',  // what is this, a coin for ants?
                'ATMCHA': 'ATM',
                'ASN': 'Ascension',
                'AST': 'Astral',
                'ATM': 'Autumncoin',
                'BCC': 'BCH',
                'BCS': 'BitcoinStake',
                'BLN': 'Bulleon',
                'BOT': 'BOTcoin',
                'BON': 'BONES',
                'BPC': 'BitcoinPremium',
                'BTS': 'Bitshares2',
                'CAT': 'BitClave',
                'CMT': 'CometCoin',
                'COV': 'Coven Coin',
                'COVX': 'COV',
                'CPC': 'Capricoin',
                'CS': 'CryptoSpots',
                'DCT': 'Discount',
                'DGD': 'DarkGoldCoin',
                'DIRT': 'DIRTY',
                'DROP': 'FaucetCoin',
                'EKO': 'EkoCoin',
                'ENTER': 'ENTRC',
                'EPC': 'ExperienceCoin',
                'ERT': 'Eristica Token',
                'ESC': 'EdwardSnowden',
                'EUROPE': 'EUROP',
                'EXT': 'LifeExtension',
                'FUNK': 'FUNKCoin',
                'GCC': 'GlobalCryptocurrency',
                'GEN': 'Genstake',
                'GENE': 'Genesiscoin',
                'GOLD': 'GoldMint',
                'GOT': 'Giotto Coin',
                'HTML5': 'HTML',
                'HYPERX': 'HYPER',
                'ICN': 'iCoin',
                'INSANE': 'INSN',
                'JNT': 'JointCoin',
                'JPC': 'JupiterCoin',
                'KNC': 'KingN Coin',
                'LBTCX': 'LiteBitcoin',
                'LIZI': 'LiZi',
                'LOC': 'LocoCoin',
                'LOCX': 'LOC',
                'LUNYR': 'LUN',
                'LUN': 'LunarCoin',  // they just change the ticker if it is already taken
                'MDT': 'Midnight',
                'NAV': 'NavajoCoin',
                'NBT': 'NiceBytes',
                'OMG': 'OMGame',
                'PAC': '$PAC',
                'PLAY': 'PlayCoin',
                'PIVX': 'Darknet',
                'PRS': 'PRE',
                'PUTIN': 'PUT',
                'STK': 'StakeCoin',
                'SUB': 'Subscriptio',
                'PAY': 'EPAY',
                'PLC': 'Platin Coin',
                'RCN': 'RCoin',
                'REP': 'Republicoin',
                'RUR': 'RUB',
                'XIN': 'XINCoin',
            },
            'options': {
                'fetchOrdersRequiresSymbol': true,
                'fetchTickersMaxLength': 512,
            },
            'exceptions': {
                'broad': {
                    'Total transaction amount': ExchangeError, // { "success": 0, "error": "Total transaction amount is less than minimal total: 0.00010000"}
                    'Insufficient funds': InsufficientFunds,
                    'invalid key': AuthenticationError,
                },
            },
        });
    }

    parseOrderStatus (status) {
        let statuses = {
            '0': 'open',
            '1': 'closed',
            '2': 'canceled',
            '3': 'open', // or partially-filled and closed? https://github.com/ccxt/ccxt/issues/1594
        };
        if (status in statuses)
            return statuses[status];
        return status;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostGetInfo ();
        let balances = response['return'];
        let result = { 'info': balances };
        let sides = { 'free': 'funds', 'total': 'funds_incl_orders' };
        let keys = Object.keys (sides);
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            let side = sides[key];
            if (side in balances) {
                let currencies = Object.keys (balances[side]);
                for (let j = 0; j < currencies.length; j++) {
                    let lowercase = currencies[j];
                    let uppercase = lowercase.toUpperCase ();
                    let currency = this.commonCurrencyCode (uppercase);
                    let account = undefined;
                    if (currency in result) {
                        account = result[currency];
                    } else {
                        account = this.account ();
                    }
                    account[key] = balances[side][lowercase];
                    if ((account['total'] !== undefined) && (account['free'] !== undefined))
                        account['used'] = account['total'] - account['free'];
                    result[currency] = account;
                }
            }
        }
        return this.parseBalance (result);
    }

    async createDepositAddress (code, params = {}) {
        let response = await this.fetchDepositAddress (code, this.extend ({
            'need_new': 1,
        }, params));
        let address = this.safeString (response, 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'tag': undefined,
            'info': response['info'],
        };
    }

    async fetchDepositAddress (code, params = {}) {
        await this.loadMarkets ();
        let currency = this.currency (code);
        let request = {
            'coinName': currency['id'],
            'need_new': 0,
        };
        let response = await this.privatePostGetDepositAddress (this.extend (request, params));
        let address = this.safeString (response['return'], 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'tag': undefined,
            'info': response,
        };
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = undefined;
        // some derived classes use camelcase notation for request fields
        let request = {
            // 'from': 123456789, // trade ID, from which the display starts numerical 0 (test result: liqui ignores this field)
            // 'count': 1000, // the number of trades for display numerical, default = 1000
            // 'from_id': trade ID, from which the display starts numerical 0
            // 'end_id': trade ID on which the display ends numerical ∞
            // 'order': 'ASC', // sorting, default = DESC (test result: liqui ignores this field, most recent trade always goes last)
            // 'since': 1234567890, // UTC start time, default = 0 (test result: liqui ignores this field)
            // 'end': 1234567890, // UTC end time, default = ∞ (test result: liqui ignores this field)
            // 'pair': 'eth_btc', // default = all markets
        };
        if (symbol !== undefined) {
            market = this.market (symbol);
            request['pair'] = market['id'];
        }
        if (limit !== undefined) {
            request['count'] = parseInt (limit);
        }
        if (since !== undefined) {
            request['since'] = parseInt (since / 1000);
        }
        let method = this.options['fetchMyTradesMethod'];
        let response = await this[method] (this.extend (request, params));
        let trades = this.safeValue (response, 'return', {});
        let ids = Object.keys (trades);
        let result = [];
        for (let i = 0; i < ids.length; i++) {
            const id = ids[i];
            const trade = this.parseTrade (this.extend (trades[id], {
                'trade_id': id,
            }), market);
            result.push (trade);
        }
        return this.filterBySymbolSinceLimit (result, symbol, since, limit);
    }

    async withdraw (code, amount, address, tag = undefined, params = {}) {
        this.checkAddress (address);
        await this.loadMarkets ();
        let currency = this.currency (code);
        let response = await this.privatePostWithdrawCoinsToAddress (this.extend ({
            'coinName': currency['id'],
            'amount': amount,
            'address': address,
        }, params));
        return {
            'info': response,
            'id': undefined,
        };
    }
};
<commit_msg>yobit has['fetchTickers'] = false close #5198<commit_after>'use strict';

// ---------------------------------------------------------------------------

const liqui = require ('./liqui.js');
const { ExchangeError, InsufficientFunds, AuthenticationError } = require ('./base/errors');

// ---------------------------------------------------------------------------

module.exports = class yobit extends liqui {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'yobit',
            'name': 'YoBit',
            'countries': [ 'RU' ],
            'rateLimit': 3000, // responses are cached every 2 seconds
            'version': '3',
            'has': {
                'createDepositAddress': true,
                'fetchDepositAddress': true,
                'fetchDeposits': false,
                'fetchWithdrawals': false,
                'fetchTransactions': false,
                'fetchTickers': false,
                'CORS': false,
                'withdraw': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766910-cdcbfdae-5eea-11e7-9859-03fea873272d.jpg',
                'api': {
                    'public': 'https://yobit.net/api',
                    'private': 'https://yobit.net/tapi',
                },
                'www': 'https://www.yobit.net',
                'doc': 'https://www.yobit.net/en/api/',
                'fees': 'https://www.yobit.net/en/fees/',
            },
            'api': {
                'public': {
                    'get': [
                        'depth/{pair}',
                        'info',
                        'ticker/{pair}',
                        'trades/{pair}',
                    ],
                },
                'private': {
                    'post': [
                        'ActiveOrders',
                        'CancelOrder',
                        'GetDepositAddress',
                        'getInfo',
                        'OrderInfo',
                        'Trade',
                        'TradeHistory',
                        'WithdrawCoinsToAddress',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.002,
                    'taker': 0.002,
                },
                'funding': {
                    'withdraw': {},
                },
            },
            'commonCurrencies': {
                'AIR': 'AirCoin',
                'ANI': 'ANICoin',
                'ANT': 'AntsCoin',  // what is this, a coin for ants?
                'ATMCHA': 'ATM',
                'ASN': 'Ascension',
                'AST': 'Astral',
                'ATM': 'Autumncoin',
                'BCC': 'BCH',
                'BCS': 'BitcoinStake',
                'BLN': 'Bulleon',
                'BOT': 'BOTcoin',
                'BON': 'BONES',
                'BPC': 'BitcoinPremium',
                'BTS': 'Bitshares2',
                'CAT': 'BitClave',
                'CMT': 'CometCoin',
                'COV': 'Coven Coin',
                'COVX': 'COV',
                'CPC': 'Capricoin',
                'CS': 'CryptoSpots',
                'DCT': 'Discount',
                'DGD': 'DarkGoldCoin',
                'DIRT': 'DIRTY',
                'DROP': 'FaucetCoin',
                'EKO': 'EkoCoin',
                'ENTER': 'ENTRC',
                'EPC': 'ExperienceCoin',
                'ERT': 'Eristica Token',
                'ESC': 'EdwardSnowden',
                'EUROPE': 'EUROP',
                'EXT': 'LifeExtension',
                'FUNK': 'FUNKCoin',
                'GCC': 'GlobalCryptocurrency',
                'GEN': 'Genstake',
                'GENE': 'Genesiscoin',
                'GOLD': 'GoldMint',
                'GOT': 'Giotto Coin',
                'HTML5': 'HTML',
                'HYPERX': 'HYPER',
                'ICN': 'iCoin',
                'INSANE': 'INSN',
                'JNT': 'JointCoin',
                'JPC': 'JupiterCoin',
                'KNC': 'KingN Coin',
                'LBTCX': 'LiteBitcoin',
                'LIZI': 'LiZi',
                'LOC': 'LocoCoin',
                'LOCX': 'LOC',
                'LUNYR': 'LUN',
                'LUN': 'LunarCoin',  // they just change the ticker if it is already taken
                'MDT': 'Midnight',
                'NAV': 'NavajoCoin',
                'NBT': 'NiceBytes',
                'OMG': 'OMGame',
                'PAC': '$PAC',
                'PLAY': 'PlayCoin',
                'PIVX': 'Darknet',
                'PRS': 'PRE',
                'PUTIN': 'PUT',
                'STK': 'StakeCoin',
                'SUB': 'Subscriptio',
                'PAY': 'EPAY',
                'PLC': 'Platin Coin',
                'RCN': 'RCoin',
                'REP': 'Republicoin',
                'RUR': 'RUB',
                'XIN': 'XINCoin',
            },
            'options': {
                'fetchOrdersRequiresSymbol': true,
                'fetchTickersMaxLength': 512,
            },
            'exceptions': {
                'broad': {
                    'Total transaction amount': ExchangeError, // { "success": 0, "error": "Total transaction amount is less than minimal total: 0.00010000"}
                    'Insufficient funds': InsufficientFunds,
                    'invalid key': AuthenticationError,
                },
            },
        });
    }

    parseOrderStatus (status) {
        let statuses = {
            '0': 'open',
            '1': 'closed',
            '2': 'canceled',
            '3': 'open', // or partially-filled and closed? https://github.com/ccxt/ccxt/issues/1594
        };
        if (status in statuses)
            return statuses[status];
        return status;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostGetInfo ();
        let balances = response['return'];
        let result = { 'info': balances };
        let sides = { 'free': 'funds', 'total': 'funds_incl_orders' };
        let keys = Object.keys (sides);
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            let side = sides[key];
            if (side in balances) {
                let currencies = Object.keys (balances[side]);
                for (let j = 0; j < currencies.length; j++) {
                    let lowercase = currencies[j];
                    let uppercase = lowercase.toUpperCase ();
                    let currency = this.commonCurrencyCode (uppercase);
                    let account = undefined;
                    if (currency in result) {
                        account = result[currency];
                    } else {
                        account = this.account ();
                    }
                    account[key] = balances[side][lowercase];
                    if ((account['total'] !== undefined) && (account['free'] !== undefined))
                        account['used'] = account['total'] - account['free'];
                    result[currency] = account;
                }
            }
        }
        return this.parseBalance (result);
    }

    async createDepositAddress (code, params = {}) {
        let response = await this.fetchDepositAddress (code, this.extend ({
            'need_new': 1,
        }, params));
        let address = this.safeString (response, 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'tag': undefined,
            'info': response['info'],
        };
    }

    async fetchDepositAddress (code, params = {}) {
        await this.loadMarkets ();
        let currency = this.currency (code);
        let request = {
            'coinName': currency['id'],
            'need_new': 0,
        };
        let response = await this.privatePostGetDepositAddress (this.extend (request, params));
        let address = this.safeString (response['return'], 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'tag': undefined,
            'info': response,
        };
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = undefined;
        // some derived classes use camelcase notation for request fields
        let request = {
            // 'from': 123456789, // trade ID, from which the display starts numerical 0 (test result: liqui ignores this field)
            // 'count': 1000, // the number of trades for display numerical, default = 1000
            // 'from_id': trade ID, from which the display starts numerical 0
            // 'end_id': trade ID on which the display ends numerical ∞
            // 'order': 'ASC', // sorting, default = DESC (test result: liqui ignores this field, most recent trade always goes last)
            // 'since': 1234567890, // UTC start time, default = 0 (test result: liqui ignores this field)
            // 'end': 1234567890, // UTC end time, default = ∞ (test result: liqui ignores this field)
            // 'pair': 'eth_btc', // default = all markets
        };
        if (symbol !== undefined) {
            market = this.market (symbol);
            request['pair'] = market['id'];
        }
        if (limit !== undefined) {
            request['count'] = parseInt (limit);
        }
        if (since !== undefined) {
            request['since'] = parseInt (since / 1000);
        }
        let method = this.options['fetchMyTradesMethod'];
        let response = await this[method] (this.extend (request, params));
        let trades = this.safeValue (response, 'return', {});
        let ids = Object.keys (trades);
        let result = [];
        for (let i = 0; i < ids.length; i++) {
            const id = ids[i];
            const trade = this.parseTrade (this.extend (trades[id], {
                'trade_id': id,
            }), market);
            result.push (trade);
        }
        return this.filterBySymbolSinceLimit (result, symbol, since, limit);
    }

    async withdraw (code, amount, address, tag = undefined, params = {}) {
        this.checkAddress (address);
        await this.loadMarkets ();
        let currency = this.currency (code);
        let response = await this.privatePostWithdrawCoinsToAddress (this.extend ({
            'coinName': currency['id'],
            'amount': amount,
            'address': address,
        }, params));
        return {
            'info': response,
            'id': undefined,
        };
    }
};
<|endoftext|>


<commit_before>/*
 Automatic Pancake
 */
var fs = require('fs');
//var path = require('path');
var express = require('express');
var busboy = require('connect-busboy');
var exec = require('child_process').exec;
var app = express();
var r = require('rethinkdb');
var bodyParser = require('body-parser');
var player = require('play-sound')(opts = {player: 'mplayer'});

app.set('port', 3456);
app.use(busboy());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    next();
});

// Initialize the rethink connection.
var connection = null;

r.connect({host: 'localhost', port: 28015, database: 'automaticpancake'}, function (err, conn) {
    if (err) throw err;
    connection = conn;
});

// Database configuration
var database = 'automaticpancake';
var tables = {files: 'files', tracking: 'tracking'};

//function tableCreate(tableName) {
//    r.db(database).tableCreate(tableName).run(connection, function(err, result) {
//        if (err) throw err;
//        logDbCall(result);
//    });
//}

function logDbCall(result) {
    console.log(JSON.stringify(result, null, 2));
}

// This...didn't really work.
//tableCreate(tables.files);
//tableCreate(tables.tracking);

var play = function (id) {
    var fullpath = __dirname + '/files/';
    r.db(database).table(tables.files).get(id).run(connection, function(err, result) {
        //filter(r.row('id').eq(id))
        fullpath += result.file;
        console.log("Playing " + fullpath);

        player.play(fullpath, function (err) {
            // Nulls show up a lot.  ¯\_(ツ)_/¯
            if (err) {
                console.log('Play error ' + err);
            }
        });
    });
};

var getIp = function (req) {
    return req.headers['x-forwarded-for'] || req.connection.remoteAddress
};

var track = function (req, id) {
    r.db(database).table('tracking').insert([{ipAddress: getIp(req), fileId: id}])
};

app.get('/', function (req, res) {
    res.send('pancakes');
});

// GET /files - return json listing of files, names and ids used to display the frontend.
app.get('/files', function (req, res) {
    r.db(database).table(tables.files).orderBy('file').run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            res.send(result);
        });
    });
});

app.get('/tracking', function (req, res) {
    r.db(database).table(tables.tracking).run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            res.send(result);
        });
    });
});

// POST /play/u-u-i-d - Make it so.
app.post('/play/:id', function (req, res) {
    console.log('Playing ' + req.params.id);
    // Check that filename exists in db.
    track(req, req.params.id);
    play(req.params.id);
    res.send();
});

// Add the file to rethink and autoplay.
function addFile(fieldname) {
    console.log("Adding file " + fieldname);
    r.db(database).table(tables.files).insert([{ file: fieldname, created: new Date()}]).run(connection, function(err, result) {
        if (err) throw err;
        logDbCall(result);
        play(result.generated_keys[0]);
    });
}

// POST /upload - Drop a file, add and play it.
app.post('/upload', function (req, res) {
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file) {
        console.log("Uploading: " + fieldname);
        fstream = fs.createWriteStream(__dirname + '/files/' + fieldname);
        file.pipe(fstream);
        addFile(fieldname)
    });
    res.send();
});

// Grab the youtube title with minimal transformation based on discovery of what youtube-dl does to drop valid filenames.
function getTitle(youtubeId, callback) {
    titleCmd = 'youtube-dl --get-title --get-id -- ' + youtubeId;
    console.log("executing " + titleCmd);
    exec(titleCmd, function(error, stdout, stderr) {
        outs = stdout.split(/\n/);
        title = outs[0].trim().replace(/:/g, ' -').replace(/"/g, "'").replace(/\//g, '_');
        id = outs[1];
        console.log(["Title", title, "id", id]);
        callback(title, id);
    });
}

// POST /youtube - grab a 'tube, strip the audio, add and play it.
app.post('/youtube', function (req, res) {
    var youtubeId = req.body.uri;
    if (! youtubeId )
    console.log(youtubeId);
    cmd = "youtube-dl -w -x --write-info-json --audio-format mp3 -o '" + __dirname + '/files/' + "%(title)s.%(id)s.%(ext)s' " + '-- ' + req.body.uri;

    getTitle(youtubeId, function(title, id) {
        console.log("executing " + cmd);
        console.log(title);
        console.log(id);
        exec(cmd, function(error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            addFile(title + '.' + id + '.mp3');
            res.send();
        })
    });
});

// POST /kill - MAKE IT STOP
app.post('/kill', function (req, res) {
    track(req, 'KILL');
    exec('killall mplayer', function (error, stdout, stderr) {
        console.log(stdout);
    });
    res.send();
});

// POST delall - big ol' reset button.
app.post('/delall', function(req, res) {
    r.db(database).table(tables.files).delete().run(connection);
    res.send();
});

// DELETE /u-u-i-d - remove one file
app.delete('/:id', function(req, res) {
    r.db(database).table(tables.files).get(req.params.id).delete().run(connection);
    res.send();
});

app.listen(app.get('port'), function () {
    console.log('Server started: http://localhost:' + app.get('port') + '/');
});
<commit_msg>Tracking now actually works.<commit_after>/*
 Automatic Pancake
 */
var fs = require('fs');
//var path = require('path');
var express = require('express');
var busboy = require('connect-busboy');
var exec = require('child_process').exec;
var app = express();
var r = require('rethinkdb');
var bodyParser = require('body-parser');
var player = require('play-sound')(opts = {player: 'mplayer'});

app.set('port', 3456);
app.use(busboy());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    next();
});

// Initialize the rethink connection.
var connection = null;

r.connect({host: 'localhost', port: 28015, database: 'automaticpancake'}, function (err, conn) {
    if (err) throw err;
    connection = conn;
});

// Database configuration
var database = 'automaticpancake';
var tables = {files: 'files', tracking: 'tracking'};

//function tableCreate(tableName) {
//    r.db(database).tableCreate(tableName).run(connection, function(err, result) {
//        if (err) throw err;
//        logDbCall(result);
//    });
//}

function logDbCall(result) {
    console.log(JSON.stringify(result, null, 2));
}

// This...didn't really work.
//tableCreate(tables.files);
//tableCreate(tables.tracking);

var play = function (id) {
    var fullpath = __dirname + '/files/';
    r.db(database).table(tables.files).get(id).run(connection, function(err, result) {
        //filter(r.row('id').eq(id))
        fullpath += result.file;
        console.log("Playing " + fullpath);

        player.play(fullpath, function (err) {
            // Nulls show up a lot.  ¯\_(ツ)_/¯
            if (err) {
                console.log('Play error ' + err);
            }
        });
    });
};

var getIp = function (req) {
    return req.headers['x-forwarded-for'] || req.connection.remoteAddress
};

var track = function (req, id) {
    r.db(database).table('tracking').insert([{ipAddress: getIp(req), fileId: id}]).run(connection);
};

app.get('/', function (req, res) {
    res.send('pancakes');
});

// GET /files - return json listing of files, names and ids used to display the frontend.
app.get('/files', function (req, res) {
    r.db(database).table(tables.files).orderBy('file').run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            res.send(result);
        });
    });
});

app.get('/tracking', function (req, res) {
    r.db(database).table(tables.tracking).run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            res.send(result);
        });
    });
});

// POST /play/u-u-i-d - Make it so.
app.post('/play/:id', function (req, res) {
    console.log('Playing ' + req.params.id);
    // Check that filename exists in db.
    track(req, req.params.id);
    play(req.params.id);
    res.send();
});

// Add the file to rethink and autoplay.
function addFile(fieldname) {
    console.log("Adding file " + fieldname);
    r.db(database).table(tables.files).insert([{ file: fieldname, created: new Date()}]).run(connection, function(err, result) {
        if (err) throw err;
        logDbCall(result);
        play(result.generated_keys[0]);
    });
}

// POST /upload - Drop a file, add and play it.
app.post('/upload', function (req, res) {
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file) {
        console.log("Uploading: " + fieldname);
        fstream = fs.createWriteStream(__dirname + '/files/' + fieldname);
        file.pipe(fstream);
        addFile(fieldname)
    });
    res.send();
});

// Grab the youtube title with minimal transformation based on discovery of what youtube-dl does to drop valid filenames.
function getTitle(youtubeId, callback) {
    titleCmd = 'youtube-dl --get-title --get-id -- ' + youtubeId;
    console.log("executing " + titleCmd);
    exec(titleCmd, function(error, stdout, stderr) {
        outs = stdout.split(/\n/);
        title = outs[0].trim().replace(/:/g, ' -').replace(/"/g, "'").replace(/\//g, '_');
        id = outs[1];
        console.log(["Title", title, "id", id]);
        callback(title, id);
    });
}

// POST /youtube - grab a 'tube, strip the audio, add and play it.
app.post('/youtube', function (req, res) {
    var youtubeId = req.body.uri;
    if (! youtubeId )
    console.log(youtubeId);
    cmd = "youtube-dl -w -x --write-info-json --audio-format mp3 -o '" + __dirname + '/files/' + "%(title)s.%(id)s.%(ext)s' " + '-- ' + req.body.uri;

    getTitle(youtubeId, function(title, id) {
        console.log("executing " + cmd);
        console.log(title);
        console.log(id);
        exec(cmd, function(error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            addFile(title + '.' + id + '.mp3');
            res.send();
        })
    });
});

// POST /kill - MAKE IT STOP
app.post('/kill', function (req, res) {
    track(req, 'KILL');
    exec('killall mplayer', function (error, stdout, stderr) {
        console.log(stdout);
    });
    res.send();
});

// POST delall - big ol' reset button.
app.post('/delall', function(req, res) {
    r.db(database).table(tables.files).delete().run(connection);
    res.send();
});

// DELETE /u-u-i-d - remove one file
app.delete('/:id', function(req, res) {
    r.db(database).table(tables.files).get(req.params.id).delete().run(connection);
    res.send();
});

app.listen(app.get('port'), function () {
    console.log('Server started: http://localhost:' + app.get('port') + '/');
});
<|endoftext|>


<commit_before>var app = require('./app'),
    debug = require('debug')('hackathon-live-feed:server'),
    http = require('http'),
    Twitter = require('twitter'),
    config = require('./_config'),
    request = require("request");

// get port from env and store
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

// create http server
var server = http.createServer(app);

// listen
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

// normalize port
function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    return val;
  }

  if (port >= 0) {
    return port;
  }

  return false;
}

// event handler for errors
function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string' ? 'Pipe ' + port: 'Port ' + port;

  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

// listening
function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string' ? 'pipe ' + addr: 'port ' + addr.port;
  debug('Listening on ' + bind);
  console.log('Express server listening on port ' + port);
}

// sockets

var io = require('socket.io').listen(server);

var client = new Twitter({
  consumer_key: config.twitterConsumerKey,
  consumer_secret: config.twitterConsumerSecret,
  access_token_key: config.twitterAccessTokenKey,
  access_token_secret: config.twitterAccessTokenSecret
});

client.stream('statuses/filter', {track: config.hashtags}, function(stream) {
  stream.on('data', function(tweet) {
    io.emit('newTweet', tweet);
  });
  stream.on('error', function(error) {
    throw error;
  });
});

// refactor!

function getCommits(owner, repo) {
  var url = 'https://api.github.com/repos/'+owner+'/'+repo+'/events';
  var options = {
    method: 'get',
    json: true,
    url: url,
    headers : {'User-Agent': 'test'}
  };
  request(options, url, function(err, resp, body) {
    if (err) {
      res.status(500).send('Something broke!');
    }
    console.log(body);
    io.emit('newCommit', body);
  });
}

var gitData = config.github;

function loop() {
  gitData.forEach(function(data) {
    getCommits(data.owner, data.repo);
  });
}

setInterval(loop() , 180000);

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});
<commit_msg>updates<commit_after>var app = require('./app'),
    debug = require('debug')('hackathon-live-feed:server'),
    http = require('http'),
    Twitter = require('twitter'),
    config = require('./_config'),
    request = require("request");

// get port from env and store
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

// create http server
var server = http.createServer(app);

// listen
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

// normalize port
function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    return val;
  }

  if (port >= 0) {
    return port;
  }

  return false;
}

// event handler for errors
function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string' ? 'Pipe ' + port: 'Port ' + port;

  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

// listening
function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string' ? 'pipe ' + addr: 'port ' + addr.port;
  debug('Listening on ' + bind);
  console.log('Express server listening on port ' + port);
}

// sockets

var io = require('socket.io').listen(server);

var client = new Twitter({
  consumer_key: config.twitterConsumerKey,
  consumer_secret: config.twitterConsumerSecret,
  access_token_key: config.twitterAccessTokenKey,
  access_token_secret: config.twitterAccessTokenSecret
});

client.stream('statuses/filter', {track: config.hashtags}, function(stream) {
  stream.on('data', function(tweet) {
    io.emit('newTweet', tweet);
  });
  stream.on('error', function(error) {
    throw error;
  });
});

// refactor!

function getCommits(owner, repo) {
  var url = 'https://api.github.com/repos/'+owner+'/'+repo+'/events';
  var options = {
    method: 'get',
    json: true,
    url: url,
    headers : {'User-Agent': 'test'}
  };
  request(options, url, function(err, resp, body) {
    if (err) {
      res.status(500).send('Something broke!');
    }
    console.log(body);
    io.emit('newCommit', body);
  });
}

var gitData = config.github;

function loop() {
  gitData.forEach(function(data) {
    getCommits(data.owner, data.repo);
  });
}

setInterval(loop, 180000);

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpackConfig = require('./webpack/webpack.config.dev.js');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const favicon = require('express-favicon');
const Promise = require('bluebird');
const logger = require('morgan');
const errorhandler = require('errorhandler');
const jwt = require('express-jwt');
const db = require('./models');
const post = require('./routes/post');

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 3000 : process.env.PORT;
console.log('process.env: ', process.env);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(favicon(`${__dirname}/favicon.ico`));

Promise.onPossiblyUnhandledRejection((err) => {
  throw new Error(err);
});

app.use('/post', post);

if (isDeveloping) {
  app.set('host', 'http://localhost');
  app.use(logger('dev'));
  app.use(errorhandler());
  const compiler = webpack(webpackConfig);
  const middleware = webpackMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    contentBase: 'src',
    stats: {
      colors: true,
      hash: false,
      timings: true,
      chunks: false,
      chunkModules: false,
      modules: false,
    },
  });
  const response = (req, res) => {
    res.write(middleware.fileSystem.readFileSync(path.resolve(__dirname, 'dist/index.html')));
    res.end();
  };

  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));
  app.get('*', response);
} else {
  app.use(express.static(`${__dirname}/dist`));
  app.get('*', (req, res) => {
    res.write(
      fs.readFileSync(path.resolve(__dirname, 'dist/index.html'))
    );
  });
}

const onStart = (err) => {
  if (err) {
    throw new Error(err);
  }
  console.info(
    `==> 🌎 Listening on port ${port}. ` +
    `Open up http://localhost:${port}/ in your browser.`
  );
  db.sequelize.sync(
    // {force: true}
  );
};

if (!module.parent) {
  app.listen(port, 'localhost', onStart);
}

module.exports = app;
<commit_msg>cl port<commit_after>'use strict';

const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpackConfig = require('./webpack/webpack.config.dev.js');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const favicon = require('express-favicon');
const Promise = require('bluebird');
const logger = require('morgan');
const errorhandler = require('errorhandler');
const jwt = require('express-jwt');
const db = require('./models');
const post = require('./routes/post');

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 3000 : process.env.PORT;
console.log('process.env: ', process.env);
console.log('process.env.PORT: ', process.env.PORT);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(favicon(`${__dirname}/favicon.ico`));

Promise.onPossiblyUnhandledRejection((err) => {
  throw new Error(err);
});

app.use('/post', post);

if (isDeveloping) {
  app.set('host', 'http://localhost');
  app.use(logger('dev'));
  app.use(errorhandler());
  const compiler = webpack(webpackConfig);
  const middleware = webpackMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    contentBase: 'src',
    stats: {
      colors: true,
      hash: false,
      timings: true,
      chunks: false,
      chunkModules: false,
      modules: false,
    },
  });
  const response = (req, res) => {
    res.write(middleware.fileSystem.readFileSync(path.resolve(__dirname, 'dist/index.html')));
    res.end();
  };

  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));
  app.get('*', response);
} else {
  app.use(express.static(`${__dirname}/dist`));
  app.get('*', (req, res) => {
    res.write(
      fs.readFileSync(path.resolve(__dirname, 'dist/index.html'))
    );
  });
}

const onStart = (err) => {
  if (err) {
    throw new Error(err);
  }
  console.info(
    `==> 🌎 Listening on port ${port}. ` +
    `Open up http://localhost:${port}/ in your browser.`
  );
  db.sequelize.sync(
    // {force: true}
  );
};

if (!module.parent) {
  app.listen(port, 'localhost', onStart);
}

module.exports = app;
<|endoftext|>


<commit_before>/*jshint esversion: 6 */
const express = require('express');
const {db} = require('./database/db-config');

const app = express();

// add middleware
require('./config/middleware.js')(app, express);

// add routes
require('./config/routes.js')(app, express);

// set port depending on prod or dev
const port = process.env.NODE_ENV === 'production' ? 80 : 3000;

const listen = app.listen(port, () => {
  console.log('Server listening on port ' + port);
  db.sync();
  // .then(() => {
  //   console.log('Database is synced');
  // });
});

const ioServer = require('./sockets/io.js')(listen);

module.exports = {app, ioServer};
<commit_msg>another attempt to fix travis, force db to drop if in testing env<commit_after>/*jshint esversion: 6 */
const express = require('express');
const {db} = require('./database/db-config');

const app = express();

// add middleware
require('./config/middleware.js')(app, express);

// add routes
require('./config/routes.js')(app, express);

// set port depending on prod or dev
const port = process.env.NODE_ENV === 'production' ? 80 : 3000;

const listen = app.listen(port, () => {
  console.log('Server listening on port ' + port);
  if (process.env.NODE_ENV === 'test') { console.log('testing'); }
  process.env.NODE_ENV === 'test' ? db.sync({ force: true }) : db.sync();
  // .then(() => {
  //   console.log('Database is synced');
  // });
});

const ioServer = require('./sockets/io.js')(listen);

module.exports = {app, ioServer};
<|endoftext|>


<commit_before>var Backbone = require('./backbone');
var _ = require('underscore');
var HTTPServer = require('express').HTTPServer;
var middleware = require('..').middleware;

module.exports = Server;
function Server(plugin) {
    HTTPServer.call(this, []);
    this.plugin = plugin;
    this.initialize.apply(this, arguments);
    this.conclude.apply(this, arguments);
};

Server.prototype.__proto__ = HTTPServer.prototype;

_.extend(Server.prototype, Backbone.Events, {
    initialize: function(plugin) {},

    conclude: function(plugin) {
        // Add catchall 404 middleware and error handler for root servers.
        if (this.port) {
            this.use(middleware.notFound());
            this.error(middleware.showError());
        // Remove redundant frontmost middleware from each server that will not
        // be a root server. See `express/lib/http.js`.
        } else {
            this.stack.shift();
        }
    },

    port: null,

    start: function(callback) {
        this.port && this.listen(this.port, callback);
        return this;
    },

    toString: function() {
        if (this.port) {
            return '[Server ' + this.constructor.title + ':' + this.address().port + ']';
        } else {
            return '[Server ' + this.constructor.title + ']';
        }
    }
});

Server.augment = Backbone.Router.augment;
Server.extend = Backbone.Router.extend;
Server.toString = function() {
    return '<Server ' + this.title + '>';
};
<commit_msg>Remove Backbone events from Bones servers.<commit_after>var Backbone = require('./backbone');
var _ = require('underscore');
var HTTPServer = require('express').HTTPServer;
var middleware = require('..').middleware;

module.exports = Server;
function Server(plugin) {
    HTTPServer.call(this, []);
    this.plugin = plugin;
    this.initialize.apply(this, arguments);
    this.conclude.apply(this, arguments);
};

Server.prototype.__proto__ = HTTPServer.prototype;

_.extend(Server.prototype, {
    initialize: function(plugin) {},

    conclude: function(plugin) {
        // Add catchall 404 middleware and error handler for root servers.
        if (this.port) {
            this.use(middleware.notFound());
            this.error(middleware.showError());
        // Remove redundant frontmost middleware from each server that will not
        // be a root server. See `express/lib/http.js`.
        } else {
            this.stack.shift();
        }
    },

    port: null,

    start: function(callback) {
        this.port && this.listen(this.port, callback);
        return this;
    },

    toString: function() {
        if (this.port) {
            return '[Server ' + this.constructor.title + ':' + this.address().port + ']';
        } else {
            return '[Server ' + this.constructor.title + ']';
        }
    }
});

Server.augment = Backbone.Router.augment;
Server.extend = Backbone.Router.extend;
Server.toString = function() {
    return '<Server ' + this.title + '>';
};
<|endoftext|>


<commit_before>var express = require('express'),
    app = express(),
    config = require('./config/config'),
    logger = require('./util/logger'),
    passport = require('passport'),
    userRouter = require('./api/user/routes'),
    bookmarkRouter = require('./api/bookmark/routes');
    tagRouter = require('./api/tag/routes');

require('mongoose').connect(config.db.url);
require('./middleware/middleware')(app);
require('./api/user/auth');

app.use(passport.initialize());

app.get('/', function(req, res) {
  res.render('index');
});

app.use('/auth', userRouter);
app.use('/bookmarks', bookmarkRouter);
app.use('/tags', tagRouter);

app.use(function(err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
    res.status(400).send('Invalid token');
  } else {
    logger.error(err.stack);
  }
});

module.exports = app;<commit_msg>refactor routing for tags and bookmarks<commit_after>var express = require('express'),
    app = express(),
    config = require('./config/config'),
    logger = require('./util/logger'),
    passport = require('passport'),
    userRouter = require('./api/user/routes'),
    bookmarkRouter = require('./api/bookmark/routes'),
    tagRouter = require('./api/tag/routes');

require('mongoose').connect(config.db.url);
require('./middleware/middleware')(app);
require('./api/user/auth');

app.use(passport.initialize());

app.get('/', function(req, res) {
  res.render('index');
});

app.use('/auth', userRouter);
app.use('/bookmarks', bookmarkRouter);
app.use('/tags', tagRouter);

app.use(function(err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
    res.status(400).send('Invalid token');
  } else {
    logger.error(err.stack);
  }
});

module.exports = app;<|endoftext|>


<commit_before>'use strict'

describe('Thermostat', function(){

  var thermostat;

  beforeEach(function(){
    thermostat = new Thermostat;
  });

  it('will start at 20 degrees', function(){
    expect(thermostat.getCurrentTemperature()).toEqual(20);
  });

  it('increases in temperature with the up button', function() {
    thermostat.up();
    expect(thermostat.getCurrentTemperature()).toEqual(21);
  });

  it('decreases in temperature with the down button', function() {
    thermostat.down();
    expect(thermostat.getCurrentTemperature()).toEqual(19);
  });

  it('has a minimum of 10 degress', function(){
    for (var i =0; i < 11; i ++){
      thermostat.down();
    }
    expect(thermostat.getCurrentTemperature()).toEqual(10);
  });

  it('has power saving mode on by default', function (){
    expect(thermostat.isPowerSavingModeOn()).toBe(true);
  });

  it('can switch PSM off', function() {
    thermostat.switchPowerSavingModeOff();
    expect(thermostat.isPowerSavingModeOn()).toBe(false);
  });

  it('can switch PSM back on', function() {
    thermostat.switchPowerSavingModeOff();
    expect(thermostat.isPowerSavingModeOn()).toBe(false);
    thermostat.switchPowerSavingModeOn();
    expect(thermostat.isPowerSavingModeOn()).toBe(true);
  });
});
<commit_msg>when power saving mode is on<commit_after>'use strict'

describe('Thermostat', function(){

  var thermostat;

  beforeEach(function(){
    thermostat = new Thermostat;
  });

  it('will start at 20 degrees', function(){
    expect(thermostat.getCurrentTemperature()).toEqual(20);
  });

  it('increases in temperature with the up button', function() {
    thermostat.up();
    expect(thermostat.getCurrentTemperature()).toEqual(21);
  });

  it('decreases in temperature with the down button', function() {
    thermostat.down();
    expect(thermostat.getCurrentTemperature()).toEqual(19);
  });

  it('has a minimum of 10 degress', function(){
    for (var i =0; i < 11; i ++){
      thermostat.down();
    }
    expect(thermostat.getCurrentTemperature()).toEqual(10);
  });

  it('has power saving mode on by default', function (){
    expect(thermostat.isPowerSavingModeOn()).toBe(true);
  });

  it('can switch PSM off', function() {
    thermostat.switchPowerSavingModeOff();
    expect(thermostat.isPowerSavingModeOn()).toBe(false);
  });

  it('can switch PSM back on', function() {
    thermostat.switchPowerSavingModeOff();
    expect(thermostat.isPowerSavingModeOn()).toBe(false);
    thermostat.switchPowerSavingModeOn();
    expect(thermostat.isPowerSavingModeOn()).toBe(true);
  });

  describe('when power saving mode is on', function() {
  it('has a maximum temperature of 25 degrees', function() {
    for (var i = 0; i < 6; i++) {
      thermostat.up();
    }
    expect(thermostat.getCurrentTemperature()).toEqual(25);
  });
 });
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

var port = process.env.PORT || 3000;

require('./config/middleware.js')(app, express);

app.listen(port);

console.log('server listening on ', port);
<commit_msg>[refactor] add MongoDB connection<commit_after>var express = require('express');
var app = express();
var mongoose = require('mongoose');
var USERTEST = require('./routes/users/usersController.js');
var port = process.env.PORT || 3000;
mongoose.connect('mongodb://localhost:27017');
mongoose.connection.once('open', function() {
  console.log("Connected to mongoDB");
  USERTEST.signup();

})
require('./config/middleware.js')(app, express);

app.listen(port);

console.log('server listening on ', port);
<|endoftext|>


<commit_before>Settings = {
  map: {
    width: 450,
    height: 270,
    scale: 110,
    squash: 0.90,
    bumpDown: 30,
    bumpLeft: 30
  }
};

IMonChoroplethWidget = function(doc) { Widget.call(this, doc); };
IMonChoroplethWidget.prototype = Object.create(Widget.prototype);
IMonChoroplethWidget.prototype.constructor = IMonChoroplethWidget;

IMonChoropleth = {
  widget: {
    name: 'Global Choropleth Map',
    description: 'Shows a global chloropleth map of individual indicators within the Internet Monitor Access Index.',
    url: 'https://thenetmonitor.org/sources/platform-data',
    dimensions: { width: 3, height: 2 },
    category: 'access',
    typeIcon: 'globe',
    constructor: IMonChoroplethWidget,
    displays: 'countryData'
  },
  org: {
    name: 'Internet Monitor',
    shortName: 'IM',
    url: 'http://thenetmonitor.org'
  }
};
<commit_msg>Remove imon-choropleth category<commit_after>Settings = {
  map: {
    width: 450,
    height: 270,
    scale: 110,
    squash: 0.90,
    bumpDown: 30,
    bumpLeft: 30
  }
};

IMonChoroplethWidget = function(doc) { Widget.call(this, doc); };
IMonChoroplethWidget.prototype = Object.create(Widget.prototype);
IMonChoroplethWidget.prototype.constructor = IMonChoroplethWidget;

IMonChoropleth = {
  widget: {
    name: 'Global Choropleth Map',
    description: 'Shows a global chloropleth map of individual indicators within the Internet Monitor Access Index.',
    url: 'https://thenetmonitor.org/sources/platform-data',
    dimensions: { width: 3, height: 2 },
    typeIcon: 'globe',
    constructor: IMonChoroplethWidget,
    displays: 'countryData'
  },
  org: {
    name: 'Internet Monitor',
    shortName: 'IM',
    url: 'http://thenetmonitor.org'
  }
};
<|endoftext|>


<commit_before>'use strict';

var config = require('../config/config')[process.env.NODE_ENV = process.env.NODE_ENV || 'development'],
    siteEmail = 'tech-support@resourcegovernance.org';

var mandrill = require('node-mandrill')(process.env.MANDRILL_APIKEY);
// send email to tech support
exports.techSend = function (req, res) {
    var issue_os, issue_browser, issue_browser_ver,
        message_content = req.body,
        issue_tool = message_content.tool.toUpperCase(),
        issue_full_name = message_content.first_name + " " + message_content.last_name;
        //issue_first_name = message_content.first_name,
        //issue_last_name = message_content.last_name,
    if (message_content.os) {
        issue_os = message_content.os;
    } else {
        if(message_content.os_text) {
            issue_os = message_content.os_text;
        } else {
            issue_os = 'None supplied';
        }
    }
    if (message_content.browser) {
        issue_browser = message_content.browser;
    } else {
        if(message_content.browser_text) {
            issue_browser = message_content.browser_text;
        } else {
            issue_browser = 'None supplied';
        }
    }
    if (message_content.browser_ver) {
        issue_browser_ver = message_content.browser_ver;
    } else {
        issue_browser_ver = 'None supplied';
    }
    //send an e-mail to technical support
    mandrill('/messages/send', {
        message: {
            to: [{email: 'tech-support@resourcegovernance.org', name: 'Assessment tool tech support'}],
            from_email: message_content.email,
            subject: issue_tool + ' Issue: ' + message_content.issue.value,
            html: "Hi,
" +
            issue_full_name + " is having an issue with the " + issue_tool + " tool. Please find more info below.
" +
            "

Issue: " + message_content.issue.name + "
<
Issue description: " + message_content.issue_description + "
" +
            "
OS: " + issue_os + "

Browser: " + issue_browser + "

Browser version: " + issue_browser_ver + "

"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });

    //send a confirmation e-mail to user
    mandrill('/messages/send', {
        message: {
            to: [{email: message_content.email, name: issue_full_name}],
            from_email: 'tech-support@resourcegovernance.org',
            subject: 'Confirmation of ' + message_content.issue.value + ' support ticket',
            html: "Hi " + issue_full_name + "\,
" +
            "Thanks for contacting us about an issue with the " + issue_tool + "tool. I'm sorry for the inconvenience\, we will contact you shortly. " +
            "In the meantime please look at the info you supplied below and let us know if any of it is incorrect.
" +
            "

Issue: " + message_content.issue.name + "
<
Issue description: " + message_content.issue_description + "
" +
            "
OS: " + issue_os + "

Browser: " + issue_browser + "

Browser version: " + issue_browser_ver + "

"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
    res.send();
};

/////////////////////////////////
///////USER RECORD EMAILS////////
/////////////////////////////////

// send email to new user
exports.new_user_confirmation = function (contact_packet, token) {
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.rec_email, name: contact_packet.rec_name}],
            from_email: contact_packet.send_email,
            subject: contact_packet.rec_role + ' account created!',
            html: 'Hello ' + contact_packet.rec_name + ',
' +
            'an RGI ' + contact_packet.rec_role + 'account was just set up for you by ' + contact_packet.send_name + '.
' +
            'The user name is ' + contact_packet.rec_username + '.' +
            'Please, set password before login.
' +
            'Thanks!
' +
            'The RGI Team.'
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

exports.reset_password_confirmation = function (user, token) {
    var fullName = user.firstName.charAt(0).toUpperCase() +
        user.firstName.slice(1) + " " +
        user.lastName.charAt(0).toUpperCase() +
        user.lastName.slice(1);
    mandrill('/messages/send', {
        message: {
            to: [{email: user.email, name: fullName}],
            from_email: siteEmail,
            subject: 'Password Recovery',
            html: 'Hello ' + fullName + ',
' +
            'Please, click here to recover your password.
' +
            'Thanks!
' +
            'The RGI Team.'
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};
//TODO delete user confirmation
exports.delete_user_confirmation = function (contact_packet) {

};

////////////////////////////////////////
///////ASSESSMENT RECORD EMAILS////////
////////////////////////////////////////

// email when assessment is assigned
exports.new_assessment_assignment = function (contact_packet, type) {
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet[type + '_email'], name: contact_packet[type + '_fullName']}],
            from_email: 'rgi-admin@resourcegovernance.org',
            subject: contact_packet.assessment_title + ' assessment assigned!',
            html: "Hello " + contact_packet[type + '_firstName'] + ",
" +
            "" + contact_packet.admin_name + " just assigned the " + contact_packet.assessment_title + " assessement to you.
" +
            "Please go to your assessment dashboard to start the assessment.
" +
            "Thanks!
" +
            "The RGI Team."
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

// email when assessment is submitted or resubmitted
exports.trial_assessment_submission = function (contact_packet) {
    //send an email to team that assessment is ready
    mandrill('/messages/send', {
        message: {
            to: [
                {email: 'RGI-admin@resourcegovernance.org', name: 'RGI Team'},
                {email: 'ahasemann@resourcegovernance.org', name: 'Anna Hasemann'},
                {email: 'cperry@resourcegovernance.org', name: 'Chris Perry'},
                {email: 'jcust@resourcegovernance.org', name: 'Jim Cust'}
            ],
            from_email: contact_packet.editor_email,
            subject: contact_packet.assessment_title + ' submitted by ' + contact_packet.editor_role + " " + contact_packet.editor_fullName,
            html: "Hi team,
" +
            contact_packet.editor_fullName + " just submitted the " + contact_packet.assessment_title + " trial assessment for review." +
            "Please visit your assessment dashboard to review.
" +
            "Thanks!
" +
            "The RGI Team.
"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
    //send email to submitter that it went through
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.editor_email, name: contact_packet.editor_fullName}],
            from_email: "rgi-admin@resourcegovernance.org",
            subject: contact_packet.assessment_title + " recieved.",
            html: "Hi "+ contact_packet.editor_fullName + ",
" +
            "Your submission of the " + contact_packet.assessment_title + " trial assessment was sent to the admin team. We will be in contact shortly with next steps." +
            "Please visit your assessment dashboard if you want to check the status.
" +
            "Thanks!
" +
            "The RGI Team.
"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

// email when assessment is submitted or resubmitted
exports.assessment_submission = function (contact_packet) {
    //send an email to team that assessment is ready
    mandrill('/messages/send', {
        message: {
            to: [
                {email: 'RGI-admin@resourcegovernance.org', name: 'RGI Team'},
                {email: 'ahasemann@resourcegovernance.org', name: 'Anna Hasemann'},
                {email: 'cperry@resourcegovernance.org', name: 'Chris Perry'},
                {email: 'jcust@resourcegovernance.org', name: 'Jim Cust'}
            ],
            from_email: contact_packet.editor_email,
            subject: contact_packet.assessment_title + ' submitted by ' + contact_packet.editor_role + " " + contact_packet.editor_fullName,
            html: "Hi team,
" +
            contact_packet.editor_fullName + " just submitted the " + contact_packet.assessment_title + " assessment for review." +
            "Please visit your assessment dashboard to review.
" +
            "Thanks!
" +
            "The RGI Team.
"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
    //send email to submitter that it went through
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.editor_email, name: contact_packet.editor_fullName}],
            from_email: "rgi-admin@resourcegovernance.org",
            subject: contact_packet.assessment_title + " recieved.",
            html: "Hi "+ contact_packet.editor_fullName + ",
" +
            "Your submission of the " + contact_packet.assessment_title + " assessment was sent to the admin team. We will be in contact shortly with next steps." +
            "Please visit your assessment dashboard if you want to check the status.
" +
            "Thanks!
" +
            "The RGI Team.
"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

// email when flags need to be reviewed by researcher or reviewer
exports.flag_review = function (contact_packet) {
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.editor_email, name: contact_packet.editor_fullName}],
            from_email: contact_packet.admin_email,
            subject: contact_packet.assessment_title + ' assessment returned for review!',
            html: "Hello " + contact_packet.editor_firstName + ",
" +
            "" + contact_packet.admin_name + " just returned the " + contact_packet.assessment_title + " assessement to you. " +
            "There are a few errors we'd like you to address before moving the assessment on.
" +
            "Please go to your assessment dashboard to take a look at flagged answers in the assessment.
" +
            "Thanks!
" +
            "The RGI Team."
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

// email when reassigning to researcher or reviewer
exports.assessment_reassignment = function (contact_packet) {
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.editor_email, name: contact_packet.editor_fullName}],
            from_email: contact_packet.admin_email,
            subject: "Please begin work on the " + contact_packet.assessment_title + " assessment!",
            html: "Hello " + contact_packet.editor_firstName + ",
" +
            "" + contact_packet.admin_name + " just returned the " + contact_packet.assessment_title + " assessement to your control.
" +
            "Please go to your assessment dashboard.
" +
            "Thanks!
" +
            "The RGI Team."
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

// email when reassigning to researcher or reviewer
exports.trial_assessment_continue = function (contact_packet) {
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.editor_email, name: contact_packet.editor_fullName}],
            from_email: contact_packet.admin_email,
            subject: "Please continue work on the " + contact_packet.assessment_title + " assessment!",
            html: "Hello " + contact_packet.editor_firstName + ",
" +
            "" + contact_packet.admin_name + " just approved your initial answers on the " + contact_packet.assessment_title + " assessement.
" +
            "Please go to your assessment dashboard to continue.
" +
            "Thanks!
" +
            "The RGI Team."
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

//// email when
//exports. = function (contact_packet) {
//    mandrill('/messages/send', {
//        message: {
//            to: [{email: , name: }],
//            from_email: [{email: , name: }],
//            subject: ,
//            html: ""
//        }
//    }, function (err, res) {
//        if (err) console.log( JSON.stringify(err) );
//        else console.log(res);
//    });
//};
<commit_msg>fixed dead links form old email model closes #143<commit_after>'use strict';

var config = require('../config/config')[process.env.NODE_ENV = process.env.NODE_ENV || 'development'],
    siteEmail = 'tech-support@resourcegovernance.org';

var mandrill = require('node-mandrill')(process.env.MANDRILL_APIKEY);
// send email to tech support
exports.techSend = function (req, res) {
    var issue_os, issue_browser, issue_browser_ver,
        message_content = req.body,
        issue_tool = message_content.tool.toUpperCase(),
        issue_full_name = message_content.first_name + " " + message_content.last_name;
        //issue_first_name = message_content.first_name,
        //issue_last_name = message_content.last_name,
    if (message_content.os) {
        issue_os = message_content.os;
    } else {
        if(message_content.os_text) {
            issue_os = message_content.os_text;
        } else {
            issue_os = 'None supplied';
        }
    }
    if (message_content.browser) {
        issue_browser = message_content.browser;
    } else {
        if(message_content.browser_text) {
            issue_browser = message_content.browser_text;
        } else {
            issue_browser = 'None supplied';
        }
    }
    if (message_content.browser_ver) {
        issue_browser_ver = message_content.browser_ver;
    } else {
        issue_browser_ver = 'None supplied';
    }
    //send an e-mail to technical support
    mandrill('/messages/send', {
        message: {
            to: [{email: 'tech-support@resourcegovernance.org', name: 'Assessment tool tech support'}],
            from_email: message_content.email,
            subject: issue_tool + ' Issue: ' + message_content.issue.value,
            html: "Hi,
" +
            issue_full_name + " is having an issue with the " + issue_tool + " tool. Please find more info below.
" +
            "

Issue: " + message_content.issue.name + "
<
Issue description: " + message_content.issue_description + "
" +
            "
OS: " + issue_os + "

Browser: " + issue_browser + "

Browser version: " + issue_browser_ver + "

"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });

    //send a confirmation e-mail to user
    mandrill('/messages/send', {
        message: {
            to: [{email: message_content.email, name: issue_full_name}],
            from_email: 'tech-support@resourcegovernance.org',
            subject: 'Confirmation of ' + message_content.issue.value + ' support ticket',
            html: "Hi " + issue_full_name + "\,
" +
            "Thanks for contacting us about an issue with the " + issue_tool + "tool. I'm sorry for the inconvenience\, we will contact you shortly. " +
            "In the meantime please look at the info you supplied below and let us know if any of it is incorrect.
" +
            "

Issue: " + message_content.issue.name + "
<
Issue description: " + message_content.issue_description + "
" +
            "
OS: " + issue_os + "

Browser: " + issue_browser + "

Browser version: " + issue_browser_ver + "

"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
    res.send();
};

/////////////////////////////////
///////USER RECORD EMAILS////////
/////////////////////////////////

// send email to new user
exports.new_user_confirmation = function (contact_packet, token) {
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.rec_email, name: contact_packet.rec_name}],
            from_email: contact_packet.send_email,
            subject: contact_packet.rec_role + ' account created!',
            html: 'Hello ' + contact_packet.rec_name + ',
' +
            'an RGI ' + contact_packet.rec_role + 'account was just set up for you by ' + contact_packet.send_name + '.
' +
            'The user name is ' + contact_packet.rec_username + '.' +
            'Please, set password before login.
' +
            'Thanks!
' +
            'The RGI Team.'
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

exports.reset_password_confirmation = function (user, token) {
    var fullName = user.firstName.charAt(0).toUpperCase() +
        user.firstName.slice(1) + " " +
        user.lastName.charAt(0).toUpperCase() +
        user.lastName.slice(1);
    mandrill('/messages/send', {
        message: {
            to: [{email: user.email, name: fullName}],
            from_email: siteEmail,
            subject: 'Password Recovery',
            html: 'Hello ' + fullName + ',
' +
            'Please, click here to recover your password.
' +
            'Thanks!
' +
            'The RGI Team.'
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};
//TODO delete user confirmation
exports.delete_user_confirmation = function (contact_packet) {

};

////////////////////////////////////////
///////ASSESSMENT RECORD EMAILS////////
////////////////////////////////////////

// email when assessment is assigned
exports.new_assessment_assignment = function (contact_packet, type) {
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet[type + '_email'], name: contact_packet[type + '_fullName']}],
            from_email: 'rgi-admin@resourcegovernance.org',
            subject: contact_packet.assessment_title + ' assessment assigned!',
            html: "Hello " + contact_packet[type + '_firstName'] + ",
" +
            "" + contact_packet.admin_name + " just assigned the " + contact_packet.assessment_title + " assessement to you.
" +
            "Please visit your assessment dashboard to start the assessment.
" +
            "Thanks!
" +
            "The RGI Team."
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

// email when assessment is submitted or resubmitted
exports.trial_assessment_submission = function (contact_packet) {
    //send an email to team that assessment is ready
    mandrill('/messages/send', {
        message: {
            to: [
                {email: 'RGI-admin@resourcegovernance.org', name: 'RGI Team'},
                {email: 'ahasemann@resourcegovernance.org', name: 'Anna Hasemann'},
                {email: 'cperry@resourcegovernance.org', name: 'Chris Perry'},
                {email: 'jcust@resourcegovernance.org', name: 'Jim Cust'}
            ],
            from_email: contact_packet.editor_email,
            subject: contact_packet.assessment_title + ' submitted by ' + contact_packet.editor_role + " " + contact_packet.editor_fullName,
            html: "Hi team,
" +
            contact_packet.editor_fullName + " just submitted the " + contact_packet.assessment_title + " trial assessment for review." +
            "Please visit your assessment dashboard to review.
" +
            "Thanks!
" +
            "The RGI Team.
"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
    //send email to submitter that it went through
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.editor_email, name: contact_packet.editor_fullName}],
            from_email: "rgi-admin@resourcegovernance.org",
            subject: contact_packet.assessment_title + " recieved.",
            html: "Hi "+ contact_packet.editor_fullName + ",
" +
            "Your submission of the " + contact_packet.assessment_title + " trial assessment was sent to the admin team. We will be in contact shortly with next steps." +
            "Please visit your assessment dashboard if you want to check the status.
" +
            "Thanks!
" +
            "The RGI Team.
"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

// email when assessment is submitted or resubmitted
exports.assessment_submission = function (contact_packet) {
    //send an email to team that assessment is ready
    mandrill('/messages/send', {
        message: {
            to: [
                {email: 'RGI-admin@resourcegovernance.org', name: 'RGI Team'},
                {email: 'ahasemann@resourcegovernance.org', name: 'Anna Hasemann'},
                {email: 'cperry@resourcegovernance.org', name: 'Chris Perry'},
                {email: 'jcust@resourcegovernance.org', name: 'Jim Cust'}
            ],
            from_email: contact_packet.editor_email,
            subject: contact_packet.assessment_title + ' submitted by ' + contact_packet.editor_role + " " + contact_packet.editor_fullName,
            html: "Hi team,
" +
            contact_packet.editor_fullName + " just submitted the " + contact_packet.assessment_title + " assessment for review." +
            "Please visit your assessment dashboard to review.
" +
            "Thanks!
" +
            "The RGI Team.
"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
    //send email to submitter that it went through
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.editor_email, name: contact_packet.editor_fullName}],
            from_email: "rgi-admin@resourcegovernance.org",
            subject: contact_packet.assessment_title + " recieved.",
            html: "Hi "+ contact_packet.editor_fullName + ",
" +
            "Your submission of the " + contact_packet.assessment_title + " assessment was sent to the admin team. We will be in contact shortly with next steps." +
            "Please visit your assessment dashboard if you want to check the status.
" +
            "Thanks!
" +
            "The RGI Team.
"
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

// email when flags need to be reviewed by researcher or reviewer
exports.flag_review = function (contact_packet) {
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.editor_email, name: contact_packet.editor_fullName}],
            from_email: contact_packet.admin_email,
            subject: contact_packet.assessment_title + ' assessment returned for review!',
            html: "Hello " + contact_packet.editor_firstName + ",
" +
            "" + contact_packet.admin_name + " just returned the " + contact_packet.assessment_title + " assessement to you. " +
            "There are a few errors we'd like you to address before moving the assessment on.
" +
            "Please go to your assessment dashboard to take a look at flagged answers in the assessment.
" +
            "Thanks!
" +
            "The RGI Team."
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

// email when reassigning to researcher or reviewer
exports.assessment_reassignment = function (contact_packet) {
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.editor_email, name: contact_packet.editor_fullName}],
            from_email: contact_packet.admin_email,
            subject: "Please begin work on the " + contact_packet.assessment_title + " assessment!",
            html: "Hello " + contact_packet.editor_firstName + ",
" +
            "" + contact_packet.admin_name + " just returned the " + contact_packet.assessment_title + " assessement to your control.
" +
            "Please go to your assessment dashboard.
" +
            "Thanks!
" +
            "The RGI Team."
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

// email when reassigning to researcher or reviewer
exports.trial_assessment_continue = function (contact_packet) {
    mandrill('/messages/send', {
        message: {
            to: [{email: contact_packet.editor_email, name: contact_packet.editor_fullName}],
            from_email: contact_packet.admin_email,
            subject: "Please continue work on the " + contact_packet.assessment_title + " assessment!",
            html: "Hello " + contact_packet.editor_firstName + ",
" +
            "" + contact_packet.admin_name + " just approved your initial answers on the " + contact_packet.assessment_title + " assessement.
" +
            "Please go to your assessment dashboard to continue.
" +
            "Thanks!
" +
            "The RGI Team."
        }
    }, function (err, res) {
        if (err) { console.log( JSON.stringify(err) ); }
        else { console.log(res); }
    });
};

//// email when
//exports. = function (contact_packet) {
//    mandrill('/messages/send', {
//        message: {
//            to: [{email: , name: }],
//            from_email: [{email: , name: }],
//            subject: ,
//            html: ""
//        }
//    }, function (err, res) {
//        if (err) console.log( JSON.stringify(err) );
//        else console.log(res);
//    });
//};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { withStyles, lighten, darken } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import SuccessOutlinedIcon from '../internal/svg-icons/SuccessOutlined';
import ReportProblemOutlinedIcon from '../internal/svg-icons/ReportProblemOutlined';
import ErrorOutlineIcon from '../internal/svg-icons/ErrorOutline';
import InfoOutlinedIcon from '../internal/svg-icons/InfoOutlined';
import CloseIcon from '../internal/svg-icons/Close';
import IconButton from '@material-ui/core/IconButton';
import { capitalize } from '@material-ui/core/utils';

export const styles = theme => ({
  /* Styles applied to the root element. */
  root: {
    ...theme.typography.body2,
    borderRadius: theme.shape.borderRadius,
    backgroundColor: 'transparent',
    display: 'flex',
    padding: '6px 16px',
  },
  /* Styles applied to the root element if `variant="standard"` and `color="success"`. */
  standardSuccess: {
    color: darken(theme.palette.success.main, 0.6),
    backgroundColor: lighten(theme.palette.success.main, 0.9),
    '& $icon': {
      color: theme.palette.success.main,
    },
  },
  /* Styles applied to the root element if `variant="standard"` and `color="info"`. */
  standardInfo: {
    color: darken(theme.palette.info.main, 0.6),
    backgroundColor: lighten(theme.palette.info.main, 0.9),
    '& $icon': {
      color: theme.palette.info.main,
    },
  },
  /* Styles applied to the root element if `variant="standard"` and `color="warning"`. */
  standardWarning: {
    color: darken(theme.palette.warning.main, 0.6),
    backgroundColor: lighten(theme.palette.warning.main, 0.9),
    '& $icon': {
      color: theme.palette.warning.main,
    },
  },
  /* Styles applied to the root element if `variant="standard"` and `color="error"`. */
  standardError: {
    color: darken(theme.palette.error.main, 0.6),
    backgroundColor: lighten(theme.palette.error.main, 0.9),
    '& $icon': {
      color: theme.palette.error.main,
    },
  },
  /* Styles applied to the root element if `variant="outlined"` and `color="success"`. */
  outlinedSuccess: {
    color:
      theme.palette.type === 'light'
        ? darken(theme.palette.success.main, 0.6)
        : lighten(theme.palette.success.main, 0.6),
    border: `1px solid ${theme.palette.success.main}`,
    '& $icon': {
      color: theme.palette.success.main,
    },
  },
  /* Styles applied to the root element if `variant="outlined"` and `color="info"`. */
  outlinedInfo: {
    color:
      theme.palette.type === 'light'
        ? darken(theme.palette.info.main, 0.6)
        : lighten(theme.palette.info.main, 0.6),
    border: `1px solid ${theme.palette.info.main}`,
    '& $icon': {
      color: theme.palette.info.main,
    },
  },
  /* Styles applied to the root element if `variant="outlined"` and `color="warning"`. */
  outlinedWarning: {
    color:
      theme.palette.type === 'light'
        ? darken(theme.palette.warning.main, 0.6)
        : lighten(theme.palette.warning.main, 0.6),
    border: `1px solid ${theme.palette.warning.main}`,
    '& $icon': {
      color: theme.palette.warning.main,
    },
  },
  /* Styles applied to the root element if `variant="outlined"` and `color="error"`. */
  outlinedError: {
    color:
      theme.palette.type === 'light'
        ? darken(theme.palette.error.main, 0.6)
        : lighten(theme.palette.error.main, 0.6),
    border: `1px solid ${theme.palette.error.main}`,
    '& $icon': {
      color: theme.palette.error.main,
    },
  },
  /* Styles applied to the root element if `variant="filled"` and `color="success"`. */
  filledSuccess: {
    color: '#fff',
    fontWeight: theme.typography.fontWeightMedium,
    backgroundColor: theme.palette.success.main,
  },
  /* Styles applied to the root element if `variant="filled"` and `color="info"`. */
  filledInfo: {
    color: '#fff',
    fontWeight: theme.typography.fontWeightMedium,
    backgroundColor: theme.palette.info.main,
  },
  /* Styles applied to the root element if `variant="filled"` and `color="warning"`. */
  filledWarning: {
    color: '#fff',
    fontWeight: theme.typography.fontWeightMedium,
    backgroundColor: theme.palette.warning.main,
  },
  /* Styles applied to the root element if `variant="filled"` and `color="error"`. */
  filledError: {
    color: '#fff',
    fontWeight: theme.typography.fontWeightMedium,
    backgroundColor: theme.palette.error.main,
  },
  /* Styles applied to the icon wrapper element. */
  icon: {
    marginRight: 12,
    padding: '7px 0',
    display: 'flex',
    fontSize: 22,
    opacity: 0.9,
  },
  /* Styles applied to the message wrapper element. */
  message: {
    padding: '8px 0',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
  },
  /* Styles applied to the action wrapper element if `action` is provided. */
  action: {
    display: 'flex',
    alignItems: 'center',
    marginLeft: 'auto',
    paddingLeft: 16,
    marginRight: -8,
  },
});

const defaultIconMapping = {
  success: <SuccessOutlinedIcon fontSize="inherit" />,
  warning: <ReportProblemOutlinedIcon fontSize="inherit" />,
  error: <ErrorOutlineIcon fontSize="inherit" />,
  info: <InfoOutlinedIcon fontSize="inherit" />,
};

const Alert = React.forwardRef(function Alert(props, ref) {
  const {
    action,
    children,
    classes,
    className,
    closeText = 'Close',
    color,
    icon,
    iconMapping = defaultIconMapping,
    onClose,
    role = 'alert',
    severity = 'success',
    variant = 'standard',
    ...other
  } = props;

  return (
    <Paper
      role={role}
      square
      elevation={0}
      className={clsx(
        classes.root,
        classes[`${variant}${capitalize(color || severity)}`],
        className,
      )}
      ref={ref}
      {...other}
    >
      {icon !== false ? (

          {icon || iconMapping[severity] || defaultIconMapping[severity]}

      ) : null}

{children}

      {action != null ?
{action}
 : null}
      {action == null && onClose ? (

          <IconButton
            size="small"
            aria-label={closeText}
            title={closeText}
            color="inherit"
            onClick={onClose}
          >
            <CloseIcon fontSize="small" />
          </IconButton>

      ) : null}
    </Paper>
  );
});

Alert.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The action to display. It renders after the message, at the end of the alert.
   */
  action: PropTypes.node,
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Override the default label for the *close popup* icon button.
   *
   * For localization purposes, you can use the provided [translations](/guides/localization/).
   */
  closeText: PropTypes.string,
  /**
   * The main color for the alert. Unless provided, the value is taken from the `severity` prop.
   */
  color: PropTypes.oneOf(['error', 'info', 'success', 'warning']),
  /**
   * Override the icon displayed before the children.
   * Unless provided, the icon is mapped to the value of the `severity` prop.
   */
  icon: PropTypes.node,
  /**
   * The component maps the `severity` prop to a range of different icons,
   * for instance success to `<SuccessOutlined>`.
   * If you wish to change this mapping, you can provide your own.
   * Alternatively, you can use the `icon` prop to override the icon displayed.
   */
  iconMapping: PropTypes.shape({
    error: PropTypes.node,
    info: PropTypes.node,
    success: PropTypes.node,
    warning: PropTypes.node,
  }),
  /**
   * Callback fired when the component requests to be closed.
   * When provided and no `action` prop is set, a close icon button is displayed that triggers the callback when clicked.
   *
   * @param {object} event The event source of the callback.
   */
  onClose: PropTypes.func,
  /**
   * The ARIA role attribute of the element.
   */
  role: PropTypes.string,
  /**
   * The severity of the alert. This defines the color and icon used.
   */
  severity: PropTypes.oneOf(['error', 'info', 'success', 'warning']),
  /**
   * The variant to use.
   */
  variant: PropTypes.oneOf(['filled', 'outlined', 'standard']),
};

export default withStyles(styles, { name: 'MuiAlert' })(Alert);
<commit_msg>[Alert] Improve dark theme coloring (#19105)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { withStyles, lighten, darken } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import SuccessOutlinedIcon from '../internal/svg-icons/SuccessOutlined';
import ReportProblemOutlinedIcon from '../internal/svg-icons/ReportProblemOutlined';
import ErrorOutlineIcon from '../internal/svg-icons/ErrorOutline';
import InfoOutlinedIcon from '../internal/svg-icons/InfoOutlined';
import CloseIcon from '../internal/svg-icons/Close';
import IconButton from '@material-ui/core/IconButton';
import { capitalize } from '@material-ui/core/utils';

export const styles = theme => {
  const getColor = theme.palette.type === 'light' ? darken : lighten;
  const getBackgroundColor = theme.palette.type === 'light' ? lighten : darken;

  return {
    /* Styles applied to the root element. */
    root: {
      ...theme.typography.body2,
      borderRadius: theme.shape.borderRadius,
      backgroundColor: 'transparent',
      display: 'flex',
      padding: '6px 16px',
    },
    /* Styles applied to the root element if `variant="standard"` and `color="success"`. */
    standardSuccess: {
      color: getColor(theme.palette.success.main, 0.6),
      backgroundColor: getBackgroundColor(theme.palette.success.main, 0.9),
      '& $icon': {
        color: theme.palette.success.main,
      },
    },
    /* Styles applied to the root element if `variant="standard"` and `color="info"`. */
    standardInfo: {
      color: getColor(theme.palette.info.main, 0.6),
      backgroundColor: getBackgroundColor(theme.palette.info.main, 0.9),
      '& $icon': {
        color: theme.palette.info.main,
      },
    },
    /* Styles applied to the root element if `variant="standard"` and `color="warning"`. */
    standardWarning: {
      color: getColor(theme.palette.warning.main, 0.6),
      backgroundColor: getBackgroundColor(theme.palette.warning.main, 0.9),
      '& $icon': {
        color: theme.palette.warning.main,
      },
    },
    /* Styles applied to the root element if `variant="standard"` and `color="error"`. */
    standardError: {
      color: getColor(theme.palette.error.main, 0.6),
      backgroundColor: getBackgroundColor(theme.palette.error.main, 0.9),
      '& $icon': {
        color: theme.palette.error.main,
      },
    },
    /* Styles applied to the root element if `variant="outlined"` and `color="success"`. */
    outlinedSuccess: {
      color: getColor(theme.palette.success.main, 0.6),
      border: `1px solid ${theme.palette.success.main}`,
      '& $icon': {
        color: theme.palette.success.main,
      },
    },
    /* Styles applied to the root element if `variant="outlined"` and `color="info"`. */
    outlinedInfo: {
      color: getColor(theme.palette.info.main, 0.6),
      border: `1px solid ${theme.palette.info.main}`,
      '& $icon': {
        color: theme.palette.info.main,
      },
    },
    /* Styles applied to the root element if `variant="outlined"` and `color="warning"`. */
    outlinedWarning: {
      color: getColor(theme.palette.warning.main, 0.6),
      border: `1px solid ${theme.palette.warning.main}`,
      '& $icon': {
        color: theme.palette.warning.main,
      },
    },
    /* Styles applied to the root element if `variant="outlined"` and `color="error"`. */
    outlinedError: {
      color: getColor(theme.palette.error.main, 0.6),
      border: `1px solid ${theme.palette.error.main}`,
      '& $icon': {
        color: theme.palette.error.main,
      },
    },
    /* Styles applied to the root element if `variant="filled"` and `color="success"`. */
    filledSuccess: {
      color: '#fff',
      fontWeight: theme.typography.fontWeightMedium,
      backgroundColor: theme.palette.success.main,
    },
    /* Styles applied to the root element if `variant="filled"` and `color="info"`. */
    filledInfo: {
      color: '#fff',
      fontWeight: theme.typography.fontWeightMedium,
      backgroundColor: theme.palette.info.main,
    },
    /* Styles applied to the root element if `variant="filled"` and `color="warning"`. */
    filledWarning: {
      color: '#fff',
      fontWeight: theme.typography.fontWeightMedium,
      backgroundColor: theme.palette.warning.main,
    },
    /* Styles applied to the root element if `variant="filled"` and `color="error"`. */
    filledError: {
      color: '#fff',
      fontWeight: theme.typography.fontWeightMedium,
      backgroundColor: theme.palette.error.main,
    },
    /* Styles applied to the icon wrapper element. */
    icon: {
      marginRight: 12,
      padding: '7px 0',
      display: 'flex',
      fontSize: 22,
      opacity: 0.9,
    },
    /* Styles applied to the message wrapper element. */
    message: {
      padding: '8px 0',
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
    },
    /* Styles applied to the action wrapper element if `action` is provided. */
    action: {
      display: 'flex',
      alignItems: 'center',
      marginLeft: 'auto',
      paddingLeft: 16,
      marginRight: -8,
    },
  };
};

const defaultIconMapping = {
  success: <SuccessOutlinedIcon fontSize="inherit" />,
  warning: <ReportProblemOutlinedIcon fontSize="inherit" />,
  error: <ErrorOutlineIcon fontSize="inherit" />,
  info: <InfoOutlinedIcon fontSize="inherit" />,
};

const Alert = React.forwardRef(function Alert(props, ref) {
  const {
    action,
    children,
    classes,
    className,
    closeText = 'Close',
    color,
    icon,
    iconMapping = defaultIconMapping,
    onClose,
    role = 'alert',
    severity = 'success',
    variant = 'standard',
    ...other
  } = props;

  return (
    <Paper
      role={role}
      square
      elevation={0}
      className={clsx(
        classes.root,
        classes[`${variant}${capitalize(color || severity)}`],
        className,
      )}
      ref={ref}
      {...other}
    >
      {icon !== false ? (

          {icon || iconMapping[severity] || defaultIconMapping[severity]}

      ) : null}

{children}

      {action != null ?
{action}
 : null}
      {action == null && onClose ? (

          <IconButton
            size="small"
            aria-label={closeText}
            title={closeText}
            color="inherit"
            onClick={onClose}
          >
            <CloseIcon fontSize="small" />
          </IconButton>

      ) : null}
    </Paper>
  );
});

Alert.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The action to display. It renders after the message, at the end of the alert.
   */
  action: PropTypes.node,
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * Override the default label for the *close popup* icon button.
   *
   * For localization purposes, you can use the provided [translations](/guides/localization/).
   */
  closeText: PropTypes.string,
  /**
   * The main color for the alert. Unless provided, the value is taken from the `severity` prop.
   */
  color: PropTypes.oneOf(['error', 'info', 'success', 'warning']),
  /**
   * Override the icon displayed before the children.
   * Unless provided, the icon is mapped to the value of the `severity` prop.
   */
  icon: PropTypes.node,
  /**
   * The component maps the `severity` prop to a range of different icons,
   * for instance success to `<SuccessOutlined>`.
   * If you wish to change this mapping, you can provide your own.
   * Alternatively, you can use the `icon` prop to override the icon displayed.
   */
  iconMapping: PropTypes.shape({
    error: PropTypes.node,
    info: PropTypes.node,
    success: PropTypes.node,
    warning: PropTypes.node,
  }),
  /**
   * Callback fired when the component requests to be closed.
   * When provided and no `action` prop is set, a close icon button is displayed that triggers the callback when clicked.
   *
   * @param {object} event The event source of the callback.
   */
  onClose: PropTypes.func,
  /**
   * The ARIA role attribute of the element.
   */
  role: PropTypes.string,
  /**
   * The severity of the alert. This defines the color and icon used.
   */
  severity: PropTypes.oneOf(['error', 'info', 'success', 'warning']),
  /**
   * The variant to use.
   */
  variant: PropTypes.oneOf(['filled', 'outlined', 'standard']),
};

export default withStyles(styles, { name: 'MuiAlert' })(Alert);
<|endoftext|>