<commit_before>var methods = {};

var validateOne = function(validatorFunction, fieldName) {
  // Get field value.
  var value = this.get(fieldName);

  try {
    // Run validator function which throws exception which we have to catch and
    // add error message to appropriate field.
    validatorFunction.call(this, fieldName, value);

    // If a field's validation didn't throw an exception then clear an error
    // message for the given field.
    this._errors.delete(fieldName);

    return true;
  } catch (e) {
    if (e instanceof ValidationError) {
      this._errors.set(fieldName, e.message);
    } else {
      throw e;
    }

    return false;
  }
};

methods.validate = function(fieldName) {
  // Run validation for current and parent classes. The "isValid" variable will
  // be set to true when all validators for all classes passed validation.
  var isValid = Astro.utils.everyClass(this.constructor, function(Class) {
    // Get list of all validators for given class.
    var validators = Class.getValidators();

    if (fieldName) {
      // Get validation function for given field name.
      var validatorFunction = validators[fieldName];

      // Validate field only if there is validation function.
      if (validatorFunction) {
        return validateOne.call(this, validatorFunction, fieldName);
      } else {
        return true;
      }
    } else {
      // Take validators and run each one.
      return _.every(validators, validateOne, this);
    }
  }, this);

  return isValid;
};

methods.getValidationError = function() {
  console.warn('getValidationError had been renamed to getError');
  return this.getError.apply(this, arguments);
};

methods.hasValidationError = function() {
  console.warn('hasValidationError had been renamed to hasError');
  return this.hasError.apply(this, arguments);
};

methods.hasValidationErrors = function() {
  console.warn('hasValidationErrors had been renamed to hasErrors');
  return this.hasErrors.apply(this, arguments);
};

methods.getError = function(fieldName) {
  return this._errors.get(fieldName);
};

methods.getErrors = function() {
  return this._errors.all();
};

methods.hasError = function(fieldName) {
  return this._errors.has(fieldName);
};

methods.hasErrors = function() {
  return this._errors.size > 0;
};

var events = {};

events.tojsonvalue = function(e) {
  var self = this;

  Tracker.nonreactive(function() {
    e.data.errors = self._errors.all();
  });
};

events.fromjsonvalue = function(e) {
  this._errors.set(e.data.errors);
};

onInitModule = function() {
  _.extend(Astro.BaseClass.prototype, methods);

  Astro.on('tojsonvalue', events.tojsonvalue);
  Astro.on('fromjsonvalue', events.fromjsonvalue);
};
<commit_msg>Add throwException and catchException methods<commit_after>var methods = {};

var validateOne = function(validatorFunction, fieldName) {
  // Get field value.
  var value = this.get(fieldName);

  try {
    // Run validator function which throws exception which we have to catch and
    // add error message to appropriate field.
    validatorFunction.call(this, fieldName, value);

    // If a field's validation didn't throw an exception then clear an error
    // message for the given field.
    this._errors.delete(fieldName);

    return true;
  } catch (e) {
    if (e instanceof ValidationError) {
      this._errors.set(fieldName, e.message);
    } else {
      throw e;
    }

    return false;
  }
};

methods.validate = function(fieldName) {
  // Run validation for current and parent classes. The "isValid" variable will
  // be set to true when all validators for all classes passed validation.
  var isValid = Astro.utils.everyClass(this.constructor, function(Class) {
    // Get list of all validators for given class.
    var validators = Class.getValidators();

    if (fieldName) {
      // Get validation function for given field name.
      var validatorFunction = validators[fieldName];

      // Validate field only if there is validation function.
      if (validatorFunction) {
        return validateOne.call(this, validatorFunction, fieldName);
      } else {
        return true;
      }
    } else {
      // Take validators and run each one.
      return _.every(validators, validateOne, this);
    }
  }, this);

  return isValid;
};

methods.getValidationError = function() {
  console.warn('getValidationError had been renamed to getError');
  return this.getError.apply(this, arguments);
};

methods.hasValidationError = function() {
  console.warn('hasValidationError had been renamed to hasError');
  return this.hasError.apply(this, arguments);
};

methods.hasValidationErrors = function() {
  console.warn('hasValidationErrors had been renamed to hasErrors');
  return this.hasErrors.apply(this, arguments);
};

methods.getError = function(fieldName) {
  return this._errors.get(fieldName);
};

methods.getErrors = function() {
  return this._errors.all();
};

methods.hasError = function(fieldName) {
  return this._errors.has(fieldName);
};

methods.hasErrors = function() {
  return this._errors.size > 0;
};

methods.throwException = function() {
  throw new Meteor.Error('validation-error', this.getErrors());
};

methods.catchException = function(exception) {
  if (!(exception instanceof Meteor.Error) ||
    exception.error !== 'validation-error' ||
    !_.isObject(exception.reason)
  ) {
    return;
  }

  this._errors.set(exception.reason);
};

var events = {};

events.tojsonvalue = function(e) {
  var self = this;

  Tracker.nonreactive(function() {
    e.data.errors = self._errors.all();
  });
};

events.fromjsonvalue = function(e) {
  this._errors.set(e.data.errors);
};

onInitModule = function() {
  _.extend(Astro.BaseClass.prototype, methods);

  Astro.on('tojsonvalue', events.tojsonvalue);
  Astro.on('fromjsonvalue', events.fromjsonvalue);
};
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var request      = require('request');
var assert       = require('assert');
var express      = require('express');
var norma        = require('norma');
var debug        = require('debug')('waif:service');
var temp         = require('temp').track();
var isUrl        = require('is-url');
var util         = require('util');
var _            = require('lodash');

/**
* Service constructor.
*
* Instances will contain a map to all of the
* services that have been mounted onto the
* system.
*/
function Service(name) {
  assert(name, "service not supplied with name");

  debug('new service: %s', name);
  this.name       = name;
  this.options    = {};
  this.middleware = [];
  this.type       = null;
  this.connType   = null;
  this.url        = null;
  this.running    = false;
  return this;
}

// Each service is also an event emitter,
// to allow you to get notifications of
// start, stop and configure.
util.inherits(Service, EventEmitter);

Service.createInstance = function(name) {
  var _service = new Service(name);

  // called directly
  var fn = function() {
    debug('request proxy on service: %s', name);
    return _service.request.apply(_service, arguments);
  };

  fn.instance = _service;
  var proxyMethods = [
    'request', 'forward', 'listen', 'use',
    'start', 'stop', 'on', 'config'
  ];

  _(proxyMethods).each(function(method) {
    fn[method] = function() {
      _service[method].apply(_service, arguments);
      return fn;
    };
  });
  return fn;
};

module.exports = Service;

// make a request against a service
Service.prototype.request = function() {
  assert.notEqual(this.type, null, 'service:'+this.name+' not mounted.');
  assert.notEqual(this.url, null, 'service:'+this.name+' has no url.');
  var args = norma('s, .*', arguments);

  var proto = (this.connType === 'socket') ? 'unix:/' : 'http://';
  var host = (this.connType === 'port') ? '127.0.0.1:' : '';

  args[0] = proto + host + this.url + args[0];

  debug('request on service: %s, %o', this.name, args);
  return request.apply(request, args);
};

// Get the URL to direct to.
Service.prototype.getUrl = function() {

  assert.notEqual(this.type, null, 'service:'+this.name+' not mounted.');
  return (this.type === 'listen') ? this.listenOn: this.forwardTo;
};

// Populate the target url.
Service.prototype.prepareUrl = function(url) {
  debug('prepare url request on service: %s, %s', this.name, url);
  if (!url) {
    this.connType = 'socket';
    return temp.path();
  } else if (_.isNumber(url)) {
    this.connType = 'port';
    return url;
  } else if (isUrl(url)) {
    this.connType = 'url';
    return url;
  }
  return false;
};

// mount services or paths
Service.prototype.use = function() {
  var args = norma('s?, f}', arguments);
  this.middleware.push(args);
  debug('use middlware on service: %s, %s', this.name, args);
  return this;
};

// Mount a service on a unix domain socket.
Service.prototype.listen = function(listenOn) {
  debug('listen on service: %s', this.name);
  assert.equal(this.type, null, 'service:'+this.name+' couldn\'t listen.');

  this.type = 'listen';
  this.url = this.prepareUrl(listenOn);
  return this;
};

// Mount a service on a http server.
Service.prototype.forward = function(forwardTo) {
  debug('forward on service: %s', this.name);
  assert.equal(this.type, null, 'service:'+this.name+' couldn\'t forward.');

  this.type = 'forward';
  this.url = this.prepareUrl(forwardTo);
  return this;
};

// Set configuration. Emits an event to handle.
Service.prototype.config = function(options) {
  debug('config on service: %s', this.name);
  this.emit('config', options);
  return this;
};

// builds an express app if needed
// emits a start event
Service.prototype.start = function(server) {

  if (this.type === 'listen') {
    debug('create app for service: %s', this.name);
    this.app = express();

    _(this.middleware).each(_use, this);

    debug('listen for service on url: %s, %s', this.name, this.url);
    this.app.listen(this.url);
  }

  debug('start on service: %s', this.name);
  this.running = true;
  this.emit('start');

  return this;

  function _use(mw) {
    this.use.apply(this, mw);
  }
};

// stops listening on ports/sockets
// emits a stop event
Service.prototype.stop = function() {
  debug('stop on service: %s', this.name);
  this.emit('stop');
  this.running = false;
  if (this.type === 'listen') {
    this.app && this.app.close();
  }
  return this;
};
<commit_msg>async listen<commit_after>var EventEmitter = require('events').EventEmitter;
var request      = require('request');
var assert       = require('assert');
var express      = require('express');
var norma        = require('norma');
var debug        = require('debug')('waif:service');
var temp         = require('temp').track();
var isUrl        = require('is-url');
var util         = require('util');
var _            = require('lodash');

/**
* Service constructor.
*
* Instances will contain a map to all of the
* services that have been mounted onto the
* system.
*/
function Service(name) {
  assert(name, "service not supplied with name");

  debug('new service: %s', name);
  this.name       = name;
  this.options    = {};
  this.middleware = [];
  this.type       = null;
  this.connType   = null;
  this.url        = null;
  this.running    = false;
  return this;
}

// Each service is also an event emitter,
// to allow you to get notifications of
// start, stop and configure.
util.inherits(Service, EventEmitter);

Service.createInstance = function(name) {
  var _service = new Service(name);

  // called directly
  var fn = function() {
    debug('request proxy on service: %s', name);
    return _service.request.apply(_service, arguments);
  };

  fn.instance = _service;
  var proxyMethods = [
    'request', 'forward', 'listen', 'use',
    'start', 'stop', 'on', 'config'
  ];

  _(proxyMethods).each(function(method) {
    fn[method] = function() {
      _service[method].apply(_service, arguments);
      return fn;
    };
  });
  return fn;
};

module.exports = Service;

// make a request against a service
Service.prototype.request = function() {
  assert.notEqual(this.type, null, 'service:'+this.name+' not mounted.');
  assert.notEqual(this.url, null, 'service:'+this.name+' has no url.');
  var args = norma('s, .*', arguments);

  var proto = (this.connType === 'socket') ? 'unix:/' : 'http://';
  var host = (this.connType === 'port') ? '127.0.0.1:' : '';

  args[0] = proto + host + this.url + args[0];

  debug('request on service: %s, %o', this.name, args);
  return request.apply(request, args);
};

// Get the URL to direct to.
Service.prototype.getUrl = function() {

  assert.notEqual(this.type, null, 'service:'+this.name+' not mounted.');
  return (this.type === 'listen') ? this.listenOn: this.forwardTo;
};

// Populate the target url.
Service.prototype.prepareUrl = function(url) {
  debug('prepare url request on service: %s, %s', this.name, url);
  if (!url) {
    this.connType = 'socket';
    return temp.path();
  } else if (_.isNumber(url)) {
    this.connType = 'port';
    return url;
  } else if (isUrl(url)) {
    this.connType = 'url';
    return url;
  }
  return false;
};

// mount services or paths
Service.prototype.use = function() {
  var args = norma('s?, f}', arguments);
  this.middleware.push(args);
  debug('use middlware on service: %s', this.name);
  return this;
};

// Mount a service on a unix domain socket.
Service.prototype.listen = function(listenOn) {
  debug('listen on service: %s', this.name);
  assert.equal(this.type, null, 'service:'+this.name+' couldn\'t listen.');

  this.type = 'listen';
  this.url = this.prepareUrl(listenOn);
  return this;
};

// Mount a service on a http server.
Service.prototype.forward = function(forwardTo) {
  debug('forward on service: %s', this.name);
  assert.equal(this.type, null, 'service:'+this.name+' couldn\'t forward.');

  this.type = 'forward';
  this.url = this.prepareUrl(forwardTo);
  return this;
};

// Set configuration. Emits an event to handle.
Service.prototype.config = function(options) {
  debug('config on service: %s', this.name);
  this.emit('config', options);
  return this;
};

// builds an express app if needed
// emits a start event
Service.prototype.start = function(server) {

  var name = this.name;
  var url = this.url;

  if (this.type === 'listen') {
    debug('create app for service: %s', this.name);

    this.app = express();

    _(this.middleware).each(_use, this);

    this.app.listen(url, function(err) {
      debug('listen for service on url: %s, %s', name, url);
      assert.equal(err, null, 'service:'+name+' couldn\'t listen on '+url);
    });
  }

  debug('start on service: %s', this.name);
  this.running = true;
  this.emit('start');

  return this;

  function _use(mw) {
    this.use.apply(this, mw);
  }
};

// stops listening on ports/sockets
// emits a stop event
Service.prototype.stop = function() {
  debug('stop on service: %s', this.name);
  this.emit('stop');
  this.running = false;
  if (this.type === 'listen') {
    this.app && this.app.close();
  }
  return this;
};
<|endoftext|>


<commit_before>/* global describe, it, xit */
/* jslint node: true, esnext: true */

"use strict";

/*
 * Just test if the message will be passed through the interceptor
 */

const chai = require('chai'),
  assert = chai.assert,
  expect = chai.expect,
  should = chai.should(),
  InterceptorUnderTest = require('../index').Interceptor,
  MockReceiveInterceptor = require('kronos-test-interceptor').MockReceiveInterceptor;

const stepMock = {
  "name": "dummy step name",
  "type": "dummy step type"
};

const checkProperties = {
  "config": {
    "keyHashFields": ["first", "last"],
    "keyHashName": "__key",
    "contentHashFields": ["first", "last", "friends"],
    "contentHashName": "__content",
    "scopeHashFields": ["street"],
    "scopeHashName": "__scope",
    "multiRowFields": ["friends"]
  }
};

describe('Interceptor test', function () {

  it('Create', function () {
    const endpoint = {
      "owner": stepMock,
      "name": "gumboIn"
    };
    const messageHandler = new InterceptorUnderTest(endpoint, checkProperties);
    assert.ok(messageHandler);
  });

  it('Send message', function (done) {
    const endpoint = {
      "owner": stepMock,
      "name": "gumboIn"
    };

    const sendMessage = {
      "info": "first message"
    };

    const messageHandler = new InterceptorUnderTest(endpoint, checkProperties);
    const mockReceive = new MockReceiveInterceptor(function (request, oldRequest) {

      assert.ok(request);

      assert.deepEqual(request, {
        "info": "first message"
      });
      done();
    });

    messageHandler.connected = mockReceive;

    messageHandler.receive(sendMessage);

  });

});
<commit_msg>fix(constructor): Changed the order of config, and endpoint<commit_after>/* global describe, it, xit */
/* jslint node: true, esnext: true */

"use strict";

/*
 * Just test if the message will be passed through the interceptor
 */

const chai = require('chai'),
  assert = chai.assert,
  expect = chai.expect,
  should = chai.should(),
  InterceptorUnderTest = require('../index').Interceptor,
  MockReceiveInterceptor = require('kronos-test-interceptor').MockReceiveInterceptor;

const stepMock = {
  "name": "dummy step name",
  "type": "dummy step type"
};

const checkProperties = {
  "config": {
    "keyHashFields": ["first", "last"],
    "keyHashName": "__key",
    "contentHashFields": ["first", "last", "friends"],
    "contentHashName": "__content",
    "scopeHashFields": ["street"],
    "scopeHashName": "__scope",
    "multiRowFields": ["friends"]
  }
};

describe('Interceptor test', function () {

  it('Create', function () {
    const endpoint = {
      "owner": stepMock,
      "name": "gumboIn"
    };
    const messageHandler = new InterceptorUnderTest(checkProperties, endpoint);
    assert.ok(messageHandler);
  });

  it('Send message', function (done) {
    const endpoint = {
      "owner": stepMock,
      "name": "gumboIn"
    };

    const sendMessage = {
      "info": "first message"
    };

    const messageHandler = new InterceptorUnderTest(checkProperties, endpoint);
    const mockReceive = new MockReceiveInterceptor(function (request, oldRequest) {

      assert.ok(request);

      assert.deepEqual(request, {
        "info": "first message"
      });
      done();
    });

    messageHandler.connected = mockReceive;

    messageHandler.receive(sendMessage);

  });

});
<|endoftext|>


<commit_before><commit_msg>feat(gatsby-source-shopify): Add compareAtPrice to presentment prices (#20144)<commit_after><|endoftext|>


<commit_before>// Export old to new forum id mappings into levelDB
//

'use strict';

const _           = require('lodash');
const co          = require('co');
const level       = require('level');
const mkdirp      = require('mkdirp');
const path        = require('path');
const pump        = require('pump');
const through2    = require('through2');
const progress    = require('./_lib/utils').progress;

////////////////////////////////////////////////////////////////////////////////

module.exports.parserParameters  = {
  addHelp:      true,
  help:         'export mappings into levelDB',
  description:  'Export old to new forum id mappings into levelDB'
};

module.exports.commandLineArguments = [
  {
    args: [ '-d', '--dest' ],
    options: {
      help:     'Database path',
      type:     'string',
      required: true
    }
  }
];

module.exports.run = co.wrap(function* (N, args) {
  let total, bar, ldb = {};

  yield N.wire.emit('init:models', N);

  mkdirp.sync(args.dest);

  //
  // Export topic mappings
  //
  N.logger.info('Loading topics into memory');

  [ 'topics', 'posts', 'avatars', 'albums', 'attachments', 'filedataids', 'pictureaids', 'blogaids' ].forEach(name => {
    ldb[name] = level(path.join(args.dest, name), {
      keyEncoding:   'json',
      valueEncoding: 'json'
    });
  });

  let all_topics    = yield N.models.forum.Topic.find().select('section hid').lean(true);
  let topics_by_hid = _.keyBy(all_topics, 'hid');
  let topics_by_id  = _.keyBy(all_topics, '_id');

  let sections_by_id = _.keyBy(
    yield N.models.forum.Section.find().select('_id hid').lean(true),
    '_id'
  );

  let batch = ldb.topics.batch();

  Object.keys(topics_by_hid).forEach(topic_hid => {
    let section_id = topics_by_hid[topic_hid].section;

    batch.put(topic_hid, { section: sections_by_id[section_id].hid });
  });

  N.logger.info('Exporting topic mappings');

  batch.write();

  //
  // Export post mappings
  //
  N.logger.info('Exporting post mappings');

  total = yield N.models.vbconvert.PostMapping.count();
  bar = progress(' posts :current/:total [:bar] :percent', total);

  yield new Promise((resolve, reject) => {
    pump(
      N.models.vbconvert.PostMapping.collection.find({}, {
        mysql_id: 1,
        topic_id: 1,
        post_hid: 1
      }).stream(),

      through2.obj((post, enc, callback) => {
        bar.tick();

        ldb.posts.put(post.mysql_id, {
          topic: topics_by_id[post.topic_id].hid,
          post:  post.post_hid
        });

        callback();
      }),

      err => {
        if (err) reject(err);
        else resolve();
      }
    );
  });

  bar.terminate();

  //
  // Export user avatar ids
  //
  N.logger.info('Exporting user avatar ids');

  let users_by_id = _.keyBy(
    yield N.models.users.User.find().select('_id hid avatar_id').lean(true),
    '_id'
  );

  batch = ldb.avatars.batch();

  Object.keys(users_by_id)
    .filter(user_id => users_by_id[user_id].avatar_id)
    .forEach(user_id => {
      batch.put(users_by_id[user_id].hid, { avatar: users_by_id[user_id].avatar_id });
    });

  batch.write();

  //
  // Export album mappings
  //
  N.logger.info('Exporting album mappings');

  total = yield N.models.vbconvert.AlbumMapping.count();
  bar = progress(' albums :current/:total [:bar] :percent', total);

  yield new Promise((resolve, reject) => {
    pump(
      N.models.vbconvert.AlbumMapping.collection.find({}).stream(),

      through2.obj((albummap, enc, callback) => {
        N.models.users.Album.findById(albummap.mongo)
            .select('user_id')
            .lean(true)
            .exec(function (err, album) {

          if (err) {
            callback(err);
            return;
          }

          bar.tick();

          let user_hid = users_by_id[album.user_id].hid;

          ldb.albums.put(albummap.mysql, { user: user_hid, album: albummap.mongo });
          callback();
        });
      }),

      err => {
        if (err) reject(err);
        else resolve();
      }
    );
  });

  bar.terminate();

  //
  // Export file mappings
  //
  N.logger.info('Exporting file mappings');

  total = yield N.models.vbconvert.FileMapping.count();
  bar = progress(' files :current/:total [:bar] :percent', total);

  yield new Promise((resolve, reject) => {
    pump(
      N.models.vbconvert.FileMapping.collection.aggregate([ {
        $lookup: {
          from: 'users.mediainfos',
          localField: 'media_id',
          foreignField: '_id',
          as: 'media'
        }
      } ]).stream(),

      through2.obj((file, enc, callback) => {
        bar.tick();

        ldb.filedataids.put(file.filedataid, { attachment: file.attachmentid });

        if (file.pictureaid_legacy) {
          ldb.pictureaids.put(file.pictureaid_legacy, { attachment: file.attachmentid });
        }

        if (file.blogaid_legacy) {
          ldb.blogaids.put(file.blogaid_legacy, { attachment: file.attachmentid });
        }

        let user_hid = users_by_id[file.media[0].user_id].hid;

        ldb.attachments.put(file.attachmentid, { user: user_hid, media: file.media_id });
        callback();
      }),

      err => {
        if (err) reject(err);
        else resolve();
      }
    );
  });

  bar.terminate();

  yield Object.keys(ldb).map(name => new Promise((resolve, reject) => {
    ldb[name].close(err => {
      if (err) reject(err);
      else resolve();
    });
  }));

  N.logger.info('Export finished');

  process.exit(0);
});
<commit_msg>Don't use json for leveldb keys<commit_after>// Export old to new forum id mappings into levelDB
//

'use strict';

const _           = require('lodash');
const co          = require('co');
const level       = require('level');
const mkdirp      = require('mkdirp');
const path        = require('path');
const pump        = require('pump');
const through2    = require('through2');
const progress    = require('./_lib/utils').progress;

////////////////////////////////////////////////////////////////////////////////

module.exports.parserParameters  = {
  addHelp:      true,
  help:         'export mappings into levelDB',
  description:  'Export old to new forum id mappings into levelDB'
};

module.exports.commandLineArguments = [
  {
    args: [ '-d', '--dest' ],
    options: {
      help:     'Database path',
      type:     'string',
      required: true
    }
  }
];

module.exports.run = co.wrap(function* (N, args) {
  let total, bar, ldb = {};

  yield N.wire.emit('init:models', N);

  mkdirp.sync(args.dest);

  //
  // Export topic mappings
  //
  N.logger.info('Loading topics into memory');

  [ 'topics', 'posts', 'avatars', 'albums', 'attachments', 'filedataids', 'pictureaids', 'blogaids' ].forEach(name => {
    ldb[name] = level(path.join(args.dest, name), {
      valueEncoding: 'json'
    });
  });

  let all_topics    = yield N.models.forum.Topic.find().select('section hid').lean(true);
  let topics_by_hid = _.keyBy(all_topics, 'hid');
  let topics_by_id  = _.keyBy(all_topics, '_id');

  let sections_by_id = _.keyBy(
    yield N.models.forum.Section.find().select('_id hid').lean(true),
    '_id'
  );

  let batch = ldb.topics.batch();

  Object.keys(topics_by_hid).forEach(topic_hid => {
    let section_id = topics_by_hid[topic_hid].section;

    batch.put(topic_hid, { section: sections_by_id[section_id].hid });
  });

  N.logger.info('Exporting topic mappings');

  batch.write();

  //
  // Export post mappings
  //
  N.logger.info('Exporting post mappings');

  total = yield N.models.vbconvert.PostMapping.count();
  bar = progress(' posts :current/:total [:bar] :percent', total);

  yield new Promise((resolve, reject) => {
    pump(
      N.models.vbconvert.PostMapping.collection.find({}, {
        mysql_id: 1,
        topic_id: 1,
        post_hid: 1
      }).stream(),

      through2.obj((post, enc, callback) => {
        bar.tick();

        ldb.posts.put(post.mysql_id, {
          topic: topics_by_id[post.topic_id].hid,
          post:  post.post_hid
        });

        callback();
      }),

      err => {
        if (err) reject(err);
        else resolve();
      }
    );
  });

  bar.terminate();

  //
  // Export user avatar ids
  //
  N.logger.info('Exporting user avatar ids');

  let users_by_id = _.keyBy(
    yield N.models.users.User.find().select('_id hid avatar_id').lean(true),
    '_id'
  );

  batch = ldb.avatars.batch();

  Object.keys(users_by_id)
    .filter(user_id => users_by_id[user_id].avatar_id)
    .forEach(user_id => {
      batch.put(users_by_id[user_id].hid, { avatar: users_by_id[user_id].avatar_id });
    });

  batch.write();

  //
  // Export album mappings
  //
  N.logger.info('Exporting album mappings');

  total = yield N.models.vbconvert.AlbumMapping.count();
  bar = progress(' albums :current/:total [:bar] :percent', total);

  yield new Promise((resolve, reject) => {
    pump(
      N.models.vbconvert.AlbumMapping.collection.find({}).stream(),

      through2.obj((albummap, enc, callback) => {
        N.models.users.Album.findById(albummap.mongo)
            .select('user_id')
            .lean(true)
            .exec(function (err, album) {

          if (err) {
            callback(err);
            return;
          }

          bar.tick();

          let user_hid = users_by_id[album.user_id].hid;

          ldb.albums.put(albummap.mysql, { user: user_hid, album: albummap.mongo });
          callback();
        });
      }),

      err => {
        if (err) reject(err);
        else resolve();
      }
    );
  });

  bar.terminate();

  //
  // Export file mappings
  //
  N.logger.info('Exporting file mappings');

  total = yield N.models.vbconvert.FileMapping.count();
  bar = progress(' files :current/:total [:bar] :percent', total);

  yield new Promise((resolve, reject) => {
    pump(
      N.models.vbconvert.FileMapping.collection.aggregate([ {
        $lookup: {
          from: 'users.mediainfos',
          localField: 'media_id',
          foreignField: '_id',
          as: 'media'
        }
      } ]).stream(),

      through2.obj((file, enc, callback) => {
        bar.tick();

        ldb.filedataids.put(file.filedataid, { attachment: file.attachmentid });

        if (file.pictureaid_legacy) {
          ldb.pictureaids.put(file.pictureaid_legacy, { attachment: file.attachmentid });
        }

        if (file.blogaid_legacy) {
          ldb.blogaids.put(file.blogaid_legacy, { attachment: file.attachmentid });
        }

        let user_hid = users_by_id[file.media[0].user_id].hid;

        ldb.attachments.put(file.attachmentid, { user: user_hid, media: file.media_id });
        callback();
      }),

      err => {
        if (err) reject(err);
        else resolve();
      }
    );
  });

  bar.terminate();

  yield Object.keys(ldb).map(name => new Promise((resolve, reject) => {
    ldb[name].close(err => {
      if (err) reject(err);
      else resolve();
    });
  }));

  N.logger.info('Export finished');

  process.exit(0);
});
<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';

var pkg = require('./package.json');
var AV_CONFIG_VERSION = '3.1.2';

//Using exclusion patterns slows down Grunt significantly
//instead of creating a set of patterns like '**/*.js' and '!**/node_modules/**'
//this method is used to create a set of inclusive patterns for all subdirectories
//skipping node_modules, bower_components, dist, and any .dirs
//This enables users to create any directory structure they desire.
var createFolderGlobs = function(fileTypePatterns) {
  fileTypePatterns = Array.isArray(fileTypePatterns) ? fileTypePatterns : [fileTypePatterns];
  var ignore = ['node_modules','bower_components','dist','temp'];
  var fs = require('fs');
  return fs.readdirSync(process.cwd())
          .map(function(file){
            if (ignore.indexOf(file) !== -1 ||
                file.indexOf('.') === 0 ||
                !fs.lstatSync(file).isDirectory()) {
              return null;
            } else {
              return fileTypePatterns.map(function(pattern) {
                return file + '/**/' + pattern;
              });
            }
          })
          .filter(function(patterns){
            return patterns;
          })
          .concat(fileTypePatterns);
};

module.exports = function (grunt) {

  // load all grunt tasks
  require('load-grunt-tasks')(grunt);

  // custom grunt task to check avConfig.js
  grunt.registerTask('check_config', function() {
    var fs = require('fs');
    var done = this.async();
    grunt.log.ok('Checking avConfig.js...');
    var conf = fs.readFile('avConfig.js', function(err, data) {
        if (err) {
            grunt.log.error('No avConfig.js file found');
            done(false);
        } else {
            var match = data.toString().match(/AV_CONFIG_VERSION = [\'\"]([\w\.]*)[\'\"];/);
            if (!match) {
                grunt.log.error('Invalid avConfig.js version');
            } else {
                var v = match[1];
                if (v === AV_CONFIG_VERSION) {
                    return done();
                } else {
                    grunt.log.error('Invalid avConfig.js version: ' + v);
                }
            }
            done(false);
        }
    });
  });

  // Project configuration.
  grunt.initConfig({
    connect: {
      main: {
        options: {
          port: 9001
        }
      }
    },
    watch: {
      main: {
        options: {
            livereload: true,
            livereloadOnError: false,
            spawn: false
        },
        files: [createFolderGlobs(['*.js','*.less','*.html']),'!_SpecRunner.html','!.grunt'],
        tasks: [] //all the tasks are run dynamically during the watch event handler
      }
    },
    jshint: {
      main: {
        options: {
            jshintrc: '.jshintrc'
        },
        src: createFolderGlobs('*.js')
      }
    },
    clean: {
      before:{
        src:['dist','temp']
      },
      after: {
        src:['temp']
      }
    },
    less: {
      production: {
        options: {
        },
        files: [{
          expand: true,
          src: ['bower_components/avCommon/themes/**/app.less'],
          dest: 'temp/',
          ext: '.css',
        }]
      }
    },
    autoprefixer: {
      options: {
        browsers: ['ie >= 8', 'ff > 4', 'last 8 versions']
      },
      main: {
        src: 'temp/bower_components/avCommon/themes/**/app.css'
      }
    },
    ngtemplates: {
      main: {
        options: {
            module: pkg.name,
            htmlmin:'<%= htmlmin.main.options %>'
        },
        src: [createFolderGlobs('*.html'),'!index.html','!_SpecRunner.html'],
        dest: 'temp/templates.js'
      },
      common: {
        options: {
            module: pkg.name,
            htmlmin:'<%= htmlmin.main.options %>'
        },
        cwd: 'bower_components/avCommon',
        src: ["avRegistration/**/*.html", "avUi/**/*.html" ],
        dest: 'temp/templates-common.js'
      }
    },
    copy: {
      main: {
        files: [
          {src: ['img/**'], dest: 'dist/'},
          {src: ['img/**'], dest: 'dist/'},
          {src: ['temp_data/**'], dest: 'dist/'},
          {
            expand: true,
            cwd:'bower_components/avCommon/themes',
            src: ['**/*.png'],
            dest: 'dist/themes/',
            ext: '.png',
            extDot: 'first'
          },
          {
            expand: true,
            cwd: 'bower_components/bootstrap/fonts/',
            src: ['**'],
            dest: 'dist/themes/fonts/'
          },
          {
            expand: true,
            cwd: 'bower_components/bootstrap/fonts/',
            src: ['**'],
            dest: 'dist/themes/fonts/'
          },
          {
            expand: true,
            cwd: 'bower_components/font-awesome/fonts/',
            src: ['**'],
            dest: 'dist/fonts/'
          }
          //{src: ['bower_components/angular-ui-utils/ui-utils-ieshiv.min.js'], dest: 'dist/'},
          //{src: ['bower_components/select2/*.png','bower_components/select2/*.gif'], dest:'dist/css/',flatten:true,expand:true},
          //{src: ['bower_components/angular-mocks/angular-mocks.js'], dest: 'dist/'}
        ]
      }
    },
    dom_munger:{
      read: {
        options: {
          read:[
            {selector:'script[class="libnocompat"]',attribute:'src',writeto:'libnocompatjs'},
            {selector:'script[class="lib"]',attribute:'src',writeto:'libjs'},
            {selector:'script[class="app"]',attribute:'src',writeto:'appjs'},
            {selector:'link[rel="stylesheet"][data-concat!="false"]',attribute:'href',writeto:'appcss'}
          ]
        },
        src: 'index.html'
      },
      update: {
        options: {
          remove: ['script[data-remove!="false"]','link[data-remove!="false"]'],
          append: [
            {selector:'body',html:'<!--[if lte IE 8]><script src="/admin/libcompat-v3.0.1.min.js"></script><![endif]--><!--[if gte IE 9]><script src="/admin/libnocompat-v3.0.1.min.js"></script><![endif]--><!--[if !IE]><!--><script src="/admin/libnocompat-v3.0.1.min.js"></script><!--<![endif]-->'},
            {selector:'body',html:'<!--All the source code of this program under copyright. Take a look at the license details at https://github.com/agoravoting/agora-core-view/blob/master/README.md -->'},
            {selector:'body',html:'<script src="/admin/lib-v3.0.1.min.js"></script>'},
            {selector:'body',html:'<script src="/admin/avConfig-v3.0.1.js"></script>'},
            {selector:'body',html:'<script src="/admin/avThemes-v3.0.1.js"></script>'},
            {selector:'body',html:'<script src="/admin/app-v3.0.1.min.js"></script>'},
            {selector:'body',html:'<script src="/admin/avPlugins-v3.0.1.js"></script>'},
            {selector:'head',html:'<link rel="stylesheet" id="theme" data-base="/admin/" href="/admin/themes/default/app.min.css">'}
          ]
        },
        src:'index.html',
        dest: 'dist/index.html'
      }
    },
    cssmin: {
      main: {
        files: [{
            expand: true,
            cwd:'temp/bower_components/avCommon/themes',
            src: ['**/app.css'],
            dest: 'dist/themes/',
            ext: '.min.css',
            extDot: 'first'
        }]
      },
    },
    concat: {
      main: {
        files: {
          'temp/libcompat.js': [
            'vendor/jquery.compat/jquery-1.11.1.js',
            'vendor/json3/json-v3.3.2.js',
            'vendor/crypto/unsupportedBrowser.js'
          ],
          'temp/libnocompat.js': ['<%= dom_munger.data.libnocompatjs %>'],
          'temp/lib.js': ['<%= dom_munger.data.libjs %>'],
          'temp/app.js': ['<%= dom_munger.data.appjs %>','<%= ngtemplates.main.dest %>','<%= ngtemplates.common.dest %>'],
          'dist/avConfig-v3.0.1.js': ['avConfig.js'],
          'dist/avThemes-v3.0.1.js': ['bower_components/avCommon/dist/avThemes-v3.0.1.js'],
          'dist/avPlugins-v3.0.1.js': ['plugins/**/*.js']
        }
      }
    },
    "merge-json": {
      main: {
        files: {
            "dist/locales/en.json": ["locales/en.json", "plugins/**/locales/en.json", "bower_components/avCommon/locales/en.json"],
            "dist/locales/es.json": ["locales/es.json", "plugins/**/locales/es.json", "bower_components/avCommon/locales/es.json"],
            "dist/locales/gl.json": ["locales/gl.json", "plugins/**/locales/gl.json", "bower_components/avCommon/locales/gl.json"],
            "dist/locales/ca.json": ["locales/ca.json", "plugins/**/locales/ca.json", "bower_components/avCommon/locales/ca.json"]
        }
      }
    },
    ngAnnotate: {
      main: {
        files: {
        'temp/app.js':['temp/app.js'],
        'temp/lib.js': ['temp/lib.js'],
        'temp/libnocompat.js': ['temp/libnocompat.js'],
        'temp/libcompat.js': ['temp/libcompat.js']
        }
      }
    },
    uglify: {
      main: {
        options:{
          mangle: false,
          compress: {},
          beautify: true
        },
        files: {
          'dist/app-v3.0.1.min.js': 'temp/app.js',
          'dist/lib-v3.0.1.min.js': 'temp/lib.js',
          'dist/libnocompat-v3.0.1.min.js': 'temp/libnocompat.js',
          'dist/libcompat-v3.0.1.min.js': 'temp/libcompat.js',
          'dist/avWidgets.min.js': 'avWidgets.js',

          "dist/locales/moment/en.js": "bower_components/moment/lang/en.js",
          "dist/locales/moment/es.js": "bower_components/moment/lang/es.js",
          "dist/locales/moment/gl.js": "bower_components/moment/lang/gl.js",
          "dist/locales/moment/ca.js": "bower_components/moment/lang/ca.js"
        }
      }
    },
    htmlmin: {
      main: {
        options: {
          collapseBooleanAttributes: true,
          collapseWhitespace: true,
          removeAttributeQuotes: false,
          removeComments: false,
          removeEmptyAttributes: true,
          removeScriptTypeAttributes: true,
          removeStyleLinkTypeAttributes: true
        },
        files: {
          'dist/index.html': 'dist/index.html'
        }
      }
    },
    imagemin: {
      main:{
        files: [{
          expand: true, cwd:'dist/',
          src:['**/{*.png,*.jpg}'],
          dest: 'dist/'
        }]
      }
    },
    karma: {
      options: {
        frameworks: ['jasmine'],
        files: [  //this files data is also updated in the watch handler, if updated change there too
          '<%= dom_munger.data.libnocompatjs %>',
          '<%= dom_munger.data.libjs %>',
          'avConfig.js',
          'avThemes.js',
          'avWidgets.js',
          '<%= dom_munger.data.appjs %>',
          '<%= ngtemplates.main.dest %>',
          '<%= ngtemplates.common.dest %>',
          'bower_components/angular-mocks/angular-mocks.js',
          createFolderGlobs('*-spec.js')
        ],
        logLevel:'ERROR',
        reporters:['mocha'],
        autoWatch: false, //watching is handled by grunt-contrib-watch
        singleRun: true
      },
      all_tests: {
        browsers: ['PhantomJS','Chrome','Firefox']
      },
      during_watch: {
        browsers: ['PhantomJS']
      },
    },
    protractor: {
      options: {
        configFile: "node_modules/protractor/referenceConf.js", // Default config file
        keepAlive: true, // If false, the grunt process stops when the test fails.
        noColor: false, // If true, protractor will not use colors in its output.
        args: {
        // Arguments passed to the command
      }
    },
    //your_target: {   // Grunt requires at least one target to run so you can simply put 'all: {}' here too.
      all: {
      options: {
        configFile: "e2e.conf.js", // Target-specific config file
        args: {} // Target-specific arguments
      }
    },
  },

  });

  grunt.registerTask('build',['check_config', 'jshint','clean:before','less','autoprefixer','dom_munger','ngtemplates','cssmin','concat','merge-json','ngAnnotate','uglify','copy','htmlmin','imagemin','clean:after']);
  grunt.registerTask('serve', ['dom_munger:read','jshint','connect', 'watch']);
  grunt.registerTask('test',['dom_munger:read','karma:all_tests']);

  grunt.event.on('watch', function(action, filepath) {
    //https://github.com/gruntjs/grunt-contrib-watch/issues/156

    var tasksToRun = [];

    if ((filepath.lastIndexOf('.json') !== -1 && filepath.lastIndexOf('.json') === filepath.length - 5) ||
        (filepath.lastIndexOf('.js') !== -1 && filepath.lastIndexOf('.js') === filepath.length - 3)) {

      //lint the changed js file
      grunt.config('jshint.main.src', filepath);
      tasksToRun.push('jshint');

      //find the appropriate unit t est for the changed file
      var spec = filepath;
      if (filepath.lastIndexOf('-spec.js') === -1 || filepath.lastIndexOf('-spec.js') !== filepath.length - 8) {
        spec = filepath.substring(0,filepath.length - 3) + '-spec.js';
      }

      //if the spec exists then lets run it
      if (grunt.file.exists(spec)) {
        var files = [].concat(grunt.config('dom_munger.data.libnocompatjs'));
        files.concat(grunt.config('dom_munger.data.libjs'));
        files.push('bower_components/angular-mocks/angular-mocks.js');
        files.push('avConfig.js');
        files.push('avThemes.js');
        files.push('avWidgets.js');
        files.concat(grunt.config('dom_munger.data.appjs'));
        files.concat(grunt.config('ngtemplates.main.dest'));
        files.push(spec);
        grunt.config('karma.options.files', files);
        tasksToRun.push('karma:during_watch');
      }
    }

    //if index.html changed, we need to reread the <script> tags so our next run of karma
    //will have the correct environment
    if (filepath === 'index.html') {
      tasksToRun.push('dom_munger:read');
    }

    grunt.config('watch.main.tasks',tasksToRun);

  });

  grunt.loadNpmTasks('grunt-protractor-runner');
};
<commit_msg>Using en-gb.js, en.js doesn't exists<commit_after>/*jslint node: true */
'use strict';

var pkg = require('./package.json');
var AV_CONFIG_VERSION = '3.1.2';

//Using exclusion patterns slows down Grunt significantly
//instead of creating a set of patterns like '**/*.js' and '!**/node_modules/**'
//this method is used to create a set of inclusive patterns for all subdirectories
//skipping node_modules, bower_components, dist, and any .dirs
//This enables users to create any directory structure they desire.
var createFolderGlobs = function(fileTypePatterns) {
  fileTypePatterns = Array.isArray(fileTypePatterns) ? fileTypePatterns : [fileTypePatterns];
  var ignore = ['node_modules','bower_components','dist','temp'];
  var fs = require('fs');
  return fs.readdirSync(process.cwd())
          .map(function(file){
            if (ignore.indexOf(file) !== -1 ||
                file.indexOf('.') === 0 ||
                !fs.lstatSync(file).isDirectory()) {
              return null;
            } else {
              return fileTypePatterns.map(function(pattern) {
                return file + '/**/' + pattern;
              });
            }
          })
          .filter(function(patterns){
            return patterns;
          })
          .concat(fileTypePatterns);
};

module.exports = function (grunt) {

  // load all grunt tasks
  require('load-grunt-tasks')(grunt);

  // custom grunt task to check avConfig.js
  grunt.registerTask('check_config', function() {
    var fs = require('fs');
    var done = this.async();
    grunt.log.ok('Checking avConfig.js...');
    var conf = fs.readFile('avConfig.js', function(err, data) {
        if (err) {
            grunt.log.error('No avConfig.js file found');
            done(false);
        } else {
            var match = data.toString().match(/AV_CONFIG_VERSION = [\'\"]([\w\.]*)[\'\"];/);
            if (!match) {
                grunt.log.error('Invalid avConfig.js version');
            } else {
                var v = match[1];
                if (v === AV_CONFIG_VERSION) {
                    return done();
                } else {
                    grunt.log.error('Invalid avConfig.js version: ' + v);
                }
            }
            done(false);
        }
    });
  });

  // Project configuration.
  grunt.initConfig({
    connect: {
      main: {
        options: {
          port: 9001
        }
      }
    },
    watch: {
      main: {
        options: {
            livereload: true,
            livereloadOnError: false,
            spawn: false
        },
        files: [createFolderGlobs(['*.js','*.less','*.html']),'!_SpecRunner.html','!.grunt'],
        tasks: [] //all the tasks are run dynamically during the watch event handler
      }
    },
    jshint: {
      main: {
        options: {
            jshintrc: '.jshintrc'
        },
        src: createFolderGlobs('*.js')
      }
    },
    clean: {
      before:{
        src:['dist','temp']
      },
      after: {
        src:['temp']
      }
    },
    less: {
      production: {
        options: {
        },
        files: [{
          expand: true,
          src: ['bower_components/avCommon/themes/**/app.less'],
          dest: 'temp/',
          ext: '.css',
        }]
      }
    },
    autoprefixer: {
      options: {
        browsers: ['ie >= 8', 'ff > 4', 'last 8 versions']
      },
      main: {
        src: 'temp/bower_components/avCommon/themes/**/app.css'
      }
    },
    ngtemplates: {
      main: {
        options: {
            module: pkg.name,
            htmlmin:'<%= htmlmin.main.options %>'
        },
        src: [createFolderGlobs('*.html'),'!index.html','!_SpecRunner.html'],
        dest: 'temp/templates.js'
      },
      common: {
        options: {
            module: pkg.name,
            htmlmin:'<%= htmlmin.main.options %>'
        },
        cwd: 'bower_components/avCommon',
        src: ["avRegistration/**/*.html", "avUi/**/*.html" ],
        dest: 'temp/templates-common.js'
      }
    },
    copy: {
      main: {
        files: [
          {src: ['img/**'], dest: 'dist/'},
          {src: ['img/**'], dest: 'dist/'},
          {src: ['temp_data/**'], dest: 'dist/'},
          {
            expand: true,
            cwd:'bower_components/avCommon/themes',
            src: ['**/*.png'],
            dest: 'dist/themes/',
            ext: '.png',
            extDot: 'first'
          },
          {
            expand: true,
            cwd: 'bower_components/bootstrap/fonts/',
            src: ['**'],
            dest: 'dist/themes/fonts/'
          },
          {
            expand: true,
            cwd: 'bower_components/bootstrap/fonts/',
            src: ['**'],
            dest: 'dist/themes/fonts/'
          },
          {
            expand: true,
            cwd: 'bower_components/font-awesome/fonts/',
            src: ['**'],
            dest: 'dist/fonts/'
          }
          //{src: ['bower_components/angular-ui-utils/ui-utils-ieshiv.min.js'], dest: 'dist/'},
          //{src: ['bower_components/select2/*.png','bower_components/select2/*.gif'], dest:'dist/css/',flatten:true,expand:true},
          //{src: ['bower_components/angular-mocks/angular-mocks.js'], dest: 'dist/'}
        ]
      }
    },
    dom_munger:{
      read: {
        options: {
          read:[
            {selector:'script[class="libnocompat"]',attribute:'src',writeto:'libnocompatjs'},
            {selector:'script[class="lib"]',attribute:'src',writeto:'libjs'},
            {selector:'script[class="app"]',attribute:'src',writeto:'appjs'},
            {selector:'link[rel="stylesheet"][data-concat!="false"]',attribute:'href',writeto:'appcss'}
          ]
        },
        src: 'index.html'
      },
      update: {
        options: {
          remove: ['script[data-remove!="false"]','link[data-remove!="false"]'],
          append: [
            {selector:'body',html:'<!--[if lte IE 8]><script src="/admin/libcompat-v3.0.1.min.js"></script><![endif]--><!--[if gte IE 9]><script src="/admin/libnocompat-v3.0.1.min.js"></script><![endif]--><!--[if !IE]><!--><script src="/admin/libnocompat-v3.0.1.min.js"></script><!--<![endif]-->'},
            {selector:'body',html:'<!--All the source code of this program under copyright. Take a look at the license details at https://github.com/agoravoting/agora-core-view/blob/master/README.md -->'},
            {selector:'body',html:'<script src="/admin/lib-v3.0.1.min.js"></script>'},
            {selector:'body',html:'<script src="/admin/avConfig-v3.0.1.js"></script>'},
            {selector:'body',html:'<script src="/admin/avThemes-v3.0.1.js"></script>'},
            {selector:'body',html:'<script src="/admin/app-v3.0.1.min.js"></script>'},
            {selector:'body',html:'<script src="/admin/avPlugins-v3.0.1.js"></script>'},
            {selector:'head',html:'<link rel="stylesheet" id="theme" data-base="/admin/" href="/admin/themes/default/app.min.css">'}
          ]
        },
        src:'index.html',
        dest: 'dist/index.html'
      }
    },
    cssmin: {
      main: {
        files: [{
            expand: true,
            cwd:'temp/bower_components/avCommon/themes',
            src: ['**/app.css'],
            dest: 'dist/themes/',
            ext: '.min.css',
            extDot: 'first'
        }]
      },
    },
    concat: {
      main: {
        files: {
          'temp/libcompat.js': [
            'vendor/jquery.compat/jquery-1.11.1.js',
            'vendor/json3/json-v3.3.2.js',
            'vendor/crypto/unsupportedBrowser.js'
          ],
          'temp/libnocompat.js': ['<%= dom_munger.data.libnocompatjs %>'],
          'temp/lib.js': ['<%= dom_munger.data.libjs %>'],
          'temp/app.js': ['<%= dom_munger.data.appjs %>','<%= ngtemplates.main.dest %>','<%= ngtemplates.common.dest %>'],
          'dist/avConfig-v3.0.1.js': ['avConfig.js'],
          'dist/avThemes-v3.0.1.js': ['bower_components/avCommon/dist/avThemes-v3.0.1.js'],
          'dist/avPlugins-v3.0.1.js': ['plugins/**/*.js']
        }
      }
    },
    "merge-json": {
      main: {
        files: {
            "dist/locales/en.json": ["locales/en.json", "plugins/**/locales/en.json", "bower_components/avCommon/locales/en.json"],
            "dist/locales/es.json": ["locales/es.json", "plugins/**/locales/es.json", "bower_components/avCommon/locales/es.json"],
            "dist/locales/gl.json": ["locales/gl.json", "plugins/**/locales/gl.json", "bower_components/avCommon/locales/gl.json"],
            "dist/locales/ca.json": ["locales/ca.json", "plugins/**/locales/ca.json", "bower_components/avCommon/locales/ca.json"]
        }
      }
    },
    ngAnnotate: {
      main: {
        files: {
        'temp/app.js':['temp/app.js'],
        'temp/lib.js': ['temp/lib.js'],
        'temp/libnocompat.js': ['temp/libnocompat.js'],
        'temp/libcompat.js': ['temp/libcompat.js']
        }
      }
    },
    uglify: {
      main: {
        options:{
          mangle: false,
          compress: {},
          beautify: true
        },
        files: {
          'dist/app-v3.0.1.min.js': 'temp/app.js',
          'dist/lib-v3.0.1.min.js': 'temp/lib.js',
          'dist/libnocompat-v3.0.1.min.js': 'temp/libnocompat.js',
          'dist/libcompat-v3.0.1.min.js': 'temp/libcompat.js',
          'dist/avWidgets.min.js': 'avWidgets.js',

          "dist/locales/moment/en.js": "bower_components/moment/lang/en-gb.js",
          "dist/locales/moment/es.js": "bower_components/moment/lang/es.js",
          "dist/locales/moment/gl.js": "bower_components/moment/lang/gl.js",
          "dist/locales/moment/ca.js": "bower_components/moment/lang/ca.js"
        }
      }
    },
    htmlmin: {
      main: {
        options: {
          collapseBooleanAttributes: true,
          collapseWhitespace: true,
          removeAttributeQuotes: false,
          removeComments: false,
          removeEmptyAttributes: true,
          removeScriptTypeAttributes: true,
          removeStyleLinkTypeAttributes: true
        },
        files: {
          'dist/index.html': 'dist/index.html'
        }
      }
    },
    imagemin: {
      main:{
        files: [{
          expand: true, cwd:'dist/',
          src:['**/{*.png,*.jpg}'],
          dest: 'dist/'
        }]
      }
    },
    karma: {
      options: {
        frameworks: ['jasmine'],
        files: [  //this files data is also updated in the watch handler, if updated change there too
          '<%= dom_munger.data.libnocompatjs %>',
          '<%= dom_munger.data.libjs %>',
          'avConfig.js',
          'avThemes.js',
          'avWidgets.js',
          '<%= dom_munger.data.appjs %>',
          '<%= ngtemplates.main.dest %>',
          '<%= ngtemplates.common.dest %>',
          'bower_components/angular-mocks/angular-mocks.js',
          createFolderGlobs('*-spec.js')
        ],
        logLevel:'ERROR',
        reporters:['mocha'],
        autoWatch: false, //watching is handled by grunt-contrib-watch
        singleRun: true
      },
      all_tests: {
        browsers: ['PhantomJS','Chrome','Firefox']
      },
      during_watch: {
        browsers: ['PhantomJS']
      },
    },
    protractor: {
      options: {
        configFile: "node_modules/protractor/referenceConf.js", // Default config file
        keepAlive: true, // If false, the grunt process stops when the test fails.
        noColor: false, // If true, protractor will not use colors in its output.
        args: {
        // Arguments passed to the command
      }
    },
    //your_target: {   // Grunt requires at least one target to run so you can simply put 'all: {}' here too.
      all: {
      options: {
        configFile: "e2e.conf.js", // Target-specific config file
        args: {} // Target-specific arguments
      }
    },
  },

  });

  grunt.registerTask('build',['check_config', 'jshint','clean:before','less','autoprefixer','dom_munger','ngtemplates','cssmin','concat','merge-json','ngAnnotate','uglify','copy','htmlmin','imagemin','clean:after']);
  grunt.registerTask('serve', ['dom_munger:read','jshint','connect', 'watch']);
  grunt.registerTask('test',['dom_munger:read','karma:all_tests']);

  grunt.event.on('watch', function(action, filepath) {
    //https://github.com/gruntjs/grunt-contrib-watch/issues/156

    var tasksToRun = [];

    if ((filepath.lastIndexOf('.json') !== -1 && filepath.lastIndexOf('.json') === filepath.length - 5) ||
        (filepath.lastIndexOf('.js') !== -1 && filepath.lastIndexOf('.js') === filepath.length - 3)) {

      //lint the changed js file
      grunt.config('jshint.main.src', filepath);
      tasksToRun.push('jshint');

      //find the appropriate unit t est for the changed file
      var spec = filepath;
      if (filepath.lastIndexOf('-spec.js') === -1 || filepath.lastIndexOf('-spec.js') !== filepath.length - 8) {
        spec = filepath.substring(0,filepath.length - 3) + '-spec.js';
      }

      //if the spec exists then lets run it
      if (grunt.file.exists(spec)) {
        var files = [].concat(grunt.config('dom_munger.data.libnocompatjs'));
        files.concat(grunt.config('dom_munger.data.libjs'));
        files.push('bower_components/angular-mocks/angular-mocks.js');
        files.push('avConfig.js');
        files.push('avThemes.js');
        files.push('avWidgets.js');
        files.concat(grunt.config('dom_munger.data.appjs'));
        files.concat(grunt.config('ngtemplates.main.dest'));
        files.push(spec);
        grunt.config('karma.options.files', files);
        tasksToRun.push('karma:during_watch');
      }
    }

    //if index.html changed, we need to reread the <script> tags so our next run of karma
    //will have the correct environment
    if (filepath === 'index.html') {
      tasksToRun.push('dom_munger:read');
    }

    grunt.config('watch.main.tasks',tasksToRun);

  });

  grunt.loadNpmTasks('grunt-protractor-runner');
};
<|endoftext|>


<commit_before>var oss = require('ali-oss');
var co = require('co');
var fs = require('fs');
var config = {}
var objectKey = 'package.json';

if(process.argv.length != 3){
	console.error('param error! please input: node app oss');
	process.exit()
}
if(process.argv[2] == 's3'){
	config = require('./s3.json')
}else if (process.argv[2] == 'oss'){
	config = require('./oss.json')
}

var client = new oss({
	  accessKeyId: config.accessKeyId,
	  accessKeySecret: config.accessKeySecret,
	  endpoint: config.endpoint,
	  region: config.region // if endpoint provide, region will be ignore.
});

function putBucket(){
	co(function* () {
		  var result = yield client.putBucket(config.bucket);
			console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function delBucket(){
	co(function* () {
		  var result = yield client.deleteBucket(config.bucket);
			console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function listBuckets() {
	co(function* () {
		  var result = yield client.listBuckets();
			console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function put(){
	co(function* () {
		client.useBucket(config.bucket);
		var result = yield client.put(objectKey, '/tmp/package.json');
		console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function get(){
	co(function* () {
		client.useBucket(config.bucket);
		var result = yield client.get(objectKey, '/tmp/package.json.oss');
		console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function del(){
	co(function* (){
		client.useBucket(config.bucket);
		var result = yield client.delete(objectKey);
		console.log(result);
	}).catch(function (err) {
		console.log(err);
	});
}

//putBucket()
//delBucket()
listBuckets()
//put()
//get()
//del()

<commit_msg>add object list test<commit_after>var oss = require('ali-oss');
var co = require('co');
var fs = require('fs');
var config = {}
var objectKey = 'civetweb-10rw.png';

if(process.argv.length != 3){
	console.error('param error! please input: node app oss');
	process.exit()
}
if(process.argv[2] == 's3'){
	config = require('./s3.json')
}else if (process.argv[2] == 'oss'){
	config = require('./oss.json')
}

var client = new oss({
	  accessKeyId: config.accessKeyId,
	  accessKeySecret: config.accessKeySecret,
	  endpoint: config.endpoint,
	  region: config.region // if endpoint provide, region will be ignore.
});

function putBucket(){
	co(function* () {
		  var result = yield client.putBucket(config.bucket);
			console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function delBucket(){
	co(function* () {
		  var result = yield client.deleteBucket(config.bucket);
			console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function listBuckets() {
	co(function* () {
		  var result = yield client.listBuckets();
			console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function list(){
	co(function* () {
		client.useBucket(config.bucket);
		var max_keys = 1;
		var result = yield client.list( {"max-keys": max_keys,'delimiter':'/'} );
		console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function put(){
	co(function* () {
		client.useBucket(config.bucket);
		var result = yield client.put(objectKey, '/tmp/civetweb-10rw.png',{ headers: {
				      'x-oss-object-acl': 'public-read'
					}
				}
			);
		console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function get(){
	co(function* () {
		client.useBucket(config.bucket);
		var result = yield client.get(objectKey, '/tmp/civetweb-10rw.png.oss');
		console.log(result);
	}).catch(function (err) {
		  console.log(err);
	});
}

function del(){
	co(function* (){
		client.useBucket(config.bucket);
		var result = yield client.delete(objectKey);
		console.log(result);
	}).catch(function (err) {
		console.log(err);
	});
}

function set_acl(acl){
	co(function* (){
		client.useBucket(config.bucket);
		var result = yield client.putACL(objectKey,acl);
		console.log(result);
	}).catch(function (err) {
		console.log(err);
	});
}

function get_acl(acl){
	co(function* (){
		client.useBucket(config.bucket);
		var result = yield client.getACL(objectKey);
		console.log(result.acl);
	}).catch(function (err) {
		console.log(err);
	});
}

//putBucket()
//delBucket()
//listBuckets()
list()
//put()
//set_acl('public-read')
//get_acl()
//get()
//del()

<|endoftext|>


<commit_before>var HTMLElement=function(t){function e(){}return e.prototype=window.HTMLElement.prototype,e}(),TokenList=function(t){for(var e=this,n=function(t){return/{(\w+|#)}/.test(t.textContent)&&(t.text=t.textContent).match(/[^{]+(?=})/g).map(function(n){return(e[n]||(e[n]=[])).push(t)})},r=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,function(t){return t.attributes&&[].slice.call(t.attributes).map(n)||n(t)},null);r.nextNode(););};TokenList.prototype.bind=function(t){var e=this;for(var n in e)e[n].map(function(t){return t.textContent=t.text})&&e[n].map(function(e){return function(n){return n.textContent=n.textContent.split("{"+e+"}").join(t[e])}}(n))},function(t){function e(t){var e=new XMLHttpRequest;e.link=t,e.onload=n,e.open("GET",t.href),e.responseType="document",e.send()}function n(t){t=this.link;for(var e=this.response,n=t.nextChild,i=t.content=e.querySelector("template"),c=0,l=document.querySelectorAll(t.id);c<l.length;c+=1){var s=l[c];i&&o.call(s,i)}for(var a=0,u=e.querySelectorAll("style,link,script");a<u.length;a+=1)r(t,u[a],n)}function r(t,e,n){var r=e.getAttribute("as"),o=document.createElement("script"==r?r:e.localName);["id","rel","href","src","textContent","as","defer","crossOrigin"].map(function(t){return e[t]&&t in o&&(o[t]=e[t])}),"style"==r&&(o.rel="stylesheet"),"script"==r&&(o.src=o.href),t.parentNode.insertBefore(o,n)}function o(t){var e=this;t=document.importNode(t,!0);var n;[].slice.call(t.attributes).map(function(t){return!e.attributes[t.name]&&e.setAttribute(t.name,t.value)});for(var r=0,o=e.querySelectorAll("[slot]");r<o.length;r+=1){var i=o[r];(n=(t.content||t).querySelector("slot[name="+i.getAttribute("slot")+"]"))&&n.parentNode.replaceChild(i,n)}return this.innerHTML=t.innerHTML}new MutationObserver(function(t){for(var n=0,r=t;n<r.length;n+=1)for(var i=0,c=r[n].addedNodes;i<c.length;i+=1){var l=c[i];/^p/.test(l.rel)&&/\-/.test(l.id)&&e(l),!!/\-/.test(l.localName)&&(link=document.querySelector("#"+l.localName))&&link.content&&o.call(l,link.content)&&customElements.upgrade(l)}}).observe(document.documentElement,{childList:!0,subtree:!0}),[].slice.call(document.querySelectorAll('[rel^=pre][id~="-"]')).map(e)}();var Template=function(t){t.length&&(t=document.querySelector("template[name="+t+"]"));var e=t.innerHTML,n=t.nextSibling;return t.innerHTML="",t.bind=function(t){for(var r=this,o=document.createElement("section"),i=0,c=r.dependents||[];i<c.length;i+=1){var l=c[i];l.parentNode.removeChild(l)}o.innerHTML=[].concat(t).reduce(function(t,n,r){var o=e;"object"!=typeof n&&(n={self:n}),n["#"]=r;for(var i in n)o=o.split("{"+i+"}").join(n[i]);return t+o},"");for(var s=0,a=r.dependents=[].slice.call(o.childNodes);s<a.length;s+=1){var u=a[s];r.parentNode.insertBefore(u,n)}}.bind(t),t};window.customElements=window.customElements||{},new(function(){function t(){customElements.define=this.define.bind(this),customElements.upgrade=this.upgrade.bind(this)}return t.prototype.define=function(t,e){this[t]=e,[].slice.call(document.querySelectorAll(t)).map(this.upgrade,this)},t.prototype.upgrade=function(t){this[t.localName]&&Object.setPrototypeOf(t,this[t.localName].prototype).connectedCallback()},t}());var ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.select=function(){return(t=this).selectAll.apply(t,arguments)[0];var t},e.prototype.selectAll=function(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];return t=[].concat(t),[].slice.call(this.querySelectorAll(e.reduce(function(e,n){return e+n+t.shift()},t.shift())))},e}(t)},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.on=function(t,e){this.addEventListener(t,this.renderable(e))},e.prototype.renderable=function(t){var e=this;return function(n){return!1!==t.call(e,n)&&n.defaultPrevented||e.render()}},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onconnect=function(){this.templates=this.selectAll("template[name]").map(Template),this.tokens=new TokenList(this),t.prototype.onconnect&&t.prototype.onconnect.call(this)},e.prototype.reflect=function(t){/^on/.test(t)&&t in HTMLElement.prototype&&this.on(t.substr(2),this[t])},e.prototype.register=function(t,e,n){for(var r=this,o=0,i=[].slice.call(t.attributes);o<i.length;o+=1){var c=i[o];/^on/.test(n=c.name)&&(e=(/{\s*(\w+)/.exec(t[n])||[])[1])&&(t[n]=r.renderable(r[e]))}},e}(t)},Custom=function(t){return function(e){function n(){e.apply(this,arguments)}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.connectedCallback=function(){this.context={},e.prototype.initialize&&e.prototype.initialize.call(this),Object.getOwnPropertyNames(t.prototype).map(this.reflect,this),this.onconnect(),this.render()},n.prototype.render=function(){for(var t=this,n=0,r=t.templates;n<r.length;n+=1){var o=r[n];o.bind(t[o.getAttribute("name")])}this.tokens.bind(this),this.register(this),this.selectAll("*").map(this.register,this),e.prototype.onidle&&e.prototype.onidle.call(this)},n}(ParentNode(EventTarget(GlobalEventHandlers(t))))},Element=function(t){return function(e){return customElements.define(t+"",Custom(e))}};<commit_msg>:muscle: bump MINIFIED distribution dist/snuggsi.min.js<commit_after>var HTMLElement=function(t){function e(){}return e.prototype=window.HTMLElement.prototype,e}(),TokenList=function(t){for(var e=this,n=function(t){return/{(\w+|#)}/.test(t.textContent)&&(t.text=t.textContent).match(/[^{]+(?=})/g).map(function(n){return(e[n]||(e[n]=[])).push(t)})},r=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,function(t){return t.attributes&&[].slice.call(t.attributes).map(n)||n(t)},null);r.nextNode(););};TokenList.prototype.bind=function(t){var e=function(e){return function(n){return n.textContent=n.textContent.split("{"+e+"}").join(t[e])}};for(var n in this)this[n].map(function(t){return t.textContent=t.text})&&this[n].map(e(n))},function(t){function e(t){var e=new XMLHttpRequest;e.link=t,e.onload=n,e.open("GET",t.href),e.responseType="document",e.send()}function n(t){t=this.link;for(var e=this.response,n=t.nextChild,o=t.content=e.querySelector("template"),i=0,c=document.querySelectorAll(t.id);i<c.length;i+=1){var l=c[i];o&&r.call(l,o)}for(var s=0,a=e.querySelectorAll("style,link,script");s<a.length;s+=1){!function(t,e,n){var r=e.getAttribute("as"),o=document.createElement("script"==r?r:e.localName);["id","rel","href","src","textContent","as","defer","crossOrigin"].map(function(t){return e[t]&&t in o&&(o[t]=e[t])}),"style"==r&&(o.rel="stylesheet"),"script"==r&&(o.src=o.href),t.parentNode.insertBefore(o,n)}(t,a[s],n)}}function r(t){var e=this;t=document.importNode(t,!0);var n;[].slice.call(t.attributes).map(function(t){return!e.attributes[t.name]&&e.setAttribute(t.name,t.value)});for(var r=0,o=e.querySelectorAll("[slot]");r<o.length;r+=1){var i=o[r];(n=(t.content||t).querySelector("slot[name="+i.getAttribute("slot")+"]"))&&n.parentNode.replaceChild(i,n)}return this.innerHTML=t.innerHTML}new MutationObserver(function(t){for(var n=0,o=t;n<o.length;n+=1)for(var i=0,c=o[n].addedNodes;i<c.length;i+=1){var l=c[i];/^p/.test(l.rel)&&/\-/.test(l.id)&&e(l),/\-/.test(l.localName)&&(link=document.querySelector("#"+l.localName))&&link.content&&r.call(l,link.content)&&customElements.upgrade(l)}}).observe(document.documentElement,{childList:!0,subtree:!0}),[].slice.call(document.querySelectorAll('[rel^=pre][id~="-"]')).map(e)}();var Template=function(t){t.length&&(t=document.querySelector("template[name="+t+"]"));var e=t.innerHTML,n=t.nextSibling;return t.innerHTML="",t.bind=function(t){for(var r=document.createElement("section"),o=0,i=this.dependents||[];o<i.length;o+=1){var c=i[o];c.parentNode.removeChild(c)}r.innerHTML=[].concat(t).reduce(function(t,n,r){var o=e;"object"!=typeof n&&(n={self:n}),n["#"]=r;for(var i in n)o=o.split("{"+i+"}").join(n[i]);return t+o},"");for(var l=0,s=this.dependents=[].slice.call(r.childNodes);l<s.length;l+=1){var a=s[l];this.parentNode.insertBefore(a,n)}}.bind(t),t};window.customElements=window.customElements||{},new(function(){function t(){customElements.define=this.define.bind(this),customElements.upgrade=this.upgrade.bind(this)}return t.prototype.define=function(t,e){this[t]=e,[].slice.call(document.querySelectorAll(t)).map(this.upgrade,this)},t.prototype.upgrade=function(t){this[t.localName]&&Object.setPrototypeOf(t,this[t.localName].prototype).connectedCallback()},t}());var ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.select=function(){return(t=this).selectAll.apply(t,arguments)[0];var t},e.prototype.selectAll=function(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];return t=[].concat(t),[].slice.call(this.querySelectorAll(e.reduce(function(e,n){return e+n+t.shift()},t.shift())))},e}(t)},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.on=function(t,e){this.addEventListener(t,this.renderable(e))},e.prototype.renderable=function(t){var e=this;return function(n){return!1!==t.call(e,n)&&n.defaultPrevented||e.render()}},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onconnect=function(){this.templates=this.selectAll("template[name]").map(Template),this.tokens=new TokenList(this),t.prototype.onconnect&&t.prototype.onconnect.call(this)},e.prototype.reflect=function(t){/^on/.test(t)&&t in HTMLElement.prototype&&this.on(t.substr(2),this[t])},e.prototype.register=function(t,e,n){for(var r=0,o=[].slice.call(t.attributes);r<o.length;r+=1){var i=o[r];/^on/.test(n=i.name)&&(e=(/{\s*(\w+)/.exec(t[n])||[])[1])&&(t[n]=this.renderable(this[e]))}},e}(t)},Custom=function(t){return function(e){function n(){e.apply(this,arguments)}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.connectedCallback=function(){this.context={},e.prototype.initialize&&e.prototype.initialize.call(this),Object.getOwnPropertyNames(t.prototype).map(this.reflect,this),this.onconnect(),this.render()},n.prototype.render=function(){for(var t=0,n=this.templates;t<n.length;t+=1){var r=n[t];r.bind(this[r.getAttribute("name")])}this.tokens.bind(this),this.register(this),this.selectAll("*").map(this.register,this),e.prototype.onidle&&e.prototype.onidle.call(this)},n}(ParentNode(EventTarget(GlobalEventHandlers(t))))},Element=function(t){return function(e){return customElements.define(t+"",Custom(e))}};<|endoftext|>


<commit_before>angular.module('feedbackcontrol', [])
.directive('transform', function(FeedbackSignal) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var currentUrl = window.location.pathname;
                var me = $(element);
                var data = FeedbackSignal.data;

                if(currentUrl.match(/published|contacts/g)) {

                    if(me.attr('return-policy') == 1) {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                    if(data.status == "feature") {
                        var state = {
                            activate: {'background-position': '-64px -31px'}
                          , deactivate_sibling: {'background-position': '-32px 0px'}
                          , activation_color: {'background-color': '#ffffe0'}
                          , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                          , state_change: '{"status": "publish", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                        }
                        published_state(me, '.publish', 'publish feedback', state);
                    }

                    if(data.status == "publish") {
                        var state = {
                            activate: {'background-position': '-32px -31px'}
                          , deactivate_sibling: {'background-position': '-64px 0px'}
                          , activation_color: {'background-color': '#fff'}
                          , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                          , state_change: '{"status": "feature", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                        }
                        published_state(me, '.feature', 'feature feedback', state);
                    }

                    if(data.status == "delete" || data.status == "fileas") {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                } else if(currentUrl.match(/filed/g)) {

                    var data_status = data.status;

                    if(data_status == "publish" || data_status == "feature" || data_status == "delete") {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                    if(data_status == "fileas") {
                        var sibling = $(me).siblings(".feedback-details-rating fild");
                        console.log(siblings);
                    }

                } else {
                    hide_the_children(me);
                    $(".checky-box-container").show();
                }

                e.preventDefault();
            });
        }
    }
})
.directive('undo', function(FeedbackSignal, FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                if (FeedbackSignal.data.id instanceof Array) {
                    for(var i=0; i < FeedbackSignal.data.id.length ; i++) {
                        var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "]");
                        feedback.show();
                        $(feedback).parents('.feedback-group').show();
                    }
                } else {
                    var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "]");
                    feedback.show();
                    $(feedback).parents('.feedback-group').show();

                    var checkbox = $(".feed-checkbox[value=" + FeedbackSignal.data.id + "]");

                    if(checkbox.is(":checked")) {
                        checkbox.click();
                    }
                }

                if($(".sorter-checkbox").is(":checked")) {
                    $(".sorter-checkbox").click();
                }

                if($('.feed-checkbox').is(":checked")) {
                    $('.feed-checkbox').prop("checked", false);
                }

                $(".dashboard-feedback").css({'background-color': '#FFF'});

                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('close', function(FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('feedcheckbox', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            var checkbox = $(element);

            checkbox.bind('change', function() {
                if(checkbox.is(":checked")) {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#F7F7F7'});
                } else {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#FFF'});
                }
            });

        }
    }
})
.directive('statuschange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'status');
            })
        }
    }
})
.directive('prioritychange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'priority');
            })
        }
    }
})
.directive('deleteBlock', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(this).parents('.custom-att').fadeOut(400, function() {
                     var new_uploaded_images = new Array;
                     var new_attached_link;

                     var div = $(this).parents('.uploaded-images-and-links');
                     var images = div.find('.uploaded_image');
                     var media_attachment = div.find('.attached_link');

                     var remove_image = {
                        'small_url'    :$(this).find('.small-image-url').val(),
                        'medium_url'   :$(this).find('.medium-image-url').val(),
                        'large_url'    :$(this).find('.large-image-url').val()
                     }

                    if(images.length > 0){
                        var us = images.not(":hidden");
                        for(var i=0; i < us.length; i++) {
                            new_uploaded_images.push({
                                'name': $(us[i]).find('.image-name').val()
                            });
                        }
                    }

                    if(!media_attachment.is(":hidden")) {
                        new_attached_link = {
                            title           : media_attachment.find('.link-title').val(),
                            description     : media_attachment.find('.link-description').val(),
                            image           : media_attachment.find('.link-image').val(),
                            url             : media_attachment.find('.link-url').val(),
                            video           : media_attachment.find('.link-video').val(),
                        }
                    }

                    var remaining = {
                        uploaded_images : new_uploaded_images
                      , attached_link   : new_attached_link
                    }

                    var attachment_data = {
                        feedbackId      : div.find('.attachment_feedback_id').val()
                      , attachments     : remaining
                      , remove_image    : remove_image
                    }

                    //place this in service you lazy bastard!
                    $.ajax({
                        type: "POST"
                      , url: "/inbox/update_feedback_attachment"
                      , dataType: "json"
                      , data: attachment_data
                    });
                });
                e.preventDefault();
            })
        }
    }
})
.directive('flag', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var policy = $(this).attr("return-policy");
                if(policy == 1) {
                    $(this).removeAttr("style");
                    $(this).attr("return-policy", 0);
                } else {
                    $(this).attr("style", "background-position: -194px -31px");
                    $(this).attr("return-policy", 1);
                }
                e.preventDefault();
            });
        }
    }
})

function published_state(obj, sibling_id, msg, state) {
    obj.parents('.dashboard-feedback').css(state.activation_color);
    obj.css(state.activate);
    obj.children('.action-tooltip').children('span').html("Return to Inbox");
    obj.siblings(sibling_id).css(state.deactivate_sibling);
    obj.siblings(sibling_id).children('.action-tooltip').children('span').html(msg);
    obj.siblings(sibling_id).attr('return-policy', 0);
    obj.siblings(sibling_id).attr('data-feed', state.state_change);
    obj.attr('return-policy', 1);
    obj.attr('data-feed', state.state_change_inbox);
}

function hide_the_children(obj) {
    obj.parents('.dashboard-feedback').hide();
    var child_count = obj.parents('.feedback-group').children('.dashboard-feedback:visible');
    if(child_count.length == 0) {
        obj.parents('.feedback-group').hide();
    }
}
<commit_msg>FUCKING<commit_after>angular.module('feedbackcontrol', [])
.directive('transform', function(FeedbackSignal) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var currentUrl = window.location.pathname;
                var me = $(element);
                var data = FeedbackSignal.data;

                if(currentUrl.match(/published|contacts/g)) {

                    if(me.attr('return-policy') == 1) {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                    if(data.status == "feature") {
                        var state = {
                            activate: {'background-position': '-64px -31px'}
                          , deactivate_sibling: {'background-position': '-32px 0px'}
                          , activation_color: {'background-color': '#ffffe0'}
                          , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                          , state_change: '{"status": "publish", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                        }
                        published_state(me, '.publish', 'publish feedback', state);
                    }

                    if(data.status == "publish") {
                        var state = {
                            activate: {'background-position': '-32px -31px'}
                          , deactivate_sibling: {'background-position': '-64px 0px'}
                          , activation_color: {'background-color': '#fff'}
                          , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                          , state_change: '{"status": "feature", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                        }
                        published_state(me, '.feature', 'feature feedback', state);
                    }

                    if(data.status == "delete" || data.status == "fileas") {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                } else if(currentUrl.match(/filed/g)) {

                    var data_status = data.status;

                    if(data_status == "publish" || data_status == "feature" || data_status == "delete") {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                    if(data_status == "fileas") {
                        var sibling = $(me).siblings(".feedback-details-rating fild");
                        console.log(sibling);
                    }

                } else {
                    hide_the_children(me);
                    $(".checky-box-container").show();
                }

                e.preventDefault();
            });
        }
    }
})
.directive('undo', function(FeedbackSignal, FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                if (FeedbackSignal.data.id instanceof Array) {
                    for(var i=0; i < FeedbackSignal.data.id.length ; i++) {
                        var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "]");
                        feedback.show();
                        $(feedback).parents('.feedback-group').show();
                    }
                } else {
                    var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "]");
                    feedback.show();
                    $(feedback).parents('.feedback-group').show();

                    var checkbox = $(".feed-checkbox[value=" + FeedbackSignal.data.id + "]");

                    if(checkbox.is(":checked")) {
                        checkbox.click();
                    }
                }

                if($(".sorter-checkbox").is(":checked")) {
                    $(".sorter-checkbox").click();
                }

                if($('.feed-checkbox').is(":checked")) {
                    $('.feed-checkbox').prop("checked", false);
                }

                $(".dashboard-feedback").css({'background-color': '#FFF'});

                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('close', function(FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('feedcheckbox', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            var checkbox = $(element);

            checkbox.bind('change', function() {
                if(checkbox.is(":checked")) {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#F7F7F7'});
                } else {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#FFF'});
                }
            });

        }
    }
})
.directive('statuschange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'status');
            })
        }
    }
})
.directive('prioritychange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'priority');
            })
        }
    }
})
.directive('deleteBlock', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(this).parents('.custom-att').fadeOut(400, function() {
                     var new_uploaded_images = new Array;
                     var new_attached_link;

                     var div = $(this).parents('.uploaded-images-and-links');
                     var images = div.find('.uploaded_image');
                     var media_attachment = div.find('.attached_link');

                     var remove_image = {
                        'small_url'    :$(this).find('.small-image-url').val(),
                        'medium_url'   :$(this).find('.medium-image-url').val(),
                        'large_url'    :$(this).find('.large-image-url').val()
                     }

                    if(images.length > 0){
                        var us = images.not(":hidden");
                        for(var i=0; i < us.length; i++) {
                            new_uploaded_images.push({
                                'name': $(us[i]).find('.image-name').val()
                            });
                        }
                    }

                    if(!media_attachment.is(":hidden")) {
                        new_attached_link = {
                            title           : media_attachment.find('.link-title').val(),
                            description     : media_attachment.find('.link-description').val(),
                            image           : media_attachment.find('.link-image').val(),
                            url             : media_attachment.find('.link-url').val(),
                            video           : media_attachment.find('.link-video').val(),
                        }
                    }

                    var remaining = {
                        uploaded_images : new_uploaded_images
                      , attached_link   : new_attached_link
                    }

                    var attachment_data = {
                        feedbackId      : div.find('.attachment_feedback_id').val()
                      , attachments     : remaining
                      , remove_image    : remove_image
                    }

                    //place this in service you lazy bastard!
                    $.ajax({
                        type: "POST"
                      , url: "/inbox/update_feedback_attachment"
                      , dataType: "json"
                      , data: attachment_data
                    });
                });
                e.preventDefault();
            })
        }
    }
})
.directive('flag', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var policy = $(this).attr("return-policy");
                if(policy == 1) {
                    $(this).removeAttr("style");
                    $(this).attr("return-policy", 0);
                } else {
                    $(this).attr("style", "background-position: -194px -31px");
                    $(this).attr("return-policy", 1);
                }
                e.preventDefault();
            });
        }
    }
})

function published_state(obj, sibling_id, msg, state) {
    obj.parents('.dashboard-feedback').css(state.activation_color);
    obj.css(state.activate);
    obj.children('.action-tooltip').children('span').html("Return to Inbox");
    obj.siblings(sibling_id).css(state.deactivate_sibling);
    obj.siblings(sibling_id).children('.action-tooltip').children('span').html(msg);
    obj.siblings(sibling_id).attr('return-policy', 0);
    obj.siblings(sibling_id).attr('data-feed', state.state_change);
    obj.attr('return-policy', 1);
    obj.attr('data-feed', state.state_change_inbox);
}

function hide_the_children(obj) {
    obj.parents('.dashboard-feedback').hide();
    var child_count = obj.parents('.feedback-group').children('.dashboard-feedback:visible');
    if(child_count.length == 0) {
        obj.parents('.feedback-group').hide();
    }
}
<|endoftext|>