<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 manager = require('../../socketHelpers/manager');
const dbConfig = require('../../config/defaults/config').databasePopulation;
const appConfig = require('../../config/defaults/config').app;
const objectValidator = require('../../utils/objectValidator');
const dbDocFile = require('../../db/connectors/docFile');
const errorCreator = require('../../objects/error/errorCreator');
const dbGameCode = require('../../db/connectors/gameCode');
const textTools = require('../../utils/textTools');
const dbUser = require('../../db/connectors/user');

/**
 * Creates game code
 * @returns {string} numerical game code
 */
function generateGameCode() {
  return textTools.shuffleArray(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']).slice(0, 6).join('');
}

/**
 * @param {Object} socket Socket.IO socket
 * @param {Object} io Socket.io
 */
function handle(socket, io) {
  // TODO Not used
  socket.on('time', (params, callback = () => {}) => {
    const now = new Date();
    now.setFullYear(now.getFullYear() + appConfig.yearModification);

    callback({ time: now });
  });

  socket.on('createDocFile', ({ docFile, token }, callback = () => {}) => {
    if (!objectValidator.isValidData({ docFile }, { docFileId: true, text: true, title: true })) {
      callback({ error: new errorCreator.InvalidData({ expected: '{ docFile: { docFileId, text, title } }' }) });

      return;
    }

    manager.userIsAllowed({
      token,
      commandName: dbConfig.commands.docFiles.commandName,
      callback: ({ error, allowedUser }) => {
        if (error) {
          callback({ error });

          return;
        }

        docFile.creator = allowedUser.userName;
        docFile.docFileId = docFile.docFileId.toLowerCase();

        dbDocFile.createDocFile(docFile, (err, newDocFile) => {
          if (err) {
            callback({ error: new errorCreator.Database({}) });

            return;
          } else if (!newDocFile) {
            callback({ error: new errorCreator.AlreadyExists({ name: 'document' }) });

            return;
          }

          callback({ data: { docFile: newDocFile } });

          if (newDocFile.isPublic) {
            socket.broadcast.emit('docFile', { docFile: newDocFile });
          } else if (newDocFile.team && newDocFile.team !== '') {
            const teamRoom = newDocFile.team + appConfig.teamAppend;

            socket.broadcast.to(teamRoom).emit('docFile', { docFile: newDocFile });
          }
        });
      },
    });
  });

  socket.on('updateDocFile', ({ docFileId, title, text, visibility, isPublic, token }, callback = () => {}) => {
    if (!objectValidator.isValidData({ docFileId }, { docFileId: true })) {
      callback({ error: new errorCreator.InvalidData({ expected: '{ docFileId }' }) });

      return;
    }

    manager.userIsAllowed({
      token,
      commandName: dbConfig.commands.docFiles.commandName,
      callback: ({ error }) => {
        if (error) {
          callback({ error });

          return;
        }

        dbDocFile.updateDocFile(docFileId, { title, text, visibility, isPublic }, (err, docFile) => {
          if (err) {
            callback({ error: new errorCreator.Database({}) });

            return;
          }

          callback({ data: { docFile } });
        });
      },
    });
  });

  socket.on('getDocFile', ({ docFileId, token }, callback = () => {}) => {
    if (!objectValidator.isValidData({ docFileId }, { docFileId: true })) {
      callback({ error: new errorCreator.InvalidData({ expected: '{ docFileId' }) });

      return;
    }

    manager.userIsAllowed({
      token,
      commandName: dbConfig.commands.getDocFile.commandName,
      callback: ({ error, allowedUser }) => {
        if (error) {
          callback({ error });

          return;
        }

        dbDocFile.getDocFile(docFileId.toLowerCase(), allowedUser.accessLevel, (err, docFile) => {
          if (err) {<commit_msg>Existing docfiles can de edited<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 manager = require('../../socketHelpers/manager');
const dbConfig = require('../../config/defaults/config').databasePopulation;
const appConfig = require('../../config/defaults/config').app;
const objectValidator = require('../../utils/objectValidator');
const dbDocFile = require('../../db/connectors/docFile');
const errorCreator = require('../../objects/error/errorCreator');
const dbGameCode = require('../../db/connectors/gameCode');
const textTools = require('../../utils/textTools');
const dbUser = require('../../db/connectors/user');

/**
 * Creates game code
 * @returns {string} numerical game code
 */
function generateGameCode() {
  return textTools.shuffleArray(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']).slice(0, 6).join('');
}

/**
 * @param {Object} socket Socket.IO socket
 * @param {Object} io Socket.io
 */
function handle(socket, io) {
  // TODO Not used
  socket.on('time', (params, callback = () => {}) => {
    const now = new Date();
    now.setFullYear(now.getFullYear() + appConfig.yearModification);

    callback({ time: now });
  });

  socket.on('createDocFile', ({ docFile, updateExisting, token }, callback = () => {}) => {
    if (!objectValidator.isValidData({ docFile }, { docFile: { docFileId: true, text: true, title: true } })) {
      callback({ error: new errorCreator.InvalidData({ expected: '{ docFile: { docFileId, text, title } }' }) });

      return;
    }

    manager.userIsAllowed({
      token,
      commandName: dbConfig.commands.docFiles.commandName,
      callback: ({ error, allowedUser }) => {
        if (error) {
          callback({ error });

          return;
        }

        if (updateExisting) {
          const { title, text, visibility, isPublic, docFileId } = docFile;

          dbDocFile.getDocFile(docFileId, allowedUser.accessLevel, (err, retrievedDocFile) => {
            if (err) {
              callback({ error: new errorCreator.Database({}) });

              return;
            } else if (retrievedDocFile.creator !== allowedUser.userName) {
              callback({ error: new errorCreator.NotAllowed({ name: 'update not owned doc file' }) });

              return;
            }

            dbDocFile.updateDocFile(docFileId, { title, text, visibility, isPublic }, (updateErr, updatedDocFile) => {
              if (updateErr) {
                callback({ error: new errorCreator.Database({}) });

                return;
              }

              callback({ data: { docFile: updatedDocFile } });
            });
          });
        } else {
          docFile.creator = allowedUser.userName;
          docFile.docFileId = docFile.docFileId.toLowerCase();

          dbDocFile.createDocFile(docFile, (err, newDocFile) => {
            if (err) {
              callback({ error: new errorCreator.Database({}) });

              return;
            } else if (!newDocFile) {
              callback({ error: new errorCreator.AlreadyExists({ name: 'document' }) });

              return;
            }

            callback({ data: { docFile: newDocFile } });

            if (newDocFile.isPublic) {
              socket.broadcast.emit('docFile', { docFile: newDocFile });
            } else if (newDocFile.team && newDocFile.team !== '') {
              const teamRoom = newDocFile.team + appConfig.teamAppend;

              socket.broadcast.to(teamRoom).emit('docFile', { docFile: newDocFile });
            }
          });
        }
      },
    });
  });

  socket.on('getDocFile', ({ docFileId, token }, callback = () => {}) => {
    if (!objectValidator.isValidData({ docFileId }, { docFileId: true })) {
      callback({ error: new errorCreator.InvalidData({ expected: '{ docFileId' }) });

      return;
    }

    manager.userIsAllowed({
      token,
      commandName: dbConfig.commands.getDocFile.commandName,
      callback: ({ error, allowedUser }) => {
        if (error) {
          callback({ error });

          return;
        }

        dbDocFile.getDocFile(docFileId.toLowerCase(), allowedUser.accessLevel, (err, docFile) => {
          if (err) {
{'fraction_non_alphanumeric': 0.15491580662683324, 'fraction_numerical': 0.0043454644215100485, 'mean_word_length': 2.5848909657320873, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5373973', 'n_tokens_mistral': 2608, 'n_tokens_neox': 2562, 'n_words': 654}