<commit_before>import React from 'react';
import { Panel, PanelBody } from '../libs/bootstrap/panel';
import globals from './globals';
import { AuditIndicators, AuditDetail, AuditMixin } from './audit';
import { ProjectBadge } from './image';
import { StatusLabel } from './statuslabel';

const File = React.createClass({
    propTypes: {
        context: React.PropTypes.object, // File object being displayed
    },

    mixins: [AuditMixin],

    render: function () {
        const { context } = this.props;
        const itemClass = globals.itemClass(context, 'view-item');
        const altacc = (context.alternate_accessions && context.alternate_accessions.length) ? context.alternate_accessions.join(', ') : null;

        // Make array of superceded_by accessions
        let supersededBys = [];
        if (context.superseded_by && context.superseded_by.length) {
            supersededBys = context.superseded_by.map(supersededBy => globals.atIdToAccession(supersededBy));
        }

        let pipelines = [];
        if (context.analysis_step_version && context.analysis_step_version.pipelines && context.analysis_step_version.pipelines.length) {
            pipelines = context.analysis_step_version.pipelines;
        }

        return (

{context.accession}{' / '}{`${context.file_format}${context.file_format_type ? ` (${context.file_format_type})` : ''}`}

                        {altacc ?
Replaces {altacc}
 : null}
                        {supersededBys.length ?
Superseded by {supersededBys.join(', ')}
 : null}

                            {context.status ?

                                    <StatusLabel title="Status" status={context.status} />

                            : null}
                            {context.audit ? <AuditIndicators audits={context.audit} id="file-audit" /> : null}

                <AuditDetail context={context} except={context['@id']} id="file-audit" />
                <Panel addClasses="data-display">
                    <PanelBody addClasses="panel-body-with-header">

Summary

Dataset

{globals.atIdToAccession(context.dataset)}

                                    {context.replicate ?

Biological replicate(s)

{`[${context.replicate.biological_replicate_number}]`}

                                    : (context.biological_replicates && context.biological_replicates.length ?

Biological replicate(s)

{`[${context.biological_replicates.join(', ')}]`}

                                    : null)}

                                    {context.replicate ?

Technical replicate

{context.replicate.technical_replicate_number}

                                    : (context.biological_replicates && context.biological_replicates.length ?

Technical replicate

{'-'}

                                    : null)}

                                    {pipelines.length ?

Technical replicate

                                                {pipelines.map((pipeline, i) =>

                                                        {i > 0 ? {','}
 : null}
                                                        {pipeline.title}

                                                )}

                                    : null}

Attribution

                                    <ProjectBadge award={context.award} addClasses="badge-heading" />

Lab

{context.lab.title}

                                    {context.award.pi && context.award.pi.lab ?

Award PI

{context.award.pi.lab.title}

                                    : null}

Submitted by

{context.submitted_by.title}

                                    {context.award.project ?

Project

{context.award.project}

                                    : null}

                    </PanelBody>
                </Panel>

        );
    },
});

globals.content_views.register(File, 'File');
<commit_msg>Adding more displayed properties<commit_after>import React from 'react';
import { Panel, PanelBody } from '../libs/bootstrap/panel';
import globals from './globals';
import { AuditIndicators, AuditDetail, AuditMixin } from './audit';
import { DbxrefList } from './dbxref';
import { ProjectBadge } from './image';
import { StatusLabel } from './statuslabel';

const File = React.createClass({
    propTypes: {
        context: React.PropTypes.object, // File object being displayed
    },

    mixins: [AuditMixin],

    render: function () {
        const { context } = this.props;
        const itemClass = globals.itemClass(context, 'view-item');
        const altacc = (context.alternate_accessions && context.alternate_accessions.length) ? context.alternate_accessions.join(', ') : null;

        // Make array of superceded_by accessions
        let supersededBys = [];
        if (context.superseded_by && context.superseded_by.length) {
            supersededBys = context.superseded_by.map(supersededBy => globals.atIdToAccession(supersededBy));
        }

        let pipelines = [];
        if (context.analysis_step_version && context.analysis_step_version.analysis_step.pipelines && context.analysis_step_version.analysis_step.pipelines.length) {
            pipelines = context.analysis_step_version.analysis_step.pipelines;
        }

        return (

{context.accession}{' / '}{`${context.file_format}${context.file_format_type ? ` (${context.file_format_type})` : ''}`}

                        {altacc ?
Replaces {altacc}
 : null}
                        {supersededBys.length ?
Superseded by {supersededBys.join(', ')}
 : null}

                            {context.status ?

                                    <StatusLabel title="Status" status={context.status} />

                            : null}
                            {context.audit ? <AuditIndicators audits={context.audit} id="file-audit" /> : null}

                <AuditDetail context={context} except={context['@id']} id="file-audit" />
                <Panel addClasses="data-display">
                    <PanelBody addClasses="panel-body-with-header">

Summary

Dataset

{globals.atIdToAccession(context.dataset)}

                                    {context.replicate ?

Biological replicate(s)

{`[${context.replicate.biological_replicate_number}]`}

                                    : (context.biological_replicates && context.biological_replicates.length ?

Biological replicate(s)

{`[${context.biological_replicates.join(', ')}]`}

                                    : null)}

                                    {context.replicate ?

Technical replicate

{context.replicate.technical_replicate_number}

                                    : (context.biological_replicates && context.biological_replicates.length ?

Technical replicate

{'-'}

                                    : null)}

                                    {pipelines.length ?

Pipelines

                                                {pipelines.map((pipeline, i) =>

                                                        {i > 0 ? {','}
 : null}
                                                        {pipeline.title}

                                                )}

                                    : null}

MD5sum

{context.md5sum}

                                    {context.content_md5sum ?

Content MD5sum

{context.content_md5sum}

                                    : null}

                                    {context.read_count ?

Read count

{context.read_count}

                                    : null}

                                    {context.file_size ?

File size

{context.file_size}

                                    : null}

                                    {context.mapped_read_length ?

Mapped read length

{context.mapped_read_length}

                                    : null}

Attribution

                                    <ProjectBadge award={context.award} addClasses="badge-heading" />

Lab

{context.lab.title}

                                    {context.award.pi && context.award.pi.lab ?

Award PI

{context.award.pi.lab.title}

                                    : null}

Submitted by

{context.submitted_by.title}

                                    {context.award.project ?

Project

{context.award.project}

                                    : null}

                                    {context.date_created ?

Date added

{context.date_created}

                                    : null}

                                    {context.dbxrefs && context.dbxrefs.length ?

External resources

<DbxrefList values={context.dbxrefs} />

                                    : null}

                    </PanelBody>
                </Panel>

        );
    },
});

globals.content_views.register(File, 'File');
<|endoftext|>


<commit_before>if (process.argv.indexOf('--no-auth') > -1 ){
  /**
   * Indicates when to run without requiring auth for API
   */
  GLOBAL.no_auth = true;
}

var express = require('express'),
    http = require('http'),
    path = require('path'),
	routes = require('./routes/routes'),
    mongoose = require('mongoose'),
    mongoStore = require('connect-mongo')(express);

var app = express();

// Le 2/9/2013, Phuong tried to fix cross-domain connections.
// The current solution is to allow CORS by overloading the middleware function:

var allowCrossDomain = function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
	res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With'); // Pierrick: needed by REST calls from angular

	// intercept OPTIONS method
    if('OPTIONS' == req.method) {
    	res.send(200); // force the server to treat such a request as a normal GET or POST request.
    }
    else {
    	next(); // otherwise, do anything else, on s'en fiche (dont care)
    }
}

// connect to the db:
 mongoose.connect('mongodb://localhost/sampledb');
//mongoose.connect('mongodb://localhost/sampledbTAM');
//mongoose.connect('mongodb://localhost/TAM');
// mongoose.connect('mongodb://localhost/tmpCURL');
mongoose.connection.on('open', function(){
	console.log("Connected to Mongoose") ;
});

keepSession = function (req, res, next) {
    var err = req.session.error,
        msg = req.session.success;
    delete req.session.error;
    delete req.session.success;
    res.locals.message = '';
    if (err) res.locals.message = '
' + err + '
';
    if (msg) res.locals.message = '
' + msg + '
';
    //console.log("res.locals"); console.log(res.locals);
    next();
}

var sessionStore = new mongoStore({db: mongoose.connections[0].db, clear_interval: 60}, function(){
                          console.log('connect mongodb session success...');
});
// configure all environments
app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon());
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());

    app.use(allowCrossDomain); //phuong added on 2/9/2013 for CORS problem!

	app.use(express.cookieParser('your secret here'));

	//app.use(express.session());
	app.use(express.session({
    	key : "camomile.sid",
    	secret: "123camomile",
    	cookie: {
    		//expires: new Date(Date.now() + 60 * 10000)
    		maxAge: 3*3600000 // 3 h resolved the prob encountered when one user is timeout
  		},
  		/*store: new mongoStore({ host: 'http://localhost/',
  			port: 27017,
  			db: 'session',
  			collection: 'sessions',
  			interval: 120000,
  			clear_interval : (10)//search db to clear the expired every 10 seconds
  			})*/
  		//store: new mongoStore({db: mongoose.connections[0].db})
  		store: sessionStore
    }));
	app.use(keepSession); //added

	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler());
}

//start routes:
routes.initialize(app);

//finally boot up the server:
http.createServer(app).listen(app.get('port'), process.env.IP, function(){
	console.log('Express server listening on port ' + app.get('port'));
	if(GLOBAL.no_auth == true){
		console.log('be careful: any user can access the data without authentication');
	}
});

<commit_msg>trying to fix the prob. of connect-mongo<commit_after>if (process.argv.indexOf('--no-auth') > -1 ){
  /**
   * Indicates when to run without requiring auth for API
   */
  GLOBAL.no_auth = true;
}

var express = require('express'),
    http = require('http'),
    path = require('path'),
	routes = require('./routes/routes'),
    mongoose = require('mongoose'),
    mongoStore = require('connect-mongo')(express);

var app = express();

// Le 2/9/2013, Phuong tried to fix cross-domain connections.
// The current solution is to allow CORS by overloading the middleware function:

var allowCrossDomain = function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
	res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With'); // Pierrick: needed by REST calls from angular

	// intercept OPTIONS method
    if('OPTIONS' == req.method) {
    	res.send(200); // force the server to treat such a request as a normal GET or POST request.
    }
    else {
    	next(); // otherwise, do anything else, on s'en fiche (dont care)
    }
}

// connect to the db:
 mongoose.connect('mongodb://localhost/sampledb');
//mongoose.connect('mongodb://localhost/sampledbTAM');
//mongoose.connect('mongodb://localhost/TAM');
// mongoose.connect('mongodb://localhost/tmpCURL');
mongoose.connection.on('open', function(){
	console.log("Connected to Mongoose") ;
});

keepSession = function (req, res, next) {
    var err = req.session.error,
        msg = req.session.success;
    delete req.session.error;
    delete req.session.success;
    res.locals.message = '';
    if (err) res.locals.message = '
' + err + '
';
    if (msg) res.locals.message = '
' + msg + '
';
    //console.log("res.locals"); console.log(res.locals);
    next();
}

var sessionStore = new mongoStore({mongoose_connection: mongoose.connection, db: mongoose.connections[0].db, clear_interval: 60}, function(){
                          console.log('connect mongodb session success...');
});
// configure all environments
app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon());
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());

    app.use(allowCrossDomain); //phuong added on 2/9/2013 for CORS problem!

	app.use(express.cookieParser('your secret here'));

	//app.use(express.session());
	app.use(express.session({
    	key : "camomile.sid",
    	secret: "123camomile",
    	cookie: {
    		//expires: new Date(Date.now() + 60 * 10000)
    		maxAge: 3*3600000 // 3 h resolved the prob encountered when one user is timeout
  		},
  		/*store: new mongoStore({ host: 'http://localhost/',
  			port: 27017,
  			db: 'session',
  			collection: 'sessions',
  			interval: 120000,
  			clear_interval : (10)//search db to clear the expired every 10 seconds
  			})*/
  		//store: new mongoStore({db: mongoose.connections[0].db})
  		store: sessionStore
    }));
	app.use(keepSession); //added

	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler());
}

//start routes:
routes.initialize(app);

//finally boot up the server:
http.createServer(app).listen(app.get('port'), process.env.IP, function(){
	console.log('Express server listening on port ' + app.get('port'));
	if(GLOBAL.no_auth == true){
		console.log('be careful: any user can access the data without authentication');
	}
});

<|endoftext|>


<commit_before>var sortOrder = '';
var sortKey = '';
var listFilter = 'view_all';

var currentDay = '';
var currentCalendarDay = '';
var currentView = 'dayview';

function newEvent(sender) {
  var urlstr = ApplicationBaseURL + "new";

  window.open(urlstr, "",
	      "width=680,height=520,resizable=1,scrollbars=1,toolbar=0," +
	      "location=0,directories=0,status=0,menubar=0,copyhistory=0");

  return false; /* stop following the link */
}

function _editEventId(id) {
  var urlstr = ApplicationBaseURL + id + "/edit";

  var win = window.open(urlstr, "SOGo_edit_" + id,
                        "width=680,height=520,resizable=1,scrollbars=1,toolbar=0," +
                        "location=0,directories=0,status=0,menubar=0,copyhistory=0");
  win.focus();
}

function editEvent() {
  var list = $("appointmentsList");
  var nodes = list.getSelectedRowsId();

  if (nodes.length > 0)
    _editEventId(nodes[0]);

  return false; /* stop following the link */
}

function deleteEvent() {
  var list = $("appointmentsList");
  var nodes = list.getSelectedRowsId();

  if (nodes.length > 0) {
    if (confirm(labels["appointmentDeleteConfirmation"])) {
      var urlstr = ApplicationBaseURL + nodes[0] + "/delete";
      document.deleteEventAjaxRequest = triggerAjaxRequest(urlstr,
                                                           deleteEventCallback,
                                                           nodes[0]);
    }
  }

  return false;
}

function deleteEventCallback(http)
{
  if (http.readyState == 4
      && http.status == 200) {
    document.deleteEventAjaxRequest = null;
    var node = $(http.callbackData);
    log ("deleteEventCallback: " + node);
    node.parentNode.removeChild(node);
  }
  else
    log ("ajax fuckage");
}

function editDoubleClickedEvent(node)
{
  var id = node.getAttribute("id");
  _editEventId(id);

  return false;
}

function onSelectAll() {
  var list = $("appointmentsList");
  list.selectRowsMatchingClass("appointmentRow");

  return false;
}

function displayAppointment(sender) {
  var aptId = sender.getAttribute("aptId");
  var urlstr = ApplicationBaseURL + aptId + "/view";

  var win = window.open(urlstr, "SOGo_view_" + aptId,
                        "width=680,height=520,resizable=1,scrollbars=1,toolbar=0," +
                        "location=0,directories=0,status=0,menubar=0,copyhistory=0");
  win.focus();

  return false; /* stop following the link */
}

function onContactRefresh(node)
{
  var parentNode = node.parentNode;
  var contacts = '';
  var done = false;

  var currentNode = parentNode.firstChild;
  while (currentNode && !done)
    {
      if (currentNode.nodeType == 1
          && currentNode.getAttribute("type") == "hidden")
        {
          contacts = currentNode.value;
          done = true;
        }
      else
        currentNode = currentNode.nextSibling;
    }

  log ('contacts: ' + contacts);
  if (contacts.length > 0)
    window.location = ApplicationBaseURL + '/show?userUIDString=' + contacts;

  return false;
}

function onDaySelect(node)
{
  currentDay = node.getAttribute("day");

  var td = node.getParentWithTagName("td");
  var table = td.getParentWithTagName("table");

//   log ("table.selected: " + table.selected);

  if (document.selectedDate)
    deselectNode(document.selectedDate);

  selectNode(td);
  document.selectedDate = td;

  changeCalendarDisplay(currentDay, null);
  if (listFilter == 'view_selectedday')
    refreshAppointments();

  return false;
}

function onDateSelectorGotoMonth(node)
{
  var day = node.getAttribute("date");

  changeDateSelectorDisplay(day);

  return false;
}

function onCalendarGotoDay(node)
{
  var day = node.getAttribute("date");

  changeCalendarDisplay(day);

  return false;
}

function gotoToday()
{
  currentDay = '';
  currentCalendarDay = '';

  changeCalendarDisplay();
  changeDateSelectorDisplay();

  return false;
}

function dateSelectorCallback(http)
{
  var div = $("dateSelectorView");

  log ("dateselectorcallback: " + div);

  if (http.readyState == 4
      && http.status == 200) {
    document.dateSelectorAjaxRequest = null;
    div.innerHTML = http.responseText;
    if (currentDay.length > 0)
      restoreCurrentDaySelection(div);
  }
  else
    log ("ajax fuckage");
}

function appointmentsListCallback(http)
{
  var div = $("appointmentsListView");

  if (http.readyState == 4
      && http.status == 200) {
    document.dateSelectorAjaxRequest = null;
    div.innerHTML = http.responseText;
    var params = parseQueryParameters(http.callbackData);
    sortKey = params["sort"];
    sortOrder = params["desc"];
  }
  else
    log ("ajax fuckage");
}

function restoreCurrentDaySelection(div)
{
  var elements = div.getElementsByTagName("a");
  var day = null;
  var i = 7;
  while (!day && i < elements.length)
    {
      day = elements[i].getAttribute("day");
      i++;
    }

  if (day
      && day.substr(0, 6) == currentDay.substr(0, 6))
    {
      for (i = 0; i < elements.length; i++) {
        day = elements[i].getAttribute("day");
        if (day && day == currentDay) {
          var td = elements[i].getParentWithTagName("td");
          if (document.selectedDate)
            deselectNode(document.selectedDate);
          selectNode(td);
          document.selectedDate = td;
        }
      }
    }
}

function changeDateSelectorDisplay(day, event)
{
  var url = ApplicationBaseURL + "dateselector";
  if (day)
    url += "?day=" + day;

//   if (currentDay.length > 0)
//     url += '&selectedDay=' + currentDay;
  log ("changeDateSelectorDisplay: " + url);

  if (document.dateSelectorAjaxRequest) {
//     log ("aborting dateselector ajaxrq");
    document.dateSelectorAjaxRequest.aborted = true;
    document.dateSelectorAjaxRequest.abort();
  }

  document.dateSelectorAjaxRequest = triggerAjaxRequest(url,
                                                        dateSelectorCallback,
                                                        null);
//   log ('should go to ' + day);
}

function changeCalendarDisplay(day, newView)
{
  var url = ApplicationBaseURL + ((newView) ? newView : currentView);

  if (!day)
    day = currentCalendarDay;
  if (day)
    url += "?day=" + day;

  if (newView)
    log ("switching to view: " + newView);
//   log ("changeCalendarDisplay: " + url);

  if (document.dayDisplayAjaxRequest) {
//     log ("aborting day ajaxrq");
    document.dayDisplayAjaxRequest.aborted = true;
    document.dayDisplayAjaxRequest.abort();
  }
  document.dayDisplayAjaxRequest = triggerAjaxRequest(url,
                                                      calendarDisplayCallback,
                                                      { "view": newView,
                                                        "day": day });

  return false;
}

function _ensureView(view) {
  if (currentView != view)
    changeCalendarDisplay(null, view);

  return false;
}

function onDayOverview()
{
  return _ensureView("dayview");
}

function onWeekOverview()
{
  return _ensureView("weekview");
}

function onMonthOverview()
{
  return _ensureView("monthview");
}

function calendarDisplayCallback(http)
{
  var div = $("calendarView");

//   log ("calendardisplaycallback: " + div);
  if (http.readyState == 4
      && http.status == 200) {
    document.dateSelectorAjaxRequest = null;
    div.innerHTML = http.responseText;
    if (http.callbackData["view"])
      currentView = http.callbackData["view"];
    if (http.callbackData["day"])
      currentCalendarDay = http.callbackData["day"];
  }
  else
    log ("ajax fuckage");
}

function popupCalendar(node)
{
  var inputId = node.getAttribute("inputId");
  var dateFormat = node.getAttribute("dateFormat");

  var calendar = new skycalendar($(inputId));
  calendar.setCalendarPage(ResourcesURL + "/skycalendar.html");
  calendar.setDateFormat(dateFormat);
  calendar.popup();

  return false;
}

function onAppointmentContextMenu(event, element)
{
  var topNode = $('appointmentsList');
  log(topNode);

  var menu = $('appointmentsListMenu');

  menu.addEventListener("hideMenu", onAppointmentContextMenuHide, false);
  onMenuClick(event, 'appointmentsListMenu');

  var topNode = $('appointmentsList');
  var selectedNodes = topNode.getSelectedRows();
  topNode.menuSelectedRows = selectedNodes;
  for (var i = 0; i < selectedNodes.length; i++)
    deselectNode (selectedNodes[i]);

  topNode.menuSelectedEntry = element;
  selectNode(element);
}

function onAppointmentContextMenuHide(event)
{
  var topNode = $('appointmentsList');

  if (topNode.menuSelectedEntry) {
    deselectNode(topNode.menuSelectedEntry);
    topNode.menuSelectedEntry = null;
  }
  if (topNode.menuSelectedRows) {
    var nodeIds = topNode.menuSelectedRows;
    for (var i = 0; i < nodeIds.length; i++) {
      var node = $(nodeIds[i]);
      selectNode (node);
    }
    topNode.menuSelectedRows = null;
  }
}

function onAppointmentsSelectionChange()
{
}

function _loadAppointmentHref(href) {
  if (document.appointmentsListAjaxRequest) {
    document.appointmentsListAjaxRequest.aborted = true;
    document.appointmentsListAjaxRequest.abort();
  }
  url = ApplicationBaseURL + href;

  document.appointmentsListAjaxRequest
    = triggerAjaxRequest(url, appointmentsListCallback, href);

  return false;
}

function onHeaderClick(node)
{
  return _loadAppointmentHref(node.getAttribute("href"));
}

function refreshAppointments() {
  return _loadAppointmentHref("aptlist?desc=" + sortOrder
                              + "&sort=" + sortKey
                              + "&day=" + currentDay
                              + "&filterpopup=" + listFilter);
}

function onListFilterChange() {
  var node = $("filterpopup");

  listFilter = node.value;
//   log ("listFilter = " + listFilter);

  return refreshAppointments();
}

function onAppointmentClick(event)
{
  var node = event.target.getParentWithTagName("tr");
  changeCalendarDisplay(node.getAttribute("day"));

  return onRowClick(event);
}

function selectMonthInMenu(menu, month)
{
  var entries = menu.childNodes[1].childNodes;
  for (i = 0; i < entries.length; i++) {
    var entry = entries[i];
    if (entry instanceof HTMLLIElement) {
      var entryMonth = entry.getAttribute("month");
      if (entryMonth == month)
        entry.addClassName("currentMonth");
      else
        entry.removeClassName("currentMonth");
    }
  }
}

function selectYearInMenu(menu, month)
{
  var entries = menu.childNodes[1].childNodes;
  for (i = 0; i < entries.length; i++) {
    var entry = entries[i];
    if (entry instanceof HTMLLIElement) {
      var entryMonth = entry.innerHTML;
      if (entryMonth == month)
        entry.addClassName("currentMonth");
      else
        entry.removeClassName("currentMonth");
    }
  }
}

function popupMonthMenu(event, menuId)
{
  var node = event.target;

  if (event.button == 0) {
    event.cancelBubble = true;
    event.returnValue = false;

    if (document.currentPopupMenu)
      hideMenu(event, document.currentPopupMenu);

    var popup = $(menuId);
    var id = node.getAttribute("id");
    if (id == "monthLabel")
      selectMonthInMenu(popup, node.getAttribute("month"));
    else
      selectYearInMenu(popup, node.innerHTML);

    var diff = (popup.offsetWidth - node.offsetWidth) /2;

    popup.style.top = (node.offsetTop + 95) + "px";
    popup.style.left = (node.offsetLeft - diff) + "px";
    popup.style.visibility = "visible";

    bodyOnClick = "" + document.body.getAttribute("onclick");
    document.body.setAttribute("onclick", "onBodyClick('" + menuId + "');");
    document.currentPopupMenu = popup;
  }
}

function onMonthMenuItemClick(node)
{
  var month = '' + node.getAttribute("month");
  var year = '' + $("yearLabel").innerHTML;

  changeDateSelectorDisplay(year+month+"01");

  return false;
}

function onYearMenuItemClick(node)
{
  var month = '' + $("monthLabel").getAttribute("month");;
  var year = '' + node.innerHTML;

  changeDateSelectorDisplay(year+month+"01");

  return false;
}
<commit_msg> <commit_after>var sortOrder = '';
var sortKey = '';
var listFilter = 'view_today';

var currentDay = '';
var currentCalendarDay = '';
var currentView = 'dayview';

function newEvent(sender) {
  var day = sender.getAttribute("day");
  var hour = sender.getAttribute("hour");
  var urlstr = (ApplicationBaseURL + "new"
                + "?day=" + day
                + "&hm=" + hour);

  window.open(urlstr, "",
	      "width=560,height=170,resizable=1,scrollbars=1,toolbar=0," +
	      "location=0,directories=0,status=0,menubar=0,copyhistory=0");

  return false; /* stop following the link */
}

function _editEventId(id) {
  var urlstr = ApplicationBaseURL + id + "/edit";

  var win = window.open(urlstr, "SOGo_edit_" + id,
                        "width=560,height=170,resizable=1,scrollbars=1,toolbar=0," +
                        "location=0,directories=0,status=0,menubar=0,copyhistory=0");
  win.focus();
}

function editEvent() {
  var list = $("appointmentsList");
  var nodes = list.getSelectedRowsId();

  if (nodes.length > 0)
    _editEventId(nodes[0]);

  return false; /* stop following the link */
}

function deleteEvent() {
  var list = $("appointmentsList");
  var nodes = list.getSelectedRowsId();

  if (nodes.length > 0) {
    if (confirm(labels["appointmentDeleteConfirmation"])) {
      var urlstr = ApplicationBaseURL + nodes[0] + "/delete";
      document.deleteEventAjaxRequest = triggerAjaxRequest(urlstr,
                                                           deleteEventCallback,
                                                           nodes[0]);
    }
  }

  return false;
}

function deleteEventCallback(http)
{
  if (http.readyState == 4
      && http.status == 200) {
    document.deleteEventAjaxRequest = null;
    var node = $(http.callbackData);
    log ("deleteEventCallback: " + node);
    node.parentNode.removeChild(node);
  }
  else
    log ("ajax fuckage");
}

function editDoubleClickedEvent(node)
{
  var id = node.getAttribute("id");
  _editEventId(id);

  return false;
}

function onSelectAll() {
  var list = $("appointmentsList");
  list.selectRowsMatchingClass("appointmentRow");

  return false;
}

function displayAppointment(sender) {
  var aptId = sender.getAttribute("aptId");
  var urlstr = ApplicationBaseURL + aptId + "/view";

  var win = window.open(urlstr, "SOGo_view_" + aptId,
                        "width=560,height=170,resizable=1,scrollbars=1,toolbar=0," +
                        "location=0,directories=0,status=0,menubar=0,copyhistory=0");
  win.focus();

  return false; /* stop following the link */
}

function onContactRefresh(node)
{
  var parentNode = node.parentNode;
  var contacts = '';
  var done = false;

  var currentNode = parentNode.firstChild;
  while (currentNode && !done)
    {
      if (currentNode.nodeType == 1
          && currentNode.getAttribute("type") == "hidden")
        {
          contacts = currentNode.value;
          done = true;
        }
      else
        currentNode = currentNode.nextSibling;
    }

  log ('contacts: ' + contacts);
  if (contacts.length > 0)
    window.location = ApplicationBaseURL + '/show?userUIDString=' + contacts;

  return false;
}

function onDaySelect(node)
{
  currentDay = node.getAttribute("day");

  var td = node.getParentWithTagName("td");
  var table = td.getParentWithTagName("table");

//   log ("table.selected: " + table.selected);

  if (document.selectedDate)
    deselectNode(document.selectedDate);

  selectNode(td);
  document.selectedDate = td;

  changeCalendarDisplay(currentDay, null);
  if (listFilter == 'view_selectedday')
    refreshAppointments();

  return false;
}

function onDateSelectorGotoMonth(node)
{
  var day = node.getAttribute("date");

  changeDateSelectorDisplay(day);

  return false;
}

function onCalendarGotoDay(node)
{
  var day = node.getAttribute("date");

  changeCalendarDisplay(day);

  return false;
}

function gotoToday()
{
  currentDay = '';
  currentCalendarDay = '';

  changeCalendarDisplay();
  changeDateSelectorDisplay();

  return false;
}

function dateSelectorCallback(http)
{
  var div = $("dateSelectorView");

  log ("dateselectorcallback: " + div);

  if (http.readyState == 4
      && http.status == 200) {
    document.dateSelectorAjaxRequest = null;
    div.innerHTML = http.responseText;
    if (currentDay.length > 0)
      restoreCurrentDaySelection(div);
  }
  else
    log ("ajax fuckage");
}

function appointmentsListCallback(http)
{
  var div = $("appointmentsListView");

  if (http.readyState == 4
      && http.status == 200) {
    document.dateSelectorAjaxRequest = null;
    div.innerHTML = http.responseText;
    var params = parseQueryParameters(http.callbackData);
    sortKey = params["sort"];
    sortOrder = params["desc"];
  }
  else
    log ("ajax fuckage");
}

function restoreCurrentDaySelection(div)
{
  var elements = div.getElementsByTagName("a");
  var day = null;
  var i = 7;
  while (!day && i < elements.length)
    {
      day = elements[i].getAttribute("day");
      i++;
    }

  if (day
      && day.substr(0, 6) == currentDay.substr(0, 6))
    {
      for (i = 0; i < elements.length; i++) {
        day = elements[i].getAttribute("day");
        if (day && day == currentDay) {
          var td = elements[i].getParentWithTagName("td");
          if (document.selectedDate)
            deselectNode(document.selectedDate);
          selectNode(td);
          document.selectedDate = td;
        }
      }
    }
}

function changeDateSelectorDisplay(day, event)
{
  var url = ApplicationBaseURL + "dateselector";
  if (day)
    url += "?day=" + day;

//   if (currentDay.length > 0)
//     url += '&selectedDay=' + currentDay;
  log ("changeDateSelectorDisplay: " + url);

  if (document.dateSelectorAjaxRequest) {
//     log ("aborting dateselector ajaxrq");
    document.dateSelectorAjaxRequest.aborted = true;
    document.dateSelectorAjaxRequest.abort();
  }

  document.dateSelectorAjaxRequest = triggerAjaxRequest(url,
                                                        dateSelectorCallback,
                                                        null);
//   log ('should go to ' + day);
}

function changeCalendarDisplay(day, newView)
{
  var url = ApplicationBaseURL + ((newView) ? newView : currentView);

  if (!day)
    day = currentCalendarDay;
  if (day)
    url += "?day=" + day;

  if (newView)
    log ("switching to view: " + newView);
//   log ("changeCalendarDisplay: " + url);

  if (document.dayDisplayAjaxRequest) {
//     log ("aborting day ajaxrq");
    document.dayDisplayAjaxRequest.aborted = true;
    document.dayDisplayAjaxRequest.abort();
  }
  document.dayDisplayAjaxRequest = triggerAjaxRequest(url,
                                                      calendarDisplayCallback,
                                                      { "view": newView,
                                                        "day": day });

  return false;
}

function _ensureView(view) {
  if (currentView != view)
    changeCalendarDisplay(null, view);

  return false;
}

function onDayOverview()
{
  return _ensureView("dayview");
}

function onWeekOverview()
{
  return _ensureView("weekview");
}

function onMonthOverview()
{
  return _ensureView("monthview");
}

function calendarDisplayCallback(http)
{
  var div = $("calendarView");

//   log ("calendardisplaycallback: " + div);
  if (http.readyState == 4
      && http.status == 200) {
    document.dateSelectorAjaxRequest = null;
    div.innerHTML = http.responseText;
    if (http.callbackData["view"])
      currentView = http.callbackData["view"];
    if (http.callbackData["day"])
      currentCalendarDay = http.callbackData["day"];
  }
  else
    log ("ajax fuckage");
}

function assignCalendar(name)
{
  var node = $(name);

  node.calendar = new skycalendar(node);
  node.calendar.setCalendarPage(ResourcesURL + "/skycalendar.html");
  var dateFormat = node.getAttribute("dateFormat");
  if (dateFormat)
    node.calendar.setDateFormat(dateFormat);
}

function popupCalendar(node)
{
  var nodeId = node.getAttribute("inputId");
  var input = $(nodeId);
  input.calendar.popup();

  return false;
}

function onAppointmentContextMenu(event, element)
{
  var topNode = $('appointmentsList');
  log(topNode);

  var menu = $('appointmentsListMenu');

  menu.addEventListener("hideMenu", onAppointmentContextMenuHide, false);
  onMenuClick(event, 'appointmentsListMenu');

  var topNode = $('appointmentsList');
  var selectedNodes = topNode.getSelectedRows();
  topNode.menuSelectedRows = selectedNodes;
  for (var i = 0; i < selectedNodes.length; i++)
    deselectNode (selectedNodes[i]);

  topNode.menuSelectedEntry = element;
  selectNode(element);
}

function onAppointmentContextMenuHide(event)
{
  var topNode = $('appointmentsList');

  if (topNode.menuSelectedEntry) {
    deselectNode(topNode.menuSelectedEntry);
    topNode.menuSelectedEntry = null;
  }
  if (topNode.menuSelectedRows) {
    var nodeIds = topNode.menuSelectedRows;
    for (var i = 0; i < nodeIds.length; i++) {
      var node = $(nodeIds[i]);
      selectNode (node);
    }
    topNode.menuSelectedRows = null;
  }
}

function onAppointmentsSelectionChange()
{
}

function _loadAppointmentHref(href) {
  if (document.appointmentsListAjaxRequest) {
    document.appointmentsListAjaxRequest.aborted = true;
    document.appointmentsListAjaxRequest.abort();
  }
  url = ApplicationBaseURL + href;

  document.appointmentsListAjaxRequest
    = triggerAjaxRequest(url, appointmentsListCallback, href);

  return false;
}

function onHeaderClick(node)
{
  return _loadAppointmentHref(node.getAttribute("href"));
}

function refreshAppointments() {
  return _loadAppointmentHref("aptlist?desc=" + sortOrder
                              + "&sort=" + sortKey
                              + "&day=" + currentDay
                              + "&filterpopup=" + listFilter);
}

function onListFilterChange() {
  var node = $("filterpopup");

  listFilter = node.value;
//   log ("listFilter = " + listFilter);

  return refreshAppointments();
}

function onAppointmentClick(event)
{
  var node = event.target.getParentWithTagName("tr");
  changeCalendarDisplay(node.getAttribute("day"));

  return onRowClick(event);
}

function selectMonthInMenu(menu, month)
{
  var entries = menu.childNodes[1].childNodes;
  for (i = 0; i < entries.length; i++) {
    var entry = entries[i];
    if (entry instanceof HTMLLIElement) {
      var entryMonth = entry.getAttribute("month");
      if (entryMonth == month)
        entry.addClassName("currentMonth");
      else
        entry.removeClassName("currentMonth");
    }
  }
}

function selectYearInMenu(menu, month)
{
  var entries = menu.childNodes[1].childNodes;
  for (i = 0; i < entries.length; i++) {
    var entry = entries[i];
    if (entry instanceof HTMLLIElement) {
      var entryMonth = entry.innerHTML;
      if (entryMonth == month)
        entry.addClassName("currentMonth");
      else
        entry.removeClassName("currentMonth");
    }
  }
}

function popupMonthMenu(event, menuId)
{
  var node = event.target;

  if (event.button == 0) {
    event.cancelBubble = true;
    event.returnValue = false;

    if (document.currentPopupMenu)
      hideMenu(event, document.currentPopupMenu);

    var popup = $(menuId);
    var id = node.getAttribute("id");
    if (id == "monthLabel")
      selectMonthInMenu(popup, node.getAttribute("month"));
    else
      selectYearInMenu(popup, node.innerHTML);

    var diff = (popup.offsetWidth - node.offsetWidth) /2;

    popup.style.top = (node.offsetTop + 95) + "px";
    popup.style.left = (node.offsetLeft - diff) + "px";
    popup.style.visibility = "visible";

    bodyOnClick = "" + document.body.getAttribute("onclick");
    document.body.setAttribute("onclick", "onBodyClick('" + menuId + "');");
    document.currentPopupMenu = popup;
  }
}

function onMonthMenuItemClick(node)
{
  var month = '' + node.getAttribute("month");
  var year = '' + $("yearLabel").innerHTML;

  changeDateSelectorDisplay(year+month+"01");

  return false;
}

function onYearMenuItemClick(node)
{
  var month = '' + $("monthLabel").getAttribute("month");;
  var year = '' + node.innerHTML;

  changeDateSelectorDisplay(year+month+"01");

  return false;
}

function onSearchFormSubmit()
{
  log ("search not implemented");

  return false;
}
<|endoftext|>


<commit_before>/*globals require, console, Uint8Array */
/*jslint node:true,sloppy:true */

/**
 * A freedom.js tcp socket provider on Node Streams
 * @constructor
 * @private
 * @param {fdom.Port} channel the module creating this provider.
 * @param {Function} dispatchEvent Method for emitting events.
 * @param {number} id The identifier of the socket, if it exposing
 * a pre-existing accepted socket.
 */
var TcpSocket_node = function (cap, dispatchEvent, id) {
  this.dispatchEvent = dispatchEvent;
  this.net = require('net');
  this.tlsconnect = require('tls-connect');

  this.state = TcpSocket_node.state.NEW;

  if (id !== undefined && TcpSocket_node.unbound[id]) {
    this.state = TcpSocket_node.state.CONNECTED;
    this.connection = TcpSocket_node.unbound[id];
    delete TcpSocket_node.unbound[id];
    this.attachListeners();
  }
};

TcpSocket_node.unbound = {};
TcpSocket_node.unboundId = 1;

TcpSocket_node.state = {
  NEW: 0,
  CONNECTING: 1,
  CONNECTED: 2,
  CLOSED: 3,
  BINDING: 4,
  LISTENING: 5
};

/**
 * Write a buffer of data to the socket
 * @method write
 * @param {ArrayBuffer} data The data to write
 * @param {Function} callback Function to call after completion or error.
 */
TcpSocket_node.prototype.write = function (data, callback) {
  if (this.state !== TcpSocket_node.state.CONNECTED) {
    callback(undefined, {
      "errcode": "NOT_CONNECTED",
      "message": "Cannot Write on Closed Socket"
    });
    return;
  }
  var buffer = new Buffer(new Uint8Array(data));
  this.connection.write(buffer, 'utf8', callback);
};

/**
 * Get information about an active socket.
 * @method getInfo
 * @param {Function} callback function to call with socket info.
 */
TcpSocket_node.prototype.getInfo = function (callback) {
  if (this.state === TcpSocket_node.state.NEW) {
    return callback({
      connected: false
    });
  } else {
    callback({
      type: 'tcp',
      connected: this.connection.state === TcpSocket_node.state.CONNECTED,
      peerAddress: this.connection.remoteAddress,
      peerPort: this.connection.remotePort,
      localAddress: this.connection.address().address,
      localPort: this.connection.address().port
    });
  }
};

/**
 * Prepares a socket for becoming secure, currently a no-op in node.
 * Details at https://github.com/freedomjs/freedom/wiki/prepareSecure-API-Usage
 * @method prepareSecure
 * @param {Function} callback function to call on completion or error.
 */
TcpSocket_node.prototype.prepareSecure = function (callback) {
  callback();
};

/**
 * Secure a socket, such that subsequent methods are sent over a TLS channel.
 * @method secure
 * @param {Function} callback function to call on completion or error.
 */
TcpSocket_node.prototype.secure = function (callback) {
  if (this.state !== TcpSocket_node.state.CONNECTED) {
    callback(undefined, {
      "errcode": "NOT_CONNECTED",
      "message": "Cannot secure closed socket"
    });
    return;
  }
  this.tlsconnect({
    socket: this.connection,
    rejectUnauthorized: true,
    requestCert: true,
    isServer: false
  }, function () {
    if (!this.connection.authorized) {
      this.connection.destroy();
      this.state = TcpSocket_node.state.CLOSED;
      callback(undefined, {
        "errcode": "CONNECTION_RESET",
        "message": "Failed to secure socket."
      });
    } else {
      callback();
    }
  }.bind(this));
};

/**
 * Connect to a designated location and begin reading.
 * @method connect
 * @param {String} hostname The host or ip to connect to.
 * @param {number} port The port to connect on.
 * @param {Function} cb Function to call with completion or error.
 */
TcpSocket_node.prototype.connect = function (hostname, port, cb) {
  if (this.state !== TcpSocket_node.state.NEW) {
    return cb(undefined, {
      "errcode": "ALREADY_CONNECTED",
      "message": "Cannot Connect Existing Socket"
    });
  }

  try {
    this.connection = this.net.connect(port, hostname);
    this.state = TcpSocket_node.state.CONNECTING;
    this.callback = cb;
    this.attachListeners();
  } catch (e) {
    this.onError(e);
  }
};

TcpSocket_node.prototype.attachListeners = function () {
  this.connection.on('data', this.onData.bind(this));
  this.connection.on('end', this.onEnd.bind(this));
  this.connection.on('timeout', this.onEnd.bind(this));
  this.connection.on('error', this.onError.bind(this));
  this.connection.on('connect', this.onConnect.bind(this, 0));
};

TcpSocket_node.prototype.onConnect = function (status) {
  if (this.state === TcpSocket_node.state.CONNECTING) {
    this.state = TcpSocket_node.state.CONNECTED;
  } else if (this.state === TcpSocket_node.state.BINDING) {
    this.state = TcpSocket_node.state.LISTENING;
  } else {
    console.warn('Connection on invalid state socket!');
    return;
  }

  if (this.callback) {
    this.callback(status);
    delete this.callback;
  }
};

TcpSocket_node.prototype.onError = function (error) {
  if (this.state === TcpSocket_node.state.CONNECTING) {
    this.callback(undefined, {
      "errcode": "CONNECTION_FAILED",
      message: "Socket Error: " + error.message
    });
    delete this.callback;
    delete this.connection;
    this.state = TcpSocket_node.state.CLOSED;
    return;
  } else if (this.state === TcpSocket_node.state.CONNECTED) {
    console.warn('Socket Error: ' + error);
    this.dispatchEvent('onDisconnect', {
      errcode: "SOCKET_CLOSED",
      message: "Socket Error: " + error.message
    });
    delete this.connection;
    this.state = TcpSocket_node.state.CLOSED;
    return;
  } else {
    console.warn('Socket Error: ' + error);
    delete this.connection;
    this.state = TcpSocket_node.state.CLOSED;
    return;
  }
};

TcpSocket_node.prototype.onEnd = function () {
  this.dispatchEvent('onDisconnect', {
    errcode: 'CONNECTION_CLOSED',
    message: 'Connection closed gracefully'
  });
  delete this.connection;
  this.state = TcpSocket_node.state.CLOSED;
};

TcpSocket_node.ERROR_MAP = {
  '-1': 'IO_PENDING',
  '-2': 'FAILED',
  '-3': 'ABORTED',
  '-4': 'INVALID_ARGUMENT',
  '-5': 'INVALID_HANDLE',
  '-7': 'TIMED_OUT',
  '-13': 'OUT_OF_MEMORY',
  '-15': 'SOCKET_NOT_CONNECTED',
  '-21': 'NETWORK_CHANGED',
  '-23': 'SOCKET_IS_CONNECTED',
  '-100': 'CONNECTION_CLOSED',
  '-101': 'CONNECTION_RESET',
  '-102': 'CONNECTION_REFUSED',
  '-103': 'CONNECTION_ABORTED',
  '-104': 'CONNECTION_FAILED',
  '-105': 'NAME_NOT_RESOLVED',
  '-106': 'INTERNET_DISCONNECTED'
};

/*
 * Read data on a socket in an event loop until the socket is closed or an
 * error occurs.
 * @method read
 * @private
 */
TcpSocket_node.prototype.onData = function (data) {
  var arrayBuffer = new Uint8Array(data).buffer;
  this.dispatchEvent('onData', {
    data: arrayBuffer
  });
};

/**
 * Listen on a socket to accept new clients.
 * @method listen
 * @param {String} address the address to listen on
 * @param {number} port the port to listen on
 * @param {Function} callback Callback to call when listening has occured.
 */
TcpSocket_node.prototype.listen = function (address, port, callback) {
  if (this.state !== TcpSocket_node.state.NEW) {
    callback(undefined, {
      errcode: "ALREADY_CONNECTED",
      message: "Cannot Listen on existing socket."
    });
    return;
  }

  this.connection = this.net.createServer();
  this.callback = callback;
  this.state = TcpSocket_node.state.BINDING;

  this.connection.on('error', this.onError.bind(this));
  this.connection.on('listening', this.onConnect.bind(this, undefined));
  this.connection.on('close', this.onEnd.bind(this));
  this.connection.on('connection', this.onAccept.bind(this));

  this.connection.listen(port, address);
};

TcpSocket_node.prototype.onAccept = function (connection) {
  var id = TcpSocket_node.unboundId += 1;
  TcpSocket_node.unbound[id] = connection;

  this.dispatchEvent('onConnection', {
    'socket': id,
    'host': connection.remoteAddress,
    'port': connection.remotePort
  });
  //TODO: initial incoming data may be dropped if received before bound.
};

/**
 * Close a socket
 * @method disconnect
 * @param {number} socketId The socket to disconnect
 * @param {Function} continuation Function to call once socket is disconnected.
 */
TcpSocket_node.prototype.close = function (continuation) {
  if (this.connection) {
    if (this.state === TcpSocket_node.state.BINDING ||
        this.state === TcpSocket_node.state.LISTENING) {
      this.connection.close();
    } else {
      this.connection.end();
    }
    delete this.connection;
    this.state = TcpSocket_node.state.CLOSED;
  }
  continuation();
};

/** REGISTER PROVIDER **/
exports.provider = TcpSocket_node;
exports.name = 'core.tcpsocket';
<commit_msg>set connecting status before invoking connect attempt, in case of side effects/failures<commit_after>/*globals require, console, Uint8Array */
/*jslint node:true,sloppy:true */

/**
 * A freedom.js tcp socket provider on Node Streams
 * @constructor
 * @private
 * @param {fdom.Port} channel the module creating this provider.
 * @param {Function} dispatchEvent Method for emitting events.
 * @param {number} id The identifier of the socket, if it exposing
 * a pre-existing accepted socket.
 */
var TcpSocket_node = function (cap, dispatchEvent, id) {
  this.dispatchEvent = dispatchEvent;
  this.net = require('net');
  this.tlsconnect = require('tls-connect');

  this.state = TcpSocket_node.state.NEW;

  if (id !== undefined && TcpSocket_node.unbound[id]) {
    this.state = TcpSocket_node.state.CONNECTED;
    this.connection = TcpSocket_node.unbound[id];
    delete TcpSocket_node.unbound[id];
    this.attachListeners();
  }
};

TcpSocket_node.unbound = {};
TcpSocket_node.unboundId = 1;

TcpSocket_node.state = {
  NEW: 0,
  CONNECTING: 1,
  CONNECTED: 2,
  CLOSED: 3,
  BINDING: 4,
  LISTENING: 5
};

/**
 * Write a buffer of data to the socket
 * @method write
 * @param {ArrayBuffer} data The data to write
 * @param {Function} callback Function to call after completion or error.
 */
TcpSocket_node.prototype.write = function (data, callback) {
  if (this.state !== TcpSocket_node.state.CONNECTED) {
    callback(undefined, {
      "errcode": "NOT_CONNECTED",
      "message": "Cannot Write on Closed Socket"
    });
    return;
  }
  var buffer = new Buffer(new Uint8Array(data));
  this.connection.write(buffer, 'utf8', callback);
};

/**
 * Get information about an active socket.
 * @method getInfo
 * @param {Function} callback function to call with socket info.
 */
TcpSocket_node.prototype.getInfo = function (callback) {
  if (this.state === TcpSocket_node.state.NEW) {
    return callback({
      connected: false
    });
  } else {
    callback({
      type: 'tcp',
      connected: this.connection.state === TcpSocket_node.state.CONNECTED,
      peerAddress: this.connection.remoteAddress,
      peerPort: this.connection.remotePort,
      localAddress: this.connection.address().address,
      localPort: this.connection.address().port
    });
  }
};

/**
 * Prepares a socket for becoming secure, currently a no-op in node.
 * Details at https://github.com/freedomjs/freedom/wiki/prepareSecure-API-Usage
 * @method prepareSecure
 * @param {Function} callback function to call on completion or error.
 */
TcpSocket_node.prototype.prepareSecure = function (callback) {
  callback();
};

/**
 * Secure a socket, such that subsequent methods are sent over a TLS channel.
 * @method secure
 * @param {Function} callback function to call on completion or error.
 */
TcpSocket_node.prototype.secure = function (callback) {
  if (this.state !== TcpSocket_node.state.CONNECTED) {
    callback(undefined, {
      "errcode": "NOT_CONNECTED",
      "message": "Cannot secure closed socket"
    });
    return;
  }
  this.tlsconnect({
    socket: this.connection,
    rejectUnauthorized: true,
    requestCert: true,
    isServer: false
  }, function () {
    if (!this.connection.authorized) {
      this.connection.destroy();
      this.state = TcpSocket_node.state.CLOSED;
      callback(undefined, {
        "errcode": "CONNECTION_RESET",
        "message": "Failed to secure socket."
      });
    } else {
      callback();
    }
  }.bind(this));
};

/**
 * Connect to a designated location and begin reading.
 * @method connect
 * @param {String} hostname The host or ip to connect to.
 * @param {number} port The port to connect on.
 * @param {Function} cb Function to call with completion or error.
 */
TcpSocket_node.prototype.connect = function (hostname, port, cb) {
  if (this.state !== TcpSocket_node.state.NEW) {
    return cb(undefined, {
      "errcode": "ALREADY_CONNECTED",
      "message": "Cannot Connect Existing Socket"
    });
  }

  try {
    this.state = TcpSocket_node.state.CONNECTING;
    this.connection = this.net.connect(port, hostname);
    this.callback = cb;
    this.attachListeners();
  } catch (e) {
    this.onError(e);
  }
};

TcpSocket_node.prototype.attachListeners = function () {
  this.connection.on('data', this.onData.bind(this));
  this.connection.on('end', this.onEnd.bind(this));
  this.connection.on('timeout', this.onEnd.bind(this));
  this.connection.on('error', this.onError.bind(this));
  this.connection.on('connect', this.onConnect.bind(this, 0));
};

TcpSocket_node.prototype.onConnect = function (status) {
  if (this.state === TcpSocket_node.state.CONNECTING) {
    this.state = TcpSocket_node.state.CONNECTED;
  } else if (this.state === TcpSocket_node.state.BINDING) {
    this.state = TcpSocket_node.state.LISTENING;
  } else {
    console.warn('Connection on invalid state socket!');
    return;
  }

  if (this.callback) {
    this.callback(status);
    delete this.callback;
  }
};

TcpSocket_node.prototype.onError = function (error) {
  if (this.state === TcpSocket_node.state.CONNECTING) {
    this.callback(undefined, {
      "errcode": "CONNECTION_FAILED",
      message: "Socket Error: " + error.message
    });
    delete this.callback;
    delete this.connection;
    this.state = TcpSocket_node.state.CLOSED;
    return;
  } else if (this.state === TcpSocket_node.state.CONNECTED) {
    console.warn('Socket Error: ' + error);
    this.dispatchEvent('onDisconnect', {
      errcode: "SOCKET_CLOSED",
      message: "Socket Error: " + error.message
    });
    delete this.connection;
    this.state = TcpSocket_node.state.CLOSED;
    return;
  } else {
    console.warn('Socket Error: ' + error);
    delete this.connection;
    this.state = TcpSocket_node.state.CLOSED;
    return;
  }
};

TcpSocket_node.prototype.onEnd = function () {
  this.dispatchEvent('onDisconnect', {
    errcode: 'CONNECTION_CLOSED',
    message: 'Connection closed gracefully'
  });
  delete this.connection;
  this.state = TcpSocket_node.state.CLOSED;
};

TcpSocket_node.ERROR_MAP = {
  '-1': 'IO_PENDING',
  '-2': 'FAILED',
  '-3': 'ABORTED',
  '-4': 'INVALID_ARGUMENT',
  '-5': 'INVALID_HANDLE',
  '-7': 'TIMED_OUT',
  '-13': 'OUT_OF_MEMORY',
  '-15': 'SOCKET_NOT_CONNECTED',
  '-21': 'NETWORK_CHANGED',
  '-23': 'SOCKET_IS_CONNECTED',
  '-100': 'CONNECTION_CLOSED',
  '-101': 'CONNECTION_RESET',
  '-102': 'CONNECTION_REFUSED',
  '-103': 'CONNECTION_ABORTED',
  '-104': 'CONNECTION_FAILED',
  '-105': 'NAME_NOT_RESOLVED',
  '-106': 'INTERNET_DISCONNECTED'
};

/*
 * Read data on a socket in an event loop until the socket is closed or an
 * error occurs.
 * @method read
 * @private
 */
TcpSocket_node.prototype.onData = function (data) {
  var arrayBuffer = new Uint8Array(data).buffer;
  this.dispatchEvent('onData', {
    data: arrayBuffer
  });
};

/**
 * Listen on a socket to accept new clients.
 * @method listen
 * @param {String} address the address to listen on
 * @param {number} port the port to listen on
 * @param {Function} callback Callback to call when listening has occured.
 */
TcpSocket_node.prototype.listen = function (address, port, callback) {
  if (this.state !== TcpSocket_node.state.NEW) {
    callback(undefined, {
      errcode: "ALREADY_CONNECTED",
      message: "Cannot Listen on existing socket."
    });
    return;
  }

  this.connection = this.net.createServer();
  this.callback = callback;
  this.state = TcpSocket_node.state.BINDING;

  this.connection.on('error', this.onError.bind(this));
  this.connection.on('listening', this.onConnect.bind(this, undefined));
  this.connection.on('close', this.onEnd.bind(this));
  this.connection.on('connection', this.onAccept.bind(this));

  this.connection.listen(port, address);
};

TcpSocket_node.prototype.onAccept = function (connection) {
  var id = TcpSocket_node.unboundId += 1;
  TcpSocket_node.unbound[id] = connection;

  this.dispatchEvent('onConnection', {
    'socket': id,
    'host': connection.remoteAddress,
    'port': connection.remotePort
  });
  //TODO: initial incoming data may be dropped if received before bound.
};

/**
 * Close a socket
 * @method disconnect
 * @param {number} socketId The socket to disconnect
 * @param {Function} continuation Function to call once socket is disconnected.
 */
TcpSocket_node.prototype.close = function (continuation) {
  if (this.connection) {
    if (this.state === TcpSocket_node.state.BINDING ||
        this.state === TcpSocket_node.state.LISTENING) {
      this.connection.close();
    } else {
      this.connection.end();
    }
    delete this.connection;
    this.state = TcpSocket_node.state.CLOSED;
  }
  continuation();
};

/** REGISTER PROVIDER **/
exports.provider = TcpSocket_node;
exports.name = 'core.tcpsocket';
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*global define, $, JSLINT, brackets */

/**
 * Provides JSLint results via the core linting extension point
 */
define(function (require, exports, module) {
    "use strict";

    // Load JSLint, a non-module lib
    require("thirdparty/jslint/jslint");

    // Load dependent modules
    var CodeInspection     = brackets.getModule("language/CodeInspection"),
        PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
        Strings            = brackets.getModule("strings");

    var prefs = PreferencesManager.getExtensionPrefs("jslint");

    PreferencesManager.definePreference("options", "object")
        .on("change", function (e, data) {
            CodeInspection.requestRun(Strings.JSLINT_NAME);
        });

    /**
     * Run JSLint on the current document. Reports results to the main UI. Displays
     * a gold star when no errors are found.
     */
    function lintOneFile(text, fullPath) {

        // If a line contains only whitespace, remove the whitespace
        // This should be doable with a regexp: text.replace(/\r[\x20|\t]+\r/g, "\r\r");,
        // but that doesn't work.
        var i, arr = text.split("\n");
        for (i = 0; i < arr.length; i++) {
            if (!arr[i].match(/\S/)) {
                arr[i] = "";
            }
        }
        text = arr.join("\n");

        var options = prefs.get("options");
        var jslintResult = JSLINT(text, options);

        if (!jslintResult) {
            // Remove any trailing null placeholder (early-abort indicator)
            var errors = JSLINT.errors.filter(function (err) { return err !== null; });

            errors = errors.map(function (jslintError) {
                return {
                    // JSLint returns 1-based line/col numbers
                    pos: { line: jslintError.line - 1, ch: jslintError.character - 1 },
                    message: jslintError.reason,
                    type: CodeInspection.Type.WARNING
                };
            });

            var result = { errors: errors };

            // If array terminated in a null it means there was a stop notice
            if (errors.length !== JSLINT.errors.length) {
                result.aborted = true;
                errors[errors.length - 1].type = CodeInspection.Type.META;
            }

            return result;
        }
        return null;
    }

    // Register for JS files
    CodeInspection.register("javascript", {
        name: Strings.JSLINT_NAME,
        scanFile: lintOneFile
    });
});
<commit_msg>Use prefs.definePreference for JSLint<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*global define, $, JSLINT, brackets */

/**
 * Provides JSLint results via the core linting extension point
 */
define(function (require, exports, module) {
    "use strict";

    // Load JSLint, a non-module lib
    require("thirdparty/jslint/jslint");

    // Load dependent modules
    var CodeInspection     = brackets.getModule("language/CodeInspection"),
        PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
        Strings            = brackets.getModule("strings");

    var prefs = PreferencesManager.getExtensionPrefs("jslint");

    prefs.definePreference("options", "object")
        .on("change", function (e, data) {
            CodeInspection.requestRun(Strings.JSLINT_NAME);
        });

    /**
     * Run JSLint on the current document. Reports results to the main UI. Displays
     * a gold star when no errors are found.
     */
    function lintOneFile(text, fullPath) {

        // If a line contains only whitespace, remove the whitespace
        // This should be doable with a regexp: text.replace(/\r[\x20|\t]+\r/g, "\r\r");,
        // but that doesn't work.
        var i, arr = text.split("\n");
        for (i = 0; i < arr.length; i++) {
            if (!arr[i].match(/\S/)) {
                arr[i] = "";
            }
        }
        text = arr.join("\n");

        var options = prefs.get("options");
        var jslintResult = JSLINT(text, options);

        if (!jslintResult) {
            // Remove any trailing null placeholder (early-abort indicator)
            var errors = JSLINT.errors.filter(function (err) { return err !== null; });

            errors = errors.map(function (jslintError) {
                return {
                    // JSLint returns 1-based line/col numbers
                    pos: { line: jslintError.line - 1, ch: jslintError.character - 1 },
                    message: jslintError.reason,
                    type: CodeInspection.Type.WARNING
                };
            });

            var result = { errors: errors };

            // If array terminated in a null it means there was a stop notice
            if (errors.length !== JSLINT.errors.length) {
                result.aborted = true;
                errors[errors.length - 1].type = CodeInspection.Type.META;
            }

            return result;
        }
        return null;
    }

    // Register for JS files
    CodeInspection.register("javascript", {
        name: Strings.JSLINT_NAME,
        scanFile: lintOneFile
    });
});
<|endoftext|>