<commit_before>/*
 Copyright 2015 <NAME>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

const dbConnector = require('../../db/databaseConnector');
const dbRoom = require('../../db/connectors/room');
const dbUser = require('../../db/connectors/user');
const dbDevice = require('../../db/connectors/device');
const manager = require('../../socketHelpers/manager');
const databasePopulation = require('../../config/defaults/config').databasePopulation;
const appConfig = require('../../config/defaults/config').app;
const logger = require('../../utils/logger');
const messenger = require('../../socketHelpers/messenger');
const objectValidator = require('../../utils/objectValidator');
const fs = require('fs');
const path = require('path');

/**
 * Follow a new room on the socket
 * @param {Object} params - Parameters
 * @param {Object} params.socket - Socket.IO socket
 * @param {Object} params.room - New room to follow
 * @param {string} params.userName - Name of the new user following the room
 * @param {Function} params.callback - Callback
 */
function followRoom({ socket, room, userName, callback }) {
  const roomName = room.roomName;

  if (Object.keys(socket.rooms).indexOf(roomName) < 0) {
    messenger.sendMsg({
      socket,
      message: {
        userName: 'SYSTEM',
        text: [`${userName} started following ${roomName}`],
        text_se: [`${userName} började följa ${roomName}`],
        roomName,
      },
      sendTo: roomName,
    });
  }

  socket.join(roomName);
  callback({ data: { room } });
}

/**
 * Should the room be hidden?
 * @static
 * @param {string} room - Room name
 * @param {string} socketId - ID of the socket
 * @returns {boolean} Should the room be hidden?
 */
function shouldBeHidden(room, socketId) {
  const hiddenRooms = [
    socketId,
    databasePopulation.rooms.important.roomName,
    databasePopulation.rooms.bcast.roomName,
    databasePopulation.rooms.morse.roomName,
  ];

  return hiddenRooms.indexOf(room) >= 0 || room.indexOf(appConfig.whisperAppend) >= 0 || room.indexOf(appConfig.deviceAppend) >= 0 || room.indexOf(appConfig.teamAppend) >= 0;
}

/**
 * @param {object} socket - Socket.IO socket
 * @param {object} io - Socket.IO
 */
function handle(socket, io) {
  socket.on('chatMsg', ({ message, image }, callback = () => {}) => {
    if (!objectValidator.isValidData({ message }, { message: { text: true, roomName: true } })) {
      callback({ error: {} });

      return;
    }

    manager.userAllowedCommand(socket.id, databasePopulation.commands.msg.commandName, (allowErr, allowed, user) => {
      if (allowErr || !allowed) {
        callback({ error: {} });

        return;
      }

      if (image && image.source.match(/^data:image\/((png)|(jpeg));base64,/)) {
        const fileName = `${user.userName}-${appConfig.mode}-${image.imageName}`;

        fs.writeFile(path.join(appConfig.publicBase, 'images', fileName), image.source.replace(/data:image\/((png)|(jpeg));base64,/, ''), { encoding: 'base64' }, (err) => {
          if (err) {
            callback({ error: err || {} });

            return;
          }

          const chatMsg = message;
          chatMsg.image = {
            imageName: image.imageName,
            fileName,
          };

          messenger.sendChatMsg({ user, callback, message: chatMsg, io, socket });
        });
      } else {
        messenger.sendChatMsg({ user, callback, message, io, socket });
      }
    });<commit_msg>Debug for Docker cloud<commit_after>/*
 Copyright 2015 <NAME>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

const dbConnector = require('../../db/databaseConnector');
const dbRoom = require('../../db/connectors/room');
const dbUser = require('../../db/connectors/user');
const dbDevice = require('../../db/connectors/device');
const manager = require('../../socketHelpers/manager');
const databasePopulation = require('../../config/defaults/config').databasePopulation;
const appConfig = require('../../config/defaults/config').app;
const logger = require('../../utils/logger');
const messenger = require('../../socketHelpers/messenger');
const objectValidator = require('../../utils/objectValidator');
const fs = require('fs');
const path = require('path');

/**
 * Follow a new room on the socket
 * @param {Object} params - Parameters
 * @param {Object} params.socket - Socket.IO socket
 * @param {Object} params.room - New room to follow
 * @param {string} params.userName - Name of the new user following the room
 * @param {Function} params.callback - Callback
 */
function followRoom({ socket, room, userName, callback }) {
  const roomName = room.roomName;

  if (Object.keys(socket.rooms).indexOf(roomName) < 0) {
    messenger.sendMsg({
      socket,
      message: {
        userName: 'SYSTEM',
        text: [`${userName} started following ${roomName}`],
        text_se: [`${userName} började följa ${roomName}`],
        roomName,
      },
      sendTo: roomName,
    });
  }

  socket.join(roomName);
  callback({ data: { room } });
}

/**
 * Should the room be hidden?
 * @static
 * @param {string} room - Room name
 * @param {string} socketId - ID of the socket
 * @returns {boolean} Should the room be hidden?
 */
function shouldBeHidden(room, socketId) {
  const hiddenRooms = [
    socketId,
    databasePopulation.rooms.important.roomName,
    databasePopulation.rooms.bcast.roomName,
    databasePopulation.rooms.morse.roomName,
  ];

  return hiddenRooms.indexOf(room) >= 0 || room.indexOf(appConfig.whisperAppend) >= 0 || room.indexOf(appConfig.deviceAppend) >= 0 || room.indexOf(appConfig.teamAppend) >= 0;
}

/**
 * @param {object} socket - Socket.IO socket
 * @param {object} io - Socket.IO
 */
function handle(socket, io) {
  socket.on('chatMsg', ({ message, image }, callback = () => {}) => {
    if (!objectValidator.isValidData({ message }, { message: { text: true, roomName: true } })) {
      callback({ error: {} });

      return;
    }

    manager.userAllowedCommand(socket.id, databasePopulation.commands.msg.commandName, (allowErr, allowed, user) => {
      if (allowErr || !allowed) {
        callback({ error: {} });

        return;
      }

      if (image && image.source.match(/^data:image\/((png)|(jpeg));base64,/)) {
        const fileName = `${user.userName}-${appConfig.mode}-${image.imageName}`;

        console.log(path.join(appConfig.publicBase, 'images', fileName));

        fs.writeFile(path.join(appConfig.publicBase, 'images', fileName), image.source.replace(/data:image\/((png)|(jpeg));base64,/, ''), { encoding: 'base64' }, (err, file) => {
          if (err) {
            callback({ error: err || {} });

            return;
          }

          console.log(file);

          const chatMsg = message;
          chatMsg.image = {
            imageName: image.imageName,
            fileName,
          };

          messenger.sendChatMsg({ user, callback, message: chatMsg, io, socket });
        });
      } else {
        messenger.sendChatMsg({ user, callback, message, io, socket });
      }
    });
{'fraction_non_alphanumeric': 0.15623441396508728, 'fraction_numerical': 0.004738154613466334, 'mean_word_length': 3.145219638242894, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4486404', 'n_tokens_mistral': 2312, 'n_tokens_neox': 2263, 'n_words': 634}