<commit_before>Dionysus.module('AdminArticle', function(Article, Dionysus, Backbone, Marionette, $) {
  'use strict';

  var validationRules = {
    title:      { identifier: 'title',      rules: [{ type: 'empty', prompt: 'Please enter a title' }] },
    category:   { identifier: 'category',   rules: [{ type: 'empty', prompt: 'Please enter a category' }] },
    summary:    { identifier: 'summary',    rules: [{ type: 'empty', prompt: 'Please enter a summary' }] },
    body:       { identifier: 'body',       rules: [{ type: 'empty', prompt: 'Please enter article body' }] }
  };

  var ArticleView = Marionette.ItemView.extend({
    template: '#admin-article-tpl',
    tagName: 'li',
    className: 'item'
  });

  var ArticlesView = Marionette.CompositeView.extend({
    template: '#admin-articles-tpl',
    childView: ArticleView,
    childViewContainer: '.items'
  });

  var ArticleEditorView = Marionette.ItemView.extend({
    template: '#admin-article-editor-tpl',
    tagName: 'form',
    className: 'ui form',
    initialize: function(options) {
      this.model = options.model;
      this.categories = options.categories;
    },
    serializeData: function(){
      var data = this.model.toJSON();
      var category = data.category;
      if (_.isObject(category)) {
        data.category = category.id;
      }
      data.categories = [{'xxx': 1}, {'yyy' : 2}];
      return data;
    },
    onRender: function() {
      this.$('select.dropdown').dropdown();
      this.$el.form();

      this.$el.form('set values', this.model.toJSON());
      this.$('.editor').editable({
        inlineMode: false,
        language: 'zh_cn',
        imageUploadURL: '/api/v1/upload',
        fileUploadURL: '/api/v1/upload'
      });
    },
    ui : {
      save : '.button.submit'
    },
    events: {
      'click @ui.save' : 'saveArticle'
    },
    saveArticle: function() {
      var json = this.$el.form('get values');
      this.model.set(json);
      this.model.save();
    }
  });

  var ArticleController = Marionette.Controller.extend({
    showArticles: function () {
      Dionysus.request('article:instances').then(function(articles) {
        Dionysus.mainRegion.show(new ArticlesView({ collection: articles }));
      });
    },
    createArticle: function() {
      var article = Dionysus.request('article:new');
      var fetchingCategory = Dionysus.request('category:instances');
      $.when(fetchingCategory).done(function(categories) {
        var editor = new ArticleEditorView({
          model: article,
          categories: categories
        });
        Dionysus.mainRegion.show(editor);
      });
    },
    editArticle: function(id) {
      Dionysus.request('article:instance', id).then(function(article) {
        // category.fetch();
        var editor = new ArticleEditorView({ model: article, categories: []});
        Dionysus.mainRegion.show(editor);
      });
    }
  });

  Dionysus.addInitializer(function() {
    new Marionette.AppRouter({
      appRoutes : {
        'admin/articles(/)': 'showArticles',
        'admin/articles/create(/)': 'createArticle',
        'admin/articles/:id': 'editArticle'
      },
      controller: new ArticleController()
    });
  });
});
<commit_msg>set category when editing<commit_after>Dionysus.module('AdminArticle', function(Article, Dionysus, Backbone, Marionette, $) {
  'use strict';

  var validationRules = {
    title:      { identifier: 'title',      rules: [{ type: 'empty', prompt: 'Please enter a title' }] },
    category:   { identifier: 'category',   rules: [{ type: 'empty', prompt: 'Please enter a category' }] },
    summary:    { identifier: 'summary',    rules: [{ type: 'empty', prompt: 'Please enter a summary' }] },
    body:       { identifier: 'body',       rules: [{ type: 'empty', prompt: 'Please enter article body' }] }
  };

  var ArticleView = Marionette.ItemView.extend({
    template: '#admin-article-tpl',
    tagName: 'li',
    className: 'item'
  });

  var ArticlesView = Marionette.CompositeView.extend({
    template: '#admin-articles-tpl',
    childView: ArticleView,
    childViewContainer: '.items'
  });

  var ArticleEditorView = Marionette.ItemView.extend({
    template: '#admin-article-editor-tpl',
    tagName: 'form',
    className: 'ui form',
    initialize: function(options) {
      this.model = options.model;
      this.categories = options.categories;
    },
    serializeData: function(){
      var data = this.model.toJSON();
      var category = data.category;
      if (_.isObject(category)) {
        data.category = category.id;
      }
      data.categories = this.categories.toJSON();
      return data;
    },
    onRender: function() {
      this.$('select.dropdown').dropdown();
      this.$el.form();
      var data = this.model.toJSON();
      var category = data.category;
      if (_.isObject(category)) {
        data.category = category.id;
      }
      this.$el.form('set values', data);
      this.$('.editor').editable({
        inlineMode: false,
        language: 'zh_cn',
        imageUploadURL: '/api/v1/upload',
        fileUploadURL: '/api/v1/upload'
      });
    },
    ui : {
      save : '.button.submit'
    },
    events: {
      'click @ui.save' : 'saveArticle'
    },
    saveArticle: function() {
      var json = this.$el.form('get values');
      json.category = parseInt(json.category);
      this.model.set(json);
      this.model.save();
    }
  });

  var ArticleController = Marionette.Controller.extend({
    showArticles: function () {
      Dionysus.request('article:instances').then(function(articles) {
        Dionysus.mainRegion.show(new ArticlesView({ collection: articles }));
      });
    },
    createArticle: function() {
      $.when(Dionysus.request('article:new'), Dionysus.request('category:instances')).done(function(article, categories) {
        var editor = new ArticleEditorView({ model: article, categories: categories });
        Dionysus.mainRegion.show(editor);
      });
    },
    editArticle: function(id) {
      $.when(Dionysus.request('article:instance', id), Dionysus.request('category:instances')).done(function(article, categories) {
        var editor = new ArticleEditorView({ model: article, categories: categories});
        Dionysus.mainRegion.show(editor);
      });
    }
  });

  Dionysus.addInitializer(function() {
    new Marionette.AppRouter({
      appRoutes : {
        'admin/articles(/)': 'showArticles',
        'admin/articles/create(/)': 'createArticle',
        'admin/articles/:id': 'editArticle'
      },
      controller: new ArticleController()
    });
  });
});
<|endoftext|>


<commit_before>(function() {

	if (['wui', 'operator', 'scheduler'].indexOf(request.param.name) === -1) {
		return response.error(404);
	}

	var filename = './log/' + request.param.name;

	if (!fs.existsSync(filename)) {
		response.head(204);
		response.exit('');
		return;
	}

	response.head(200);

	response.write(new Array(1024).join(' '));

	var tailf = child_process.spawn('tail', ['-f', '-n', '30', filename]);

	tailf.stdout.pipe(response);

	tailf.on('exit', function(code) {
		response.exit();
	});

	request.on('close', function() {
		response.exit();
	});

})();<commit_msg>WUI/API/log-stream: プロセスがリークするバグ<commit_after>(function() {

	if (['wui', 'operator', 'scheduler'].indexOf(request.param.name) === -1) {
		return response.error(404);
	}

	var filename = './log/' + request.param.name;

	if (!fs.existsSync(filename)) {
		response.head(204);
		response.end('');
		return;
	}

	response.head(200);

	response.write(new Array(1024).join(' '));

	var tailf = child_process.spawn('tail', ['-f', '-n', '30', filename]);
	children.push(tailf);// 安全対策

	tailf.stdout.pipe(response);

	tailf.on('exit', function(code) {
		response.end();
	});

	request.on('close', function() {
		tailf.kill('SIGKILL');
	});

})();<|endoftext|>


<commit_before><commit_msg>Add File Upload example and explanation<commit_after><|endoftext|>


<commit_before>

var __builders = {
	// TODO: separate appending, from creating somehow.
	// so that when appendNode appends codeMirror it works.
	// futher: natives should receive arb data to config etc.
	// e.g. in codemirror we can give a mode

	codeMirror: function(parent, attrs, props, events) {
		var cm = CodeMirror(parent, {
			lineNumbers: true,
			matchBrackets: true,
			tabMode: 'shift',
			autofocus: true,
			//value: "function myScript(){return 100;}\n",
			mode:  "javascript"
		});
		cm.getDoc().setValue(props['value']);
		setTimeout(function() {
            cm.refresh();
        }, 100);

		cm.on('cursorActivity', function (editor) {
			var position = editor.getCursor();
			var line = position.line;
			var token = editor.getTokenAt(position);
			if (events.cursorActivity) {
				schedule(__event_queue, events.cursorActivity,  {line: line, start: token.start,
					end: token.end, string: token.string, tokenType: token.type});
			}
		});
		cm.on('change', function (editor, change) {
			if (events.change) {
				schedule(__event_queue, events.change,  {
					fromLine: change.from.line, fromCol: change.from.ch,
					toLine: change.to.line, toCol: change.to.ch,
					text: change.text.join('\n'),
					removed: change.removed.join("\n")
				});
			}
		});
	}
};

function makeNative(native) {
	if (!__natives.hasOwnProperty(native.key)) {
		__natives[native.key] = function(parent) {
			return __builders[native.kind](parent, native.attrs, native.props, native.events);
		};
	}
	return __natives[native.key];
}

var __event_queue = [];
var __other_queue = [];

var __natives = {};
var __subscriptions = {};

function pendingWork() {
	return __event_queue.length > 0 || __other_queue.length > 0;
}

function nextMessage() {
	return __event_queue.length > 0 ? __event_queue.shift() : __other_queue.shift();
}

function flushUIEvents() {
	console.log("Flushing pending events." + JSON.stringify(__event_queue));
	__event_queue = [];
}

function render(timestamp) {
	window.requestAnimationFrame(render);

	if (!pendingWork()) {
		return;
	}

	if (waitingForResponse()) {
		flushUIEvents();
		return;
	}

	sendMessage('/msg', nextMessage(), function (work) {
		doCommands(work[2]);
		subscribe(work[1]);
		patch(root(), work[0], dec2handler);
	});
}

var __waiting = false;

function waitingForResponse() {
	return __waiting;
}

function sendMessage(url, message, handle) {
	__waiting = true;
	$.get(url, message, handle, 'json').always(function () {
		__waiting = false;
	});
}

function root() {
	return document.getElementById('root');
}

function start() {
	sendMessage('/init', {}, function (work) {
		doCommands(work[2]);
		subscribe(work[1]);
		replace(root(), build(work[0]));
	});
	window.requestAnimationFrame(render);
}

function replace(dom, newDom) {
	dom.parentNode.replaceChild(newDom, dom);
}

function nodeType(node) {
	for (var type in node) { break; }
	return type;
}

function doCommands(cmds) {
	for (var i = 0; i < cmds.length; i++) {
		var cmd = cmds[i];

		switch (nodeType(cmd)) {

		case 'random':
			var random = Math.floor(Math.random() * (cmd.random.to - cmd.random.from + 1)) + cmd.random.from;
			schedule(__other_queue, cmd.random.handle.handle, {type: 'integer', intVal: random});
			break;
		}

	}
}

function sub2handler(sub) {
	switch (nodeType(sub)) {

	case 'timeEvery':
		var timer = setInterval(function() {
			var data = {type: 'integer', intVal: (new Date().getTime() / 1000) | 0};
			schedule(__other_queue, sub.timeEvery.handle.handle, data);
		}, sub.timeEvery.interval);
		return function () {
			clearInterval(timer);
		};
	}
}

function subscribe(subs) {
	for (var i = 0; i < subs.length; i++) {
		var sub = subs[i];
		var type = nodeType(sub);
		var id = sub[type].handle.handle.id;
		if (__subscriptions.hasOwnProperty(id)) {
			continue;
		}
		__subscriptions[id] = sub2handler(sub);
	}

	unsubscribeStaleSubs(subs);
}

function unsubscribeStaleSubs(subs) {
	var toDelete = [];
	outer: for (var k in __subscriptions) {
		if (__subscriptions.hasOwnProperty(k)) {
			for (var i = 0; i < subs.length; i++) {
				var sub = subs[i];
				var id = sub[nodeType(sub)].handle.handle.id;
				if (('' + id) === k) {
					continue outer;
				}
			}
			toDelete.push(k);
		}
	}
	for (var i = 0; i < toDelete.length; i++) {
		__subscriptions[toDelete[i]](); // shutdown
		delete __subscriptions[toDelete[i]];
	}
}

function schedule(queue, handle, data) {
	var result = {id: handle.id};
	if (handle.maps) {
		result.maps = handle.maps.join(';');
	}
	for (var k in data) {
		if (data.hasOwnProperty(k)) {
			result[k] = data[k];
		}
	}
	queue.push(result);
}

// this needs adaptation if new kinds of data are required.
function dec2handler(decoder) {
	switch (nodeType(decoder)) {

	case 'succeed':
		return function (event) {
			// TODO: change 'nothing' to 'ok'
			schedule(__event_queue, decoder.succeed.handle.handle, {type: 'nothing'});
		};

	case 'targetValue':
		return function (event) {
			schedule(__event_queue, decoder.targetValue.handle.handle,
					{type: 'string', strVal: event.target.value});
		};

	case 'targetChecked':
		return function (event) {
			schedule(__event_queue, decoder.targetChecked.handle.handle,
					{type: 'boolean', boolVal: event.target.checked});
		};

	}
}

function patchThis(dom, edits) {
	edits = edits || [];
	for (var i = 0; i < edits.length; i++) {
		var edit = edits[i];
		for (var type in edit) {

			switch (type) {

			case 'replace':
				return build(edit[type].html);

			case 'setText':
				dom.nodeValue = edit[type].contents;
				break;

			case 'removeNode':
				dom.removeChild(dom.lastChild);
				break;

			case 'appendNode':
				var kid = build(edit[type].html);
				if (typeof kid === 'function') {
					kid(dom);
				}
				else {
					dom.appendChild(kid);
				}
				break;

			case 'setAttr':
				dom.setAttribute(edit[type].name, edit[type].val);
				break;

			case 'setProp':
				dom[edit[type].name] = edit[type].val;
				break;

			case 'setEvent':
				var key = edit[type].name;
				var handler = dec2handler(edit[type].handler);
				dom.addEventListener(key, withCleanListeners(dom, key, handler));
				break

			case 'removeAttr':
				dom.removeAttribute(edit[type].name);
				break;

			case 'removeProp':
				delete dom[edit[type].name]; //???
				break;

			case 'removeEvent':
				// todo: refactor
				var handler = dom.myHandlers[edit[type].name];
				dom.removeEventListener(edit[type].name, handler);
				break;

			default:
				throw 'unsupported edit: ' + JSON.stringify(edit);

			}
			break;
		}
	}
}

function patch(dom, tree) {
	var newDom = patchThis(dom, tree.patch.edits);

	if (newDom) {
		replace(dom, newDom);
		return;
	}

	var patches = tree.patch.patches || [];
	for (var i = 0; i < patches.length; i++) {
		var p = patches[i];
		patch(dom.childNodes[p.patch.pos], p);
	}

}

function withCleanListeners(dom, key, handler) {
	var allHandlers = dom.myHandlers || {};
	if (allHandlers.hasOwnProperty(key)) {
		dom.removeEventListener(key, allHandlers[key]);
	}
	allHandlers[key] = handler;
	dom.myHandlers = allHandlers;
	return handler;
}

function build(vdom) {
    if (vdom === undefined) {
        return document.createTextNode('');
    }

    if (vdom.txt !== undefined) {
        return document.createTextNode(vdom.txt.contents);
    }

    if (vdom.native !== undefined) {
    	return makeNative(vdom.native);
    }

    var vattrs = vdom.element.attrs || {};
    var vprops = vdom.element.props || {};

    var elt = vprops.namespace != undefined
            ? document.createElementNS(vprops.namespace, vdom.element.tagName)
            : document.createElement(vdom.element.tagName);

    for (var k in vattrs) {
        if (vattrs.hasOwnProperty(k)) {
            elt.setAttribute(k, vattrs[k]);
        }
    }

    for (var k in vprops) {
    	if (vprops.hasOwnProperty(k)) {
    		elt[k] = vprops[k];
    	}
    }

    var vevents = vdom.element.events || {};
    for (var k in vevents) {
    	if (vevents.hasOwnProperty(k)) {
    		elt.addEventListener(k, withCleanListeners(elt, k, dec2handler(vevents[k])));
    	}
    }

    for (var i = 0; i < vdom.element.kids.length; i++) {
    	var kid = build(vdom.element.kids[i]);
    	if (typeof kid === 'function') {
    		// natives append themselves
    		kid(elt);
    	}
    	else {
    		elt.appendChild(kid);
    	}
    }

    return elt;
}
<commit_msg>More refactoring.<commit_after>

// TODO: make nice object, with methods to register natives/builders etc.

function start() {
	buildInitialView();

	window.requestAnimationFrame(render);
}

function render(timestamp) {
	window.requestAnimationFrame(render);

	if (!pendingWork()) {
		return;
	}

	if (waitingForResponse()) {
		flushUIEvents();
		return;
	}

	processMessage(nextMessage());
}

var __event_queue = [];
var __other_queue = [];

var __natives = {};
var __subscriptions = {};

function pendingWork() {
	return __event_queue.length > 0 || __other_queue.length > 0;
}

function nextMessage() {
	return __event_queue.length > 0 ? __event_queue.shift() : __other_queue.shift();
}

function flushUIEvents() {
	console.log("Flushing pending events." + JSON.stringify(__event_queue));
	__event_queue = [];
}

function buildInitialView() {
	send('/init', {}, function (work) {
		doCommands(work[2]);
		subscribe(work[1]);
		replace(root(), build(work[0]));
	});
}

function processMessage(msg) {
	send('/msg', msg, function (work) {
		doCommands(work[2]);
		subscribe(work[1]);
		patch(root(), work[0], dec2handler);
	});
}

var __waiting = false;

function waitingForResponse() {
	return __waiting;
}

function send(url, message, handle) {
	__waiting = true;
	$.get(url, message, handle, 'json').always(function () {
		__waiting = false;
	});
}

function root() {
	return document.getElementById('root');
}

function replace(dom, newDom) {
	dom.parentNode.replaceChild(newDom, dom);
}

function nodeType(node) {
	for (var type in node) { break; }
	return type;
}

function doCommands(cmds) {
	for (var i = 0; i < cmds.length; i++) {
		var cmd = cmds[i];

		switch (nodeType(cmd)) {

		case 'random':
			var random = Math.floor(Math.random() * (cmd.random.to - cmd.random.from + 1)) + cmd.random.from;
			schedule(__other_queue, cmd.random.handle.handle, {type: 'integer', intVal: random});
			break;

		}

	}
}

function sub2handler(sub) {
	switch (nodeType(sub)) {

	case 'timeEvery':
		var timer = setInterval(function() {
			var data = {type: 'integer', intVal: (new Date().getTime() / 1000) | 0};
			schedule(__other_queue, sub.timeEvery.handle.handle, data);
		}, sub.timeEvery.interval);
		return function () {
			clearInterval(timer);
		};

	}
}

function subscribe(subs) {
	for (var i = 0; i < subs.length; i++) {
		var sub = subs[i];
		var type = nodeType(sub);
		var id = sub[type].handle.handle.id;
		if (__subscriptions.hasOwnProperty(id)) {
			continue;
		}
		__subscriptions[id] = sub2handler(sub);
	}

	unsubscribeStaleSubs(subs);
}

function unsubscribeStaleSubs(subs) {
	var toDelete = [];
	outer: for (var k in __subscriptions) {
		if (__subscriptions.hasOwnProperty(k)) {
			for (var i = 0; i < subs.length; i++) {
				var sub = subs[i];
				var id = sub[nodeType(sub)].handle.handle.id;
				if (('' + id) === k) {
					continue outer;
				}
			}
			toDelete.push(k);
		}
	}
	for (var i = 0; i < toDelete.length; i++) {
		__subscriptions[toDelete[i]](); // shutdown
		delete __subscriptions[toDelete[i]];
	}
}

function schedule(queue, handle, data) {
	var result = {id: handle.id};
	if (handle.maps) {
		result.maps = handle.maps.join(';');
	}
	for (var k in data) {
		if (data.hasOwnProperty(k)) {
			result[k] = data[k];
		}
	}
	queue.push(result);
}

// this needs adaptation if new kinds of data are required.
function dec2handler(decoder) {
	switch (nodeType(decoder)) {

	case 'succeed':
		return function (event) {
			// TODO: change 'nothing' to 'ok'
			schedule(__event_queue, decoder.succeed.handle.handle, {type: 'nothing'});
		};

	case 'targetValue':
		return function (event) {
			schedule(__event_queue, decoder.targetValue.handle.handle,
					{type: 'string', strVal: event.target.value});
		};

	case 'targetChecked':
		return function (event) {
			schedule(__event_queue, decoder.targetChecked.handle.handle,
					{type: 'boolean', boolVal: event.target.checked});
		};

	}
}

function patchThis(dom, edits) {
	edits = edits || [];
	for (var i = 0; i < edits.length; i++) {
		var edit = edits[i];
		var type = nodeType(edit);

		switch (type) {

		case 'replace':
			return build(edit[type].html);

		case 'setText':
			dom.nodeValue = edit[type].contents;
			break;

		case 'removeNode':
			dom.removeChild(dom.lastChild);
			break;

		case 'appendNode':
			var kid = build(edit[type].html);
			if (typeof kid === 'function') {
				kid(dom);
			}
			else {
				dom.appendChild(kid);
			}
			break;

		case 'setAttr':
			dom.setAttribute(edit[type].name, edit[type].val);
			break;

		case 'setProp':
			dom[edit[type].name] = edit[type].val;
			break;

		case 'setEvent':
			var key = edit[type].name;
			var handler = dec2handler(edit[type].handler);
			dom.addEventListener(key, withCleanListeners(dom, key, handler));
			break

		case 'removeAttr':
			dom.removeAttribute(edit[type].name);
			break;

		case 'removeProp':
			delete dom[edit[type].name]; //???
			break;

		case 'removeEvent':
			// todo: refactor
			var handler = dom.myHandlers[edit[type].name];
			dom.removeEventListener(edit[type].name, handler);
			break;

		default:
			throw 'unsupported edit: ' + JSON.stringify(edit);

		}
	}
}

function patch(dom, tree) {
	var newDom = patchThis(dom, tree.patch.edits);

	if (newDom) {
		replace(dom, newDom);
		return;
	}

	var patches = tree.patch.patches || [];
	for (var i = 0; i < patches.length; i++) {
		var p = patches[i];
		patch(dom.childNodes[p.patch.pos], p);
	}

}

function withCleanListeners(dom, key, handler) {
	var allHandlers = dom.myHandlers || {};
	if (allHandlers.hasOwnProperty(key)) {
		dom.removeEventListener(key, allHandlers[key]);
	}
	allHandlers[key] = handler;
	dom.myHandlers = allHandlers;
	return handler;
}

function build(vdom) {
    if (vdom === undefined) {
        return document.createTextNode('');
    }

    if (vdom.txt !== undefined) {
        return document.createTextNode(vdom.txt.contents);
    }

    if (vdom.native !== undefined) {
    	return makeNative(vdom.native);
    }

    var vattrs = vdom.element.attrs || {};
    var vprops = vdom.element.props || {};

    var elt = vprops.namespace != undefined
            ? document.createElementNS(vprops.namespace, vdom.element.tagName)
            : document.createElement(vdom.element.tagName);

    for (var k in vattrs) {
        if (vattrs.hasOwnProperty(k)) {
            elt.setAttribute(k, vattrs[k]);
        }
    }

    for (var k in vprops) {
    	if (vprops.hasOwnProperty(k)) {
    		elt[k] = vprops[k];
    	}
    }

    var vevents = vdom.element.events || {};
    for (var k in vevents) {
    	if (vevents.hasOwnProperty(k)) {
    		elt.addEventListener(k, withCleanListeners(elt, k, dec2handler(vevents[k])));
    	}
    }

    for (var i = 0; i < vdom.element.kids.length; i++) {
    	var kid = build(vdom.element.kids[i]);
    	if (typeof kid === 'function') {
    		// natives append themselves
    		kid(elt);
    	}
    	else {
    		elt.appendChild(kid);
    	}
    }

    return elt;
}

function makeNative(native) {
	if (!__natives.hasOwnProperty(native.key)) {
		__natives[native.key] = function(parent) {
			return __builders[native.kind](parent, native.attrs, native.props, native.events);
		};
	}
	return __natives[native.key];
}

<|endoftext|>


<commit_before>import Ember from 'ember';
import { Adapter } from 'ember-pouch';
import PouchAdapterUtils from 'hospitalrun/mixins/pouch-adapter-utils';

export default Adapter.extend(PouchAdapterUtils, {
  database: Ember.inject.service(),
  db: Ember.computed.reads('database.mainDB'),

  _specialQueries: [
    'containsValue',
    'mapReduce',
    'searchIndex'
  ],

  _executeContainsSearch: function(store, type, query) {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      var typeName = this.getRecordTypeName(type);
      var searchUrl = `/search/hrdb/${typeName}/_search`;
      if (query.containsValue && query.containsValue.value) {
        var queryString = '';
        query.containsValue.keys.forEach(function(key) {
          if (!Ember.isEmpty(queryString)) {
            queryString = `${queryString} OR `;
          }
          queryString = `${queryString}${key}:${query.containsValue.value}`;
        });
        Ember.$.ajax(searchUrl, {
          dataType: 'json',
          data: {
            q: queryString
          },
          success: function(results) {
            if (results && results.hits && results.hits.hits) {
              var resultDocs = Ember.A(results.hits.hits).map(function(hit) {
                var mappedResult = hit._source;
                mappedResult.id = mappedResult._id;
                return mappedResult;
              });
              var response = {
                rows: resultDocs
              };
              this._handleQueryResponse(response, store, type).then(resolve, reject);
            } else if (results.rows) {
              this._handleQueryResponse(results, store, type).then(resolve, reject);
            } else {
              reject('Search results are not valid');
            }
          }.bind(this)
        });
      } else {
        reject('invalid query');
      }
    }.bind(this));
  },

  _handleQueryResponse: function(response, store, type) {
    var database = this.get('database');
    return new Ember.RSVP.Promise(function(resolve, reject) {
      if (response.rows.length > 0) {
        var ids = response.rows.map(function(row) {
          return database.getEmberId(row.id);
        });
        this.findRecord(store, type, ids).then(function(findResponse) {
          var primaryRecordName = type.modelName.camelize().pluralize(),
            sortedValues = [];
          // Sort response in order of ids
          ids.forEach(function(id) {
            var resolvedRecord = findResponse[primaryRecordName].findBy('id', id);
            sortedValues.push(resolvedRecord);
          });
          findResponse[primaryRecordName] = sortedValues;
          resolve(findResponse);
        }.bind(this), reject);
      } else {
        var emptyResponse = {};
        emptyResponse[type.modelName] = [];
        resolve(emptyResponse);
      }
    }.bind(this));
  },

  /**
   * @private
   * Look for nulls and maxvalues in start key because those keys can't be handled by the sort/list function
   */
  _doesStartKeyContainSpecialCharacters: function(startkey) {
    var haveSpecialCharacters = false,
      maxValue = this.get('maxValue');
    if (!Ember.isEmpty(startkey) && Ember.isArray(startkey)) {
      startkey.forEach(function(keyvalue) {
        if (keyvalue === null || keyvalue === maxValue) {
          haveSpecialCharacters = true;
        }
      });
    }
    return haveSpecialCharacters;
  },

  generateIdForRecord: function() {
    return PouchDB.utils.uuid();
  },

  onChange: function(change) {
    // If relational_pouch isn't initialized yet, there can't be any records
    // in the store to update.
    if (!this.get('db').rel) {
      return;
    }

    var obj = this.get('db').rel.parseDocID(change.id);
    // skip changes for non-relational_pouch docs. E.g., design docs.
    if (!obj.type || !obj.id || obj.type === '') {
      return;
    }

    var store = this.store;

    try {
      store.modelFor(obj.type);
    } catch (e) {
      // The record refers to a model which this version of the application
      // does not have.
      return;
    }

    var recordInStore = store.peekRecord(obj.type, obj.id);
    if (!recordInStore) {
      // The record hasn't been loaded into the store; no need to reload its data.
      return;
    }
    if (!recordInStore.get('isLoaded') || recordInStore.get('hasDirtyAttributes')) {
      // The record either hasn't loaded yet or has unpersisted local changes.
      // In either case, we don't want to refresh it in the store
      // (and for some substates, attempting to do so will result in an error).
      return;
    }

    if (change.deleted) {
      store.unloadRecord(recordInStore);
    } else {
      recordInStore.reload();
    }
  },

  query: function(store, type, query, options) {
    var specialQuery = false;
    for (var i = 0; i < this._specialQueries.length; i++) {
      if (Ember.get(query, this._specialQueries[i])) {
        specialQuery = true;
        break;
      }
    }
    if (!specialQuery) {
      if (query.options) {
        this._init(store, type);
        var recordTypeName = this.getRecordTypeName(type);
        return this.get('db').rel.find(recordTypeName, query.options);
      } else {
        return this._super(store, type, query, options);
      }
    } else {
      var mapReduce = null,
        queryParams = {};
      if (query.searchIndex) {
        queryParams = query.searchIndex;
      }
      if (query.options) {
        queryParams = Ember.copy(query.options);
        if (query.sortKey || query.filterBy) {
          if (query.sortDesc) {
            queryParams.sortDesc = query.sortDesc;
          }
          if (query.sortKey) {
            queryParams.sortKey = query.sortKey;
          }
          if (!this._doesStartKeyContainSpecialCharacters(queryParams.startkey)) {
            queryParams.sortLimit = queryParams.limit;
            delete queryParams.limit;
            queryParams.sortStartKey = JSON.stringify(queryParams.startkey);
            delete queryParams.startkey;
          } else if (queryParams.startkey) {
            queryParams.startkey = JSON.stringify(queryParams.startkey);
          }
          if (query.filterBy) {
            queryParams.filterBy = JSON.stringify(query.filterBy);
          }
          if (queryParams.endkey) {
            queryParams.endkey = JSON.stringify(queryParams.endkey);
          }
          query.useList = true;
        }
      }
      queryParams.reduce = false;
      queryParams.include_docs = false;
      if (query.mapReduce) {
        mapReduce = query.mapReduce;
      } else if (query.containsValue) {
        return this._executeContainsSearch(store, type, query);
      }
      return new Ember.RSVP.Promise(function(resolve, reject) {
        var db = this.get('db');
        try {
          if (mapReduce) {
            if (query.useList) {
              queryParams.include_docs = true;
              var listParams = {
                query: queryParams
              };
              db.list(`${mapReduce}/sort/${mapReduce}`, listParams, function(err, response) {
                if (err) {
                  this._pouchError(reject)(err);
                } else {
                  this._handleQueryResponse(response.json, store, type).then(resolve, reject);
                }
              }.bind(this));
            } else {
              db.query(mapReduce, queryParams, function(err, response) {
                if (err) {
                  this._pouchError(reject)(err);
                } else {
                  this._handleQueryResponse(response, store, type).then(resolve, reject);
                }
              }.bind(this));
            }
          } else {
            db.allDocs(queryParams, function(err, response) {
              if (err) {
                this._pouchError(reject)(err);
              } else {
                this._handleQueryResponse(response, store, type).then(resolve, reject);
              }
            }.bind(this));
          }
        } catch (err) {
          this._pouchError(reject)(err);
        }
      }.bind(this), 'findQuery in application-pouchdb-adapter');
    }
  },

  shouldReloadAll: function() {
    return false;
  }
});
<commit_msg>Remove unneeded code because ember-pouch has been upgraded.<commit_after>import Ember from 'ember';
import { Adapter } from 'ember-pouch';
import PouchAdapterUtils from 'hospitalrun/mixins/pouch-adapter-utils';

export default Adapter.extend(PouchAdapterUtils, {
  database: Ember.inject.service(),
  db: Ember.computed.reads('database.mainDB'),

  _specialQueries: [
    'containsValue',
    'mapReduce',
    'searchIndex'
  ],

  _executeContainsSearch: function(store, type, query) {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      var typeName = this.getRecordTypeName(type);
      var searchUrl = `/search/hrdb/${typeName}/_search`;
      if (query.containsValue && query.containsValue.value) {
        var queryString = '';
        query.containsValue.keys.forEach(function(key) {
          if (!Ember.isEmpty(queryString)) {
            queryString = `${queryString} OR `;
          }
          queryString = `${queryString}${key}:${query.containsValue.value}`;
        });
        Ember.$.ajax(searchUrl, {
          dataType: 'json',
          data: {
            q: queryString
          },
          success: function(results) {
            if (results && results.hits && results.hits.hits) {
              var resultDocs = Ember.A(results.hits.hits).map(function(hit) {
                var mappedResult = hit._source;
                mappedResult.id = mappedResult._id;
                return mappedResult;
              });
              var response = {
                rows: resultDocs
              };
              this._handleQueryResponse(response, store, type).then(resolve, reject);
            } else if (results.rows) {
              this._handleQueryResponse(results, store, type).then(resolve, reject);
            } else {
              reject('Search results are not valid');
            }
          }.bind(this)
        });
      } else {
        reject('invalid query');
      }
    }.bind(this));
  },

  _handleQueryResponse: function(response, store, type) {
    var database = this.get('database');
    return new Ember.RSVP.Promise(function(resolve, reject) {
      if (response.rows.length > 0) {
        var ids = response.rows.map(function(row) {
          return database.getEmberId(row.id);
        });
        this.findRecord(store, type, ids).then(function(findResponse) {
          var primaryRecordName = type.modelName.camelize().pluralize(),
            sortedValues = [];
          // Sort response in order of ids
          ids.forEach(function(id) {
            var resolvedRecord = findResponse[primaryRecordName].findBy('id', id);
            sortedValues.push(resolvedRecord);
          });
          findResponse[primaryRecordName] = sortedValues;
          resolve(findResponse);
        }.bind(this), reject);
      } else {
        var emptyResponse = {};
        emptyResponse[type.modelName] = [];
        resolve(emptyResponse);
      }
    }.bind(this));
  },

  /**
   * @private
   * Look for nulls and maxvalues in start key because those keys can't be handled by the sort/list function
   */
  _doesStartKeyContainSpecialCharacters: function(startkey) {
    var haveSpecialCharacters = false,
      maxValue = this.get('maxValue');
    if (!Ember.isEmpty(startkey) && Ember.isArray(startkey)) {
      startkey.forEach(function(keyvalue) {
        if (keyvalue === null || keyvalue === maxValue) {
          haveSpecialCharacters = true;
        }
      });
    }
    return haveSpecialCharacters;
  },

  generateIdForRecord: function() {
    return PouchDB.utils.uuid();
  },

  query: function(store, type, query, options) {
    var specialQuery = false;
    for (var i = 0; i < this._specialQueries.length; i++) {
      if (Ember.get(query, this._specialQueries[i])) {
        specialQuery = true;
        break;
      }
    }
    if (!specialQuery) {
      if (query.options) {
        this._init(store, type);
        var recordTypeName = this.getRecordTypeName(type);
        return this.get('db').rel.find(recordTypeName, query.options);
      } else {
        return this._super(store, type, query, options);
      }
    } else {
      var mapReduce = null,
        queryParams = {};
      if (query.searchIndex) {
        queryParams = query.searchIndex;
      }
      if (query.options) {
        queryParams = Ember.copy(query.options);
        if (query.sortKey || query.filterBy) {
          if (query.sortDesc) {
            queryParams.sortDesc = query.sortDesc;
          }
          if (query.sortKey) {
            queryParams.sortKey = query.sortKey;
          }
          if (!this._doesStartKeyContainSpecialCharacters(queryParams.startkey)) {
            queryParams.sortLimit = queryParams.limit;
            delete queryParams.limit;
            queryParams.sortStartKey = JSON.stringify(queryParams.startkey);
            delete queryParams.startkey;
          } else if (queryParams.startkey) {
            queryParams.startkey = JSON.stringify(queryParams.startkey);
          }
          if (query.filterBy) {
            queryParams.filterBy = JSON.stringify(query.filterBy);
          }
          if (queryParams.endkey) {
            queryParams.endkey = JSON.stringify(queryParams.endkey);
          }
          query.useList = true;
        }
      }
      queryParams.reduce = false;
      queryParams.include_docs = false;
      if (query.mapReduce) {
        mapReduce = query.mapReduce;
      } else if (query.containsValue) {
        return this._executeContainsSearch(store, type, query);
      }
      return new Ember.RSVP.Promise(function(resolve, reject) {
        var db = this.get('db');
        try {
          if (mapReduce) {
            if (query.useList) {
              queryParams.include_docs = true;
              var listParams = {
                query: queryParams
              };
              db.list(`${mapReduce}/sort/${mapReduce}`, listParams, function(err, response) {
                if (err) {
                  this._pouchError(reject)(err);
                } else {
                  this._handleQueryResponse(response.json, store, type).then(resolve, reject);
                }
              }.bind(this));
            } else {
              db.query(mapReduce, queryParams, function(err, response) {
                if (err) {
                  this._pouchError(reject)(err);
                } else {
                  this._handleQueryResponse(response, store, type).then(resolve, reject);
                }
              }.bind(this));
            }
          } else {
            db.allDocs(queryParams, function(err, response) {
              if (err) {
                this._pouchError(reject)(err);
              } else {
                this._handleQueryResponse(response, store, type).then(resolve, reject);
              }
            }.bind(this));
          }
        } catch (err) {
          this._pouchError(reject)(err);
        }
      }.bind(this), 'findQuery in application-pouchdb-adapter');
    }
  }

});
<|endoftext|>


<commit_before>'use strict';

const objHash = require('object-hash');

const getDesignDoc = require('../design/app');

const connect = require('../connect');
const constants = require('../constants');
const CouchError = require('../util/CouchError');
const debug = require('../util/debug')('main:init');
const nanoPromise = require('../util/nanoPromise');

const methods = {
    async open() {
        if (this._initPromise) {
            return this._initPromise;
        }
        return this._initPromise = this.getInitPromise();
    },

    close() {
        return connect.close();
    },

    async getInitPromise() {
        debug(`initialize db ${this._databaseName}`);
        this._nano = await connect.open();
        this._db = this._nano.db.use(this._databaseName);
        const db = await nanoPromise.getDatabase(this._nano, this._databaseName);
        if (!db) {
            if (this._couchOptions.autoCreate) {
                debug.trace('db not found -> create');
                await nanoPromise.createDatabase(this._nano, this._databaseName);
                await nanoPromise.request(this._nano, {
                    method: 'PUT',
                    db: this._databaseName,
                    doc: '_security',
                    body: {
                        admins: {
                            names: [this._couchOptions.username],
                            roles: []
                        },
                        members: {
                            names: [this._couchOptions.username],
                            roles: []
                        }
                    }
                });
            } else {
                debug('db not found - autoCreate is false');
                throw new CouchError(`database ${this._databaseName} does not exist`, 'not found');
            }
        }
        // Must be done before the other checks because they can add documents to the db
        await checkSecurity(this._db, this._couchOptions.username);

        await Promise.all([
            checkDesignDoc(this),
            checkRightsDoc(this._db, this._rights),
            checkDefaultGroupsDoc(this._db)
        ]);
    }
};

async function checkSecurity(db, admin) {
    debug.trace('check security');
    const security = await nanoPromise.getDocument(db, '_security');
    if (!security.admins || !security.admins.names.includes(admin)) {
        throw new CouchError(`${admin} is not an admin of ${db.config.db}`, 'fatal');
    }
}

async function checkDesignDoc(couch) {
    const db = couch._db;
    const dbName = db.config.db;
    debug.trace(`check design documents for database ${dbName}`);
    var custom = couch._customDesign;
    custom.views = custom.views || {};
    const designNames = new Set();
    designNames.add(constants.DESIGN_DOC_NAME);
    let viewNames = Object.keys(custom.views);
    for (let key of viewNames) {
        if (custom.views[key].designDoc) {
            designNames.add(custom.views[key].designDoc);
        }
    }

    // Create the new design doc that would be stored upstream for comparison
    for (let designName of designNames) {
        const newDesignDoc = getNewDesignDoc(designName);
        const oldDesignDoc = await nanoPromise.getDocument(db, `_design/${designName}`);
        if (designDocNeedsUpdate(newDesignDoc, oldDesignDoc)) {
            debug.trace(`design doc ${designName} needs update, saving new revision`);
            await createDesignDoc(db, oldDesignDoc && oldDesignDoc._rev || null, newDesignDoc);
        }
    }

    function designDocNeedsUpdate(newDesignDoc, oldDesignDoc) {
        if (!oldDesignDoc) return true;
        return newDesignDoc.hash !== oldDesignDoc.hash;
    }

    // Generates design document from customViews config
    function getNewDesignDoc(designName) {
        if (designName === constants.DESIGN_DOC_NAME) {
            var designDoc = Object.assign({}, custom);
        } else {
            designDoc = {};
        }
        designDoc.views = {};
        designDoc.designDoc = designName;
        for (var i = 0; i < viewNames.length; i++) {
            var viewName = viewNames[i];
            if (custom.views[viewName].designDoc === designName) {
                designDoc.views[viewName] = custom.views[viewName];
            } else if (!custom.views[viewName].designDoc && designName === constants.DESIGN_DOC_NAME) {
                designDoc.views[viewName] = custom.views[viewName];
            }
        }
        designDoc._id = `_design/${designName}`;
        designDoc = getDesignDoc(designDoc, dbName);
        designDoc.hash = objHash(designDoc);
        return designDoc;
    }
}

async function createDesignDoc(db, revID, designDoc) {
    debug.trace('create design doc');
    const hashDoc = Object.assign({}, designDoc);
    delete hashDoc._rev;
    delete hashDoc.hash;
    const hash = objHash(hashDoc);
    designDoc.hash = hash;
    if (revID) {
        designDoc._rev = revID;
    }
    return nanoPromise.insertDocument(db, designDoc);
}

async function checkRightsDoc(db, rights) {
    debug.trace('check rights doc');
    const doc = await nanoPromise.getDocument(db, constants.RIGHTS_DOC_ID);
    if (doc === null) {
        debug.trace('rights doc does not exist');
        return createRightsDoc(db, rights);
    }
    return true;
}

async function createRightsDoc(db, rightsDoc) {
    return nanoPromise.insertDocument(db, rightsDoc);
}

async function checkDefaultGroupsDoc(db) {
    debug.trace('check defaultGroups doc');
    const doc = await nanoPromise.getDocument(db, constants.DEFAULT_GROUPS_DOC_ID);
    if (doc === null) {
        debug.trace('defaultGroups doc does not exist');
        return nanoPromise.insertDocument(db, {
            _id: constants.DEFAULT_GROUPS_DOC_ID,
            $type: 'db',
            anonymous: [],
            anyuser: []
        });
    }
    return true;
}

module.exports = {
    methods
};
<commit_msg>fix(init): make sure to update nano and db instances on open<commit_after>'use strict';

const objHash = require('object-hash');

const getDesignDoc = require('../design/app');

const connect = require('../connect');
const constants = require('../constants');
const CouchError = require('../util/CouchError');
const debug = require('../util/debug')('main:init');
const nanoPromise = require('../util/nanoPromise');

const methods = {
    async open() {
        const _nano = await connect.open();
        if(this._nano !== _nano) {
            this._nano = _nano;
            this._db = this._nano.db.use(this._databaseName);
        }

        if (this._initPromise) {
            return this._initPromise;
        }
        return this._initPromise = this.getInitPromise();
    },

    close() {
        return connect.close();
    },

    async getInitPromise() {
        debug(`initialize db ${this._databaseName}`);
        const db = await nanoPromise.getDatabase(this._nano, this._databaseName);
        if (!db) {
            if (this._couchOptions.autoCreate) {
                debug.trace('db not found -> create');
                await nanoPromise.createDatabase(this._nano, this._databaseName);
                await nanoPromise.request(this._nano, {
                    method: 'PUT',
                    db: this._databaseName,
                    doc: '_security',
                    body: {
                        admins: {
                            names: [this._couchOptions.username],
                            roles: []
                        },
                        members: {
                            names: [this._couchOptions.username],
                            roles: []
                        }
                    }
                });
            } else {
                debug('db not found - autoCreate is false');
                throw new CouchError(`database ${this._databaseName} does not exist`, 'not found');
            }
        }
        // Must be done before the other checks because they can add documents to the db
        await checkSecurity(this._db, this._couchOptions.username);

        await Promise.all([
            checkDesignDoc(this),
            checkRightsDoc(this._db, this._rights),
            checkDefaultGroupsDoc(this._db)
        ]);
    }
};

async function checkSecurity(db, admin) {
    debug.trace('check security');
    const security = await nanoPromise.getDocument(db, '_security');
    if (!security.admins || !security.admins.names.includes(admin)) {
        throw new CouchError(`${admin} is not an admin of ${db.config.db}`, 'fatal');
    }
}

async function checkDesignDoc(couch) {
    const db = couch._db;
    const dbName = db.config.db;
    debug.trace(`check design documents for database ${dbName}`);
    var custom = couch._customDesign;
    custom.views = custom.views || {};
    const designNames = new Set();
    designNames.add(constants.DESIGN_DOC_NAME);
    let viewNames = Object.keys(custom.views);
    for (let key of viewNames) {
        if (custom.views[key].designDoc) {
            designNames.add(custom.views[key].designDoc);
        }
    }

    // Create the new design doc that would be stored upstream for comparison
    for (let designName of designNames) {
        const newDesignDoc = getNewDesignDoc(designName);
        const oldDesignDoc = await nanoPromise.getDocument(db, `_design/${designName}`);
        if (designDocNeedsUpdate(newDesignDoc, oldDesignDoc)) {
            debug.trace(`design doc ${designName} needs update, saving new revision`);
            await createDesignDoc(db, oldDesignDoc && oldDesignDoc._rev || null, newDesignDoc);
        }
    }

    function designDocNeedsUpdate(newDesignDoc, oldDesignDoc) {
        if (!oldDesignDoc) return true;
        return newDesignDoc.hash !== oldDesignDoc.hash;
    }

    // Generates design document from customViews config
    function getNewDesignDoc(designName) {
        if (designName === constants.DESIGN_DOC_NAME) {
            var designDoc = Object.assign({}, custom);
        } else {
            designDoc = {};
        }
        designDoc.views = {};
        designDoc.designDoc = designName;
        for (var i = 0; i < viewNames.length; i++) {
            var viewName = viewNames[i];
            if (custom.views[viewName].designDoc === designName) {
                designDoc.views[viewName] = custom.views[viewName];
            } else if (!custom.views[viewName].designDoc && designName === constants.DESIGN_DOC_NAME) {
                designDoc.views[viewName] = custom.views[viewName];
            }
        }
        designDoc._id = `_design/${designName}`;
        designDoc = getDesignDoc(designDoc, dbName);
        designDoc.hash = objHash(designDoc);
        return designDoc;
    }
}

async function createDesignDoc(db, revID, designDoc) {
    debug.trace('create design doc');
    const hashDoc = Object.assign({}, designDoc);
    delete hashDoc._rev;
    delete hashDoc.hash;
    const hash = objHash(hashDoc);
    designDoc.hash = hash;
    if (revID) {
        designDoc._rev = revID;
    }
    return nanoPromise.insertDocument(db, designDoc);
}

async function checkRightsDoc(db, rights) {
    debug.trace('check rights doc');
    const doc = await nanoPromise.getDocument(db, constants.RIGHTS_DOC_ID);
    if (doc === null) {
        debug.trace('rights doc does not exist');
        return createRightsDoc(db, rights);
    }
    return true;
}

async function createRightsDoc(db, rightsDoc) {
    return nanoPromise.insertDocument(db, rightsDoc);
}

async function checkDefaultGroupsDoc(db) {
    debug.trace('check defaultGroups doc');
    const doc = await nanoPromise.getDocument(db, constants.DEFAULT_GROUPS_DOC_ID);
    if (doc === null) {
        debug.trace('defaultGroups doc does not exist');
        return nanoPromise.insertDocument(db, {
            _id: constants.DEFAULT_GROUPS_DOC_ID,
            $type: 'db',
            anonymous: [],
            anyuser: []
        });
    }
    return true;
}

module.exports = {
    methods
};
<|endoftext|>


<commit_before>/**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/

import React, { Component, PropTypes } from 'react';
import { push } from 'react-router-redux';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import runtime from 'offline-plugin/runtime';
import styles from './styles.css';
import Notifications from 'containers/Notifications';
import CircularProgress from 'material-ui/CircularProgress';
import MenuItem from 'material-ui/MenuItem';
import Close from 'material-ui/svg-icons/navigation/close';
import IconButton from 'material-ui/IconButton';
import NavigationMenuIcon from 'material-ui/svg-icons/navigation/menu';
import FlatButton from 'material-ui/FlatButton';
import { Toolbar, ToolbarGroup } from 'material-ui/Toolbar';
import AppMainDrawer from 'containers/AppMainDrawer';

import {
  selectBalance,
  selectCompteUtilisateur,
} from 'containers/CompteUtilisateur/selectors';

import {
  selectPending,
  selectMessagesUtilisateurLoaded,
  selectMessagesUtilisateur,
} from './selectors';

import {
  loadMessages,
} from './actions';

import { logout } from 'containers/Login/actions';
import Logged from './components/Logged';
import Login from './components/Login';

const getDrawerHeaderStyle = (context) => {
  const {
    appBar,
  } = context.muiTheme;
  return {
    color: appBar.textColor,
    backgroundColor: appBar.color,
    height: appBar.height + 6,
    fontSize: 24,
    paddingTop: 0,
    lineHeight: `${appBar.height}px`,
  };
};

class App extends Component { // eslint-disable-line react/prefer-stateless-function
  static propTypes = {
    children: PropTypes.node,
    pushState: PropTypes.func.isRequired,
    destinataires: PropTypes.array.isRequired,
    messagesLoaded: PropTypes.bool.isRequired,
    messages: PropTypes.array.isRequired,
    logout: PropTypes.func.isRequired,
    compte: PropTypes.object,
    user: PropTypes.oneOfType([
      PropTypes.object,
      PropTypes.bool,
    ]),
    pending: PropTypes.bool.isRequired,
    loadM: PropTypes.func.isRequired,
  }

  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
  };

  state = {
    drawerOpen: false,
  }

  componentDidMount = () => {
    const { loadM, user, messagesLoaded } = this.props;

    if (user && !messagesLoaded) {
      loadM({ a: user.id });
    }

    console.log('text service workers');
    runtime.install({
      onUpdating: () => {
        console.log('SW Event:', 'onUpdating');
      },
      onUpdateReady: () => {
        console.log('SW Event:', 'onUpdateReady');
        // Update is applied here
        runtime.applyUpdate();
      },
      onUpdated: () => {
        console.log('SW Event:', 'onUpdated');
        // Force reload happens here
        window.location.reload(true);
      },

      onUpdateFailed: () => {
        console.log('SW Event:', 'onUpdateFailed');
      },
    });
  }

  toggleDrawer = () =>
    this.setState({ ...this.state, drawerOpen: !this.state.drawerOpen })

  closeDrawer = () =>
    this.setState({ ...this.state, drawerOpen: false })

  handleChangeList = (event, value) => {
    event.preventDefault();
    this.props.pushState(value);
    this.closeDrawer();
  }

  handleChangeRequestNavDrawer = (open) => {
    this.setState({
      drawerOpen: open,
    });
  };

  render() {
    const {
      user,
      pending,
      destinataires,
      pushState,
      compte,
      messages,
    } = this.props;
    const { muiTheme } = this.context;
    const drawerStyle = getDrawerHeaderStyle(this.context);
    let showPorteMonnaie = false;
    if (compte) {
      showPorteMonnaie = true;
    }
    return (

        <Toolbar
          className={`${styles.noPrint} ${styles.toolbar}`}
          style={{
            backgroundColor: muiTheme.appBar.color,
            height: '50px',
          }}
        >
          <ToolbarGroup firstChild>
            <IconButton touch onClick={this.toggleDrawer} style={{ paddingRight: 0 }}>
              <NavigationMenuIcon />
            </IconButton>
            <FlatButton
              label="Relais ProxiWeb"
              style={{ color: 'black', marginLeft: 0, marginTop: 5 }}
              onClick={() => pushState('/')}
            />
            {pending && (

                <CircularProgress
                  size={20}
                  color="white"
                  status="loading"
                  style={{ display: 'inline-block', position: 'absolute', zIndex: 1200, top: 19, left: -35 }}
                />

            )}
          </ToolbarGroup>
          {
            user
            ?
              <Logged
                messages={messages.filter((m) => m.dateConsultation === null)}
                destinataires={destinataires}
                pushState={pushState}
              />
            :
              <Login onClick={this.handleChangeList} />
          }
        </Toolbar>
        <AppMainDrawer
          open={this.state.drawerOpen}
          onSelect={this.navigateTo}
          onChangeList={this.handleChangeList}
          user={user}
          showPorteMonnaie={showPorteMonnaie}
          onRequestChange={(open) => this.setState({ drawerOpen: open })}
          logout={this.props.logout}
          messages={messages}
          header={(
            <MenuItem
              primaryText="Menu"
              rightIcon={<Close color={drawerStyle.textColor} style={{ height: 40, width: 30 }} />}
              onTouchTap={this.closeDrawer}
              style={drawerStyle}
            />)}
        />
        <div className={`container-fluid ${styles.mainContent}`}>
          {React.Children.toArray(this.props.children)}

        <Notifications />

    );
  }
}

const selectDestinaires = () => (state) => (state.admin ? state.admin.communication.destinataires : []);

const mapStateToProps = createStructuredSelector({
  user: selectCompteUtilisateur(),
  pending: selectPending(),
  destinataires: selectDestinaires(),
  messagesLoaded: selectMessagesUtilisateurLoaded(),
  messages: selectMessagesUtilisateur(),
  compte: selectBalance(),
});

const mapDispatchToProps = (dispatch) => ({
  pushState: (url) => dispatch(push(url)),
  logout: () => dispatch(logout()),
  loadM: (query) => dispatch(loadMessages(query)),
});

export default connect(mapStateToProps, mapDispatchToProps)(App);
<commit_msg>ajout message MAJ<commit_after>/**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/

import React, { Component, PropTypes } from 'react';
import { push } from 'react-router-redux';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import runtime from 'offline-plugin/runtime';
import styles from './styles.css';
import Notifications from 'containers/Notifications';
import CircularProgress from 'material-ui/CircularProgress';
import MenuItem from 'material-ui/MenuItem';
import Close from 'material-ui/svg-icons/navigation/close';
import IconButton from 'material-ui/IconButton';
import NavigationMenuIcon from 'material-ui/svg-icons/navigation/menu';
import FlatButton from 'material-ui/FlatButton';
import { Toolbar, ToolbarGroup } from 'material-ui/Toolbar';
import AppMainDrawer from 'containers/AppMainDrawer';

import {
  selectBalance,
  selectCompteUtilisateur,
} from 'containers/CompteUtilisateur/selectors';

import {
  selectPending,
  selectMessagesUtilisateurLoaded,
  selectMessagesUtilisateur,
} from './selectors';

import {
  loadMessages,
} from './actions';

import { logout } from 'containers/Login/actions';
import Logged from './components/Logged';
import Login from './components/Login';
import MessageMaj from './components/MessageMaj';

const getDrawerHeaderStyle = (context) => {
  const {
    appBar,
  } = context.muiTheme;
  return {
    color: appBar.textColor,
    backgroundColor: appBar.color,
    height: appBar.height + 6,
    fontSize: 24,
    paddingTop: 0,
    lineHeight: `${appBar.height}px`,
  };
};

class App extends Component { // eslint-disable-line react/prefer-stateless-function
  static propTypes = {
    children: PropTypes.node,
    pushState: PropTypes.func.isRequired,
    destinataires: PropTypes.array.isRequired,
    messagesLoaded: PropTypes.bool.isRequired,
    messages: PropTypes.array.isRequired,
    logout: PropTypes.func.isRequired,
    compte: PropTypes.object,
    user: PropTypes.oneOfType([
      PropTypes.object,
      PropTypes.bool,
    ]),
    pending: PropTypes.bool.isRequired,
    loadM: PropTypes.func.isRequired,
  }

  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
  };

  state = {
    drawerOpen: false,
    maj: false,
  }

  componentDidMount = () => {
    const { loadM, user, messagesLoaded } = this.props;

    if (user && !messagesLoaded) {
      loadM({ a: user.id });
    }

    console.log('text service workers');
    runtime.install({
      onUpdating: () => {
        console.log('SW Event:', 'onUpdating');
      },
      onUpdateReady: () => {
        console.log('SW Event:', 'onUpdateReady');
        // Update is applied here
        runtime.applyUpdate();
      },
      onUpdated: () => {
        console.log('SW Event:', 'onUpdated');
        // Force reload happens here
        this.setState({ maj: true });
        setTimeout(
          window.location.reload(true),
          5000
        );
      },

      onUpdateFailed: () => {
        console.log('SW Event:', 'onUpdateFailed');
      },
    });
  }

  toggleDrawer = () =>
    this.setState({ ...this.state, drawerOpen: !this.state.drawerOpen })

  closeDrawer = () =>
    this.setState({ ...this.state, drawerOpen: false })

  handleChangeList = (event, value) => {
    event.preventDefault();
    this.props.pushState(value);
    this.closeDrawer();
  }

  handleChangeRequestNavDrawer = (open) => {
    this.setState({
      drawerOpen: open,
    });
  };

  render() {
    const {
      user,
      pending,
      destinataires,
      pushState,
      compte,
      messages,
    } = this.props;
    const { muiTheme } = this.context;
    const drawerStyle = getDrawerHeaderStyle(this.context);
    let showPorteMonnaie = false;
    if (compte) {
      showPorteMonnaie = true;
    }
    return (

        <Toolbar
          className={`${styles.noPrint} ${styles.toolbar}`}
          style={{
            backgroundColor: muiTheme.appBar.color,
            height: '50px',
          }}
        >
          <ToolbarGroup firstChild>
            <IconButton touch onClick={this.toggleDrawer} style={{ paddingRight: 0 }}>
              <NavigationMenuIcon />
            </IconButton>
            <FlatButton
              label="Relais ProxiWeb"
              style={{ color: 'black', marginLeft: 0, marginTop: 5 }}
              onClick={() => pushState('/')}
            />
            {pending && (

                <CircularProgress
                  size={20}
                  color="white"
                  status="loading"
                  style={{ display: 'inline-block', position: 'absolute', zIndex: 1200, top: 19, left: -35 }}
                />

            )}
          </ToolbarGroup>
          {
            user
            ?
              <Logged
                messages={messages.filter((m) => m.dateConsultation === null)}
                destinataires={destinataires}
                pushState={pushState}
              />
            :
              <Login onClick={this.handleChangeList} />
          }
        </Toolbar>
        <AppMainDrawer
          open={this.state.drawerOpen}
          onSelect={this.navigateTo}
          onChangeList={this.handleChangeList}
          user={user}
          showPorteMonnaie={showPorteMonnaie}
          onRequestChange={(open) => this.setState({ drawerOpen: open })}
          logout={this.props.logout}
          messages={messages}
          header={(
            <MenuItem
              primaryText="Menu"
              rightIcon={<Close color={drawerStyle.textColor} style={{ height: 40, width: 30 }} />}
              onTouchTap={this.closeDrawer}
              style={drawerStyle}
            />)}
        />
        <div className={`container-fluid ${styles.mainContent}`}>
          {!this.state.maj && React.Children.toArray(this.props.children)}
          {this.state.maj && <MessageMaj />}

        <Notifications />

    );
  }
}

const selectDestinaires = () => (state) => (state.admin ? state.admin.communication.destinataires : []);

const mapStateToProps = createStructuredSelector({
  user: selectCompteUtilisateur(),
  pending: selectPending(),
  destinataires: selectDestinaires(),
  messagesLoaded: selectMessagesUtilisateurLoaded(),
  messages: selectMessagesUtilisateur(),
  compte: selectBalance(),
});

const mapDispatchToProps = (dispatch) => ({
  pushState: (url) => dispatch(push(url)),
  logout: () => dispatch(logout()),
  loadM: (query) => dispatch(loadMessages(query)),
});

export default connect(mapStateToProps, mapDispatchToProps)(App);
<|endoftext|>


<commit_before>// Github.js 0.8.0
// (c) 2013 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {

  // Initial Setup
  // -------------

  var XMLHttpRequest, Base64, _;
  if (typeof exports !== 'undefined') {
      XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
      _ = require('underscore');
      Base64 = require('./lib/base64.js');
  }else{
      _ = window._;
      Base64 = window.Base64;
  }
  //prefer native XMLHttpRequest always
  if (typeof window !== 'undefined' && typeof window.XMLHttpRequest !== 'undefined'){
      XMLHttpRequest = window.XMLHttpRequest;
  }

  var API_URL = 'https://api.github.com';

  var Github = function(options) {

    // HTTP Request Abstraction
    // =======
    //
    // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

    function _request(method, path, data, cb, raw) {
      function getURL() {
        var url = API_URL + path;
        return url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime();
      }

      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json";}

      xhr.open(method, getURL());
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true);
          } else {
            cb({request: this, error: this.status});
          }
        }
      };
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        var command = username ? "/users/"+username : "/user";

        _request("GET", command, null, function(err, res) {
          cb(err, res);
        });
      };

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };

      // Follow user
      // -------

      this.follow = function(username, cb) {
        _request("PUT", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // Unfollow user
      // -------

      this.unfollow = function(username, cb) {
        _request("DELETE", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // Create a repo
      // -------
      this.createRepo = function(options, cb) {
        _request("POST", "/user/repos", options, cb);
      };

    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Delete a repo
      // --------

      this.deleteRepo = function(cb) {
        _request("DELETE", repoPath, options, cb);
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef("heads/"+branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // Create a new reference
      // --------
      //
      // {
      //   "ref": "refs/heads/my-new-branch-name",
      //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
      // }

      this.createRef = function(options, cb) {
        _request("POST", repoPath + "/git/refs", options, cb);
      };

      // Delete a reference
      // --------
      //
      // repo.deleteRef('heads/gh-pages')
      // repo.deleteRef('tags/v1.0')

      this.deleteRef = function(ref, cb) {
        _request("DELETE", repoPath + "/git/refs/"+ref, options, cb);
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef("heads/"+branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, cb);
      };

      // Get contents
      // --------

      this.contents = function(branch, path, cb) {
        _request("GET", repoPath + "/contents?ref=" + branch, { path: path }, cb);
      };

      // Fork repository
      // -------

      this.fork = function(cb) {
        console.error(repoPath);
        _request("POST", repoPath + "/forks", null, cb);
      };

      // Create pull request
      // --------

      this.createPullRequest = function(options, cb) {
        _request("POST", repoPath + "/pulls", options, cb);
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, function(err, content) {
            cb(err, content, sha);
          });
        });
      };

      // Remove a file
      // -------

      this.remove = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (err) return cb(err);
          _request("DELETE", repoPath + "/contents/" + path, {
            message: path + " is removed",
            sha: sha,
            branch: branch
          }, cb);
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (err) return cb(err);
          _request("PUT", repoPath + "/contents/" + path, {
            message: message,
            content: Base64.encode(content),
            branch: branch,
            sha: sha
          }, cb);
        });
      };

    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Create the gist
      // --------
      // {
      //  "description": "the description for this gist",
      //    "public": true,
      //    "files": {
      //      "file1.txt": {
      //        "content": "String file contents"
      //      }
      //    }
      // }

      this.create = function(options, cb){
        _request("POST","/gists", options, cb);
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };

  if (typeof exports !== 'undefined') {
    // Github = exports;
    module.exports = Github;
  } else {
    window.Github = Github;
  }
}).call(this);
<commit_msg>better getSha and read functions<commit_after>// Github.js 0.8.0
// (c) 2013 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {

  // Initial Setup
  // -------------

  var XMLHttpRequest, Base64, _;
  if (typeof exports !== 'undefined') {
      XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
      _ = require('underscore');
      Base64 = require('./lib/base64.js');
  }else{
      _ = window._;
      Base64 = window.Base64;
  }
  //prefer native XMLHttpRequest always
  if (typeof window !== 'undefined' && typeof window.XMLHttpRequest !== 'undefined'){
      XMLHttpRequest = window.XMLHttpRequest;
  }

  var API_URL = 'https://api.github.com';

  var Github = function(options) {

    // HTTP Request Abstraction
    // =======
    //
    // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

    function _request(method, path, data, cb, raw) {
      function getURL() {
        var url = API_URL + path;
        return url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime();
      }

      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json";}

      xhr.open(method, getURL());
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true);
          } else {
            cb({request: this, error: this.status});
          }
        }
      };
      xhr.setRequestHeader('Accept','application/json');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        var command = username ? "/users/"+username : "/user";

        _request("GET", command, null, function(err, res) {
          cb(err, res);
        });
      };

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };

      // Follow user
      // -------

      this.follow = function(username, cb) {
        _request("PUT", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // Unfollow user
      // -------

      this.unfollow = function(username, cb) {
        _request("DELETE", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // Create a repo
      // -------
      this.createRepo = function(options, cb) {
        _request("POST", "/user/repos", options, cb);
      };

    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Delete a repo
      // --------

      this.deleteRepo = function(cb) {
        _request("DELETE", repoPath, options, cb);
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef("heads/"+branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // Create a new reference
      // --------
      //
      // {
      //   "ref": "refs/heads/my-new-branch-name",
      //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
      // }

      this.createRef = function(options, cb) {
        _request("POST", repoPath + "/git/refs", options, cb);
      };

      // Delete a reference
      // --------
      //
      // repo.deleteRef('heads/gh-pages')
      // repo.deleteRef('tags/v1.0')

      this.deleteRef = function(ref, cb) {
        _request("DELETE", repoPath + "/git/refs/"+ref, options, cb);
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        if (!path || path === "") return that.getRef("heads/"+branch, cb);
        _request("GET", repoPath + "/contents/"+path, {ref: branch}, function(err, pathContent) {
          if (err) return cb(err);
          cb(null, pathContent.sha);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, cb);
      };

      // Get contents
      // --------

      this.contents = function(branch, path, cb) {
        _request("GET", repoPath + "/contents?ref=" + branch, { path: path }, cb);
      };

      // Fork repository
      // -------

      this.fork = function(cb) {
        _request("POST", repoPath + "/forks", null, cb);
      };

      // Create pull request
      // --------

      this.createPullRequest = function(options, cb) {
        _request("POST", repoPath + "/pulls", options, cb);
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        _request("GET", repoPath + "/contents/"+path, {ref: branch}, function(err, obj) {
          if (err && err.error === 404) return cb("not found", null, null);

          if (err) return cb(err);
          var sha = obj.sha
            , content = Base64.decode(obj.content);

          cb(null, content, sha);
        });
      };

      // Remove a file
      // -------

      this.remove = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (err) return cb(err);
          _request("DELETE", repoPath + "/contents/" + path, {
            message: path + " is removed",
            sha: sha,
            branch: branch
          }, cb);
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (err && err.error!=404) return cb(err);
          _request("PUT", repoPath + "/contents/" + path, {
            message: message,
            content: Base64.encode(content),
            branch: branch,
            sha: sha
          }, cb);
        });
      };

    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Create the gist
      // --------
      // {
      //  "description": "the description for this gist",
      //    "public": true,
      //    "files": {
      //      "file1.txt": {
      //        "content": "String file contents"
      //      }
      //    }
      // }

      this.create = function(options, cb){
        _request("POST","/gists", options, cb);
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };

  if (typeof exports !== 'undefined') {
    // Github = exports;
    module.exports = Github;
  } else {
    window.Github = Github;
  }
}).call(this);
<|endoftext|>


<commit_before>module.exports = {
  'GitHub example testing': function (test) {
  test
    .open('https://github.com')
    .waitForElement('input[name=q]')
    .assert.title().is('GitHub · Build software better, together.', 'GitHub has the correct page title!')
    .type('input[name=q]', 'dalekjs')
    .submit('.js-site-search-form')
    .waitFor(function() {
      return $('li.repo-list-item:nth-child(1) > h3:nth-child(2) > a:nth-child(1)').text() === 'dalekjs/dalek'
    })
    .assert.text('.sort-bar > h3:nth-child(2)', 'We\'ve found 53 repository results')
    .done();
  }
};
<commit_msg>Simplify example<commit_after>module.exports = {
  'GitHub example testing': function (test) {
  test
    .open('https://github.com')
    .waitForElement('input[name=q]')
    .assert.title().is('GitHub · Build software better, together.', 'GitHub has the correct page title!')
    .type('input[name=q]', 'dalekjs')
    .submit('.js-site-search-form')
    .assert.text('.sort-bar > h3:nth-child(2)', 'We\'ve found 53 repository results')
    .done();
  }
};
<|endoftext|>


<commit_before>import React from 'react';
import axios from 'axios';
import Event from './Event';
import MenuBar from '../components/MenuBar';

class EventList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
    };
  }

  componentDidMount() {
    axios.get('/api/events')
      .then((response) => {
        this.setState({ data: [{"id": 1, "location": "here", "name": "my cool event", "description": "my cool description"},
          {"id": 2, "location": "here", "name": "my cool event", "description": "my cool description"},
          {"id": 3, "location": "here", "name": "my cool event", "description": "my cool description"},
          ] });
      })
      .catch((error) => {
        console.log(error);
      });
  }

  render() {
    const eventNodes = this.state.data.map((event) => {
      return (
        <Event
          key={event.id}
          name={event.name}
          location={event.location}
          description={event.description}
          id={event.id}
        >
        .
        </Event>
      );
    });
    return (

        <MenuBar />

          {eventNodes}

    );
  }
}

export default EventList;
<commit_msg>deleted dummy data<commit_after>import React from 'react';
import axios from 'axios';
import Event from './Event';
import MenuBar from '../components/MenuBar';

class EventList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
    };
  }

  componentDidMount() {
    axios.get('/api/events')
      .then((response) => {
        this.setState({ data: response.data });
      })
      .catch((error) => {
        console.log(error);
      });
  }

  render() {
    const eventNodes = this.state.data.map((event) => {
      return (
        <Event
          key={event.id}
          name={event.name}
          location={event.location}
          description={event.description}
          id={event.id}
        >
        .
        </Event>
      );
    });
    return (

        <MenuBar />

          {eventNodes}

    );
  }
}

export default EventList;
<|endoftext|>


<commit_before>var express = require('express');
var config = require('../../config.json');
var githubHandler = require('../github-deployment/handler');

var app = express();

app.post(config.githubDeployment.path, function(req, res) {
  console.log("handling new github request: ", req.url.split('?').shift());
  githubHandler(req, res, function(err) {
    console.log("Error handling github request: ", err);
  });
});

app.get('/', function(req, res) {
  res.send('Hello there!');
});

var server = app.listen(config.frontend.port, function() {
  var host = server.address().address;
  var port = server.address().port;

  console.log("application-server-manager frontend listening at http://%s:%s", host, port);
});

process.on('exit', function() {
  server.close();
})

process.on('uncaughtException', function() {
  console.log("uncaught exception");
  server.close();
});

process.on('SIGTERM', function() {
  server.close();
});

module.exports = {
  app: app,
  githubHandler: githubHandler
}
<commit_msg>info around uncaught exceptions<commit_after>var express = require('express');
var config = require('../../config.json');
var githubHandler = require('../github-deployment/handler');

var app = express();

app.post(config.githubDeployment.path, function(req, res) {
  console.log("handling new github request: ", req.url.split('?').shift());
  githubHandler(req, res, function(err) {
    console.log("Error handling github request: ", err);
  });
});

app.get('/', function(req, res) {
  res.send('Hello there!');
});

var server = app.listen(config.frontend.port, function() {
  var host = server.address().address;
  var port = server.address().port;

  console.log("application-server-manager frontend listening at http://%s:%s", host, port);
});

process.on('exit', function() {
  server.close();
})

process.on('uncaughtException', function(e) {
  console.log("uncaught exception", e);
  server.close();
});

process.on('SIGTERM', function() {
  server.close();
});

module.exports = {
  app: app,
  githubHandler: githubHandler
}
<|endoftext|>