<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2015, Robin Jarry
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var RSTHighlightRules = function() {

  var tokens = {
    title: "markup.heading",
    list: "markup.heading",
    table: "constant",
    directive: "keyword.operator",
    entity: "string",
    link: "markup.underline.list",
    bold: "markup.bold",
    italic: "markup.italic",
    literal: "support.function",
    comment: "comment"
  };

  this.$rules = {
    "start": [
      /* NB: Only the underline of the heading is highlighted.
       * ACE tokenizer does not allow backtracking, the underlined text of the
       * heading cannot be highlighted. */
      {
        token : tokens.title,
        regex : "(^)([\\=\\-`:\\.'\"~\\^_\\*\\+#])(\\2{2,}\\s*$)"
      },
      /* Generic directive syntax (e.g. .. code-block:: c)
       * All of the directive body is highlighted as a code block. */
      {
        token : [tokens.directive, tokens.literal],
        regex : "(^\\s*\\.\\. [^:]+::)(.*$)",
        next  : "codeblock"
      },
      {
        token : tokens.directive,
        regex : "::$",
        next  : "codeblock"
      },
      /* Link/anchor definitions */
      {
        token : [tokens.entity, tokens.link],
        regex : "(^\\.\\. _[^:]+:)(.*$)"
      },
      {
        token : [tokens.entity, tokens.link],
        regex : "(^__ )(https?://.*$)"
      },
      /* Footnote definition */
      {
        token : tokens.entity,
        regex : "^\\.\\. \\[[^\\]]+\\] "
      },
      /* Comment block start */
      {
        token : tokens.comment,
        regex : "^\\.\\. .*$",
        next  : "comment"
      },
      /* List items */
      {
        token : tokens.list,
        regex : "^\\s*(?:[\\*\\+-]|\\d+\\.|#\\.) "
      },
      /* "Simple" tables */
      {
        token : tokens.table,
        regex : "^={2,}(?: +={2,})+$"
      },
      /* "Grid" tables */
      {
        token : tokens.table,
        regex : "^\\+-{2,}(?:\\+-{2,})+\\+$"
      },
      {
        token : tokens.table,
        regex : "^\\+={2,}(?:\\+={2,})+\\+$"
      },
      /* Inline markup */
      {
        token : tokens.literal,
        regex : "``(?:\\\\`|[^`])+?``"
      },
      {
        token : tokens.bold,
        regex : "\\*\\*(?:\\\\\\*|[^\\*])+?\\*\\*"
      },
      {
        token : tokens.italic,
        regex : "\\*(?:\\\\\\*|[^\\*])+?\\*"
      },
      /* Link/footnote references */
      {
        token : tokens.entity,
        regex : ":[\\w-]+:`[^`]+?`"
      },
      {
        token : tokens.link,
        regex : "`[^`]+?`__?"
      },
      {
        token : tokens.link,
        regex : "[A-Za-z0-9\\-]+?__?"
      },
      {
        token : tokens.link,
        regex : "\\[[^\\]]+?\\]_"
      },
      {
        token : tokens.link,
        regex : "https?://\\S+"
      },
      /* "Grid" tables column separator
       * This is at the end to make it lower priority over all other rules. */
      {
        token : tokens.table,
        regex : "\\|"
      },
      {
        defaultToken : "text"
      }
    ],

    /* This state is used for all directive bodies and litteral blocks.
     * The parser returns to the "start" state when reaching the first
     * non-empty line that does not start with at least one space. */
    "codeblock": [
      {
        token : tokens.literal,
        regex : "^ +.+$",
        next : "codeblock"
      },
      {
        token : tokens.literal,
        regex : '^$',
        next: "codeblock"
      },
      {
        token : "empty",
        regex : "",
        next : "start"
      }
    ],

    /* Comment block.
     * The parser returns to the "start" state when reaching the first
     * non-empty line that does not start with at least one space. */
    "comment": [
      {
        token : tokens.comment,
        regex : "^ +.+$",
        next : "comment"
      },
      {
        token : tokens.comment,
        regex : '^$',
        next: "comment"
      },
      {
        token : "empty",
        regex : "",
        next : "start"
      }
    ]
  };
};
oop.inherits(RSTHighlightRules, TextHighlightRules);

exports.RSTHighlightRules = RSTHighlightRules;
});
<commit_msg>mode/rst: support multiline inline markup<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2015, Robin Jarry
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var RSTHighlightRules = function() {

  var tokens = {
    title: "markup.heading",
    list: "markup.heading",
    table: "constant",
    directive: "keyword.operator",
    entity: "string",
    link: "markup.underline.list",
    bold: "markup.bold",
    italic: "markup.italic",
    literal: "support.function",
    comment: "comment"
  };

  this.$rules = {
    "start": [
      /* NB: Only the underline of the heading is highlighted.
       * ACE tokenizer does not allow backtracking, the underlined text of the
       * heading cannot be highlighted. */
      {
        token : tokens.title,
        regex : "(^)([\\=\\-`:\\.'\"~\\^_\\*\\+#])(\\2{2,}\\s*$)"
      },
      /* Generic directive syntax (e.g. .. code-block:: c)
       * All of the directive body is highlighted as a code block. */
      {
        token : [tokens.directive, tokens.literal],
        regex : "(^\\s*\\.\\. [^:]+::)(.*$)",
        next  : "codeblock"
      },
      {
        token : tokens.directive,
        regex : "::$",
        next  : "codeblock"
      },
      /* Link/anchor definitions */
      {
        token : [tokens.entity, tokens.link],
        regex : "(^\\.\\. _[^:]+:)(.*$)"
      },
      {
        token : [tokens.entity, tokens.link],
        regex : "(^__ )(https?://.*$)"
      },
      /* Footnote definition */
      {
        token : tokens.entity,
        regex : "^\\.\\. \\[[^\\]]+\\] "
      },
      /* Comment block start */
      {
        token : tokens.comment,
        regex : "^\\.\\. .*$",
        next  : "comment"
      },
      /* List items */
      {
        token : tokens.list,
        regex : "^\\s*(?:[\\*\\+-]|\\d+\\.|#\\.) "
      },
      /* "Simple" tables */
      {
        token : tokens.table,
        regex : "^={2,}(?: +={2,})+$"
      },
      /* "Grid" tables */
      {
        token : tokens.table,
        regex : "^\\+-{2,}(?:\\+-{2,})+\\+$"
      },
      {
        token : tokens.table,
        regex : "^\\+={2,}(?:\\+={2,})+\\+$"
      },
      /* Inline markup */
      {
        token : tokens.literal,
        regex : "``",
        next  : "code"
      },
      {
        token : tokens.bold,
        regex : "\\*\\*",
        next  : "bold"
      },
      {
        token : tokens.italic,
        regex : "\\*",
        next  : "italic"
      },
      /* Link/footnote references */
      {
        token : tokens.entity,
        regex : ":[\\w-:]+:`",
        next  : "entity"
      },
      {
        token : tokens.entity,
        regex : "_`",
        next  : "entity"
      },
      {
        token : tokens.entity,
        regex : "_[A-Za-z0-9\\-]+?"
      },
      {
        token : tokens.link,
        regex : "`",
        next  : "link"
      },
      {
        token : tokens.link,
        regex : "[A-Za-z0-9\\-]+?__?"
      },
      {
        token : tokens.link,
        regex : "\\[[^\\]]+?\\]_"
      },
      {
        token : tokens.link,
        regex : "https?://\\S+"
      },
      /* "Grid" tables column separator
       * This is at the end to make it lower priority over all other rules. */
      {
        token : tokens.table,
        regex : "\\|"
      }
    ],

    /* This state is used for all directive bodies and literal blocks.
     * The parser returns to the "start" state when reaching the first
     * non-empty line that does not start with at least one space. */
    "codeblock": [
      {
        token : tokens.literal,
        regex : "^ +.+$",
        next : "codeblock"
      },
      {
        token : tokens.literal,
        regex : '^$',
        next: "codeblock"
      },
      {
        token : "empty",
        regex : "",
        next : "start"
      }
    ],

    /* Inline code
     * The parser returns to the "start" state when reaching "``" */
    "code": [
      {
        token : tokens.literal,
        regex : "``",
        next  : "start"
      },
      {
        defaultToken: tokens.literal
      }
    ],

    /* Bold (strong) text
     * The parser returns to the "start" state when reaching "**" */
    "bold": [
      {
        token : tokens.bold,
        regex : "\\*\\*",
        next  : "start"
      },
      {
        defaultToken: tokens.bold
      }
    ],

    /* Italic (emphasis) text
     * The parser returns to the "start" state when reaching "*" */
    "italic": [
      {
        token : tokens.italic,
        regex : "\\*",
        next  : "start"
      },
      {
        defaultToken: tokens.italic
      }
    ],

    /* Explicit role/class text or link anchor definition
     * The parser returns to the "start" state when reaching "`" */
    "entity": [
      {
        token : tokens.entity,
        regex : "`",
        next  : "start"
      },
      {
        defaultToken: tokens.entity
      }
    ],

    /* Link reference
     * The parser returns to the "start" state when reaching "`_" or "`__" */
    "link": [
      {
        token : tokens.link,
        regex : "`__?",
        next  : "start"
      },
      {
        defaultToken: tokens.link
      }
    ],

    /* Comment block.
     * The parser returns to the "start" state when reaching the first
     * non-empty line that does not start with at least one space. */
    "comment": [
      {
        token : tokens.comment,
        regex : "^ +.+$",
        next : "comment"
      },
      {
        token : tokens.comment,
        regex : '^$',
        next: "comment"
      },
      {
        token : "empty",
        regex : "",
        next : "start"
      }
    ]
  };
};
oop.inherits(RSTHighlightRules, TextHighlightRules);

exports.RSTHighlightRules = RSTHighlightRules;
});
<|endoftext|>


<commit_before>/**
 * Copyright - A Produle Systems Private Limited. All Rights Reserved.
 *
 * @desc Handles all the message related operations
 *
 */

function UC_MessagingController()
{
	var thisClass = this;

    this.emailMessagingController = new UC_EmailMessagingController();

    this.browserNotificationController = new UC_BrowserNotificationController();

    this.rivetFieldListObj = null;

    this.quill = null;

	this.constructor = function()
	{

        thisClass.emailMessagingController.constructor();

        thisClass.browserNotificationController.constructor();

        $(document).on("click","#ucSendMessageGroupBtn",thisClass.openSendMessageModal);

        $(document).on("click",".ucSendMessageSingleTrigger",thisClass.selectCurrentVisitor);

		thisClass.rivetFieldListObj = rivets.bind(
            document.querySelector('#ucEmailFieldList'), {
                fieldList: []
            }
        );

		var toolbarOptions = [{ 'header': [1, 2, 3, 4, 5, 6, false] },'bold', 'italic', 'underline','link',{ 'list': 'ordered'}, { 'list': 'bullet' }, 'clean'];
		thisClass.quill = new Quill('#ucSendMessageEmailBody', {
			theme: 'snow',
			modules: {
				toolbar: toolbarOptions
			},
		});
	};

    this.openSendMessageModal = function()
    {
        $("#ucSendMessageModal").modal();

        $('#ucSendMessageAjaxLoader').hide();

        $("#ucDeleteEmailTemplateBtn, #ucDeleteBrowserNotificationTemplateBtn").hide();

        $("#ucSendMessageEmailTemplate, #ucSendMessageBrowserNotificationTemplate").removeClass("ucExistTemplate");

        $(".ucSendMessageContainer").hide();
        $("#ucSendMessageEmailContainer").show();

        $("#ucSendMessageTypeTabGroup button").removeClass("active");
        $("#ucSendMessageTypeTabGroup button[data-tabgroup-tabid=ucSendMessageEmailContainer]").addClass("active");

        thisClass.quill.setText("");

        thisClass.emailMessagingController.getEmailTemplates();

        thisClass.browserNotificationController.getBrowserNotificationTemplates();

        UC_AJAX.call('VisitorListManager/getfieldslist',{appid:uc_main.appController.currentAppId,user:UC_UserSession.user},function(data,status,xhr){

            if(data.status == "failure")
            {
                alert("Error while getting field list");
            }
            else if(data.status == "authenticationfailed")
            {
                location.href="/";
            }
            else
            {
                for(var iter = 0; iter < data.fields.length; iter++)
                {
                    data.fields[iter] = "{"+data.fields[iter]+"}";
                }
                thisClass.rivetFieldListObj.models.fieldList = data.fields;
            }
        });
    };

    /*
     * @desc Selects the checkbox of corresponding visitor to insert them in inclusionList
     */
    this.selectCurrentVisitor = function()
    {
        $("#uc-all-user-select").prop("checked",false);
        $(".uc-user-select").prop("checked",false);

        uc_main.visitorListController.userListSelectHandler();

        $(this).closest(".ucTableRow").find(".uc-user-select").prop("checked",true);

        thisClass.openSendMessageModal();
    };

    /*
     * @desc Collects the filterId, inclusionList and exclusionList for send message
     */
    this.sendMessageHandler = function(subject,message,template,link,blockDuplicate,messageType)
    {
        var filterId = null;
        var exclusionList = [];
        var inclusionList = [];

        if($("#uc-all-user-select").is(":checked"))
        {
            filterId = uc_main.visitorListController.currentFilterId;

            $(".uc-user-select").each(function(){
                if(!$(this).is(":checked"))
                {
                    exclusionList.push($(this).attr("data-visitorid"));
                }
            });
        }
        else
        {
            $(".uc-user-select").each(function(){
                if($(this).is(":checked"))
                {
                    inclusionList.push($(this).attr("data-visitorid"));
                }
            });
        }

        //call the email trigger server function

        $('#ucSendMessageAjaxLoader').show();

        UC_AJAX.call('MessagingManager/sendmessage',{appid:uc_main.appController.currentAppId,user:UC_UserSession.user,filterId:filterId,exclusionList:exclusionList,inclusionList:inclusionList,subject:subject,message:message,template:template,link:link,blockDuplicate:blockDuplicate,messageType:messageType},function(data,status,xhr){

                if(data.status == "failure")
                {
                    alert("Could not send emails, kindly check the Email Settings");
                }
                else if(data.status == "authenticationfailed")
                {
                    location.href="/";
                }
                else
                {
                    $("#ucSendMessageModal").modal("hide");
                }

                $('#ucSendMessageAjaxLoader').hide();
            });
    };
}
<commit_msg>UC-76 - partial commit<commit_after>/**
 * Copyright - A Produle Systems Private Limited. All Rights Reserved.
 *
 * @desc Handles all the message related operations
 *
 */

function UC_MessagingController()
{
	var thisClass = this;

    this.emailMessagingController = new UC_EmailMessagingController();

    this.browserNotificationController = new UC_BrowserNotificationController();

    this.rivetFieldListObj = null;

    this.quill = null;

	this.constructor = function()
	{

        thisClass.emailMessagingController.constructor();

        thisClass.browserNotificationController.constructor();

        $(document).on("click","#ucSendMessageGroupBtn",thisClass.openSendMessageModal);

        $(document).on("click",".ucSendMessageSingleTrigger",thisClass.selectCurrentVisitor);

		thisClass.rivetFieldListObj = rivets.bind(
            document.querySelector('#ucEmailFieldList'), {
                fieldList: []
            }
        );

		var toolbarOptions = [{ 'header': [1, 2, 3, 4, 5, 6, false] },'bold', 'italic', 'underline','link', 'image',{ 'list': 'ordered'}, { 'list': 'bullet' }, 'clean'];

		var toolbarOptions = [
		                      ['bold', 'italic', 'underline'],        // toggled buttons
		                      ['link','image'],
		                      [{ 'color': ['#F44336','#E91E63','#F44336','#E91E63','#F44336','#E91E63'] }, { 'background': ['#F44336','#E91E63'] }],          // dropdown with defaults from theme
		                      [{ 'font': [] },{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown],
		                    ];

		thisClass.quill = new Quill('#ucSendMessageEmailBody', {
			theme: 'snow',
			modules: {
				toolbar: toolbarOptions
			},
		});
	};

    this.openSendMessageModal = function()
    {
        $("#ucSendMessageModal").modal();

        $('#ucSendMessageAjaxLoader').hide();

        $("#ucDeleteEmailTemplateBtn, #ucDeleteBrowserNotificationTemplateBtn").hide();

        $("#ucSendMessageEmailTemplate, #ucSendMessageBrowserNotificationTemplate").removeClass("ucExistTemplate");

        $(".ucSendMessageContainer").hide();
        $("#ucSendMessageEmailContainer").show();

        $("#ucSendMessageTypeTabGroup button").removeClass("active");
        $("#ucSendMessageTypeTabGroup button[data-tabgroup-tabid=ucSendMessageEmailContainer]").addClass("active");

        thisClass.quill.setText("");

        thisClass.emailMessagingController.getEmailTemplates();

        thisClass.browserNotificationController.getBrowserNotificationTemplates();

        UC_AJAX.call('VisitorListManager/getfieldslist',{appid:uc_main.appController.currentAppId,user:UC_UserSession.user},function(data,status,xhr){

            if(data.status == "failure")
            {
                alert("Error while getting field list");
            }
            else if(data.status == "authenticationfailed")
            {
                location.href="/";
            }
            else
            {
                for(var iter = 0; iter < data.fields.length; iter++)
                {
                    data.fields[iter] = "{"+data.fields[iter]+"}";
                }
                thisClass.rivetFieldListObj.models.fieldList = data.fields;
            }
        });
    };

    /*
     * @desc Selects the checkbox of corresponding visitor to insert them in inclusionList
     */
    this.selectCurrentVisitor = function()
    {
        $("#uc-all-user-select").prop("checked",false);
        $(".uc-user-select").prop("checked",false);

        uc_main.visitorListController.userListSelectHandler();

        $(this).closest(".ucTableRow").find(".uc-user-select").prop("checked",true);

        thisClass.openSendMessageModal();
    };

    /*
     * @desc Collects the filterId, inclusionList and exclusionList for send message
     */
    this.sendMessageHandler = function(subject,message,template,link,blockDuplicate,messageType)
    {
        var filterId = null;
        var exclusionList = [];
        var inclusionList = [];

        if($("#uc-all-user-select").is(":checked"))
        {
            filterId = uc_main.visitorListController.currentFilterId;

            $(".uc-user-select").each(function(){
                if(!$(this).is(":checked"))
                {
                    exclusionList.push($(this).attr("data-visitorid"));
                }
            });
        }
        else
        {
            $(".uc-user-select").each(function(){
                if($(this).is(":checked"))
                {
                    inclusionList.push($(this).attr("data-visitorid"));
                }
            });
        }

        //call the email trigger server function

        $('#ucSendMessageAjaxLoader').show();

        UC_AJAX.call('MessagingManager/sendmessage',{appid:uc_main.appController.currentAppId,user:UC_UserSession.user,filterId:filterId,exclusionList:exclusionList,inclusionList:inclusionList,subject:subject,message:message,template:template,link:link,blockDuplicate:blockDuplicate,messageType:messageType},function(data,status,xhr){

                if(data.status == "failure")
                {
                    alert("Could not send emails, kindly check the Email Settings");
                }
                else if(data.status == "authenticationfailed")
                {
                    location.href="/";
                }
                else
                {
                    $("#ucSendMessageModal").modal("hide");
                }

                $('#ucSendMessageAjaxLoader').hide();
            });
    };
}
<|endoftext|>


<commit_before>var extend = require('./utils').extend;
var crypto = require('crypto');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var WebSocketFrame = require('./WebSocketFrame');
var BufferList = require('../vendor/FastBufferList');

function WebSocketConnection(socket, extensions, protocol, maskOutgoingPackets, config) {
    this.config = config;
    this.socket = socket;
    this.protocol = protocol;
    this.extensions = extensions;
    this.remoteAddress = socket.remoteAddress;

    // We have to mask outgoing packets if we're acting as a WebSocket client.
    this.maskOutgoingPackets = maskOutgoingPackets;

    // We re-use the same buffers for the mask and frame header for all frames
    // received on each connection to avoid a small memory allocation for each
    // frame.
    this.maskBytes = new Buffer(4);
    this.frameHeader = new Buffer(10);

    // the BufferList will handle the data streaming in
    this.bufferList = new BufferList();

    // Prepare for receiving first frame
    this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
    this.fragmentationOpcode = 0;
    this.frameQueue = [];

    // Various bits of connection state
    this.connected = true;
    this.waitingForCloseResponse = false;

    this.closeTimeout = this.config.closeTimeout;
    this.assembleFragments = this.config.assembleFragments;

    this.socket.on('data', this.handleSocketData.bind(this));
    this.socket.on('end', this.handleSocketEnd.bind(this));
    this.socket.on('close', this.handleSocketClose.bind(this));

    this._closeTimerHandler = this.handleCloseTimer.bind(this);
};

WebSocketConnection.CLOSE_REASON_NORMAL = 1000;
WebSocketConnection.CLOSE_REASON_GOING_AWAY = 1001;
WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR = 1002;
WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT = 1003;
WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_LARGE = 1004;

util.inherits(WebSocketConnection, EventEmitter);

extend(WebSocketConnection.prototype, {
    handleSocketData: function(data) {
        this.bufferList.write(data);

        // currentFrame.addData returns true if all data necessary to parse
        // the frame was available.  It returns false if we are waiting for
        // more data to come in on the wire.
        while (this.currentFrame.addData(this.bufferList, this.fragmentationOpcode)) {

            // Handle possible parsing errors
            if (this.currentFrame.protocolError) {
                // Something bad happened.. get rid of this client.
                this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, this.currentFrame.dropReason);
                return;
            }
            else if (this.currentFrame.frameTooLarge) {
                this.drop(WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_LARGE, this.currentFrame.dropReason);
                return;
            }

            if (!this.assembleFragments) {
                this.emit('frame', this.currentFrame);
            }
            this.processFrame(this.currentFrame);
            this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
        }
    },

    handleSocketEnd: function() {
        this.socket.end();
    },

    handleSocketClose: function(hadError) {
        this.socketHadError = hadError;
        this.connected = false;
        if (!this.closeEventEmitted) {
            this.closeEventEmitted = true;
            this.emit('close', this);
        }
    },

    close: function() {
        if (this.connected) {
            this.setCloseTimer();
            this.sendCloseFrame();
            this.connected = false;
        }
    },

    drop: function(closeReason, reasonText) {
        if (typeof(closeReason) !== 'number') {
            closeReason = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR;
        }
        var logText = "WebSocket: Dropping Connection. Code: " + closeReason.toString(10);
        if (reasonText) {
            logText += (" - " + reasonText);
        }
        console.error((new Date()) + " " + logText);
        this.sendCloseFrame(closeReason, reasonText);
        this.connected = false;
        this.socket.end();
    },

    setCloseTimer: function() {
        this.clearCloseTimer();
        this.waitingForCloseResponse = true;
        this.closeTimer = setTimeout(this._closeTimerHandler, this.closeTimeout);
    },

    clearCloseTimer: function() {
        if (this.closeTimer) {
            clearTimeout(this.closeTimer);
            this.waitingForCloseResponse = false;
            this.closeTimer = null;
        }
    },

    handleCloseTimer: function() {
        this.closeTimer = null;
        if (this.waitingForCloseResponse) {
            this.waitingForCloseResponse = false;
            this.socket.end();
        }
    },

    processFrame: function(frame) {
        var i;
        var currentFrame;
        var message;

        switch(frame.opcode) {
            case 0x02: // WebSocketFrame.BINARY_FRAME
                if (frame.fin) {
                    // Complete single-frame message received
                    this.emit('message', {
                        type: 'binary',
                        binaryData: frame.binaryPayload
                    });
                }
                else if (this.frameQueue.length === 0) {
                    if (this.assembleFragments) {
                        // beginning of a fragmented message
                        this.frameQueue.push(frame);
                        this.fragmentationOpcode = frame.opcode;
                    }
                }
                else {
                    this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
                              "Illegal BINARY_FRAME received in the middle of a fragmented message.  Expected a continuation or control frame.");
                    return;
                }
                break;
            case 0x01: // WebSocketFrame.TEXT_FRAME
                if (frame.fin) {
                    // Complete single-frame message received
                    this.emit('message', {
                        type: 'utf8',
                        utf8Data: frame.binaryPayload.toString('utf8')
                    });
                }
                else if (this.frameQueue.length === 0) {
                    if (this.assembleFragments) {
                        // beginning of a fragmented message
                        this.frameQueue.push(frame);
                        this.fragmentationOpcode = frame.opcode;
                    }
                }
                else {
                    this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
                              "Illegal TEXT_FRAME received in the middle of a fragmented message.  Expected a continuation or control frame.");
                    return;
                }
                break;
            case 0x00: // WebSocketFrame.CONTINUATION
                if (!this.assembleFragments) {
                    return;
                }
                this.frameQueue.push(frame);
                if (frame.fin) {
                    // end of fragmented message, so we process the whole
                    // message now.  We also have to decode the utf-8 data
                    // for text frames after combining all the fragments.
                    var totalLength = 0;
                    var bytesCopied = 0;
                    this.frameQueue.forEach(function (currentFrame) {
                        totalLength += currentFrame.binaryData.length;
                    });
                    if (totalLenth > this.maxMessageSize) {
                        this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
                                  "Maximum message size exceeded.");
                        this.frameQueue = [];
                        return;
                    }
                    var binaryData = new Buffer(totalLength);
                    this.frameQueue.forEach(function (currentFrame) {
                        currentFrame.binaryData.copy(binaryData, bytesCopied);
                        bytesCopied += currentFrame.binaryData.length;
                    });
                    this.frameQueue = [];

                    switch (this.frameQueue[0].opcode) {
                        case 0x02: // WebSocketOpcode.BINARY_FRAME
                            this.emit('message', {
                                type: 'binary',
                                binaryData: binaryData
                            });
                            break;
                        case 0x01: // WebSocketOpcode.TEXT_FRAME
                            this.emit('message', {
                                type: 'utf8',
                                utf8Data: binaryData.toString('utf8')
                            });
                            break;
                        default:
                            this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
                                      "Unexpected first opcode in fragmentation sequence: 0x" + this.frameQueue[0].opcode.toString(16));
                            return;
                    }
                }
                break;
            case 0x09: // WebSocketFrame.PING
                this.pong(frame.binaryPayload);
                break;
            case 0x0A: // WebSocketFrame.PONG
                break;
            case 0x08: // WebSocketFrame.CONNECTION_CLOSE
                if (this.waitingForCloseResponse) {
                    // Got response to our request to close the connection.
                    // Close is complete, so we just hang up.
                    this.clearCloseTimer();
                    this.waitingForCloseResponse = false;
                    this.socket.end();
                }
                else {
                    // Got request from other party to close connection.
                    // Send back acknowledgement and then hang up.
                    if (frame.closeStatus !== WebSocketConnection.CLOSE_REASON_NORMAL) {
                        var logCloseError;
                        switch(frame.closeStatus) {
                            case WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR:
                                logCloseError = "Remote peer closed connection: Protocol Error";
                                break;
                            case WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_LARGE:
                                logCloseError = "Remote peer closed connection: Received Message Too Large";
                                break;
                            case WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT:
                                logCloseError = "Remote peer closed connection: Unprocessable Input";
                                break;
                            case WebSocketConnection.CLOSE_REASON_GOING_AWAY:
                                logCloseError = "Remote peer closed connection: Going Away";
                                break;
                            default:
                                logCloseError = "Remote peer closed connection: Status code " + frame.closeStatus.toString(10);
                                break;
                        }
                        if (frame.binaryPayload) {
                            logCloseError += (" - Description Provided: " + frame.binaryPayload.toString('utf8'));
                        }
                        console.error((new Date()) + " " + logCloseError);
                    }
                    this.sendCloseFrame(WebSocketConnection.CLOSE_REASON_NORMAL);
                    this.socket.end();
                }
                break;
            default:
                this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
                          "Unrecognized Opcode: 0x" + frame.opcode.toString(16));
                break;
        }
    },

    sendUTF: function(data) {
        if (this.connected && this.socket.writable && data) {
            data = new Buffer(data);
            var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
            frame.opcode = 0x01; // WebSocketOpcode.TEXT_FRAME
            frame.binaryPayload = new Buffer(data, 'utf8');
            this.fragmentAndSend(frame);
        }
    },

    sendBytes: function(data) {
        if (this.connected && this.socket.writable) {
            var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
            frame.opcode = 0x02; // WebSocketOpcode.BINARY_FRAME
            frame.binaryPayload = data;
            this.fragmentAndSend(frame);
        }
    },

    ping: function() {
        if (this.connected && this.socket.writable) {
            var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
            frame.opcode = 0x09; // WebSocketOpcode.PING
            frame.fin = true;
            this.sendFrame(frame);
        }
    },

    // Pong frames have to echo back the contents of the data portion of the
    // ping frame exactly, byte for byte.
    pong: function(binaryPayload) {
        if (this.connected && this.socket.writable) {
            var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
            frame.opcode = 0x0A; // WebSocketOpcode.PONG
            frame.binaryPayload = binaryPayload;
            frame.fin = true;
            this.sendFrame(frame);
        }
    },

    fragmentAndSend: function(frame) {
        if (frame.opcode > 0x07) {
            throw new Error("You cannot fragment control frames.");
        }

        var threshold = this.config.fragmentationThreshold;
        var length = frame.binaryPayload.length;

        if (this.config.fragmentOutgoingMessages && frame.binaryPayload && length > threshold) {
            var numFragments = Math.ceil(length / threshold);
            for (var i=1; i <= numFragments; i++) {
                var currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);

                // continuation opcode except for first frame.
                currentFrame.opcode = (i === 1) ? frame.opcode : 0x00;

                // fin set on last frame only
                currentFrame.fin = (i === numFragments);

                // length is likely to be shorter on the last fragment
                var currentLength = (i === numFragments) ? length - (threshold * (i-1)) : threshold;
                var sliceStart = threshold * (i-1);

                // Slice the right portion of the original payload
                currentFrame.binaryPayload = frame.binaryPayload.slice(sliceStart, sliceStart + currentLength);

                this.sendFrame(currentFrame);
            }
        }
        else {
            frame.fin = true;
            this.sendFrame(frame);
        }
    },

    sendCloseFrame: function(reasonCode, reasonText) {
        if (this.connected && this.socket.writable) {
            var reasonLength = 0;
            if (typeof(reasonCode) !== 'number') {
                reasonCode = WebSocketConnection.CLOSE_REASON_NORMAL;
            }
            if (typeof(reasonText) === 'string') {
                reasonLength = Buffer.byteLength(reasonText, 'utf8');
            }
            var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
            frame.fin = true;
            frame.opcode = 0x08; // WebSocketOpcode.CONNECTION_CLOSE
            frame.closeStatus = reasonCode;
            if (reasonText) {
                frame.binaryPayload = new Buffer(reasonText, 'utf8');
            }

            this.sendFrame(frame);
        }
    },

    sendFrame: function(frame) {
        frame.mask = this.maskOutgoingPackets;
        this.socket.write(frame.toBuffer());
    }
});

module.exports = WebSocketConnection;<commit_msg>Removing unused variable declaration.<commit_after>var extend = require('./utils').extend;
var crypto = require('crypto');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var WebSocketFrame = require('./WebSocketFrame');
var BufferList = require('../vendor/FastBufferList');

function WebSocketConnection(socket, extensions, protocol, maskOutgoingPackets, config) {
    this.config = config;
    this.socket = socket;
    this.protocol = protocol;
    this.extensions = extensions;
    this.remoteAddress = socket.remoteAddress;

    // We have to mask outgoing packets if we're acting as a WebSocket client.
    this.maskOutgoingPackets = maskOutgoingPackets;

    // We re-use the same buffers for the mask and frame header for all frames
    // received on each connection to avoid a small memory allocation for each
    // frame.
    this.maskBytes = new Buffer(4);
    this.frameHeader = new Buffer(10);

    // the BufferList will handle the data streaming in
    this.bufferList = new BufferList();

    // Prepare for receiving first frame
    this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
    this.fragmentationOpcode = 0;
    this.frameQueue = [];

    // Various bits of connection state
    this.connected = true;
    this.waitingForCloseResponse = false;

    this.closeTimeout = this.config.closeTimeout;
    this.assembleFragments = this.config.assembleFragments;

    this.socket.on('data', this.handleSocketData.bind(this));
    this.socket.on('end', this.handleSocketEnd.bind(this));
    this.socket.on('close', this.handleSocketClose.bind(this));

    this._closeTimerHandler = this.handleCloseTimer.bind(this);
};

WebSocketConnection.CLOSE_REASON_NORMAL = 1000;
WebSocketConnection.CLOSE_REASON_GOING_AWAY = 1001;
WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR = 1002;
WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT = 1003;
WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_LARGE = 1004;

util.inherits(WebSocketConnection, EventEmitter);

extend(WebSocketConnection.prototype, {
    handleSocketData: function(data) {
        this.bufferList.write(data);

        // currentFrame.addData returns true if all data necessary to parse
        // the frame was available.  It returns false if we are waiting for
        // more data to come in on the wire.
        while (this.currentFrame.addData(this.bufferList, this.fragmentationOpcode)) {

            // Handle possible parsing errors
            if (this.currentFrame.protocolError) {
                // Something bad happened.. get rid of this client.
                this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, this.currentFrame.dropReason);
                return;
            }
            else if (this.currentFrame.frameTooLarge) {
                this.drop(WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_LARGE, this.currentFrame.dropReason);
                return;
            }

            if (!this.assembleFragments) {
                this.emit('frame', this.currentFrame);
            }
            this.processFrame(this.currentFrame);
            this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
        }
    },

    handleSocketEnd: function() {
        this.socket.end();
    },

    handleSocketClose: function(hadError) {
        this.socketHadError = hadError;
        this.connected = false;
        if (!this.closeEventEmitted) {
            this.closeEventEmitted = true;
            this.emit('close', this);
        }
    },

    close: function() {
        if (this.connected) {
            this.setCloseTimer();
            this.sendCloseFrame();
            this.connected = false;
        }
    },

    drop: function(closeReason, reasonText) {
        if (typeof(closeReason) !== 'number') {
            closeReason = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR;
        }
        var logText = "WebSocket: Dropping Connection. Code: " + closeReason.toString(10);
        if (reasonText) {
            logText += (" - " + reasonText);
        }
        console.error((new Date()) + " " + logText);
        this.sendCloseFrame(closeReason, reasonText);
        this.connected = false;
        this.socket.end();
    },

    setCloseTimer: function() {
        this.clearCloseTimer();
        this.waitingForCloseResponse = true;
        this.closeTimer = setTimeout(this._closeTimerHandler, this.closeTimeout);
    },

    clearCloseTimer: function() {
        if (this.closeTimer) {
            clearTimeout(this.closeTimer);
            this.waitingForCloseResponse = false;
            this.closeTimer = null;
        }
    },

    handleCloseTimer: function() {
        this.closeTimer = null;
        if (this.waitingForCloseResponse) {
            this.waitingForCloseResponse = false;
            this.socket.end();
        }
    },

    processFrame: function(frame) {
        var i;
        var message;

        switch(frame.opcode) {
            case 0x02: // WebSocketFrame.BINARY_FRAME
                if (frame.fin) {
                    // Complete single-frame message received
                    this.emit('message', {
                        type: 'binary',
                        binaryData: frame.binaryPayload
                    });
                }
                else if (this.frameQueue.length === 0) {
                    if (this.assembleFragments) {
                        // beginning of a fragmented message
                        this.frameQueue.push(frame);
                        this.fragmentationOpcode = frame.opcode;
                    }
                }
                else {
                    this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
                              "Illegal BINARY_FRAME received in the middle of a fragmented message.  Expected a continuation or control frame.");
                    return;
                }
                break;
            case 0x01: // WebSocketFrame.TEXT_FRAME
                if (frame.fin) {
                    // Complete single-frame message received
                    this.emit('message', {
                        type: 'utf8',
                        utf8Data: frame.binaryPayload.toString('utf8')
                    });
                }
                else if (this.frameQueue.length === 0) {
                    if (this.assembleFragments) {
                        // beginning of a fragmented message
                        this.frameQueue.push(frame);
                        this.fragmentationOpcode = frame.opcode;
                    }
                }
                else {
                    this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
                              "Illegal TEXT_FRAME received in the middle of a fragmented message.  Expected a continuation or control frame.");
                    return;
                }
                break;
            case 0x00: // WebSocketFrame.CONTINUATION
                if (!this.assembleFragments) {
                    return;
                }
                this.frameQueue.push(frame);
                if (frame.fin) {
                    // end of fragmented message, so we process the whole
                    // message now.  We also have to decode the utf-8 data
                    // for text frames after combining all the fragments.
                    var totalLength = 0;
                    var bytesCopied = 0;
                    this.frameQueue.forEach(function (currentFrame) {
                        totalLength += currentFrame.binaryData.length;
                    });
                    if (totalLenth > this.maxMessageSize) {
                        this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
                                  "Maximum message size exceeded.");
                        this.frameQueue = [];
                        return;
                    }
                    var binaryData = new Buffer(totalLength);
                    this.frameQueue.forEach(function (currentFrame) {
                        currentFrame.binaryData.copy(binaryData, bytesCopied);
                        bytesCopied += currentFrame.binaryData.length;
                    });
                    this.frameQueue = [];

                    switch (this.frameQueue[0].opcode) {
                        case 0x02: // WebSocketOpcode.BINARY_FRAME
                            this.emit('message', {
                                type: 'binary',
                                binaryData: binaryData
                            });
                            break;
                        case 0x01: // WebSocketOpcode.TEXT_FRAME
                            this.emit('message', {
                                type: 'utf8',
                                utf8Data: binaryData.toString('utf8')
                            });
                            break;
                        default:
                            this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
                                      "Unexpected first opcode in fragmentation sequence: 0x" + this.frameQueue[0].opcode.toString(16));
                            return;
                    }
                }
                break;
            case 0x09: // WebSocketFrame.PING
                this.pong(frame.binaryPayload);
                break;
            case 0x0A: // WebSocketFrame.PONG
                break;
            case 0x08: // WebSocketFrame.CONNECTION_CLOSE
                if (this.waitingForCloseResponse) {
                    // Got response to our request to close the connection.
                    // Close is complete, so we just hang up.
                    this.clearCloseTimer();
                    this.waitingForCloseResponse = false;
                    this.socket.end();
                }
                else {
                    // Got request from other party to close connection.
                    // Send back acknowledgement and then hang up.
                    if (frame.closeStatus !== WebSocketConnection.CLOSE_REASON_NORMAL) {
                        var logCloseError;
                        switch(frame.closeStatus) {
                            case WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR:
                                logCloseError = "Remote peer closed connection: Protocol Error";
                                break;
                            case WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_LARGE:
                                logCloseError = "Remote peer closed connection: Received Message Too Large";
                                break;
                            case WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT:
                                logCloseError = "Remote peer closed connection: Unprocessable Input";
                                break;
                            case WebSocketConnection.CLOSE_REASON_GOING_AWAY:
                                logCloseError = "Remote peer closed connection: Going Away";
                                break;
                            default:
                                logCloseError = "Remote peer closed connection: Status code " + frame.closeStatus.toString(10);
                                break;
                        }
                        if (frame.binaryPayload) {
                            logCloseError += (" - Description Provided: " + frame.binaryPayload.toString('utf8'));
                        }
                        console.error((new Date()) + " " + logCloseError);
                    }
                    this.sendCloseFrame(WebSocketConnection.CLOSE_REASON_NORMAL);
                    this.socket.end();
                }
                break;
            default:
                this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR,
                          "Unrecognized Opcode: 0x" + frame.opcode.toString(16));
                break;
        }
    },

    sendUTF: function(data) {
        if (this.connected && this.socket.writable && data) {
            data = new Buffer(data);
            var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
            frame.opcode = 0x01; // WebSocketOpcode.TEXT_FRAME
            frame.binaryPayload = new Buffer(data, 'utf8');
            this.fragmentAndSend(frame);
        }
    },

    sendBytes: function(data) {
        if (this.connected && this.socket.writable) {
            var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
            frame.opcode = 0x02; // WebSocketOpcode.BINARY_FRAME
            frame.binaryPayload = data;
            this.fragmentAndSend(frame);
        }
    },

    ping: function() {
        if (this.connected && this.socket.writable) {
            var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
            frame.opcode = 0x09; // WebSocketOpcode.PING
            frame.fin = true;
            this.sendFrame(frame);
        }
    },

    // Pong frames have to echo back the contents of the data portion of the
    // ping frame exactly, byte for byte.
    pong: function(binaryPayload) {
        if (this.connected && this.socket.writable) {
            var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
            frame.opcode = 0x0A; // WebSocketOpcode.PONG
            frame.binaryPayload = binaryPayload;
            frame.fin = true;
            this.sendFrame(frame);
        }
    },

    fragmentAndSend: function(frame) {
        if (frame.opcode > 0x07) {
            throw new Error("You cannot fragment control frames.");
        }

        var threshold = this.config.fragmentationThreshold;
        var length = frame.binaryPayload.length;

        if (this.config.fragmentOutgoingMessages && frame.binaryPayload && length > threshold) {
            var numFragments = Math.ceil(length / threshold);
            for (var i=1; i <= numFragments; i++) {
                var currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);

                // continuation opcode except for first frame.
                currentFrame.opcode = (i === 1) ? frame.opcode : 0x00;

                // fin set on last frame only
                currentFrame.fin = (i === numFragments);

                // length is likely to be shorter on the last fragment
                var currentLength = (i === numFragments) ? length - (threshold * (i-1)) : threshold;
                var sliceStart = threshold * (i-1);

                // Slice the right portion of the original payload
                currentFrame.binaryPayload = frame.binaryPayload.slice(sliceStart, sliceStart + currentLength);

                this.sendFrame(currentFrame);
            }
        }
        else {
            frame.fin = true;
            this.sendFrame(frame);
        }
    },

    sendCloseFrame: function(reasonCode, reasonText) {
        if (this.connected && this.socket.writable) {
            var reasonLength = 0;
            if (typeof(reasonCode) !== 'number') {
                reasonCode = WebSocketConnection.CLOSE_REASON_NORMAL;
            }
            if (typeof(reasonText) === 'string') {
                reasonLength = Buffer.byteLength(reasonText, 'utf8');
            }
            var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config);
            frame.fin = true;
            frame.opcode = 0x08; // WebSocketOpcode.CONNECTION_CLOSE
            frame.closeStatus = reasonCode;
            if (reasonText) {
                frame.binaryPayload = new Buffer(reasonText, 'utf8');
            }

            this.sendFrame(frame);
        }
    },

    sendFrame: function(frame) {
        frame.mask = this.maskOutgoingPackets;
        this.socket.write(frame.toBuffer());
    }
});

module.exports = WebSocketConnection;<|endoftext|>


<commit_before>import React, { Component } from 'react';

class Review extends Component {
  constructor(props) {
    super(props);
    this.renderReviews = this.renderReviews.bind(this);
  }
  renderReviews() {
    const { reviews } = this.props;
    if (!reviews.length) {
      return (

 No Reviews yet.

      );
    }
    return reviews.map((review, index) => (

account_circle{ review.userId }
                             { review.createdAt.split('T')[0] }

                                { review.review }

    ));
  }
  render() {
    return (

Reviews

                    { this.renderReviews() };

    );
  }
}

export default Review;

<commit_msg>Add user's names to review<commit_after>import React, { Component } from 'react';

class Review extends Component {
  constructor(props) {
    super(props);
    this.renderReviews = this.renderReviews.bind(this);
  }
  renderReviews() {
    const { reviews } = this.props;
    if (!reviews.length) {
      return (

 No Reviews yet.

      );
    }
    return reviews.map((review, index) => (

account_circle{ `${review.userReviews.firstName} ${review.userReviews.lastName}` }
                             { review.createdAt.split('T')[0] }

                                { review.review }

    ));
  }
  render() {
    return (

Reviews

                    { this.renderReviews() };

    );
  }
}

export default Review;

<|endoftext|>


<commit_before>var http = require( 'http' );
var async = require( 'async' );
var person = require( './Person' );
var GetData = require( './Request' );
var buildStatus = require( './Builds' );
var file = require( './FileIO' );
var userInfo = require( './getUsers' );
var _ = require( 'lodash' );
var checkdouble = require( './checkUsername' );
var redis = require( 'redis-url' ).connect( process.env.REDISTOGO_URL );
var excludedBuilds = require( 'config' ).ExcludeBuilds;
var Failed = require('./lastBuild');
var builds = "";
var buildID = "";
var buildstatus = [];
var change = [];
var usersarray = {};
var failedArray = {};
var fileio = new file();
function getPoints( buildId, Person ) {
    async.series( [
        function ( callback ) {
            GetData( "/httpAuth/app/rest/builds/id:" + buildId, function ( result ) {
                builds = result;
                callback( null, builds );
            });
        },
        function ( callback ) {
            change = [];
            GetData( builds['changes']['href'], function ( result ) {
                for ( var i = 0; i < result['change'].length; i++ ) {
                    if ( result['change'] != null ) {
                        change.push( result['change'][i]['href'] );
                    } else {
                        change.push( null );
                    }
                }
                callback( null, null );

            });
        },
        function ( callback ) {
            async.mapSeries( change, getName, function ( error, names ) {
                callback( null, names );
            });
        },
        function(callback) {
            Failed(function(result) {
                callback(null,result);
            });

        }
    ],
        function ( err, results ) {
            /*try {*/

            redis.get( "obj", function ( er, data ) {
                if ( data ) {
                    var tempfile = JSON.parse( data );
                    for ( var user in tempfile ) {
                        usersarray[user] = new person( tempfile[user]['name'] );
                        usersarray[user].lastdate = tempfile[user]['lastdate'];
                        usersarray[user].build = tempfile[user]['build'];
                        usersarray[user].gravUrl = tempfile[user]['gravUrl'];
                        usersarray[user].status = tempfile[user]['status'];
                        usersarray[user].streak = tempfile[user]['streak'];
                        usersarray[user].points = tempfile[user]['points'];

                    }
                }

                var userName;

                buildstatus[0] = new buildStatus( results[0]['buildType']['name'], results[0]['status'], results[0]['buildType']['id'], results[0]['startDate'], results[0]['finishDate'] );
                var uniqpersons = _.uniq( results[2] );

                for ( var k = 0; k < uniqpersons.length; k++ ) {
                    if ( uniqpersons[k] != "undefined" && uniqpersons[k] != null ) {
                        userName = checkdouble( uniqpersons[k] );
                        if ( !usersarray[uniqpersons[k]] ) {

                            usersarray[userName] = new person( userName );
                        }
                    } else {
                        userName = null;
                    }

                    if ( usersarray[userName] ) {
                        if ( results[0] != null && !_.contains( excludedBuilds, buildstatus[0]['id'] ) ) {
                            if ( buildstatus[0]['status'] == "SUCCESS" ) {
                                usersarray[userName].addPoints( 1 );
                                usersarray[userName].lastdate = ( buildstatus[0]['finishdate'] );
                                usersarray[userName].build.push( buildstatus[0]['id'] );
                                if (usersarray[userName].streak5 == true) {
                                    usersarray[userName].streak5 = false;
                                }
                                if ( usersarray[userName].status && usersarray[userName].status == "Success" ) {
                                    if ( usersarray[userName].streak < 5 ) {
                                        usersarray[userName].streakAdd();
                                    }
                                    if ( usersarray[userName].streak >= 5 ) {
                                        usersarray[userName].streak5=true;
                                        usersarray[userName].streakReset();
                                        usersarray[userName].addPoints( 4 );
                                    }
                                }
                                usersarray[userName].status = "Success";
                            } else if ( buildstatus[0]['status'] == "FAILURE" && !_.contains( excludedBuilds, buildstatus[0]['id'] ) ) {
                                usersarray[userName].substractPoints( 4 );
                                usersarray[userName].lastdate = ( buildstatus[0]['finishdate'] );
                                usersarray[userName].build.push( buildstatus[0]['id'] );
                                usersarray[userName].status = "Failed";
                                usersarray[userName].streakReset();
                                usersarray[userName].streak5 = false;
                            }
                        }
                    }

                }

                userInfo( function ( er2, profiles ) {
                    for ( var user in usersarray ) {
                        for ( var i = 0; i < profiles.length; i++ ) {
                            if ( usersarray[user]['name'] == profiles[i]['username'] ) {
                                usersarray[user].gravUrl = profiles[i]['img'];
                            }
                        }
                    }
                    for (i=0;i<results[3].length;i++) {
                        failedArray[results[3][i]] = usersarray[results[3][i]];
                    }
                    redis.set("failed", JSON.stringify(failedArray));
                    redis.set( "obj", JSON.stringify( usersarray ) );
                    //fileio.writeFile( "temp/score.txt", JSON.stringify( usersarray ) );
                    console.log( usersarray );
                    Person( err, usersarray );
                });
            });
        });
}
module.exports = getPoints;
/*function getChanges( url, changes ) {
    GetData( url, function ( result ) {
        if ( result['count'] != 0 ) {
            changes( null, result['change'][0] );
        } else {
            changes( null, null );
        }
    });
}*/

function getName( url, names ) {
    if ( url != null ) {
        GetData( url, function ( result ) {
            if ( result.files.file.length != 0 ) {
                if ( result['user'] ) {
                    names( null, result['user']['username'] );
                } else {
                    names( null, result["username"] );
                }
            }
            else {
                names( null, null );
            }
        });
    } else {
        names( null, null );
    }
}
/*function getBuilds( url, buildinfo ) {
    GetData( url, function ( result ) {
        buildinfo( null, result );
    });
}*/

<commit_msg>streak 5 reset disabled when still successful build<commit_after>var http = require( 'http' );
var async = require( 'async' );
var person = require( './Person' );
var GetData = require( './Request' );
var buildStatus = require( './Builds' );
var file = require( './FileIO' );
var userInfo = require( './getUsers' );
var _ = require( 'lodash' );
var checkdouble = require( './checkUsername' );
var redis = require( 'redis-url' ).connect( process.env.REDISTOGO_URL );
var excludedBuilds = require( 'config' ).ExcludeBuilds;
var Failed = require('./lastBuild');
var builds = "";
var buildID = "";
var buildstatus = [];
var change = [];
var usersarray = {};
var failedArray = {};
var fileio = new file();
function getPoints( buildId, Person ) {
    async.series( [
        function ( callback ) {
            GetData( "/httpAuth/app/rest/builds/id:" + buildId, function ( result ) {
                builds = result;
                callback( null, builds );
            });
        },
        function ( callback ) {
            change = [];
            GetData( builds['changes']['href'], function ( result ) {
                for ( var i = 0; i < result['change'].length; i++ ) {
                    if ( result['change'] != null ) {
                        change.push( result['change'][i]['href'] );
                    } else {
                        change.push( null );
                    }
                }
                callback( null, null );

            });
        },
        function ( callback ) {
            async.mapSeries( change, getName, function ( error, names ) {
                callback( null, names );
            });
        },
        function(callback) {
            Failed(function(result) {
                callback(null,result);
            });

        }
    ],
        function ( err, results ) {
            /*try {*/

            redis.get( "obj", function ( er, data ) {
                if ( data ) {
                    var tempfile = JSON.parse( data );
                    for ( var user in tempfile ) {
                        usersarray[user] = new person( tempfile[user]['name'] );
                        usersarray[user].lastdate = tempfile[user]['lastdate'];
                        usersarray[user].build = tempfile[user]['build'];
                        usersarray[user].gravUrl = tempfile[user]['gravUrl'];
                        usersarray[user].status = tempfile[user]['status'];
                        usersarray[user].streak = tempfile[user]['streak'];
                        usersarray[user].points = tempfile[user]['points'];

                    }
                }

                var userName;

                buildstatus[0] = new buildStatus( results[0]['buildType']['name'], results[0]['status'], results[0]['buildType']['id'], results[0]['startDate'], results[0]['finishDate'] );
                var uniqpersons = _.uniq( results[2] );

                for ( var k = 0; k < uniqpersons.length; k++ ) {
                    if ( uniqpersons[k] != "undefined" && uniqpersons[k] != null ) {
                        userName = checkdouble( uniqpersons[k] );
                        if ( !usersarray[uniqpersons[k]] ) {

                            usersarray[userName] = new person( userName );
                        }
                    } else {
                        userName = null;
                    }

                    if ( usersarray[userName] ) {
                        if ( results[0] != null && !_.contains( excludedBuilds, buildstatus[0]['id'] ) ) {
                            if ( buildstatus[0]['status'] == "SUCCESS" ) {
                                usersarray[userName].addPoints( 1 );
                                usersarray[userName].lastdate = ( buildstatus[0]['finishdate'] );
                                usersarray[userName].build.push( buildstatus[0]['id'] );
                                if ( usersarray[userName].status && usersarray[userName].status == "Success" ) {
                                    if ( usersarray[userName].streak < 5 ) {
                                        usersarray[userName].streakAdd();
                                    }
                                    if ( usersarray[userName].streak >= 5 ) {
                                        usersarray[userName].streak5=true;
                                        usersarray[userName].streakReset();
                                        usersarray[userName].addPoints( 4 );
                                    }
                                }
                                usersarray[userName].status = "Success";
                            } else if ( buildstatus[0]['status'] == "FAILURE" && !_.contains( excludedBuilds, buildstatus[0]['id'] ) ) {
                                usersarray[userName].substractPoints( 4 );
                                usersarray[userName].lastdate = ( buildstatus[0]['finishdate'] );
                                usersarray[userName].build.push( buildstatus[0]['id'] );
                                usersarray[userName].status = "Failed";
                                usersarray[userName].streakReset();
                                usersarray[userName].streak5 = false;
                            }
                        }
                    }

                }

                userInfo( function ( er2, profiles ) {
                    for ( var user in usersarray ) {
                        for ( var i = 0; i < profiles.length; i++ ) {
                            if ( usersarray[user]['name'] == profiles[i]['username'] ) {
                                usersarray[user].gravUrl = profiles[i]['img'];
                            }
                        }
                    }
                    for (i=0;i<results[3].length;i++) {
                        failedArray[results[3][i]] = usersarray[results[3][i]];
                    }
                    redis.set("failed", JSON.stringify(failedArray));
                    redis.set( "obj", JSON.stringify( usersarray ) );
                    //fileio.writeFile( "temp/score.txt", JSON.stringify( usersarray ) );
                    console.log( usersarray );
                    Person( err, usersarray );
                });
            });
        });
}
module.exports = getPoints;
/*function getChanges( url, changes ) {
    GetData( url, function ( result ) {
        if ( result['count'] != 0 ) {
            changes( null, result['change'][0] );
        } else {
            changes( null, null );
        }
    });
}*/

function getName( url, names ) {
    if ( url != null ) {
        GetData( url, function ( result ) {
            if ( result.files.file.length != 0 ) {
                if ( result['user'] ) {
                    names( null, result['user']['username'] );
                } else {
                    names( null, result["username"] );
                }
            }
            else {
                names( null, null );
            }
        });
    } else {
        names( null, null );
    }
}
/*function getBuilds( url, buildinfo ) {
    GetData( url, function ( result ) {
        buildinfo( null, result );
    });
}*/

<|endoftext|>


<commit_before>this.interval = null;
this.h = 0;
this.m = 0;
this.s = 0;
this.publisher = false;

var start = function(sendMessageToParticipants){
  if(this.interval  && this.interval != null){
    stop();
  }
  this.interval = setInterval(function(){tick()},1000);
  if(sendMessageToParticipants == true){
    displayMessage(getLocalUser(), "started");
    sendMessage("started");
    this.publisher = true;
  }
};

var stop = function(sendMessageToParticipants){
  window.clearInterval(interval);
  if(sendMessageToParticipants == true){
   displayMessage(getLocalUser(), "stopped");
   sendMessage("stopped");
   this.publisher = false;
 }
};

var reset = function(sendMessageToParticipants){
 this.h = 0;
 this.m = 0;
 this.s = 0;

 displayTime();
 if(sendMessageToParticipants == true){
  displayMessage(getLocalUser(), "reset");
  sendMessage("reset");
}
};

var getLocalUser =function(){
  return gapi.hangout.getLocalParticipant();
};

var tick = function(){
  this.s += 1;
  if(this.s >= 60)
  {
    this.m += 1;
    this.s = 0;
    if(this.publisher == true){
      sendMessage("");
    }
  }

  if(this.m >= 60){
    this.h += 1;
    this.m = 0;
  }

  displayTime();
};

var displayTime = function(message){

  if(message){
    this.h = message.hours
    this.m = message.minutes
    this.s = message.seconds
  }

  html = "";
  html += getText(this.h)
  html += ":";

  html += getText(this.m)
  html += ":";

  html += getText(this.s)

  document.getElementById('timer').innerText = html;
};

var getText = function(n){
  var str  = "";
  if(n<10)
    str += "0";
  str += n;
  return str;
};

var sendMessage = function(msg){
  var message = {"action":msg, "hours":this.h, "minutes":this.m, "seconds":this.s};
  msg = JSON.stringify(message);
  gapi.hangout.data.sendMessage(msg)
  console.log(msg);
};

var getUser = function(){
  return "user";
};

var init = function(){
 console.log('init called');
 gapi.hangout.onApiReady.add(
  function(eventObj) {
    if (eventObj.isApiReady) {
      try {
        gapi.hangout.data.onMessageReceived.add(
          function(msg){
           console.log('message received');
           var participant = gapi.hangout.getParticipantById(msg.senderId);
           var message = JSON.parse(msg.message);

           displayMessage(participant, message.action);

           displayTime(message);

           if(msg.message == "started" || msg.message == ""){
            start();
          }

          if(msg.message == "stopped"){
            stop();
          }

          if(msg.message == "reset"){
           reset();
         });

        console.log('message handler registered');
      } catch (e) {
        console.log('init:ERROR');
        console.log(e);
      }
    }
  });
};

var displayMessage = function(participant, message){
  var messageArea =   document.getElementById('messageArea');
  messageArea.innerText = messageArea.innerHTML + "\n" + participant.person.displayName + " : " + message ;
  messageArea.scrollTop = messageArea.scrollTop + 50;
};

gadgets.util.registerOnLoadHandler(init);
console.log('script loaded'); <commit_msg>fixed js error<commit_after>this.interval = null;
this.h = 0;
this.m = 0;
this.s = 0;
this.publisher = false;

var start = function(sendMessageToParticipants){
  if(this.interval  && this.interval != null){
    stop();
  }
  this.interval = setInterval(function(){tick()},1000);
  if(sendMessageToParticipants == true){
    displayMessage(getLocalUser(), "started");
    sendMessage("started");
    this.publisher = true;
  }
};

var stop = function(sendMessageToParticipants){
  window.clearInterval(interval);
  if(sendMessageToParticipants == true){
   displayMessage(getLocalUser(), "stopped");
   sendMessage("stopped");
   this.publisher = false;
 }
};

var reset = function(sendMessageToParticipants){
 this.h = 0;
 this.m = 0;
 this.s = 0;

 displayTime();
 if(sendMessageToParticipants == true){
  displayMessage(getLocalUser(), "reset");
  sendMessage("reset");
}
};

var getLocalUser =function(){
  return gapi.hangout.getLocalParticipant();
};

var tick = function(){
  this.s += 1;
  if(this.s >= 60)
  {
    this.m += 1;
    this.s = 0;
    if(this.publisher == true){
      sendMessage("");
    }
  }

  if(this.m >= 60){
    this.h += 1;
    this.m = 0;
  }

  displayTime();
};

var displayTime = function(message){

  if(message){
    this.h = message.hours
    this.m = message.minutes
    this.s = message.seconds
  }

  html = "";
  html += getText(this.h)
  html += ":";

  html += getText(this.m)
  html += ":";

  html += getText(this.s)

  document.getElementById('timer').innerText = html;
};

var getText = function(n){
  var str  = "";
  if(n<10)
    str += "0";
  str += n;
  return str;
};

var sendMessage = function(msg){
  var message = {"action":msg, "hours":this.h, "minutes":this.m, "seconds":this.s};
  msg = JSON.stringify(message);
  gapi.hangout.data.sendMessage(msg)
  console.log(msg);
};

var getUser = function(){
  return "user";
};

var init = function(){
 console.log('init called');
 gapi.hangout.onApiReady.add(
  function(eventObj) {
    if (eventObj.isApiReady) {
      try {
        gapi.hangout.data.onMessageReceived.add(
          function(msg){
           console.log('message received');
           var participant = gapi.hangout.getParticipantById(msg.senderId);
           var message = JSON.parse(msg.message);

           displayMessage(participant, message.action);

           displayTime(message);

           if(message.action == "started" || message.action == ""){
            start();
          }

          if(message.action == "stopped"){
            stop();
          }

          if(message.action == "reset"){
           reset();
         });

        console.log('message handler registered');
      } catch (e) {
        console.log('init:ERROR');
        console.log(e);
      }
    }
  });
};

var displayMessage = function(participant, message){
  var messageArea =   document.getElementById('messageArea');
  messageArea.innerText = messageArea.innerHTML + "\n" + participant.person.displayName + " : " + message ;
  messageArea.scrollTop = messageArea.scrollTop + 50;
};

gadgets.util.registerOnLoadHandler(init);
console.log('script loaded'); <|endoftext|>