<commit_before>'use strict';

/**
 * Rhizome - The API that feeds grassroots movements
 *
 * @file campaign.js
 * @description Campaign definition.
 * @module Model
 * @exports model, schema, constants
 * @author <NAME>
 *
 */

const fs = require('fs');
const mongoose = require('mongoose');
const Model = require('../');
const Logging = require('../../logging');
const Config = require('../../config');

/**
 * Constants
 */

var constants = {
};

/**
 * Schema
 */
var schema = new mongoose.Schema();
schema.add({
  name: {
    type: String,
    index: true
  },
  description: String,
  legals: String,
  _app: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'App'
  },
  images: [{label: String, pathname: String}],
  templates: [{label: String, markup: String}],
  metadata: [{key: String, value: String}]
});

var ModelDef = null;

/*
  VIRTUALS
 */
schema.virtual('details').get(function() {
  return {
    id: this._id,
    name: this.name,
    description: this.description,
    legals: this.legals,
    images: this.images.map(i => i.label),
    templates: this.templates.map(t => t.label),
    metadata: this._metadata
  };
});

schema.virtual('_metadata').get(function() {
  return this.metadata
    .map(m => ({key: m.key, value: JSON.parse(m.value)}));
});

/**
 * Schema Static Methods
 */

/**
 * @param {Object} body - body passed through from a POST request
 * @return {Promise} - returns a promise that is fulfilled when the database request is completed
 */
schema.statics.add = body => {
  var campaign = new ModelDef({
    _app: Model.app,
    name: body.name,
    description: body.description,
    legals: body.legals
  });

  // Logging.log(body);
  Logging.log(campaign.name, Logging.Constants.LogLevel.DEBUG);
  Logging.log(campaign.description, Logging.Constants.LogLevel.DEBUG);
  Logging.log(campaign.legals, Logging.Constants.LogLevel.DEBUG);

  return campaign.save();
};

schema.methods.addImage = function(label, image, encoding) {
  encoding = encoding || 'base64';
  var buffer = Buffer.from(image, encoding);

  return new Promise((resolve, reject) => {
    var dirName = `${Config.appDataPath}/public/${Model.app.getPublicUID()}`;
    var pathName = `${dirName}/${label}.png`;
    Logging.log(pathName, Logging.Constants.LogLevel.DEBUG);

    var dirStats = fs.statSync(dirName);
    if (dirStats.isDirectory() !== true) {
      fs.mkDirSync(dirName);
    }

    fs.writeFile(pathName, buffer, 'binary', err => {
      if (err) {
        reject(err);
        return;
      }

      resolve(true);
    });
  });
};

/**
 * @param {string} key - index name of the metadata
 * @param {*} value - value of the meta data
 * @return {Promise} - resolves when save operation is completed, rejects if metadata already exists
 */
schema.methods.addOrUpdateMetadata = function(key, value) {
  Logging.log(`${Model.app.id}`, Logging.Constants.LogLevel.DEBUG);
  Logging.log(key, Logging.Constants.LogLevel.DEBUG);
  Logging.log(value, Logging.Constants.LogLevel.DEBUG);

  var exists = this.metadata.find(m => m.key === key);
  if (exists) {
    exists.value = value;<commit_msg>- UPDATE: save the file into an app specific directory. return the label and url to access the image.<commit_after>'use strict';

/**
 * Rhizome - The API that feeds grassroots movements
 *
 * @file campaign.js
 * @description Campaign definition.
 * @module Model
 * @exports model, schema, constants
 * @author <NAME>
 *
 */

const fs = require('fs');
const mongoose = require('mongoose');
const Model = require('../');
const Logging = require('../../logging');
const Config = require('../../config');

/**
 * Constants
 */

var constants = {
};

/**
 * Schema
 */
var schema = new mongoose.Schema();
schema.add({
  name: {
    type: String,
    index: true
  },
  description: String,
  legals: String,
  _app: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'App'
  },
  images: [{label: String, pathname: String}],
  templates: [{label: String, markup: String}],
  metadata: [{key: String, value: String}]
});

var ModelDef = null;

/*
  VIRTUALS
 */
schema.virtual('details').get(function() {
  return {
    id: this._id,
    name: this.name,
    description: this.description,
    legals: this.legals,
    images: this.images.map(i => i.label),
    templates: this.templates.map(t => t.label),
    metadata: this._metadata
  };
});

schema.virtual('_metadata').get(function() {
  return this.metadata
    .map(m => ({key: m.key, value: JSON.parse(m.value)}));
});

/**
 * Schema Static Methods
 */

/**
 * @param {Object} body - body passed through from a POST request
 * @return {Promise} - returns a promise that is fulfilled when the database request is completed
 */
schema.statics.add = body => {
  var campaign = new ModelDef({
    _app: Model.app,
    name: body.name,
    description: body.description,
    legals: body.legals
  });

  // Logging.log(body);
  Logging.log(campaign.name, Logging.Constants.LogLevel.DEBUG);
  Logging.log(campaign.description, Logging.Constants.LogLevel.DEBUG);
  Logging.log(campaign.legals, Logging.Constants.LogLevel.DEBUG);

  return campaign.save();
};

schema.methods.addImage = function(label, image, encoding) {
  encoding = encoding || 'base64';
  var buffer = Buffer.from(image, encoding);

  return new Promise((resolve, reject) => {
    var uid = Model.app.getPublicUID();
    var dirName = `${Config.appDataPath}/public/${uid}`;
    var pathName = `${dirName}/${label}.png`;
    Logging.log(pathName, Logging.Constants.LogLevel.DEBUG);

    fs.mkdir(dirName, err => {
      if (err && err.code !== 'EEXIST') {
        reject(err);
        return;
      }

      fs.writeFile(pathName, buffer, 'binary', err => {
        if (err) {
          reject(err);
          return;
        }

        resolve({label: label, url: `${Config.app.protocol}://${Config.app.subdomain}.${Config.app.domain}/${uid}/${label}.png`});
      });
    });
  });
};

/**
 * @param {string} key - index name of the metadata
 * @param {*} value - value of the meta data
 * @return {Promise} - resolves when save operation is completed, rejects if metadata already exists
 */
schema.methods.addOrUpdateMetadata = function(key, value) {
  Logging.log(`${Model.app.id}`, Logging.Constants.LogLevel.DEBUG);
  Logging.log(key, Logging.Constants.LogLevel.DEBUG);
  Logging.log(value, Logging.Constants.LogLevel.DEBUG);

  var exists = this.metadata.find(m => m.key === key);
  if (exists) {
    exists.value = value;
{'fraction_non_alphanumeric': 0.16553112418705482, 'fraction_numerical': 0.0006193868070610096, 'mean_word_length': 3.3700947225981057, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 20, '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': '7230276', 'n_tokens_mistral': 2080, 'n_tokens_neox': 2049, 'n_words': 504}