<commit_before>(function($) {
	$.fn.cachesize = function(options) {
		var containers = [];
		var supportsCanvas = (function() {
			var elem = document.createElement('canvas');
			return !!(elem.getContext && elem.getContext('2d'));
		})();

		var settings = {
			getSize: function() {
				return {
					width: $(window).width(),
					height: $(window).height()
				};
			},
			updateCallback: function() {},
			msInterpolationMode: 'nearest-neighbor'
		};

		$.extend(settings, options);

		var calculateRect = function(image, size) {
			var aspectRatio = image.width / image.height;
			var lockVert = (size.width / aspectRatio) >= size.height;

			var rect = {};
			rect.width = lockVert ? size.width : size.height * aspectRatio;
			rect.height = lockVert ? size.width / aspectRatio : size.height;
			rect.left = lockVert ? 0 : Math.round((size.width - rect.width) / 2);
			rect.top = lockVert ? Math.round((size.height - rect.height) / 2) : 0;

			return rect;
		}

		var updateCanvas = function(canvas, original) {
			var size = settings.getSize();
			var rect = calculateRect(original, size);
			canvas.width = size.width;
			canvas.height = size.height;

			var context = canvas.getContext('2d');
			context.drawImage(original, rect.left, rect.top, Math.ceil(rect.width), Math.ceil(rect.height));

			settings.updateCallback(size, rect);
		}

		var updateImage = function(container) {
			var image = container.data('image');
			var size = settings.getSize();
			var rect = calculateRect(image.get(0), size);

			image.css(rect);
			container.css({width: size.width, height: size.height});

			settings.updateCallback(size, rect);
		}

		$(window).resize(function() {
			for (var i in containers) {
				var container = $(containers[i]);

				if (supportsCanvas) {
					var original = container.data('original');

					if (original) {
						var canvas = container.data('canvas');
						updateCanvas(canvas, original);
					}
				} else {
					var image = container.data('image');
					updateImage(container);
				}
			}
		});

		$(this).each(function() {
			var image = $(this);
			var container = $('<div />');

			if (supportsCanvas) {
				var canvas = $('<canvas />').appendTo(container).get(0);
				var original = new Image();

				container.data('canvas', canvas);

				original.onload = function() {
					container.data('original', original);
					updateCanvas(canvas, original);
				}

				original.src = image.attr('src');

				image.replaceWith(container);
			} else {
				image.css('position', 'absolute');

				container.css('overflow', 'hidden');
				container.data('image', image);
				container.insertAfter(image);
				container.append(image);

				updateImage(container);
			}

			containers.push(container.get(0));
		});

		return $(containers);
	};
})(jQuery);<commit_msg>Change tabs to spaces<commit_after>(function($) {
    $.fn.cachesize = function(options) {
        var containers = [];
        var supportsCanvas = (function() {
            var elem = document.createElement('canvas');
            return !!(elem.getContext && elem.getContext('2d'));
        })();

        var settings = {
            getSize: function() {
                return {
                    width: $(window).width(),
                    height: $(window).height()
                };
            },
            updateCallback: function() {},
            msInterpolationMode: 'nearest-neighbor'
        };

        $.extend(settings, options);

        var calculateRect = function(image, size) {
            var aspectRatio = image.width / image.height;
            var lockVert = (size.width / aspectRatio) >= size.height;

            var rect = {};
            rect.width = lockVert ? size.width : size.height * aspectRatio;
            rect.height = lockVert ? size.width / aspectRatio : size.height;
            rect.left = lockVert ? 0 : Math.round((size.width - rect.width) / 2);
            rect.top = lockVert ? Math.round((size.height - rect.height) / 2) : 0;

            return rect;
        }

        var updateCanvas = function(canvas, original) {
            var size = settings.getSize();
            var rect = calculateRect(original, size);
            canvas.width = size.width;
            canvas.height = size.height;

            var context = canvas.getContext('2d');
            context.drawImage(original, rect.left, rect.top, Math.ceil(rect.width), Math.ceil(rect.height));

            settings.updateCallback(size, rect);
        }

        var updateImage = function(container) {
            var image = container.data('image');
            var size = settings.getSize();
            var rect = calculateRect(image.get(0), size);

            image.css(rect);
            container.css({width: size.width, height: size.height});

            settings.updateCallback(size, rect);
        }

        $(window).resize(function() {
            for (var i in containers) {
                var container = $(containers[i]);

                if (supportsCanvas) {
                    var original = container.data('original');

                    if (original) {
                        var canvas = container.data('canvas');
                        updateCanvas(canvas, original);
                    }
                } else {
                    var image = container.data('image');
                    updateImage(container);
                }
            }
        });

        $(this).each(function() {
            var image = $(this);
            var container = $('<div />');

            if (supportsCanvas) {
                var canvas = $('<canvas />').appendTo(container).get(0);
                var original = new Image();

                container.data('canvas', canvas);

                original.onload = function() {
                    container.data('original', original);
                    updateCanvas(canvas, original);
                }

                original.src = image.attr('src');

                image.replaceWith(container);
            } else {
                image.css('position', 'absolute');

                container.css('overflow', 'hidden');
                container.data('image', image);
                container.insertAfter(image);
                container.append(image);

                updateImage(container);
            }

            containers.push(container.get(0));
        });

        return $(containers);
    };
})(jQuery);<|endoftext|>


<commit_before>function plugin(UIkit) {

    if (plugin.installed) {
        return;
    }

    var { util, mixin } = UIkit;
    var {$, doc, toJQuery} = util;

    UIkit.component('countdown', {

        attrs: true,

        mixins: [mixin.class],

        props: {
            endtime: String
        },

        defaults: {
            endtime: ''
        },

        connected() {

            if (!this.$el.html().trim()) {
                this.$el.html(`00:00:00:00`);
            }

            this.days = this.$el.find('.uk-countdown-days');
            this.hours = this.$el.find('.uk-countdown-hours');
            this.minutes = this.$el.find('.uk-countdown-minutes');
            this.seconds = this.$el.find('.uk-countdown-seconds');

            this.update();
            this.start();
        },

        disconnected() {
            this.stop();
            this.$el.html('');
        },

        methods: {

            start() {

                this.stop();

                if (!this.endtime) {
                    return;
                }

                this.timer = setInterval(() => this.update(), 100);
            },

            stop() {

                if (this.timer) {
                    clearInterval(this.timer);
                }
            },

            update(){

                var t = this.getDifference();

                if (t.total <= 0){
                    t.total = t.days = t.hours = t.minutes = t.seconds = 0;
                }

                ['days','hours','minutes','seconds'].forEach(item => {

                    if (Number(this[item].text()) !== Number(t[item])) {
                        this[item].text(('00'+t[item]).slice(-2));
                    }
                });

                if (t.total <= 0){
                    this.stop();
                }
            },

            getDifference() {

                  var total = Date.parse(this.endtime) - Date.parse(new Date());
                  var seconds = Math.floor((total/1000) % 60);
                  var minutes = Math.floor((total/1000/60) % 60);
                  var hours = Math.floor((total/(1000*60*60)) % 24);
                  var days = Math.floor(total/(1000*60*60*24));

                  return {total, days, hours,  minutes, seconds};
            }
        }

    });

}

if (!BUNDLED && typeof window !== 'undefined' && window.UIkit) {
    window.UIkit.use(plugin);
}

export default plugin;
<commit_msg>wrap countdown digits in spans<commit_after>function plugin(UIkit) {

    if (plugin.installed) {
        return;
    }

    var { util, mixin } = UIkit;
    var {$, doc, toJQuery} = util;

    UIkit.component('countdown', {

        attrs: true,

        mixins: [mixin.class],

        props: {
            endtime: String
        },

        defaults: {
            endtime: ''
        },

        connected() {

            if (!this.$el.html().trim()) {
                this.$el.html(`00:00:00:00`);
            }

            this.days = this.$el.find('.uk-countdown-days');
            this.hours = this.$el.find('.uk-countdown-hours');
            this.minutes = this.$el.find('.uk-countdown-minutes');
            this.seconds = this.$el.find('.uk-countdown-seconds');

            this.update();
            this.start();
        },

        disconnected() {
            this.stop();
            this.$el.html('');
        },

        methods: {

            start() {

                this.stop();

                if (!this.endtime) {
                    return;
                }

                this.timer = setInterval(() => this.update(), 100);
            },

            stop() {

                if (this.timer) {
                    clearInterval(this.timer);
                }
            },

            update(){

                var t = this.getDifference();

                if (t.total <= 0){
                    t.total = t.days = t.hours = t.minutes = t.seconds = 0;
                }

                ['days','hours','minutes','seconds'].forEach(item => {

                    if (Number(this[item].text()) !== Number(t[item])) {
                        this[item].html(('00'+t[item]).slice(-2).split('').map(n => `<span>${n}</span>`).join(''));
                    }
                });

                if (t.total <= 0){
                    this.stop();
                }
            },

            getDifference() {

                  var total = Date.parse(this.endtime) - Date.parse(new Date());
                  var seconds = Math.floor((total/1000) % 60);
                  var minutes = Math.floor((total/1000/60) % 60);
                  var hours = Math.floor((total/(1000*60*60)) % 24);
                  var days = Math.floor(total/(1000*60*60*24));

                  return {total, days, hours,  minutes, seconds};
            }
        }

    });

}

if (!BUNDLED && typeof window !== 'undefined' && window.UIkit) {
    window.UIkit.use(plugin);
}

export default plugin;
<|endoftext|>


<commit_before>const path = require('path');
const upath = require('upath');
const minimatch = require('minimatch');

const { migrateAndValidate } = require('../config/migrate-validate');
const presets = require('../config/presets');

const manager = require('./index');
const dockerResolve = require('../manager/docker/resolve');
const nodeResolve = require('../manager/node/resolve');
const bazelResolve = require('../manager/bazel/resolve');
const { mergeChildConfig } = require('../config');
const { checkMonorepos } = require('../manager/npm/monorepos');

module.exports = {
  resolvePackageFiles,
};

async function resolvePackageFiles(config) {
  logger.trace({ config }, 'resolvePackageFiles()');
  const allPackageFiles = config.packageFiles.length
    ? config.packageFiles
    : await manager.detectPackageFiles(config);
  logger.debug({ allPackageFiles }, 'allPackageFiles');
  const fileList = await platform.getFileList();
  async function resolvePackageFile(p) {
    const packageFile = typeof p === 'string' ? { packageFile: p } : p;
    Object.assign(packageFile, config.npm);
    if (packageFile.packageFile.endsWith('package.json')) {
      logger.debug(`Resolving packageFile ${JSON.stringify(packageFile)}`);
      const pFileRaw = await platform.getFile(packageFile.packageFile);
      if (!pFileRaw) {
        logger.info(
          { packageFile: packageFile.packageFile },
          'Cannot find package.json'
        );
        config.errors.push({
          depName: packageFile.packageFile,
          message: 'Cannot find package.json',
        });
        return null;
      }
      try {
        packageFile.content = JSON.parse(pFileRaw);
      } catch (err) {
        logger.info(
          { packageFile: packageFile.packageFile },
          'Cannot parse package.json'
        );
        if (config.repoIsOnboarded) {
          const error = new Error('config-validation');
          error.configFile = packageFile.packageFile;
          error.validationError = 'Cannot parse package.json';
          error.validationMessage =
            'This package.json contains invalid JSON and cannot be parsed. Please fix it, or add it to your "ignorePaths" array in your renovate config so that Renovate can continue.';
          throw error;
        }
        config.errors.push({
          depName: packageFile.packageFile,
          message:
            "Cannot parse package.json (invalid JSON). Please fix the contents or add the file/path to the `ignorePaths` array in Renovate's config",
        });
        return null;
      }
      if (!config.ignoreNpmrcFile) {
        packageFile.npmrc = await platform.getFile(
          upath.join(path.dirname(packageFile.packageFile), '.npmrc')
        );
      }
      if (packageFile.npmrc) {
        logger.info('Found .npmrc');
      } else {
        delete packageFile.npmrc;
      }
      packageFile.yarnrc = await platform.getFile(
        upath.join(path.dirname(packageFile.packageFile), '.yarnrc')
      );
      if (packageFile.yarnrc) {
        logger.info('Found .yarnrc');
      } else {
        delete packageFile.yarnrc;
      }
      // hoist renovate config if exists
      if (packageFile.content.renovate) {
        logger.debug(
          {
            packageFile: packageFile.packageFile,
            config: packageFile.content.renovate,
          },
          `Found package.json renovate config`
        );
        const migratedConfig = migrateAndValidate(
          config,
          packageFile.content.renovate
        );
        logger.debug(
          { config: migratedConfig },
          'package.json migrated config'
        );
        // istanbul ignore if
        if (migratedConfig.errors.length) {
          const error = new Error('config-validation');
          error.configFile = packageFile.packageFile;
          error.validationError =
            'The `renovate` config inside `package.json` failed validation';
          error.validationMessage = migratedConfig.errors
            .map(e => e.message)
            .join(', ');
          throw error;
        }
        const resolvedConfig = await presets.resolveConfigPresets(
          migratedConfig
        );
        logger.debug(
          { config: resolvedConfig },
          'package.json resolved config'
        );
        Object.assign(packageFile, resolvedConfig);
        delete packageFile.content.renovate;
      } else {
        logger.debug(
          { packageFile: packageFile.packageFile },
          `No renovate config`
        );
      }
      // Detect if lock files are used
      const yarnLockFileName = upath.join(
        path.dirname(packageFile.packageFile),
        'yarn.lock'
      );
      if (fileList.includes(yarnLockFileName)) {
        logger.debug(
          { packageFile: packageFile.packageFile },
          'Found yarn.lock'
        );
        packageFile.yarnLock = yarnLockFileName;
      }
      const packageLockFileName = upath.join(
        path.dirname(packageFile.packageFile),
        'package-lock.json'
      );
      if (fileList.includes(packageLockFileName)) {
        logger.debug(
          { packageFile: packageFile.packageFile },
          'Found package-lock.json'
        );
        packageFile.packageLock = packageLockFileName;
      }
      const shrinkwrapFileName = upath.join(
        path.dirname(packageFile.packageFile),
        'shrinkwrap.yaml'
      );
      if (fileList.includes(shrinkwrapFileName)) {
        logger.debug(
          { packageFile: packageFile.packageFile },
          'Found shrinkwrap.yaml'
        );
        packageFile.shrinkwrapYaml = shrinkwrapFileName;
      }
      packageFile.currentPackageJsonVersion = packageFile.content.version;
      return packageFile;
    } else if (packageFile.packageFile.endsWith('package.js')) {
      // meteor
      return mergeChildConfig(config.meteor, packageFile);
    } else if (packageFile.packageFile.endsWith('Dockerfile')) {
      logger.debug('Resolving Dockerfile');
      return dockerResolve.resolvePackageFile(config, packageFile);
    } else if (packageFile.packageFile.endsWith('.travis.yml')) {
      logger.debug('Resolving .travis.yml');
      return nodeResolve.resolvePackageFile(config, packageFile);
    } else if (packageFile.packageFile.endsWith('WORKSPACE')) {
      logger.debug('Resolving WORKSPACE');
      return bazelResolve.resolvePackageFile(config, packageFile);
    }
    return null;
  }
  logger.debug('queue');
  const queue = allPackageFiles.map(p => resolvePackageFile(p));
  let packageFiles = (await Promise.all(queue)).filter(p => p !== null);

  logger.debug('Checking against path rules');
  packageFiles = packageFiles.map(pf => {
    let packageFile = { ...pf };
    for (const pathRule of config.pathRules) {
      /* eslint-disable no-loop-func */
      if (
        pathRule.paths.some(
          rulePath =>
            packageFile.packageFile.includes(rulePath) ||
            minimatch(packageFile.packageFile, rulePath)
        )
      ) {
        logger.debug({ pathRule, packageFile }, 'Matched pathRule');
        packageFile = mergeChildConfig(packageFile, pathRule);
        delete packageFile.paths;
      }
      /* eslint-enable */
    }
    return packageFile;
  });

  platform.ensureIssueClosing('Action Required: Fix Renovate Configuration');
  return checkMonorepos({ ...config, packageFiles });
}
<commit_msg>refactor: add log if package.json renovate config found outside root of repository<commit_after>const path = require('path');
const upath = require('upath');
const minimatch = require('minimatch');

const { migrateAndValidate } = require('../config/migrate-validate');
const presets = require('../config/presets');

const manager = require('./index');
const dockerResolve = require('../manager/docker/resolve');
const nodeResolve = require('../manager/node/resolve');
const bazelResolve = require('../manager/bazel/resolve');
const { mergeChildConfig } = require('../config');
const { checkMonorepos } = require('../manager/npm/monorepos');

module.exports = {
  resolvePackageFiles,
};

async function resolvePackageFiles(config) {
  logger.trace({ config }, 'resolvePackageFiles()');
  const allPackageFiles = config.packageFiles.length
    ? config.packageFiles
    : await manager.detectPackageFiles(config);
  logger.debug({ allPackageFiles }, 'allPackageFiles');
  const fileList = await platform.getFileList();
  async function resolvePackageFile(p) {
    const packageFile = typeof p === 'string' ? { packageFile: p } : p;
    Object.assign(packageFile, config.npm);
    if (packageFile.packageFile.endsWith('package.json')) {
      logger.debug(`Resolving packageFile ${JSON.stringify(packageFile)}`);
      const pFileRaw = await platform.getFile(packageFile.packageFile);
      if (!pFileRaw) {
        logger.info(
          { packageFile: packageFile.packageFile },
          'Cannot find package.json'
        );
        config.errors.push({
          depName: packageFile.packageFile,
          message: 'Cannot find package.json',
        });
        return null;
      }
      try {
        packageFile.content = JSON.parse(pFileRaw);
      } catch (err) {
        logger.info(
          { packageFile: packageFile.packageFile },
          'Cannot parse package.json'
        );
        if (config.repoIsOnboarded) {
          const error = new Error('config-validation');
          error.configFile = packageFile.packageFile;
          error.validationError = 'Cannot parse package.json';
          error.validationMessage =
            'This package.json contains invalid JSON and cannot be parsed. Please fix it, or add it to your "ignorePaths" array in your renovate config so that Renovate can continue.';
          throw error;
        }
        config.errors.push({
          depName: packageFile.packageFile,
          message:
            "Cannot parse package.json (invalid JSON). Please fix the contents or add the file/path to the `ignorePaths` array in Renovate's config",
        });
        return null;
      }
      if (!config.ignoreNpmrcFile) {
        packageFile.npmrc = await platform.getFile(
          upath.join(path.dirname(packageFile.packageFile), '.npmrc')
        );
      }
      if (packageFile.npmrc) {
        logger.info('Found .npmrc');
      } else {
        delete packageFile.npmrc;
      }
      packageFile.yarnrc = await platform.getFile(
        upath.join(path.dirname(packageFile.packageFile), '.yarnrc')
      );
      if (packageFile.yarnrc) {
        logger.info('Found .yarnrc');
      } else {
        delete packageFile.yarnrc;
      }
      // hoist renovate config if exists
      if (packageFile.content.renovate) {
        logger.debug(
          {
            packageFile: packageFile.packageFile,
            config: packageFile.content.renovate,
          },
          `Found package.json renovate config`
        );
        // istanbul ignore if
        if (packageFile.packageFile !== 'package.json') {
          logger.info('Found package.json renovate config in subdirectory.');
        }
        const migratedConfig = migrateAndValidate(
          config,
          packageFile.content.renovate
        );
        logger.debug(
          { config: migratedConfig },
          'package.json migrated config'
        );
        // istanbul ignore if
        if (migratedConfig.errors.length) {
          const error = new Error('config-validation');
          error.configFile = packageFile.packageFile;
          error.validationError =
            'The `renovate` config inside `package.json` failed validation';
          error.validationMessage = migratedConfig.errors
            .map(e => e.message)
            .join(', ');
          throw error;
        }
        const resolvedConfig = await presets.resolveConfigPresets(
          migratedConfig
        );
        logger.debug(
          { config: resolvedConfig },
          'package.json resolved config'
        );
        Object.assign(packageFile, resolvedConfig);
        delete packageFile.content.renovate;
      } else {
        logger.debug(
          { packageFile: packageFile.packageFile },
          `No renovate config`
        );
      }
      // Detect if lock files are used
      const yarnLockFileName = upath.join(
        path.dirname(packageFile.packageFile),
        'yarn.lock'
      );
      if (fileList.includes(yarnLockFileName)) {
        logger.debug(
          { packageFile: packageFile.packageFile },
          'Found yarn.lock'
        );
        packageFile.yarnLock = yarnLockFileName;
      }
      const packageLockFileName = upath.join(
        path.dirname(packageFile.packageFile),
        'package-lock.json'
      );
      if (fileList.includes(packageLockFileName)) {
        logger.debug(
          { packageFile: packageFile.packageFile },
          'Found package-lock.json'
        );
        packageFile.packageLock = packageLockFileName;
      }
      const shrinkwrapFileName = upath.join(
        path.dirname(packageFile.packageFile),
        'shrinkwrap.yaml'
      );
      if (fileList.includes(shrinkwrapFileName)) {
        logger.debug(
          { packageFile: packageFile.packageFile },
          'Found shrinkwrap.yaml'
        );
        packageFile.shrinkwrapYaml = shrinkwrapFileName;
      }
      packageFile.currentPackageJsonVersion = packageFile.content.version;
      return packageFile;
    } else if (packageFile.packageFile.endsWith('package.js')) {
      // meteor
      return mergeChildConfig(config.meteor, packageFile);
    } else if (packageFile.packageFile.endsWith('Dockerfile')) {
      logger.debug('Resolving Dockerfile');
      return dockerResolve.resolvePackageFile(config, packageFile);
    } else if (packageFile.packageFile.endsWith('.travis.yml')) {
      logger.debug('Resolving .travis.yml');
      return nodeResolve.resolvePackageFile(config, packageFile);
    } else if (packageFile.packageFile.endsWith('WORKSPACE')) {
      logger.debug('Resolving WORKSPACE');
      return bazelResolve.resolvePackageFile(config, packageFile);
    }
    return null;
  }
  logger.debug('queue');
  const queue = allPackageFiles.map(p => resolvePackageFile(p));
  let packageFiles = (await Promise.all(queue)).filter(p => p !== null);

  logger.debug('Checking against path rules');
  packageFiles = packageFiles.map(pf => {
    let packageFile = { ...pf };
    for (const pathRule of config.pathRules) {
      /* eslint-disable no-loop-func */
      if (
        pathRule.paths.some(
          rulePath =>
            packageFile.packageFile.includes(rulePath) ||
            minimatch(packageFile.packageFile, rulePath)
        )
      ) {
        logger.debug({ pathRule, packageFile }, 'Matched pathRule');
        packageFile = mergeChildConfig(packageFile, pathRule);
        delete packageFile.paths;
      }
      /* eslint-enable */
    }
    return packageFile;
  });

  platform.ensureIssueClosing('Action Required: Fix Renovate Configuration');
  return checkMonorepos({ ...config, packageFiles });
}
<|endoftext|>


<commit_before>import Hook from '../../util/hook'
import dns from 'native-dns'

import schemaGen from './gensrc/schema'
import resolverGen from './gensrc/resolver'
import {deepMergeToFirst} from 'util/deepMerge'
import resolver from "../cronjob/resolver";
import schema from "../cronjob/schema";

console.log('create dns server')
const server = dns.createServer()

let database = null
let hosts = {}

// Hook to add mongodb resolver
Hook.on('resolver', ({db, resolvers}) => {
    deepMergeToFirst(resolvers, resolverGen(db))
})

// Hook to add mongodb schema
Hook.on('schema', ({schemas}) => {
    schemas.push(schemaGen)
})

// Hook when db is ready
Hook.on('appready', ({db}) => {
    database = db
    readHosts(db)
})

// Hook when the type CronJob has changed
Hook.on('typeUpdated_DnsHost', ({result}) => {
    if (result.name) {
        console.log(result)
        hosts[result.name] = result.block
    }
})

server.on('request', (req, res) => {

    const hostname = req.question[0].name

    if (database != null) {

        if (hosts[hostname] === undefined) {
            hosts[hostname] = false
            database.collection('DnsHost').insertOne({
                name: hostname
            })
        }

    }

    if(hosts[hostname] === true){
        console.log(`block host ${hostname}`)
        res.answer.push(dns.A({
            name: hostname,
            address: '0.0.0.0',
            ttl: 1,
        }))
        res.send()
    }else {

        console.log(`resolve host ${hostname}`)
        const dnsRequest = dns.Request({
            question: req.question[0],
            server: {address: '8.8.8.8', port: 53, type: 'udp'},
            timeout: 1000
        })

        dnsRequest.on('timeout', () => {
            console.log('Timeout in making request')
        })

        dnsRequest.on('message', (err, answer) => {
            answer.answer.forEach((a) => {
                res.answer.push(a)
            })
        })

        dnsRequest.on('end', () => {
            res.send()
        })

        dnsRequest.send()
    }
})

server.on('error', (err, buff, req, res) => {
    console.log(err.stack)
})

server.serve(3053, '*')

const readHosts = async (db) => {
    (await db.collection('DnsHost').find().forEach(o => {
        hosts[o.name] = !!o.block
    }))
}
<commit_msg>Small improvements<commit_after>import Hook from '../../util/hook'
import dns from 'native-dns'

import schemaGen from './gensrc/schema'
import resolverGen from './gensrc/resolver'
import {deepMergeToFirst} from 'util/deepMerge'
import resolver from "../cronjob/resolver";
import schema from "../cronjob/schema";

console.log('create dns server')
const server = dns.createServer()

let database = null
let hosts = {}

// Hook to add mongodb resolver
Hook.on('resolver', ({db, resolvers}) => {
    deepMergeToFirst(resolvers, resolverGen(db))
})

// Hook to add mongodb schema
Hook.on('schema', ({schemas}) => {
    schemas.push(schemaGen)
})

// Hook when db is ready
Hook.on('appready', ({db}) => {
    database = db
    readHosts(db)
})

// Hook when the type CronJob has changed
Hook.on('typeUpdated_DnsHost', ({result}) => {
    if (result.name) {
        console.log(result)
        hosts[result.name] = result.block
    }
})

server.on('request', (req, res) => {

    const hostname = req.question[0].name

    if (database != null) {

        if (hosts[hostname] === undefined) {
            hosts[hostname] = false
            database.collection('DnsHost').insertOne({
                name: hostname
            })
        }

    }

    if(hosts[hostname] === true){
        console.log(`block host ${hostname}`)
        res.answer.push(dns.A({
            name: hostname,
            address: '0.0.0.0',
            ttl: 1,
        }))
        res.send()
    }else {

        console.log(`resolve host ${hostname}`)
        const dnsRequest = dns.Request({
            question: req.question[0],
            server: {address: '8.8.8.8', port: 53, type: 'udp'},
            timeout: 1000
        })

        dnsRequest.on('timeout', () => {
            console.log('Timeout in making request')
        })

        dnsRequest.on('message', (err, answer) => {
            answer.answer.forEach((a) => {
                res.answer.push(a)
            })
        })

        dnsRequest.on('end', () => {
            res.send()
        })

        dnsRequest.send()
    }
})

server.on('error', (err, buff, req, res) => {
    console.log(err.stack)
})

server.on('listening', ()=> {
    console.log('dns listening')
})

server.on('listening', ()=> {
    console.log('dns close')
})

server.serve(3053, '*')

const readHosts = async (db) => {
    (await db.collection('DnsHost').find().forEach(o => {
        hosts[o.name] = !!o.block
    }))
}
<|endoftext|>


<commit_before>'use strict';

angular.module('copayApp.controllers').controller('copayersController',
  function($scope, $log, $timeout, $stateParams, $state, $rootScope, $ionicHistory, $window, lodash, profileService, walletService, popupService, platformInfo, gettextCatalog, ongoingProcess) {

    var appName = $window.appConfig.userVisibleName;
    var appUrl = $window.appConfig.url;

    $scope.isCordova = platformInfo.isCordova;
    $scope.$on("$ionicView.beforeEnter", function(event, data) {
      $scope.wallet = profileService.getWallet(data.stateParams.walletId);
      updateWallet();
    });

    $rootScope.$on('bwsEvent', function() {
      updateWallet();
    });

    var updateWallet = function() {
      $log.debug('Updating wallet:' + $scope.wallet.name)
      walletService.getStatus($scope.wallet, {}, function(err, status) {
        if (err) {
          $log.error(err); //TODO
          return;
        }
        $scope.wallet.status = status;
        $scope.copayers = $scope.wallet.status.wallet.copayers;
        $scope.secret = $scope.wallet.status.wallet.secret;
        $timeout(function() {
          $scope.$apply();
        });
        if (status.wallet.status == 'complete') {
          $scope.wallet.openWallet(function(err, status) {
            if (err) $log.error(err);
            $scope.goHome();
          });
        }
      });
    };

    $scope.showDeletePopup = function() {
      var title = gettextCatalog.getString('Confirm');
      var msg = gettextCatalog.getString('Are you sure you want to cancel and delete this wallet?');
      popupService.showConfirm(title, msg, null, null, function(res) {
        if (res) deleteWallet();
      });
    };

    function deleteWallet() {
      ongoingProcess.set('deletingWallet', true);
      profileService.deleteWalletClient($scope.wallet, function(err) {
        ongoingProcess.set('deletingWallet', false);
        if (err) {
          popupService.showAlert(gettextCatalog.getString('Error'), err.message || err);
        } else {
          $scope.goHome();
        }
      });
    };

    $scope.copySecret = function() {
      if ($scope.isCordova) {
        window.cordova.plugins.clipboard.copy($scope.secret);
        window.plugins.toast.showShortCenter(gettextCatalog.getString('Copied to clipboard'));
      }
    };

    $scope.shareSecret = function() {
      if ($scope.isCordova) {
        var message = gettextCatalog.getString('Join my {{appName}} Wallet. Here is the invitation code: {{secret}} You can download {{appName}} for your phone or desktop at {{appUrl}}', {
          secret: $scope.secret,
          appName: appName,
          appUrl: appUrl
        });
        window.plugins.socialsharing.share(message, gettextCatalog.getString('Invitation to share a {{appName}} Wallet', {
          appName: appName
        }), null, null);
      }
    };

    $scope.goHome = function() {
      $ionicHistory.removeBackView();
      $state.go('tabs.home');
    };

  });
<commit_msg>Fix error if backView does not exist<commit_after>'use strict';

angular.module('copayApp.controllers').controller('copayersController',
  function($scope, $log, $timeout, $stateParams, $state, $rootScope, $ionicHistory, $window, lodash, profileService, walletService, popupService, platformInfo, gettextCatalog, ongoingProcess) {

    var appName = $window.appConfig.userVisibleName;
    var appUrl = $window.appConfig.url;

    $scope.isCordova = platformInfo.isCordova;
    $scope.$on("$ionicView.beforeEnter", function(event, data) {
      $scope.wallet = profileService.getWallet(data.stateParams.walletId);
      updateWallet();
    });

    $rootScope.$on('bwsEvent', function() {
      updateWallet();
    });

    var updateWallet = function() {
      $log.debug('Updating wallet:' + $scope.wallet.name)
      walletService.getStatus($scope.wallet, {}, function(err, status) {
        if (err) {
          $log.error(err); //TODO
          return;
        }
        $scope.wallet.status = status;
        $scope.copayers = $scope.wallet.status.wallet.copayers;
        $scope.secret = $scope.wallet.status.wallet.secret;
        $timeout(function() {
          $scope.$apply();
        });
        if (status.wallet.status == 'complete') {
          $scope.wallet.openWallet(function(err, status) {
            if (err) $log.error(err);
            $scope.goHome();
          });
        }
      });
    };

    $scope.showDeletePopup = function() {
      var title = gettextCatalog.getString('Confirm');
      var msg = gettextCatalog.getString('Are you sure you want to cancel and delete this wallet?');
      popupService.showConfirm(title, msg, null, null, function(res) {
        if (res) deleteWallet();
      });
    };

    function deleteWallet() {
      ongoingProcess.set('deletingWallet', true);
      profileService.deleteWalletClient($scope.wallet, function(err) {
        ongoingProcess.set('deletingWallet', false);
        if (err) {
          popupService.showAlert(gettextCatalog.getString('Error'), err.message || err);
        } else {
          $scope.goHome();
        }
      });
    };

    $scope.copySecret = function() {
      if ($scope.isCordova) {
        window.cordova.plugins.clipboard.copy($scope.secret);
        window.plugins.toast.showShortCenter(gettextCatalog.getString('Copied to clipboard'));
      }
    };

    $scope.shareSecret = function() {
      if ($scope.isCordova) {
        var message = gettextCatalog.getString('Join my {{appName}} Wallet. Here is the invitation code: {{secret}} You can download {{appName}} for your phone or desktop at {{appUrl}}', {
          secret: $scope.secret,
          appName: appName,
          appUrl: appUrl
        });
        window.plugins.socialsharing.share(message, gettextCatalog.getString('Invitation to share a {{appName}} Wallet', {
          appName: appName
        }), null, null);
      }
    };

    $scope.goHome = function() {
      $state.go('tabs.home');
      $ionicHistory.clearHistory();
    };

  });
<|endoftext|>


<commit_before>(function uglify_js_closure(con ,doc ,win ,l10n){
var devel = true
var app = { // configuration placeholders
        config: null //{ db: null ,extjs:null }
        ,user: { id: 'olecom' ,name:'Олег Верич' ,role:'склад' }//TODO:login
        ,role: { va_permissions: null }
        //,tools: { /*load_extjs: null*/ }
    }

    /* two frontend parts: under `node-webkit` and `express` in browser */

    if(typeof process != 'undefined'){// `nodeJS` is inside HTML
        app.process = process
        app.tray = { obj: null ,stat: 'show' }
        app.w = null
        // start local ExtJS 'App'
        node_webkit(con ,app)
    } else {// 'node_express': XHR communication with backend
        var xhr = new XMLHttpRequest()
        xhr.open('GET' ,'/app.config.extjs.json' ,true)
        xhr.onreadystatechange = function(){
            if(4 == xhr.readyState) {
                if(200 != xhr.status){
                    alert(l10n.errload_config_read)
                } else {
                    // start external ExtJS 'App'
                    app.config = { extjs: JSON.parse(xhr.responseText) }
                    extjs_load(doc ,win)
                }
            }
        }
        xhr.send(null)
    }

/*
 * front end: node-webkit part
 */
function node_webkit(con ,app){

    app.process.on('uncaughtException' ,function(err){
        con.error('uncaughtException:', err)
        alert(l10n.uncaughtException  + err)
    })

    var gui = require('nw.gui')

    app.w = gui.Window.get()

    //if(devel) app.w.showDevTools()

    setup_tray(app.tray ,app.w)

    // long xhr pooling gets messages from backend
    load_config(app) && require('http')
    .get("http://127.0.0.1:" + app.config.backend.ctl_port ,backend_is_running)
    .on('error' ,backend_ctl_errors)

    return

function backend_is_running(){
    extjs_load(app.w.window.document ,app.w.window)
    con.log('reload just extjs, backend is up and running already')
}

function backend_ctl_errors(e){
// NOTE: this is permanent error handler for all requests to `backend.ctl_port`
    if(app.config.extjs){// run setup only first time after ctl check
        spawn_backend(app) && extjs_load(app.w.window.document ,app.w.window)
        con.log('on error backend spawed && extjs')
    }
    // ignore other errors for now
    con.warn(e)
}

function spawn_backend(app){
// loads `express` and answers on http requests,
// as for this `nw` instance as for remote clients
// closing `nw` doesn't mean closing backend processing (maybe cfg it?)

    var fs = require('fs')

    try {// check and/or create log dir
        if(!fs.statSync(app.config.log).isDirectory()){
            con.error('ERROR log dir is not a directory')
            app.w.window.alert(l10n.errload_config_log_not_dir + app.config.log)
            return false
        }
    } catch(ex){
        try {
            fs.mkdirSync(app.config.log)
        } catch(ex) {
            con.error('ERROR log dir:' + (ex = (' ' + app.config.log + '\n' + ex)))
            app.w.window.alert(l10n.errload_config_log_mkdir + ex)
            return false
        }
    }
    var  log = app.config.log +
               app.config.backend.file.replace(/[\\/]/g ,'_') + '.log'
        ,backend = require('child_process').spawn(
            'node'
            ,[ app.config.backend.file ]
            ,{
                 detached: true
                ,env: {
                    NODEJS_CONFIG: JSON.stringify(app.config)
                }
                ,stdio: [ 'ignore'
                    ,fs.openSync(log ,'a+')
                    ,fs.openSync(log ,'a+')
                ]
            }
        )
    if(!backend.pid || backend.exitCode){
        con.error('ERROR spawn backend exit code: ' + backend.exitCode)
        app.w.window.alert(l10n.errload_spawn_backend + backend.exitCode)
        return false
    }
    backend.unref()
    con.error('backend.pid: ' + backend.pid)

    return true
}

function load_config(app){// loaded only by main process -- node-webkit
    var cfg
    var fs = require('fs')

    if((cfg = app.process._nw_app.argv[0])){// cmd line
        cfg = 'config/' + cfg
    } else {// HOME config
        if(app.process.env.HOME){
            cfg = app.process.env.HOME
        } else if(app.process.env.HOMEDRIVE && app.process.env.HOMEPATH){
            cfg = app.process.env.HOMEDRIVE +  app.process.env.HOMEPATH
        }
        cfg = cfg + '/.enjsms.js'//FIXME: app specific part
        try {
            fs.statSync(cfg)
        } catch (ex){
            cfg = null
        }
    }
    if(!cfg)// default
        cfg = 'config/cfg_default.js'

    try {
        app.config = (
            new Function('var config ; return ' +
                          fs.readFileSync(cfg ,'utf8'))
        )()
    } catch(ex){
        con.error('ERROR load_config:' + (cfg = (' ' + cfg + '\n' + ex)))
        app.w.window.alert(l10n.errload_config_read + cfg)
        return false
    }
    con.log('reading config: ' + cfg + ' done')
    return true
}

function setup_tray(t ,w){
    t.obj = new gui.Tray({ title: l10n.tray.title ,icon: 'app_main/css/favicon.png' })
    t.obj.tooltip = l10n.tray.winvis

    t.obj.on('click' ,function onTrayClick(){
        if('show' == t.stat){// simple show,focus / hide
            t.stat = 'hide'
            t.obj.tooltip = l10n.tray.wininv
            w.hide()
        } else {
            w.show()
            t.obj.tooltip = l10n.tray.winvis
            t.stat = 'show'
        }
    })
    con.log('setup_tray: done')
}
}// nw

/*
 * common tools for `nw` && `express` front ends
 */

function extjs_load(doc ,w){
var extjs, path

    path = app.config.extjs.path
    extjs = doc.createElement('link')
    extjs.setAttribute('rel', 'stylesheet')
    extjs.setAttribute('href', path + 'resources/css/ext-all.css')
    doc.head.appendChild(extjs)

    extjs = doc.createElement('script'),
    extjs.setAttribute('type' ,'application/javascript')
    extjs.setAttribute('charset' ,'utf-8')
    extjs.setAttribute('src' ,path + 'ext-all' + (devel ? '-debug' : '') + '.js')
    doc.head.appendChild(extjs)

    path = '1234'
    extjs = setInterval(function waiting_extjs(){
        if('undefined' != typeof Ext){
            clearInterval(extjs)
            path = Ext.Loader.getPath('Ext')
            con.log(
                'ExtJS version: ' + Ext.getVersion('extjs') + '\n' +
                'ExtJS is at <' + path + '>'
            )
            Ext.Loader.setPath('Ext.ux', path + '/../examples/ux')
            Ext.Loader.setPath('Ext.uxo', app.config.extjs.appFolder + '/uxo')
            app.config.extjs.launch = extjs_launch
            Ext.application(app.config.extjs)
            return
        } else if('' == path){
            clearInterval(extjs)
            con.error(l10n.extjsNotFound)
            w.alert(l10n.extjsNotFound)
            return
        }
        path = path.slice(1)
    }, 1024)
    con.log('load_extjs: done, waiting for ExtJS')
}

function extjs_launch(){
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider)

    //TODO: for each app.config.app.modules load module
    //TODO: dynamic addition in toolbar or items/xtype construction
    //global `App` object is available now
    App.config = app.config ,App.user = app.user ,App.role = app.role
    //TODO: events via long pooling from app_backend/express
    //App.sync_clearTimeout = Ext.defer(App.sync_extjs_nodejs, 3777)

    if(app.config.extjs.fading){
        // very strange composition to get gears to fadeOut and viewport to fadeIn
        var b = Ext.getBody()
        b.fadeOut({duration:777 ,callback:
            function(){
                Ext.fly('startup').remove()
                b.show()
                Ext.create('App.view.Viewport')
                b.fadeIn({easing:'easeIn' ,duration:1024})
                con.log('extjs: faded In')
            }
        })
    } else Ext.create('App.view.Viewport')

    app.config.extjs = null // clear ref for GC
    con.log('extjs_launch: OK')
}

})(console ,document ,window ,l10n)
<commit_msg>app_front: fix some comments<commit_after>(function uglify_js_closure(con ,doc ,win ,l10n){
var devel = true
var app = { // configuration placeholders
        config: null //{ db: null ,extjs:null }
        ,user: { id: 'olecom' ,name:'Олег Верич' ,role:'склад' }//TODO:login
        ,role: { va_permissions: null }
        //,tools: { /*load_extjs: null*/ }
    }

    /* two frontend parts: under `node-webkit` and `express` in browser */

    if(typeof process != 'undefined'){// `nodejs` runtime inside HTML (native desktop)
        app.process = process
        app.tray = { obj: null ,stat: 'show' }
        app.w = null
        // start local ExtJS 'App'
        node_webkit(con ,app)
    } else {// 'nodejs + connectjs': XHR communication with backend (remote web browser)
        var xhr = new XMLHttpRequest()
        xhr.open('GET' ,'/app.config.extjs.json' ,true)
        xhr.onreadystatechange = function(){
            if(4 == xhr.readyState){
                if(200 != xhr.status){
                    alert(l10n.errload_config_read)
                } else {
                    // start external ExtJS 'App'
                    app.config = { extjs: JSON.parse(xhr.responseText) }
                    extjs_load(doc ,win)
                }
            }
        }
        xhr.send(null)
    }

/*
 * front end: node-webkit part
 */
function node_webkit(con ,app){

    app.process.on('uncaughtException' ,function(err){
        con.error('uncaughtException:', err)
        alert(l10n.uncaughtException  + err)
    })

    var gui = require('nw.gui')

    app.w = gui.Window.get()

    //if(devel) app.w.showDevTools()

    setup_tray(app.tray ,app.w)

    // long xhr pooling gets messages from backend
    load_config(app) && require('http')
    .get("http://127.0.0.1:" + app.config.backend.ctl_port ,backend_is_running)
    .on('error' ,backend_ctl_errors)

    return

function backend_is_running(){
    extjs_load(app.w.window.document ,app.w.window)
    con.log('reload just extjs, backend is up and running already')
}

function backend_ctl_errors(e){
// NOTE: this is permanent error handler for all requests to `backend.ctl_port`
    if(app.config.extjs){// run setup only first time after ctl check
        spawn_backend(app) && extjs_load(app.w.window.document ,app.w.window)
        con.log('on error backend spawed && extjs')
    }
    // ignore other errors for now
    con.warn(e)
}

function spawn_backend(app){
// loads `node`+`connect` as separate process and answers on http requests,
// as for this `nw` instance, as for remote clients
// closing `nw` doesn't mean closing backend processing (maybe cfg it?)

    var fs = require('fs')

    try {// check and/or create log dir
        if(!fs.statSync(app.config.log).isDirectory()){
            con.error('ERROR log dir is not a directory')
            app.w.window.alert(l10n.errload_config_log_not_dir + app.config.log)
            return false
        }
    } catch(ex){
        try {
            fs.mkdirSync(app.config.log)
        } catch(ex) {
            con.error('ERROR log dir:' + (ex = (' ' + app.config.log + '\n' + ex)))
            app.w.window.alert(l10n.errload_config_log_mkdir + ex)
            return false
        }
    }
    var  log = app.config.log +
               app.config.backend.file.replace(/[\\/]/g ,'_') + '.log'
        ,backend = require('child_process').spawn(
            'node'
            ,[ app.config.backend.file ]
            ,{
                 detached: true
                ,env: {
                    NODEJS_CONFIG: JSON.stringify(app.config)
                }
                ,stdio: [ 'ignore'
                    ,fs.openSync(log ,'a+')
                    ,fs.openSync(log ,'a+')
                ]
            }
        )
    if(!backend.pid || backend.exitCode){
        con.error('ERROR spawn backend exit code: ' + backend.exitCode)
        app.w.window.alert(l10n.errload_spawn_backend + backend.exitCode)
        return false
    }
    backend.unref()
    con.error('backend.pid: ' + backend.pid)

    return true
}

function load_config(app){// loaded only by main process -- node-webkit
    var cfg
    var fs = require('fs')

    if((cfg = app.process._nw_app.argv[0])){// cmd line
        cfg = 'config/' + cfg
    } else {// HOME config
        if(app.process.env.HOME){
            cfg = app.process.env.HOME
        } else if(app.process.env.HOMEDRIVE && app.process.env.HOMEPATH){
            cfg = app.process.env.HOMEDRIVE +  app.process.env.HOMEPATH
        }
        cfg = cfg + '/.enjsms.js'//FIXME: app specific part
        try {
            fs.statSync(cfg)
        } catch (ex){
            cfg = null
        }
    }
    if(!cfg)// default
        cfg = 'config/cfg_default.js'

    try {
        app.config = (
            new Function('var config ; return ' +
                          fs.readFileSync(cfg ,'utf8'))
        )()
    } catch(ex){
        con.error('ERROR load_config:' + (cfg = (' ' + cfg + '\n' + ex)))
        app.w.window.alert(l10n.errload_config_read + cfg)
        return false
    }
    con.log('reading config: ' + cfg + ' done')
    return true
}

function setup_tray(t ,w){
    t.obj = new gui.Tray({ title: l10n.tray.title ,icon: 'app_main/css/favicon.png' })
    t.obj.tooltip = l10n.tray.winvis

    t.obj.on('click' ,function onTrayClick(){
        if('show' == t.stat){// simple show,focus / hide
            t.stat = 'hide'
            t.obj.tooltip = l10n.tray.wininv
            w.hide()
        } else {
            w.show()
            t.obj.tooltip = l10n.tray.winvis
            t.stat = 'show'
        }
    })
    con.log('setup_tray: done')
}
}// nw

/*
 * common tools for `nw` && `express` front ends
 */

function extjs_load(doc ,w){
var extjs, path

    path = app.config.extjs.path
    extjs = doc.createElement('link')
    extjs.setAttribute('rel', 'stylesheet')
    extjs.setAttribute('href', path + 'resources/css/ext-all.css')
    doc.head.appendChild(extjs)

    extjs = doc.createElement('script'),
    extjs.setAttribute('type' ,'application/javascript')
    extjs.setAttribute('charset' ,'utf-8')
    extjs.setAttribute('src' ,path + 'ext-all' + (devel ? '-debug' : '') + '.js')
    doc.head.appendChild(extjs)

    path = '1234'
    extjs = setInterval(function waiting_extjs(){
        if('undefined' != typeof Ext){
            clearInterval(extjs)
            path = Ext.Loader.getPath('Ext')
            con.log(
                'ExtJS version: ' + Ext.getVersion('extjs') + '\n' +
                'ExtJS is at <' + path + '>'
            )
            Ext.Loader.setPath('Ext.ux', path + '/../examples/ux')
            Ext.Loader.setPath('Ext.uxo', app.config.extjs.appFolder + '/uxo')
            app.config.extjs.launch = extjs_launch
            Ext.application(app.config.extjs)
            return
        } else if('' == path){
            clearInterval(extjs)
            con.error(l10n.extjsNotFound)
            w.alert(l10n.extjsNotFound)
            return
        }
        path = path.slice(1)
    }, 1024)
    con.log('load_extjs: done, waiting for ExtJS')
}

function extjs_launch(){
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider)

    //TODO: for each app.config.app.modules load module
    //TODO: dynamic addition in toolbar or items/xtype construction
    //global `App` object is available now
    App.config = app.config ,App.user = app.user ,App.role = app.role
    //TODO: events via long pooling from app_backend/express
    //App.sync_clearTimeout = Ext.defer(App.sync_extjs_nodejs, 3777)

    if(app.config.extjs.fading){
        // very strange composition to get gears to fadeOut and viewport to fadeIn
        var b = Ext.getBody()
        b.fadeOut({duration:777 ,callback:
            function(){
                Ext.fly('startup').remove()
                b.show()
                Ext.create('App.view.Viewport')
                b.fadeIn({easing:'easeIn' ,duration:1024})
                con.log('extjs: faded In')
            }
        })
    } else Ext.create('App.view.Viewport')

    app.config.extjs = null // clear ref for GC
    con.log('extjs_launch: OK')
}

})(console ,document ,window ,l10n)
<|endoftext|>


<commit_before>'use strict';

angular.module('copayApp.controllers').controller('tabHomeController',
  function($rootScope, sendFlowService, $timeout, $scope, $state, $stateParams, $ionicScrollDelegate, $window, gettextCatalog, lodash, popupService, ongoingProcess, bannerService, externalLinkService, latestReleaseService, profileService, walletService, configService, $log, platformInfo, storageService, txpModalService, appConfigService, startupService, addressbookService, bwcError, nextStepsService, buyAndSellService, homeIntegrationsService, bitpayCardService, pushNotificationsService, timeService, $ionicNavBarDelegate) {
    var wallet;
    var listeners = [];
    var notifications = [];
    $scope.externalServices = {};
    $scope.openTxpModal = txpModalService.open;
    $scope.version = $window.version;
    $scope.name = appConfigService.nameCase;
    $scope.homeTip = $stateParams.fromOnboarding;
    $scope.isCordova = platformInfo.isCordova;
    $scope.isAndroid = platformInfo.isAndroid;
    $scope.isWindowsPhoneApp = platformInfo.isCordova && platformInfo.isWP;
    $scope.isNW = platformInfo.isNW;
    $scope.showServices = false;
    $scope.bannerIsLoading = true;
    $scope.bannerImageUrl = '';
    $scope.bannerUrl = '';

    $scope.$on("$ionicView.beforeEnter", onBeforeEnter);
    $scope.$on("$ionicView.enter", onEnter);
    $scope.$on("$ionicView.afterEnter", onAfterEnter);
    $scope.$on("$ionicView.leave", onLeave);

    function onAfterEnter () {
      startupService.ready();

      bannerService.getBanner(function (banner) {
        $scope.bannerImageUrl = banner.imageURL;
        $scope.bannerUrl = banner.url;
        $scope.bannerIsLoading = false;
      });
    };

    function onBeforeEnter (event, data) {

      if (!$scope.homeTip) {
        storageService.getHomeTipAccepted(function(error, value) {
          $scope.homeTip = (value == 'accepted') ? false : true;
        });
      }

      if ($scope.isNW) {
        latestReleaseService.checkLatestRelease(function(err, newRelease) {
          if (err) {
            $log.warn(err);
            return;
          }
          if (newRelease) {
            $scope.newRelease = true;
            $scope.updateText = gettextCatalog.getString('There is a new version of {{appName}} available', {
              appName: $scope.name
            });
          }
        });
      }
    };

    function onEnter(event, data) {
      $ionicNavBarDelegate.showBar(true);

      addressbookService.list(function(err, ab) {
        if (err) $log.error(err);
        $scope.addressbook = ab || {};
      });

      listeners = [
        $rootScope.$on('bwsEvent', function(e, walletId, type, n) {
          var wallet = profileService.getWallet(walletId);
          updateWallet(wallet);
          if ($scope.recentTransactionsEnabled) getNotifications();

        }),
        $rootScope.$on('Local/TxAction', function(e, walletId) {
          $log.debug('Got action for wallet ' + walletId);
          var wallet = profileService.getWallet(walletId);
          updateWallet(wallet);
          if ($scope.recentTransactionsEnabled) getNotifications();
        })
      ];

      $scope.buyAndSellItems = buyAndSellService.getLinked();
      $scope.homeIntegrations = homeIntegrationsService.get();

      bitpayCardService.get({}, function(err, cards) {
        $scope.bitpayCardItems = cards;
      });

      configService.whenAvailable(function(config) {
        $scope.selectedPriceDisplay = config.wallet.settings.priceDisplay;
        $scope.recentTransactionsEnabled = config.recentTransactions.enabled;
        if ($scope.recentTransactionsEnabled) getNotifications();

        if (config.hideNextSteps.enabled) {
          $scope.nextStepsItems = null;
        } else {
          $scope.nextStepsItems = nextStepsService.get();
        }

        $scope.showServices = true;

        $timeout(function() {
          $ionicScrollDelegate.resize();
          $scope.$apply();
        }, 10);
      });
    };

    function onLeave (event, data) {
      lodash.each(listeners, function(x) {
        x();
      });
    };

    $scope.createdWithinPastDay = function(time) {
      return timeService.withinPastDay(time);
    };

    $scope.startFreshSend = function() {
      sendFlowService.clear();
      $state.go('tabs.send');
    }

    $scope.openExternalLink = function() {
      var url = 'https://github.com/Bitcoin-com/Wallet/releases/latest';
      var optIn = true;
      var title = gettextCatalog.getString('Update Available');
      var message = gettextCatalog.getString('An update to this app is available. For your security, please update to the latest version.');
      var okText = gettextCatalog.getString('View Update');
      var cancelText = gettextCatalog.getString('Go Back');
      externalLinkService.open(url, optIn, title, message, okText, cancelText);
    };

    $scope.openBannerUrl = function() {
      externalLinkService.open($scope.bannerUrl, false);
    };

    $scope.openNotificationModal = function(n) {
      wallet = profileService.getWallet(n.walletId);

      if (n.txid) {
        $state.transitionTo('tabs.wallet.tx-details', {
          txid: n.txid,
          walletId: n.walletId
        });
      } else {
        var txp = lodash.find($scope.txps, {
          id: n.txpId
        });
        if (txp) {
          txpModalService.open(txp);
        } else {
          ongoingProcess.set('loadingTxInfo', true);
          walletService.getTxp(wallet, n.txpId, function(err, txp) {
            var _txp = txp;
            ongoingProcess.set('loadingTxInfo', false);
            if (err) {
              $log.warn('No txp found');
              return popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Transaction not found'));
            }
            txpModalService.open(_txp);
          });
        }
      }
    };

    $scope.openWallet = function(wallet) {
      if (!wallet.isComplete()) {
        return $state.go('tabs.copayers', {
          walletId: wallet.credentials.walletId
        });
      }

      $state.go('tabs.wallet', {
        walletId: wallet.credentials.walletId
      });
    };

    var updateTxps = function() {
      profileService.getTxps({
        limit: 3
      }, function(err, txps, n) {
        if (err) $log.error(err);
        $scope.txps = txps;
        $scope.txpsN = n;
        $timeout(function() {
          $ionicScrollDelegate.resize();
          $scope.$apply();
        }, 10);
      })
    };

    var updateAllWallets = function(cb) {
      var wallets = [];
      $scope.walletsBtc = profileService.getWallets({coin: 'btc'});
      $scope.walletsBch = profileService.getWallets({coin: 'bch'});

      lodash.each($scope.walletsBtc, function(wBtc) {
        wallets.push(wBtc);
      });

      lodash.each($scope.walletsBch, function(wBch) {
        wallets.push(wBch);
      });

      if (lodash.isEmpty(wallets)) return;

      var i = wallets.length;
      var j = 0;

      lodash.each(wallets, function(wallet) {
        walletService.getStatus(wallet, {}, function(err, status) {
          if (err) {

            wallet.error = (err === 'WALLET_NOT_REGISTERED') ? gettextCatalog.getString('Wallet not registered') : bwcError.msg(err);

            $log.error(err);
          } else {
            wallet.error = null;
            wallet.status = status;

            // TODO service refactor? not in profile service
            profileService.setLastKnownBalance(wallet.id, wallet.status.totalBalanceStr, function() {});
          }
          if (++j == i) {
            updateTxps();
            if (cb !== undefined) {
              cb();
            }
          }
          $scope.walletsWithFunds = profileService.getWallets({hasFunds: true});
        });
      });
    };

    var updateWallet = function(wallet) {
      $log.debug('Updating wallet:' + wallet.name)
      walletService.getStatus(wallet, {}, function(err, status) {
        if (err) {
          $log.error(err);
          return;
        }
        wallet.status = status;
        updateTxps();
      });
    };

    var getNotifications = function() {
      profileService.getNotifications({
        limit: 3
      }, function(err, notifications, total) {
        if (err) {
          $log.error(err);
          return;
        }

        if (!notifications) return;

        var txIdList = [];

        for (var i=0; i<notifications.length; i++) {
            var txId = notifications[i].txid;
            if (txIdList.includes(txId)) {
                notifications.splice(i, 1);
                i = i - 1;
            } else {
                txIdList.push(txId)
            }
        }

        $scope.notifications = notifications;
        $timeout(function() {
          $ionicScrollDelegate.resize();
          $scope.$apply();
        }, 10);
      });
    };

    $scope.hideHomeTip = function() {
      storageService.setHomeTipAccepted('accepted', function() {
        $scope.homeTip = false;
        $timeout(function() {
          $scope.$apply();
        })
      });
    };

    $scope.onRefresh = function() {
      $timeout(function() {
        $scope.$broadcast('scroll.refreshComplete');
      }, 300);
      updateAllWallets();
    };

  });
<commit_msg>add update wallet<commit_after>'use strict';

angular.module('copayApp.controllers').controller('tabHomeController',
  function($rootScope, sendFlowService, $timeout, $scope, $state, $stateParams, $ionicScrollDelegate, $window, gettextCatalog, lodash, popupService, ongoingProcess, bannerService, externalLinkService, latestReleaseService, profileService, walletService, configService, $log, platformInfo, storageService, txpModalService, appConfigService, startupService, addressbookService, bwcError, nextStepsService, buyAndSellService, homeIntegrationsService, bitpayCardService, pushNotificationsService, timeService, $ionicNavBarDelegate) {
    var wallet;
    var listeners = [];
    var notifications = [];
    $scope.externalServices = {};
    $scope.openTxpModal = txpModalService.open;
    $scope.version = $window.version;
    $scope.name = appConfigService.nameCase;
    $scope.homeTip = $stateParams.fromOnboarding;
    $scope.isCordova = platformInfo.isCordova;
    $scope.isAndroid = platformInfo.isAndroid;
    $scope.isWindowsPhoneApp = platformInfo.isCordova && platformInfo.isWP;
    $scope.isNW = platformInfo.isNW;
    $scope.showServices = false;
    $scope.bannerIsLoading = true;
    $scope.bannerImageUrl = '';
    $scope.bannerUrl = '';

    $scope.$on("$ionicView.beforeEnter", onBeforeEnter);
    $scope.$on("$ionicView.enter", onEnter);
    $scope.$on("$ionicView.afterEnter", onAfterEnter);
    $scope.$on("$ionicView.leave", onLeave);

    function onAfterEnter () {
      startupService.ready();

      bannerService.getBanner(function (banner) {
        $scope.bannerImageUrl = banner.imageURL;
        $scope.bannerUrl = banner.url;
        $scope.bannerIsLoading = false;
      });
    };

    function onBeforeEnter (event, data) {

      if (!$scope.homeTip) {
        storageService.getHomeTipAccepted(function(error, value) {
          $scope.homeTip = (value == 'accepted') ? false : true;
        });
      }

      if ($scope.isNW) {
        latestReleaseService.checkLatestRelease(function(err, newRelease) {
          if (err) {
            $log.warn(err);
            return;
          }
          if (newRelease) {
            $scope.newRelease = true;
            $scope.updateText = gettextCatalog.getString('There is a new version of {{appName}} available', {
              appName: $scope.name
            });
          }
        });
      }
    };

    function onEnter(event, data) {
      $ionicNavBarDelegate.showBar(true);
      updateAllWallets();

      addressbookService.list(function(err, ab) {
        if (err) $log.error(err);
        $scope.addressbook = ab || {};
      });

      listeners = [
        $rootScope.$on('bwsEvent', function(e, walletId, type, n) {
          var wallet = profileService.getWallet(walletId);
          updateWallet(wallet);
          if ($scope.recentTransactionsEnabled) getNotifications();

        }),
        $rootScope.$on('Local/TxAction', function(e, walletId) {
          $log.debug('Got action for wallet ' + walletId);
          var wallet = profileService.getWallet(walletId);
          updateWallet(wallet);
          if ($scope.recentTransactionsEnabled) getNotifications();
        })
      ];

      $scope.buyAndSellItems = buyAndSellService.getLinked();
      $scope.homeIntegrations = homeIntegrationsService.get();

      bitpayCardService.get({}, function(err, cards) {
        $scope.bitpayCardItems = cards;
      });

      configService.whenAvailable(function(config) {
        $scope.selectedPriceDisplay = config.wallet.settings.priceDisplay;
        $scope.recentTransactionsEnabled = config.recentTransactions.enabled;
        if ($scope.recentTransactionsEnabled) getNotifications();

        if (config.hideNextSteps.enabled) {
          $scope.nextStepsItems = null;
        } else {
          $scope.nextStepsItems = nextStepsService.get();
        }

        $scope.showServices = true;

        $timeout(function() {
          $ionicScrollDelegate.resize();
          $scope.$apply();
        }, 10);
      });
    };

    function onLeave (event, data) {
      lodash.each(listeners, function(x) {
        x();
      });
    };

    $scope.createdWithinPastDay = function(time) {
      return timeService.withinPastDay(time);
    };

    $scope.startFreshSend = function() {
      sendFlowService.clear();
      $state.go('tabs.send');
    }

    $scope.openExternalLink = function() {
      var url = 'https://github.com/Bitcoin-com/Wallet/releases/latest';
      var optIn = true;
      var title = gettextCatalog.getString('Update Available');
      var message = gettextCatalog.getString('An update to this app is available. For your security, please update to the latest version.');
      var okText = gettextCatalog.getString('View Update');
      var cancelText = gettextCatalog.getString('Go Back');
      externalLinkService.open(url, optIn, title, message, okText, cancelText);
    };

    $scope.openBannerUrl = function() {
      externalLinkService.open($scope.bannerUrl, false);
    };

    $scope.openNotificationModal = function(n) {
      wallet = profileService.getWallet(n.walletId);

      if (n.txid) {
        $state.transitionTo('tabs.wallet.tx-details', {
          txid: n.txid,
          walletId: n.walletId
        });
      } else {
        var txp = lodash.find($scope.txps, {
          id: n.txpId
        });
        if (txp) {
          txpModalService.open(txp);
        } else {
          ongoingProcess.set('loadingTxInfo', true);
          walletService.getTxp(wallet, n.txpId, function(err, txp) {
            var _txp = txp;
            ongoingProcess.set('loadingTxInfo', false);
            if (err) {
              $log.warn('No txp found');
              return popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Transaction not found'));
            }
            txpModalService.open(_txp);
          });
        }
      }
    };

    $scope.openWallet = function(wallet) {
      if (!wallet.isComplete()) {
        return $state.go('tabs.copayers', {
          walletId: wallet.credentials.walletId
        });
      }

      $state.go('tabs.wallet', {
        walletId: wallet.credentials.walletId
      });
    };

    var updateTxps = function() {
      profileService.getTxps({
        limit: 3
      }, function(err, txps, n) {
        if (err) $log.error(err);
        $scope.txps = txps;
        $scope.txpsN = n;
        $timeout(function() {
          $ionicScrollDelegate.resize();
          $scope.$apply();
        }, 10);
      })
    };

    var updateAllWallets = function(cb) {
      var wallets = [];
      $scope.walletsBtc = profileService.getWallets({coin: 'btc'});
      $scope.walletsBch = profileService.getWallets({coin: 'bch'});

      lodash.each($scope.walletsBtc, function(wBtc) {
        wallets.push(wBtc);
      });

      lodash.each($scope.walletsBch, function(wBch) {
        wallets.push(wBch);
      });

      if (lodash.isEmpty(wallets)) return;

      var i = wallets.length;
      var j = 0;

      lodash.each(wallets, function(wallet) {
        walletService.getStatus(wallet, {}, function(err, status) {
          if (err) {

            wallet.error = (err === 'WALLET_NOT_REGISTERED') ? gettextCatalog.getString('Wallet not registered') : bwcError.msg(err);

            $log.error(err);
          } else {
            wallet.error = null;
            wallet.status = status;

            // TODO service refactor? not in profile service
            profileService.setLastKnownBalance(wallet.id, wallet.status.totalBalanceStr, function() {});
          }
          if (++j == i) {
            updateTxps();
            if (cb !== undefined) {
              cb();
            }
          }
          $scope.walletsWithFunds = profileService.getWallets({hasFunds: true});
        });
      });
    };

    var updateWallet = function(wallet) {
      $log.debug('Updating wallet:' + wallet.name)
      walletService.getStatus(wallet, {}, function(err, status) {
        if (err) {
          $log.error(err);
          return;
        }
        wallet.status = status;
        updateTxps();
      });
    };

    var getNotifications = function() {
      profileService.getNotifications({
        limit: 3
      }, function(err, notifications, total) {
        if (err) {
          $log.error(err);
          return;
        }

        if (!notifications) return;

        var txIdList = [];

        for (var i=0; i<notifications.length; i++) {
            var txId = notifications[i].txid;
            if (txIdList.includes(txId)) {
                notifications.splice(i, 1);
                i = i - 1;
            } else {
                txIdList.push(txId)
            }
        }

        $scope.notifications = notifications;
        $timeout(function() {
          $ionicScrollDelegate.resize();
          $scope.$apply();
        }, 10);
      });
    };

    $scope.hideHomeTip = function() {
      storageService.setHomeTipAccepted('accepted', function() {
        $scope.homeTip = false;
        $timeout(function() {
          $scope.$apply();
        })
      });
    };

    $scope.onRefresh = function() {
      $timeout(function() {
        $scope.$broadcast('scroll.refreshComplete');
      }, 300);
      updateAllWallets();
    };

  });
<|endoftext|>


<commit_before>const e = require('eris')

// Please edit config.json with your token.
const conf = JSON.parse(require('fs').readFileSync('config.json', 'utf8'))

// You may change this desc, the owner, and prefix.
const bot = new e.CommandClient(conf.token, {}, {
  description: conf.desc,
  owner: 'Someone',
  prefix: conf.prefix
})

bot.on('ready', () => {
  console.log('dbot - discord responded with ready')
})

bot.registerCommand('about', 'my name is dbot and I live in `' + require('os').hostname() + '` https://github.com/tilda/dbot', {
  description: 'who am I? run this to find out',
  fullDescription: ':thinking:'
})

bot.registerCommand('generic', 'generic sucks', {
  description: 'what is generic',
  fullDescription: 'lmao im gonan die'
})

bot.on('messageCreate', (msg, args, err) => {
  if (msg.content === conf.prefix + 'shutdown') {
    if (msg.author.id === conf.owner) {
      bot.createMessage(msg.channel.id, 'ok bye')
      process.exit(1)
    } else {
      bot.createMessage(msg.channel.id, 'no')
    }
  }
  if (msg.content === conf.prefix + 'exec') {
    if (msg.author.id === conf.owner) {
      const lol = require('shelljs').exec(args.toString())
      if (lol.code !== 0) {
        bot.createMessage(msg.channel.id, 'Error!\n\`\`\`' + err.toString() + '\n\`\`\`')
      } else {
	 bot.createMessage(msg.channel.id, 'Success \`\`\`\n' + lol '\n\`\`\`')
      }}})

bot.connect()
<commit_msg>[bot, core, eval] oh wait what<commit_after>const e = require('eris')

// Please edit config.json with your token.
const conf = JSON.parse(require('fs').readFileSync('config.json', 'utf8'))

// You may change this desc, the owner, and prefix.
const bot = new e.CommandClient(conf.token, {}, {
  description: conf.desc,
  owner: 'Someone',
  prefix: conf.prefix
})

bot.on('ready', () => {
  console.log('dbot - discord responded with ready')
})

bot.registerCommand('about', 'my name is dbot and I live in `' + require('os').hostname() + '` https://github.com/tilda/dbot', {
  description: 'who am I? run this to find out',
  fullDescription: ':thinking:'
})

bot.registerCommand('generic', 'generic sucks', {
  description: 'what is generic',
  fullDescription: 'lmao im gonan die'
})

bot.on('messageCreate', (msg, args, err) => {
  if (msg.content === conf.prefix + 'shutdown') {
    if (msg.author.id === conf.owner) {
      bot.createMessage(msg.channel.id, 'ok bye')
      process.exit(1)
    } else {
      bot.createMessage(msg.channel.id, 'no')
    }
  }
  if (msg.content === conf.prefix + 'exec') {
    if (msg.author.id === conf.owner) {
      const lol = require('shelljs').exec(args.toString())
      if (lol.code !== 0) {
        bot.createMessage(msg.channel.id, 'Error!\n\`\`\`' + err.toString() + '\n\`\`\`')
      } else {
	 bot.createMessage(msg.channel.id, 'Success \`\`\`\n' + lol + '\n\`\`\`')
      }}})

bot.connect()
<|endoftext|>


<commit_before>exports.plugin = function(cli)
{
    cli.loading = function(label, callback)
    {
        if(typeof label == 'function')
        {
            callback = label;
            label = '';
        }

        function done(success)
        {
            var message = arguments.length ? (success ? 'success'.green.bold : 'fail'.red.bold ) : 'done'.grey.bold;

            clearInterval(interval);
            cli.replaceLine(label+message);
            cli.newLine();
        }

        if(callback) callback(done);

        var seq = '–\|/';
        pos = 0,
        interval = setInterval(function()
        {
            cli.replaceLine(label+'['+seq[pos++%seq.length].blue+'] ');
        }, 200);

        return {
            done: done
        };

    }
}<commit_msg>label shouldn't be required<commit_after>exports.plugin = function(cli)
{
    cli.loading = function(label, callback)
    {

        if(typeof label == 'function')
        {
            callback = label;
            label = '';
        }

        if(!label) label = '';

        function done(success)
        {
            var message = arguments.length ? (success ? 'success'.green.bold : 'fail'.red.bold ) : 'done'.grey.bold;

            clearInterval(interval);
            cli.replaceLine(label+message);
            cli.newLine();
        }

        if(callback) callback(done);

        var seq = '–\|/';
        pos = 0,
        interval = setInterval(function()
        {
            cli.replaceLine(label+'['+seq[pos++%seq.length].blue+'] ');
        }, 200);

        return {
            done: done
        };

    }
}<|endoftext|>