<commit_before>const cheerio = require("cheerio");
const moment = require("moment/min/moment-with-locales");
const axios = require("axios");

const PAPER_URL = "https://www.clarin.com";

const MINUTE = 60; // Seconds
const CACHE_DURATION = 10 * MINUTE;
const CACHE_DURATION_ARTICLE = 30 * MINUTE;
const CACHE_DURATION_ERROR = 60 * MINUTE;

moment.locale("es");

let template = `
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{title}}</title>
    <link href="https://fonts.googleapis.com/css?family=Libre+Baskerville:400,400i,700|Lora:700" rel="stylesheet">
    <link rel="stylesheet" href="/css/main.css">
    <link rel="icon" href="/favicon.png" type="image/png">
    <link rel="apple-touch-icon" href="/favicon.png">
    <link rel="shortcut" href="/favicon.ico" type="image/x-icon">

Clean Paper

{{date}} · {{time}} hs

      {{body}}

`;

const fetchContent = (url, res) =>
  axios(url)
    .then(({ data, headers }) => {
      // Solo parsear html
      if (headers["content-type"].indexOf("text/html") !== 0) {
        throw Error();
      }

      return data;
    })
    .catch(() => {
      res.setHeader(
        "Cache-Control",
        `max-age=0, s-maxage=${CACHE_DURATION_ERROR}`
      );
      res.send("");
    });

const getOndemand = ($) => {
  const onDemand = [];
  $(".on-demand").each((i, e) => {
    onDemand.push(
      axios(`${PAPER_URL}${$(e).data("src")}`).then(
        // Eliminar los parentesis del "JSON"
        ({ data }) => JSON.parse(data.slice(1, -1)).data
      )
    );
  });
  return Promise.all(onDemand);
};

const parseHome = (res, withImages) => {
  res.setHeader("Cache-Control", `max-age=0, s-maxage=${CACHE_DURATION}`);

  fetchContent(PAPER_URL, res).then((body) => {
    const $ = cheerio.load(body);

    getOndemand($).then((values) => {
      values.forEach((onDemandContent) => {
        $("body").append(onDemandContent);
      });

      $("header").remove();
      $("footer").remove();
      $("script").remove();
      $(".on-demand").remove();
      $("article.visual").remove();

      // Eliminar clickbait CX Sense
      $("#containder_cxense").remove(); // Sí, hay un typo en el ID

      if (!withImages) {
        $("img").remove();
      } else {
        $(".img-responsive").each((idx, node) => {
          const elem = $(node);
          elem.attr("src", elem.data("small"));
        });
        $("img").removeAttr("alt");
      }

      // Cambiar los swiper slides a articles para En Foco
      $("#enFoco .swiper-slide").each((i, elem) => {
        const article = $("

").html($(elem).html());
        $(elem).after(article);
      });
      $(".swiper-slide").remove();

      // Limpio el markup de los artículos
      $("article").each((i, elem) => {
        let volanta = $(elem).find("p.volanta").first().remove();
        const title = $(elem).find("h1,h2,h3").remove();
        const url = $(elem).find("a").first().attr("href");
        const link = $("").append(title).attr("href", url);

        const image = $(elem)
          .find(withImages ? "figure" : "")
          .remove();

        const text = $(elem).find("p.summary").remove();

        // El orden siempre va a ser titulo - imagen - bajada
        $(elem).empty().append(volanta, link, image, text);
        $(elem).removeAttr("style");
        $(elem).removeAttr("class");

        // Los articulos de BrandStudio son contenido patrocinado
        if (url.indexOf("brandstudio") !== -1) {
          $(elem).addClass("remove");
        }

        // Definición de clickbait
        if (title.text().indexOf("CLICK") !== -1) {
          $(elem).addClass("remove");
        }

        // Sacamos links a Elle
        if (url.indexOf("elle.") !== -1) {
          $(elem).addClass("remove");
        }
      });
      $(".remove").remove();

      const content = $("
");
      content.append($("article"));

      const timeClarin = moment().utcOffset(-180);
      let date = `${timeClarin.format("dddd DD MMMM")} de `;
      date += `${timeClarin.format("YYYY")}`;
      date = `${date[0].toUpperCase()}${date.substr(1)}`;
      const time = timeClarin.format("HH:mm");

      const htmlContent = template
        .replace("{{body}}", content.html())
        .replace("{{title}}", "Clarin Limpio")
        .replace("{{date}}", date)
        .replace("{{time}}", time);

      res.send(htmlContent);
    });
  });
};

const parseArticle = (res, url, withImages) => {
  res.setHeader(
    "Cache-Control",
    `max-age=0, s-maxage=${CACHE_DURATION_ARTICLE}`
  );

  fetchContent(`${PAPER_URL}/${url}`, res).then((body) => {
    const $ = cheerio.load(body);

    $("header").remove();
    $("footer").remove();

    if (!withImages) {
      // Las imágenes suelen venir adentro de un link en los articulos
      $("article > a").has("img").remove();
      $("img").remove();
      $("#galeria-trigger, .image-trigger").remove();
      // Eliminar todos los embeds que no sean tweets
      $("[class^=embed-]").each((i, elem) => {
        if (!$(elem).find(".twitter-tweet").length) {
          $(elem).remove();
        }
      });
    } else {
      $(".img-responsive").each((idx, node) => {
        const elem = $(node);
        elem.attr("src", elem.data("small"));
      });

      $("article").each((i, elem) => {
        if ($(elem).find("img").length > 0) {
          $(elem).prepend($(elem).find(".txt").first().remove());
        }
      });
    }

    const content = $("
");

    $("[id^=bannerId_]").remove();
    $("[id^=sas_]").remove();
    $('[itemprop="video"]').remove();

    // Parsear mvHero
    const mvHero = $("#mnhead");
    if (mvHero) {
      try {
        const script = mvHero.find("script").html();
        const title = script.replace(/\n/g, "").match(/title: +"([^"]+)",/)[1];
        const divTitle = $("

")
          .addClass("title")
          .append($(`<h1>${title}</h1>`))
          .append($(".bajada"));
        $(".nota-unica").prepend(divTitle);
      } catch (e) {
        // Ignore error
      }
    }

    // Outlinks
    const outlinks = $('

');
    outlinks.append($(".box-content-new, .content-new").remove());
    outlinks.find("span").remove();

    // Heurísticas:
    // A veces los outlinks estan en medio del texto y tienen la pinta
    // de "Mirá también: <noticia>"
    $("a").each((i, elem) => {
      if ($(elem).text().toLowerCase().indexOf("mir") === 0) {
        outlinks.append($(elem).remove());
      }
    });

    // Otras veces hay párrafos enteros que sólo son clickbait+link
    const clickbaits = ["leé", "lee", "te puede interesar", "te puede"];
    $("p").each((i, elem) => {
      const p = $(elem);
      if (p.find("a").length === 1) {
        const link = p.find("a").text();
        const clickbait = p.text().replace(link, "").trim().toLowerCase();
        if (clickbaits.indexOf(clickbait) > -1) {
          outlinks.append(p.find("a").remove());
          p.remove();
        }
      }
    });

    $("p a").each((i, elem) => {
      const url = $(elem).attr("href");
      if (url.indexOf("/tema/") !== -1) {
        // Esto es más clickbait basicamente
        $(elem).replaceWith($(elem).text());
      } else {
        // Si no es clickbait, hacer los links relativos
        $(elem).attr(
          "href",
          url.replace(/http(s)?:\/\/(www.)?clarin.com/i, "")
        );
      }
    });

    // Reemplazar los mark por strong
    $("mark").each((i, elem) => {
      $(elem).replaceWith(`<strong>${$(elem).text()}</strong>`);
    });

    content.append($(".nota-unica .title, .nota-unica .notas-content"));
    const miraTambien = $("

");
    outlinks.find("a").each((i, elem) => {
      const $elem = $(elem);
      if ($elem.text().trim().length > 1) {
        const link = $("")
          .text($elem.text().replace(/Mir[áa] (tambi[ée]n: )?/i, ""))
          .attr("href", $elem.attr("href"));
        miraTambien.append($("

").append(link));
      }
    });

    if (miraTambien.find("li").length) {
      content.append($("
Mirá también
"));
      content.append(miraTambien);
    }

    const publishedDate = content
      .find(".breadcrumb .publishedDate")
      .text()
      .trim();
    const modifiedDate = content
      .find(".breadcrumb .modificatedDate")
      .text()
      .trim();

    content
      .find(".bajada")
      .append($(`<p>${publishedDate} - ${modifiedDate}</p>`));

    // Eliminar cosas de más
    content
      .find(".pull-right, .entry-head, .body-nota > div, #comments")
      .remove();
    $("script").remove();

    title = $("title").text();

    const timeClarin = moment().utcOffset(-180);

    let date = `${timeClarin.format("dddd DD MMMM")} de `;
    date += `${timeClarin.format("YYYY")}`;
    date = `${date[0].toUpperCase()}${date.substr(1)}`;
    const time = timeClarin.format("HH:mm");

    const htmlContent = template
      .replace("{{body}}", content.html())
      .replace("{{title}}", title)
      .replace("{{date}}", date)
      .replace("{{time}}", time);

    res.send(htmlContent);
  });
};

module.exports = (req, res) => {
  let url = req.query.url || "/";

  res.setHeader("Cache-Control", `max-age=0, s-maxage=${CACHE_DURATION}`);
  res.status(200);

  if (url.indexOf(".js") >= 0 || url.indexOf(".css") >= 0) {
    // No pedir los JS ni CSS externos
    res.setHeader(
      "Cache-Control",
      `max-age=0, s-maxage=${CACHE_DURATION_ERROR}`
    );
    res.send("");
  } else {
    let images = false;

    if (url.indexOf("img") === 0) {
      // Con imágenes
      url = url.replace(/img\/?/, "");
      images = true;
    }

    if (url.length > 1) {
      // Es un artículo
      parseArticle(res, url, images);
    } else {
      // Es la home
      parseHome(res, images);
    }
  }
};
<commit_msg>Parsear bien mvHead<commit_after>const cheerio = require("cheerio");
const moment = require("moment/min/moment-with-locales");
const axios = require("axios");

const PAPER_URL = "https://www.clarin.com";

const MINUTE = 60; // Seconds
const CACHE_DURATION = 10 * MINUTE;
const CACHE_DURATION_ARTICLE = 30 * MINUTE;
const CACHE_DURATION_ERROR = 60 * MINUTE;

moment.locale("es");

let template = `
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{title}}</title>
    <link href="https://fonts.googleapis.com/css?family=Libre+Baskerville:400,400i,700|Lora:700" rel="stylesheet">
    <link rel="stylesheet" href="/css/main.css">
    <link rel="icon" href="/favicon.png" type="image/png">
    <link rel="apple-touch-icon" href="/favicon.png">
    <link rel="shortcut" href="/favicon.ico" type="image/x-icon">

Clean Paper

{{date}} · {{time}} hs

      {{body}}

`;

const fetchContent = (url, res) =>
  axios(url)
    .then(({ data, headers }) => {
      // Solo parsear html
      if (headers["content-type"].indexOf("text/html") !== 0) {
        throw Error();
      }

      return data;
    })
    .catch(() => {
      res.setHeader(
        "Cache-Control",
        `max-age=0, s-maxage=${CACHE_DURATION_ERROR}`
      );
      res.send("");
    });

const getOndemand = ($) => {
  const onDemand = [];
  $(".on-demand").each((i, e) => {
    onDemand.push(
      axios(`${PAPER_URL}${$(e).data("src")}`).then(
        // Eliminar los parentesis del "JSON"
        ({ data }) => JSON.parse(data.slice(1, -1)).data
      )
    );
  });
  return Promise.all(onDemand);
};

const parseHome = (res, withImages) => {
  res.setHeader("Cache-Control", `max-age=0, s-maxage=${CACHE_DURATION}`);

  fetchContent(PAPER_URL, res).then((body) => {
    const $ = cheerio.load(body);

    getOndemand($).then((values) => {
      values.forEach((onDemandContent) => {
        $("body").append(onDemandContent);
      });

      $("header").remove();
      $("footer").remove();
      $("script").remove();
      $(".on-demand").remove();
      $("article.visual").remove();

      // Eliminar clickbait CX Sense
      $("#containder_cxense").remove(); // Sí, hay un typo en el ID

      if (!withImages) {
        $("img").remove();
      } else {
        $(".img-responsive").each((idx, node) => {
          const elem = $(node);
          elem.attr("src", elem.data("small"));
        });
        $("img").removeAttr("alt");
      }

      // Cambiar los swiper slides a articles para En Foco
      $("#enFoco .swiper-slide").each((i, elem) => {
        const article = $("

").html($(elem).html());
        $(elem).after(article);
      });
      $(".swiper-slide").remove();

      // Limpio el markup de los artículos
      $("article").each((i, elem) => {
        let volanta = $(elem).find("p.volanta").first().remove();
        const title = $(elem).find("h1,h2,h3").remove();
        const url = $(elem).find("a").first().attr("href");
        const link = $("").append(title).attr("href", url);

        const image = $(elem)
          .find(withImages ? "figure" : "")
          .remove();

        const text = $(elem).find("p.summary").remove();

        // El orden siempre va a ser titulo - imagen - bajada
        $(elem).empty().append(volanta, link, image, text);
        $(elem).removeAttr("style");
        $(elem).removeAttr("class");

        // Los articulos de BrandStudio son contenido patrocinado
        if (url.indexOf("brandstudio") !== -1) {
          $(elem).addClass("remove");
        }

        // Definición de clickbait
        if (title.text().indexOf("CLICK") !== -1) {
          $(elem).addClass("remove");
        }

        // Sacamos links a Elle
        if (url.indexOf("elle.") !== -1) {
          $(elem).addClass("remove");
        }
      });
      $(".remove").remove();

      const content = $("
");
      content.append($("article"));

      const timeClarin = moment().utcOffset(-180);
      let date = `${timeClarin.format("dddd DD MMMM")} de `;
      date += `${timeClarin.format("YYYY")}`;
      date = `${date[0].toUpperCase()}${date.substr(1)}`;
      const time = timeClarin.format("HH:mm");

      const htmlContent = template
        .replace("{{body}}", content.html())
        .replace("{{title}}", "Clarin Limpio")
        .replace("{{date}}", date)
        .replace("{{time}}", time);

      res.send(htmlContent);
    });
  });
};

const parseArticle = (res, url, withImages) => {
  res.setHeader(
    "Cache-Control",
    `max-age=0, s-maxage=${CACHE_DURATION_ARTICLE}`
  );

  fetchContent(`${PAPER_URL}/${url}`, res).then((body) => {
    const $ = cheerio.load(body);

    $("header").remove();
    $("footer").remove();

    if (!withImages) {
      // Las imágenes suelen venir adentro de un link en los articulos
      $("article > a").has("img").remove();
      $("img").remove();
      $("#galeria-trigger, .image-trigger").remove();
      // Eliminar todos los embeds que no sean tweets
      $("[class^=embed-]").each((i, elem) => {
        if (!$(elem).find(".twitter-tweet").length) {
          $(elem).remove();
        }
      });
    } else {
      $(".img-responsive").each((idx, node) => {
        const elem = $(node);
        elem.attr("src", elem.data("small"));
      });

      $("article").each((i, elem) => {
        if ($(elem).find("img").length > 0) {
          $(elem).prepend($(elem).find(".txt").first().remove());
        }
      });
    }

    const content = $("
");

    $("[id^=bannerId_]").remove();
    $("[id^=sas_]").remove();
    $('[itemprop="video"]').remove();

    // Parsear mvHero
    const mvHero = $("#mnhead");
    if (mvHero) {
      try {
        const script = mvHero.find("script").html();
        const title = script
          .replace(/\n/g, "")
          .match(/title: +["']([^"']+)["'],/)[1];
        const divTitle = $("

")
          .addClass("title")
          .append($(`<h1>${title}</h1>`))
          .append($(".bajada"));
        $(".nota-unica").prepend(divTitle);
      } catch (e) {
        // Ignore error
      }
    }

    // Outlinks
    const outlinks = $('

');
    outlinks.append($(".box-content-new, .content-new").remove());
    outlinks.find("span").remove();

    // Heurísticas:
    // A veces los outlinks estan en medio del texto y tienen la pinta
    // de "Mirá también: <noticia>"
    $("a").each((i, elem) => {
      if ($(elem).text().toLowerCase().indexOf("mir") === 0) {
        outlinks.append($(elem).remove());
      }
    });

    // Otras veces hay párrafos enteros que sólo son clickbait+link
    const clickbaits = ["leé", "lee", "te puede interesar", "te puede"];
    $("p").each((i, elem) => {
      const p = $(elem);
      if (p.find("a").length === 1) {
        const link = p.find("a").text();
        const clickbait = p.text().replace(link, "").trim().toLowerCase();
        if (clickbaits.indexOf(clickbait) > -1) {
          outlinks.append(p.find("a").remove());
          p.remove();
        }
      }
    });

    $("p a").each((i, elem) => {
      const url = $(elem).attr("href");
      if (url.indexOf("/tema/") !== -1) {
        // Esto es más clickbait basicamente
        $(elem).replaceWith($(elem).text());
      } else {
        // Si no es clickbait, hacer los links relativos
        $(elem).attr(
          "href",
          url.replace(/http(s)?:\/\/(www.)?clarin.com/i, "")
        );
      }
    });

    // Reemplazar los mark por strong
    $("mark").each((i, elem) => {
      $(elem).replaceWith(`<strong>${$(elem).text()}</strong>`);
    });

    content.append($(".nota-unica .title, .nota-unica .notas-content"));
    const miraTambien = $("

");
    outlinks.find("a").each((i, elem) => {
      const $elem = $(elem);
      if ($elem.text().trim().length > 1) {
        const link = $("")
          .text($elem.text().replace(/Mir[áa] (tambi[ée]n: )?/i, ""))
          .attr("href", $elem.attr("href"));
        miraTambien.append($("

").append(link));
      }
    });

    if (miraTambien.find("li").length) {
      content.append($("
Mirá también
"));
      content.append(miraTambien);
    }

    const publishedDate = content
      .find(".breadcrumb .publishedDate")
      .text()
      .trim();
    const modifiedDate = content
      .find(".breadcrumb .modificatedDate")
      .text()
      .trim();

    content
      .find(".bajada")
      .append($(`<p>${publishedDate} - ${modifiedDate}</p>`));

    // Eliminar cosas de más
    content
      .find(".pull-right, .entry-head, .body-nota > div, #comments")
      .remove();
    $("script").remove();

    title = $("title").text();

    const timeClarin = moment().utcOffset(-180);

    let date = `${timeClarin.format("dddd DD MMMM")} de `;
    date += `${timeClarin.format("YYYY")}`;
    date = `${date[0].toUpperCase()}${date.substr(1)}`;
    const time = timeClarin.format("HH:mm");

    const htmlContent = template
      .replace("{{body}}", content.html())
      .replace("{{title}}", title)
      .replace("{{date}}", date)
      .replace("{{time}}", time);

    res.send(htmlContent);
  });
};

module.exports = (req, res) => {
  let url = req.query.url || "/";

  res.setHeader("Cache-Control", `max-age=0, s-maxage=${CACHE_DURATION}`);
  res.status(200);

  if (url.indexOf(".js") >= 0 || url.indexOf(".css") >= 0) {
    // No pedir los JS ni CSS externos
    res.setHeader(
      "Cache-Control",
      `max-age=0, s-maxage=${CACHE_DURATION_ERROR}`
    );
    res.send("");
  } else {
    let images = false;

    if (url.indexOf("img") === 0) {
      // Con imágenes
      url = url.replace(/img\/?/, "");
      images = true;
    }

    if (url.length > 1) {
      // Es un artículo
      parseArticle(res, url, images);
    } else {
      // Es la home
      parseHome(res, images);
    }
  }
};
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const fs = require('fs');
const ytdl = require('ytdl-core');
const bot = new Discord.Client();
const token = require('./config/botLogin.js').token;

// command initializer
const CMDINIT = '-';
const localPath = './local/';

var adminRole = "admin";		// This can be changed to what ever

var defaultChannels = [{}];
var defualtChannelsPath = './config/default_channels.json';

try{
	var botVersion = require('./package.json').version;
}catch(error) {
	if(error) console.error(error);
	var botVersion = "#?";
}

function checkDefaultChannels(){
	if(fs.existsSync(defualtChannelsPath)){
		try {
			defaultChannels = require(defualtChannelsPath);
		} catch(error){
			console.log("ERROR: reading file:\n" +  error.message);
			fs.rename(defualtChannelsPath, './config/default_channels_ERROR.json', () =>{
				fs.writeFile(fdefualtChannelsPath, JSON.stringify(defaultChannels, null, '\t'), error =>{
					if(error) return console.error(error);
					console.log("\nRESPONSE: Renamed config file with error and created new config file. Please revise and replace!\n");
				});
			});
		}
	} else{
		defaultChannels = [{}];
		fs.writeFile('./config/default_channels.json', JSON.stringify(defaultChannels, null, '\t'), error =>{
			if(error) return console.error(error);
			console.log("Default channel config file created");
		});
	}
}

function isCommand(message, command){
	if(message[0] === CMDINIT && (message.toLowerCase().slice(1) === command.toLowerCase() || message.toLowerCase().slice(1, message.indexOf(" ")) === command.toLowerCase()) ){
		return true;
	}
	return false;
}

function isDev(message){
	var roles = message.member.roles.array();
	for(var role = 0; role < roles.length; role++){
		if(roles[role].name.toLowerCase() === adminRole)
			return true;
	}
	message.channel.sendMessage("You aren't admin for this command.");
	return false;
}

function getGuildByString(guildName){
	return bot.guilds.filterArray( (guild) =>{
		return guild.name === guildName;
	})[0];
}

function getChannelByString(guild, channelName){
	return guild.channels.filterArray( (channel) =>{
		return channel.name === channelName;
	})[0];
}

function setGame(game){
	bot.user.setGame(game);
	console.log("DISCORD: Game set to " + game);
}

function joinDefaultChannels(){
	var botGuilds = bot.guilds.array();
		botGuilds.forEach( guild => {
			for(var i = 0; i < defaultChannels.length; i++){
				if(guild.id === defaultChannels[i].guildID){
					var voiceChannel = guild.channels.filterArray( channel =>{
						return channel.id === defaultChannels[i].voiceID;
					})[0];

					voiceChannel.join();
					console.log("DISCORD: Joined voice channel: " + defaultChannels[i].name + " at [" + defaultChannels[i].guild + "]");
				}
			}
		});
}

bot.on('ready', () => {
	console.log("ApolloBot V" + botVersion)
	console.log(bot.user.username + " (" + bot.user.id + ")");

	// display servers
	var guilds = [];
	bot.guilds.array().forEach( (guild) =>{
		guilds.push(guild.name);
	});
	console.log("Servers:");
	console.log(guilds.join("\n"));
	console.log();

	checkDefaultChannels();
	joinDefaultChannels();
});

bot.on('disconnect', (event) =>{
	console.log("Exited with code: " + event.code);
	if(event.reason)
		console.log("Reason: " + event.reason);
	process.exit(0);
});

bot.on('message', message => {
	// Admin commands
  	if(isCommand(message.content, 'exit')){
  		// Disconnect from voice channels first
  		if(!isDev(message)) return;
  		var connections = bot.voiceConnections.array();
			connections.forEach( (connection) =>{
			connection.disconnect();
		});
  		bot.destroy();
  	}
  	// ----

  	if(isCommand(message.content, 'invite')){
  		bot.generateInvite([
  			"CONNECT", "SPEAK", "READ_MESSAGES", "SEND_MESSAGES", "SEND_TTS_MESSAGES",
  			"ATTACH_FILES", "USE_VAD"
  		]).then( link => {
  			message.channel.sendMessage("**Invite:** "  + link);
  		});
  	}

  	if(isCommand(message.content, 'setvc')){
  		if(message.content.indexOf(" ") !== -1){
  			var voiceChannelName = message.content.split(" ")[1];

  			var guild = message.member.guild;
  			var channel = getChannelByString(guild, voiceChannelName);

  			function writeOutChannels(){
  				fs.writeFile(defualtChannelsPath, JSON.stringify(defaultChannels, null, '\t'), () =>{
		  			message.channel.sendMessage("Server default voice channel set to " + voiceChannelName);
		  		});
  			}

  			if(channel){

  				for(var i = 0; i < defaultChannels.length; i++){
  					if(guild.id === defaultChannels[i].guildID){
  						defaultChannels[i].voiceID = channel.id;
  						defaultChannels[i].name = voiceChannelName;
  						writeOutChannels();
		  				return;
  					}
  				}

  				// Create a default voice channel if there are none.
  				defaultChannels.push({
					name: voiceChannelName,
					guild: guild.name,
					voiceID: channel.id,
					guildID: guild.id
				});
				writeOutChannels();
  			} else{
  				message.channel.sendMessage("No voice channel found");
  			}
  		}
  	}

  	if(isCommand(message.content, 'join')){
  		var userVoiceChannel = message.member.voiceChannel;
  		if(userVoiceChannel)
  			userVoiceChannel.join();
  		else
  			message.channel.sendMessage("You are not in a voice channel.");
  	}

});

bot.login(token);<commit_msg>Fixed defualt channels set to only using one server<commit_after>const Discord = require('discord.js');
const fs = require('fs');
const bot = new Discord.Client();
const token = require('./config/botLogin.js').token;
const yt = require('./youtube.js');

// command initializer
const CMDINIT = '-';
const localPath = './local/';

var adminRole = "admin";		// This can be changed to what ever
var defaultChannel = {};
var defaultChannelPath = './config/default_channel.json';

try{
	var botVersion = require('./package.json').version;
}catch(error) {
	if(error) console.error(error);
	var botVersion = "#?";
}

function checkDefaultChannel(){
	if(fs.existsSync(defaultChannelPath)){
		try {
			defaultChannel = require(defaultChannelPath);
		} catch(error){
			console.log("ERROR: reading file:\n" +  error.message);
			fs.rename(defaultChannelPath, './config/default_channel_ERROR.json', () =>{
				fs.writeFile(defaultChannelPath, JSON.stringify(defaultChannel, null, '\t'), error =>{
					if(error) return console.error(error);
					console.log("\nRESPONSE: Renamed config file with error and created new config file. Please revise and replace!\n");
				});
			});
		}
	} else{
		fs.writeFile(defaultChannelPath, JSON.stringify(defaultChannel, null, '\t'), error =>{
			if(error) return console.error(error);
			console.log("Default channel config file created");
		});
	}
}

function joinDefaultChannel(){
	var botGuilds = bot.guilds.array();
	botGuilds.forEach( guild => {
		if(defaultChannel.guildID === guild.id){
			var channel = guild.channels.filterArray( channel =>{
				return channel.id === defaultChannel.voiceID;
			})[0];
			channel.join();
			console.log("DISCORD: Joined voice channel " + channel.name);
		}
	});
}

function isCommand(message, command){
	if(message[0] === CMDINIT && (message.toLowerCase().slice(1) === command.toLowerCase() || message.toLowerCase().slice(1, message.indexOf(" ")) === command.toLowerCase()) ){
		return true;
	}
	return false;
}

function isDev(message){
	var roles = message.member.roles.array();
	for(var role = 0; role < roles.length; role++){
		if(roles[role].name.toLowerCase() === adminRole)
			return true;
	}
	message.channel.sendMessage("You aren't admin for this command.");
	return false;
}

function getGuildByString(guildName){
	return bot.guilds.filterArray( (guild) =>{
		return guild.name === guildName;
	})[0];
}

function getChannelByString(guild, channelName){
	return guild.channels.filterArray( (channel) =>{
		return channel.name === channelName;
	})[0];
}

function setGame(game){
	bot.user.setGame(game);
	console.log("DISCORD: Game set to " + game);
}

bot.on('ready', () => {
	console.log("ApolloBot V" + botVersion)
	console.log(bot.user.username + " (" + bot.user.id + ")");

	// display servers
	var guilds = [];
	bot.guilds.array().forEach( (guild) =>{
		guilds.push(guild.name);
	});
	console.log("Servers:");
	console.log(guilds.join("\n"));
	console.log();

	checkDefaultChannel();
	joinDefaultChannel();
});

bot.on('disconnect', (event) =>{
	console.log("Exited with code: " + event.code);
	if(event.reason)
		console.log("Reason: " + event.reason);
	process.exit(0);
});

bot.on('message', message => {
	// Admin commands
  	if(isCommand(message.content, 'exit')){
  		// Disconnect from voice channels first
  		if(!isDev(message)) return;
  		var connections = bot.voiceConnections.array();
			connections.forEach( (connection) =>{
			connection.disconnect();
		});
  		bot.destroy();
  	}
  	// ----

  	if(isCommand(message.content, 'invite')){
  		bot.generateInvite([
  			"CONNECT", "SPEAK", "READ_MESSAGES", "SEND_MESSAGES", "SEND_TTS_MESSAGES",
  			"ATTACH_FILES", "USE_VAD"
  		]).then( link => {
  			message.channel.sendMessage("**Invite:** "  + link);
  		});
  	}

  	if(isCommand(message.content, 'setvc')){
  		if(message.content.indexOf(" ") !== -1){
  			var voiceChannelName = message.content.split(" ")[1];

  			var guild = message.member.guild;
  			var channel = getChannelByString(guild, voiceChannelName);

  			function writeOutChannels(){
  				fs.writeFile(defaultChannelPath, JSON.stringify(defaultChannel, null, '\t'), () =>{
		  			message.channel.sendMessage("Server default voice channel set to " + voiceChannelName);
		  		});
  			}

  			if(channel){
  				defaultChannel.name = voiceChannelName;
				defaultChannel.guild = guild.name;
				defaultChannel.voiceID = channel.id;
				defaultChannel.guildID = guild.id;
				writeOutChannels();
  			} else
  			  	message.channel.sendMessage("No voice channel found");
  		}
  	}

  	if(isCommand(message.content, 'join')){
  		var userVoiceChannel = message.member.voiceChannel;
  		if(userVoiceChannel)
  			userVoiceChannel.join();
  		else
  			message.channel.sendMessage("You are not in a voice channel.");
  	}

});

bot.login(token);<|endoftext|>


<commit_before>import Immutable from 'immutable';

export const Events = {
  CHANGE: 'store:change',
  CHANGE_SELECTION: 'store:change-selection',
  LOADING_START: 'store:loading-start',
  LOADING_END: 'store:loading-end',
};

const defaultSequence = new Immutable.List('AAACGAAAACT'.split(''));
const defaultLabels = new Immutable.List([
  {
    name: 'Exon',
    color: '#334854',
    isActive: true,
  },
  {
    name: 'Primer',
    color: '#f9c535',
    isActive: true,
  },
  {
    name: 'SNP',
    color: '#e04462',
    isActive: true,
  },
]);

export default class Store {

  constructor(events) {
    this.events = events;
    this.reader = new FileReader();

    this.state = {
      sequence: [],
      labels: defaultLabels,
      selection: new Immutable.OrderedSet(),
      modalIsOpen: true,
    };

    // file reader
    this.offset = 0;
    this.file = null;
    this.fileParts = [];
    this.reader.onload = this.onFileLoad.bind(this);
  }

  getState() {
    return this.state;
  }

  loadFromFile(file) {
    this.events.emit(Events.LOADING_START);

    // reset
    this.offset = 0;
    this.file = file;
    this.fileParts = [];

    this.loadFileChunk();
  }

  loadFileChunk() {
    const end = this.offset + (10 * 1024); // chunk size
    const blob = this.file.slice(this.offset, end);
    this.offset = end;

    this.reader.readAsText(blob);
  }

  onFileLoad(event) {
    if (null === event.target.error) {
      let parts = event.target.result.split('\n');

      if (/>/.test(parts[0])) {
        parts = parts.slice(1);
      }

      this.fileParts = this.fileParts.concat(parts);
    }

    if (this.offset >= this.file.size) {
      this.state.sequence = new Immutable.List(
        this.fileParts.join('').split('')
      );

      this.events.emit(Events.LOADING_END);
      this.events.emit(Events.CHANGE, this.state);

      return;
    }

    this.loadFileChunk();
  }

  addNewLabel(label) {
    this.state.labels = this.state.labels.push(label);

    this.events.emit(Events.CHANGE, this.state);
  }

  updateLabelAt(index, label) {
    this.state.labels = this.state.labels.update(index, () => (
      {
        name: label.name,
        color: label.color,
        isActive: true,
      }
    ));

    this.events.emit(Events.CHANGE, this.state);
  }

  removeLabelAt(index) {
    this.state.labels = this.state.labels.splice(index, 1);

    this.events.emit(Events.CHANGE, this.state);
  }

  toggleLabelAt(index) {
    this.state.labels = this.state.labels.update(index, (label) => (
      {
        name: label.name,
        color: label.color,
        isActive: !label.isActive,
      }
    ));

    this.events.emit(Events.CHANGE, this.state);
  }

  clearSelection() {
    this.state.selection = this.state.selection.clear();
  }

  updateSelection(selected) {
    let previousSelection = this.state.selection;

    if (2 <= previousSelection.size) {
      previousSelection = previousSelection.slice(1);
    }

    this.state.selection = previousSelection.has(selected) ?
      previousSelection.delete(selected) : previousSelection.add(selected);

    this.events.emit(Events.CHANGE_SELECTION, this.state.selection);
  }

  startDemo() {
    this.state.sequence = defaultSequence;
    this.state.modalIsOpen = false;

    this.events.emit(Events.CHANGE, this.state);
  }

  closeModal() {
    this.state.modalIsOpen = false;

    this.events.emit(Events.CHANGE, this.state);
  }
}
<commit_msg>Add a realistic sequence sample<commit_after>import Immutable from 'immutable';

export const Events = {
  CHANGE: 'store:change',
  CHANGE_SELECTION: 'store:change-selection',
  LOADING_START: 'store:loading-start',
  LOADING_END: 'store:loading-end',
};

const defaultSequence = new Immutable.List(
  [
    'ATGGTCACTCTAATCGCAGTCTGCAATTTACGTGTTTCCAACTTAACGCCCCCAAGTTAATAGCCGTAAT',
    'CATTTGAAAAGAAAGGCACGCACGCACAACGCCATGCGGATCGAACCTGGGGACTCCTTTTGGACGAAAA',
    'AGGCGATGTTTTCCAACGCAGAAAGGCAGTACTTTGAGACGGTCCGTCCGCGGAAGACCAGTGTGAGTAA',
    'AAGTTGACCGTCGATGGCGATTTCACAAGTGACGTTTAAGTGGCGGGAACTTCTACTCACAAATCCCTGA',
    'GCCCTGTGATATGATTTATTTTATGGAGCCGTGATCCGGACGAAAAATGCACACACATTTCTACAAAAAT',
    'ATGTACATCGCGGTGCGATTGTGTCGCTTAAAGCACACGTACACCCACTGTCACACTCACACTCACATGC',
  ].join('').split('')
);
const defaultLabels = new Immutable.List([
  {
    name: 'Exon',
    color: '#334854',
    isActive: true,
  },
  {
    name: 'Primer',
    color: '#f9c535',
    isActive: true,
  },
  {
    name: 'SNP',
    color: '#e04462',
    isActive: true,
  },
]);

export default class Store {

  constructor(events) {
    this.events = events;
    this.reader = new FileReader();

    this.state = {
      sequence: [],
      labels: defaultLabels,
      selection: new Immutable.OrderedSet(),
      modalIsOpen: true,
    };

    // file reader
    this.offset = 0;
    this.file = null;
    this.fileParts = [];
    this.reader.onload = this.onFileLoad.bind(this);
  }

  getState() {
    return this.state;
  }

  loadFromFile(file) {
    this.events.emit(Events.LOADING_START);

    // reset
    this.offset = 0;
    this.file = file;
    this.fileParts = [];

    this.loadFileChunk();
  }

  loadFileChunk() {
    const end = this.offset + (10 * 1024); // chunk size
    const blob = this.file.slice(this.offset, end);
    this.offset = end;

    this.reader.readAsText(blob);
  }

  onFileLoad(event) {
    if (null === event.target.error) {
      let parts = event.target.result.split('\n');

      if (/>/.test(parts[0])) {
        parts = parts.slice(1);
      }

      this.fileParts = this.fileParts.concat(parts);
    }

    if (this.offset >= this.file.size) {
      this.state.sequence = new Immutable.List(
        this.fileParts.join('').split('')
      );

      this.events.emit(Events.LOADING_END);
      this.events.emit(Events.CHANGE, this.state);

      return;
    }

    this.loadFileChunk();
  }

  addNewLabel(label) {
    this.state.labels = this.state.labels.push(label);

    this.events.emit(Events.CHANGE, this.state);
  }

  updateLabelAt(index, label) {
    this.state.labels = this.state.labels.update(index, () => (
      {
        name: label.name,
        color: label.color,
        isActive: true,
      }
    ));

    this.events.emit(Events.CHANGE, this.state);
  }

  removeLabelAt(index) {
    this.state.labels = this.state.labels.splice(index, 1);

    this.events.emit(Events.CHANGE, this.state);
  }

  toggleLabelAt(index) {
    this.state.labels = this.state.labels.update(index, (label) => (
      {
        name: label.name,
        color: label.color,
        isActive: !label.isActive,
      }
    ));

    this.events.emit(Events.CHANGE, this.state);
  }

  clearSelection() {
    this.state.selection = this.state.selection.clear();
  }

  updateSelection(selected) {
    let previousSelection = this.state.selection;

    if (2 <= previousSelection.size) {
      previousSelection = previousSelection.slice(1);
    }

    this.state.selection = previousSelection.has(selected) ?
      previousSelection.delete(selected) : previousSelection.add(selected);

    this.events.emit(Events.CHANGE_SELECTION, this.state.selection);
  }

  startDemo() {
    this.state.sequence = defaultSequence;
    this.state.modalIsOpen = false;

    this.events.emit(Events.CHANGE, this.state);
  }

  closeModal() {
    this.state.modalIsOpen = false;

    this.events.emit(Events.CHANGE, this.state);
  }
}
<|endoftext|>


<commit_before>// The contents of this file will be executed before any of
// your view controllers are ever executed, including the index.
// You have access to all functionality on the `Alloy` namespace.
//
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the `Alloy.Globals`
// object. For example:
//
// Alloy.Globals.someGlobalFunction = function(){};

var moment = require('alloy/moment');

//Dotcms env
Alloy.Globals.dotcms = {
    url: 'http://starter.dotcms.com:8080',
    hostId: '48190c8c-42c4-46af-8d1a-0cd5db894797',
    yahooApi: 'http://query.yahooapis.com/v1/public/yql?'
};

// Menu options
// The id is the name of the controller
Alloy.Globals.menuOptions = [
    {
        first: true,
        id: 'home',
        title: 'Home'
    },
    {
        id: 'about-us',
        title: 'About Us'
    },
    {
        id: 'our-team',
        title: 'Our Team'
    },
    {
        id: 'products',
        title: 'Products'
    },
    {
        id: 'news',
        title: 'News'
    },
    {
        id: 'events',
        title: 'Events'
    },
    {
        id: 'gallery',
        title: 'Gallery',
        header: {
            buttons: {
                icon: 'plus',
                id: 'gallery-upload',
                title: 'Upload content to gallery'
            }
        }
    },
    // {
    //     id: 'contact-us',
    //     title: 'Contact Us'
    // }
];

// Creating NavigationController as a global object
var NavigationController = require('NavigationController'); // use the NavigationController library
var navController = new NavigationController();
Alloy.Globals.navcontroller = navController;

// Opening new windows
Alloy.Globals.winToOpen = function(option) {
    var topWin = Alloy.Globals.navcontroller.windowsInfo().stackTop || {};
    var stackLength = Alloy.Globals.navcontroller.windowsInfo().stackLength;
    if (topWin.name != option.id || stackLength === 0) {
        var standardWin = Alloy.createController('standard-win');
        var standardWinView = standardWin.getView();
        standardWinView.title = option.title;
        standardWinView.name = option.id;

        // Setting the content into the just opened window
        option.standardWinView = standardWinView;
        var mainContent = Alloy.createController(option.id, option);
        standardWin.setMainContent(mainContent.getView());

        // Setting the header right button
        if (_.isObject(option.header)) {
            standardWin.setHeaderButtons(option.header.buttons);
        }
    }
};

Alloy.Globals.openWindow = function(win) {
    Alloy.Globals.navcontroller.open(win);
};

// Utils
Alloy.Globals.isAndroid = Ti.Platform.osname == 'android';
Alloy.Globals.isiOS = Ti.Platform.osname === 'iphone' || Ti.Platform.osname === 'ipad';
Alloy.Globals.platformWidth = Ti.Platform.displayCaps.platformWidth;
Alloy.Globals.screenWidth = Alloy.Globals.isAndroid ? Ti.Platform.displayCaps.platformWidth / (Titanium.Platform.displayCaps.dpi / 160) : Ti.Platform.displayCaps.platformWidth;

// TODO: find a better way to parse/encode HTML
Alloy.Globals.stripHtml = function(content) {
    var stripped = content.replace(/<[^>]*>?/g, '');
    stripped = stripped.replace('\n', '');
    stripped = stripped.replace('— ', '— ');
    return stripped;
};

// Colors
Alloy.Globals.colors = {
    black: '#000000',
    blue: '#26333F',
    blueLight: '#9FC5E2',
    blueLightest: '#ECF3F9',
    green: '#7ED321',
    red: '#D0021B',
    white: 'white',
    gray: '#89939C'
};
Alloy.Globals.colors.slideMenuBg = Alloy.Globals.colors.blue;
Alloy.Globals.colors.headerBg = Alloy.Globals.colors.blue;

// Fonts
var buildFonts = function () {
    var fonts = {
        primary: 'Kameron',
        secondary: 'Oxygen'
    };

    var weights = {
        primary: {
            regular: '',
            bold: '-Bold',
        },
        secondary: {
            regular: '',
            bold: '-Bold',
            bolditalic: '-BoldItalic',
            italic: '-Italic',
        }
    };

    var sizes = {
        productPrice: 72,
        header1: 26,
        header2: 24,
        header3: 22,
        header4: 20,
        header5: 18,
        body1: 16,
        body2: 14,
        mouse: 12
    };

    _.each(_.keys(fonts), function (levelName) {
        var font = fonts[levelName];
        fonts[levelName] = {};
        _.each(_.keys(sizes), function (sizeName) {
            var size = sizes[sizeName];
            fonts[levelName][sizeName] = {};
            _.each(_.keys(weights[levelName]), function (weightName) {
                var weight = weights[levelName][weightName];
                fonts[levelName][sizeName][weightName] = {
                    fontFamily: font + weight,
                    fontSize: size
                };
            });
        });
    });
    return fonts;
};

// Margins
Alloy.Globals.margin = 15;

Alloy.Globals.fonts = buildFonts();
<commit_msg>Point to demo30<commit_after>// The contents of this file will be executed before any of
// your view controllers are ever executed, including the index.
// You have access to all functionality on the `Alloy` namespace.
//
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the `Alloy.Globals`
// object. For example:
//
// Alloy.Globals.someGlobalFunction = function(){};

var moment = require('alloy/moment');

//Dotcms env
Alloy.Globals.dotcms = {
    url: 'http://demo30.dotcms.com',
    hostId: '48190c8c-42c4-46af-8d1a-0cd5db894797',
    yahooApi: 'http://query.yahooapis.com/v1/public/yql?'
};

// Menu options
// The id is the name of the controller
Alloy.Globals.menuOptions = [
    {
        first: true,
        id: 'home',
        title: 'Home'
    },
    {
        id: 'about-us',
        title: 'About Us'
    },
    {
        id: 'our-team',
        title: 'Our Team'
    },
    {
        id: 'products',
        title: 'Products'
    },
    {
        id: 'news',
        title: 'News'
    },
    {
        id: 'events',
        title: 'Events'
    },
    {
        id: 'gallery',
        title: 'Gallery',
        header: {
            buttons: {
                icon: 'plus',
                id: 'gallery-upload',
                title: 'Upload content to gallery'
            }
        }
    },
    // {
    //     id: 'contact-us',
    //     title: 'Contact Us'
    // }
];

// Creating NavigationController as a global object
var NavigationController = require('NavigationController'); // use the NavigationController library
var navController = new NavigationController();
Alloy.Globals.navcontroller = navController;

// Opening new windows
Alloy.Globals.winToOpen = function(option) {
    var topWin = Alloy.Globals.navcontroller.windowsInfo().stackTop || {};
    var stackLength = Alloy.Globals.navcontroller.windowsInfo().stackLength;
    if (topWin.name != option.id || stackLength === 0) {
        var standardWin = Alloy.createController('standard-win');
        var standardWinView = standardWin.getView();
        standardWinView.title = option.title;
        standardWinView.name = option.id;

        // Setting the content into the just opened window
        option.standardWinView = standardWinView;
        var mainContent = Alloy.createController(option.id, option);
        standardWin.setMainContent(mainContent.getView());

        // Setting the header right button
        if (_.isObject(option.header)) {
            standardWin.setHeaderButtons(option.header.buttons);
        }
    }
};

Alloy.Globals.openWindow = function(win) {
    Alloy.Globals.navcontroller.open(win);
};

// Utils
Alloy.Globals.isAndroid = Ti.Platform.osname == 'android';
Alloy.Globals.isiOS = Ti.Platform.osname === 'iphone' || Ti.Platform.osname === 'ipad';
Alloy.Globals.platformWidth = Ti.Platform.displayCaps.platformWidth;
Alloy.Globals.screenWidth = Alloy.Globals.isAndroid ? Ti.Platform.displayCaps.platformWidth / (Titanium.Platform.displayCaps.dpi / 160) : Ti.Platform.displayCaps.platformWidth;

// TODO: find a better way to parse/encode HTML
Alloy.Globals.stripHtml = function(content) {
    var stripped = content.replace(/<[^>]*>?/g, '');
    stripped = stripped.replace('\n', '');
    stripped = stripped.replace('— ', '— ');
    return stripped;
};

// Colors
Alloy.Globals.colors = {
    black: '#000000',
    blue: '#26333F',
    blueLight: '#9FC5E2',
    blueLightest: '#ECF3F9',
    green: '#7ED321',
    red: '#D0021B',
    white: 'white',
    gray: '#89939C'
};
Alloy.Globals.colors.slideMenuBg = Alloy.Globals.colors.blue;
Alloy.Globals.colors.headerBg = Alloy.Globals.colors.blue;

// Fonts
var buildFonts = function () {
    var fonts = {
        primary: 'Kameron',
        secondary: 'Oxygen'
    };

    var weights = {
        primary: {
            regular: '',
            bold: '-Bold',
        },
        secondary: {
            regular: '',
            bold: '-Bold',
            bolditalic: '-BoldItalic',
            italic: '-Italic',
        }
    };

    var sizes = {
        productPrice: 72,
        header1: 26,
        header2: 24,
        header3: 22,
        header4: 20,
        header5: 18,
        body1: 16,
        body2: 14,
        mouse: 12
    };

    _.each(_.keys(fonts), function (levelName) {
        var font = fonts[levelName];
        fonts[levelName] = {};
        _.each(_.keys(sizes), function (sizeName) {
            var size = sizes[sizeName];
            fonts[levelName][sizeName] = {};
            _.each(_.keys(weights[levelName]), function (weightName) {
                var weight = weights[levelName][weightName];
                fonts[levelName][sizeName][weightName] = {
                    fontFamily: font + weight,
                    fontSize: size
                };
            });
        });
    });
    return fonts;
};

// Margins
Alloy.Globals.margin = 15;

Alloy.Globals.fonts = buildFonts();
<|endoftext|>


<commit_before>console.log('yo')
<commit_msg>add let test<commit_after>let x = 10
console.log(x)
<|endoftext|>


<commit_before>import _ from 'underscore';
import $ from 'jquery';
import {history} from 'backbone';

import app from './application';

import playlistsController from './modules/playlists/controller';
import activitiesController from './modules/activities/controller';
import videosController from './modules/videos/controller';
import youtubeController from './modules/youtube/controller';

// Router
import './modules/playlists/router';
import './modules/activities/router';
import './modules/videos/router';

var initControllers = function () {
    const mainRegion = app.getRegion('main');

    playlistsController.init(mainRegion);
    activitiesController.init(mainRegion);
    videosController.init(mainRegion);
    youtubeController.init();
};

var getFragments = function () {
    return history.fragment.split('/');
};

app.listenTo(app, 'start', function () {
    initControllers();

    history.start();

    app.navigate();

    const fragments = getFragments();
    const rootFragment = _.first(fragments);

    if (rootFragment === 'standalone') {
        $('html').addClass('is-'+ rootFragment);

        return;
    }

    app.initBreadcrumb();
    app.initNavigation();
    app.detectAdBlock();
});

app.start();
<commit_msg>Replaced var Added getRootFragment()<commit_after>import _ from 'underscore';
import $ from 'jquery';
import {history} from 'backbone';

import app from './application';

import playlistsController from './modules/playlists/controller';
import activitiesController from './modules/activities/controller';
import videosController from './modules/videos/controller';
import youtubeController from './modules/youtube/controller';

// Router
import './modules/playlists/router';
import './modules/activities/router';
import './modules/videos/router';

const initControllers = function () {
    const mainRegion = app.getRegion('main');

    playlistsController.init(mainRegion);
    activitiesController.init(mainRegion);
    videosController.init(mainRegion);
    youtubeController.init();
};

const getFragments = function () {
    return history.fragment.split('/');
};

const getRootFragment = function () {
    const fragments = getFragments();

    return _.first(fragments);
};

app.listenTo(app, 'start', function () {
    initControllers();

    history.start();

    app.navigate();

    const rootFragment = getRootFragment();

    if (rootFragment === 'standalone') {
        $('html').addClass('is-'+ rootFragment);

        return;
    }

    app.initBreadcrumb();
    app.initNavigation();
    app.detectAdBlock();
});

app.start();
<|endoftext|>


<commit_before>'use strict';
var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

var authorPrompts = [
  {
    name: 'name',
    message: 'Author\'s Name:',
    required: true
  },
  {
    name: 'email',
    message: 'Author\'s Email:',
    required: true
  },
  {
    name: 'website',
    message: 'Author\'s Website (optional):',
    required: true
  },
  {
    name: 'year',
    message: 'Year(s) to include on the license (i.e. 2016-2017):',
    required: true,
    default: (new Date()).getFullYear()
  }
];

module.exports = Generator.extend({
  prompting: {
    qSourceCode() {
      // Have Yeoman greet the user.
      this.log(yosay(
        'Welcome to the dazzling ' + chalk.red('yo licensor') + '!'
      ));

      var prompts = [
        {
          type: 'confirm',
          name: 'hasSourceCode',
          message: 'Do you want to license ' + chalk.underline('source code') + ' of a software project?',
          default: true
        }
      ];

      return this.prompt(prompts).then(function (answers) {
        // To access props later use this.props.someAnswer;
        this.options.qSourceCode = answers;
      }.bind(this));
    },

    qSourceCodeAuthor() {
      if (this.options.qSourceCode.hasSourceCode) {
        var prompts = authorPrompts;

        return this.prompt(prompts).then(function (answers) {
          // To access props later use this.props.someAnswer;
          this.options.qSourceCodeAuthor = answers;
        }.bind(this));
      }
    },

    doLicenseSourceCode() {
      if (this.options.qSourceCode.hasSourceCode === true) {
        this.log(yosay(
          'Generating LICENSE for ' + chalk.red.underline('Source Code') + '!'
        ));

        this.composeWith(require.resolve('generator-license/app'), {
          name: this.options.qSourceCodeAuthor.name,
          email: this.options.qSourceCodeAuthor.email,
          website: this.options.qSourceCodeAuthor.website,
          year: this.options.qSourceCodeAuthor.year
        });
      }
    },

    qSourceWithCreative() {
      if (this.options.qSourceCode.hasSourceCode === true) {
        var prompts = [
          {
            type: 'confirm',
            name: 'hasCreativeWork',
            message: 'Does your software project include other ' + chalk.underline('creative work') + ' (i.e. documentation, media files, tutorials) that you want to license under an appropriate license?',
            default: true
          },
          {
            name: 'creativeWork',
            message: 'Title of Creative Work (i.e. ProjectX Documentation, Media files in the repository, Data in the archives):',
            when: function (answers) {
              return answers.hasCreativeWork === true;
            }
          },
          {
            name: 'ccDir',
            message: 'Main directory where Creative Work is stored (i.e. ' + chalk.underline('docs/') + ', ' + chalk.underline('music/') + ', ' + chalk.underline('data/') + '):',
            default: 'docs/',
            when: function (answers) {
              return answers.hasCreativeWork === true;
            }
          }
        ];

        return this.prompt(prompts).then(function (answers) {
          // To access props later use this.props.someAnswer;
          this.options.qSourceWithCreative = answers;
        }.bind(this));
      }
    },

    qCreativeWork() {
      var prompts = [
        {
          type: 'confirm',
          name: 'hasCreativeWork',
          message: 'Do you want to license ' + chalk.underline('creative work') + ' (i.e. audio/video files, written matterial, database data)?',
          default: true,
          when: this.options.qSourceCode.hasSourceCode === false
        },
        {
          name: 'creativeWork',
          message: 'Title of creative work (i.e. "Loud Song" Remix, Cat Video, "Book of Knowledge", Map of local coffeeshops):',
          when: function (answers) {
            return answers.hasCreativeWork === true;
          }
        }
      ];

      return this.prompt(prompts).then(function (answers) {
        // To access props later use this.props.someAnswer;
        this.options.qCreativeWork = answers;
      }.bind(this));
    },

    qCreativeWorkAuthor() {
      // only prompt this if it wasn't already answered and is required
      if (this.options.qSourceCode.hasSourceCode === false &&
      this.options.qCreativeWork.hasCreativeWork === true) {
        var prompts = authorPrompts;

        return this.prompt(prompts).then(function (answers) {
          // To access props later use this.props.someAnswer;
          this.options.qCreativeWorkAuthor = answers;
        }.bind(this));
      }
    },

    licenseSourceCodeWithCreativeWork() {
      if (this.options.qSourceCode.hasSourceCode === true &&
      this.options.qSourceWithCreative.hasCreativeWork === true) {
        this.composeWith(require.resolve('generator-license/app'), {
          name: this.options.qSourceCodeAuthor.name,
          email: this.options.qSourceCodeAuthor.email,
          website: this.options.qSourceCodeAuthor.website,
          year: this.options.qSourceCodeAuthor.year,
          licensePrompt: 'Choose a license for source code:'
        });

        var outputFile = this.options.qSourceWithCreative.ccDir + '/LICENSE';

        this.composeWith(require.resolve('generator-license-cc/app'), {
          name: this.options.qSourceCodeAuthor.name,
          ccWork: this.options.qCreativeWork.creativeWork,
          email: this.options.qSourceCodeAuthor.email,
          website: this.options.qSourceCodeAuthor.website,
          year: this.options.qSourceCodeAuthor.year,
          licensePrompt: 'Choose a license for creative work:',
          output: outputFile
        });
      }
    },

    licenseSourceCodeOnly() {
      if (this.options.qSourceCode.hasSourceCode === true &&
      this.options.qSourceWithCreative.hasCreativeWork === false) {
        this.composeWith(require.resolve('generator-license/app'), {
          name: this.options.qSourceCodeAuthor.name,
          email: this.options.qSourceCodeAuthor.email,
          website: this.options.qSourceCodeAuthor.website,
          year: this.options.qSourceCodeAuthor.year,
          licensePrompt: 'Choose a license for source code:'
        });
      }
    },

    licenseCreativeWorkOnly() {
      if (this.options.qCreativeWork.hasCreativeWork) {
        this.composeWith(require.resolve('generator-license-cc/app'), {
          name: this.options.qCreativeWorkAuthor.name,
          ccWork: this.options.qCreativeWork.creativeWork,
          email: this.options.qCreativeWorkAuthor.email,
          website: this.options.qCreativeWorkAuthor.website,
          year: this.options.qCreativeWorkAuthor.year,
          licensePrompt: 'Choose a license for creative work:',
          output: 'LICENSE'
        });
      }
    }
  },

  writing: function () {
  },

  install: function () {
  }
});
<commit_msg>fix double source code license prompt - fixes #3<commit_after>'use strict';
var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

var authorPrompts = [
  {
    name: 'name',
    message: 'Author\'s Name:',
    required: true
  },
  {
    name: 'email',
    message: 'Author\'s Email:',
    required: true
  },
  {
    name: 'website',
    message: 'Author\'s Website (optional):',
    required: true
  },
  {
    name: 'year',
    message: 'Year(s) to include on the license (i.e. 2016-2017):',
    required: true,
    default: (new Date()).getFullYear()
  }
];

module.exports = Generator.extend({
  prompting: {
    qSourceCode() {
      // Have Yeoman greet the user.
      this.log(yosay(
        'Welcome to the dazzling ' + chalk.red('yo licensor') + '!'
      ));

      var prompts = [
        {
          type: 'confirm',
          name: 'hasSourceCode',
          message: 'Do you want to license ' + chalk.underline('source code') + ' of a software project?',
          default: true
        }
      ];

      return this.prompt(prompts).then(function (answers) {
        // To access props later use this.props.someAnswer;
        this.options.qSourceCode = answers;
      }.bind(this));
    },

    qSourceCodeAuthor() {
      if (this.options.qSourceCode.hasSourceCode) {
        var prompts = authorPrompts;

        return this.prompt(prompts).then(function (answers) {
          // To access props later use this.props.someAnswer;
          this.options.qSourceCodeAuthor = answers;
        }.bind(this));
      }
    },

    doLicenseSourceCode() {
      if (this.options.qSourceCode.hasSourceCode === true) {
        this.log(yosay(
          'Generating LICENSE for ' + chalk.red.underline('Source Code') + '!'
        ));

        this.composeWith(require.resolve('generator-license/app'), {
          name: this.options.qSourceCodeAuthor.name,
          email: this.options.qSourceCodeAuthor.email,
          website: this.options.qSourceCodeAuthor.website,
          year: this.options.qSourceCodeAuthor.year
        });
      }
    },

    qSourceWithCreative() {
      if (this.options.qSourceCode.hasSourceCode === true) {
        var prompts = [
          {
            type: 'confirm',
            name: 'hasCreativeWork',
            message: 'Does your software project include other ' + chalk.underline('creative work') + ' (i.e. documentation, media files, tutorials) that you want to license under an appropriate license?',
            default: true
          },
          {
            name: 'creativeWork',
            message: 'Title of Creative Work (i.e. ProjectX Documentation, Media files in the repository, Data in the archives):',
            when: function (answers) {
              return answers.hasCreativeWork === true;
            }
          },
          {
            name: 'ccDir',
            message: 'Main directory where Creative Work is stored (i.e. ' + chalk.underline('docs/') + ', ' + chalk.underline('music/') + ', ' + chalk.underline('data/') + '):',
            default: 'docs/',
            when: function (answers) {
              return answers.hasCreativeWork === true;
            }
          }
        ];

        return this.prompt(prompts).then(function (answers) {
          // To access props later use this.props.someAnswer;
          this.options.qSourceWithCreative = answers;
        }.bind(this));
      }
    },

    qCreativeWork() {
      var prompts = [
        {
          type: 'confirm',
          name: 'hasCreativeWork',
          message: 'Do you want to license ' + chalk.underline('creative work') + ' (i.e. audio/video files, written matterial, database data)?',
          default: true,
          when: this.options.qSourceCode.hasSourceCode === false
        },
        {
          name: 'creativeWork',
          message: 'Title of creative work (i.e. "Loud Song" Remix, Cat Video, "Book of Knowledge", Map of local coffeeshops):',
          when: function (answers) {
            return answers.hasCreativeWork === true;
          }
        }
      ];

      return this.prompt(prompts).then(function (answers) {
        // To access props later use this.props.someAnswer;
        this.options.qCreativeWork = answers;
      }.bind(this));
    },

    qCreativeWorkAuthor() {
      // only prompt this if it wasn't already answered and is required
      if (this.options.qSourceCode.hasSourceCode === false &&
      this.options.qCreativeWork.hasCreativeWork === true) {
        var prompts = authorPrompts;

        return this.prompt(prompts).then(function (answers) {
          // To access props later use this.props.someAnswer;
          this.options.qCreativeWorkAuthor = answers;
        }.bind(this));
      }
    },

    licenseSourceCodeWithCreativeWork() {
      if (this.options.qSourceCode.hasSourceCode === true &&
      this.options.qSourceWithCreative.hasCreativeWork === true) {
        this.composeWith(require.resolve('generator-license/app'), {
          name: this.options.qSourceCodeAuthor.name,
          email: this.options.qSourceCodeAuthor.email,
          website: this.options.qSourceCodeAuthor.website,
          year: this.options.qSourceCodeAuthor.year,
          licensePrompt: 'Choose a license for source code:'
        });

        var outputFile = this.options.qSourceWithCreative.ccDir + '/LICENSE';

        this.composeWith(require.resolve('generator-license-cc/app'), {
          name: this.options.qSourceCodeAuthor.name,
          ccWork: this.options.qCreativeWork.creativeWork,
          email: this.options.qSourceCodeAuthor.email,
          website: this.options.qSourceCodeAuthor.website,
          year: this.options.qSourceCodeAuthor.year,
          licensePrompt: 'Choose a license for creative work:',
          output: outputFile
        });
      }
    },

    licenseSourceCodeOnly() {
      if (this.options.qSourceCode.hasSourceCode === true &&
      this.options.qSourceWithCreative.hasCreativeWork === false) {
        this.composeWith(require.resolve('generator-license/app'), {
          name: this.options.qSourceCodeAuthor.name,
          email: this.options.qSourceCodeAuthor.email,
          website: this.options.qSourceCodeAuthor.website,
          year: this.options.qSourceCodeAuthor.year,
          licensePrompt: 'Choose a license for source code:'
        });
      }
    },

    licenseCreativeWorkOnly() {
      if (this.options.qSourceCode.hasSourceCode === false &&
        this.options.qCreativeWork.hasCreativeWork === true) {

        this.composeWith(require.resolve('generator-license-cc/app'), {
          name: this.options.qCreativeWorkAuthor.name,
          ccWork: this.options.qCreativeWork.creativeWork,
          email: this.options.qCreativeWorkAuthor.email,
          website: this.options.qCreativeWorkAuthor.website,
          year: this.options.qCreativeWorkAuthor.year,
          licensePrompt: 'Choose a license for creative work:',
          output: 'LICENSE'
        });
      }
    }
  },

  writing: function () {
  },

  install: function () {
  }
});
<|endoftext|>


<commit_before>const async = require('async')
const express = require('express')
var app = express()

// Instantiate intializers of the application
const intializers = [
  // 1. Initialize logger
  './models/logger',
  // 2. Body and Cookie Parsing
  './models/parsing',
  // 3. Initialize database
  './database/database',
  // 4. Serve Static Files
  './models/static-files',
  // 5. Initialize server
  './models/server',
  // 5. Initialize socket connection
  './models/room-socket',
  // 6. Initilize all of the routes
  './routes'
].map(filename => {
  return (done) => { require(filename).init(app, done) }
})

// activate all intializers
async.waterfall(intializers, (err, _) => {
  // success: Start server
  // failure: Log error Message
  if(err) {
    app.logger.error(error)
  } else {
    app.server.listen(app.PORT, () => {
        app.logger.info("Server started on port " + app.PORT)
    })
  }
})
<commit_msg>:golf:<commit_after>const async = require('async')
const express = require('express')
var app = express()

// Instantiate intializers of the application
const intializers = [
  // 1. Initialize logger
  './models/logger',
  // 2. Body and Cookie Parsing
  './models/parsing',
  // 3. Initialize database
  './database/database',
  // 4. Serve Static Files
  './models/static-files',
  // 5. Initialize server
  './models/server',
  // 5. Initialize socket connection
  './models/room-socket',
  // 6. Initilize all of the routes
  './routes'
].map(filename => done => require(filename).init(app, done) )

// activate all intializers
async.waterfall(intializers, (err, _) => {
  // success: Start server
  // failure: Log error Message
  if(err) {
    app.logger.error(error)
  } else {
    app.server.listen(app.PORT, () => {
        app.logger.info("Server started on port " + app.PORT)
    })
  }
})
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var NlexpressGenerator = module.exports = function NlexpressGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(NlexpressGenerator, yeoman.generators.Base);

NlexpressGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    type: 'confirm',
    name: 'someOption',
    message: 'Would you like to enable this option?',
    default: true
  }];

  this.prompt(prompts, function (props) {
    this.someOption = props.someOption;

    cb();
  }.bind(this));
};

NlexpressGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/templates');

  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
};

NlexpressGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<commit_msg>add prompt for app name<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var NlexpressGenerator = module.exports = function NlexpressGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(NlexpressGenerator, yeoman.generators.Base);

NlexpressGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    name: 'appName',
    message: 'What would you like to name your app?'
  }];

  this.prompt(prompts, function (props) {
    this.appName = props.appName;

    cb();
  }.bind(this));
};

NlexpressGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/templates');

  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
};

NlexpressGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<|endoftext|>


<commit_before>'use strict';

var util = require('util'),
    fs = require('fs'),
    path = require('path'),
    chalk = require('chalk'),
    yeoman = require('yeoman-generator'),
    pkgName = require('pkg-name'),
    updateNotifier = require('update-notifier'),
    compareVersion = require('compare-version'),
    stringLength = require('string-length'),
    _ = require('underscore.string'),
    mkdirp = require('mkdirp'),
    childProcess = require('child_process'),
    pkg = require('../package.json'),
    templateName = 'freekerneljs-basic-app-md',
    generatorRoot = '',
    templatePath = '';

var exec = childProcess.exec;

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function (file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

var freekerneljsGenerator = yeoman.generators.Base.extend({
    constructor: function () {
        yeoman.generators.Base.apply(this, arguments);

        this.on('end', function () {
            console.log('Running Grunt tasks now...');

            if (templateName == 'freekerneljs-basic-app') {
                var done = this.async();
                exec('grunt copy:bootstrap-fonts --project=' + this.slugname, function (err) {
                    if (err) {
                        this.log.error('Error: Grunt "copy:bootstrap-fonts" task.');
                        this.abort = true;
                    }
                    done();
                }.bind(this));
            }

            var done = this.async();
            exec('grunt default --project=' + this.slugname, function (err) {
                if (err) {
                    this.log.error('Error: Grunt "default" task.');
                    this.abort = true;
                }
                done();
            }.bind(this));

            var done = this.async();
            exec('grunt clean-workspace', function (err) {
                if (err) {
                    this.log.error('Error: Grunt "clean-workspace" task.');
                    this.abort = true;
                }
                done();
                console.log('Grunt tasks completed.');
            }.bind(this));
        });
    },

    initializing: function () {
        generatorRoot = this.templatePath('../../');
        templatePath = this.templatePath();

        var done = this.async();
        updateNotifier({
            pkg: pkg,
            callback: function (err, update) {
                if (err) {
                    console.log(err);
                }
                else if (compareVersion(update.latest, update.current) == 1) {
                    var fill = function (str, count) {
                        return Array(count + 1).join(str);
                    };

                    var line1 = ' Update available: ' + chalk.green.bold(update.latest) + chalk.dim(' (current: ' + update.current + ')') + ' ',
                        line2 = ' Run ' + chalk.magenta('npm update -g ' + pkg.name) + ' to update. ',
                        contentWidth = Math.max(stringLength(line1), stringLength(line2)),
                        line1rest = contentWidth - stringLength(line1),
                        line2rest = contentWidth - stringLength(line2),
                        top = chalk.yellow('┌' + fill('─', contentWidth) + '┐'),
                        bottom = chalk.yellow('└' + fill('─', contentWidth) + '┘'),
                        side = chalk.yellow('│'),
                        updateMessage = '\n\n' + top + '\n' + side + line1 + fill(' ', line1rest) + side + '\n' + side + line2 + fill(' ', line2rest) + side + '\n' + bottom + '\n';

                    console.log(updateMessage);
                }

                done();
            }
        })
    },

    prompting: function () {
        var done = this.async();

        var welcomeMsg = '\n' +
          '+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+\n' +
          '|F|r|e|e|K|e|r|n|e|l|J|S| |G|e|n|e|r|a|t|o|r|\n' +
          '+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+\n' +
          '\n'

        console.log(welcomeMsg);

        var prompts = [{
            when: function (response) {
                if (getDirectories(templatePath).length > 1)
                    return true

                return false
            },
            type: 'list',
            name: 'template',
            message: 'Select a template',
            choices: getDirectories(templatePath),
            default: 'freekerneljs-basic-app-md'
        }, {
            when: function (response) {
                return response.template === 'freekerneljs-basic-app';
            },
            type: 'checkbox',
            name: 'modules',
            message: 'Which packages would you like to include?',
            choices: [{
                value: 'cookiesModule',
                name: 'angular-cookies',
                checked: false
            }, {
                value: 'resourceModule',
                name: 'angular-resource',
                checked: false
            }, {
                value: 'messagesModule',
                name: 'angular-messages',
                checked: false
            }, {
                value: 'sanitizeModule',
                name: 'angular-sanitize',
                checked: false
            }, {
                value: 'touchModule',
                name: 'angular-touch',
                checked: false
            }]
        }, {
            when: function (response) {
                return response.template === 'freekerneljs-basic-app-md';
            },
            type: 'checkbox',
            name: 'modules',
            message: 'Which packages would you like to include?',
            choices: [{
                value: 'cookiesModule',
                name: 'angular-cookies',
                checked: false
            }, {
                value: 'resourceModule',
                name: 'angular-resource',
                checked: false
            }, {
                value: 'messagesModule',
                name: 'angular-messages',
                checked: false
            }, {
                value: 'sanitizeModule',
                name: 'angular-sanitize',
                checked: false
            }, {
                value: 'touchModule',
                name: 'angular-touch',
                checked: false
            }, {
                value: 'iconicFont',
                name: 'material-design-iconic-font',
                checked: false
            }]
        }, {
            type: 'input',
            name: 'name',
            message: 'Project name',
            default: function (response) {
                //var name = this.appname || path.basename(process.cwd());
                //return name.replace(/\s+/g, '-');
                return response.template + '-' + Math.floor((Math.random() * 1000000) + 1).toString();
            }
        }, {
            type: 'input',
            name: 'title',
            message: 'Title',
            default: 'FreeKernelJS App'
        }, {
            type: 'input',
            name: 'description',
            message: 'Description',
            default: 'A FreeKernelJS project'
        }, {
            type: 'input',
            name: 'version',
            message: 'Version',
            default: '1.0.0'
        }, {
            type: 'input',
            name: 'license',
            message: 'License',
            default: 'MIT'
        }, {
            type: 'input',
            name: 'repository',
            message: 'Repository',
            default: 'none'
        }, {
            type: 'input',
            name: 'author_name',
            message: 'Author name'
        }, {
            type: 'input',
            name: 'author_email',
            message: 'Author email'
        }, {
            type: 'input',
            name: 'author_url',
            message: 'Author url'
        }, {
            type: 'input',
            name: 'homepage',
            message: 'Home page'
        }];

        this.prompt(prompts, function (props) {
            this.props = props;

            if (props.template) {
                templateName = props.template;
            }

            // For easier access in the templates.
            this.slugname = _.slugify(props.name);

            var hasMod = function (mod) {
                return props.modules.indexOf(mod) !== -1;
            };

            // Common modules.
            this.angularModule = true;
            this.mocksModule = true;
            this.routeModule = true;
            this.scriptjsModule = true;
            this.angularTranslateModule = true;
            this.angularTranslateLoaderStaticFilesModule = true;
            this.cookiesModule = hasMod('cookiesModule');
            this.resourceModule = hasMod('resourceModule');
            this.messagesModule = hasMod('messagesModule');
            this.sanitizeModule = hasMod('sanitizeModule');
            this.touchModule = hasMod('touchModule');

            switch (templateName) {
                case 'freekerneljs-basic-app':
                    this.bootstrapModule = true;
                    break;
                case 'freekerneljs-basic-app-md':
                    this.materialModule = true;
                    this.iconicFont = hasMod('iconicFont');
                    break;
                default:
            }

            mkdirp(this.slugname);

            done();
        }.bind(this));
    },

    configuration: function () {
        // Workspace
        this.template(templateName + '/_package.json', 'package.json');
        this.template(templateName + '/_bower.json', 'bower.json');
        this.template('_bowerrc', '.bowerrc');
        this.copy('Gruntfile.js', 'Gruntfile.js');

        // Project folder
        this.template(templateName + '/_package.json', this.slugname + '/package.json');
        this.template(templateName + '/_bower.json', this.slugname + '/bower.json');
        this.copy('Gruntfile.js', this.slugname + '/Gruntfile.js');
        this.copy(templateName + '/gitignore', this.slugname + '/.gitignore');
        this.copy(templateName + '/bowerrc', this.slugname + '/.bowerrc');
    },

    app: function () {
        this.copy(templateName + '/app/_app.bootstrap.js', this.slugname + '/app/app.bootstrap.js');
        this.copy(templateName + '/app/_app.module.js', this.slugname + '/app/app.module.js');
        this.copy(templateName + '/app/_app.routes.js', this.slugname + '/app/app.routes.js');
        this.copy(templateName + '/app/_index.html', this.slugname + '/app/index.html');
        this.bulkDirectory(templateName + '/app/assets/images', this.slugname + '/app/assets/images');
        this.bulkDirectory(templateName + '/app/assets/scss', this.slugname + '/app/assets/scss');
        this.bulkDirectory(templateName + '/app/assets/css', this.slugname + '/app/assets/css');
        this.bulkDirectory(templateName + '/app/views', this.slugname + '/app/views');
        this.bulkDirectory(templateName + '/app/widgets', this.slugname + '/app/widgets');
        this.bulkDirectory(templateName + '/app/services', this.slugname + '/app/services');
        this.bulkDirectory(templateName + '/app/data', this.slugname + '/app/data');
    },

    writing: function () {
        this.copy(templateName + '/README.md', this.slugname + '/README.md');
        this.copy(templateName + '/README.md', 'README.md');
    },

    test: function () {
        this.bulkDirectory(templateName + '/app/_test', this.slugname + '/app/_test');
    },

    install: function () {
        this.installDependencies({
            skipInstall: this.options['skip-install']
        });
    }
});

module.exports = freekerneljsGenerator;<commit_msg>Update: check if project folder already exists<commit_after>'use strict';

var util = require('util'),
    fs = require('fs'),
    path = require('path'),
    chalk = require('chalk'),
    yeoman = require('yeoman-generator'),
    pkgName = require('pkg-name'),
    updateNotifier = require('update-notifier'),
    compareVersion = require('compare-version'),
    stringLength = require('string-length'),
    _ = require('underscore.string'),
    mkdirp = require('mkdirp'),
    childProcess = require('child_process'),
    pkg = require('../package.json'),
    templateName = 'freekerneljs-basic-app-md',
    generatorRoot = '',
    templatePath = '';

var exec = childProcess.exec;

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function (file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

var freekerneljsGenerator = yeoman.generators.Base.extend({
    constructor: function () {
        yeoman.generators.Base.apply(this, arguments);

        this.on('end', function () {
            console.log('Running Grunt tasks now...');

            if (templateName == 'freekerneljs-basic-app') {
                var done = this.async();
                exec('grunt copy:bootstrap-fonts --project=' + this.slugname, function (err) {
                    if (err) {
                        this.log.error('Error: Grunt "copy:bootstrap-fonts" task.');
                        this.abort = true;
                    }
                    done();
                }.bind(this));
            }

            var done = this.async();
            exec('grunt default --project=' + this.slugname, function (err) {
                if (err) {
                    this.log.error('Error: Grunt "default" task.');
                    this.abort = true;
                }
                done();
            }.bind(this));

            var done = this.async();
            exec('grunt clean-workspace', function (err) {
                if (err) {
                    this.log.error('Error: Grunt "clean-workspace" task.');
                    this.abort = true;
                }
                done();
                console.log('Grunt tasks completed.');
            }.bind(this));
        });
    },

    initializing: function () {
        generatorRoot = this.templatePath('../../');
        templatePath = this.templatePath();

        var done = this.async();
        updateNotifier({
            pkg: pkg,
            callback: function (err, update) {
                if (err) {
                    console.log(err);
                }
                else if (compareVersion(update.latest, update.current) == 1) {
                    var fill = function (str, count) {
                        return Array(count + 1).join(str);
                    };

                    var line1 = ' Update available: ' + chalk.green.bold(update.latest) + chalk.dim(' (current: ' + update.current + ')') + ' ',
                        line2 = ' Run ' + chalk.magenta('npm update -g ' + pkg.name) + ' to update. ',
                        contentWidth = Math.max(stringLength(line1), stringLength(line2)),
                        line1rest = contentWidth - stringLength(line1),
                        line2rest = contentWidth - stringLength(line2),
                        top = chalk.yellow('┌' + fill('─', contentWidth) + '┐'),
                        bottom = chalk.yellow('└' + fill('─', contentWidth) + '┘'),
                        side = chalk.yellow('│'),
                        updateMessage = '\n\n' + top + '\n' + side + line1 + fill(' ', line1rest) + side + '\n' + side + line2 + fill(' ', line2rest) + side + '\n' + bottom + '\n';

                    console.log(updateMessage);
                }

                done();
            }
        })
    },

    prompting: function () {
        var done = this.async();

        var welcomeMsg = '\n' +
          '+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+\n' +
          '|F|r|e|e|K|e|r|n|e|l|J|S| |G|e|n|e|r|a|t|o|r|\n' +
          '+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+\n' +
          '\n'

        console.log(welcomeMsg);

        var prompts = [{
            when: function (response) {
                if (getDirectories(templatePath).length > 1)
                    return true

                return false
            },
            type: 'list',
            name: 'template',
            message: 'Select a template',
            choices: getDirectories(templatePath),
            default: 'freekerneljs-basic-app-md'
        }, {
            when: function (response) {
                return response.template === 'freekerneljs-basic-app';
            },
            type: 'checkbox',
            name: 'modules',
            message: 'Which packages would you like to include?',
            choices: [{
                value: 'cookiesModule',
                name: 'angular-cookies',
                checked: false
            }, {
                value: 'resourceModule',
                name: 'angular-resource',
                checked: false
            }, {
                value: 'messagesModule',
                name: 'angular-messages',
                checked: false
            }, {
                value: 'sanitizeModule',
                name: 'angular-sanitize',
                checked: false
            }, {
                value: 'touchModule',
                name: 'angular-touch',
                checked: false
            }]
        }, {
            when: function (response) {
                return response.template === 'freekerneljs-basic-app-md';
            },
            type: 'checkbox',
            name: 'modules',
            message: 'Which packages would you like to include?',
            choices: [{
                value: 'cookiesModule',
                name: 'angular-cookies',
                checked: false
            }, {
                value: 'resourceModule',
                name: 'angular-resource',
                checked: false
            }, {
                value: 'messagesModule',
                name: 'angular-messages',
                checked: false
            }, {
                value: 'sanitizeModule',
                name: 'angular-sanitize',
                checked: false
            }, {
                value: 'touchModule',
                name: 'angular-touch',
                checked: false
            }, {
                value: 'iconicFont',
                name: 'material-design-iconic-font',
                checked: false
            }]
        }, {
            type: 'input',
            name: 'name',
            message: 'Project name',
            default: function (response) {
                //var name = this.appname || path.basename(process.cwd());
                //return name.replace(/\s+/g, '-');
                return response.template + '-' + Math.floor((Math.random() * 1000000) + 1).toString();
            },
            validate: function (str) {
                return fs.existsSync(str) ? 'Project name already exists!' : true;
            }
        }, {
            type: 'input',
            name: 'title',
            message: 'Title',
            default: 'FreeKernelJS App'
        }, {
            type: 'input',
            name: 'description',
            message: 'Description',
            default: 'A FreeKernelJS project'
        }, {
            type: 'input',
            name: 'version',
            message: 'Version',
            default: '1.0.0'
        }, {
            type: 'input',
            name: 'license',
            message: 'License',
            default: 'MIT'
        }, {
            type: 'input',
            name: 'repository',
            message: 'Repository',
            default: 'none'
        }, {
            type: 'input',
            name: 'author_name',
            message: 'Author name'
        }, {
            type: 'input',
            name: 'author_email',
            message: 'Author email'
        }, {
            type: 'input',
            name: 'author_url',
            message: 'Author url'
        }, {
            type: 'input',
            name: 'homepage',
            message: 'Home page'
        }];

        this.prompt(prompts, function (props) {
            this.props = props;

            if (props.template) {
                templateName = props.template;
            }

            // For easier access in the templates.
            this.slugname = _.slugify(props.name);

            var hasMod = function (mod) {
                return props.modules.indexOf(mod) !== -1;
            };

            // Common modules.
            this.angularModule = true;
            this.mocksModule = true;
            this.routeModule = true;
            this.scriptjsModule = true;
            this.angularTranslateModule = true;
            this.angularTranslateLoaderStaticFilesModule = true;
            this.cookiesModule = hasMod('cookiesModule');
            this.resourceModule = hasMod('resourceModule');
            this.messagesModule = hasMod('messagesModule');
            this.sanitizeModule = hasMod('sanitizeModule');
            this.touchModule = hasMod('touchModule');

            switch (templateName) {
                case 'freekerneljs-basic-app':
                    this.bootstrapModule = true;
                    break;
                case 'freekerneljs-basic-app-md':
                    this.materialModule = true;
                    this.iconicFont = hasMod('iconicFont');
                    break;
                default:
            }

            mkdirp(this.slugname);

            done();
        }.bind(this));
    },

    configuration: function () {
        // Workspace
        this.template(templateName + '/_package.json', 'package.json');
        this.template(templateName + '/_bower.json', 'bower.json');
        this.template('_bowerrc', '.bowerrc');
        this.copy('Gruntfile.js', 'Gruntfile.js');

        // Project folder
        this.template(templateName + '/_package.json', this.slugname + '/package.json');
        this.template(templateName + '/_bower.json', this.slugname + '/bower.json');
        this.copy('Gruntfile.js', this.slugname + '/Gruntfile.js');
        this.copy(templateName + '/gitignore', this.slugname + '/.gitignore');
        this.copy(templateName + '/bowerrc', this.slugname + '/.bowerrc');
    },

    app: function () {
        this.copy(templateName + '/app/_app.bootstrap.js', this.slugname + '/app/app.bootstrap.js');
        this.copy(templateName + '/app/_app.module.js', this.slugname + '/app/app.module.js');
        this.copy(templateName + '/app/_app.routes.js', this.slugname + '/app/app.routes.js');
        this.copy(templateName + '/app/_index.html', this.slugname + '/app/index.html');
        this.bulkDirectory(templateName + '/app/assets/images', this.slugname + '/app/assets/images');
        this.bulkDirectory(templateName + '/app/assets/scss', this.slugname + '/app/assets/scss');
        this.bulkDirectory(templateName + '/app/assets/css', this.slugname + '/app/assets/css');
        this.bulkDirectory(templateName + '/app/views', this.slugname + '/app/views');
        this.bulkDirectory(templateName + '/app/widgets', this.slugname + '/app/widgets');
        this.bulkDirectory(templateName + '/app/services', this.slugname + '/app/services');
        this.bulkDirectory(templateName + '/app/data', this.slugname + '/app/data');
    },

    writing: function () {
        this.copy(templateName + '/README.md', this.slugname + '/README.md');
        this.copy(templateName + '/README.md', 'README.md');
    },

    test: function () {
        this.bulkDirectory(templateName + '/app/_test', this.slugname + '/app/_test');
    },

    install: function () {
        this.installDependencies({
            skipInstall: this.options['skip-install']
        });
    }
});

module.exports = freekerneljsGenerator;<|endoftext|>