<commit_before>const Joi = require('joi');
const LocalDatabaseConnector = require('../../shared/local-database-connector');
const SendingUtils = require('../sending-utils');
const SendmailClient = require('../sendmail-client');

const SEND_TIMEOUT = 1000 * 60; // millliseconds

const recipient = Joi.object().keys({
  name: Joi.string().required(),
  email: Joi.string().email().required(),
  account_id: Joi.string(),
  client_id: Joi.string(),
  id: Joi.string(),
  thirdPartyData: Joi.object(),
});
const recipientList = Joi.array().items(recipient);

const respondWithError = (request, reply, error) => {
  if (!error.httpCode) {
    error.type = 'apiError';
    error.httpCode = 500;
  }
  request.logger.error('responding with error', error, error.logContext);
  reply(JSON.stringify(error)).code(error.httpCode);
}

module.exports = (server) => {
  server.route({
    method: 'POST',
    path: '/send',
    handler: async (request, reply) => {
      try {
        const account = request.auth.credentials;
        const db = await LocalDatabaseConnector.forAccount(account.id)
        const draft = await SendingUtils.findOrCreateMessageFromJSON(request.payload, db);
        // Calculate the response now to prevent errors after the draft has
        // already been sent.
        const responseOnSuccess = draft.toJSON();
        const sender = new SendmailClient(account, request.logger);
        await sender.send(draft);
        reply(responseOnSuccess);
      } catch (err) {
        respondWithError(request, reply, err);
      }
    },
  });

  // Initiates a multi-send session by creating a new multi-send draft.
  server.route({
    method: 'POST',
    path: '/send-multiple',
    config: {
      validate: {
        payload: {
          to: recipientList,
          cc: recipientList,
          bcc: recipientList,
          from: recipientList.length(1).required(),
          reply_to: recipientList.min(0).max(1),
          subject: Joi.string().required(),
          body: Joi.string().required(),
          thread_id: Joi.string(),
          reply_to_message_id: Joi.string(),
          client_id: Joi.string(),
          account_id: Joi.string(),
          id: Joi.string(),
          object: Joi.string(),
          metadata: Joi.array().items(Joi.string()),
          date: Joi.number(),
          files: Joi.array().items(Joi.string()),
          file_ids: Joi.array().items(Joi.string()),
          uploads: Joi.array().items(Joi.string()),
          events: Joi.array().items(Joi.string()),
          pristine: Joi.boolean(),
          categories: Joi.array().items(Joi.string()),
          draft: Joi.boolean(),
        },
      },
    },
    handler: async (request, reply) => {
      try {
        const accountId = request.auth.credentials.id;
        const db = await LocalDatabaseConnector.forAccount(accountId)
        const draft = await SendingUtils.findOrCreateMessageFromJSON(request.payload, db, false)
        await (draft.isSending = true);
        const savedDraft = await draft.save();
        reply(savedDraft.toJSON());
      } catch (err) {
        respondWithError(request, reply, err);
      }
    },
  });

  // Performs a single send operation in an individualized multi-send
  // session. Sends a copy of the draft at draft_id to the specified address
  // with the specified body, and ensures that a corresponding sent message is
  // either not created in the user's Sent folder or is immediately
  // deleted from it.
  server.route({
    method: 'POST',
    path: '/send-multiple/{draftId}',
    config: {
      validate: {
        params: {<commit_msg>[local-sync] Fix(send): change some validation fields for multi-send<commit_after>const Joi = require('joi');
const LocalDatabaseConnector = require('../../shared/local-database-connector');
const SendingUtils = require('../sending-utils');
const SendmailClient = require('../sendmail-client');

const SEND_TIMEOUT = 1000 * 60; // millliseconds

const recipient = Joi.object().keys({
  name: Joi.string().required(),
  email: Joi.string().email().required(),
  account_id: Joi.string(),
  client_id: Joi.string(),
  id: Joi.string(),
  thirdPartyData: Joi.object(),
});
const recipientList = Joi.array().items(recipient);

const respondWithError = (request, reply, error) => {
  if (!error.httpCode) {
    error.type = 'apiError';
    error.httpCode = 500;
  }
  request.logger.error('responding with error', error, error.logContext);
  reply(JSON.stringify(error)).code(error.httpCode);
}

module.exports = (server) => {
  server.route({
    method: 'POST',
    path: '/send',
    handler: async (request, reply) => {
      try {
        const account = request.auth.credentials;
        const db = await LocalDatabaseConnector.forAccount(account.id)
        const draft = await SendingUtils.findOrCreateMessageFromJSON(request.payload, db);
        // Calculate the response now to prevent errors after the draft has
        // already been sent.
        const responseOnSuccess = draft.toJSON();
        const sender = new SendmailClient(account, request.logger);
        await sender.send(draft);
        reply(responseOnSuccess);
      } catch (err) {
        respondWithError(request, reply, err);
      }
    },
  });

  // Initiates a multi-send session by creating a new multi-send draft.
  server.route({
    method: 'POST',
    path: '/send-multiple',
    config: {
      validate: {
        payload: {
          to: recipientList,
          cc: recipientList,
          bcc: recipientList,
          from: recipientList.length(1).required(),
          reply_to: recipientList.min(0).max(1),
          subject: Joi.string().required(),
          body: Joi.string().required(),
          thread_id: Joi.string(),
          reply_to_message_id: Joi.string(),
          client_id: Joi.string(),
          account_id: Joi.string(),
          id: Joi.string(),
          object: Joi.string(),
          metadata: Joi.array().items(Joi.object()),
          date: Joi.number(),
          files: Joi.array().items(Joi.string()),
          file_ids: Joi.array(),
          uploads: Joi.array(),
          events: Joi.array(),
          pristine: Joi.boolean(),
          categories: Joi.array().items(Joi.string()),
          draft: Joi.boolean(),
        },
      },
    },
    handler: async (request, reply) => {
      try {
        const accountId = request.auth.credentials.id;
        const db = await LocalDatabaseConnector.forAccount(accountId)
        const draft = await SendingUtils.findOrCreateMessageFromJSON(request.payload, db, false)
        await (draft.isSending = true);
        const savedDraft = await draft.save();
        reply(savedDraft.toJSON());
      } catch (err) {
        respondWithError(request, reply, err);
      }
    },
  });

  // Performs a single send operation in an individualized multi-send
  // session. Sends a copy of the draft at draft_id to the specified address
  // with the specified body, and ensures that a corresponding sent message is
  // either not created in the user's Sent folder or is immediately
  // deleted from it.
  server.route({
    method: 'POST',
    path: '/send-multiple/{draftId}',
    config: {
      validate: {
        params: {
{'fraction_non_alphanumeric': 0.1373146736871276, 'fraction_numerical': 0.003325481502009145, 'mean_word_length': 2.6491405460060666, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '2133781', 'n_tokens_mistral': 2104, 'n_tokens_neox': 2074, 'n_words': 517}