<commit_before>/**
 * Module dependencies
 */
var accounting = require('accounting')
  , util = require('util')
  , currency = require('currency-symbol-map');

/**
 * formatPrice - format currency code and price nicely
 * @param {Object} value
 * @returns {String} formatted price
 * @note Value is expected to be of the form:
 *   {
 *     CurrencyCode: [ 'EUR' ],
 *     Amount: [ '130' ] // Cents
 *   }
 */
module.exports.formatPrice = function (val) {
  var code = val && val.CurrencyCode && val.CurrencyCode[0]
    , amount = val && val.Amount && val.Amount[0];

  if (!code || !amount) return null;

  return accounting.formatMoney(amount / 100, currency(code));
};
<commit_msg>Format prices differently for germany<commit_after>/**
 * Module dependencies
 */
var accounting = require('accounting')
  , util = require('util')
  , currency = require('currency-symbol-map');

/**
 * formatPrice - format currency code and price nicely
 * @param {Object} value
 * @returns {String} formatted price
 * @note Value is expected to be of the form:
 *   {
 *     CurrencyCode: [ 'EUR' ],
 *     Amount: [ '130' ] // Cents
 *   }
 */
module.exports.formatPrice = function (val) {
  var code = val && val.CurrencyCode && val.CurrencyCode[0]
    , amount = val && val.Amount && val.Amount[0]
    , decimal, thousand;

  if (!code || !amount) return null;

  // Set separator
  if (~['DE'].indexOf(this.country)) {
    decimal = ',';
    thousand = '.';
  } else {
    decimal = '.';
    thousand = ',';
  }

  return accounting.formatMoney(amount / 100, currency(code), 2, thousand, decimal);
};
<|endoftext|>


<commit_before>'use strict';

module.exports = Translator;

function Translator(actions) {
	this._actions = actions;
}

Translator.prototype.visit = function(node) {
	if (Array.isArray(node)) return this._visitNodes(node);
	else return this._visitNode(node);
};

Translator.prototype._visitNodes = function (nodes) {
	var i = 0;
	while (i < nodes.length) {
		var ret = this._visitNode(nodes[i]);
		i = this._replaceNode(ret, i, nodes);
	}
	return nodes;
};

Translator.prototype._visitNode = function(node) {
	if (node !== Object(node)) return node;
	if (!node.type) return node;
	var action = this._actions[node.type] || this._actions.node;
	if (action) {
		var ret = action.call(this, node);
		return ret === undefined ? node : ret;
	}
};

Translator.prototype._replaceNode = function (node, i, nodes) {
	if (node === null) {
		nodes.splice(i, 1);
		return i;
	}
	if (Array.isArray(node)) {
		nodes.splice.apply(nodes, [i, 1].concat(node));
		return i + node.length;
	}
	if (node !== undefined) nodes[i] = node;
	return i + 1;
};<commit_msg>Inherits ast-visitor<commit_after>'use strict';

var Visitor = require('ast-visitor');
var inherits = require('util').inherits;

module.exports = Translator;

function Translator(actions) {
	Visitor.apply(this, arguments);
}
inherits(Translator, Visitor);

Translator.prototype._visitNodes = function (nodes) {
	var i = 0;
	while (i < nodes.length) {
		var ret = this._visitNode(nodes[i]);
		i = this._replaceNode(ret, i, nodes);
	}
	return nodes;
};

Translator.prototype._visitNode = function(node) {
	var ret = Visitor.prototype._visitNode.apply(this, arguments);
	return ret === undefined ? node : ret;
};

Translator.prototype._replaceNode = function (ret, i, nodes) {
	if (ret === null) {
		nodes.splice(i, 1);
		return i;
	}
	if (Array.isArray(ret)) {
		nodes.splice.apply(nodes, [i, 1].concat(ret));
		return i + ret.length;
	}
	if (ret !== undefined) nodes[i] = ret;
	return i + 1;
};<|endoftext|>


<commit_before>import { types as t } from 'mobx-state-tree'

import { PAGE_SIZE } from 'config'

import { User, PagedUsers } from './User'
import { Community } from './Community'
import { Tag } from './Tag'

const Contributor = t.model('Contributor', {
  avatar: t.string,
  nickname: t.string,
  htmlUrl: t.string,
})

const Language = t.model('Language', {
  name: t.string,
  color: t.string,
})

export const Repo = t.model('Reop', {
  id: t.maybeNull(t.string),
  title: t.maybeNull(t.string),
  ownerName: t.maybeNull(t.string),
  ownerUrl: t.maybeNull(t.string),
  repoUrl: t.maybeNull(t.string),

  desc: t.maybeNull(t.string),
  homepageUrl: t.maybeNull(t.string),
  readme: t.maybeNull(t.string),

  issuesCount: t.optional(t.number, 0),
  prsCount: t.optional(t.number, 0),
  starCount: t.optional(t.number, 0),
  forkCount: t.optional(t.number, 0),
  watchCount: t.optional(t.number, 0),

  primaryLanguage: t.optional(Language, { name: '', color: 'grey' }),
  license: t.optional(t.string, 'MIT'),
  releaseTag: t.maybeNull(t.string),
  contributors: t.array(Contributor),

  author: t.maybeNull(User),
  views: t.optional(t.number, 0),
  pin: t.maybeNull(t.boolean),

  favoritedCount: t.optional(t.number, 0),
  viewerHasFavorited: t.optional(t.boolean, false),
  favoritedCategoryId: t.maybeNull(t.string),

  communities: t.optional(t.array(Community), []),
  tags: t.optional(t.array(Tag), []),

  lastSync: t.maybeNull(t.string),
  pagedCommentsParticipators: t.optional(PagedUsers, {}),

  viewerHasViewed: t.optional(t.boolean, false),

  insertedAt: t.optional(t.string, ''),
  updatedAt: t.optional(t.string, ''),
})

export const PagedRepos = t.model('PagedRepos', {
  entries: t.optional(t.array(Repo), []),
  pageNumber: t.optional(t.number, 1),
  pageSize: t.optional(t.number, PAGE_SIZE.D),
  totalCount: t.optional(t.number, 0),
  totalPages: t.optional(t.number, 0),
})
<commit_msg>chore: merge branch 'dev'<commit_after>import { types as t } from 'mobx-state-tree'

import { PAGE_SIZE } from 'config'

import { User, PagedUsers } from './User'
import { Community } from './Community'
import { Tag } from './Tag'

const Contributor = t.model('Contributor', {
  avatar: t.string,
  nickname: t.string,
  htmlUrl: t.string,
})

const Language = t.model('Language', {
  name: t.string,
  color: t.string,
})

export const Repo = t.model('Reop', {
  id: t.maybeNull(t.string),
  title: t.maybeNull(t.string),
  ownerName: t.maybeNull(t.string),
  ownerUrl: t.maybeNull(t.string),
  repoUrl: t.maybeNull(t.string),

  desc: t.maybeNull(t.string),
  homepageUrl: t.maybeNull(t.string),
  readme: t.maybeNull(t.string),

  issuesCount: t.optional(t.number, 0),
  prsCount: t.optional(t.number, 0),
  starCount: t.optional(t.number, 0),
  forkCount: t.optional(t.number, 0),
  watchCount: t.optional(t.number, 0),

  primaryLanguage: t.optional(Language, { name: '', color: 'grey' }),
  license: t.maybeNull(t.string),
  releaseTag: t.maybeNull(t.string),
  contributors: t.array(Contributor),

  author: t.maybeNull(User),
  views: t.optional(t.number, 0),
  pin: t.maybeNull(t.boolean),

  favoritedCount: t.optional(t.number, 0),
  viewerHasFavorited: t.optional(t.boolean, false),
  favoritedCategoryId: t.maybeNull(t.string),

  communities: t.optional(t.array(Community), []),
  tags: t.optional(t.array(Tag), []),

  lastSync: t.maybeNull(t.string),
  pagedCommentsParticipators: t.optional(PagedUsers, {}),

  viewerHasViewed: t.optional(t.boolean, false),

  insertedAt: t.optional(t.string, ''),
  updatedAt: t.optional(t.string, ''),
})

export const PagedRepos = t.model('PagedRepos', {
  entries: t.optional(t.array(Repo), []),
  pageNumber: t.optional(t.number, 1),
  pageSize: t.optional(t.number, PAGE_SIZE.D),
  totalCount: t.optional(t.number, 0),
  totalPages: t.optional(t.number, 0),
})
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var async = require('async');
var mongoose = require('mongoose');
var grid = require('gridfs-stream');
var stream = require('stream');
var DocumentCategory = require('./document-category.model');
var DocumentTypes = require('./documentTypes');

var allDocumentTypes = DocumentTypes.obligatoires.concat(DocumentTypes.complementaires);
grid.mongo = mongoose.mongo;

function comparePosition(catA, catB) {
  return catA.position - catB.position;
}

function populateCategoryBarcode(category, callback) {
  if (!category.barcode) {
    return callback(null, category);
  }

  var gfs = grid(mongoose.connection.db);
  gfs.findOne({_id: category.barcode}, function(err, file) {
    category.barcode = file;
    callback(null, category);
  });
}

function createSpecialCategory(options, callback) {
  var newCategory = new DocumentCategory(options);

  if (newCategory.unclassified) {
    newCategory.label = 'Documents non catégorisés';
  } else {
    newCategory.label = 'Document de la demande';
  }

  newCategory.save(callback);
}

function getOrCreateSpecialCategory(options, callback) {
  var search = options;

  DocumentCategory
    .findOne(options)
    .lean()
    .exec(function(err, category) {
      if (err) callback(err);
      if (!category) {
        createSpecialCategory(options, callback);
      } else {
        populateCategoryBarcode(category, callback);
      }
    });
}

exports.getUnclassifiedCategory = function(mdph, callback) {
  return getOrCreateSpecialCategory({mdph: mdph._id, unclassified: true}, callback);
};

exports.getPdfCategory = function(mdph, callback) {
  return getOrCreateSpecialCategory({mdph: mdph._id, required: true}, callback);
};

exports.findAndSortCategoriesForMdph = function(mdph, callback) {
  DocumentCategory
    .find({mdph: mdph._id, unclassified: {$ne: true}})
    .lean()
    .exec(function(err, list) {
      if (err) { callback(err); }

      if (!list) { callback(null, []); }

      // "Populate" documents
      var gfs = grid(mongoose.connection.db);

      async.map(list, function(category, mapCallback) {
        if (category.documentTypes && category.documentTypes.length > 0) {
          // Poor man's population
          let fullTypes = [];
          category.documentTypes.forEach(function(documentType) {
            fullTypes.push(_.find(allDocumentTypes, {id: documentType}));
          });

          category.documentTypes = fullTypes;
        }

        populateCategoryBarcode(category, mapCallback);
      },

      function() {
        // Sort by position in the tree
        list.sort(comparePosition);

        return callback(null, list);
      });
    });
};

exports.showUncategorizedDocumentTypes = function(mdph, callback) {
  DocumentCategory
    .find({mdph: mdph._id})
    .lean()
    .exec(function(err, list) {
      if (err) { callback(err); }

      if (!list) { callback({status: 404}); }

      var filteredList = [];
      let found;
      _.forEach(allDocumentTypes, function(documentType) {
        found = false;
        _.forEach(list, function(category) {
          if (category.documentTypes && category.documentTypes.indexOf(documentType.id) >= 0) {
            found = true;
          }
        });

        if (!found) {
          filteredList.push(documentType);
        }
      });

      callback(null, filteredList);
    });
};

exports.saveDocumentCategoryFile = function(file, categoryId, logger, callback) {
  var gfs = grid(mongoose.connection.db);

  var writeStream = gfs.createWriteStream({
    filename: file.originalname,
    mimetype: file.mimetype
  });

  var bufferStream = new stream.PassThrough();
  bufferStream.end(file.buffer);
  bufferStream.pipe(writeStream);

  writeStream.on('close', function(file) {
    DocumentCategory.findById(categoryId, function(err, category) {
      if (err) { return callback(err); }

      if (category.barcode) {
        // remove existing file, only one allowed
        gfs.remove({_id: category.barcode}, function(err) {
          if (err) return callback(err);

          logger.info('Removed gfs file "' + category.barcode + '" for category "' + category._id + '"', category);
        });
      }

      category
        .set('barcode', file._id)
        .save(function(err, updated) {
          if (err) { return callback(err); }

          return callback(null, file);
        });
    });
  });
};

exports.getDocumentCategoryFile = function(categoryId, callback) {
  DocumentCategory.findById(categoryId, function(err, category) {
    if (err) { return callback(err); }

    if (category.barcode) {
      var gfs = grid(mongoose.connection.db);
      var readstream = gfs.createReadStream({_id: category.barcode});
      callback(null, readstream);
    } else {
      callback();
    }
  });
};

exports.createNewDocumentCategory = function(mdph, position, callback) {
  var newCategory = new DocumentCategory({
    mdph: mdph._id,
    position: position
  });

  newCategory.save(callback);
};

exports.updateDocumentCategory = function(categoryId, label, callback) {
  DocumentCategory.findById(categoryId, function(err, category) {
    if (err) { return callback(err); }

    category
      .set('label', label)
      .save(function(err, updated) {
        if (err) { return callback(err); }

        return callback(null, updated);
      });
  });
};

exports.removeDocumentCategory = function(categoryId, callback) {
  DocumentCategory
    .findById(categoryId)
    .remove()
    .exec(callback);
};

exports.updateDocumentCategories = function(updatedCategories, callback) {
  async.map(updatedCategories, function(positionObj, mapCallback) {
    DocumentCategory
      .findById(positionObj._id)
      .exec(function(err, category) {
        if (err) {
          mapCallback(err);
        }

        category
          .set('position', positionObj.position)
          .save(mapCallback);
      });
  },

  function(err) {
    callback(err);
  });
};

exports.updateDocumentType = function(documentType, oldCategoryId, newCategoryId, callback) {
  async.parallel({
    old: function(cb) {
      if (!oldCategoryId) {
        cb();
      } else {
        DocumentCategory.findById(oldCategoryId).exec(cb);
      }
    },

    new: function(cb) {
      if (!newCategoryId) {
        cb();
      } else {
        DocumentCategory.findById(newCategoryId).exec(cb);
      }
    }
  },
  function(err, results) {
    if (err) {
      callback(err);
    }

    if (results.old) {
      results.old.update(
        { $pull: { documentTypes: documentType } }
      ).exec();
    }

    if (results.new) {
      results.new.update(
        { $push: { documentTypes: documentType } }
      ).exec();
    }

    callback();
  });
};
<commit_msg>Update document-category.controller.js<commit_after>'use strict';

var _ = require('lodash');
var async = require('async');
var mongoose = require('mongoose');
var grid = require('gridfs-stream');
var stream = require('stream');
var DocumentCategory = require('./document-category.model');
var DocumentTypes = require('./documentTypes');

var allDocumentTypes = DocumentTypes.obligatoires.concat(DocumentTypes.complementaires);
grid.mongo = mongoose.mongo;

function comparePosition(catA, catB) {
  return catA.position - catB.position;
}

function populateCategoryBarcode(category, callback) {
  if (!category.barcode) {
    return callback(null, category);
  }

  var gfs = grid(mongoose.connection.db);
  gfs.findOne({_id: category.barcode}, function(err, file) {
    category.barcode = file;
    callback(null, category);
  });
}

function createSpecialCategory(options, callback) {
  var newCategory = new DocumentCategory(options);

  if (newCategory.unclassified) {
    newCategory.label = 'Documents non catégorisés';
  } else {
    newCategory.label = 'Document de la demande';
  }

  newCategory.save(callback);
}

function getOrCreateSpecialCategory(options, callback) {
  DocumentCategory
    .findOne(options)
    .lean()
    .exec(function(err, category) {
      if (err) callback(err);
      if (!category) {
        createSpecialCategory(options, callback);
      } else {
        populateCategoryBarcode(category, callback);
      }
    });
}

exports.getUnclassifiedCategory = function(mdph, callback) {
  return getOrCreateSpecialCategory({mdph: mdph._id, unclassified: true}, callback);
};

exports.getPdfCategory = function(mdph, callback) {
  return getOrCreateSpecialCategory({mdph: mdph._id, required: true}, callback);
};

exports.findAndSortCategoriesForMdph = function(mdph, callback) {
  DocumentCategory
    .find({mdph: mdph._id, unclassified: {$ne: true}})
    .lean()
    .exec(function(err, list) {
      if (err) { callback(err); }

      if (!list) { callback(null, []); }

      // "Populate" documents
      var gfs = grid(mongoose.connection.db);

      async.map(list, function(category, mapCallback) {
        if (category.documentTypes && category.documentTypes.length > 0) {
          // Poor man's population
          let fullTypes = [];
          category.documentTypes.forEach(function(documentType) {
            fullTypes.push(_.find(allDocumentTypes, {id: documentType}));
          });

          category.documentTypes = fullTypes;
        }

        populateCategoryBarcode(category, mapCallback);
      },

      function() {
        // Sort by position in the tree
        list.sort(comparePosition);

        return callback(null, list);
      });
    });
};

exports.showUncategorizedDocumentTypes = function(mdph, callback) {
  DocumentCategory
    .find({mdph: mdph._id})
    .lean()
    .exec(function(err, list) {
      if (err) { callback(err); }

      if (!list) { callback({status: 404}); }

      var filteredList = [];
      let found;
      _.forEach(allDocumentTypes, function(documentType) {
        found = false;
        _.forEach(list, function(category) {
          if (category.documentTypes && category.documentTypes.indexOf(documentType.id) >= 0) {
            found = true;
          }
        });

        if (!found) {
          filteredList.push(documentType);
        }
      });

      callback(null, filteredList);
    });
};

exports.saveDocumentCategoryFile = function(file, categoryId, logger, callback) {
  var gfs = grid(mongoose.connection.db);

  var writeStream = gfs.createWriteStream({
    filename: file.originalname,
    mimetype: file.mimetype
  });

  var bufferStream = new stream.PassThrough();
  bufferStream.end(file.buffer);
  bufferStream.pipe(writeStream);

  writeStream.on('close', function(file) {
    DocumentCategory.findById(categoryId, function(err, category) {
      if (err) { return callback(err); }

      if (category.barcode) {
        // remove existing file, only one allowed
        gfs.remove({_id: category.barcode}, function(err) {
          if (err) return callback(err);

          logger.info('Removed gfs file "' + category.barcode + '" for category "' + category._id + '"', category);
        });
      }

      category
        .set('barcode', file._id)
        .save(function(err, updated) {
          if (err) { return callback(err); }

          return callback(null, file);
        });
    });
  });
};

exports.getDocumentCategoryFile = function(categoryId, callback) {
  DocumentCategory.findById(categoryId, function(err, category) {
    if (err) { return callback(err); }

    if (category.barcode) {
      var gfs = grid(mongoose.connection.db);
      var readstream = gfs.createReadStream({_id: category.barcode});
      callback(null, readstream);
    } else {
      callback();
    }
  });
};

exports.createNewDocumentCategory = function(mdph, position, callback) {
  var newCategory = new DocumentCategory({
    mdph: mdph._id,
    position: position
  });

  newCategory.save(callback);
};

exports.updateDocumentCategory = function(categoryId, label, callback) {
  DocumentCategory.findById(categoryId, function(err, category) {
    if (err) { return callback(err); }

    category
      .set('label', label)
      .save(function(err, updated) {
        if (err) { return callback(err); }

        return callback(null, updated);
      });
  });
};

exports.removeDocumentCategory = function(categoryId, callback) {
  DocumentCategory
    .findById(categoryId)
    .remove()
    .exec(callback);
};

exports.updateDocumentCategories = function(updatedCategories, callback) {
  async.map(updatedCategories, function(positionObj, mapCallback) {
    DocumentCategory
      .findById(positionObj._id)
      .exec(function(err, category) {
        if (err) {
          mapCallback(err);
        }

        category
          .set('position', positionObj.position)
          .save(mapCallback);
      });
  },

  function(err) {
    callback(err);
  });
};

exports.updateDocumentType = function(documentType, oldCategoryId, newCategoryId, callback) {
  async.parallel({
    old: function(cb) {
      if (!oldCategoryId) {
        cb();
      } else {
        DocumentCategory.findById(oldCategoryId).exec(cb);
      }
    },

    new: function(cb) {
      if (!newCategoryId) {
        cb();
      } else {
        DocumentCategory.findById(newCategoryId).exec(cb);
      }
    }
  },
  function(err, results) {
    if (err) {
      callback(err);
    }

    if (results.old) {
      results.old.update(
        { $pull: { documentTypes: documentType } }
      ).exec();
    }

    if (results.new) {
      results.new.update(
        { $push: { documentTypes: documentType } }
      ).exec();
    }

    callback();
  });
};
<|endoftext|>


<commit_before>'use strict';

var app = require('../..');
var request = require('supertest');
var auth = require("../../auth/local/test.integration");
var superwith = require("../superwith.integration");

var SectionEvent = require('./sectionevent.model');

var seed = require('../../config/seed');
var exampleSectionEvent = seed.exampleSectionEvent;
var exampleStudent = seed.exampleStudent;
var scheduler = require('../../schedule');

var newSectionEvent;

describe.only("SectionEvent Notification Handling", function(){
    var sectionEvent;

    before(done => {
        SectionEvent.findByIdAsync(exampleSectionEvent._id).then(se => {
            sectionEvent = se;
            done();
        });
    });

    var relatedUsers;
    describe("Static Methods", () => {
        before(done => {
            sectionEvent.getRelatedUsers().then(users => {
                relatedUsers = users;
                done();
            });
        });

        it("getRelatedUsers() should return users", () => {
            expect(relatedUsers).to.be.a('array');
        });
    });

    describe('Set notifications for event', function() {

      before((done)=>{
        scheduler.cancel({'data.user._id': exampleStudent._id})
          .then(numRemoved => {
            done();
          });
      });

      before((done)=>{
        sectionEvent.updateUserNotifications()
          .then(() => done());
      });

      it("should have given the user notifications", done => {
        scheduler.jobs({'data.user._id': exampleStudent._id}, function(err, jobs) {
          expect(jobs.length).to.be.at.least(1);
          done();
        });
      });

    });

});

describe('SectionEvent API:', function() {

  describe('GET /api/sectionevents', function() {
    var sectionevents;

    beforeEach(function(done) {
      auth.student.request(app)
        .get('/api/sectionevents?array=true') // TODO remove array=true
        .expect(200)
        .expect('Content-Type', /json/)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          sectionevents = res.body;
          done();
        });
    });

    it('should respond with JSON array', function() {
      expect(sectionevents).to.be.instanceOf(Array);
    });
  });

  describe('GET /api/sectionevents with options', () => {
      superwith.test(auth.student.request(app), '/api/sectionevents?array=true', [
          {
              param: "withEventInfo=true",
              should: "get event info",
              test: (svnts) => {
                  expect(svnts[0]).to.have.property('description');
                  expect(svnts[0]).to.have.property('title');
              }
          },
          {
              param: "withAuthor=true",
              should: "get section event author",
              test: (svnts) => {
                  expect(svnts[0].sectionEvents[0].author).to.have.property('_id');
              }
          },
          {
              param: "withSection=true",
              should: "get section event section",
              test: (svnts) => {
                  expect(svnts[0].sectionEvents[0].section).to.have.property('_id');
              },
              params: [
                  {
                      param: "withCourse=true",
                      should: "get section event section course",
                      test: (svnts) => {
                          expect(svnts[0].sectionEvents[0].section.course).to.have.property('_id');
                      }
                  },
                  {
                      param: "withSectionStudents=true",
                      should: "get section event section students",
                      test: (svnts) => {
                          expect(svnts[0].sectionEvents[0].section.students).to.be.a('array');
                      }
                  }
              ]
          }

      ])
  });

  describe('GET /api/sectionevents just count', () => {
      var number;

      beforeEach(function(done) {
        auth.student.request(app)
          .get('/api/sectionevents?onlyNumber=true')
          .expect(200)
          .expect('Content-Type', /json/)
          .end(function(err, res) {
            if (err) {
              return done(err);
            }
            number = res.body;
            done();
          });
      });

      it('should respond with JSON array', function() {
        expect(number).to.have.property('number');
        expect(number.number).to.be.a('number');
      });
  });

  describe('POST /api/sectionevents', function() {
    beforeEach(function(done) {
      auth.instructor.request(app)
        .post('/api/sectionevents')
        .send({
          section: '000000000000000000000120',
          course: '000000000000000000000010',
          submissionInstructions: 'New SectionEvent',
          author: '000000000000000000000003',
          creationDate: new Date(),
          info: '000000000000000000000020',
          _id: '555555555555555555555555'
        })
        .expect(201)
        .expect('Content-Type', /json/)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          newSectionEvent = res.body;
          done();
        });
    });

    it('should respond with the newly created sectionevent', function() {
      expect(newSectionEvent.submissionInstructions).to.equal('New SectionEvent');
    });

  });

  describe('GET /api/sectionevents/:id', function() {
    var sectionevent;

    beforeEach(function(done) {
      request(app)
        .get('/api/sectionevents/' + newSectionEvent._id)
        .expect(200)
        .expect('Content-Type', /json/)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          sectionevent = res.body;
          done();
        });
    });

    afterEach(function() {
      sectionevent = {};
    });

    it('should respond with the requested sectionevent', function() {
      expect(sectionevent.submissionInstructions).to.equal('New SectionEvent');
    });

  });

  describe('GET /api/sectionevents/:id with options', () => {
      superwith.test(request(app), `/api/sectionevents/${exampleSectionEvent._id}`, [
          {
              param: "withEventInfo=true",
              should: "get event info",
              test: (sectionEvent) => {
                  expect(sectionEvent.info).to.have.property("_id");
                  expect(sectionEvent.info).to.have.property("description");
              },
              params: [
                  {
                      param: "withEventInfoAuthor=true",
                      should: "get event info author",
                      test: (sectionEvent) => {
                          expect(sectionEvent.info.author).to.have.property("_id");
                      }
                  }
              ]
          },
          {
              param: "withSection=true",
              should: "get section",
              test: (sectionEvent) => {
                  expect(sectionEvent.section).to.have.property("_id");
              },
              params: [
                  {
                      param: "withSectionCourse=true",
                      should: "get section course",
                      test: (sectionEvent) => {
                          expect(sectionEvent.section.course).to.have.property("_id");
                      }
                  }
              ]
          },
          {
              param: "withAuthor=true",
              should: "get author",
              test: (sectionEvent) => {
                  expect(sectionEvent.author).to.have.property("_id");
              }
          }
      ])
  });

  describe('PUT /api/sectionevents/:id', function() {
    var updatedSectionEvent

    beforeEach(function(done) {
      auth.instructor.request(app)
        .put('/api/sectionevents/' + newSectionEvent._id)
        .send({
          submissionInstructions: 'Updated SectionEvent',
        })
        .expect(200)
        .expect('Content-Type', /json/)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          updatedSectionEvent = res.body;
          done();
        });
    });

    afterEach(function() {
      updatedSectionEvent = {};
    });

    it('should respond with the updated sectionevent', function() {
      expect(updatedSectionEvent.submissionInstructions).to.equal('Updated SectionEvent');
    });

  });

  describe('DELETE /api/sectionevents/:id', function() {

    it('should respond with 204 on successful removal', function(done) {
      auth.instructor.request(app)
        .delete('/api/sectionevents/' + newSectionEvent._id)
        .expect(204)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          done();
        });
    });

    it('should respond with 404 when sectionevent does not exist', function(done) {
      request(app)
        .get('/api/sectionevents/' + newSectionEvent._id)
        .expect(404)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          done();
        });
    });
  });

});
<commit_msg>updated sectionevent notifications to use promises<commit_after>'use strict';

var app = require('../..');
var request = require('supertest');
var auth = require("../../auth/local/test.integration");
var superwith = require("../superwith.integration");

var SectionEvent = require('./sectionevent.model');
var User = require("../user/user.model");

var seed = require('../../config/seed');
var exampleSectionEvent = seed.exampleSectionEvent;
var exampleStudent = seed.exampleStudent;
var scheduler = require('../../schedule');

var newSectionEvent;

describe("SectionEvent Notification Handling", function(){
    var sectionEvent;
    var student;

    before(() => {
        return SectionEvent.findByIdAsync(exampleSectionEvent._id).then(se => {
            sectionEvent = se;
        });
    });

    before(() => {
        return User.findByIdAsync(exampleStudent._id).then(stdent => {
          student = stdent;
        });
    });

    var relatedUsers;
    describe("Static Methods", () => {
        before(() => {
            return sectionEvent.getRelatedUsers().then(users => {
                relatedUsers = users;
            });
        });

        it("getRelatedUsers() should return users", () => {
            expect(relatedUsers).to.be.a('array');
        });
    });

    describe('Set notifications for event', function() {

      before(() => student.clearNotifications());

      before(()=> sectionEvent.updateUserNotifications());

      it("should have given the user notifications", () => {
        return student.getNotifications().then((jobs) => {
          expect(jobs.length).to.be.at.least(1);
        });
      });

    });

});

describe('SectionEvent API:', function() {

  describe('GET /api/sectionevents', function() {
    var sectionevents;

    beforeEach(function(done) {
      auth.student.request(app)
        .get('/api/sectionevents?array=true') // TODO remove array=true
        .expect(200)
        .expect('Content-Type', /json/)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          sectionevents = res.body;
          done();
        });
    });

    it('should respond with JSON array', function() {
      expect(sectionevents).to.be.instanceOf(Array);
    });
  });

  describe('GET /api/sectionevents with options', () => {
      superwith.test(auth.student.request(app), '/api/sectionevents?array=true', [
          {
              param: "withEventInfo=true",
              should: "get event info",
              test: (svnts) => {
                  expect(svnts[0]).to.have.property('description');
                  expect(svnts[0]).to.have.property('title');
              }
          },
          {
              param: "withAuthor=true",
              should: "get section event author",
              test: (svnts) => {
                  expect(svnts[0].sectionEvents[0].author).to.have.property('_id');
              }
          },
          {
              param: "withSection=true",
              should: "get section event section",
              test: (svnts) => {
                  expect(svnts[0].sectionEvents[0].section).to.have.property('_id');
              },
              params: [
                  {
                      param: "withCourse=true",
                      should: "get section event section course",
                      test: (svnts) => {
                          expect(svnts[0].sectionEvents[0].section.course).to.have.property('_id');
                      }
                  },
                  {
                      param: "withSectionStudents=true",
                      should: "get section event section students",
                      test: (svnts) => {
                          expect(svnts[0].sectionEvents[0].section.students).to.be.a('array');
                      }
                  }
              ]
          }

      ])
  });

  describe('GET /api/sectionevents just count', () => {
      var number;

      beforeEach(function(done) {
        auth.student.request(app)
          .get('/api/sectionevents?onlyNumber=true')
          .expect(200)
          .expect('Content-Type', /json/)
          .end(function(err, res) {
            if (err) {
              return done(err);
            }
            number = res.body;
            done();
          });
      });

      it('should respond with JSON array', function() {
        expect(number).to.have.property('number');
        expect(number.number).to.be.a('number');
      });
  });

  describe('POST /api/sectionevents', function() {
    beforeEach(function(done) {
      auth.instructor.request(app)
        .post('/api/sectionevents')
        .send({
          section: '000000000000000000000120',
          course: '000000000000000000000010',
          submissionInstructions: 'New SectionEvent',
          author: '000000000000000000000003',
          creationDate: new Date(),
          info: '000000000000000000000020',
          _id: '555555555555555555555555'
        })
        .expect(201)
        .expect('Content-Type', /json/)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          newSectionEvent = res.body;
          done();
        });
    });

    it('should respond with the newly created sectionevent', function() {
      expect(newSectionEvent.submissionInstructions).to.equal('New SectionEvent');
    });

  });

  describe('GET /api/sectionevents/:id', function() {
    var sectionevent;

    beforeEach(function(done) {
      request(app)
        .get('/api/sectionevents/' + newSectionEvent._id)
        .expect(200)
        .expect('Content-Type', /json/)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          sectionevent = res.body;
          done();
        });
    });

    afterEach(function() {
      sectionevent = {};
    });

    it('should respond with the requested sectionevent', function() {
      expect(sectionevent.submissionInstructions).to.equal('New SectionEvent');
    });

  });

  describe('GET /api/sectionevents/:id with options', () => {
      superwith.test(request(app), `/api/sectionevents/${exampleSectionEvent._id}`, [
          {
              param: "withEventInfo=true",
              should: "get event info",
              test: (sectionEvent) => {
                  expect(sectionEvent.info).to.have.property("_id");
                  expect(sectionEvent.info).to.have.property("description");
              },
              params: [
                  {
                      param: "withEventInfoAuthor=true",
                      should: "get event info author",
                      test: (sectionEvent) => {
                          expect(sectionEvent.info.author).to.have.property("_id");
                      }
                  }
              ]
          },
          {
              param: "withSection=true",
              should: "get section",
              test: (sectionEvent) => {
                  expect(sectionEvent.section).to.have.property("_id");
              },
              params: [
                  {
                      param: "withSectionCourse=true",
                      should: "get section course",
                      test: (sectionEvent) => {
                          expect(sectionEvent.section.course).to.have.property("_id");
                      }
                  }
              ]
          },
          {
              param: "withAuthor=true",
              should: "get author",
              test: (sectionEvent) => {
                  expect(sectionEvent.author).to.have.property("_id");
              }
          }
      ])
  });

  describe('PUT /api/sectionevents/:id', function() {
    var updatedSectionEvent

    beforeEach(function(done) {
      auth.instructor.request(app)
        .put('/api/sectionevents/' + newSectionEvent._id)
        .send({
          submissionInstructions: 'Updated SectionEvent',
        })
        .expect(200)
        .expect('Content-Type', /json/)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          updatedSectionEvent = res.body;
          done();
        });
    });

    afterEach(function() {
      updatedSectionEvent = {};
    });

    it('should respond with the updated sectionevent', function() {
      expect(updatedSectionEvent.submissionInstructions).to.equal('Updated SectionEvent');
    });

  });

  describe('DELETE /api/sectionevents/:id', function() {

    it('should respond with 204 on successful removal', function(done) {
      auth.instructor.request(app)
        .delete('/api/sectionevents/' + newSectionEvent._id)
        .expect(204)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          done();
        });
    });

    it('should respond with 404 when sectionevent does not exist', function(done) {
      request(app)
        .get('/api/sectionevents/' + newSectionEvent._id)
        .expect(404)
        .end(function(err, res) {
          if (err) {
            return done(err);
          }
          done();
        });
    });
  });

});
<|endoftext|>


<commit_before>
exports.up = function(knex, Promise) {
  return Promise.all([
    knex.schema.alterTable('users', function(table){
      table.unique('remote_id');
    }),
    knex.schema.alterTable('ads', function(table){
      table.dropForeign('user_id');
      table.foreign('user_id').references('id').inTable('users').onDelete('CASCADE');
    }),
    knex.schema.alterTable('answers', function(table){
      table.dropForeign('ad_id');
      table.foreign('ad_id').references('id').inTable('ads').onDelete('CASCADE');
      table.dropForeign('user_id');
      table.foreign('user_id').references('id').inTable('users').onDelete('CASCADE');
    })
  ]);
};

exports.down = function(knex, Promise) {
  return Promise.all([
    knex.schema.alterTable('users', function(table){
      table.dropUnique('remote_id');
    }),
    knex.schema.alterTable('ads', function(table){
      table.dropForeign('user_id');
      table.foreign('user_id').references('id').inTable('users');
    }),
    knex.schema.alterTable('answers', function(table){
      table.dropForeign('ad_id');
      table.foreign('ad_id').references('id').inTable('ads');
      table.dropForeign('user_id');
      table.foreign('user_id').references('id').inTable('users');
    })
  ]);
};<commit_msg>add cascade to sessions<commit_after>
exports.up = function(knex, Promise) {
  return Promise.all([
    knex.schema.alterTable('users', function(table){
      table.unique('remote_id');
    }),
    knex.schema.alterTable('ads', function(table){
      table.dropForeign('user_id');
      table.foreign('user_id').references('id').inTable('users').onDelete('CASCADE');
    }),
    knex.schema.alterTable('answers', function(table){
      table.dropForeign('ad_id');
      table.foreign('ad_id').references('id').inTable('ads').onDelete('CASCADE');
      table.dropForeign('user_id');
      table.foreign('user_id').references('id').inTable('users').onDelete('CASCADE');
    }),
    knex.schema.alterTable('sessions', function(table){
      table.dropForeign('user_id');
      table.foreign('user_id').references('id').inTable('users').onDelete('CASCADE');
    })
  ]);
};

exports.down = function(knex, Promise) {
  return Promise.all([
    knex.schema.alterTable('users', function(table){
      table.dropUnique('remote_id');
    }),
    knex.schema.alterTable('ads', function(table){
      table.dropForeign('user_id');
      table.foreign('user_id').references('id').inTable('users');
    }),
    knex.schema.alterTable('answers', function(table){
      table.dropForeign('ad_id');
      table.foreign('ad_id').references('id').inTable('ads');
      table.dropForeign('user_id');
      table.foreign('user_id').references('id').inTable('users');
    }),
    knex.schema.alterTable('sessions', function(table){
      table.dropForeign('user_id');
      table.foreign('user_id').references('id').inTable('users');
    })
  ]);
};<|endoftext|>


<commit_before>import { Platform, StyleSheet } from 'react-native';

import Colors from '../../constants/Colors';

const styles = StyleSheet.create({
  container: {
    flex: 0.2,
    backgroundColor: '#f7f7f7',
    flexDirection: 'row',
    marginTop: 5,
    paddingTop: 10,
  },
  responseContainer: {
    borderWidth: 0.5,
    borderColor: '#d6d7da',
    backgroundColor: 'white',
  },
  responseGrid: {
    flex: 1.6,
  },
  responseTab: {
    flex: 0.1,
    padding: 0,
    marginTop: 10,
    borderWidth: 0.5,
    borderColor: '#d6d7da',
    backgroundColor: '#f7f7f7',
  },
  viewTab: {
    marginTop: 10,
    marginBottom: 10,
    textAlign: 'center',
  },
  viewTabSelected: {
    marginTop: 10,
    marginBottom: 10,
    textAlign: 'center',
    color: Colors.mainTheme,
  },
  viewCol: {
    backgroundColor: '#f7f7f7',
  },
  responseStat: {
    marginTop: 10,
    color: '#c6c7c6',
    textAlign: 'left',
  },
  developmentModeText: {
    marginBottom: 20,
    color: 'rgba(0,0,0,0.4)',
    fontSize: 15,
    textAlign: 'center',
  },
  contentContainer: {
    paddingTop: 80,
  },
  welcomeContainer: {
    alignItems: 'center',
    marginTop: 10,
    marginBottom: 20,
  },
  welcomeImage: {
    width: 140,
    height: 38,
    resizeMode: 'contain',
    marginTop: 3,
    marginLeft: -10,
  },
  getStartedContainer: {
    alignItems: 'center',
    marginRight: 20,
    marginTop: 10,
    marginLeft: 100,
  },
  homeScreenFilename: {
    marginVertical: 7,
  },
  codeHighlightText: {
    color: 'rgba(96,100,109, 0.8)',
  },
  codeHighlightContainer: {
    backgroundColor: 'rgba(0,0,0,0.05)',
    borderRadius: 3,
    paddingHorizontal: 4,
  },
  getStartedText: {
    fontSize: 17,
    color: 'rgba(96,100,109, 1)',
    lineHeight: 23,
    textAlign: 'center',
  },
  tabBarInfoContainer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    ...Platform.select({
      ios: {
        shadowColor: 'black',
        shadowOffset: { height: -3 },
        shadowOpacity: 0.1,
        shadowRadius: 3,
      },
      android: {
        elevation: 20,
      },
    }),
    alignItems: 'center',
    backgroundColor: '#fbfbfb',
    paddingVertical: 20,
  },
  tabBarInfoText: {
    fontSize: 17,
    color: 'rgba(96,100,109, 1)',
    textAlign: 'center',
  },
  navigationFilename: {
    marginTop: 5,
  },
  helpContainer: {
    marginTop: 15,
    alignItems: 'center',
  },
  helpLink: {
    paddingVertical: 15,
  },
  helpLinkText: {
    fontSize: 14,
    color: '#2e78b7',
  },
  pickerContainer: {
    flex: 0.22,
    marginRight: 10,
    height: 40,
    marginTop: 5,
    borderBottomRightRadius: 7,
    borderTopRightRadius: 7,
  },
  sendButton: {
    marginTop: 5,
    height: 40,
    flex: 0.05,
    borderBottomLeftRadius: 7,
    borderTopLeftRadius: 7,
    backgroundColor: '#4fca34',
  },
  urlBox: {
    backgroundColor: 'white',
    borderBottomLeftRadius: 3,
    borderTopLeftRadius: 3,
    paddingLeft: 10,
    flex: 0.30,
    height: 50,
  },
  url: {
    fontSize: 14,
  },
  requestHeader: {
    borderWidth: 0,
    marginRight: 10,
    backgroundColor: 'white',
    shadowColor: 'transparent',
    shadowOpacity: 0,
  },
  requestPicker: {
    borderBottomRightRadius: 5,
    borderTopRightRadius: 5,
    overflow: 'hidden',
  },
});

export default styles;
<commit_msg>#17 | Modify height of URL input field to fix minor display issue<commit_after>import { Platform, StyleSheet } from 'react-native';

import Colors from '../../constants/Colors';

const styles = StyleSheet.create({
  container: {
    flex: 0.2,
    backgroundColor: '#f7f7f7',
    flexDirection: 'row',
    marginTop: 5,
    paddingTop: 10,
  },
  responseContainer: {
    borderWidth: 0.5,
    borderColor: '#d6d7da',
    backgroundColor: 'white',
  },
  responseGrid: {
    flex: 1.6,
  },
  responseTab: {
    flex: 0.1,
    padding: 0,
    marginTop: 10,
    borderWidth: 0.5,
    borderColor: '#d6d7da',
    backgroundColor: '#f7f7f7',
  },
  viewTab: {
    marginTop: 10,
    marginBottom: 10,
    textAlign: 'center',
  },
  viewTabSelected: {
    marginTop: 10,
    marginBottom: 10,
    textAlign: 'center',
    color: Colors.mainTheme,
  },
  viewCol: {
    backgroundColor: '#f7f7f7',
  },
  responseStat: {
    marginTop: 10,
    color: '#c6c7c6',
    textAlign: 'left',
  },
  developmentModeText: {
    marginBottom: 20,
    color: 'rgba(0,0,0,0.4)',
    fontSize: 15,
    textAlign: 'center',
  },
  contentContainer: {
    paddingTop: 80,
  },
  welcomeContainer: {
    alignItems: 'center',
    marginTop: 10,
    marginBottom: 20,
  },
  welcomeImage: {
    width: 140,
    height: 38,
    resizeMode: 'contain',
    marginTop: 3,
    marginLeft: -10,
  },
  getStartedContainer: {
    alignItems: 'center',
    marginRight: 20,
    marginTop: 10,
    marginLeft: 100,
  },
  homeScreenFilename: {
    marginVertical: 7,
  },
  codeHighlightText: {
    color: 'rgba(96,100,109, 0.8)',
  },
  codeHighlightContainer: {
    backgroundColor: 'rgba(0,0,0,0.05)',
    borderRadius: 3,
    paddingHorizontal: 4,
  },
  getStartedText: {
    fontSize: 17,
    color: 'rgba(96,100,109, 1)',
    lineHeight: 23,
    textAlign: 'center',
  },
  tabBarInfoContainer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    ...Platform.select({
      ios: {
        shadowColor: 'black',
        shadowOffset: { height: -3 },
        shadowOpacity: 0.1,
        shadowRadius: 3,
      },
      android: {
        elevation: 20,
      },
    }),
    alignItems: 'center',
    backgroundColor: '#fbfbfb',
    paddingVertical: 20,
  },
  tabBarInfoText: {
    fontSize: 17,
    color: 'rgba(96,100,109, 1)',
    textAlign: 'center',
  },
  navigationFilename: {
    marginTop: 5,
  },
  helpContainer: {
    marginTop: 15,
    alignItems: 'center',
  },
  helpLink: {
    paddingVertical: 15,
  },
  helpLinkText: {
    fontSize: 14,
    color: '#2e78b7',
  },
  pickerContainer: {
    flex: 0.22,
    marginRight: 10,
    height: 40,
    marginTop: 5,
    borderBottomRightRadius: 7,
    borderTopRightRadius: 7,
  },
  sendButton: {
    marginTop: 5,
    height: 40,
    flex: 0.05,
    borderBottomLeftRadius: 7,
    borderTopLeftRadius: 7,
    backgroundColor: '#4fca34',
  },
  urlBox: {
    backgroundColor: 'white',
    borderBottomLeftRadius: 3,
    borderTopLeftRadius: 3,
    paddingLeft: 10,
    flex: 0.30,
    height: 45,
  },
  url: {
    fontSize: 14,
  },
  requestHeader: {
    borderWidth: 0,
    marginRight: 10,
    backgroundColor: 'white',
    shadowColor: 'transparent',
    shadowOpacity: 0,
  },
  requestPicker: {
    borderBottomRightRadius: 5,
    borderTopRightRadius: 5,
    overflow: 'hidden',
  },
});

export default styles;
<|endoftext|>


<commit_before>define([
  'underscore',
  'mockup-ui-url/views/popover',
  'text!mockup-patterns-filemanager-url/templates/popover.xml',
], function(_, PopoverView, PopoverTemplate) {
  'use strict';

  var FileManagerPopover = PopoverView.extend({
    className: 'popover',
    title: _.template('nothing'),
    content: _.template('<div/>'),
    template: PopoverTemplate,
    initialize: function(options) {
      this.app = options.app;
      PopoverView.prototype.initialize.apply(this, [options]);
    },
    afterRender: function () {
      var self = this;
      self.$el.find(".popover-close").click(function(e){
        self.hide(true);
      });
      return self;
    },
    getBodyClassName: function(){
      var name = 'popover-';
      if(this.options.id){
        name += this.options.id + '-';
      }
      name += 'active';
      return name;
    },
    render: function() {
      var self = this;
      PopoverView.prototype.render.call(this);
      return self;
    },
    hide: function(closePopover) {
      if(this.closeOnOutClick || closePopover == true){
        this.opened = false;
        this.$el.removeClass('active');
        if (this.triggerView) {
          this.triggerView.$el.removeClass('active');
          this.triggerView.$el.attr('aria-hidden', 'true');
        }
        this.uiEventTrigger('hide', this);
        this.$el.attr('aria-hidden', 'true');
        $('body').removeClass(this.getBodyClassName());
      }
    },
    toggle: function(button, e) {
      PopoverView.prototype.toggle.apply(this, [button, e]);
      var self = this;
      if (!self.opened) {
        return;
      }
      var $path = self.$('.current-path');
      if ($path.length !== 0) {
        $path.html(self.getPath());
      }
    },
    getPath: function() {
      return this.app.getFolderPath();
    }
  });

  return FileManagerPopover;
});
<commit_msg>Add missing jquery dependency for basepopover<commit_after>define([
  'jquery',
  'underscore',
  'mockup-ui-url/views/popover',
  'text!mockup-patterns-filemanager-url/templates/popover.xml',
], function($, _, PopoverView, PopoverTemplate) {
  'use strict';

  var FileManagerPopover = PopoverView.extend({
    className: 'popover',
    title: _.template('nothing'),
    content: _.template('<div/>'),
    template: PopoverTemplate,
    initialize: function(options) {
      this.app = options.app;
      PopoverView.prototype.initialize.apply(this, [options]);
    },
    afterRender: function () {
      var self = this;
      self.$el.find(".popover-close").click(function(e){
        self.hide(true);
      });
      return self;
    },
    getBodyClassName: function(){
      var name = 'popover-';
      if(this.options.id){
        name += this.options.id + '-';
      }
      name += 'active';
      return name;
    },
    render: function() {
      var self = this;
      PopoverView.prototype.render.call(this);
      return self;
    },
    hide: function(closePopover) {
      if(this.closeOnOutClick || closePopover == true){
        this.opened = false;
        this.$el.removeClass('active');
        if (this.triggerView) {
          this.triggerView.$el.removeClass('active');
          this.triggerView.$el.attr('aria-hidden', 'true');
        }
        this.uiEventTrigger('hide', this);
        this.$el.attr('aria-hidden', 'true');
        $('body').removeClass(this.getBodyClassName());
      }
    },
    toggle: function(button, e) {
      PopoverView.prototype.toggle.apply(this, [button, e]);
      var self = this;
      if (!self.opened) {
        return;
      }
      var $path = self.$('.current-path');
      if ($path.length !== 0) {
        $path.html(self.getPath());
      }
    },
    getPath: function() {
      return this.app.getFolderPath();
    }
  });

  return FileManagerPopover;
});
<|endoftext|>


<commit_before>"use strict";

({define:typeof define!="undefined"?define:function(deps, factory){module.exports = factory(exports, require("./parser"));}}).
define(["exports", "./parser"], function(exports, parser){

	function short(fullname){
		var n = fullname.split(":");
		return (n[0]+n[1].charAt(0).toUpperCase()+n[1].substr(1)).replace(/#|-/g,"");
	}

	function Transpiler(execute){
		this.dict = {};
		this.lib = {};
		this.cache = [];
		this.count = 0;
	}

	Transpiler.prototype.use = function(value,params,callback){
		// TODO filter and separate core definitions
		var core = value.args;
		var reqs = core.map(function(_){
			return "intern/dojo/text!/raddled/"+_+".rdl";
		});
		var self = this;
		require(core.map(function(_){ return _ }),function(){
			var libs = Array.prototype.slice.call(arguments);
			libs.forEach(function(lib,i){
				var nslib = {};
				for(var k in lib){
					var name = core[i].split("/")[0]+":"+k;
					console.warn(name);
					if(!self.lib[name]) self.lib[name] = lib[k];
				}
			});
			require(reqs,function(){
				var deps = Array.prototype.slice.call(arguments);
				deps.forEach(function(dep,i){
					var parsed = parser.parse(dep);
					if(parsed.args.length) self.process(parsed,{use:core[i]},callback);
				});
				if(callback) callback();
			});
		});
	};

	Transpiler.prototype.transpile = function(value,params){
		this.cache = [];
		var ret = this.process(value,params).filter(function(_){
			return !!_;
		}).pop();
		if(params.callback) {

		}
		return ret;
	};

	Transpiler.prototype.process = function(value,params,callback){
		var args = Array.prototype.slice.call(arguments);
		var value = args.shift();
		var params = args.length>1 && typeof args[0]!="function" ? args.shift() : {};
		var callback = args.shift();
		if(typeof value == "string") value = parser.parse(value);
		if(value.name=="use"){
			this.use(value,params,callback);
		} else if(value.name=="define"){
			this.define(value,params);
		} else if(value.name=="" && value.args) {
			var self=this,use,define=[],args=[];
			value.args.forEach(function(arg){
				if(arg.name=="use") {
					use = arg;
				} else if(arg.name=="define"){
					define.push(arg);
				} else {
					args.push(arg);
				}
			});
			var cb = !params.use && !!callback ? callback : function(){};
			callback = function(){
				define.forEach(function(arg){
					self.define(arg,params);
				});
				var ret = args.map(function(arg){
					return self.process(arg,params,callback);
				}).pop();
				// always return a function
				if(!ret) ret = function anon0() {};
				cb(null,ret);
			};
			use ? this.use(use,params,callback) : callback();
		} else {
			value.top = true;
			return this.compile(value);
		}
	};

	function typeOf(o) {
		return o === undefined ? "undefined" : o === null ? "null" : o.constructor.name.toLowerCase();
	}

	Transpiler.prototype.typeCheck = function(value,type){
		// TODO check occurrence and function arity+types
		var t = typeOf(type) == "array" ? "function" : type.replace(/\?|\+|\*|-/,"");
		return typeOf(value)==t || t=="any";
	};

	var autoConverted = {
		"true": true,
		"false": false,
		"null": null,
		"undefined": undefined,
		"Infinity": Infinity,
		"-Infinity": -Infinity
	};

	Transpiler.prototype.convert = function(string){
		if(autoConverted.hasOwnProperty(string)){
			return autoConverted[string];
		}
		var number = +string;
		if(isNaN(number) || number.toString() !== string){
			/*var isoDate = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/.exec(x);
			if (isoDate) {
			date = new Date(Date.UTC(+isoDate[1], +isoDate[2] - 1, +isoDate[3], +isoDate[4], +isoDate[5], +isoDate[6], +isoDate[7] || 0));
			}*/
			string = decodeURIComponent(string);
			if(exports.jsonQueryCompatible){
				if(string.charAt(0) == "'" && string.charAt(string.length-1) == "'"){
					return JSON.parse('"' + string.substring(1,string.length-1) + '"');
				}
			}
			return string;
		}
		return number;
	};

	Transpiler.prototype.getFunction = function(fullname){
		return this.lib[fullname];
	};

	Transpiler.prototype.getFunctionDef = function(qname,arity){
		if(!this.dict[qname]) return;
		return this.dict[qname][arity+1] ? this.dict[qname][arity+1] : this.dict[qname][0];
	};

	Transpiler.prototype.coerce = function(value,type){
		// should we infer and check?
		if (type === 'string') {
			value = value ? '' + value : '';
		} else if (type === 'number') {
			value = +value;
		} else if (type === 'boolean') {
			value = !!value;
//		} else if (type === 'array') {
//			if(!(value instanceof Array)) value = new Array();
//		} else if (type === 'object') {
//			if(!(value instanceof Object)) value = new Object();
		} else if (type instanceof Array) {
			var def = this.dict[value];
			value = this.lib[def.module][value];
		}
		return value;
	};

	Transpiler.prototype.type = function(t){
		var ts = ["null","number","string","boolean","node","map","function","any"];
		// return tuple: [type,cardinality]
		var rt = new Array(2);
		var card = -1;
		var type = 0;
		// TODO ?
		var re = /(\*)|(\+)|(\-)/;
		var gr = t.match(re);
		if(gr) {
			var i=0,l=gr.length;
			for(;i<l;i++){
				if(gr[i+1]) break;
			}
			card = i;
		}
		type = ts.indexOf(t.replace(re,""));
		return [type,card];
	};

	Transpiler.prototype.matchTypes = function(i,o){
		var ti = this.type(i);
		var to = this.type(o);
		//console.warn(i,ti,"->",o,to);
		// cardinality checks:
		// string->string* -1->0 => allow
		// string*->string 0->-1 => deny
		// string->string+ -1->1 => deny
		// string*->string+ 0->1 => allow (runtime check)
		// string->any 2->7 => allow
		// any->string 7->2 => allow (infer+check @ runtime)
		var d = to[1]-ti[1];
		return (ti[0]==to[0] || to[0]==7 || ti[0]==7) && d>=0 && d<=1;
	};

	Transpiler.prototype.compile = function(value,parent,compose){
		var self = this;
		var isSeq = typeOf(value)=="array";
		var top = isSeq ? false : value.top;
		var fargs = parent ? parent.args.map(function(_,i){
			return "arg" + (i+1);
		}).join(",") : "arg0";
		var fname = "anon"+this.count;
		if(parent){
			var parity = parent.more ? "N" : parent.args.length;
			fname = short(parent.name+"#"+parity);
		} else if(top) {
			this.count++;
		}
		if(isSeq) {
			var seq = value.map(function(_){
				if(typeOf(_)=="query"){
					// compose the functions in the array
					return "arg0 = "+this.compile(_,null,true).toString()+";\n";
				} else {
					return _;
				}
			},this);
			var pre = parent ? "var arg0;\n" : "";
			return new Function("return function "+fname+"("+fargs+"){\n"+pre+seq.join("")+"return arg0;\n}")();
		}
		var name = value.name,
			args = value.args;
		if(!name.match(/:/)) name = "core:"+name;
		var def = this.getFunctionDef(name,args.length);
		var fullname = name+"#"+(def.more ? "N" : def.args.length);
		if(this.cache.indexOf(fullname)==-1) this.cache.push(fullname);
		args = args.map(function(_){
			if(typeOf(_) == "array") {
				return this.compile(_,null,null).toString();
			} else if(typeOf(_) == "query") {
				return this.compile(_,null,null);
			} else if(_.match(/^(\.\/)|\.$/)) {
				return _;
			} else if(_.match(/^\$[0-9]+$/)) {
				return _.replace(/^\$([0-9]+)$/,"arg$1");
			} else {
				var r = this.convert(_);
				if(typeof r=="string" && r.match(/^.+#[0-9]+$/)){
					var fullname = (r.indexOf(":")>-1 ? r : "core:"+r);
					if(this.cache.indexOf(fullname)==-1) this.cache.push(fullname);
					return short(fullname);
				}
				// check type here
				//if(!this.typeCheck(r,t)){
				//	throw new Error("Expected type ",t," for argument value ",r);
				//}
				return JSON.stringify(r);
			}
		},this);
		var args2 = args.reduce(function(pre,cur,i){
			if(cur.match(/^(\.\/)|\.$/)) {
				pre.push("arg0");
			} else {
				var s = pre.length-1;
				var last = pre[s];
				if(last.match(/^(\.\/)|\.$/) || s<1) {
					pre.push(cur);
				} else {
					pre[s] = last + "," + cur;
				}
			}
			return pre;
		},[short(fullname) + "("]);
		args2.push(")");
		var fn = args2.join("");
		if(compose) return fn;
		var fns = "\n";
		if(top) {
			for(var i=0;i<this.cache.length;i++){
				var f = this.getFunction(this.cache[i]);
				fns += "var "+short(this.cache[i])+"="+f.toString()+";\n";
			}
		}
		return new Function("return function "+fname+"("+fargs+"){ "+fns+"return "+fn+";}")();
	};

	Transpiler.prototype.define = function(value,params){
		this.cache = [];
		var l = value.args.length;
		var parts = value.args[0].split(":");
		var name = parts.pop();
		var module = "";
		var ns = parts.length ? parts[0] : "local";
		var type, args = [], qname;
		var body,def;
		if(l==2){
			// lookup
			def = this.dict[value.args[1]];
			if(!def) {
				throw new Error("Unknown reference in definition "+name);
			}
			type = def.type;
			args = def.args;
			body = def.body;
			module = def.module;
			qname = ns+":"+name;
		} else if(l==3 || l==4){
			if(l==3) {
				module = params.use;
				if(ns=="local"){
					ns = module.split("/")[0];
				}
			} else {
				body = value.args[3];
				module = ns;
			}
			// core
			args = value.args[1];
			type = value.args[2];
			qname = ns+":"+name;
		}
		var len = args.length;
		// check if more argument of last type is allowed
		var last = args[len-1];
		var more = typeOf(last) == "string" ? last.substr(-1) === "-" : false;
		var arity = more ? -1 : len;
		var existing = this.getFunctionDef(qname,arity);
		if(existing) return existing;
		def = {
			name:qname,
			type:type,
			args:args,
			more:more,
			body:body,
			module:module
		};
		if(!this.dict[qname]){
			this.dict[qname] = [];
		}
		this.dict[qname][arity+1] = def;
		if(l==4) {
			// compile definition
			this.lib[qname+"#"+(arity<0 ? "N" : arity)] = this.compile(body,def);
		}
		return def;
	};
	exports.Transpiler = Transpiler;

	return exports;
});<commit_msg>use require to load js modules from identical paths<commit_after>"use strict";

({define:typeof define!="undefined"?define:function(deps, factory){module.exports = factory(exports, require("./parser"));}}).
define(["exports", "./parser"], function(exports, parser){

	function short(fullname){
		var n = fullname.split(":");
		return (n[0]+n[1].charAt(0).toUpperCase()+n[1].substr(1)).replace(/#|-/g,"");
	}

	function Transpiler(execute){
		this.dict = {};
		this.lib = {};
		this.cache = [];
		this.count = 0;
	}

	Transpiler.prototype.use = function(value,params,callback){
		// TODO filter and separate core definitions
		var modulePath = params.modules || "raddle/modules.json";
		var textPrefix = params.moduleTextPrefix || "text!";
		var defaultNamespace = params.defaultNamespace || "core";
		var use = value.args;
		var self = this;
		//require([textPrefix+modulePath],function(moduleText){
			/*var modules = JSON.parse(moduleText);
			var moduleMap = {};
			for(var i=0,l=modules.length;i<l;i++) {
				moduleMap[modules[i].prefix ? modules[i].prefix : defaultNamespace] = modules[i];
			}*/
			var reqs = use.map(function(_){
				return textPrefix+"raddled/"+_+".rdl";
			});
			/*var core = use.map(function(_){
				// FIXME don't use first part of path as namespace!
				var parts = _.split("/");
				var ns = parts.shift();
				var mod = moduleMap[ns];
				return mod.location+"/"+parts.join("/");
			});*/
			require(use,function(){
				var libs = Array.prototype.slice.call(arguments);
				libs.forEach(function(lib,i){
					for(var k in lib){
						var name = use[i].split("/")[0]+":"+k;
						if(!self.lib[name]) self.lib[name] = lib[k];
					}
				});
				require(reqs,function(){
					var deps = Array.prototype.slice.call(arguments);
					deps.forEach(function(dep,i){
						var parsed = parser.parse(dep);
						if(parsed.args.length) self.process(parsed,{use:use[i]},callback);
					});
					if(callback) callback();
				});
			});
		//});
	};

	Transpiler.prototype.transpile = function(value,params){
		this.cache = [];
		var ret = this.process(value,params).filter(function(_){
			return !!_;
		}).pop();
		if(params.callback) {

		}
		return ret;
	};

	Transpiler.prototype.process = function(value,params,callback){
		var args = Array.prototype.slice.call(arguments);
		var value = args.shift();
		var params = args.length>1 && typeof args[0]!="function" ? args.shift() : {};
		var callback = args.shift();
		if(typeof value == "string") value = parser.parse(value);
		if(value.name=="use"){
			this.use(value,params,callback);
		} else if(value.name=="define"){
			this.define(value,params);
		} else if(value.name=="" && value.args) {
			var self=this,use,define=[],args=[];
			value.args.forEach(function(arg){
				if(arg.name=="use") {
					use = arg;
				} else if(arg.name=="define"){
					define.push(arg);
				} else {
					args.push(arg);
				}
			});
			var cb = !params.use && !!callback ? callback : function(){};
			callback = function(){
				define.forEach(function(arg){
					self.define(arg,params);
				});
				var ret = args.map(function(arg){
					return self.process(arg,params,callback);
				}).pop();
				// always return a function
				if(!ret) ret = function anon0() {};
				cb(null,ret);
			};
			use ? this.use(use,params,callback) : callback();
		} else {
			value.top = true;
			return this.compile(value);
		}
	};

	function typeOf(o) {
		return o === undefined ? "undefined" : o === null ? "null" : o.constructor.name.toLowerCase();
	}

	Transpiler.prototype.typeCheck = function(value,type){
		// TODO check occurrence and function arity+types
		var t = typeOf(type) == "array" ? "function" : type.replace(/\?|\+|\*|-/,"");
		return typeOf(value)==t || t=="any";
	};

	var autoConverted = {
		"true": true,
		"false": false,
		"null": null,
		"undefined": undefined,
		"Infinity": Infinity,
		"-Infinity": -Infinity
	};

	Transpiler.prototype.convert = function(string){
		if(autoConverted.hasOwnProperty(string)){
			return autoConverted[string];
		}
		var number = +string;
		if(isNaN(number) || number.toString() !== string){
			/*var isoDate = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/.exec(x);
			if (isoDate) {
			date = new Date(Date.UTC(+isoDate[1], +isoDate[2] - 1, +isoDate[3], +isoDate[4], +isoDate[5], +isoDate[6], +isoDate[7] || 0));
			}*/
			string = decodeURIComponent(string);
			if(exports.jsonQueryCompatible){
				if(string.charAt(0) == "'" && string.charAt(string.length-1) == "'"){
					return JSON.parse('"' + string.substring(1,string.length-1) + '"');
				}
			}
			return string;
		}
		return number;
	};

	Transpiler.prototype.getFunction = function(fullname){
		return this.lib[fullname];
	};

	Transpiler.prototype.getFunctionDef = function(qname,arity){
		if(!this.dict[qname]) return;
		return this.dict[qname][arity+1] ? this.dict[qname][arity+1] : this.dict[qname][0];
	};

	Transpiler.prototype.coerce = function(value,type){
		// should we infer and check?
		if (type === 'string') {
			value = value ? '' + value : '';
		} else if (type === 'number') {
			value = +value;
		} else if (type === 'boolean') {
			value = !!value;
//		} else if (type === 'array') {
//			if(!(value instanceof Array)) value = new Array();
//		} else if (type === 'object') {
//			if(!(value instanceof Object)) value = new Object();
		} else if (type instanceof Array) {
			var def = this.dict[value];
			value = this.lib[def.module][value];
		}
		return value;
	};

	Transpiler.prototype.type = function(t){
		var ts = ["null","number","string","boolean","node","map","function","any"];
		// return tuple: [type,cardinality]
		var rt = new Array(2);
		var card = -1;
		var type = 0;
		// TODO ?
		var re = /(\*)|(\+)|(\-)/;
		var gr = t.match(re);
		if(gr) {
			var i=0,l=gr.length;
			for(;i<l;i++){
				if(gr[i+1]) break;
			}
			card = i;
		}
		type = ts.indexOf(t.replace(re,""));
		return [type,card];
	};

	Transpiler.prototype.matchTypes = function(i,o){
		var ti = this.type(i);
		var to = this.type(o);
		//console.warn(i,ti,"->",o,to);
		// cardinality checks:
		// string->string* -1->0 => allow
		// string*->string 0->-1 => deny
		// string->string+ -1->1 => deny
		// string*->string+ 0->1 => allow (runtime check)
		// string->any 2->7 => allow
		// any->string 7->2 => allow (infer+check @ runtime)
		var d = to[1]-ti[1];
		return (ti[0]==to[0] || to[0]==7 || ti[0]==7) && d>=0 && d<=1;
	};

	Transpiler.prototype.compile = function(value,parent,compose){
		var self = this;
		var isSeq = typeOf(value)=="array";
		var top = isSeq ? false : value.top;
		var fargs = parent ? parent.args.map(function(_,i){
			return "arg" + (i+1);
		}).join(",") : "arg0";
		var fname = "anon"+this.count;
		if(parent){
			var parity = parent.more ? "N" : parent.args.length;
			fname = short(parent.name+"#"+parity);
		} else if(top) {
			this.count++;
		}
		if(isSeq) {
			var seq = value.map(function(_){
				if(typeOf(_)=="query"){
					// compose the functions in the array
					return "arg0 = "+this.compile(_,null,true).toString()+";\n";
				} else {
					return _;
				}
			},this);
			var pre = parent ? "var arg0;\n" : "";
			return new Function("return function "+fname+"("+fargs+"){\n"+pre+seq.join("")+"return arg0;\n}")();
		}
		var name = value.name,
			args = value.args;
		if(!name.match(/:/)) name = "core:"+name;
		var def = this.getFunctionDef(name,args.length);
		var fullname = name+"#"+(def.more ? "N" : def.args.length);
		if(this.cache.indexOf(fullname)==-1) this.cache.push(fullname);
		args = args.map(function(_){
			if(typeOf(_) == "array") {
				return this.compile(_,null,null).toString();
			} else if(typeOf(_) == "query") {
				return this.compile(_,null,null);
			} else if(_.match(/^(\.\/)|\.$/)) {
				return _;
			} else if(_.match(/^\$[0-9]+$/)) {
				return _.replace(/^\$([0-9]+)$/,"arg$1");
			} else {
				var r = this.convert(_);
				if(typeof r=="string" && r.match(/^.+#[0-9]+$/)){
					var fullname = (r.indexOf(":")>-1 ? r : "core:"+r);
					if(this.cache.indexOf(fullname)==-1) this.cache.push(fullname);
					return short(fullname);
				}
				// check type here
				//if(!this.typeCheck(r,t)){
				//	throw new Error("Expected type ",t," for argument value ",r);
				//}
				return JSON.stringify(r);
			}
		},this);
		var args2 = args.reduce(function(pre,cur,i){
			if(cur.match(/^(\.\/)|\.$/)) {
				pre.push("arg0");
			} else {
				var s = pre.length-1;
				var last = pre[s];
				if(last.match(/^(\.\/)|\.$/) || s<1) {
					pre.push(cur);
				} else {
					pre[s] = last + "," + cur;
				}
			}
			return pre;
		},[short(fullname) + "("]);
		args2.push(")");
		var fn = args2.join("");
		if(compose) return fn;
		var fns = "\n";
		if(top) {
			for(var i=0;i<this.cache.length;i++){
				var f = this.getFunction(this.cache[i]);
				fns += "var "+short(this.cache[i])+"="+f.toString()+";\n";
			}
		}
		return new Function("return function "+fname+"("+fargs+"){ "+fns+"return "+fn+";}")();
	};

	Transpiler.prototype.define = function(value,params){
		this.cache = [];
		var l = value.args.length;
		var parts = value.args[0].split(":");
		var name = parts.pop();
		var module = "";
		var ns = parts.length ? parts[0] : "local";
		var type, args = [], qname;
		var body,def;
		if(l==2){
			// lookup
			def = this.dict[value.args[1]];
			if(!def) {
				throw new Error("Unknown reference in definition "+name);
			}
			type = def.type;
			args = def.args;
			body = def.body;
			module = def.module;
			qname = ns+":"+name;
		} else if(l==3 || l==4){
			if(l==3) {
				module = params.use;
				if(ns=="local"){
					ns = module.split("/")[0];
				}
			} else {
				body = value.args[3];
				module = ns;
			}
			// core
			args = value.args[1];
			type = value.args[2];
			qname = ns+":"+name;
		}
		var len = args.length;
		// check if more argument of last type is allowed
		var last = args[len-1];
		var more = typeOf(last) == "string" ? last.substr(-1) === "-" : false;
		var arity = more ? -1 : len;
		var existing = this.getFunctionDef(qname,arity);
		if(existing) return existing;
		def = {
			name:qname,
			type:type,
			args:args,
			more:more,
			body:body,
			module:module
		};
		if(!this.dict[qname]){
			this.dict[qname] = [];
		}
		this.dict[qname][arity+1] = def;
		if(l==4) {
			// compile definition
			this.lib[qname+"#"+(arity<0 ? "N" : arity)] = this.compile(body,def);
		}
		return def;
	};
	exports.Transpiler = Transpiler;

	return exports;
});<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    runSequence = require('run-sequence');

gulp.task('default', function(cb) {
    global.isWatching = true;

    runSequence([
            'compass-dev',
            'browserify'
        ],
        'browser-sync',
        'watch',
        cb);
});<commit_msg>removed browserify from default task since watch runs it as a prerequisite<commit_after>'use strict';

var gulp = require('gulp'),
    runSequence = require('run-sequence');

gulp.task('default', function(cb) {
    global.isWatching = true;

    runSequence([
            'compass-dev'
        ],
        'browser-sync',
        'watch',
        cb);
});<|endoftext|>


<commit_before>var ADNAPI = function(user, readycb) {
	this.apibase		= 'https://alpha-api.app.net/stream/0/';
	this.user			= user;

	this.limits = {
		maxLength:		256
	};

	this.terms = {
		message:		'post',
		messages:		'posts',
		Messages:		'Posts',

		Repost:			'Repost',
		repost:			'repost',
		reposted:		'reposted',
		RP:				'RP',
		PM:				'PM',
		PMs:			'PMs'
	};

	if (this.user) {
		this.accesstoken = this.user.accesstoken;
	}

	if (this.user && this.user.options) {
		/* Use whatever key the user's account was created with */
		this.options = this.user.options;
	} else {
		/* Macaw for all the things */
		this.options = {
			clientID:		'qjpU52DDXuurvMw65gzNbv7XCreV5v3m'
		};
	}

	if (this.options && this.user && !this.user.options) {
		/*
			Save the clientID on the user object. This will ensure that if the
			clientID is changed at some point that existing users will be able
			to continue using their account.
		*/
		var users = prefs.get('accounts');

		for (var i = 0, u; u = users[i]; i++) {
			if (u.id == this.user.id) {
				u.options = this.options;
				prefs.set('accounts', users);
				break;
			}
		}
	}

	this.dateFormat	= new enyo.g11n.DateFmt({
		date:		'short',
		time:		'short'
	});

	/*
		Load this user's profile information, working under the assumption that
		a consumer will usually want access to this.
	*/
	if (this.user) {
		this.getUser('me', function(success, profile) {
			if (success) {
				this.user.profile		= profile;
				this.user.id			= profile.id;
				this.user.screenname	= profile.screenname;

				console.log(this.user);
			}

			if (readycb) readycb();
		}.bind(this));
	} else {
		if (readycb) readycb();
	}

	// TODO	Load a list of friends to use for username auto completion
};

ADNAPI.prototype = {

toString: function()
{
	return('adn');
},

buildURL: function(url, params)
{
	var p = [];

	for (var key in params) {
		p.push(key + '=' + encodeURIComponent(params[key]));
	}

	if (p.length > 0) {
		return(url + '?' + p.join('&'));
	} else {
		return(url);
	}
},

get: function(url, cb)
{
	var x = new enyo.Ajax({
		url:					url,
		method:					'GET',
		headers: {
			'Authorization':	'Bearer ' + this.accesstoken
		}
	});
	x.go({});

	x.response(this, cb);
},

post: function(url, body, cb)
{
	var x = new enyo.Ajax({
		url:					url,
		method:					'POST',
		postBody:				enyo.json.stringify(body),
		headers: {
			'Authorization':	'Bearer ' + this.accesstoken,
			'Content-Type':		'application/json'
		}
	});
	x.go({});

	x.response(this, cb);
},

cleanupUser: function(user)
{
	var created			= null;
	var description		= null;
	var avatar			= null;
	var relationship;

	if (user.avatar_image) {
		avatar = user.avatar_image.url;
	}

	if (user.description) {
		description =	user.description.text;
	}

	if (user.created_at) {
		created = new Date(user.created_at);
	} else if (user.created) {
		created = new Date(user.created);
	}
	if (created && isNaN(created.getTime())) {
		created = null;
	}

	if (!(relationship = user.relationship)) {
		relationship = [];

		if (user.id == this.user.id) {
			relationship.push('you');
		}

		if (user.follows_you) {
			relationship.push('followed_by');
		}

		if (user.you_follow) {
			relationship.push('following');
		}
	}

	return({
		id:				user.id,
		name:			user.name,
		screenname:		user.username	|| user.screenname,
		description:	description		|| user.description,
		avatar:			avatar			|| user.avatar,
		largeAvatar:	'https://alpha-api.app.net/stream/0/users/' + user.id + '/avatar',

		created:		created,
		createdStr:		created ? this.dateFormat.format(created) : null,
		type:			user.type,

		counts: {
			following:	user.counts.following	|| 0,
			followers:	user.counts.followers	|| 0,
			posts:		user.counts.posts		|| 0,
			favorites:	user.counts.favorites	|| 0
		},

		relationship:	relationship
	});
},

getUser: function(user, cb, resource)
{
	var url		= this.apibase;
	var x;

	resource = resource || 'profile';
	switch (resource) {
		case 'profile':
			url += 'users/' + user;
			break;

		case 'relationship':
			/* The relationship details are included in the profile */
			cb(false);
			break;

		default:
			console.log('getUser does not yet support: ' + resource);
	}

	this.get(url, function(sender, response) {
		if (response.data) {
			cb(true, this.cleanupUser(response.data));
		} else {
			cb(false);
		}
	});
},

getMessages: function(resource, cb, params)
{
	var plural	= true;

	params = params || {};

	/* Use since_id and before_id for ADN */
	if (params.max_id) {
		params.before_id = params.max_id;
		delete params.max_id;
	}

	var url		= this.apibase;
	var user	= params.user || 'me';

	switch (resource) {
		case 'timeline':
			if (params.user) {
				console.log('ADN does not support getting a timeline for another user');
				return;
			}

			url += 'posts/stream';
			break;

		case 'user':
			url += 'users/' + user + '/posts';
			break;

		case 'show':
			/* Show a single tweet, requires an "id" in params */
			plural = false;
			url += 'posts/' + params.id;
			break;

		case 'mentions':
			url += 'users/' + user + '/mentions';
			break;

		case 'favorites':
			url += 'users/' + user + '/stars';
			break;

		case 'messages':
		case 'search':
		default:
			console.log('getMessages does not yet support: ' + resource);
			return;
	}

	/* Delete any params that we don't want to include in the URI */
	delete params.user;
	delete params.id;

	this.get(this.buildURL(url, params), function(sender, response) {
		if (response.data) {
			var results = null;

			if (plural) {
				results = this.cleanupMessages(response.data);
			} else {
				results = this.cleanupMessage(response.data);
			}

			cb(true, results);
		} else {
			cb(false);
		}
	});
},

cleanupMessages: function(messages)
{
	if (messages) {
		for (var i = 0, tweet; tweet = messages[i]; i++) {
			messages[i] = this.cleanupMessage(tweet);
		}
	}

	return(messages);
},

/*
	Cleanup the provided message

	This function takes a raw message, and does any processing needed to allow
	displaying it easily. It is safe to call this function multiple times on the
	same message, and it should be called agin if the message has been converted
	to json and back.
*/
cleanupMessage: function(message)
{
	/*
		If this is a repost then we want to act on the original message, not the
		wrapper. Keep the wrapper around so that the details of the sender can
		be displayed.
	*/
	if (message.repost_of) {
		var	real = message;

		message = real.repost_of;
		delete real.repost_of;

		/* Both messages need to be cleaned up */
		message.real = this.cleanupMessage(real);
	}

	/* Store a date object, and a properly formated date string */
	switch (typeof(message.created)) {
		case "string":
			message.created = new Date(message.created);
			break;
		default:
			message.created = new Date(message.created_at);
			break;
	}

	if (message.created && !message.createdStr) {
		message.createdStr = this.dateFormat.format(message.created);
	}

	if (message.user) {
		message.user = this.cleanupUser(message.user);
	}

	if (message.reply_to) {
		message.replyto = message.reply_to;
		delete message.reply_to;
	}

	if (message.canonical_url) {
		message.link = message.canonical_url;
		delete message.canonical_url;
	}

	if (message.source) {
		if (message.source.name) {
			message.source = message.source.name;
		}
	}

	if (!message.stripped) {
		message.stripped = message.text || '';
	}

	message.text	= EntityAPI.text(message);
	message.media	= EntityAPI.media(message.entities.urls);

	return(message);
},

sendMessage: function(resource, cb, params)
{
	var url		= this.apibase + 'posts';

	if (params.status) {
		params.text = params.status;
		delete params.status;
	}

	if (params.replyto) {
		params.reply_to = params.replyto;
		delete params.replyto;
	}

	if (params.to) {
		// TODO	Add ADN support for PMs
		ex("Sorry, we don't support ADN PMs yet. We're working on it.");
		cb(false);
		return;
	}

	this.post(url, params, function(sender, response) {
		if (response.data) {
			cb(true, response.data);
		} else {
			cb(false, response);
		}
	});
},

authorize: function(cb, token)
{
	if (!cb || !token) {
		/*
			Step 1:	Request an authorization token, and open a browser window so
					that the user may authorize the app.
		*/
		var id	= Math.random();
		var uri	= this.buildURL('http://minego.net/macawadn/', {
				redirect_uri:	window.location + '?create=' + id
		});

		/*
			Store a random number in our prefs and in the URI so that we can
			tell if we are looking at an old create request once we've finished
			this one.
		*/
		prefs.set('creating', id);

		var params = {
			client_id:		this.options.clientID,
			response_type:	'token',
			redirect_uri:	uri,
			scope:			'basic stream email write_post follow public_messages messages update_profile'
		};

		window.location = this.buildURL('https://account.app.net/oauth/authorize', params);
	} else {
		/* Step 2: Load the user profile */
		this.accesstoken = token;

		cb({
			servicename:		'adn',
			accesstoken:		token
		});
	}
}

};

<commit_msg>Hide deleted messages from ADN<commit_after>var ADNAPI = function(user, readycb) {
	this.apibase		= 'https://alpha-api.app.net/stream/0/';
	this.user			= user;

	this.limits = {
		maxLength:		256
	};

	this.terms = {
		message:		'post',
		messages:		'posts',
		Messages:		'Posts',

		Repost:			'Repost',
		repost:			'repost',
		reposted:		'reposted',
		RP:				'RP',
		PM:				'PM',
		PMs:			'PMs'
	};

	if (this.user) {
		this.accesstoken = this.user.accesstoken;
	}

	if (this.user && this.user.options) {
		/* Use whatever key the user's account was created with */
		this.options = this.user.options;
	} else {
		/* Macaw for all the things */
		this.options = {
			clientID:		'qjpU52DDXuurvMw65gzNbv7XCreV5v3m'
		};
	}

	if (this.options && this.user && !this.user.options) {
		/*
			Save the clientID on the user object. This will ensure that if the
			clientID is changed at some point that existing users will be able
			to continue using their account.
		*/
		var users = prefs.get('accounts');

		for (var i = 0, u; u = users[i]; i++) {
			if (u.id == this.user.id) {
				u.options = this.options;
				prefs.set('accounts', users);
				break;
			}
		}
	}

	this.dateFormat	= new enyo.g11n.DateFmt({
		date:		'short',
		time:		'short'
	});

	/*
		Load this user's profile information, working under the assumption that
		a consumer will usually want access to this.
	*/
	if (this.user) {
		this.getUser('me', function(success, profile) {
			if (success) {
				this.user.profile		= profile;
				this.user.id			= profile.id;
				this.user.screenname	= profile.screenname;

				console.log(this.user);
			}

			if (readycb) readycb();
		}.bind(this));
	} else {
		if (readycb) readycb();
	}

	// TODO	Load a list of friends to use for username auto completion
};

ADNAPI.prototype = {

toString: function()
{
	return('adn');
},

buildURL: function(url, params)
{
	var p = [];

	for (var key in params) {
		p.push(key + '=' + encodeURIComponent(params[key]));
	}

	if (p.length > 0) {
		return(url + '?' + p.join('&'));
	} else {
		return(url);
	}
},

get: function(url, cb)
{
	var x = new enyo.Ajax({
		url:					url,
		method:					'GET',
		headers: {
			'Authorization':	'Bearer ' + this.accesstoken
		}
	});
	x.go({});

	x.response(this, cb);
},

post: function(url, body, cb)
{
	var x = new enyo.Ajax({
		url:					url,
		method:					'POST',
		postBody:				enyo.json.stringify(body),
		headers: {
			'Authorization':	'Bearer ' + this.accesstoken,
			'Content-Type':		'application/json'
		}
	});
	x.go({});

	x.response(this, cb);
},

cleanupUser: function(user)
{
	var created			= null;
	var description		= null;
	var avatar			= null;
	var relationship;

	if (user.avatar_image) {
		avatar = user.avatar_image.url;
	}

	if (user.description) {
		description =	user.description.text;
	}

	if (user.created_at) {
		created = new Date(user.created_at);
	} else if (user.created) {
		created = new Date(user.created);
	}
	if (created && isNaN(created.getTime())) {
		created = null;
	}

	if (!(relationship = user.relationship)) {
		relationship = [];

		if (user.id == this.user.id) {
			relationship.push('you');
		}

		if (user.follows_you) {
			relationship.push('followed_by');
		}

		if (user.you_follow) {
			relationship.push('following');
		}
	}

	return({
		id:				user.id,
		name:			user.name,
		screenname:		user.username	|| user.screenname,
		description:	description		|| user.description,
		avatar:			avatar			|| user.avatar,
		largeAvatar:	'https://alpha-api.app.net/stream/0/users/' + user.id + '/avatar',

		created:		created,
		createdStr:		created ? this.dateFormat.format(created) : null,
		type:			user.type,

		counts: {
			following:	user.counts.following	|| 0,
			followers:	user.counts.followers	|| 0,
			posts:		user.counts.posts		|| 0,
			favorites:	user.counts.favorites	|| 0
		},

		relationship:	relationship
	});
},

getUser: function(user, cb, resource)
{
	var url		= this.apibase;
	var x;

	resource = resource || 'profile';
	switch (resource) {
		case 'profile':
			url += 'users/' + user;
			break;

		case 'relationship':
			/* The relationship details are included in the profile */
			cb(false);
			break;

		default:
			console.log('getUser does not yet support: ' + resource);
	}

	this.get(url, function(sender, response) {
		if (response.data) {
			cb(true, this.cleanupUser(response.data));
		} else {
			cb(false);
		}
	});
},

getMessages: function(resource, cb, params)
{
	var plural	= true;

	params = params || {};

	/* Use since_id and before_id for ADN */
	if (params.max_id) {
		params.before_id = params.max_id;
		delete params.max_id;
	}

	var url		= this.apibase;
	var user	= params.user || 'me';

	switch (resource) {
		case 'timeline':
			if (params.user) {
				console.log('ADN does not support getting a timeline for another user');
				return;
			}

			url += 'posts/stream';
			break;

		case 'user':
			url += 'users/' + user + '/posts';
			break;

		case 'show':
			/* Show a single tweet, requires an "id" in params */
			plural = false;
			url += 'posts/' + params.id;
			break;

		case 'mentions':
			url += 'users/' + user + '/mentions';
			break;

		case 'favorites':
			url += 'users/' + user + '/stars';
			break;

		case 'messages':
		case 'search':
		default:
			console.log('getMessages does not yet support: ' + resource);
			return;
	}

	/* Delete any params that we don't want to include in the URI */
	delete params.user;
	delete params.id;

	this.get(this.buildURL(url, params), function(sender, response) {
		if (response.data) {
			var results = null;

			if (plural) {
				results = this.cleanupMessages(response.data);
			} else {
				results = this.cleanupMessage(response.data);
			}

			cb(true, results);
		} else {
			cb(false);
		}
	});
},

cleanupMessages: function(messages)
{
	if (messages) {
		for (var i = 0, message; message = messages[i]; i++) {
			if (message.deleted) {
				messages.splice(i, 1);
				i--;
			} else {
				messages[i] = this.cleanupMessage(message);
			}
		}
	}

	return(messages);
},

/*
	Cleanup the provided message

	This function takes a raw message, and does any processing needed to allow
	displaying it easily. It is safe to call this function multiple times on the
	same message, and it should be called agin if the message has been converted
	to json and back.
*/
cleanupMessage: function(message)
{
	/*
		If this is a repost then we want to act on the original message, not the
		wrapper. Keep the wrapper around so that the details of the sender can
		be displayed.
	*/
	if (message.repost_of) {
		var	real = message;

		message = real.repost_of;
		delete real.repost_of;

		/* Both messages need to be cleaned up */
		message.real = this.cleanupMessage(real);
	}

	/* Store a date object, and a properly formated date string */
	switch (typeof(message.created)) {
		case "string":
			message.created = new Date(message.created);
			break;
		default:
			message.created = new Date(message.created_at);
			break;
	}

	if (message.created && !message.createdStr) {
		message.createdStr = this.dateFormat.format(message.created);
	}

	if (message.user) {
		message.user = this.cleanupUser(message.user);
	}

	if (message.reply_to) {
		message.replyto = message.reply_to;
		delete message.reply_to;
	}

	if (message.canonical_url) {
		message.link = message.canonical_url;
		delete message.canonical_url;
	}

	if (message.source) {
		if (message.source.name) {
			message.source = message.source.name;
		}
	}

	if (!message.stripped) {
		message.stripped = message.text || '';
	}

	message.text	= EntityAPI.text(message);
	message.media	= EntityAPI.media(message.entities.urls);

	return(message);
},

sendMessage: function(resource, cb, params)
{
	var url		= this.apibase + 'posts';

	if (params.status) {
		params.text = params.status;
		delete params.status;
	}

	if (params.replyto) {
		params.reply_to = params.replyto;
		delete params.replyto;
	}

	if (params.to) {
		// TODO	Add ADN support for PMs
		ex("Sorry, we don't support ADN PMs yet. We're working on it.");
		cb(false);
		return;
	}

	this.post(url, params, function(sender, response) {
		if (response.data) {
			cb(true, response.data);
		} else {
			cb(false, response);
		}
	});
},

authorize: function(cb, token)
{
	if (!cb || !token) {
		/*
			Step 1:	Request an authorization token, and open a browser window so
					that the user may authorize the app.
		*/
		var id	= Math.random();
		var uri	= this.buildURL('http://minego.net/macawadn/', {
				redirect_uri:	window.location + '?create=' + id
		});

		/*
			Store a random number in our prefs and in the URI so that we can
			tell if we are looking at an old create request once we've finished
			this one.
		*/
		prefs.set('creating', id);

		var params = {
			client_id:		this.options.clientID,
			response_type:	'token',
			redirect_uri:	uri,
			scope:			'basic stream email write_post follow public_messages messages update_profile'
		};

		window.location = this.buildURL('https://account.app.net/oauth/authorize', params);
	} else {
		/* Step 2: Load the user profile */
		this.accesstoken = token;

		cb({
			servicename:		'adn',
			accesstoken:		token
		});
	}
}

};

<|endoftext|>