<commit_before>
/*!
 * Module dependencies.
 */

var _ = require('lodash');
var multiparty = require('multiparty');
var knox = require('knox');
var randomstring = require('randomstring');
var path = require('path');
var easyimage = require('easyimage');
var async = require('async');
var models = require('../models');
var Q = require('q');

var s3Client = knox.createClient({
    secure: false,
    key: process.env.S3_KEY,
    secret: process.env.S3_SECRET,
    bucket: process.env.S3_BUCKET,
});

exports.index = function (req, res, next) {

    models.Session.findAll({
        order: '"createdAt" DESC'
    }).then(function(sessions) {
        res.render('session/index', {
            sessions: sessions
        });
    }).error(next);
};

exports.feed = function (req, res, next) {

    var sessionId = req.params.sid;
    var Session = models.Session;
    var VisualizationType = models.VisualizationType;
    var Visualization = models.Visualization;

    Q.all([
        Session
            .find({
                where: {
                    id: sessionId
                }
            }),
        Visualization
            .findAll({
                where: {
                    SessionId: sessionId
                }
            }),
        VisualizationType.findAll()
    ]).spread(function(session, visualizations, vizTypes) {

        if(!session) {
            return res.status(404).send('Session not found');
        }

        _.each(visualizations, function(viz) {
            console.log(viz.images);
        });

        res.render('session/feed', {
            session: session,
            visualizations: visualizations,
            vizTypes: _.object(_.map(vizTypes, function(item) {
                return [item.name, item];
            }))
        });
    }).fail(next);
};

exports.update = function (req, res, next) {

    var sessionId = req.params.sid;
    var Session = models.Session;

    Session
        .update(req.body, {
            id: sessionId
        }).success(function(sessions) {
            return res.json(sessions);
        }).error(next);

};
exports.updateVisualization = function (req, res, next) {

    var vid = req.params.vid;
    var Visualization = models.Visualization;

    console.log('updating visualization ' + vid);

    Visualization
        .update(req.body, {
            id: vid
        }).success(function(visualizations) {
            return res.status(200).send();
        }).error(function(err) {
            console.log(err);
            return res.status(500).send();
        });

};

exports.read = function (req, res, next) {

    var vizId = req.params.vid;
    var Visualization = models.Visualization;
    var VisualizationType = models.VisualizationType;

    Q.all([
        Visualization.find(vizId),
        VisualizationType.findAll()
    ]).spread(function(viz, vizTypes) {
            res.render('session/visualization', {
                viz: viz,
                vizTypes: _.object(_.map(vizTypes, function(item) {
                    return [item.name, item];
                }))
            });
    }).fail(next);
};

exports.create = function(req, res, next) {

    models.Session
        .create(_.pick(req.body, 'name'))
        .then(function(session) {
            return res.json(session);
        }).error(next);
};

exports.getCreate = function(req, res, next) {
    models.Session
        .create()
        .then(function(session) {
            return res.redirect('/sessions/' + session.id + '/feed/');
        }).error(next);
};

exports.delete = function(req, res, next) {
    var sessionId = req.params.sid;

    models.Session
        .find(sessionId)
        .then(function(session) {
            session.destroy().success(function() {
                return res.json(session);
            }).error(next);
        }).error(next);
};

exports.getDelete = function(req, res, next) {

    var sessionId = req.params.sid;

    models.Session
        .find(sessionId)
        .then(function(session) {
            session.destroy().success(function() {
                return res.redirect('/sessions/');
            }).error(next);
        }).error(next);
};

exports.addData = function (req, res, next) {
    var sessionId = req.params.sid;

    var Visualization = models.Visualization;

    if(req.is('json')) {
        Visualization
            .create({
                data: req.body.data,
                type: req.body.type,
                SessionId: sessionId
            }).then(function(viz) {
                req.io.of('/sessions/' + sessionId)
                    .emit('viz', viz);
                return res.json(viz);
            }).error(next);
    } else {
        var form = new multiparty.Form();

        form.parse(req, function(err, fields, files) {

            console.log(fields.type[0]);
            _.each(files, function(f) {
                thumbnailAndUpload(f, sessionId, function(err, data) {

                    var imgData = data.imgData;

                    console.log(imgData);

                    var type = 'image';
                    if(fields.type) {
                        if(_.isArray(fields.type) || _.isObject(fields.type)) {
                            type = fields.type[0];
                        } else {
                            type = fields.type;
                        }
                    }

                    Visualization
                        .create({
                            type:  type,
                            images: [imgData],
                            SessionId: sessionId
                        }).then(function(viz) {
                            req.io.of('/sessions/' + sessionId)
                                .emit('viz', viz);

                            return res.json(viz);
                        }).error(next);
                });
            });
        });
    }
};

exports.getData = function (req, res, next) {
    var vizId = req.params.vid;

    var Visualization = models.Visualization;

    Visualization
        .find(vizId)
        .then(function(viz) {
            return res.json({
                data: viz.data
            });
        }).error(next);
};

exports.getDataField = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;

    console.log('getting data field ' + fieldName);

    models.Visualization
        .getNamedObjectForVisualization(vizId, fieldName)
        .then(function(data) {
            return res.json({
                data: data
            });
        }).error(next);
};

exports.getDataAtIndex = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;
    var index = req.params.index;

    models.Visualization
        .getNamedObjectAtIndexForVisualization(vizId, fieldName, index)
        .then(function(data) {
            return res.json({
                data: data[0][fieldName]
            });
        }).error(next);
};

exports.updateData = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;

    models.Visualization
        .find(vizId)
        .then(function(viz) {

            if(fieldName) {
                viz.data[fieldName] = req.body.data;
            } else {
                viz.data = req.body.data;
            }

            viz.save()
                .then(function() {
                    return res.json(viz);
                }).error(next);
        }).error(next);
};

exports.appendData = function (req, res, next) {

    var sessionId = req.params.sid;
    var vizId = req.params.vid;
    var fieldName = req.params.field;

    models.Visualization
        .find(vizId)
        .then(function(viz) {
            if(req.is('json')) {

                if(fieldName) {

                    if(_.isArray(viz.data[fieldName])) {
                        viz.data[fieldName].push(req.body.data);
                    } else if(_.isUndefined(viz.data[fieldName])) {
                        console.log(fieldName);
                        viz.data[fieldName] = req.body.data;
                    } else {
                        console.log('unknown field');
                    }
                } else {
                    if(_.isArray(viz.data)) {
                        viz.data.push(req.body.data);
                    } else if(_.isUndefined(viz.data)) {
                        viz.data = req.body.data;
                    } else {
                        console.log('unknown field');
                    }
                }

                viz
                    .save()
                    .then(function() {
                        return res.json(viz);
                    }).error(next);

            } else if(fieldName === 'images') {

                var form = new multiparty.Form();

                form.parse(req, function(err, fields, files) {
                    _.each(files, function(f) {
                        thumbnailAndUpload(f, sessionId, function(err, data) {

                            var imgData = data.imgData;
                            var s3Response = data.response;

                            if(viz.images) {
                                viz.images.push(imgData);
                            } else {
                                viz.images = [imgData];
                            }
                            viz
                                .save()
                                .then(function() {
                                    res.statusCode = s3Response.statusCode;
                                    s3Response.pipe(res);
                                });

                            req.io.of('/sessions/' + sessionId)
                                .emit('update', {
                                    vizId: viz.id,
                                    data: imgData
                                });

                        });
                    });
                });
            } else {
                return next(500);
            }

        }).error(next);

};

var thumbnailAndUpload = function(f, sessionId, callback) {

    var maxWidth = 500;
    var maxHeight = 500;

    // Image file info
    var imgPath = f[0].path;
    var extension = path.extname(imgPath).toLowerCase();
    var filenameWithoutExtension = path.basename(imgPath, extension);

    var thumbnailPath;

    if(process.env.NODE_ENV === 'production') {
        thumbnailPath = path.resolve(__dirname + '/../../'  + './tmp/' + filenameWithoutExtension + '_thumbnail' + extension);
    } else {
        thumbnailPath = path.dirname(imgPath) + filenameWithoutExtension + '_thumbnail' + extension;
    }

    // Upload paths for s3
    var uploadName = randomstring.generate();
    var destPath = '/sessions/' + sessionId + '/';
    var originalS3Path = destPath + uploadName;
    var thumbnailS3Path = destPath + uploadName + '_small';

    // s3 headers
    var headers = {
      'x-amz-acl': 'public-read',
    };
    if( extension === '.jpg' || extension === '.jpeg' ) {
        headers['Content-Type'] = 'image/jpeg';
    } else if (extension === '.png') {
        headers['Content-Type'] = 'image/png';
    }

    easyimage
        .info(imgPath)
        .then(function(file) {
            var thumbWidth;
            var thumbHeight;

            console.log('outputing to: ' + thumbnailPath);

            if(file.width > file.height) {
                thumbWidth = Math.min(maxWidth, file.width);
                thumbHeight = file.height * (thumbWidth / file.width);
            } else {
                thumbHeight = Math.min(maxHeight, file.height);
                thumbWidth = file.width * (thumbHeight / file.height);
            }

            return easyimage.resize({
                src: imgPath,
                dst: thumbnailPath,
                width: thumbWidth,
                height: thumbHeight
            });
        }).then(function() {
            async.parallel([
                function(callback) {
                    console.log(imgPath + ':' + originalS3Path);
                    s3Client.putFile(imgPath, originalS3Path, headers, callback);
                },
                function(callback) {
                    console.log(thumbnailPath + ':' + thumbnailS3Path);
                    s3Client.putFile(thumbnailPath, thumbnailS3Path, headers, callback);
                }
            ], function(err, results) {
                var s3Response = results[0];

                var imgURL = 'https://s3.amazonaws.com/' + process.env.S3_BUCKET + originalS3Path;
                // var thumbURL = 'https://s3.amazonaws.com/' + process.env.S3_BUCKET + thumbnailS3Path;

                var imgData = imgURL;
                // {
                //     original: imgURL,
                //     thumbnail: thumbURL
                // };

                callback(null, {
                    response: s3Response,
                    imgData: imgData
                });

            });
        }, function(err) {
            console.log(err);
            callback(err);
        });
};<commit_msg>remove extraneous debug<commit_after>
/*!
 * Module dependencies.
 */

var _ = require('lodash');
var multiparty = require('multiparty');
var knox = require('knox');
var randomstring = require('randomstring');
var path = require('path');
var easyimage = require('easyimage');
var async = require('async');
var models = require('../models');
var Q = require('q');

var s3Client = knox.createClient({
    secure: false,
    key: process.env.S3_KEY,
    secret: process.env.S3_SECRET,
    bucket: process.env.S3_BUCKET,
});

exports.index = function (req, res, next) {

    models.Session.findAll({
        order: '"createdAt" DESC'
    }).then(function(sessions) {
        res.render('session/index', {
            sessions: sessions
        });
    }).error(next);
};

exports.feed = function (req, res, next) {

    var sessionId = req.params.sid;
    var Session = models.Session;
    var VisualizationType = models.VisualizationType;
    var Visualization = models.Visualization;

    Q.all([
        Session
            .find({
                where: {
                    id: sessionId
                }
            }),
        Visualization
            .findAll({
                where: {
                    SessionId: sessionId
                }
            }),
        VisualizationType.findAll()
    ]).spread(function(session, visualizations, vizTypes) {

        if(!session) {
            return res.status(404).send('Session not found');
        }

        _.each(visualizations, function(viz) {
            console.log(viz.images);
        });

        res.render('session/feed', {
            session: session,
            visualizations: visualizations,
            vizTypes: _.object(_.map(vizTypes, function(item) {
                return [item.name, item];
            }))
        });
    }).fail(next);
};

exports.update = function (req, res, next) {

    var sessionId = req.params.sid;
    var Session = models.Session;

    Session
        .update(req.body, {
            id: sessionId
        }).success(function(sessions) {
            return res.json(sessions);
        }).error(next);

};
exports.updateVisualization = function (req, res, next) {

    var vid = req.params.vid;
    var Visualization = models.Visualization;

    console.log('updating visualization ' + vid);

    Visualization
        .update(req.body, {
            id: vid
        }).success(function(visualizations) {
            return res.status(200).send();
        }).error(function(err) {
            console.log(err);
            return res.status(500).send();
        });

};

exports.read = function (req, res, next) {

    var vizId = req.params.vid;
    var Visualization = models.Visualization;
    var VisualizationType = models.VisualizationType;

    Q.all([
        Visualization.find(vizId),
        VisualizationType.findAll()
    ]).spread(function(viz, vizTypes) {
            res.render('session/visualization', {
                viz: viz,
                vizTypes: _.object(_.map(vizTypes, function(item) {
                    return [item.name, item];
                }))
            });
    }).fail(next);
};

exports.create = function(req, res, next) {

    models.Session
        .create(_.pick(req.body, 'name'))
        .then(function(session) {
            return res.json(session);
        }).error(next);
};

exports.getCreate = function(req, res, next) {
    models.Session
        .create()
        .then(function(session) {
            return res.redirect('/sessions/' + session.id + '/feed/');
        }).error(next);
};

exports.delete = function(req, res, next) {
    var sessionId = req.params.sid;

    models.Session
        .find(sessionId)
        .then(function(session) {
            session.destroy().success(function() {
                return res.json(session);
            }).error(next);
        }).error(next);
};

exports.getDelete = function(req, res, next) {

    var sessionId = req.params.sid;

    models.Session
        .find(sessionId)
        .then(function(session) {
            session.destroy().success(function() {
                return res.redirect('/sessions/');
            }).error(next);
        }).error(next);
};

exports.addData = function (req, res, next) {
    var sessionId = req.params.sid;

    var Visualization = models.Visualization;

    if(req.is('json')) {
        Visualization
            .create({
                data: req.body.data,
                type: req.body.type,
                SessionId: sessionId
            }).then(function(viz) {
                req.io.of('/sessions/' + sessionId)
                    .emit('viz', viz);
                return res.json(viz);
            }).error(next);
    } else {
        var form = new multiparty.Form();

        form.parse(req, function(err, fields, files) {

            _.each(files, function(f) {
                thumbnailAndUpload(f, sessionId, function(err, data) {

                    var imgData = data.imgData;

                    console.log(imgData);

                    var type = 'image';
                    if(fields.type) {
                        if(_.isArray(fields.type) || _.isObject(fields.type)) {
                            type = fields.type[0];
                        } else {
                            type = fields.type;
                        }
                    }

                    Visualization
                        .create({
                            type:  type,
                            images: [imgData],
                            SessionId: sessionId
                        }).then(function(viz) {
                            req.io.of('/sessions/' + sessionId)
                                .emit('viz', viz);

                            return res.json(viz);
                        }).error(next);
                });
            });
        });
    }
};

exports.getData = function (req, res, next) {
    var vizId = req.params.vid;

    var Visualization = models.Visualization;

    Visualization
        .find(vizId)
        .then(function(viz) {
            return res.json({
                data: viz.data
            });
        }).error(next);
};

exports.getDataField = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;

    console.log('getting data field ' + fieldName);

    models.Visualization
        .getNamedObjectForVisualization(vizId, fieldName)
        .then(function(data) {
            return res.json({
                data: data
            });
        }).error(next);
};

exports.getDataAtIndex = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;
    var index = req.params.index;

    models.Visualization
        .getNamedObjectAtIndexForVisualization(vizId, fieldName, index)
        .then(function(data) {
            return res.json({
                data: data[0][fieldName]
            });
        }).error(next);
};

exports.updateData = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;

    models.Visualization
        .find(vizId)
        .then(function(viz) {

            if(fieldName) {
                viz.data[fieldName] = req.body.data;
            } else {
                viz.data = req.body.data;
            }

            viz.save()
                .then(function() {
                    return res.json(viz);
                }).error(next);
        }).error(next);
};

exports.appendData = function (req, res, next) {

    var sessionId = req.params.sid;
    var vizId = req.params.vid;
    var fieldName = req.params.field;

    models.Visualization
        .find(vizId)
        .then(function(viz) {
            if(req.is('json')) {

                if(fieldName) {

                    if(_.isArray(viz.data[fieldName])) {
                        viz.data[fieldName].push(req.body.data);
                    } else if(_.isUndefined(viz.data[fieldName])) {
                        console.log(fieldName);
                        viz.data[fieldName] = req.body.data;
                    } else {
                        console.log('unknown field');
                    }
                } else {
                    if(_.isArray(viz.data)) {
                        viz.data.push(req.body.data);
                    } else if(_.isUndefined(viz.data)) {
                        viz.data = req.body.data;
                    } else {
                        console.log('unknown field');
                    }
                }

                viz
                    .save()
                    .then(function() {
                        return res.json(viz);
                    }).error(next);

            } else if(fieldName === 'images') {

                var form = new multiparty.Form();

                form.parse(req, function(err, fields, files) {
                    _.each(files, function(f) {
                        thumbnailAndUpload(f, sessionId, function(err, data) {

                            var imgData = data.imgData;
                            var s3Response = data.response;

                            if(viz.images) {
                                viz.images.push(imgData);
                            } else {
                                viz.images = [imgData];
                            }
                            viz
                                .save()
                                .then(function() {
                                    res.statusCode = s3Response.statusCode;
                                    s3Response.pipe(res);
                                });

                            req.io.of('/sessions/' + sessionId)
                                .emit('update', {
                                    vizId: viz.id,
                                    data: imgData
                                });

                        });
                    });
                });
            } else {
                return next(500);
            }

        }).error(next);

};

var thumbnailAndUpload = function(f, sessionId, callback) {

    var maxWidth = 500;
    var maxHeight = 500;

    // Image file info
    var imgPath = f[0].path;
    var extension = path.extname(imgPath).toLowerCase();
    var filenameWithoutExtension = path.basename(imgPath, extension);

    var thumbnailPath;

    if(process.env.NODE_ENV === 'production') {
        thumbnailPath = path.resolve(__dirname + '/../../'  + './tmp/' + filenameWithoutExtension + '_thumbnail' + extension);
    } else {
        thumbnailPath = path.dirname(imgPath) + filenameWithoutExtension + '_thumbnail' + extension;
    }

    // Upload paths for s3
    var uploadName = randomstring.generate();
    var destPath = '/sessions/' + sessionId + '/';
    var originalS3Path = destPath + uploadName;
    var thumbnailS3Path = destPath + uploadName + '_small';

    // s3 headers
    var headers = {
      'x-amz-acl': 'public-read',
    };
    if( extension === '.jpg' || extension === '.jpeg' ) {
        headers['Content-Type'] = 'image/jpeg';
    } else if (extension === '.png') {
        headers['Content-Type'] = 'image/png';
    }

    easyimage
        .info(imgPath)
        .then(function(file) {
            var thumbWidth;
            var thumbHeight;

            console.log('outputing to: ' + thumbnailPath);

            if(file.width > file.height) {
                thumbWidth = Math.min(maxWidth, file.width);
                thumbHeight = file.height * (thumbWidth / file.width);
            } else {
                thumbHeight = Math.min(maxHeight, file.height);
                thumbWidth = file.width * (thumbHeight / file.height);
            }

            return easyimage.resize({
                src: imgPath,
                dst: thumbnailPath,
                width: thumbWidth,
                height: thumbHeight
            });
        }).then(function() {
            async.parallel([
                function(callback) {
                    console.log(imgPath + ':' + originalS3Path);
                    s3Client.putFile(imgPath, originalS3Path, headers, callback);
                },
                function(callback) {
                    console.log(thumbnailPath + ':' + thumbnailS3Path);
                    s3Client.putFile(thumbnailPath, thumbnailS3Path, headers, callback);
                }
            ], function(err, results) {
                var s3Response = results[0];

                var imgURL = 'https://s3.amazonaws.com/' + process.env.S3_BUCKET + originalS3Path;
                // var thumbURL = 'https://s3.amazonaws.com/' + process.env.S3_BUCKET + thumbnailS3Path;

                var imgData = imgURL;
                // {
                //     original: imgURL,
                //     thumbnail: thumbURL
                // };

                callback(null, {
                    response: s3Response,
                    imgData: imgData
                });

            });
        }, function(err) {
            console.log(err);
            callback(err);
        });
};<|endoftext|>


<commit_before>import React from 'react';

export const IDENTIFIER_FIELDS = ['title', 'path'];

export const INFERABLE_FIELDS = {
  title: {
    type: 'string',
    secondaryTypes: [],
    synonyms: ['title', 'name', 'label', 'headline', 'header'],
    defaultPreview: value =>
{value}
, // eslint-disable-line react/display-name
    fallbackToFirstField: true,
    showError: true,
  },
  shortTitle: {
    type: 'string',
    secondaryTypes: [],
    synonyms: ['short_title', 'shortTitle', 'short'],
    defaultPreview: value =>
{value}
, // eslint-disable-line react/display-name
    fallbackToFirstField: false,
    showError: false,
  },
  author: {
    type: 'string',
    secondaryTypes: [],
    synonyms: ['author', 'name', 'by', 'byline', 'owner'],
    defaultPreview: value => {value}, // eslint-disable-line react/display-name
    fallbackToFirstField: false,
    showError: false,
  },
  date: {
    type: 'datetime',
    secondaryTypes: ['date'],
    synonyms: ['date', 'publishDate', 'publish_date'],
    defaultPreview: value => value,
    fallbackToFirstField: false,
    showError: false,
  },
  description: {
    type: 'string',
    secondaryTypes: ['text', 'markdown'],
    synonyms: [
      'shortDescription',
      'short_description',
      'shortdescription',
      'description',
      'intro',
      'introduction',
      'brief',
      'content',
      'biography',
      'bio',
      'summary',
    ],
    defaultPreview: value => value,
    fallbackToFirstField: false,
    showError: false,
  },
  image: {
    type: 'image',
    secondaryTypes: [],
    synonyms: ['image', 'thumbnail', 'thumb', 'picture', 'avatar', 'photo', 'cover'],
    defaultPreview: value => value,
    fallbackToFirstField: false,
    showError: false,
  },
};
<commit_msg>feat: Add 'hero' as inferable image field (#3294)<commit_after>import React from 'react';

export const IDENTIFIER_FIELDS = ['title', 'path'];

export const INFERABLE_FIELDS = {
  title: {
    type: 'string',
    secondaryTypes: [],
    synonyms: ['title', 'name', 'label', 'headline', 'header'],
    defaultPreview: value =>
{value}
, // eslint-disable-line react/display-name
    fallbackToFirstField: true,
    showError: true,
  },
  shortTitle: {
    type: 'string',
    secondaryTypes: [],
    synonyms: ['short_title', 'shortTitle', 'short'],
    defaultPreview: value =>
{value}
, // eslint-disable-line react/display-name
    fallbackToFirstField: false,
    showError: false,
  },
  author: {
    type: 'string',
    secondaryTypes: [],
    synonyms: ['author', 'name', 'by', 'byline', 'owner'],
    defaultPreview: value => {value}, // eslint-disable-line react/display-name
    fallbackToFirstField: false,
    showError: false,
  },
  date: {
    type: 'datetime',
    secondaryTypes: ['date'],
    synonyms: ['date', 'publishDate', 'publish_date'],
    defaultPreview: value => value,
    fallbackToFirstField: false,
    showError: false,
  },
  description: {
    type: 'string',
    secondaryTypes: ['text', 'markdown'],
    synonyms: [
      'shortDescription',
      'short_description',
      'shortdescription',
      'description',
      'intro',
      'introduction',
      'brief',
      'content',
      'biography',
      'bio',
      'summary',
    ],
    defaultPreview: value => value,
    fallbackToFirstField: false,
    showError: false,
  },
  image: {
    type: 'image',
    secondaryTypes: [],
    synonyms: ['image', 'thumbnail', 'thumb', 'picture', 'avatar', 'photo', 'cover', 'hero'],
    defaultPreview: value => value,
    fallbackToFirstField: false,
    showError: false,
  },
};
<|endoftext|>


<commit_before>var React = require("react");
var Router = require("react-router");
var debounce = require("debounce");
var ExecutionEnvironment = require("exenv");
var storeClientSize = require("./storeClientSize.js");

/**
 * Client Router is used to handle client routing
 * @return {Promise}
 */
module.exports = function clientContext(cfg) {
    /* eslint-disable react/no-multi-comp */
    var ClientContext = React.createClass({
        childContextTypes: {
            radiumConfig: React.PropTypes.shape({
                userAgent: React.PropTypes.string
            })
        },

        componentDidMount: function () {
            if (ExecutionEnvironment.canUseDOM) {
                window.addEventListener("resize", this.onResize);
                this.onResize();
            }
        },

        componentWillUnmount: function () {
            if (ExecutionEnvironment.canUseDOM) {
                window.removeEventListener("resize", this.onResize);
            }
        },

        onResize: debounce(function () {
            storeClientSize(window);
        }, 50),

        getChildContext() {
            // Pass user agent to Radium
            return {
                radiumConfig: {
                    userAgent: ExecutionEnvironment.canUseDOM ? window.navigator.userAgent : null
                }
            };
        },

        render: function () {
            return (
                React.createElement(Router.default || Router, cfg, cfg.routes)
            );
        }
    });

    return React.createElement(ClientContext);
};
<commit_msg>fix(react-wildcat-handoff): make es5-friendly<commit_after>var React = require("react");
var Router = require("react-router");
var debounce = require("debounce");
var ExecutionEnvironment = require("exenv");
var storeClientSize = require("./storeClientSize.js");

/**
 * Client Router is used to handle client routing
 * @return {Promise}
 */
module.exports = function clientContext(cfg) {
    /* eslint-disable react/no-multi-comp */
    var ClientContext = React.createClass({
        childContextTypes: {
            radiumConfig: React.PropTypes.shape({
                userAgent: React.PropTypes.string
            })
        },

        componentDidMount: function () {
            if (ExecutionEnvironment.canUseDOM) {
                window.addEventListener("resize", this.onResize);
                this.onResize();
            }
        },

        componentWillUnmount: function () {
            if (ExecutionEnvironment.canUseDOM) {
                window.removeEventListener("resize", this.onResize);
            }
        },

        onResize: debounce(function () {
            storeClientSize(window);
        }, 50),

        getChildContext: function () {
            // Pass user agent to Radium
            return {
                radiumConfig: {
                    userAgent: ExecutionEnvironment.canUseDOM ? window.navigator.userAgent : null
                }
            };
        },

        render: function () {
            return (
                React.createElement(Router.default || Router, cfg, cfg.routes)
            );
        }
    });

    return React.createElement(ClientContext);
};
<|endoftext|>


<commit_before>
import { Meteor } from 'meteor/meteor';

class RoomStreamer extends Meteor.Streamer {
	_publish(publication, eventName, options) {
		super._publish(publication, eventName, options);
		const uid = Meteor.userId();
		if (/rooms-changed/.test(eventName)) {
			const roomEvent = (...args) => {
				RocketChat.Notifications.notifyUserInThisInstance(uid, 'rooms-changed', ...args);
			};
			const rooms = RocketChat.models.Subscriptions.find({ 'u._id': uid }, { fields: { rid: 1 } }).fetch();
			rooms.forEach(({ rid }) => {
				this.on(rid, roomEvent);
			});

			const userEvent = (clientAction, { rid }) => {
				switch (clientAction) {
					case 'inserted':
						rooms.push({ rid });
						this.on(rid, roomEvent);
						break;

					case 'removed':
						this.removeListener(rid, roomEvent);
						break;
				}
			};
			this.on(uid, userEvent);

			publication.onStop(() => {
				this.removeListener(uid, userEvent);
				rooms.forEach(({ rid }) => this.removeListener(rid, roomEvent));
			});
		}
	}
}

RocketChat.Notifications = new class {
	constructor() {
		this.debug = false;
		this.streamAll = new Meteor.Streamer('notify-all');
		this.streamLogged = new Meteor.Streamer('notify-logged');
		this.streamRoom = new Meteor.Streamer('notify-room');
		this.streamRoomUsers = new Meteor.Streamer('notify-room-users');
		this.streamUser = new RoomStreamer('notify-user');
		this.streamAll.allowWrite('none');
		this.streamLogged.allowWrite('none');
		this.streamRoom.allowWrite('none');
		this.streamRoomUsers.allowWrite(function(eventName, ...args) {
			const [roomId, e] = eventName.split('/');
			// const user = Meteor.users.findOne(this.userId, {
			// 	fields: {
			// 		username: 1
			// 	}
			// });
			if (RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId) != null) {
				const subscriptions = RocketChat.models.Subscriptions.findByRoomIdAndNotUserId(roomId, this.userId).fetch();
				subscriptions.forEach((subscription) => RocketChat.Notifications.notifyUser(subscription.u._id, e, ...args));
			}
			return false;
		});
		this.streamUser.allowWrite('logged');
		this.streamAll.allowRead('all');
		this.streamLogged.allowRead('logged');
		this.streamRoom.allowRead(function(eventName, extraData) {
			const [roomId] = eventName.split('/');
			const room = RocketChat.models.Rooms.findOneById(roomId);
			if (!room) {
				console.warn(`Invalid streamRoom eventName: "${ eventName }"`);
				return false;
			}
			if (room.t === 'l' && extraData && extraData.token && room.v.token === extraData.token) {
				return true;
			}
			if (this.userId == null) {
				return false;
			}
			const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId, { fields: { _id: 1 } });
			return subscription != null;
		});
		this.streamRoomUsers.allowRead('none');
		this.streamUser.allowRead(function(eventName) {
			const [userId] = eventName.split('/');
			return (this.userId != null) && this.userId === userId;
		});
	}

	notifyAll(eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyAll', [eventName, ...args]);
		}
		args.unshift(eventName);
		return this.streamAll.emit.apply(this.streamAll, args);
	}

	notifyLogged(eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyLogged', [eventName, ...args]);
		}
		args.unshift(eventName);
		return this.streamLogged.emit.apply(this.streamLogged, args);
	}

	notifyRoom(room, eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyRoom', [room, eventName, ...args]);
		}
		args.unshift(`${ room }/${ eventName }`);
		return this.streamRoom.emit.apply(this.streamRoom, args);
	}

	notifyUser(userId, eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyUser', [userId, eventName, ...args]);
		}
		args.unshift(`${ userId }/${ eventName }`);
		return this.streamUser.emit.apply(this.streamUser, args);
	}

	notifyAllInThisInstance(eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyAll', [eventName, ...args]);
		}
		args.unshift(eventName);
		return this.streamAll.emitWithoutBroadcast.apply(this.streamAll, args);
	}

	notifyLoggedInThisInstance(eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyLogged', [eventName, ...args]);
		}
		args.unshift(eventName);
		return this.streamLogged.emitWithoutBroadcast.apply(this.streamLogged, args);
	}

	notifyRoomInThisInstance(room, eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyRoomAndBroadcast', [room, eventName, ...args]);
		}
		args.unshift(`${ room }/${ eventName }`);
		return this.streamRoom.emitWithoutBroadcast.apply(this.streamRoom, args);
	}

	notifyUserInThisInstance(userId, eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyUserAndBroadcast', [userId, eventName, ...args]);
		}
		args.unshift(`${ userId }/${ eventName }`);
		return this.streamUser.emitWithoutBroadcast.apply(this.streamUser, args);
	}
};

RocketChat.Notifications.streamRoom.allowWrite(function(eventName, username, typing, extraData) {
	const [roomId, e] = eventName.split('/');

	if (e === 'webrtc') {
		return true;
	}
	if (e === 'typing') {
		const key = RocketChat.settings.get('UI_Use_Real_Name') ? 'name' : 'username';
		// typing from livechat widget
		if (extraData && extraData.token) {
			const room = RocketChat.models.Rooms.findOneById(roomId);
			if (room && room.t === 'l' && room.v.token === extraData.token) {
				return true;
			}
		}

		const user = Meteor.users.findOne(this.userId, {
			fields: {
				[key]: 1,
			},
		});

		if (!user) {
			return false;
		}

		return user[key] === username;
	}
	return false;
});
<commit_msg>[FIX] multiple rooms-changed (#12940)<commit_after>
import { Meteor } from 'meteor/meteor';
import { DDPCommon } from 'meteor/ddp-common';

const changedPayload = function(collection, id, fields) {
	return DDPCommon.stringifyDDP({
		msg: 'changed',
		collection,
		id,
		fields,
	});
};
const send = function(self, msg) {
	if (!self.socket) {
		return;
	}
	self.socket.send(msg);
};
class RoomStreamer extends Meteor.Streamer {
	_publish(publication, eventName, options) {
		super._publish(publication, eventName, options);
		const uid = Meteor.userId();
		if (/rooms-changed/.test(eventName)) {
			const roomEvent = (...args) => send(publication._session, changedPayload(this.subscriptionName, 'id', {
				eventName: `${ uid }/rooms-changed`,
				args,
			}));
			const rooms = RocketChat.models.Subscriptions.find({ 'u._id': uid }, { fields: { rid: 1 } }).fetch();
			rooms.forEach(({ rid }) => {
				this.on(rid, roomEvent);
			});

			const userEvent = (clientAction, { rid }) => {
				switch (clientAction) {
					case 'inserted':
						rooms.push({ rid });
						this.on(rid, roomEvent);
						break;

					case 'removed':
						this.removeListener(rid, roomEvent);
						break;
				}
			};
			this.on(uid, userEvent);

			publication.onStop(() => {
				this.removeListener(uid, userEvent);
				rooms.forEach(({ rid }) => this.removeListener(rid, roomEvent));
			});
		}
	}
}

RocketChat.Notifications = new class {
	constructor() {
		this.debug = false;
		this.streamAll = new Meteor.Streamer('notify-all');
		this.streamLogged = new Meteor.Streamer('notify-logged');
		this.streamRoom = new Meteor.Streamer('notify-room');
		this.streamRoomUsers = new Meteor.Streamer('notify-room-users');
		this.streamUser = new RoomStreamer('notify-user');
		this.streamAll.allowWrite('none');
		this.streamLogged.allowWrite('none');
		this.streamRoom.allowWrite('none');
		this.streamRoomUsers.allowWrite(function(eventName, ...args) {
			const [roomId, e] = eventName.split('/');
			// const user = Meteor.users.findOne(this.userId, {
			// 	fields: {
			// 		username: 1
			// 	}
			// });
			if (RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId) != null) {
				const subscriptions = RocketChat.models.Subscriptions.findByRoomIdAndNotUserId(roomId, this.userId).fetch();
				subscriptions.forEach((subscription) => RocketChat.Notifications.notifyUser(subscription.u._id, e, ...args));
			}
			return false;
		});
		this.streamUser.allowWrite('logged');
		this.streamAll.allowRead('all');
		this.streamLogged.allowRead('logged');
		this.streamRoom.allowRead(function(eventName, extraData) {
			const [roomId] = eventName.split('/');
			const room = RocketChat.models.Rooms.findOneById(roomId);
			if (!room) {
				console.warn(`Invalid streamRoom eventName: "${ eventName }"`);
				return false;
			}
			if (room.t === 'l' && extraData && extraData.token && room.v.token === extraData.token) {
				return true;
			}
			if (this.userId == null) {
				return false;
			}
			const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId, { fields: { _id: 1 } });
			return subscription != null;
		});
		this.streamRoomUsers.allowRead('none');
		this.streamUser.allowRead(function(eventName) {
			const [userId] = eventName.split('/');
			return (this.userId != null) && this.userId === userId;
		});
	}

	notifyAll(eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyAll', [eventName, ...args]);
		}
		args.unshift(eventName);
		return this.streamAll.emit.apply(this.streamAll, args);
	}

	notifyLogged(eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyLogged', [eventName, ...args]);
		}
		args.unshift(eventName);
		return this.streamLogged.emit.apply(this.streamLogged, args);
	}

	notifyRoom(room, eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyRoom', [room, eventName, ...args]);
		}
		args.unshift(`${ room }/${ eventName }`);
		return this.streamRoom.emit.apply(this.streamRoom, args);
	}

	notifyUser(userId, eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyUser', [userId, eventName, ...args]);
		}
		args.unshift(`${ userId }/${ eventName }`);
		return this.streamUser.emit.apply(this.streamUser, args);
	}

	notifyAllInThisInstance(eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyAll', [eventName, ...args]);
		}
		args.unshift(eventName);
		return this.streamAll.emitWithoutBroadcast.apply(this.streamAll, args);
	}

	notifyLoggedInThisInstance(eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyLogged', [eventName, ...args]);
		}
		args.unshift(eventName);
		return this.streamLogged.emitWithoutBroadcast.apply(this.streamLogged, args);
	}

	notifyRoomInThisInstance(room, eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyRoomAndBroadcast', [room, eventName, ...args]);
		}
		args.unshift(`${ room }/${ eventName }`);
		return this.streamRoom.emitWithoutBroadcast.apply(this.streamRoom, args);
	}

	notifyUserInThisInstance(userId, eventName, ...args) {
		if (this.debug === true) {
			console.log('notifyUserAndBroadcast', [userId, eventName, ...args]);
		}
		args.unshift(`${ userId }/${ eventName }`);
		return this.streamUser.emitWithoutBroadcast.apply(this.streamUser, args);
	}
};

RocketChat.Notifications.streamRoom.allowWrite(function(eventName, username, typing, extraData) {
	const [roomId, e] = eventName.split('/');

	if (e === 'webrtc') {
		return true;
	}
	if (e === 'typing') {
		const key = RocketChat.settings.get('UI_Use_Real_Name') ? 'name' : 'username';
		// typing from livechat widget
		if (extraData && extraData.token) {
			const room = RocketChat.models.Rooms.findOneById(roomId);
			if (room && room.t === 'l' && room.v.token === extraData.token) {
				return true;
			}
		}

		const user = Meteor.users.findOne(this.userId, {
			fields: {
				[key]: 1,
			},
		});

		if (!user) {
			return false;
		}

		return user[key] === username;
	}
	return false;
});
<|endoftext|>


<commit_before>var forEach = require('./lodash').forEach
var isString = require('./lodash').isString

function addEventListener (el, type, fn) {
  if (el.addEventListener) {
    el.addEventListener(type, handler)
    return function () {
      el.removeEventListener(type, handler)
    }
  } else if (el.attachEvent) {
    el.attachEvent('on' + type, handler)
    return function () {
      el.detachEvent('on' + type, handler)
    }
  } else {
    throw new Error('addEventListener')
  }

  function handler (event) {
    var e = event || global.window.event
    return fn.call(el, e)
  }
}

function shouldIgnoreElement (el) {
  var tag = el.tagName.toLowerCase()
  var type = el.getAttribute('type')
  if (tag === 'input' && type === 'password') {
    return true
  }

  var role = el.getAttribute('role')
  if (
    role === 'button' ||
    role === 'link' ||
    tag === 'a' ||
    tag === 'button' ||
    tag === 'input'
  ) {
    return false
  }

  return true
}

function createTreeHasIgnoreAttribute (ignoreAttribute) {
  return function treeHasIgnoreAttribute (el) {
    if (!el || el.tagName.toLowerCase() === 'html') {
      return false
    } else if (el.getAttribute(ignoreAttribute)) {
      return true
    } else {
      return treeHasIgnoreAttribute(el.parentNode)
    }
  }
}

function getElementData (el) {
  var data = {
    tag: el.tagName.toLowerCase(),
    tree: htmlTreeAsString(el)
  }

  forEach([
    'alt',
    'class',
    'href',
    'id',
    'name',
    'role',
    'title',
    'type'
  ], function (attrName) {
    var attr = el[attrName] || el.getAttribute(attr)
    if (attr) {
      data[attrName] = attr
    }
  })

  return data
}

/**
 * ORIGINAL SOURCE: https://github.com/getsentry/raven-js/
 * Given a child DOM element, returns a query-selector statement describing that
 * and its ancestors
 * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
 * @param elem
 * @returns {string}
 */
function htmlTreeAsString (elem) {
  var MAX_TRAVERSE_HEIGHT = 5
  var MAX_OUTPUT_LEN = 80
  var out = []
  var height = 0
  var len = 0
  var separator = ' > '
  var sepLength = separator.length
  var nextStr

  while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
    nextStr = htmlElementAsString(elem)
    // bail out if
    // - nextStr is the 'html' element
    // - the length of the string that would be created exceeds MAX_OUTPUT_LEN
    //   (ignore this limit if we are on the first iteration)
    if (
      nextStr === 'html' ||
      height > 1 &&
      len + (out.length * sepLength) + nextStr.length >= MAX_OUTPUT_LEN
    ) {
      break
    }

    out.push(nextStr)

    len += nextStr.length
    elem = elem.parentNode
  }

  return out.reverse().join(separator)
}

/**
 * ORIGINAL SOURCE: https://github.com/getsentry/raven-js/
 * Returns a simple, query-selector representation of a DOM element
 * e.g. [HTMLElement] => input#foo.btn[name=baz]
 * @param HTMLElement
 * @returns {string}
 */
function htmlElementAsString (elem) {
  var out = []
  var className
  var classes
  var key
  var attr
  var i

  if (!elem || !elem.tagName) {
    return ''
  }

  out.push(elem.tagName.toLowerCase())
  if (elem.id) {
    out.push('#' + elem.id)
  }

  className = elem.className
  if (className && isString(className)) {
    classes = className.split(' ')
    for (i = 0; i < classes.length; i++) {
      out.push('.' + classes[i])
    }
  }
  var attrWhitelist = ['type', 'name', 'title', 'alt']
  for (i = 0; i < attrWhitelist.length; i++) {
    key = attrWhitelist[i]
    attr = elem.getAttribute(key)
    if (attr) {
      out.push('[' + key + '="' + attr + '"]')
    }
  }
  return out.join('')
}

module.exports = {
  addEventListener: addEventListener,
  createTreeHasIgnoreAttribute: createTreeHasIgnoreAttribute,
  getElementData: getElementData,
  htmlElementAsString: htmlElementAsString,
  htmlTreeAsString: htmlTreeAsString,
  shouldIgnoreElement: shouldIgnoreElement
}
<commit_msg>Simplify prop access<commit_after>var forEach = require('./lodash').forEach
var isString = require('./lodash').isString

function addEventListener (el, type, fn) {
  if (el.addEventListener) {
    el.addEventListener(type, handler)
    return function () {
      el.removeEventListener(type, handler)
    }
  } else if (el.attachEvent) {
    el.attachEvent('on' + type, handler)
    return function () {
      el.detachEvent('on' + type, handler)
    }
  } else {
    throw new Error('addEventListener')
  }

  function handler (event) {
    var e = event || global.event
    return fn.call(el, e)
  }
}

function shouldIgnoreElement (el) {
  var tag = el.tagName.toLowerCase()
  var type = el.getAttribute('type')
  if (tag === 'input' && type === 'password') {
    return true
  }

  var role = el.getAttribute('role')
  if (
    role === 'button' ||
    role === 'link' ||
    tag === 'a' ||
    tag === 'button' ||
    tag === 'input'
  ) {
    return false
  }

  return true
}

function createTreeHasIgnoreAttribute (ignoreAttribute) {
  return function treeHasIgnoreAttribute (el) {
    if (!el || el.tagName.toLowerCase() === 'html') {
      return false
    } else if (el.getAttribute(ignoreAttribute)) {
      return true
    } else {
      return treeHasIgnoreAttribute(el.parentNode)
    }
  }
}

function getElementData (el) {
  var data = {
    tag: el.tagName.toLowerCase(),
    tree: htmlTreeAsString(el)
  }

  forEach([
    'alt',
    'class',
    'href',
    'id',
    'name',
    'role',
    'title',
    'type'
  ], function (attrName) {
    var attr = el[attrName] || el.getAttribute(attr)
    if (attr) {
      data[attrName] = attr
    }
  })

  return data
}

/**
 * ORIGINAL SOURCE: https://github.com/getsentry/raven-js/
 * Given a child DOM element, returns a query-selector statement describing that
 * and its ancestors
 * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
 * @param elem
 * @returns {string}
 */
function htmlTreeAsString (elem) {
  var MAX_TRAVERSE_HEIGHT = 5
  var MAX_OUTPUT_LEN = 80
  var out = []
  var height = 0
  var len = 0
  var separator = ' > '
  var sepLength = separator.length
  var nextStr

  while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
    nextStr = htmlElementAsString(elem)
    // bail out if
    // - nextStr is the 'html' element
    // - the length of the string that would be created exceeds MAX_OUTPUT_LEN
    //   (ignore this limit if we are on the first iteration)
    if (
      nextStr === 'html' ||
      height > 1 &&
      len + (out.length * sepLength) + nextStr.length >= MAX_OUTPUT_LEN
    ) {
      break
    }

    out.push(nextStr)

    len += nextStr.length
    elem = elem.parentNode
  }

  return out.reverse().join(separator)
}

/**
 * ORIGINAL SOURCE: https://github.com/getsentry/raven-js/
 * Returns a simple, query-selector representation of a DOM element
 * e.g. [HTMLElement] => input#foo.btn[name=baz]
 * @param HTMLElement
 * @returns {string}
 */
function htmlElementAsString (elem) {
  var out = []
  var className
  var classes
  var key
  var attr
  var i

  if (!elem || !elem.tagName) {
    return ''
  }

  out.push(elem.tagName.toLowerCase())
  if (elem.id) {
    out.push('#' + elem.id)
  }

  className = elem.className
  if (className && isString(className)) {
    classes = className.split(' ')
    for (i = 0; i < classes.length; i++) {
      out.push('.' + classes[i])
    }
  }
  var attrWhitelist = ['type', 'name', 'title', 'alt']
  for (i = 0; i < attrWhitelist.length; i++) {
    key = attrWhitelist[i]
    attr = elem.getAttribute(key)
    if (attr) {
      out.push('[' + key + '="' + attr + '"]')
    }
  }
  return out.join('')
}

module.exports = {
  addEventListener: addEventListener,
  createTreeHasIgnoreAttribute: createTreeHasIgnoreAttribute,
  getElementData: getElementData,
  htmlElementAsString: htmlElementAsString,
  htmlTreeAsString: htmlTreeAsString,
  shouldIgnoreElement: shouldIgnoreElement
}
<|endoftext|>


<commit_before>'use strict';

var Customer = function (request) {
    this.request = request;
};

// https://github.com/GleSYS/API/wiki/functions_customer#customercontactinfo
Customer.prototype.contactInfo = function (data) {
    return this.request.post('/customer/contactinfo', data);
};

module.exports = Customer;
<commit_msg>Rewrite Customer to ES2015<commit_after>'use strict';

class Customer {
    constructor (request) {
        this.request = request;
    }

    // https://github.com/GleSYS/API/wiki/functions_customer#customercontactinfo
    contactInfo (data) {
        return this.request.post('/customer/contactinfo', data);
    }
}

module.exports = Customer;
<|endoftext|>


<commit_before>'use strict'
var Observable = require('vigour-js/lib/observable')
var Base = require('vigour-js/lib/base')
var _remove = Base.prototype.remove
var _addNewProperty = Observable.prototype.addNewProperty
var _setKey = Observable.prototype.setKey
var render = require('./render')

module.exports = function (element) {
  var Element = element.Constructor
  exports.define = {
    node: {
      get () {
        return this.getNode()
      }
    },
    getNode () {
      return this.engine && this.engine.nodes[this.getHashedPath()]
    },
    // TESTING
    getNodeDelete (block, blocknode, hashed) {
      var node = this.getNode() // can be a lot faster here
      if (node && !block) {
        delete this.engine.nodes[this.getHashedPath()]
        var pnode = node.parentNode
        var engine = this.engine
        this.each((p) => {
          if (p.getNodeDelete) {
            p.getNodeDelete(block, this.type !== 'group')
          }
          // p.clearContext()
        }, function (prop) {
          return prop instanceof engine.ChildConstructor
        })
        // this.clearContext()
        if (pnode && !blocknode) {
          pnode.removeChild(node)
        }
      }
      // if (this.path.join('.')==='a.shows.headerofX_shows') {
      //   console.log(this.path.join('.'), this._context)
      // }
      this.clearContext()
    },
    remove () {
      if (this._input !== null) {
        // this._input = null
        this.getNodeDelete()
      }
      return _remove.call(this, false)
    },
    contextRemove () {
      return Base.prototype.contextRemove.apply(this, arguments)
    },
    setKey (key, val, event) {
      if (this[key] && val instanceof Element) {
        if (val !== this[key] && this[key].remove) {
          if ((this.hasOwnProperty(key) || this.hasOwnProperty('_' + key))) {
            this[key].remove(event)
          } else {
            this[key] = null
          }
        }
      }
      return _setKey.apply(this, arguments)
    },
    addNewProperty (key, val, property, event) {
      // use the prop for different engines with specific _Element types
      var ret = _addNewProperty.apply(this, arguments)
      if (this.engine) { // engine needs to be sort of the same as context
        let Element = this.engine.ChildConstructor // cleaner super slow getter
        let val = this[key]
        // check for maps
        if (val instanceof Element) {
          let node = this.getNode()
          if (node && !this.engine.nodes[val.getHashedPath()]) {
            render(val, node, Element, event, this.engine)
          }
        }
      }
      // do the checks
      // if (val instanceof Element) {
      console.log(this, val)
      if (this.$) {
        console.log('lets clear!', val)
      }
      // }
      return ret
    }
  }

  exports.properties = {
    // *** CLONE NODE ***
    __node__: true // this is for doing stuff more efficiently , move all engine specific shit away!
  }

  element.set(exports)
}

// exports.inject = require('../../event/browser')
<commit_msg>fixes<commit_after>'use strict'
var Observable = require('vigour-js/lib/observable')
var Base = require('vigour-js/lib/base')
var _remove = Base.prototype.remove
var _addNewProperty = Observable.prototype.addNewProperty
var _setKey = Observable.prototype.setKey
var render = require('./render')

module.exports = function (element) {
  var Element = element.Constructor
  exports.define = {
    node: {
      get () {
        return this.getNode()
      }
    },
    getNode () {
      return this.engine && this.engine.nodes[this.getHashedPath()]
    },
    // TESTING
    getNodeDelete (block, blocknode, hashed) {
      var node = this.getNode() // can be a lot faster here
      if (node && !block) {
        delete this.engine.nodes[this.getHashedPath()]
        var pnode = node.parentNode
        var engine = this.engine
        this.each((p) => {
          if (p.getNodeDelete) {
            p.getNodeDelete(block, this.type !== 'group')
          }
          // p.clearContext()
        }, function (prop) {
          return prop instanceof engine.ChildConstructor
        })
        // this.clearContext()
        if (pnode && !blocknode) {
          pnode.removeChild(node)
        }
      }
      // if (this.path.join('.')==='a.shows.headerofX_shows') {
      //   console.log(this.path.join('.'), this._context)
      // }
      this.clearContext()
    },
    remove () {
      if (this._input !== null) {
        // this._input = null
        this.getNodeDelete()
      }
      return _remove.call(this, false)
    },
    contextRemove () {
      return Base.prototype.contextRemove.apply(this, arguments)
    },
    setKey (key, val, event) {
      if (this[key] && val instanceof Element) {
        if (val !== this[key] && this[key].remove) {
          if ((this.hasOwnProperty(key) || this.hasOwnProperty('_' + key))) {
            this[key].remove(event)
          } else {
            this[key] = null
          }
        }
      }
      return _setKey.apply(this, arguments)
    },
    addNewProperty (key, val, property, event) {
      // use the prop for different engines with specific _Element types
      var ret = _addNewProperty.apply(this, arguments)
      if (this.engine) { // engine needs to be sort of the same as context
        // let Element = this.engine.ChildConstructor // cleaner super slow getter
        let val = this[key]
        // check for maps
        if (val instanceof Element) {
          let node = this.getNode()
          if (node && !this.engine.nodes[val.getHashedPath()]) {
            render(val, node, Element, event, this.engine)
          }
        }
      }
      // do the checks
      // if (val instanceof Element) {
      // console.log(this, val)
      if (val instanceof Element && val.$ && val.render) {
        console.log('?xxxx', val._path)
      }
      if (this.$) {
        console.log('lets clear!', val)
      }
      // }
      return ret
    }
  }

  exports.properties = {
    // *** CLONE NODE ***
    __node__: true // this is for doing stuff more efficiently , move all engine specific shit away!
  }

  element.set(exports)
}

// exports.inject = require('../../event/browser')
<|endoftext|>


<commit_before>enyo.kind({
    name: "moon.sample.video.BrowserMoviesNarrowSample",
    kind: "moon.Panel",
    classes: "enyo-unselectable moon moon-video-browsermovies",
    titleAbove: "02",
    title: "Browser Movies",
    titleBelow: "37 Movies",

    headerComponents: [
        {classes: "moon-video-browsermovie-header-button", components: [
            {kind: "moon.IconButton", src: "../assets/icon-list.png"}
        ]}
    ],

    components: [
/** If you want to use this template alone with spotlight, remove this comment out.
        {kind: "enyo.Spotlight"},
*/
        {
            kind : "moon.Scroller",
            fit: true,
            touch : true,
            horizontal : "hidden",
            components : [
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                }
            ]
        }
    ]
});<commit_msg>GF-9993 bug fixing for pattern sample in video<commit_after>enyo.kind({
    name: "moon.sample.video.BrowserMoviesNarrowSample",
    kind: "moon.Panel",
    classes: "enyo-unselectable moon moon-video-browsermovies",
    titleAbove: "02",
    title: "Browser Movies",
    titleBelow: "37 Movies",

    headerComponents: [
        {classes: "moon-video-browsermovie-header-button", components: [
            {kind: "moon.IconButton", src: "../assets/icon-list.png"}
        ]}
    ],

    components: [
        {kind: "enyo.Spotlight"},
        {
            kind : "moon.Scroller",
            fit: true,
            touch : true,
            horizontal : "hidden",
            components : [
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                },
                {
                    kind : "moon.ImageItem",
                    source: "../assets/album.png",
                    label: "MOVIE NAME",
                    text: "Staring: Actor Name and Actor Name"
                }
            ]
        }
    ]
});<|endoftext|>


<commit_before>var SELF_KEY = '$self';
var YIELD_KEY = '$yield';
var STRING = 'string';
var BOOLEAN = 'boolean';
var FUNC = 'function';

var YieldConduit = {};

YieldConduit.handleYield = function(bestNode, surrogateRoot) {
    var behavior,
        surrogates,
        target;

    for (var i = 0; i < bestNode.behaviorList.length; i++) {
        behavior = bestNode.behaviorList[i];
        if (behavior.name === YIELD_KEY) {
            switch (typeof(behavior.action)) {
                case STRING: YIELD_HANLDERS[STRING](bestNode, surrogateRoot, behavior); break;
                case BOOLEAN: YIELD_HANLDERS[BOOLEAN](bestNode, surrogateRoot, behavior); break;
                case FUNC: YIELD_HANLDERS[FUNC](bestNode, surrogateRoot, behavior); break;
                default:
                    throw new Error('$yield handler must be a boolean, string or function');
            }
        }
    };
}

YieldConduit.processStringYield = function(bestNode, surrogateRoot, behavior) {
    surrogates = surrogateRoot.querySelectorAll(behavior.action);
    var wrapper = document.createElement('_wrapper');
    for (var index = 0; index < surrogates.length; index++) {
        wrapper.appendChild(surrogates[index]);
    };
    YieldConduit.addSurrogates(bestNode, behavior.selector, wrapper.childNodes);
}

YieldConduit.processBooleanYield = function(bestNode, surrogateRoot, behavior) {
    if (behavior.action) {
        YieldConduit.addSurrogates(bestNode, behavior.selector, surrogateRoot.childNodes);
    }
}

YieldConduit.processFuncYield = function(bestNode, surrogateRoot, behavior) {
    var payload = behavior.action.call(null, surrogateRoot.childNodes);
    if (typeof(payload) === STRING) YIELD_HANLDERS[STRING](bestNode, surrogateRoot, behavior)
    else if (typeof(payload) === BOOLEAN) YIELD_HANLDERS[BOOLEAN](bestNode, surrogateRoot, behavior)
    else {
        if (payload.toString().indexOf('NodeList') === -1 || Array.isArray(payload)) {
            throw new Error('$yield handler function must return a NodeList');
        }
        else {
            YieldConduit.addSurrogates(bestNode, behavior.selector, payload)
        }
    }
}

YieldConduit.addSurrogates = function(bestNode, targetSelector, surrogates) {
    var targetDOMNode = targetSelector === SELF_KEY ?
                                            bestNode.DOMNode :
                                            bestNode.DOMNode.querySelectorAll(targetSelector)[0];

    // TODO: Implement some logic supporting multiple target DOM nodes.
    // This may need to involve cloning the surrogates.
    while (targetDOMNode.firstChild) targetDOMNode.removeChild(targetDOMNode.firstChild);
    while (surrogates.length > 0) targetDOMNode.appendChild(surrogates[0]);
}

var YIELD_HANLDERS = {};
YIELD_HANLDERS[STRING] = YieldConduit.processStringYield;
YIELD_HANLDERS[BOOLEAN] = YieldConduit.processBooleanYield;
YIELD_HANLDERS[FUNC] = YieldConduit.processFuncYield;

module.exports = YieldConduit;<commit_msg>Add check for ELEMENT_NODE_TYPE in yield conduit<commit_after>var SELF_KEY = '$self';
var YIELD_KEY = '$yield';
var STRING = 'string';
var BOOLEAN = 'boolean';
var FUNC = 'function';
var ELEMENT_NODE_TYPE = 1;

var YieldConduit = {};

YieldConduit.handleYield = function(bestNode, surrogateRoot) {
    var behavior,
        surrogates,
        target;

    for (var i = 0; i < bestNode.behaviorList.length; i++) {
        behavior = bestNode.behaviorList[i];
        if (behavior.name === YIELD_KEY) {
            switch (typeof(behavior.action)) {
                case STRING: YIELD_HANLDERS[STRING](bestNode, surrogateRoot, behavior); break;
                case BOOLEAN: YIELD_HANLDERS[BOOLEAN](bestNode, surrogateRoot, behavior); break;
                case FUNC: YIELD_HANLDERS[FUNC](bestNode, surrogateRoot, behavior); break;
                default:
                    throw new Error('$yield handler must be a boolean, string or function');
            }
        }
    };
}

YieldConduit.processStringYield = function(bestNode, surrogateRoot, behavior) {
    surrogates = surrogateRoot.querySelectorAll(behavior.action);
    var wrapper = document.createElement('_wrapper');
    for (var index = 0; index < surrogates.length; index++) {
        wrapper.appendChild(surrogates[index]);
    };
    YieldConduit.addSurrogates(bestNode, behavior.selector, wrapper.childNodes);
}

YieldConduit.processBooleanYield = function(bestNode, surrogateRoot, behavior) {
    if (behavior.action) {
        YieldConduit.addSurrogates(bestNode, behavior.selector, surrogateRoot.childNodes);
    }
}

YieldConduit.processFuncYield = function(bestNode, surrogateRoot, behavior) {
    var payload = behavior.action.call(null, surrogateRoot.childNodes);
    if (typeof(payload) === STRING) YIELD_HANLDERS[STRING](bestNode, surrogateRoot, behavior)
    else if (typeof(payload) === BOOLEAN) YIELD_HANLDERS[BOOLEAN](bestNode, surrogateRoot, behavior)
    else {
        if (payload.toString().indexOf('NodeList') === -1 || Array.isArray(payload)) {
            throw new Error('$yield handler function must return a NodeList');
        }
        else {
            YieldConduit.addSurrogates(bestNode, behavior.selector, payload)
        }
    }
}

YieldConduit.containsElementNode = function(nodes) {
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].nodeType === ELEMENT_NODE_TYPE) return true;
    };
    return false;
}

YieldConduit.addSurrogates = function(bestNode, targetSelector, surrogates) {
    // TODO: Implement some logic supporting multiple target DOM nodes.
    // This may need to involve cloning the surrogates.
    var targetDOMNode = targetSelector === SELF_KEY ?
                                            bestNode.DOMNode :
                                            bestNode.DOMNode.querySelectorAll(targetSelector)[0];

    // Only remove children & add surrogates if there is at least 1 node in the
    // surrogates that is ELEMENT_NODE type.
    // (https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType).
    // This enables components to define 'default' content that will not
    // accidentately be replaced by white-space or comment nodes.
    if (YieldConduit.containsElementNode(surrogates)) {
        while (targetDOMNode.firstChild) targetDOMNode.removeChild(targetDOMNode.firstChild);
        while (surrogates.length > 0) targetDOMNode.appendChild(surrogates[0]);
    }
}

var YIELD_HANLDERS = {};
YIELD_HANLDERS[STRING] = YieldConduit.processStringYield;
YIELD_HANLDERS[BOOLEAN] = YieldConduit.processBooleanYield;
YIELD_HANLDERS[FUNC] = YieldConduit.processFuncYield;

module.exports = YieldConduit;<|endoftext|>


<commit_before>'use strict';

/**
 * Format the browser DOM attributes.
 *
 * @param  {NamedNodeMap} - The attributes.
 * @return {Object}
 */
function formatAttributes(attributes) {
    var result = {};
    var attribute;

    // NamedNodeMap is array-like
    for (var i = 0, len = attributes.length; i < len; i++) {
        attribute = attributes[i];
        result[attribute.name] = attribute.value;
    }

    return result;
}

/**
 * Format the browser DOM nodes to match that of `htmlparser2.parseDOM`.
 *
 * @param  {NodeList} nodes        - The DOM nodes.
 * @param  {Object}   [parentNode] - The parent node that's already formatted.
 * @return {Object}
 */
function formatDOM(nodes, parentNode) {
    var result = [];
    var node;
    var prevNode;
    var nodeObj;

    // NodeList is array-like
    for (var i = 0, len = nodes.length; i < len; i++) {
        node = nodes[i];
        // reset
        nodeObj = {
            next: null,
            prev: result[i - 1] || null,
            parent: parentNode || null
        };

        // set the next node for the previous node (if applicable)
        prevNode = result[i - 1];
        if (prevNode) {
            prevNode.next = nodeObj;
        }

        // set the node name if it's not "#text" or "#comment"
        // e.g., "div"
        if (node.nodeName.indexOf('#') !== 0) {
            nodeObj.name = node.nodeName.toLowerCase();

            // also, type "tag" nodes have"attribs"
            nodeObj.attribs = {}; // default
            if (node.attributes && node.attributes.length) {
                nodeObj.attribs = formatAttributes(node.attributes);
            }
        }

        // set the node type
        // e.g., "tag"
        switch (node.nodeType) {
            // 1 = element
            case 1:
                if (nodeObj.name === 'script' || nodeObj.name === 'style') {
                    nodeObj.type = nodeObj.name;
                } else {
                    nodeObj.type = 'tag';
                }
                // recursively format the children
                nodeObj.children = formatDOM(node.childNodes, nodeObj);
                break;
                // 2 = attribute
                // 3 = text
            case 3:
                nodeObj.type = 'text';
                nodeObj.data = node.nodeValue;
                break;
                // 8 = comment
            case 8:
                nodeObj.type = 'comment';
                nodeObj.data = node.nodeValue;
                break;
            default:
                break;
        }

        result.push(nodeObj);
    }

    return result;
}

/**
 * Parse HTML string to DOM nodes.
 * This uses the browser DOM API.
 *
 * @param  {String} html - The HTML.
 * @return {Object}      - The DOM nodes.
 */
function htmlToDOMClient(html) {
    var root;

    // `DOMParser` can parse full HTML
    // https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
    if (window.DOMParser) {
        var parser = new window.DOMParser();
        root = parser.parseFromString(html, 'text/html');

    // otherwise, use `innerHTML`
    // but this will strip out tags like <html> and <body>
    } else {
        root = document.createElement('div');
        root.innerHTML = html;
    }

    return formatDOM(root.childNodes);
}

/**
 * Export HTML to DOM parser (client).
 */
module.exports = htmlToDOMClient;
<commit_msg>Fix HTML to DOM client parser<commit_after>'use strict';

/**
 * Format the browser DOM attributes.
 *
 * @param  {NamedNodeMap} - The attributes.
 * @return {Object}
 */
function formatAttributes(attributes) {
    var result = {};
    var attribute;

    // NamedNodeMap is array-like
    for (var i = 0, len = attributes.length; i < len; i++) {
        attribute = attributes[i];
        result[attribute.name] = attribute.value;
    }

    return result;
}

/**
 * Format the browser DOM nodes to match that of `htmlparser2.parseDOM`.
 *
 * @param  {NodeList} nodes        - The DOM nodes.
 * @param  {Object}   [parentNode] - The parent node that's already formatted.
 * @return {Object}
 */
function formatDOM(nodes, parentNode) {
    var result = [];
    var node;
    var prevNode;
    var nodeObj;

    // NodeList is array-like
    for (var i = 0, len = nodes.length; i < len; i++) {
        node = nodes[i];
        // reset
        nodeObj = {
            next: null,
            prev: result[i - 1] || null,
            parent: parentNode || null
        };

        // set the next node for the previous node (if applicable)
        prevNode = result[i - 1];
        if (prevNode) {
            prevNode.next = nodeObj;
        }

        // set the node name if it's not "#text" or "#comment"
        // e.g., "div"
        if (node.nodeName.indexOf('#') !== 0) {
            nodeObj.name = node.nodeName.toLowerCase();

            // also, type "tag" nodes have"attribs"
            nodeObj.attribs = {}; // default
            if (node.attributes && node.attributes.length) {
                nodeObj.attribs = formatAttributes(node.attributes);
            }
        }

        // set the node type
        // e.g., "tag"
        switch (node.nodeType) {
            // 1 = element
            case 1:
                if (nodeObj.name === 'script' || nodeObj.name === 'style') {
                    nodeObj.type = nodeObj.name;
                } else {
                    nodeObj.type = 'tag';
                }
                // recursively format the children
                nodeObj.children = formatDOM(node.childNodes, nodeObj);
                break;
                // 2 = attribute
                // 3 = text
            case 3:
                nodeObj.type = 'text';
                nodeObj.data = node.nodeValue;
                break;
                // 8 = comment
            case 8:
                nodeObj.type = 'comment';
                nodeObj.data = node.nodeValue;
                break;
            default:
                break;
        }

        result.push(nodeObj);
    }

    return result;
}

/**
 * Parse HTML string to DOM nodes.
 * This uses the browser DOM API.
 *
 * @param  {String} html - The HTML.
 * @return {Object}      - The DOM nodes.
 */
function htmlToDOMClient(html) {
    var match = typeof html === 'string' ? html.match(/<(.+?)>/) : null;
    var tagName;
    var parentNode;
    var nodes;

    if (match && typeof match[1] === 'string') {
        tagName = match[1].toLowerCase();
    }

    // `DOMParser` can parse full HTML
    // https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
    if (tagName && window.DOMParser) {
        var parser = new window.DOMParser();
        var doc = parser.parseFromString(html, 'text/html');

        // <head> and <body> are siblings
        if (tagName === 'head' || tagName === 'body') {
            nodes = doc.getElementsByTagName(tagName);

        // document's child nodes
        } else if (tagName === 'html') {
            nodes = doc.childNodes;

        // get the element's parent's child nodes
        // do this in case of adjacent elements
        } else {
            parentNode = doc.getElementsByTagName(tagName)[0].parentNode;
            nodes = parentNode.childNodes;
        }

    // otherwise, use `innerHTML`
    // but this will strip out tags like <html> and <body>
    } else {
        parentNode = document.createElement('div');
        parentNode.innerHTML = html;
        nodes = parentNode.childNodes;
    }

    return formatDOM(nodes);
}

/**
 * Export HTML to DOM parser (client).
 */
module.exports = htmlToDOMClient;
<|endoftext|>


<commit_before>var tls = require('tls');
var Q = require('q');
var cert = require('./cert');
var MAX_SERVERS = 256;
var MAX_PORT = 60000;
var curPort = 50000;

function ServerAgent() {
	this._cache = {};
	this._serverCount = 0;
}

var proto = ServerAgent.prototype;

proto.createServer = function createServer(hostname, secureConnectionListener, callback) {
	var self = this;
	var cache = self._cache;

	var promise = cache[hostname];
	var defer;

	if (!promise) {
		defer = Q.defer();
		cache[hostname] = promise = defer.promise;
	}

	promise.done(callback);

	if (!defer) {
		return ;
	}

	var certs = cert.getCert(hostname);
	self.freeServer();
	getServer({
		key: certs[0],
		cert: certs[1]
	}, secureConnectionListener,
			defer.resolve.bind(defer));
	self._serverCount++;

	return self;
};

proto.freeServer = function() {
	if (this._serverCount < MAX_SERVERS) {
		return;
	}

	var cache = this._cache;
	for (var i in cache) {
		var server = cache[i];
		if (!server.connections) {
			delete cache[i];
			server.close();
			if (--this._serverCount < MAX_SERVERS) {
				return;
			}
		}
	}
};

proto.destroy = function destroy() {
	var cache = this._cache;
	this._cache = {};
	this._serverCount = 0;
	for (var i in cache) {
		var server = cache[i];
		delete cache[i];
		server.close();
	}
};

function getServer(options, secureConnectionListener, callback) {
	var self = this;

	if (curPort > MAX_PORT) {
		curPort = MIN_PORT = 40000;
	}

	var server = tls.createServer(options, secureConnectionListener);
	var next = function() {
		getServer(options, secureConnectionListener, callback);
	};
	server.on('error', next);

	var port = curPort++;
	server.listen(port, 'localhost', function() {
		server.removeListener('error', next);
		server.on('error', function() {
			tls.createServer(options, secureConnectionListener)
					.on('error', noop);
		});
		callback(port);
	});
}

function noop() {}

module.exports = ServerAgent;

<commit_msg>add clear input btn<commit_after>var tls = require('tls');
var Q = require('q');
var cert = require('./cert');
var MAX_SERVERS = 256;
var MAX_PORT = 60000;
var curPort = 50000;

function ServerAgent() {
	this._cache = {};
	this._serverCount = 0;
}

var proto = ServerAgent.prototype;

proto.createServer = function createServer(hostname, secureConnectionListener, callback) {
	var self = this;
	var cache = self._cache;

	var promise = cache[hostname];
	var defer;

	if (!promise) {
		defer = Q.defer();
		cache[hostname] = promise = defer.promise;
	}

	promise.done(callback);

	if (!defer) {
		return ;
	}

	var certs = cert.getCert(hostname);
	self.freeServer();
	getServer({
		key: certs[0],
		cert: certs[1]
	}, secureConnectionListener,
			function(port, server) {
		server.on('error', function() {
			if (cache[hostname]) {
				tls.createServer(options, secureConnectionListener)
				.on('error', noop);
			}
		});
		defer.resolve(port);
	});
	self._serverCount++;

	return self;
};

proto.freeServer = function() {
	if (this._serverCount < MAX_SERVERS) {
		return;
	}

	var cache = this._cache;
	for (var i in cache) {
		var server = cache[i];
		if (!server.connections) {
			delete cache[i];
			server.close();
			if (--this._serverCount < MAX_SERVERS) {
				return;
			}
		}
	}
};

proto.destroy = function destroy() {
	var cache = this._cache;
	this._cache = {};
	this._serverCount = 0;
	for (var i in cache) {
		var server = cache[i];
		delete cache[i];
		server.close();
	}
};

function getServer(options, secureConnectionListener, callback) {
	var self = this;

	if (curPort > MAX_PORT) {
		curPort = MIN_PORT = 40000;
	}

	var server = tls.createServer(options, secureConnectionListener);
	var next = function() {
		getServer(options, secureConnectionListener, callback);
	};
	server.on('error', next);

	var port = curPort++;
	server.listen(port, 'localhost', function() {
		server.removeListener('error', next);
		callback(port, server);
	});
}

function noop() {}

module.exports = ServerAgent;

<|endoftext|>


<commit_before>var _ = require('lodash');
var path = require("path");
var xmldom = require('xmldom');
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));
var log = require("../logger");
//var f1 = "./fixtures/ui/me.pou.app-188.xml";
//var f = "/Users/khalid/git/sieveable/test-1.xml";
//var expected = "./fixtures/examples/index/me.pou.app-188.expected.result.txt"

function FileExtractingError(message, fileName) {
    this.message = message;
    this.fileName = fileName;
    this.name = "FileExtractingError";
    //Error.captureStackTrace(this, FileExtractingError);
}
FileExtractingError.prototype = Object.create(Error.prototype);
FileExtractingError.prototype.constructor = FileExtractingError;

module.exports = function (xmlFileNames, targetDir, callback) {
    log.info("Extracting parent-child tags (h1 index data) for %d files to %s",
        xmlFileNames.length, targetDir);
    Promise.map(xmlFileNames, function (xmlFile) {
        return extract(xmlFile, targetDir)
            .then(function (res) {
                log.info(res);
            });

    }, {concurrency: 1}).then(function () {
        callback(null, "Done");
    }).catch(FileExtractingError, function (e) {
        log.error("Failed to extract h1-index data for %s. %s", e.fileName, e.message);
        callback(e);
    });
}

function extract(xmlFile, targetDir) {
    return new Promise(function (resolve, reject) {
        var outFile = path.resolve(targetDir, path.basename(xmlFile, '.xml') +
            '-ui-h1.txt');
        var writeStream = fs.createWriteStream(outFile, {encoding: "utf8"});
        var xmlFileContent = fs.readFileSync(xmlFile, "utf8");
        var doc = new xmldom.DOMParser().parseFromString(xmlFileContent,
            "text/xml");
        var fileElements = doc.getElementsByTagName('File');
        _.forEach(fileElements, function (fileElement) {
            var rootElementList = _.filter(fileElement.childNodes, function (child) {
                return child.nodeType === 1;
            });
            // Each layout file must contain exactly one root element.
            if (rootElementList.length != 1) {
                reject(new Error('File node has more than one child. %s',
                    xmlFile));
            }
            var rootElement = rootElementList[0];
            var children = _.filter(rootElement.childNodes, function (child) {
                return child.nodeType === 1;
            });
            _.forEach(children, function (child) {
                doChildren(child, rootElement, writeStream);
            })
        });

        writeStream.on("finish", function () {
            resolve("H1 tags have been extracted for " + xmlFile);
        })
        writeStream.end();
    });
}

function doChildren(element, parent, writeStream) {
    if (element.hasChildNodes()) {
        emitPairs(parent, element, writeStream);
        var children = _.filter(element.childNodes, function (child) {
            return child.nodeType === 1;
        });
        _.forEach(children, function (child) {
            doChildren(child, element, writeStream)
        })
    }
    else {
        emitPairs(parent, element, writeStream);
    }
}

function emitPairs(parent, child, writeStream) {
    writeStream.write(parent.localName + "-" + child.localName + "\n");
    //var parentAttrs = getAttributes(parent);
    //console.log(parentAttrs.join('-'));
}

function getAttributes(elem) {
    return _.map(elem.attributes, function (attr) {
        var name = attr.nodeName;
        var value = attr.nodeValue;
        return name + "=" + value;
    })
}
<commit_msg>remove commented code<commit_after>var _ = require('lodash');
var path = require("path");
var xmldom = require('xmldom');
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));
var log = require("../logger");

function FileExtractingError(message, fileName) {
    this.message = message;
    this.fileName = fileName;
    this.name = "FileExtractingError";
    //Error.captureStackTrace(this, FileExtractingError);
}
FileExtractingError.prototype = Object.create(Error.prototype);
FileExtractingError.prototype.constructor = FileExtractingError;

module.exports = function (xmlFileNames, targetDir, callback) {
    log.info("Extracting parent-child tags (h1 index data) for %d files to %s",
        xmlFileNames.length, targetDir);
    Promise.map(xmlFileNames, function (xmlFile) {
        return extract(xmlFile, targetDir)
            .then(function (res) {
                log.info(res);
            });

    }, {concurrency: 1}).then(function () {
        callback(null, "Done");
    }).catch(FileExtractingError, function (e) {
        log.error("Failed to extract h1-index data for %s. %s", e.fileName, e.message);
        callback(e);
    });
}

function extract(xmlFile, targetDir) {
    return new Promise(function (resolve, reject) {
        var outFile = path.resolve(targetDir, path.basename(xmlFile, '.xml') +
            '-ui-h1.txt');
        var writeStream = fs.createWriteStream(outFile, {encoding: "utf8"});
        var xmlFileContent = fs.readFileSync(xmlFile, "utf8");
        var doc = new xmldom.DOMParser().parseFromString(xmlFileContent,
            "text/xml");
        var fileElements = doc.getElementsByTagName('File');
        _.forEach(fileElements, function (fileElement) {
            var rootElementList = _.filter(fileElement.childNodes, function (child) {
                return child.nodeType === 1;
            });
            // Each layout file must contain exactly one root element.
            if (rootElementList.length != 1) {
                reject(new Error('File node has more than one child. %s',
                    xmlFile));
            }
            var rootElement = rootElementList[0];
            var children = _.filter(rootElement.childNodes, function (child) {
                return child.nodeType === 1;
            });
            _.forEach(children, function (child) {
                doChildren(child, rootElement, writeStream);
            })
        });

        writeStream.on("finish", function () {
            resolve("H1 tags have been extracted for " + xmlFile);
        })
        writeStream.end();
    });
}

function doChildren(element, parent, writeStream) {
    if (element.hasChildNodes()) {
        emitPairs(parent, element, writeStream);
        var children = _.filter(element.childNodes, function (child) {
            return child.nodeType === 1;
        });
        _.forEach(children, function (child) {
            doChildren(child, element, writeStream)
        })
    }
    else {
        emitPairs(parent, element, writeStream);
    }
}

function emitPairs(parent, child, writeStream) {
    writeStream.write(parent.localName + "-" + child.localName + "\n");
    //var parentAttrs = getAttributes(parent);
    //console.log(parentAttrs.join('-'));
}

function getAttributes(elem) {
    return _.map(elem.attributes, function (attr) {
        var name = attr.nodeName;
        var value = attr.nodeValue;
        return name + "=" + value;
    })
}
<|endoftext|>