<commit_before>'use strict';

var Promise = require('promise');
var handleQs = require('then-request/lib/handle-qs.js');

var jsonpID = 0;

module.exports = pquest;
function pquest(method, url, options, callback) {
  var result = new Promise(function (resolve, reject) {

    // check types of arguments

    if (typeof method !== 'string') {
      throw new TypeError('The method must be a string.');
    }
    if (typeof url !== 'string') {
      throw new TypeError('The URL/path must be a string.');
    }
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }
    if (options === null || options === undefined) {
      options = {};
    }
    if (typeof options !== 'object') {
      throw new TypeError('Options must be an object (or null).');
    }
    if (typeof callback !== 'function') {
      callback = undefined;
    }

    if (options.body) {
      throw new TypeError('JSONP does not support requests that have bodies');
    }
    if (options.headers) {
      throw new TypeError('JSONP does not support requests that specify headers');
    }
    if (options.followRedirects === false) {
      throw new TypeError('JSONP does not support requests that do not follow redirects');
    }

    options.qs = options.qs || {};
    if (options.json) {
      Object.keys(options.json).forEach(function (key) {
        options.qs[key] = options.json[key];
      });
      delete options.json;
    }

    var callbackName = options.callbackName || 'then_jsonp_' + (++jsonpID);

    if (options.callbackParameter !== false) {
      options.qs[options.callbackParameter || 'callback'] = callbackName;
    }
    if (method.toLowerCase() !== 'get') {
      options.qs[options.methodParameter || 'method'] = method;
    }

    // handle query string
    if (options.qs) {
      url = handleQs(url, options.qs);
    }

    var script = document.createElement('script');
    var head = document.getElementsByTagName('head')[0] || document.documentElement;
    var abortTimeout;

    script.onerror = function () {
      clearTimeout(abortTimeout);
      if (callbackName in window) window[callbackName] = function () {};
      reject(new Error('JSONP request failed'));
    };
    window[callbackName] = function (result) {
      clearTimeout(abortTimeout);
      delete window[callbackName];
      resolve(result);
    };
    abortTimeout = setTimeout(function(){
      if (callbackName in window) window[callbackName] = function () {};
      reject(new Error('JSONP timed out'));
    }, options.timeout || 10000);

    script.src = url;

    // Use insertBefore instead of appendChild to circumvent an IE6 bug.
    // This arises when a base node is used (see jQuery bugs #2709 and #4378).
    head.insertBefore(script, head.firstChild);
  });
  result.getBody = function () {
    return result.then(function (res) { return res.getBody(); });
  };
  return result.nodeify(callback);
}
<commit_msg>Queue if multiple requests are attempted with the same callbackName<commit_after>'use strict';

var Promise = require('promise');
var handleQs = require('then-request/lib/handle-qs.js');

var jsonpID = 0;

var queues = {};

module.exports = pquest;
function pquest(method, url, options, callback) {
  var result = new Promise(function (resolve, reject) {

    // check types of arguments

    if (typeof method !== 'string') {
      throw new TypeError('The method must be a string.');
    }
    if (typeof url !== 'string') {
      throw new TypeError('The URL/path must be a string.');
    }
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }
    if (options === null || options === undefined) {
      options = {};
    }
    if (typeof options !== 'object') {
      throw new TypeError('Options must be an object (or null).');
    }
    if (typeof callback !== 'function') {
      callback = undefined;
    }

    if (options.body) {
      throw new TypeError('JSONP does not support requests that have bodies');
    }
    if (options.headers) {
      throw new TypeError('JSONP does not support requests that specify headers');
    }
    if (options.followRedirects === false) {
      throw new TypeError('JSONP does not support requests that do not follow redirects');
    }

    options.qs = options.qs || {};
    if (options.json) {
      Object.keys(options.json).forEach(function (key) {
        options.qs[key] = options.json[key];
      });
      delete options.json;
    }

    var callbackName = options.callbackName || 'then_jsonp_' + (++jsonpID);

    if (options.callbackParameter !== false) {
      options.qs[options.callbackParameter || 'callback'] = callbackName;
    }
    if (method.toLowerCase() !== 'get') {
      options.qs[options.methodParameter || 'method'] = method;
    }

    if (queues[callbackName]) {
      queues[callbackName].push(run);
    } else {
      queues[callbackName] = [];
      run();
    }

    function run() {
      // handle query string
      if (options.qs) {
        url = handleQs(url, options.qs);
      }

      var script = document.createElement('script');
      var head = document.getElementsByTagName('head')[0] || document.documentElement;
      var abortTimeout;
      var done = false;
      function onComplete(success) {
        if (!done) {
          done = true;
          script.onload = script.onreadystatechange = script.onerror = null;
          clearTimeout(abortTimeout);
          if (callbackName in window) {
            if (success) delete window[callbackName];
            else window[callbackName] = function () {};
          }
          if (script && script.parentNode) {
            script.parentNode.removeChild(script);
          }
          if (queues[callbackName].length) queues[callbackName].shift()();
          else delete queues[callbackName];
        }
      }
      script.onload = script.onreadystatechange = function () {
        if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
          onComplete();
        }
        setTimeout(function () {
          reject(new Error('JSONP callback should already have been called'));
        }, 100);
      };
      script.onerror = function () {
        onComplete();
        reject(new Error('JSONP request failed'));
      };
      window[callbackName] = function (result) {
        onComplete(true);
        resolve(result);
      };
      abortTimeout = setTimeout(function(){
        onComplete();
        reject(new Error('JSONP timed out'));
      }, options.timeout || 10000);

      script.src = url;
      script.async = true;

      head.appendChild(script);
    }
  });
  result.getBody = function () {
    return result.then(function (res) { return res.getBody(); });
  };
  return result.nodeify(callback);
}
<|endoftext|>


<commit_before>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2018 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * @fileoverview Tests for Blockly.Block
 * @author fenichel@google.com (Rachel Fenichel)
 */

goog.require('goog.testing');
goog.require('goog.testing.MockControl');

'use strict';

var workspace;
var mockControl_;

function defineTestBlocks() {
  Blockly.defineBlocksWithJsonArray([{
    "type": "stack_block",
    "message0": "",
    "previousStatement": null,
    "nextStatement": null
  },
  {
    "type": "row_block",
    "message0": "%1",
    "args0": [
      {
        "type": "input_value",
        "name": "INPUT"
      }
    ],
    "output": null
  }]);
}

function undefineTestBlocks() {
  delete Blockly.Blocks['stack_block'];
  delete Blockly.Blocks['row_block'];
}

function blockTest_setUp() {
  defineTestBlocks();
  mockControl_ = new goog.testing.MockControl();
  workspace = new Blockly.Workspace();
}

function blockTest_tearDown() {
  undefineTestBlocks();
  workspace.dispose();
}

function assertUnpluggedNoheal(blocks) {
  // A has nothing connected to it.
  assertEquals(0, blocks.A.getChildren().length);
  // B and C are still connected.
  assertEquals(blocks.B, blocks.C.getParent());
  // B is the top of its stack.
  assertNull(blocks.B.getParent());
}

function assertUnpluggedHealed(blocks) {
  // A and C are connected.
  assertEquals(1, blocks.A.getChildren().length);
  assertEquals(blocks.A, blocks.C.getParent());
  // B has nothing connected to it.
  assertEquals(0, blocks.B.getChildren().length);
  // B is the top of its stack.
  assertNull(blocks.B.getParent());
}

function setUpRowBlocks() {
  var blockA = workspace.newBlock('row_block');
  var blockB = workspace.newBlock('row_block');
  var blockC = workspace.newBlock('row_block');

  blockA.inputList[0].connection.connect(blockB.outputConnection);
  blockB.inputList[0].connection.connect(blockC.outputConnection);

  assertEquals(blockB, blockC.getParent());

  return {
    A: blockA,
    B: blockB,
    C: blockC
  };
}

function setUpStackBlocks() {
  var blockA = workspace.newBlock('stack_block');
  var blockB = workspace.newBlock('stack_block');
  var blockC = workspace.newBlock('stack_block');

  blockA.nextConnection.connect(blockB.previousConnection);
  blockB.nextConnection.connect(blockC.previousConnection);

  assertEquals(blockB, blockC.getParent());

  return {
    A: blockA,
    B: blockB,
    C: blockC
  };
}

function test_block_stack_unplug_noheal() {
  blockTest_setUp();
  try {
    var blocks = setUpStackBlocks();
    blocks.B.unplug();
    assertUnpluggedNoheal(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_stack_unplug_heal() {
  blockTest_setUp();
  try {
    var blocks = setUpStackBlocks();
    blocks.B.unplug(true);
    assertUnpluggedHealed(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_stack_unplug_heal_bad_checks() {
  blockTest_setUp();
  try {
    var blocks = setUpStackBlocks();

    // A and C can't connect, but both can connect to B.
    blocks.A.nextConnection.setCheck('type1');
    blocks.C.previousConnection.setCheck('type2');

    // The types don't work.
    blocks.B.unplug(true);

    // Stack blocks unplug before checking whether the types match.
    // TODO (#1994): Check types before unplugging.
    // A has nothing connected to it.
    assertEquals(0, blocks.A.getChildren().length);
    // B has nothing connected to it.
    assertEquals(0, blocks.B.getChildren().length);
    // C has nothing connected to it.
    assertEquals(0, blocks.C.getChildren().length);
    // A is the top of its stack.
    assertNull(blocks.A.getParent());
    // B is the top of its stack.
    assertNull(blocks.B.getParent());
    // C is the top of its stack.
    assertNull(blocks.C.getParent());
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_noheal() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();
    blocks.B.unplug(false);
    assertUnpluggedNoheal(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_heal() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();
    // Each block has only one input, and the types work.
    blocks.B.unplug(true);
    assertUnpluggedHealed(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_heal_bad_checks() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();

    // A and C can't connect, but both can connect to B.
    blocks.A.inputList[0].connection.setCheck('type1');
    blocks.C.outputConnection.setCheck('type2');

    // Each block has only one input, but the types don't work.
    blocks.B.unplug(true);
    assertUnpluggedNoheal(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_multi_inputs_parent() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();
    // Add extra input to parent
    blocks.A.appendValueInput('INPUT').setCheck(null);

    // Parent block has multiple inputs.
    blocks.B.unplug(true);
    assertUnpluggedHealed(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_multi_inputs_middle() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();
    // Add extra input to middle block
    blocks.B.appendValueInput('INPUT').setCheck(null);

    // Middle block has multiple inputs.
    blocks.B.unplug(true);
    assertUnpluggedHealed(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_multi_inputs_child() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();
    // Add extra input to child block
    blocks.C.appendValueInput('INPUT').setCheck(null);

    // Child block input count doesn't matter.
    blocks.B.unplug(true);
    assertUnpluggedHealed(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_set_style() {
  blockTest_setUp();
  var styleStub = {
    getBlockStyle: function() {
      return {
        "colourPrimary": "#ffffff",
        "colourSecondary": "#aabbcc",
        "colourTertiary": "#ddeeff"
      }
    }
  };
  setUpMockMethod(mockControl_, Blockly, 'getTheme', null, [styleStub]);
  var blockA = workspace.newBlock('row_block');
  blockA.setStyle('styleOne');

  assertEquals('#ffffff', blockA.colour_);
  assertEquals('#aabbcc', blockA.colourSecondary_);
  assertEquals('#ddeeff', blockA.colourTertiary_);

  blockTest_tearDown();
}

function test_set_style_throw_exception() {
  blockTest_setUp();
  var styleStub = {
    getBlockStyle: function() {
      return null;
    }
  };
  setUpMockMethod(mockControl_, Blockly, 'getTheme', null, [styleStub]);
  var blockA = workspace.newBlock('row_block');
  try {
    blockA.setStyle('styleOne');
  } catch(error) {
    assertEquals(error.message, 'Invalid style name: styleOne');
  } finally {
    blockTest_tearDown();
  }
}
<commit_msg>Properly tear down tests<commit_after>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2018 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * @fileoverview Tests for Blockly.Block
 * @author fenichel@google.com (Rachel Fenichel)
 */

goog.require('goog.testing');
goog.require('goog.testing.MockControl');

'use strict';

var workspace;
var mockControl_;

function defineTestBlocks() {
  Blockly.defineBlocksWithJsonArray([{
    "type": "stack_block",
    "message0": "",
    "previousStatement": null,
    "nextStatement": null
  },
  {
    "type": "row_block",
    "message0": "%1",
    "args0": [
      {
        "type": "input_value",
        "name": "INPUT"
      }
    ],
    "output": null
  }]);
}

function undefineTestBlocks() {
  delete Blockly.Blocks['stack_block'];
  delete Blockly.Blocks['row_block'];
}

function blockTest_setUp() {
  defineTestBlocks();
  mockControl_ = new goog.testing.MockControl();
  workspace = new Blockly.Workspace();
}

function blockTest_tearDown() {
  undefineTestBlocks();
  workspace.dispose();
  mockControl_.$tearDown();
}

function assertUnpluggedNoheal(blocks) {
  // A has nothing connected to it.
  assertEquals(0, blocks.A.getChildren().length);
  // B and C are still connected.
  assertEquals(blocks.B, blocks.C.getParent());
  // B is the top of its stack.
  assertNull(blocks.B.getParent());
}

function assertUnpluggedHealed(blocks) {
  // A and C are connected.
  assertEquals(1, blocks.A.getChildren().length);
  assertEquals(blocks.A, blocks.C.getParent());
  // B has nothing connected to it.
  assertEquals(0, blocks.B.getChildren().length);
  // B is the top of its stack.
  assertNull(blocks.B.getParent());
}

function setUpRowBlocks() {
  var blockA = workspace.newBlock('row_block');
  var blockB = workspace.newBlock('row_block');
  var blockC = workspace.newBlock('row_block');

  blockA.inputList[0].connection.connect(blockB.outputConnection);
  blockB.inputList[0].connection.connect(blockC.outputConnection);

  assertEquals(blockB, blockC.getParent());

  return {
    A: blockA,
    B: blockB,
    C: blockC
  };
}

function setUpStackBlocks() {
  var blockA = workspace.newBlock('stack_block');
  var blockB = workspace.newBlock('stack_block');
  var blockC = workspace.newBlock('stack_block');

  blockA.nextConnection.connect(blockB.previousConnection);
  blockB.nextConnection.connect(blockC.previousConnection);

  assertEquals(blockB, blockC.getParent());

  return {
    A: blockA,
    B: blockB,
    C: blockC
  };
}

function test_block_stack_unplug_noheal() {
  blockTest_setUp();
  try {
    var blocks = setUpStackBlocks();
    blocks.B.unplug();
    assertUnpluggedNoheal(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_stack_unplug_heal() {
  blockTest_setUp();
  try {
    var blocks = setUpStackBlocks();
    blocks.B.unplug(true);
    assertUnpluggedHealed(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_stack_unplug_heal_bad_checks() {
  blockTest_setUp();
  try {
    var blocks = setUpStackBlocks();

    // A and C can't connect, but both can connect to B.
    blocks.A.nextConnection.setCheck('type1');
    blocks.C.previousConnection.setCheck('type2');

    // The types don't work.
    blocks.B.unplug(true);

    // Stack blocks unplug before checking whether the types match.
    // TODO (#1994): Check types before unplugging.
    // A has nothing connected to it.
    assertEquals(0, blocks.A.getChildren().length);
    // B has nothing connected to it.
    assertEquals(0, blocks.B.getChildren().length);
    // C has nothing connected to it.
    assertEquals(0, blocks.C.getChildren().length);
    // A is the top of its stack.
    assertNull(blocks.A.getParent());
    // B is the top of its stack.
    assertNull(blocks.B.getParent());
    // C is the top of its stack.
    assertNull(blocks.C.getParent());
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_noheal() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();
    blocks.B.unplug(false);
    assertUnpluggedNoheal(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_heal() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();
    // Each block has only one input, and the types work.
    blocks.B.unplug(true);
    assertUnpluggedHealed(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_heal_bad_checks() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();

    // A and C can't connect, but both can connect to B.
    blocks.A.inputList[0].connection.setCheck('type1');
    blocks.C.outputConnection.setCheck('type2');

    // Each block has only one input, but the types don't work.
    blocks.B.unplug(true);
    assertUnpluggedNoheal(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_multi_inputs_parent() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();
    // Add extra input to parent
    blocks.A.appendValueInput('INPUT').setCheck(null);

    // Parent block has multiple inputs.
    blocks.B.unplug(true);
    assertUnpluggedHealed(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_multi_inputs_middle() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();
    // Add extra input to middle block
    blocks.B.appendValueInput('INPUT').setCheck(null);

    // Middle block has multiple inputs.
    blocks.B.unplug(true);
    assertUnpluggedHealed(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_block_row_unplug_multi_inputs_child() {
  blockTest_setUp();
  try {
    var blocks = setUpRowBlocks();
    // Add extra input to child block
    blocks.C.appendValueInput('INPUT').setCheck(null);

    // Child block input count doesn't matter.
    blocks.B.unplug(true);
    assertUnpluggedHealed(blocks);
  } finally {
    blockTest_tearDown();
  }
}

function test_set_style() {
  blockTest_setUp();
  var styleStub = {
    getBlockStyle: function() {
      return {
        "colourPrimary": "#ffffff",
        "colourSecondary": "#aabbcc",
        "colourTertiary": "#ddeeff"
      }
    }
  };
  setUpMockMethod(mockControl_, Blockly, 'getTheme', null, [styleStub]);
  var blockA = workspace.newBlock('row_block');
  blockA.setStyle('styleOne');

  assertEquals('#ffffff', blockA.colour_);
  assertEquals('#aabbcc', blockA.colourSecondary_);
  assertEquals('#ddeeff', blockA.colourTertiary_);

  blockTest_tearDown();
  \
}

function test_set_style_throw_exception() {
  blockTest_setUp();
  var styleStub = {
    getBlockStyle: function() {
      return null;
    }
  };
  setUpMockMethod(mockControl_, Blockly, 'getTheme', null, [styleStub]);
  var blockA = workspace.newBlock('row_block');
  try {
    blockA.setStyle('styleOne');
  } catch(error) {
    assertEquals(error.message, 'Invalid style name: styleOne');
  } finally {
    blockTest_tearDown();
  }
}
<|endoftext|>


<commit_before>"use strict";
var gPrivTimeline = {"done":0,"postsById":{},"oraphed":{count:0},"noKey":{},"noDecipher":{},nCmts:0,"posts":[] };
var matrix  = new Object();
var Init = require("./init.js")
var Addons = require("./addons.js");
window.browserDoc = function(){
	var cView = document.cView;
	var Utils = cView.Utils;
	var locationPath = /(https?:\/\/[^\?]*)/.exec(document.location)[1].slice(gConfig.front.length);
	if (locationPath == "")locationPath = "home";
	cView.fullPath = locationPath;
	var arrLocationPath = locationPath.split("/");
	if(arrLocationPath[0].toLowerCase() != "settings"){
		cView.search = document.location.search.slice(1);
		var matchOffset = cView.search.match(/offset=(\d+)/);
		if(matchOffset) cView.skip = matchOffset[1];
		cView.search = cView.search.replace(/offset=\d+&?/,"").replace(/limit=\d+&?/,"")
	}else if(locationPath.indexOf("settings/raw") != -1){
		var nodeSplash = document.getElementById("splash");
		cView.Drawer.drawRaw(nodeSplash);
	}

	if(JSON.parse(cView.localStorage.getItem("blocks")))
		cView.blocks = JSON.parse(cView.localStorage.getItem("blocks"));
	if(typeof cView.blocks.blockStrings === "undefined")
		cView.blocks.blockStrings = new Object();
	var nameMode = cView.localStorage.getItem("screenname");
	if(nameMode){
		cView.localStorage.setItem("display_name", nameMode);
		cView.localStorage.removeItem("screenname");
	}
	setLocalSettings();
	cView.Common.loadLogins();
	var body = cView.gNodes["main"].cloneAll();
	cView.Utils.setChild(body.cNodes["container"], "controls",(
		Object.keys(cView.contexts).some(function(domain){return cView.contexts[domain].token})?
		cView.gNodes["controls-login"].cloneAll()
		:cView.gNodes["controls-anon"].cloneAll()
	));
	cView.doc.getElementsByTagName("body")[0].appendChild(body);
	/*
	var nodeDebug =  document.createElement("div");
	nodeDebug.id = "debug";
	nodeDebug.className = "debug";
	body.appendChild(nodeDebug);
	nodeDebug.innerHTML = [document.location
		,"--------"
		,locationPath
		,gConfig.front.length].join("
");
	*/
	var contexts = new Object();
	Object.keys(cView.contexts).forEach(function(domain){contexts[domain] = cView.contexts[domain];});
	cView.Router.route(contexts, locationPath).then(postInit,function(err){
		console.log(err);
		if (Array.isArray(err))
			err = err.filter(function(item){return typeof item !== "undefined"})[0];

		if( typeof err === "string") switch(err){
			case "token":
				cView.Common.auth();
			break;
		}else {
			var nodeMsg = cView.gNodes["global-failure"].cloneAll();
			body.getNode(["c","container"],["c","details"]).appendChild(nodeMsg);
			try{
				nodeMsg.cNodes["title"].innerHTML = "Error " + err.code;
				nodeMsg.cNodes["info"].innerHTML = cView.Utils.err2html(err.data);
			}catch(e){ };
		}
		postInit();
	});

	return ;
}

window.initDoc = function(){
	Init.init(document);
	//document.cView.Utils._Promise = Promise;
	browserDoc();
}

function postInit(){
	var cView = document.cView;
	(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,cView.doc,"script","//www.google-analytics.com/analytics.js","ga");
	ga("create", gConfig.ga, "auto");
	ga("send", "pageview");

	//if(parseInt(cView.localStorage.getItem("rt")) ) cView.initRt();
	if(JSON.parse(cView.localStorage.getItem("show_link_preview"))){
		(function(a,b,c){
			var d,e,f;
			f="PIN_"+~~((new Date).getTime()/864e5),
			a[f]||(a[f]=!0,a.setTimeout(function(){
				d=b.getElementsByTagName("SCRIPT")[0],
				e=b.createElement("SCRIPT"),
				e.type="text/javascript",
				e.async=!0,
				e.src=c+"?"+f,
				d.parentNode.insertBefore(e,d)
			}
			,10))
		})(window,cView.doc,"//assets.pinterest.com/js/pinit_main.js");
	}
	var nodesAttImg = document.getElementsByClassName("atts-img");
	for (var idx = 0; idx < nodesAttImg.length; idx++){
		var nodeImgAtt = nodesAttImg[idx];
		if(cView.Utils.chkOverflow(nodeImgAtt))
			nodeImgAtt.parentNode.cNodes["atts-unfold"].hidden = false;
	}
	cView.Drawer.applyReadMore( cView.doc);

	var nodeSplash = document.getElementById("splash");
	nodeSplash.parentNode.removeChild(nodeSplash);
	cView.Common.setIcon("favicon.ico");
	Addons.commit(cView).then(function(){
		var lists = cView.blockLists;
		Object.keys(cView.contexts).forEach(function (domain){
			var context = cView.contexts[domain];
			Object.keys(lists).forEach(function(type){
				var list = cView.blocks[lists[type]][domain];
				if(typeof list !== "undefined") Object.keys(list).forEach(function(id){
					if(list[id] !== true) return;
					var user = context.gUsers[id];
					if(typeof user === "undefined") return;
					list[id] = user.username;
				});

			});
		});
		cView.Common.updateBlockList();
	});
}
window.srvDoc = function(){
	var cView = document.cView;
	var idx = 0;
	var aidx = 0;
	setLocalSettings();
	if(typeof cView.gContent !== "undefined")
		cView.Drawer.loadGlobals(cView.gContent);
	regenCNodes(document.getElementsByTagName("body")[0]);

	switch(cView.timeline){
	case "settings":
		return cView.Drawer.drawSettings();
	case "requests":
		return cView.Drawer.drawRequests();
	default:

	}

	document.posts = document.getElementById("posts");
	document.hiddenCount = 0;
	document.hiddenPosts = new Array();
	if(Array.isArray(cView.gContent.posts))
		cView.gContent.posts.forEach(function(post){
			document.hiddenPosts.push({"data":post, "is": post.isHidden});
			if(!post.isHidden) document.getElementById(post.id).rawData = post;
			else document.hiddenCount++;
		});
	else if(typeof cView.gContent.posts !== "undefined")
		document.getElementById(cView.gContent.posts.id).rawData = cView.gContent.posts;
	setAttr(document.getElementsByClassName("avatar-h"),"userid");
	setAttr(document.getElementsByTagName("a"),"action");
	Object.keys(gEvents).forEach(function(id){
		var node = document.getElementById(id);
		var eh = gEvents[id];
		Object.keys(eh).forEach(function(evt){
			eh[evt].forEach(function(a){
				node.addEventListener(evt, cView[a[0]][a[1]])
			});
		});
	});
	if(cView.gContent.comments)cView.gContent.comments.forEach(function(cmt){
		var nodeComment = document.getElementById(cmt.id);
		if(nodeComment ){
			nodeComment.createdAt = cmt.createdAt;
			nodeComment.userid = cmt.createdBy;
		}
	});
	var nodesDate = document.getElementsByClassName("post-date");
	for(idx = 0; idx < nodesDate.length; idx++){
		var victim = nodesDate[idx]; do victim = victim.parentNode; while(victim.className != "post");
		var aNode = nodesDate[idx].getElementsByTagName("a")[0];
		aNode.date = JSON.parse(victim.rawData.createdAt);
		window.setTimeout(cView.Drawer.updateDate, 100, aNode, cView);

	}
	var arrUsernames = new Array();
	var nodesUsernames = document.getElementsByClassName("username");
	for(idx = 0; idx < nodesUsernames.length; idx++)
		arrUsernames.push(nodesUsernames[idx]);
	arrUsernames.forEach(function(node){
		if(typeof cView.gUsers.byName[node.innerHTML] !== "undefined")
			node.parentNode.outerHTML = cView.gUsers.byName[node.innerHTML].link;

	});
	var urlMatch;
	if(JSON.parse(cView.localStorage.getItem("show_link_preview"))){
		var nodesPost = document.getElementsByClassName("post");
		for(idx = 0; idx < nodesPost.length; idx ++){
			if(((urlMatch = nodesPost[idx].rawData.body.match(/https?:\/\/[^\s\/$.?#].[^\s]*/i) )!= null)
			&& (!nodesPost[idx].rawData.attachments))
			(function(url, nodePost){
				cView.gEmbed.p.then(function(oEmbedPr){
					cView.Drawer.embedPreview(oEmbedPr
						,url[0]
						,nodePost.cNodes["post-body"].cNodes["attachments"]
					);
				});
			})(urlMatch, nodesPost[idx]);
		}
	}
	["blockPosts", "blockComments"].forEach(function(list){
		if(Array.isArray(cView[list]))
			cView[list].forEach(function(user){ cView.Drawer[list](user,true); });
	});
	var nodeAddSender = document.getElementsByClassName("add-sender")[0];
	if(nodeAddSender != null) nodeAddSender.ids = [cView.mainId];
	var nodeNewPostTo =  document.getElementsByClassName("new-post-to")[0];
	if(nodeNewPostTo != null) nodeNewPostTo.userid = cView.mainId;

	cView.Utils.postInit();
}
function regenCNodes(node){
	var cView = document.cView;
	node.cNodes = new Object();
	node.getNode = function(){
		var args = cView.Utils.args2Arr.apply(this,arguments);
		args.unshift(node);
		return cView.Utils.getNode.apply(node, args);
	};
	for(var idx = 0; idx < node.childNodes.length; idx++){
		regenCNodes(node.childNodes[idx]);
		var cName = node.childNodes[idx].className;
		if(cName != "")node.cNodes[cName] = node.childNodes[idx];
	}
}
function setAttr(nodes, name){
	for(var idx = 0; idx < nodes.length; idx++){
		var aidx = 0;
		do{
			if (nodes[idx].attributes[aidx].name == name){
				nodes[idx][name] = nodes[idx].attributes[aidx].value;
				if (nodes[idx][name] == "true") nodes[idx][name] = true;
				if (nodes[idx][name] == "false") nodes[idx][name] = false;
				break;
			}
		}while(++aidx< nodes[idx].attributes.length);

	}
}
function setLocalSettings(){
	var cView = document.cView;
	cView.mode = cView.localStorage.getItem("display_name");
	cView.readMore = JSON.parse(cView.localStorage.getItem("read_more"));
	//default
	if (cView.localStorage.getItem("read_more_height") == null) cView.localStorage.setItem("read_more_height", 10);
	cView.readMoreHeight = cView.readMore? JSON.parse(cView.localStorage.getItem("read_more_height")):0;

	var cssTheme = cView.localStorage.getItem("display_theme");
	if (cssTheme == "main.css") {
		cssTheme = "expanded.css";
		cView.localStorage.setItem("display_theme", cssTheme)
	}
	var sheet;
	var idx;
	for ( idx = 0 ; idx< document.styleSheets.length; idx ++)
		if( document.styleSheets[idx].title == "local")
			sheet = document.styleSheets[idx];
	if (JSON.parse(cView.localStorage.getItem("show_newlines")))
		sheet.insertRule(".long-text{white-space:pre-wrap;}",0);
	else
		sheet.insertRule(".long-text{white-space:normal;}",0);

	if(cssTheme)
		document.getElementById("main-stylesheet").href = gConfig.static
		+ cssTheme
		+ "?build="
		+ encodeURIComponent(___BUILD___);
	if(JSON.parse(cView.localStorage.getItem("show_link_preview"))){
		var nodeEmScript =  document.createElement("script");
		(function(w, d){
			var id='embedly-platform', n = 'script';
			if (!d.getElementById(id)){
				w.embedly = w.embedly || function() {(w.embedly.q = w.embedly.q || []).push(arguments);};
				var e = d.createElement(n); e.id = id; e.async=1;
				e.src = ('https:' === document.location.protocol ? 'https' : 'http') + '://cdn.embedly.com/widgets/platform.js';
				var s = d.getElementsByTagName(n)[0];
				s.parentNode.insertBefore(e, s);
			}
		})(window, document);
		embedly("defaults", {
			cards: {
				height: 200
				//width: 700
				//align: 'right',
				//chrome: 0
			}
		});
		embedly('on', 'card.rendered', function(iframe){
			cView.Utils.unscroll(iframe);
		});

		cView.gEmbed.p = new Promise(function(resolve,reject){
			var oReq = new XMLHttpRequest();
			oReq.onload = function(){
				if(oReq.status < 400)
					resolve(JSON.parse(oReq.response));
				else reject(oReq.response);
			}

			oReq.open("get",gConfig.static + "providers.json",true);
			oReq.send();

		});
	}

}
<commit_msg>Correct undefined settings<commit_after>"use strict";
var gPrivTimeline = {"done":0,"postsById":{},"oraphed":{count:0},"noKey":{},"noDecipher":{},nCmts:0,"posts":[] };
var matrix  = new Object();
var Init = require("./init.js")
var Addons = require("./addons.js");
window.browserDoc = function(){
	var cView = document.cView;
	var Utils = cView.Utils;
	var locationPath = /(https?:\/\/[^\?]*)/.exec(document.location)[1].slice(gConfig.front.length);
	if (locationPath == "")locationPath = "home";
	cView.fullPath = locationPath;
	var arrLocationPath = locationPath.split("/");
	var settingsNames = require("json!./settings.json");
	settingsNames.forEach(function(name){
		var setting =  cView.localStorage.getItem(name);
		if (setting == "undefined")cView.localStorage.setItem(name, "false");
	});
	if(arrLocationPath[0].toLowerCase() != "settings"){
		cView.search = document.location.search.slice(1);
		var matchOffset = cView.search.match(/offset=(\d+)/);
		if(matchOffset) cView.skip = matchOffset[1];
		cView.search = cView.search.replace(/offset=\d+&?/,"").replace(/limit=\d+&?/,"")
	}else if(locationPath.indexOf("settings/raw") != -1){
		var nodeSplash = document.getElementById("splash");
		cView.Drawer.drawRaw(nodeSplash);
	}

	if(JSON.parse(cView.localStorage.getItem("blocks")))
		cView.blocks = JSON.parse(cView.localStorage.getItem("blocks"));
	if(typeof cView.blocks.blockStrings === "undefined")
		cView.blocks.blockStrings = new Object();
	var nameMode = cView.localStorage.getItem("screenname");
	if(nameMode){
		cView.localStorage.setItem("display_name", nameMode);
		cView.localStorage.removeItem("screenname");
	}
	setLocalSettings();
	cView.Common.loadLogins();
	var body = cView.gNodes["main"].cloneAll();
	cView.Utils.setChild(body.cNodes["container"], "controls",(
		Object.keys(cView.contexts).some(function(domain){return cView.contexts[domain].token})?
		cView.gNodes["controls-login"].cloneAll()
		:cView.gNodes["controls-anon"].cloneAll()
	));
	cView.doc.getElementsByTagName("body")[0].appendChild(body);
	/*
	var nodeDebug =  document.createElement("div");
	nodeDebug.id = "debug";
	nodeDebug.className = "debug";
	body.appendChild(nodeDebug);
	nodeDebug.innerHTML = [document.location
		,"--------"
		,locationPath
		,gConfig.front.length].join("
");
	*/
	var contexts = new Object();
	Object.keys(cView.contexts).forEach(function(domain){contexts[domain] = cView.contexts[domain];});
	cView.Router.route(contexts, locationPath).then(postInit,function(err){
		console.log(err);
		if (Array.isArray(err))
			err = err.filter(function(item){return typeof item !== "undefined"})[0];

		if( typeof err === "string") switch(err){
			case "token":
				cView.Common.auth();
			break;
		}else {
			var nodeMsg = cView.gNodes["global-failure"].cloneAll();
			body.getNode(["c","container"],["c","details"]).appendChild(nodeMsg);
			try{
				nodeMsg.cNodes["title"].innerHTML = "Error " + err.code;
				nodeMsg.cNodes["info"].innerHTML = cView.Utils.err2html(err.data);
			}catch(e){ };
		}
		postInit();
	});

	return ;
}

window.initDoc = function(){
	Init.init(document);
	//document.cView.Utils._Promise = Promise;
	browserDoc();
}

function postInit(){
	var cView = document.cView;
	(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,cView.doc,"script","//www.google-analytics.com/analytics.js","ga");
	ga("create", gConfig.ga, "auto");
	ga("send", "pageview");

	//if(parseInt(cView.localStorage.getItem("rt")) ) cView.initRt();
	if(JSON.parse(cView.localStorage.getItem("show_link_preview"))){
		(function(a,b,c){
			var d,e,f;
			f="PIN_"+~~((new Date).getTime()/864e5),
			a[f]||(a[f]=!0,a.setTimeout(function(){
				d=b.getElementsByTagName("SCRIPT")[0],
				e=b.createElement("SCRIPT"),
				e.type="text/javascript",
				e.async=!0,
				e.src=c+"?"+f,
				d.parentNode.insertBefore(e,d)
			}
			,10))
		})(window,cView.doc,"//assets.pinterest.com/js/pinit_main.js");
	}
	var nodesAttImg = document.getElementsByClassName("atts-img");
	for (var idx = 0; idx < nodesAttImg.length; idx++){
		var nodeImgAtt = nodesAttImg[idx];
		if(cView.Utils.chkOverflow(nodeImgAtt))
			nodeImgAtt.parentNode.cNodes["atts-unfold"].hidden = false;
	}
	cView.Drawer.applyReadMore( cView.doc);

	var nodeSplash = document.getElementById("splash");
	nodeSplash.parentNode.removeChild(nodeSplash);
	cView.Common.setIcon("favicon.ico");
	Addons.commit(cView).then(function(){
		var lists = cView.blockLists;
		Object.keys(cView.contexts).forEach(function (domain){
			var context = cView.contexts[domain];
			Object.keys(lists).forEach(function(type){
				var list = cView.blocks[lists[type]][domain];
				if(typeof list !== "undefined") Object.keys(list).forEach(function(id){
					if(list[id] !== true) return;
					var user = context.gUsers[id];
					if(typeof user === "undefined") return;
					list[id] = user.username;
				});

			});
		});
		cView.Common.updateBlockList();
	});
}
window.srvDoc = function(){
	var cView = document.cView;
	var idx = 0;
	var aidx = 0;
	setLocalSettings();
	if(typeof cView.gContent !== "undefined")
		cView.Drawer.loadGlobals(cView.gContent);
	regenCNodes(document.getElementsByTagName("body")[0]);

	switch(cView.timeline){
	case "settings":
		return cView.Drawer.drawSettings();
	case "requests":
		return cView.Drawer.drawRequests();
	default:

	}

	document.posts = document.getElementById("posts");
	document.hiddenCount = 0;
	document.hiddenPosts = new Array();
	if(Array.isArray(cView.gContent.posts))
		cView.gContent.posts.forEach(function(post){
			document.hiddenPosts.push({"data":post, "is": post.isHidden});
			if(!post.isHidden) document.getElementById(post.id).rawData = post;
			else document.hiddenCount++;
		});
	else if(typeof cView.gContent.posts !== "undefined")
		document.getElementById(cView.gContent.posts.id).rawData = cView.gContent.posts;
	setAttr(document.getElementsByClassName("avatar-h"),"userid");
	setAttr(document.getElementsByTagName("a"),"action");
	Object.keys(gEvents).forEach(function(id){
		var node = document.getElementById(id);
		var eh = gEvents[id];
		Object.keys(eh).forEach(function(evt){
			eh[evt].forEach(function(a){
				node.addEventListener(evt, cView[a[0]][a[1]])
			});
		});
	});
	if(cView.gContent.comments)cView.gContent.comments.forEach(function(cmt){
		var nodeComment = document.getElementById(cmt.id);
		if(nodeComment ){
			nodeComment.createdAt = cmt.createdAt;
			nodeComment.userid = cmt.createdBy;
		}
	});
	var nodesDate = document.getElementsByClassName("post-date");
	for(idx = 0; idx < nodesDate.length; idx++){
		var victim = nodesDate[idx]; do victim = victim.parentNode; while(victim.className != "post");
		var aNode = nodesDate[idx].getElementsByTagName("a")[0];
		aNode.date = JSON.parse(victim.rawData.createdAt);
		window.setTimeout(cView.Drawer.updateDate, 100, aNode, cView);

	}
	var arrUsernames = new Array();
	var nodesUsernames = document.getElementsByClassName("username");
	for(idx = 0; idx < nodesUsernames.length; idx++)
		arrUsernames.push(nodesUsernames[idx]);
	arrUsernames.forEach(function(node){
		if(typeof cView.gUsers.byName[node.innerHTML] !== "undefined")
			node.parentNode.outerHTML = cView.gUsers.byName[node.innerHTML].link;

	});
	var urlMatch;
	if(JSON.parse(cView.localStorage.getItem("show_link_preview"))){
		var nodesPost = document.getElementsByClassName("post");
		for(idx = 0; idx < nodesPost.length; idx ++){
			if(((urlMatch = nodesPost[idx].rawData.body.match(/https?:\/\/[^\s\/$.?#].[^\s]*/i) )!= null)
			&& (!nodesPost[idx].rawData.attachments))
			(function(url, nodePost){
				cView.gEmbed.p.then(function(oEmbedPr){
					cView.Drawer.embedPreview(oEmbedPr
						,url[0]
						,nodePost.cNodes["post-body"].cNodes["attachments"]
					);
				});
			})(urlMatch, nodesPost[idx]);
		}
	}
	["blockPosts", "blockComments"].forEach(function(list){
		if(Array.isArray(cView[list]))
			cView[list].forEach(function(user){ cView.Drawer[list](user,true); });
	});
	var nodeAddSender = document.getElementsByClassName("add-sender")[0];
	if(nodeAddSender != null) nodeAddSender.ids = [cView.mainId];
	var nodeNewPostTo =  document.getElementsByClassName("new-post-to")[0];
	if(nodeNewPostTo != null) nodeNewPostTo.userid = cView.mainId;

	cView.Utils.postInit();
}
function regenCNodes(node){
	var cView = document.cView;
	node.cNodes = new Object();
	node.getNode = function(){
		var args = cView.Utils.args2Arr.apply(this,arguments);
		args.unshift(node);
		return cView.Utils.getNode.apply(node, args);
	};
	for(var idx = 0; idx < node.childNodes.length; idx++){
		regenCNodes(node.childNodes[idx]);
		var cName = node.childNodes[idx].className;
		if(cName != "")node.cNodes[cName] = node.childNodes[idx];
	}
}
function setAttr(nodes, name){
	for(var idx = 0; idx < nodes.length; idx++){
		var aidx = 0;
		do{
			if (nodes[idx].attributes[aidx].name == name){
				nodes[idx][name] = nodes[idx].attributes[aidx].value;
				if (nodes[idx][name] == "true") nodes[idx][name] = true;
				if (nodes[idx][name] == "false") nodes[idx][name] = false;
				break;
			}
		}while(++aidx< nodes[idx].attributes.length);

	}
}
function setLocalSettings(){
	var cView = document.cView;
	cView.mode = cView.localStorage.getItem("display_name");
	cView.readMore = JSON.parse(cView.localStorage.getItem("read_more"));
	//default
	if (cView.localStorage.getItem("read_more_height") == null) cView.localStorage.setItem("read_more_height", 10);
	cView.readMoreHeight = cView.readMore? JSON.parse(cView.localStorage.getItem("read_more_height")):0;

	var cssTheme = cView.localStorage.getItem("display_theme");
	if (cssTheme == "main.css") {
		cssTheme = "expanded.css";
		cView.localStorage.setItem("display_theme", cssTheme)
	}
	var sheet;
	var idx;
	for ( idx = 0 ; idx< document.styleSheets.length; idx ++)
		if( document.styleSheets[idx].title == "local")
			sheet = document.styleSheets[idx];
	if (JSON.parse(cView.localStorage.getItem("show_newlines")))
		sheet.insertRule(".long-text{white-space:pre-wrap;}",0);
	else
		sheet.insertRule(".long-text{white-space:normal;}",0);

	if(cssTheme)
		document.getElementById("main-stylesheet").href = gConfig.static
		+ cssTheme
		+ "?build="
		+ encodeURIComponent(___BUILD___);
	if(JSON.parse(cView.localStorage.getItem("show_link_preview"))){
		var nodeEmScript =  document.createElement("script");
		(function(w, d){
			var id='embedly-platform', n = 'script';
			if (!d.getElementById(id)){
				w.embedly = w.embedly || function() {(w.embedly.q = w.embedly.q || []).push(arguments);};
				var e = d.createElement(n); e.id = id; e.async=1;
				e.src = ('https:' === document.location.protocol ? 'https' : 'http') + '://cdn.embedly.com/widgets/platform.js';
				var s = d.getElementsByTagName(n)[0];
				s.parentNode.insertBefore(e, s);
			}
		})(window, document);
		embedly("defaults", {
			cards: {
				height: 200
				//width: 700
				//align: 'right',
				//chrome: 0
			}
		});
		embedly('on', 'card.rendered', function(iframe){
			cView.Utils.unscroll(iframe);
		});

		cView.gEmbed.p = new Promise(function(resolve,reject){
			var oReq = new XMLHttpRequest();
			oReq.onload = function(){
				if(oReq.status < 400)
					resolve(JSON.parse(oReq.response));
				else reject(oReq.response);
			}

			oReq.open("get",gConfig.static + "providers.json",true);
			oReq.send();

		});
	}

}
<|endoftext|>


<commit_before>// Config
export const FETCH_CONFIG_REQUEST = 'FETCH_CONFIG_REQUEST';
export const FETCH_CONFIG_SUCCESS = 'FETCH_CONFIG_SUCCESS';
export const FETCH_CONFIG_FAILURE = 'FETCH_CONFIG_FAILURE';

export const PUT_CONFIG_REQUEST = 'PUT_CONFIG_REQUEST';
export const PUT_CONFIG_SUCCESS = 'PUT_CONFIG_SUCCESS';
export const PUT_CONFIG_FAILURE = 'PUT_CONFIG_FAILURE';

export const CONFIG_EDITOR_CHANGED = 'CONFIG_EDITOR_CHANGED';

// Pages
export const FETCH_PAGES_REQUEST = 'FETCH_PAGES_REQUEST';
export const FETCH_PAGES_SUCCESS = 'FETCH_PAGES_SUCCESS';
export const FETCH_PAGES_FAILURE = 'FETCH_PAGES_FAILURE';

export const FETCH_PAGE_REQUEST = 'FETCH_PAGE_REQUEST';
export const FETCH_PAGE_SUCCESS = 'FETCH_PAGE_SUCCESS';
export const FETCH_PAGE_FAILURE = 'FETCH_PAGE_FAILURE';

export const PUT_PAGE_REQUEST = 'PUT_PAGE_REQUEST';
export const PUT_PAGE_SUCCESS = 'PUT_PAGE_SUCCESS';
export const PUT_PAGE_FAILURE = 'PUT_PAGE_FAILURE';

export const DELETE_PAGE_REQUEST = 'DELETE_PAGE_REQUEST';
export const DELETE_PAGE_SUCCESS = 'DELETE_PAGE_SUCCESS';
export const DELETE_PAGE_FAILURE = 'DELETE_PAGE_FAILURE';

// COLLECTIONS
export const FETCH_COLLECTIONS_REQUEST = 'FETCH_COLLECTIONS_REQUEST';
export const FETCH_COLLECTIONS_SUCCESS = 'FETCH_COLLECTIONS_SUCCESS';
export const FETCH_COLLECTIONS_FAILURE = 'FETCH_COLLECTIONS_FAILURE';

export const FETCH_COLLECTION_REQUEST = 'FETCH_COLLECTION_REQUEST';
export const FETCH_COLLECTION_SUCCESS = 'FETCH_COLLECTION_SUCCESS';
export const FETCH_COLLECTION_FAILURE = 'FETCH_COLLECTION_FAILURE';

export const FETCH_DOCUMENTS_REQUEST = 'FETCH_DOCUMENTS_REQUEST';
export const FETCH_DOCUMENTS_SUCCESS = 'FETCH_DOCUMENTS_SUCCESS';
export const FETCH_DOCUMENTS_FAILURE = 'FETCH_DOCUMENTS_FAILURE';

export const FETCH_DOCUMENT_REQUEST = 'FETCH_DOCUMENT_REQUEST';
export const FETCH_DOCUMENT_SUCCESS = 'FETCH_DOCUMENT_SUCCESS';
export const FETCH_DOCUMENT_FAILURE = 'FETCH_DOCUMENT_FAILURE';

export const PUT_DOCUMENT_REQUEST = 'PUT_DOCUMENT_REQUEST';
export const PUT_DOCUMENT_SUCCESS = 'PUT_DOCUMENT_SUCCESS';
export const PUT_DOCUMENT_FAILURE = 'PUT_DOCUMENT_FAILURE';

export const DELETE_DOCUMENT_REQUEST = 'DELETE_DOCUMENT_REQUEST';
export const DELETE_DOCUMENT_SUCCESS = 'DELETE_DOCUMENT_SUCCESS';
export const DELETE_DOCUMENT_FAILURE = 'DELETE_DOCUMENT_FAILURE';

// Metadata
export const UPDATE_TITLE = 'UPDATE_TITLE';
export const UPDATE_BODY = 'UPDATE_BODY';
export const UPDATE_PATH = 'UPDATE_PATH';
export const UPDATE_DRAFT = 'UPDATE_DRAFT';
export const STORE_CONTENT_FIELDS = 'STORE_CONTENT_FIELDS';
export const ADD_METAFIELD = 'ADD_METAFIELD';
export const REMOVE_METAFIELD = 'REMOVE_METAFIELD';
export const UPDATE_FIELD_KEY = 'UPDATE_FIELD_KEY';
export const UPDATE_FIELD_VALUE = 'UPDATE_FIELD_VALUE';
export const MOVE_ARRAY_ITEM = 'MOVE_ARRAY_ITEM';
export const CONVERT_FIELD = 'CONVERT_FIELD';

// Datafiles
export const FETCH_DATAFILES_REQUEST = 'FETCH_DATAFILES_REQUEST';
export const FETCH_DATAFILES_SUCCESS = 'FETCH_DATAFILES_SUCCESS';
export const FETCH_DATAFILES_FAILURE = 'FETCH_DATAFILES_FAILURE';

export const FETCH_DATAFILE_REQUEST = 'FETCH_DATAFILE_REQUEST';
export const FETCH_DATAFILE_SUCCESS = 'FETCH_DATAFILE_SUCCESS';
export const FETCH_DATAFILE_FAILURE = 'FETCH_DATAFILE_FAILURE';

export const PUT_DATAFILE_REQUEST = 'PUT_DATAFILE_REQUEST';
export const PUT_DATAFILE_SUCCESS = 'PUT_DATAFILE_SUCCESS';
export const PUT_DATAFILE_FAILURE = 'PUT_DATAFILE_FAILURE';

export const DELETE_DATAFILE_REQUEST = 'DELETE_DATAFILE_REQUEST';
export const DELETE_DATAFILE_SUCCESS = 'DELETE_DATAFILE_SUCCESS';
export const DELETE_DATAFILE_FAILURE = 'DELETE_DATAFILE_FAILURE';

export const DATAFILE_CHANGED = 'DATAFILE_CHANGED';

// Static Files

export const FETCH_STATICFILES_REQUEST = 'FETCH_STATICFILES_REQUEST';
export const FETCH_STATICFILES_SUCCESS = 'FETCH_STATICFILES_SUCCESS';
export const FETCH_STATICFILES_FAILURE = 'FETCH_STATICFILES_FAILURE';

export const FETCH_STATICFILE_REQUEST = 'FETCH_STATICFILE_REQUEST';
export const FETCH_STATICFILE_SUCCESS = 'FETCH_STATICFILE_SUCCESS';
export const FETCH_STATICFILE_FAILURE = 'FETCH_STATICFILE_FAILURE';

export const PUT_STATICFILE_REQUEST = 'PUT_STATICFILE_REQUEST';
export const PUT_STATICFILE_SUCCESS = 'PUT_STATICFILE_SUCCESS';
export const PUT_STATICFILE_FAILURE = 'PUT_STATICFILE_FAILURE';

export const DELETE_STATICFILE_REQUEST = 'DELETE_STATICFILE_REQUEST';
export const DELETE_STATICFILE_SUCCESS = 'DELETE_STATICFILE_SUCCESS';
export const DELETE_STATICFILE_FAILURE = 'DELETE_STATICFILE_FAILURE';

export const STATICFILES_UPLOADED = 'STATICFILES_UPLOADED';

// Utility
export const SEARCH_CONTENT = 'SEARCH_CONTENT';
export const CLEAR_ERRORS = 'CLEAR_ERRORS';
export const VALIDATION_ERROR = 'VALIDATION_ERROR';
<commit_msg>remove unused action type<commit_after>// Config
export const FETCH_CONFIG_REQUEST = 'FETCH_CONFIG_REQUEST';
export const FETCH_CONFIG_SUCCESS = 'FETCH_CONFIG_SUCCESS';
export const FETCH_CONFIG_FAILURE = 'FETCH_CONFIG_FAILURE';

export const PUT_CONFIG_REQUEST = 'PUT_CONFIG_REQUEST';
export const PUT_CONFIG_SUCCESS = 'PUT_CONFIG_SUCCESS';
export const PUT_CONFIG_FAILURE = 'PUT_CONFIG_FAILURE';

export const CONFIG_EDITOR_CHANGED = 'CONFIG_EDITOR_CHANGED';

// Pages
export const FETCH_PAGES_REQUEST = 'FETCH_PAGES_REQUEST';
export const FETCH_PAGES_SUCCESS = 'FETCH_PAGES_SUCCESS';
export const FETCH_PAGES_FAILURE = 'FETCH_PAGES_FAILURE';

export const FETCH_PAGE_REQUEST = 'FETCH_PAGE_REQUEST';
export const FETCH_PAGE_SUCCESS = 'FETCH_PAGE_SUCCESS';
export const FETCH_PAGE_FAILURE = 'FETCH_PAGE_FAILURE';

export const PUT_PAGE_REQUEST = 'PUT_PAGE_REQUEST';
export const PUT_PAGE_SUCCESS = 'PUT_PAGE_SUCCESS';
export const PUT_PAGE_FAILURE = 'PUT_PAGE_FAILURE';

export const DELETE_PAGE_REQUEST = 'DELETE_PAGE_REQUEST';
export const DELETE_PAGE_SUCCESS = 'DELETE_PAGE_SUCCESS';
export const DELETE_PAGE_FAILURE = 'DELETE_PAGE_FAILURE';

// COLLECTIONS
export const FETCH_COLLECTIONS_REQUEST = 'FETCH_COLLECTIONS_REQUEST';
export const FETCH_COLLECTIONS_SUCCESS = 'FETCH_COLLECTIONS_SUCCESS';
export const FETCH_COLLECTIONS_FAILURE = 'FETCH_COLLECTIONS_FAILURE';

export const FETCH_COLLECTION_REQUEST = 'FETCH_COLLECTION_REQUEST';
export const FETCH_COLLECTION_SUCCESS = 'FETCH_COLLECTION_SUCCESS';
export const FETCH_COLLECTION_FAILURE = 'FETCH_COLLECTION_FAILURE';

export const FETCH_DOCUMENTS_REQUEST = 'FETCH_DOCUMENTS_REQUEST';
export const FETCH_DOCUMENTS_SUCCESS = 'FETCH_DOCUMENTS_SUCCESS';
export const FETCH_DOCUMENTS_FAILURE = 'FETCH_DOCUMENTS_FAILURE';

export const FETCH_DOCUMENT_REQUEST = 'FETCH_DOCUMENT_REQUEST';
export const FETCH_DOCUMENT_SUCCESS = 'FETCH_DOCUMENT_SUCCESS';
export const FETCH_DOCUMENT_FAILURE = 'FETCH_DOCUMENT_FAILURE';

export const PUT_DOCUMENT_REQUEST = 'PUT_DOCUMENT_REQUEST';
export const PUT_DOCUMENT_SUCCESS = 'PUT_DOCUMENT_SUCCESS';
export const PUT_DOCUMENT_FAILURE = 'PUT_DOCUMENT_FAILURE';

export const DELETE_DOCUMENT_REQUEST = 'DELETE_DOCUMENT_REQUEST';
export const DELETE_DOCUMENT_SUCCESS = 'DELETE_DOCUMENT_SUCCESS';
export const DELETE_DOCUMENT_FAILURE = 'DELETE_DOCUMENT_FAILURE';

// Metadata
export const UPDATE_TITLE = 'UPDATE_TITLE';
export const UPDATE_BODY = 'UPDATE_BODY';
export const UPDATE_PATH = 'UPDATE_PATH';
export const UPDATE_DRAFT = 'UPDATE_DRAFT';
export const STORE_CONTENT_FIELDS = 'STORE_CONTENT_FIELDS';
export const ADD_METAFIELD = 'ADD_METAFIELD';
export const REMOVE_METAFIELD = 'REMOVE_METAFIELD';
export const UPDATE_FIELD_KEY = 'UPDATE_FIELD_KEY';
export const UPDATE_FIELD_VALUE = 'UPDATE_FIELD_VALUE';
export const MOVE_ARRAY_ITEM = 'MOVE_ARRAY_ITEM';
export const CONVERT_FIELD = 'CONVERT_FIELD';

// Datafiles
export const FETCH_DATAFILES_REQUEST = 'FETCH_DATAFILES_REQUEST';
export const FETCH_DATAFILES_SUCCESS = 'FETCH_DATAFILES_SUCCESS';
export const FETCH_DATAFILES_FAILURE = 'FETCH_DATAFILES_FAILURE';

export const FETCH_DATAFILE_REQUEST = 'FETCH_DATAFILE_REQUEST';
export const FETCH_DATAFILE_SUCCESS = 'FETCH_DATAFILE_SUCCESS';
export const FETCH_DATAFILE_FAILURE = 'FETCH_DATAFILE_FAILURE';

export const PUT_DATAFILE_REQUEST = 'PUT_DATAFILE_REQUEST';
export const PUT_DATAFILE_SUCCESS = 'PUT_DATAFILE_SUCCESS';
export const PUT_DATAFILE_FAILURE = 'PUT_DATAFILE_FAILURE';

export const DELETE_DATAFILE_REQUEST = 'DELETE_DATAFILE_REQUEST';
export const DELETE_DATAFILE_SUCCESS = 'DELETE_DATAFILE_SUCCESS';
export const DELETE_DATAFILE_FAILURE = 'DELETE_DATAFILE_FAILURE';

export const DATAFILE_CHANGED = 'DATAFILE_CHANGED';

// Static Files

export const FETCH_STATICFILES_REQUEST = 'FETCH_STATICFILES_REQUEST';
export const FETCH_STATICFILES_SUCCESS = 'FETCH_STATICFILES_SUCCESS';
export const FETCH_STATICFILES_FAILURE = 'FETCH_STATICFILES_FAILURE';

export const FETCH_STATICFILE_REQUEST = 'FETCH_STATICFILE_REQUEST';
export const FETCH_STATICFILE_SUCCESS = 'FETCH_STATICFILE_SUCCESS';
export const FETCH_STATICFILE_FAILURE = 'FETCH_STATICFILE_FAILURE';

export const PUT_STATICFILE_REQUEST = 'PUT_STATICFILE_REQUEST';
export const PUT_STATICFILE_SUCCESS = 'PUT_STATICFILE_SUCCESS';
export const PUT_STATICFILE_FAILURE = 'PUT_STATICFILE_FAILURE';

export const DELETE_STATICFILE_REQUEST = 'DELETE_STATICFILE_REQUEST';
export const DELETE_STATICFILE_SUCCESS = 'DELETE_STATICFILE_SUCCESS';
export const DELETE_STATICFILE_FAILURE = 'DELETE_STATICFILE_FAILURE';

// Utility
export const SEARCH_CONTENT = 'SEARCH_CONTENT';
export const CLEAR_ERRORS = 'CLEAR_ERRORS';
export const VALIDATION_ERROR = 'VALIDATION_ERROR';
<|endoftext|>


<commit_before>//create player div on page
$('body').append("

");
$('#popdiv').load("/DesktopModules/AgapeConnect/Stories/controls/popup.html");

//set up video
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// creates an  (and YouTube player) after the API code downloads.
var player;
var currentvidslider;
var currentvidid;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('popplayer', {
        origin: 'https://www.agapefrance.org',
        height: '432',
        width: '768',
        playerVars: { 'rel': 0, 'color': 'white' }
    });
}

function popclosevideo() {
    $('#fr_video_popup').fadeOut();
    player.pauseVideo();
    setTimeout("$('#slider' + currentvidslider).data('nivoslider').start()",1000); //restart the slider after the video is closed
}

function popupvideo(videoid, sliderid) {
    currentvidslider = sliderid;
    if (currentvidid == videoid) { } else { player.loadVideoById(videoid); }
    currentvidid = videoid;
    $('#fr_video_popup').fadeIn();
    $('#fr_video_popup').css("display", "flex");
    $('#slider' + sliderid).data('nivoslider').stop(); //stop the slider while the video is open
}

$(document).keyup(function (e) {
    if (e.which == 27) {
        popclosevideo();
    }
});<commit_msg>do not autoplay videos<commit_after>//create player div on page
$('body').append("

");
$('#popdiv').load("/DesktopModules/AgapeConnect/Stories/controls/popup.html");

//set up video
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// creates an  (and YouTube player) after the API code downloads.
var player;
var currentvidslider;
var currentvidid;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('popplayer', {
        origin: 'https://www.agapefrance.org',
        height: '432',
        width: '768',
        playerVars: { 'rel': 0, 'color': 'white' }
    });
}

function popclosevideo() {
    $('#fr_video_popup').fadeOut();
    player.pauseVideo();
    setTimeout("$('#slider' + currentvidslider).data('nivoslider').start()",1000); //restart the slider after the video is closed
}

function popupvideo(videoid, sliderid) {
    currentvidslider = sliderid;
    if (currentvidid == videoid) { } else { player.cueVideoById(videoid); }
    currentvidid = videoid;
    $('#fr_video_popup').fadeIn();
    $('#fr_video_popup').css("display", "flex");
    $('#slider' + sliderid).data('nivoslider').stop(); //stop the slider while the video is open
}

$(document).keyup(function (e) {
    if (e.which == 27) {
        popclosevideo();
    }
});<|endoftext|>


<commit_before>/**
 * @file Member visibility definition
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfExtend*/ // gpf.extend
/*global _GpfClassDefMember*/ // GPF class member definition
/*exported _GPF_VISIBILITY*/ // Member visibility enum
/*exported _gpfVisibilityKeywords*/ // List of visibility keywords
/*exported _gpfVisibilityFromKeyword*/ // Convert visibility keyword into enum
/*#endif*/

var _gpfVisibilityKeywords = "public|protected|private|static".split("|"),

    /**
     * Enumeration of visibility values
     *
     * @enum {Number}
     */
    _GPF_VISIBILITY = {
        /** Not set or keyword not recognized */
        UNKNOWN   : -1,
        /** Public */
        PUBLIC    : 0,
        /** Protected */
        PROTECTED : 1,
        /** Private */
        PRIVATE   : 2,
        /** Static */
        STATIC    : 3
    };

/**
 * Convert visibility keyword into the corresponding enum value
 *
 * @param {String} keyword Keyword to convert
 * @returns {_GPF_VISIBILITY}
 */
function _gpfVisibilityFromKeyword (keyword) {
    return _gpfVisibilityKeywords.indexOf(keyword);
}

//region Extension of _GpfClassDefMember

_gpfExtend(_GpfClassDefMember.prototype, /** @lends _GpfClassDefMember.prototype */ {

    /**
     * Member visibility
     *
     * @type {_GPF_VISIBILITY}
     */
    _visibility: _GPF_VISIBILITY.PUBLIC,

    _setVisibility: function (visibility) {
        this._visibility = visibility;
    },

    /** @return {_GPF_VISIBILITY} Member visibility */
    getVisibility: function () {
        return this._visibility;
    }

});

//endregion Extension of _GpfClassDefMember

/*#ifndef(UMD)*/

gpf.internals._GPF_VISIBILITY = _GPF_VISIBILITY;
gpf.internals._gpfVisibilityFromKeyword = _gpfVisibilityFromKeyword;

/*#endif*/
<commit_msg>Dependencies update<commit_after>/**
 * @file Member visibility definition
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GpfClassDefMember*/ // GPF class member definition
/*global _gpfExtend*/ // gpf.extend
/*exported _GPF_VISIBILITY*/ // Member visibility enum
/*exported _gpfVisibilityFromKeyword*/ // Convert visibility keyword into enum
/*exported _gpfVisibilityKeywords*/ // List of visibility keywords
/*#endif*/

var _gpfVisibilityKeywords = "public|protected|private|static".split("|"),

    /**
     * Enumeration of visibility values
     *
     * @enum {Number}
     */
    _GPF_VISIBILITY = {
        /** Not set or keyword not recognized */
        UNKNOWN   : -1,
        /** Public */
        PUBLIC    : 0,
        /** Protected */
        PROTECTED : 1,
        /** Private */
        PRIVATE   : 2,
        /** Static */
        STATIC    : 3
    };

/**
 * Convert visibility keyword into the corresponding enum value
 *
 * @param {String} keyword Keyword to convert
 * @returns {_GPF_VISIBILITY}
 */
function _gpfVisibilityFromKeyword (keyword) {
    return _gpfVisibilityKeywords.indexOf(keyword);
}

//region Extension of _GpfClassDefMember

_gpfExtend(_GpfClassDefMember.prototype, /** @lends _GpfClassDefMember.prototype */ {

    /**
     * Member visibility
     *
     * @type {_GPF_VISIBILITY}
     */
    _visibility: _GPF_VISIBILITY.PUBLIC,

    _setVisibility: function (visibility) {
        this._visibility = visibility;
    },

    /** @return {_GPF_VISIBILITY} Member visibility */
    getVisibility: function () {
        return this._visibility;
    }

});

//endregion Extension of _GpfClassDefMember

/*#ifndef(UMD)*/

gpf.internals._GPF_VISIBILITY = _GPF_VISIBILITY;
gpf.internals._gpfVisibilityFromKeyword = _gpfVisibilityFromKeyword;

/*#endif*/
<|endoftext|>


<commit_before>let fs = require('fs')
let jsonParser = require('./jsonParser.js')
const db = './db.json'

exports.listData = function (dbInput) {
  dbInput = jsonParser.delSpace(dbInput.slice(7))
  let json = require(db)
  for (let ob in json) {
    console.log(ob, ':', json[ob])
  }
  return [Object.keys(json).length + ' Items', dbInput]
}

exports.insertData = function (dbInput) {
  dbInput = jsonParser.delSpace(dbInput.slice(6))
  let res = getKeyValue(dbInput)
  if (!fs.existsSync(db)) return firstInsert(res)
  else {
    let json = require(db)
    if (!keyExists(res[0], json)) {
      return (insertSimpleOrNestedKey(res)) ? ['Data inserted', res[2]] : ['Error', res[2]]
    } else return ['Key already exists', res[2]]
  }
}

function firstInsert (res) {
  let json = {}
  fs.open(db, 'w+', (err, fd) => {
    if (err) throw err
    else {
      json[res[0]] = res[1][0]
      writeData(json)
    }
  })
  return ['Data inserted', res[2]]
}

function insertSimpleOrNestedKey (res) {
  let json = require(db), flag, keyArr = res[0].split('.')
  flag = (keyArr.length === 1) ? simpleKeyInsert(json, res) : nestedKeyInsert(json, res, keyArr)
  return flag
}

function simpleKeyInsert (json, res) {
  json[res[0]] = res[1][0]
  writeData(json)
  return true
}

function nestedKeyInsert (obj, res, keyArr) {
  if (keyArr.length === 2) {
    let ob = obj[keyArr[0]]
    ob[keyArr[1]] = res[1][0]
    obj[keyArr[0]] = ob
    return true
  }
  if (keyExists(keyArr[0], obj) && keyArr.length > 2) {
    let flag = nestedKeyInsert(obj[keyArr[0]], res, keyArr.slice(1))
    writeData(obj)
    return flag
  }
}

exports.updateData = function (dbInput) {
  dbInput = jsonParser.delSpace(dbInput.slice(6))
  let res = getKeyValue(dbInput)
  return (updateSimpleOrNestedKey(res)) ? ['Value updated', res[2]] : ['No such key found', res[2]]
}

function updateSimpleOrNestedKey (res) {
  let json = require(db), flag, keyArr = res[0].split('.')
  flag = (!/./.test(res[0])) ? simpleKeyUpdate(json, res) : nestedKeyUpdate(json, res, keyArr)
  return flag
}

function simpleKeyUpdate (json, res) {
  if (!keyExists(res[0], json)) return false
  else {
    json[res[0]] = res[1][0]
    writeData(json)
    return true
  }
}

function nestedKeyUpdate (obj, res, keyArr) {
  if (keyExists(keyArr[0], obj)) {
    if (keyArr.length === 1) {
      obj[keyArr[0]] = res[1][0]
      return true
    } else if (keyArr.length > 1) {
      let flag = nestedKeyUpdate(obj[keyArr[0]], res, keyArr.slice(1))
      writeData(obj)
      return flag
    }
  } else return false
}

exports.deleteData = function (dbInput) {
  dbInput = jsonParser.delSpace(dbInput.slice(6))
  let res = getKeyValue(dbInput)
  return (deleteSimpleOrNestedKey(res)) ? ['Data deleted', res[2]] : ['No such key found', res[2]]
}

function deleteSimpleOrNestedKey (res) {
  let json = require(db), keyArr = res[0].split('.')
  let flag = (keyArr.length === 1) ? simpleKeyDelete(json, res) : nestedKeyDelete(json, res, keyArr)
  return flag
}

function simpleKeyDelete (json, res) {
  if (!keyExists(res[0], json)) return false
  else {
    delete json[res[0]]
    writeData(json)
    return true
  }
}

function nestedKeyDelete (obj, res, keyArr) {
  if (keyExists(keyArr[0], obj)) {
    if (keyArr.length === 1) {
      delete obj[keyArr[0]]
      return true
    } else if (keyArr.length > 1) {
      let flag = nestedKeyDelete(obj[keyArr[0]], res, keyArr.slice(1))
      writeData(obj)
      return flag
    }
  } else return false
}

exports.showValue = function (dbInput) {
  dbInput = jsonParser.delSpace(dbInput.slice(4))
  let res = getKeyValue(dbInput)
  return showSimpleOrNestedKey(res) ? ['Key exists', res[2]] : ['No such key found', res[2]]
}

function showSimpleOrNestedKey (res) {
  let json = require(db), keyArr = res[0].split('.')
  let flag = (keyArr.length === 1) ? simpleKeyShow(json, res) : nestedKeyShow(json, res, keyArr)
  return flag
}

function simpleKeyShow (json, res) {
  if (keyExists(res[0], json)) {
    console.log(json[res[0]])
    return true
  } else return false
}

function nestedKeyShow (obj, res, keyArr) {
  if (keyExists(keyArr[0], obj)) {
    if (keyArr.length === 1) {
      console.log(obj[keyArr[0]])
      return true
    } else if (keyArr.length > 1) {
      let flag = nestedKeyShow(obj[keyArr[0]], res, keyArr.slice(1))
      return flag
    }
  } else return false
}

function getKeyValue (dbInput) {
  let key = dbInput.split(' ')[0], value
  dbInput = jsonParser.delSpace(dbInput.slice(key.length))
  if (dbInput) {
    value = jsonParser.parseJSON(dbInput)
    dbInput = value[1]
  } else value = ''
  return [key, value, dbInput]
}

function keyExists (key, obj) {
  return key in obj
}

function writeData (json) {
  fs.writeFile('db.json', JSON.stringify(json, null, 4), function (err) {
    if (err) throw err
  })
}
<commit_msg>Working on merge conflicts<commit_after>let fs = require('fs')
let jsonParser = require('./jsonParser.js')
const db = './db.json'

exports.listData = function (dbInput) {
  dbInput = jsonParser.delSpace(dbInput.slice(7))
  let json = require(db)
  for (let ob in json) {
    console.log(ob, ':', json[ob])
  }
  return [Object.keys(json).length + ' Items', dbInput]
}

exports.insertData = function (dbInput) {
  dbInput = jsonParser.delSpace(dbInput.slice(6))
  let res = getKeyValue(dbInput)
  if (!fs.existsSync(db)) return firstInsert(res)
  else {
    let json = require(db)
    if (!keyExists(res[0], json)) {
      return (insertSimpleOrNestedKey(res)) ? ['Data inserted', res[1][0]] : ['Key already exists', res[1][0]]
    } else return ['Key already exists', res[1][0]]
  }
}

function firstInsert (res) {
  let json = {}
  fs.open(db, 'w+', (err, fd) => {
    if (err) throw err
    else {
      json[res[0]] = res[1][0]
      writeData(json)
    }
  })
  return ['Data inserted', res[1][0]]
}

function insertSimpleOrNestedKey (res) {
  let json = require(db), flag, keyArr = res[0].split('.')
  flag = (keyArr.length === 1) ? simpleKeyInsert(json, res) : nestedKeyInsert(json, res, keyArr)
  return flag
}

function simpleKeyInsert (json, res) {
  json[res[0]] = res[1][0]
  writeData(json)
  return true
}

function nestedKeyInsert (obj, res, keyArr) {
  if (keyExists(keyArr[0], obj)) {
    if (!keyExists(keyArr[1], obj[keyArr[0]])) {
      let ob = obj[keyArr[0]]
      if (ob.length >= 0) {
        keyArr[1] = ob.length
      }
      ob[keyArr[1]] = res[1][0]
      obj[keyArr[0]] = ob
      writeData(obj)
      return true
    } else {
      let flag = nestedKeyInsert(obj[keyArr[0]], res, keyArr.slice(1))
      writeData(obj)
      return flag
    }
  } else return false
}

exports.updateData = function (dbInput) {
  dbInput = jsonParser.delSpace(dbInput.slice(6))
  let res = getKeyValue(dbInput)
  return (updateSimpleOrNestedKey(res)) ? ['Value updated', res[1][0]] : ['No such key found', res[1][0]]
}

function updateSimpleOrNestedKey (res) {
  let json = require(db), flag, keyArr = res[0].split('.')
  flag = (keyArr.length === 1) ? simpleKeyUpdate(json, res) : nestedKeyUpdate(json, res, keyArr)
  return flag
}

function simpleKeyUpdate (json, res) {
  if (!keyExists(res[0], json)) return false
  else {
    json[res[0]] = res[1][0]
    writeData(json)
    return true
  }
}

function nestedKeyUpdate (obj, res, keyArr) {
  if (keyExists(keyArr[0], obj)) {
    if (keyArr.length === 1) {
      obj[keyArr[0]] = res[1][0]
      return true
    } else if (keyArr.length > 1) {
      let flag = nestedKeyUpdate(obj[keyArr[0]], res, keyArr.slice(1))
      console.log(obj)
      writeData(obj)
      return flag
    }
  } else return false
}

exports.deleteData = function (dbInput) {
  dbInput = jsonParser.delSpace(dbInput.slice(6))
  let res = getKeyValue(dbInput)
  return (deleteSimpleOrNestedKey(res)) ? ['Data deleted', res[1][0]] : ['No such key found', res[1][0]]
}

function deleteSimpleOrNestedKey (res) {
  let json = require(db), keyArr = res[0].split('.')
  let flag = (keyArr.length === 1) ? simpleKeyDelete(json, res) : nestedKeyDelete(json, res, keyArr)
  return flag
}

function simpleKeyDelete (json, res) {
  if (!keyExists(res[0], json)) return false
  else {
    delete json[res[0]]
    writeData(json)
    return true
  }
}

function nestedKeyDelete (obj, res, keyArr) {
  if (keyExists(keyArr[0], obj)) {
    if (keyArr.length === 1) {
      if (obj.length) obj.splice(keyArr[0], 1)
      else delete obj[keyArr[0]]
      return true
    } else if (keyArr.length > 1) {
      let flag = nestedKeyDelete(obj[keyArr[0]], res, keyArr.slice(1))
      writeData(obj)
      return flag
    }
  } else return false
}

exports.showValue = function (dbInput) {
  dbInput = jsonParser.delSpace(dbInput.slice(4))
  let res = getKeyValue(dbInput)
  return showSimpleOrNestedKey(res) ? ['Key exists', res[1][0]] : ['No such key found', res[1][0]]
}

function showSimpleOrNestedKey (res) {
  let json = require(db), keyArr = res[0].split('.')
  let flag = (keyArr.length === 1) ? simpleKeyShow(json, res) : nestedKeyShow(json, res, keyArr)
  return flag
}

function simpleKeyShow (json, res) {
  if (keyExists(res[0], json)) {
    console.log(json[res[0]])
    return true
  } else return false
}

function nestedKeyShow (obj, res, keyArr) {
  if (keyExists(keyArr[0], obj)) {
    if (keyArr.length === 1) {
      console.log(obj[keyArr[0]])
      return true
    } else if (keyArr.length > 1) {
      let flag = nestedKeyShow(obj[keyArr[0]], res, keyArr.slice(1))
      return flag
    }
  } else return false
}

function getKeyValue (dbInput) {
  let key = dbInput.split(' ')[0], value
  dbInput = jsonParser.delSpace(dbInput.slice(key.length))
  if (dbInput) {
    value = jsonParser.parseJSON(dbInput)
    dbInput = value[1]
  } else value = ''
  return [key, value]
}

function keyExists (key, obj) {
  return key in obj
}

function writeData (json) {
  fs.writeFile('db.json', JSON.stringify(json, null, 4), function (err) {
    if (err) throw err
  })
}
<|endoftext|>


<commit_before>(function () {
	'use strict';

	// requestAnimationFrame polyfill
	window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || setTimeout;

	// preconfiguration using <script>'s data-attributes values
	var scripts = document.getElementsByTagName('script'),
		script = scripts[scripts.length - 1],
		worker = new Worker('worker.js'),
		nextIndex = 0,
		sentVideos = 0,
		currentVideo = null,
		videos = [],
		lastOriginal,
		canvas = document.getElementById(script.getAttribute('data-canvas')),
		manifest = script.getAttribute('data-hls'),
		context = canvas.getContext('2d');

	// drawing new frame
	function nextFrame() {
		if (currentVideo.paused || currentVideo.ended) {
			return;
		}
		context.drawImage(currentVideo, 0, 0);
		requestAnimationFrame(nextFrame);
	}

	worker.addEventListener('message', function (event) {
		var data = event.data, descriptor = '#' + data.index + ': ' + data.original;

		switch (data.type) {
			// worker is ready to convert
			case 'ready':
				getMore();
				return;

			// got debug message from worker
			case 'debug':
				Function.prototype.apply.call(console[data.action], console, data.args);
				return;

			// got new converted MP4 video data
			case 'video':
				var video = document.createElement('video'), source = document.createElement('source');
				source.type = 'video/mp4';
				video.appendChild(source);

				video.addEventListener('loadedmetadata', function () {
					if (canvas.width !== this.videoWidth || canvas.height !== this.videoHeight) {
						canvas.width = this.width = this.videoWidth;
						canvas.height = this.height = this.videoHeight;
					}
				});

				video.addEventListener('play', function () {
					if (currentVideo !== this) {
						if (!currentVideo) {
							// UI initialization magic to be left in main HTML for unobtrusiveness
							new Function(script.text).call({
								worker: worker,
								canvas: canvas,
								get currentVideo() { return currentVideo }
							});
						}
						console.log('playing ' + descriptor);
						currentVideo = this;
						nextIndex++;
						if (sentVideos - nextIndex <= 1) {
							getMore();
						}
					}
					nextFrame();
				});

				video.addEventListener('ended', function () {
					delete videos[nextIndex - 1];
					if (nextIndex in videos) {
						videos[nextIndex].play();
					}
				});
				if (video.src.slice(0, 5) === 'blob:') {
					video.addEventListener('ended', function () {
						URL.revokeObjectURL(this.src);
					});
				}

				video.src = source.src = data.url;
				video.load();

				(function canplaythrough() {
					console.log('converted ' + descriptor);
					videos[data.index] = this;
					if ((!currentVideo || currentVideo.ended) && data.index === nextIndex) {
						this.play();
					}
				}).call(video);

				return;
		}
	});

	// relative URL resolver
	var resolveURL = (function () {
		var doc = document,
			old_base = doc.getElementsByTagName('base')[0],
			old_href = old_base && old_base.href,
			doc_head = doc.head || doc.getElementsByTagName('head')[0],
			our_base = old_base || doc.createElement('base'),
			resolver = doc.createElement('a'),
			resolved_url;

		return function (base_url, url) {
			old_base || doc_head.appendChild(our_base);

			our_base.href = base_url;
			resolver.href = url;
			resolved_url  = resolver.href; // browser magic at work here

			old_base ? old_base.href = old_href : doc_head.removeChild(our_base);

			return resolved_url;
		};
	})();

	// loading more videos from manifest
	function getMore() {
		var ajax = new XMLHttpRequest();
		ajax.addEventListener('load', function () {
			var originals =
				this.responseText
				.split(/\r?\n/)
				.filter(RegExp.prototype.test.bind(/\.ts$/))
				.map(resolveURL.bind(null, manifest));

			originals = originals.slice(originals.lastIndexOf(lastOriginal) + 1);
			lastOriginal = originals[originals.length - 1];

			worker.postMessage(originals.map(function (url, index) {
				return {url: url, index: sentVideos + index};
			}));

			sentVideos += originals.length;

			console.log('asked for ' + originals.length + ' more videos');
		});
		ajax.open('GET', manifest, true);
		ajax.send();
	}
})();<commit_msg>Use loadeddata instead of loadedmetadata<commit_after>(function () {
	'use strict';

	// requestAnimationFrame polyfill
	window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || setTimeout;

	// preconfiguration using <script>'s data-attributes values
	var scripts = document.getElementsByTagName('script'),
		script = scripts[scripts.length - 1],
		worker = new Worker('worker.js'),
		nextIndex = 0,
		sentVideos = 0,
		currentVideo = null,
		videos = [],
		lastOriginal,
		canvas = document.getElementById(script.getAttribute('data-canvas')),
		manifest = script.getAttribute('data-hls'),
		context = canvas.getContext('2d');

	// drawing new frame
	function nextFrame() {
		if (currentVideo.paused || currentVideo.ended) {
			return;
		}
		context.drawImage(currentVideo, 0, 0);
		requestAnimationFrame(nextFrame);
	}

	worker.addEventListener('message', function (event) {
		var data = event.data, descriptor = '#' + data.index + ': ' + data.original;

		switch (data.type) {
			// worker is ready to convert
			case 'ready':
				getMore();
				return;

			// got debug message from worker
			case 'debug':
				Function.prototype.apply.call(console[data.action], console, data.args);
				return;

			// got new converted MP4 video data
			case 'video':
				var video = document.createElement('video'), source = document.createElement('source');
				source.type = 'video/mp4';
				video.appendChild(source);

				video.addEventListener('loadeddata', function () {
					if (canvas.width !== this.videoWidth || canvas.height !== this.videoHeight) {
						canvas.width = this.width = this.videoWidth;
						canvas.height = this.height = this.videoHeight;
					}
				});

				video.addEventListener('play', function () {
					if (currentVideo !== this) {
						if (!currentVideo) {
							// UI initialization magic to be left in main HTML for unobtrusiveness
							new Function(script.text).call({
								worker: worker,
								canvas: canvas,
								get currentVideo() { return currentVideo }
							});
						}
						console.log('playing ' + descriptor);
						currentVideo = this;
						nextIndex++;
						if (sentVideos - nextIndex <= 1) {
							getMore();
						}
					}
					nextFrame();
				});

				video.addEventListener('ended', function () {
					delete videos[nextIndex - 1];
					if (nextIndex in videos) {
						videos[nextIndex].play();
					}
				});
				if (video.src.slice(0, 5) === 'blob:') {
					video.addEventListener('ended', function () {
						URL.revokeObjectURL(this.src);
					});
				}

				video.src = source.src = data.url;
				video.load();

				(function canplaythrough() {
					console.log('converted ' + descriptor);
					videos[data.index] = this;
					if ((!currentVideo || currentVideo.ended) && data.index === nextIndex) {
						this.play();
					}
				}).call(video);

				return;
		}
	});

	// relative URL resolver
	var resolveURL = (function () {
		var doc = document,
			old_base = doc.getElementsByTagName('base')[0],
			old_href = old_base && old_base.href,
			doc_head = doc.head || doc.getElementsByTagName('head')[0],
			our_base = old_base || doc.createElement('base'),
			resolver = doc.createElement('a'),
			resolved_url;

		return function (base_url, url) {
			old_base || doc_head.appendChild(our_base);

			our_base.href = base_url;
			resolver.href = url;
			resolved_url  = resolver.href; // browser magic at work here

			old_base ? old_base.href = old_href : doc_head.removeChild(our_base);

			return resolved_url;
		};
	})();

	// loading more videos from manifest
	function getMore() {
		var ajax = new XMLHttpRequest();
		ajax.addEventListener('load', function () {
			var originals =
				this.responseText
				.split(/\r?\n/)
				.filter(RegExp.prototype.test.bind(/\.ts$/))
				.map(resolveURL.bind(null, manifest));

			originals = originals.slice(originals.lastIndexOf(lastOriginal) + 1);
			lastOriginal = originals[originals.length - 1];

			worker.postMessage(originals.map(function (url, index) {
				return {url: url, index: sentVideos + index};
			}));

			sentVideos += originals.length;

			console.log('asked for ' + originals.length + ' more videos');
		});
		ajax.open('GET', manifest, true);
		ajax.send();
	}
})();
<|endoftext|>


<commit_before>const uuidV4 = require('uuid/v4');
const fs = require('fs');
const path = require('path');
const readline = require('readline');

function collection(name, dataPath) {
	let logPath = path.resolve(dataPath, name + '_log');
	let sourcePath = path.resolve(dataPath, name);
	let collection = [];
	let persistenceStream = fs.createWriteStream(logPath, {flags:'a'});

	unPack();

	function persistChange(operation) {
		persistenceStream.write(JSON.stringify(operation)+'\n');
	}

	function pack() {
		persistenceStream.cork();
		fs.writeFile(sourcePath, JSON.stringify(collection), 'utf-8',() => {
			fs.writeFile(logPath, '','utf-8', () => {
				persistenceStream.uncork();
			});
		});
	}

	function unPack() {
		try {
			let collectionFileContent = fs.readFileSync(sourcePath, 'utf-8');

			if(!collectionFileContent || collectionFileContent.length == 0) {
				collection = [];
			} else {
				collection = JSON.parse(collectionFileContent);
			}
		} catch (err) {
			collection = [];
		}

		fs.readFileSync(logPath, 'utf-8')
		.split('\n')
		.forEach((line) => {
			if(!line || line.length == 0) {
				return;
			}

			let operation = JSON.parse(line);
			switch(operation.operation) {
				case 'I':
				collection.push(operation.data);
				break;
				case 'U':
				findElements((element) => element['_id'] == operation.data['_id'])
				.forEach((element) => extend(element, operation.data));
				break;
				case 'D':
				collection.splice(operation.index, 1);
				break;
			}
		});
		pack();
		setInterval(pack, 1000 * 60 * 60);
	}

	function findElements(query) {
		return collection.filter((element, index) => {
			if(query(element)) {
				element['_index'] = index;
				return true;
			}
			return false;
		});
	}

	function insertElement(data) {
		data['_id'] = uuidV4();
		collection.push(data);
		persistChange({operation:'I', data: data});
		return data['_id'];
	}

	function updateElements(query, update) {
		findElements(query)
		.forEach((element) => {
			update(element);
			persistChange({operation:'U', data:element});
		});

	}

	function deleteElements(query) {
		findElements(query)
		.reverse()
		.forEach((element) => {
			persistChange({operation:'D', index:element['_index']});
			collection.splice(element['_index'], 1);
		});
	}

	return {
		findElements : findElements,
		insertElement : insertElement,
		updateElements : updateElements,
		deleteElements : deleteElements
	};
}

module.exports = collection;<commit_msg>Add missing require<commit_after>const uuidV4 = require('uuid/v4');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const extend = require('extend');

function collection(name, dataPath) {
	let logPath = path.resolve(dataPath, name + '_log');
	let sourcePath = path.resolve(dataPath, name);
	let collection = [];
	let persistenceStream = fs.createWriteStream(logPath, {flags:'a'});

	unPack();

	function persistChange(operation) {
		persistenceStream.write(JSON.stringify(operation)+'\n');
	}

	function pack() {
		persistenceStream.cork();
		fs.writeFile(sourcePath, JSON.stringify(collection), 'utf-8',() => {
			fs.writeFile(logPath, '','utf-8', () => {
				persistenceStream.uncork();
			});
		});
	}

	function unPack() {
		try {
			let collectionFileContent = fs.readFileSync(sourcePath, 'utf-8');

			if(!collectionFileContent || collectionFileContent.length == 0) {
				collection = [];
			} else {
				collection = JSON.parse(collectionFileContent);
			}
		} catch (err) {
			collection = [];
		}

		fs.readFileSync(logPath, 'utf-8')
		.split('\n')
		.forEach((line) => {
			if(!line || line.length == 0) {
				return;
			}

			let operation = JSON.parse(line);
			switch(operation.operation) {
				case 'I':
				collection.push(operation.data);
				break;
				case 'U':
				findElements((element) => element['_id'] == operation.data['_id'])
				.forEach((element) => extend(element, operation.data));
				break;
				case 'D':
				collection.splice(operation.index, 1);
				break;
			}
		});
		pack();
		setInterval(pack, 1000 * 60 * 60);
	}

	function findElements(query) {
		return collection.filter((element, index) => {
			if(query(element)) {
				element['_index'] = index;
				return true;
			}
			return false;
		});
	}

	function insertElement(data) {
		data['_id'] = uuidV4();
		collection.push(data);
		persistChange({operation:'I', data: data});
		return data['_id'];
	}

	function updateElements(query, update) {
		findElements(query)
		.forEach((element) => {
			update(element);
			persistChange({operation:'U', data:element});
		});

	}

	function deleteElements(query) {
		findElements(query)
		.reverse()
		.forEach((element) => {
			persistChange({operation:'D', index:element['_index']});
			collection.splice(element['_index'], 1);
		});
	}

	return {
		findElements : findElements,
		insertElement : insertElement,
		updateElements : updateElements,
		deleteElements : deleteElements
	};
}

module.exports = collection;<|endoftext|>