<commit_before>// const logger = require('winston')
const lists = require('../model/lists')
const listItems = require('../model/listitems')
const modelConstants = require('../model/modelconstants')
const smsProcessor = require('../src/smsprocessor')
const phrases = require('../src/phrases')
const logger = require('winston')
const familyMembers = require('../model/familymembers')
const jwt = require('jsonwebtoken')
const families = require('../model/families')
const snakeKeys = require('snakecase-keys-object')

const errorMessages = {
  notFound: { errorCode: 1001, errorMessage: 'not found' },
  alreadyExists: { errorCode: 1002, errorMessage: 'already exists' },
  generalError: { errorCode: 1000, errorMessage: 'error' },
  invalidPhoneNumber: { errorCode: 1003, errorMessage: 'invalid phone number' },
  invalidVerificationNumber: { errorCode: 1004, errorMessage: 'invalid verification number' },
  tokenRequired: { errorCode: 1005, errorMessage: 'token required' },
  tokenVerificationFailure: { errorCode: 1006, errorMessage: 'token verification failed' },
  expiredVerificationNumber: { errorCode: 1007, errorMessage: 'expired verification number' },
  memberRetrivalFailure: { errorCode: 1008, errorMessage: 'could not retrieve member' }
}

const issuer = 'https://packhack.us'

const getLists = (request, response) => {
  lists.findAllPromise({familyId: 2})
    .then(result => {
      const listNames = result.lists.map(list => {
        return {name: list.listKey}
      })
      response.json(listNames)
    }, result => {
      response.status(404).send(errorMessages.generalError)
    }
  )
}

const addList = (request, response) => {
  let list = request.body.name
  lists.saveNewPromise({list, familyId: 2})
    .then(result => {
      response.json({name: list})
    }, result => {
      if (result.errorMessage === modelConstants.errorTypes.duplicateList) {
        response.status(409).send(errorMessages.alreadyExists)
      } else {
        response.status(404).send(errorMessages.generalError)
      }
    }
  )
}

const deleteList = (request, response) => {
  let list = request.params.list
  lists.deletePromise({list, familyId: 2})
    .then(result => {
      response.json({name: list})
    }, result => {
      if (result.errorMessage === modelConstants.errorTypes.listNotFound) {
        response.status(404).send(errorMessages.notFound)
      } else {
        response.status(404).send(errorMessages.generalError)
      }
    }
  )
}

const getListItems = (request, response) => {
  listItems.findPromise({list: request.params.list, familyId: 2})
    .then(result => {
      const listItemNames = result.listItems.map(listItem => {
        return {name: listItem.listItemName}
      })
      response.json(listItemNames)
    }, result => {
      response.status(404).send(errorMessages.generalError)
    }
  )
}

const addListItem = (request, response) => {
  let listItemName = request.body.name
  // TODO: deal with duplicates
  listItems.saveNewPromise({list: request.params.list, familyId: 2, listItemName: listItemName})
    .then(result => {
      response.json({name: listItemName})
    }, result => {
      if (result.errorMessage === modelConstants.errorTypes.duplicateListItem) {
        response.status(409).send(errorMessages.alreadyExists)
      } else {
        response.status(404).send(errorMessages.generalError)
      }
    }
  )
}

// Can handle delete and clear (delete all)
const deleteListItem = (request, response) => {
  let listItemName = request.params.item
  listItems.deletePromise({list: request.params.list, familyId: 2}, listItemName)
    .then(result => {
      response.json({name: listItemName})
    }, result => {
      if (result.errorMessage === modelConstants.errorTypes.listItemNotFound) {
        response.status(404).send(errorMessages.notFound)
      } else {
        response.status(404).send(errorMessages.generalError)
      }
    })
}

// This will first check if phone already already exists
// If so, will just update the verification Number.
// If not, will create new family + member.
const authenticatePhone = (request, response) => {
  logger.log('info', '----authenticatePhone start', request.body)
  const phoneNumber = request.body.phone
  if (!phoneNumber || smsProcessor.validatePhoneNumber(phoneNumber) === false) {
    response.status(404).send(errorMessages.invalidPhoneNumber)
    return
  }
  const newVerificationNumber = Math.floor(Math.random() * 90000) + 10000
  const text = newVerificationNumber + phrases.verification

  // Verification expiry - now + 5 minutes
  let expiryDate = new Date()
  expiryDate.setMinutes(expiryDate.getMinutes() + 5)
  expiryDate = new Date(expiryDate)

  let data = {
    fromPhoneNumber: phoneNumber
  }

  smsProcessor.sendSmsPromise({}, phoneNumber, text)
    .then(result => {
      logger.log('info', '----authenticatePhone SMS success')
      return data
    })
    .then(familyMembers.retrievePersonFromPhoneNumberPromise)
    .catch(data => {
      if (data.errorMessage === modelConstants.errorTypes.personNotFound) {
        return data
      } else {
        throw data
      }
    })
    .then(data => {
      data.verificationNumber = newVerificationNumber
      data.verificationNumberExpiry = expiryDate
      if (data.errorMessage === modelConstants.errorTypes.personNotFound) {
        logger.log('info', '----authenticatePhone save new family + member')
        return families.saveNewFamilyPromise(data)
          .then(familyMembers.saveNewFamilyMemberPromise)
      } else {
        logger.log('info', '----authenticatePhone update')
        return familyMembers.updateFamilyMemberVerificationNumberPromise(data)
      }
    })
    .then(data => {
      logger.log('info', '----authenticatePhone update success')
      response.json({'phone': phoneNumber})
    })
    .catch(data => {
      logger.log('info', '----authenticatePhone Failure', data)
      response.status(404).send(errorMessages.invalidPhoneNumber)
    })
}

// verify phone
const verifyPhone = (request, response) => {
  const verificationNumber = request.query.verification_number
  logger.log('info', '----verification requested-X ' + request.query.verification_number)
  const phoneNumber = request.query.phone
  let data = {
    fromPhoneNumber: phoneNumber
  }
  logger.log('info', '----verification requested', request.query)
  if (!verificationNumber || verificationNumber.length !== 5) {
    response.status(404).send(errorMessages.invalidVerificationNumber)
    return
  } else if (!phoneNumber || smsProcessor.validatePhoneNumber(phoneNumber) === false) {
    response.status(404).send(errorMessages.invalidPhoneNumber)
    return
  }
  familyMembers.retrievePersonFromPhoneNumberPromise(data)
    .catch(data => {
      data.errorMessage = errorMessages.invalidPhoneNumber
      throw data
    })
    .then(data => {
      if (data.verificationNumber !== parseInt(verificationNumber) && verificationNumber !== '32272') {
        logger.log('info', '----verification no match', data.verificationNumber)
        data.errorMessage = errorMessages.invalidVerificationNumber
        throw data
      }
      if (new Date(data.verificationNumberExpiry) < new Date()) {
        logger.log('info', '----verification expired', data.verificationNumberExpiry)
        data.errorMessage = errorMessages.expiredVerificationNumber
        throw data
      }
      const payload = {phone: phoneNumber}
      const options = {expiresIn: '1y', issuer: issuer}
      const secret = process.env.JWT_SECRET
      const token = jwt.sign(payload, secret, options)
      logger.log('debug', '----verification token', token)
      response.json({'token': token})
    })
    .catch(data => {
      response.status(404).send(data.errorMessage)
    })
}

const validateToken = (request, response, next) => {
  const authorizationHeaader = request.headers.authorization
  let result
  if (authorizationHeaader) {
    const token = request.headers.authorization
    const options = {
      expiresIn: '1y',
      issuer: issuer
    }
    try {
      result = jwt.verify(token, process.env.JWT_SECRET, options)
      request.decoded = result
      // We call next to pass execution to the subsequent middleware
      next()
    } catch (err) {
      logger.log('info', '----verification token invalid', err)
      response.status(401).send(errorMessages.tokenVerificationFailure)
    }
  } else {
    logger.log('info', '----verification token required')
    response.status(401).send(errorMessages.tokenRequired)
  }
}

const getFamilyMemberMe = (request, response) => {
  const phoneNumber = request.decoded.phone
  let data = {
    fromPhoneNumber: phoneNumber
  }
  familyMembers.retrieveForExternalPersonFromPhoneNumberPromise(data)
    .then(data => {
      // If this an orphan, it's not an error
      // If it has a family, retrieve family description.
      if (data.familyId == null) {
        response.json(snakeKeys(data))
      } else {
        return families.retrieveFamilyPromise(data)
          .then(data => {
            response.json(snakeKeys(data))
          })
          .catch(data => {
            logger.log('info', '----getFamilyMemberMe retrieveFamilyPromise Failure', data)
            response.status(404).send(errorMessages.memberRetrivalFailure)
          })
      }
    })
    .catch(data => {
      logger.log('info', '----getFamilyMemberMe Failure', data)
      response.status(404).send(errorMessages.memberRetrivalFailure)
    })
}

const patchFamilyMemberMe = (request, response) => {
  let updateData = {
    name: request.body.name,
    description: request.body.description,
    familyId: request.body.familyId,
    timeZone: request.body.timeZone
  }
  const phoneNumber = request.decoded.phone
  let keyData = {
    fromPhoneNumber: phoneNumber
  }
  logger.log('info', '----patchFamilyMemberMe updateData', updateData)
  familyMembers.retrieveForExternalPersonFromPhoneNumberPromise(keyData)
    .then(data => {
      logger.log('info', '----patchFamilyMemberMe userId', data.userId)
      return familyMembers.updateFamilyMemberPromise(data.userId, updateData)
        .then(data => {
          response.json(snakeKeys(data))
        })
        .catch(data => {
          logger.log('info', '----patchFamilyMemberMe patch Failure', data)
          response.status(404).send(errorMessages.memberRetrivalFailure)
        })
    })
    .catch(data => {
      logger.log('info', '----patchFamilyMemberMe get Failure', data)
      response.status(404).send(errorMessages.memberRetrivalFailure)
    })
}

module.exports = {
  getLists,
  addList,
  deleteList,
  getListItems,
  addListItem,
  deleteListItem,
  authenticatePhone,
  verifyPhone,
  validateToken,
  getFamilyMemberMe,
  patchFamilyMemberMe
}
<commit_msg>patch updated<commit_after>// const logger = require('winston')
const lists = require('../model/lists')
const listItems = require('../model/listitems')
const modelConstants = require('../model/modelconstants')
const smsProcessor = require('../src/smsprocessor')
const phrases = require('../src/phrases')
const logger = require('winston')
const familyMembers = require('../model/familymembers')
const jwt = require('jsonwebtoken')
const families = require('../model/families')
const snakeKeys = require('snakecase-keys-object')

const errorMessages = {
  notFound: { errorCode: 1001, errorMessage: 'not found' },
  alreadyExists: { errorCode: 1002, errorMessage: 'already exists' },
  generalError: { errorCode: 1000, errorMessage: 'error' },
  invalidPhoneNumber: { errorCode: 1003, errorMessage: 'invalid phone number' },
  invalidVerificationNumber: { errorCode: 1004, errorMessage: 'invalid verification number' },
  tokenRequired: { errorCode: 1005, errorMessage: 'token required' },
  tokenVerificationFailure: { errorCode: 1006, errorMessage: 'token verification failed' },
  expiredVerificationNumber: { errorCode: 1007, errorMessage: 'expired verification number' },
  memberRetrivalFailure: { errorCode: 1008, errorMessage: 'could not retrieve member' }
}

const issuer = 'https://packhack.us'

const getLists = (request, response) => {
  lists.findAllPromise({familyId: 2})
    .then(result => {
      const listNames = result.lists.map(list => {
        return {name: list.listKey}
      })
      response.json(listNames)
    }, result => {
      response.status(404).send(errorMessages.generalError)
    }
  )
}

const addList = (request, response) => {
  let list = request.body.name
  lists.saveNewPromise({list, familyId: 2})
    .then(result => {
      response.json({name: list})
    }, result => {
      if (result.errorMessage === modelConstants.errorTypes.duplicateList) {
        response.status(409).send(errorMessages.alreadyExists)
      } else {
        response.status(404).send(errorMessages.generalError)
      }
    }
  )
}

const deleteList = (request, response) => {
  let list = request.params.list
  lists.deletePromise({list, familyId: 2})
    .then(result => {
      response.json({name: list})
    }, result => {
      if (result.errorMessage === modelConstants.errorTypes.listNotFound) {
        response.status(404).send(errorMessages.notFound)
      } else {
        response.status(404).send(errorMessages.generalError)
      }
    }
  )
}

const getListItems = (request, response) => {
  listItems.findPromise({list: request.params.list, familyId: 2})
    .then(result => {
      const listItemNames = result.listItems.map(listItem => {
        return {name: listItem.listItemName}
      })
      response.json(listItemNames)
    }, result => {
      response.status(404).send(errorMessages.generalError)
    }
  )
}

const addListItem = (request, response) => {
  let listItemName = request.body.name
  // TODO: deal with duplicates
  listItems.saveNewPromise({list: request.params.list, familyId: 2, listItemName: listItemName})
    .then(result => {
      response.json({name: listItemName})
    }, result => {
      if (result.errorMessage === modelConstants.errorTypes.duplicateListItem) {
        response.status(409).send(errorMessages.alreadyExists)
      } else {
        response.status(404).send(errorMessages.generalError)
      }
    }
  )
}

// Can handle delete and clear (delete all)
const deleteListItem = (request, response) => {
  let listItemName = request.params.item
  listItems.deletePromise({list: request.params.list, familyId: 2}, listItemName)
    .then(result => {
      response.json({name: listItemName})
    }, result => {
      if (result.errorMessage === modelConstants.errorTypes.listItemNotFound) {
        response.status(404).send(errorMessages.notFound)
      } else {
        response.status(404).send(errorMessages.generalError)
      }
    })
}

// This will first check if phone already already exists
// If so, will just update the verification Number.
// If not, will create new family + member.
const authenticatePhone = (request, response) => {
  logger.log('info', '----authenticatePhone start', request.body)
  const phoneNumber = request.body.phone
  if (!phoneNumber || smsProcessor.validatePhoneNumber(phoneNumber) === false) {
    response.status(404).send(errorMessages.invalidPhoneNumber)
    return
  }
  const newVerificationNumber = Math.floor(Math.random() * 90000) + 10000
  const text = newVerificationNumber + phrases.verification

  // Verification expiry - now + 5 minutes
  let expiryDate = new Date()
  expiryDate.setMinutes(expiryDate.getMinutes() + 5)
  expiryDate = new Date(expiryDate)

  let data = {
    fromPhoneNumber: phoneNumber
  }

  smsProcessor.sendSmsPromise({}, phoneNumber, text)
    .then(result => {
      logger.log('info', '----authenticatePhone SMS success')
      return data
    })
    .then(familyMembers.retrievePersonFromPhoneNumberPromise)
    .catch(data => {
      if (data.errorMessage === modelConstants.errorTypes.personNotFound) {
        return data
      } else {
        throw data
      }
    })
    .then(data => {
      data.verificationNumber = newVerificationNumber
      data.verificationNumberExpiry = expiryDate
      if (data.errorMessage === modelConstants.errorTypes.personNotFound) {
        logger.log('info', '----authenticatePhone save new family + member')
        return families.saveNewFamilyPromise(data)
          .then(familyMembers.saveNewFamilyMemberPromise)
      } else {
        logger.log('info', '----authenticatePhone update')
        return familyMembers.updateFamilyMemberVerificationNumberPromise(data)
      }
    })
    .then(data => {
      logger.log('info', '----authenticatePhone update success')
      response.json({'phone': phoneNumber})
    })
    .catch(data => {
      logger.log('info', '----authenticatePhone Failure', data)
      response.status(404).send(errorMessages.invalidPhoneNumber)
    })
}

// verify phone
const verifyPhone = (request, response) => {
  const verificationNumber = request.query.verification_number
  logger.log('info', '----verification requested-X ' + request.query.verification_number)
  const phoneNumber = request.query.phone
  let data = {
    fromPhoneNumber: phoneNumber
  }
  logger.log('info', '----verification requested', request.query)
  if (!verificationNumber || verificationNumber.length !== 5) {
    response.status(404).send(errorMessages.invalidVerificationNumber)
    return
  } else if (!phoneNumber || smsProcessor.validatePhoneNumber(phoneNumber) === false) {
    response.status(404).send(errorMessages.invalidPhoneNumber)
    return
  }
  familyMembers.retrievePersonFromPhoneNumberPromise(data)
    .catch(data => {
      data.errorMessage = errorMessages.invalidPhoneNumber
      throw data
    })
    .then(data => {
      if (data.verificationNumber !== parseInt(verificationNumber) && verificationNumber !== '32272') {
        logger.log('info', '----verification no match', data.verificationNumber)
        data.errorMessage = errorMessages.invalidVerificationNumber
        throw data
      }
      if (new Date(data.verificationNumberExpiry) < new Date()) {
        logger.log('info', '----verification expired', data.verificationNumberExpiry)
        data.errorMessage = errorMessages.expiredVerificationNumber
        throw data
      }
      const payload = {phone: phoneNumber}
      const options = {expiresIn: '1y', issuer: issuer}
      const secret = process.env.JWT_SECRET
      const token = jwt.sign(payload, secret, options)
      logger.log('debug', '----verification token', token)
      response.json({'token': token})
    })
    .catch(data => {
      response.status(404).send(data.errorMessage)
    })
}

const validateToken = (request, response, next) => {
  const authorizationHeaader = request.headers.authorization
  let result
  if (authorizationHeaader) {
    const token = request.headers.authorization
    const options = {
      expiresIn: '1y',
      issuer: issuer
    }
    try {
      result = jwt.verify(token, process.env.JWT_SECRET, options)
      request.decoded = result
      // We call next to pass execution to the subsequent middleware
      next()
    } catch (err) {
      logger.log('info', '----verification token invalid', err)
      response.status(401).send(errorMessages.tokenVerificationFailure)
    }
  } else {
    logger.log('info', '----verification token required')
    response.status(401).send(errorMessages.tokenRequired)
  }
}

const getFamilyMemberMe = (request, response) => {
  const phoneNumber = request.decoded.phone
  let data = {
    fromPhoneNumber: phoneNumber
  }
  familyMembers.retrieveForExternalPersonFromPhoneNumberPromise(data)
    .then(data => {
      // If this an orphan, it's not an error
      // If it has a family, retrieve family description.
      if (data.familyId == null) {
        response.json(snakeKeys(data))
      } else {
        return families.retrieveFamilyPromise(data)
          .then(data => {
            response.json(snakeKeys(data))
          })
          .catch(data => {
            logger.log('info', '----getFamilyMemberMe retrieveFamilyPromise Failure', data)
            response.status(404).send(errorMessages.memberRetrivalFailure)
          })
      }
    })
    .catch(data => {
      logger.log('info', '----getFamilyMemberMe Failure', data)
      response.status(404).send(errorMessages.memberRetrivalFailure)
    })
}

const patchFamilyMemberMe = (request, response) => {
  let updateData = {
    name: request.body.name,
    description: request.body.description,
    familyId: request.body.familyId,
    timeZone: request.body.timeZone
  }
  let keyData = {
    fromPhoneNumber: request.decoded.phone
  }
  logger.log('info', '----patchFamilyMemberMe updateData', updateData)
  logger.log('info', '----patchFamilyMemberMe keyData', keyData)
  familyMembers.retrieveForExternalPersonFromPhoneNumberPromise(keyData)
    .then(data => {
      logger.log('info', '----patchFamilyMemberMe userId', data.userId)
      return familyMembers.updateFamilyMemberPromise(data.userId, updateData)
        .then(data => {
          response.json(snakeKeys(data))
        })
        .catch(data => {
          logger.log('info', '----patchFamilyMemberMe patch Failure', data)
          response.status(404).send(errorMessages.memberRetrivalFailure)
        })
    })
    .catch(data => {
      logger.log('info', '----patchFamilyMemberMe get Failure', data)
      response.status(404).send(errorMessages.memberRetrivalFailure)
    })
}

module.exports = {
  getLists,
  addList,
  deleteList,
  getListItems,
  addListItem,
  deleteListItem,
  authenticatePhone,
  verifyPhone,
  validateToken,
  getFamilyMemberMe,
  patchFamilyMemberMe
}
<|endoftext|>


<commit_before>var DiscordClient = require('discord.io');
var bot = new DiscordClient({
    token: "...",
    autorun: true
});

bot.on('ready', function(rawEvent) {
    require('fs').writeFileSync('./bot.json', JSON.stringify(bot,null,'\t'));
    console.log(bot.username + " - (" + bot.id + ")" + "Token: " + "[[" + bot.internals.token + "]]");
    bot.setPresence({game: "Doom"});
     // Reminds the channel to
    function remindChannel() {
        bot.sendMessage({
            to: "102910652447752192",   // test-area channel
            message: "To see my commands type: *!Commands*",
            typing: true
        });
    }
    setInterval(remindChannel, 7200000); // @ every 2 hours
});

bot.on('presence', function(user, userID, status, gameName, rawEvent) {

 });

bot.on('message', function(user, userID, channelID, message, rawEvent) {

    if(message === "!me"){
        bot.sendMessage({
            to: channelID,
            message: "```\nUsername: " + JSON.stringify(bot.servers["102910652447752192"].members[userID].user.username) +"\nID: "+bot.servers["102910652447752192"].members[userID].user.id +"\nAvatar: "+bot.servers["102910652447752192"].members[userID].user.avatar+"```"
        });
    }

    if(message.toLowerCase()==="!listmembers"){
        var listMembers = [];
        for(var i in bot.servers["102910652447752192"].members){
            listMembers.push(bot.servers["102910652447752192"].members[i].user.username);
           }

        bot.sendMessage({
            to: channelID,
            message: "```" + listMembers + "```"
            });
    }
    // -------------------------------------------
    if(message.toLowerCase() === "!commands") {
    bot.sendMessage({
        to: channelID,
         message: "<@" + userID + ">"+ "```Akephalos\nHere are my commands:\n\n1. @mentions: gives you a rude statement.\n2. !Sample text: Outputs Sample Text Youtube video.\n3. !ping: See ping status\n4. Peace or Godnight: Saying peace or goodnight will result in Akephalos also saying goodbye.\n5. No invite?: Results in saying that, that's cold.\n6. !rekt: Display's rekt meme gif.\n7. 1V1: Bot will fight you.\n8. !Yes: Creepy Jack gif\n9. Why?: Go ahead ask me why.\n10. !doit: JUST DO IT!```"
        });
    }

    if(message.toLowerCase() === "!yes") {
        bot.sendMessage({
            to: channelID,
            message:"https://media.giphy.com/media/3rgXBOmTlzyFCURutG/giphy.gif"
        });
       }

    if ((message.toLowerCase() === "!delete") && user === "Mesmaroth") {
         bot.getMessages({
            channel: channelID,
            limit: 5 //If 'limit' isn't added, it defaults to 50, the Discord default, 100 is the max.
        }, function(messageArr) {
            for(var i = 0; i < messageArr.length; i++)
            {
                var msgID = messageArr[i].id;
                bot.deleteMessage({
                    channel: channelID,
                    messageID: msgID
                })
            }
        });
    }
    else if((message.toLowerCase() === "!delete") && user !== "Mesmaroth") {
        bot.sendMessage({
            to: channelID,
            message: "<@" + userID + ">" + " You are not authorized to use this command.",
            typing: true
        });
    }

// Delete Bot messages only.
if(message.toLowerCase() === "!delmsgakephalos" && user === "Mesmaroth"){
    bot.getMessages({
        channel: channelID,
        limit: 100
    }, function(messageArr){
        for(var i = 0; i < messageArr.length; i++) {
            if(messageArr[i].author.username === 'Akephalos(Bot)') {
                bot.deleteMessage({
                    channel: channelID,
                    messageID: messageArr[i].id
                });
            }
        }
    });
}
    // Delete Mesmaroth messages only
    if(message.toLowerCase() === "!delmsgmes" && user === "Mesmaroth") {
        bot.getMessages({
            channel: channelID,
            limit: 100
        }, function(messageArr){
            var msgsDeleted = 0;
            for(var i = 0; i < messageArr.length; i++){
                if(messageArr[i].author.username === 'Mesmaroth'){
                    bot.deleteMessage({
                        channel: channelID,
                        messageID: messageArr[i].id
                    });
                    msgsDeleted+=1;
                }
            }
            console.log("Deleted "+ (msgsDeleted-1) + " messages for " + user);
        });
    }

// Delete gun messages only
if(message.toLowerCase() === "$sudo rm gun -r" && user === "Gun") {
    bot.getMessages({
        channel: channelID,
        limit: 100
    }, function(messageArr){
        var msgsDeleted = 0;
        for(var i = 0; i < messageArr.length; i++){
            if(messageArr[i].author.username === 'Gun'){
                bot.deleteMessage({
                    channel: channelID,
                    messageID: messageArr[i].id
                });
                msgsDeleted+=1;
            }
        }
        console.log("Deleted "+ (msgsDeleted-1) + " messages for " + user); // not including command request
    });
}
else if(message.toLowerCase() === "$sudo rm gun -r" && user !== "Gun") {
    bot.sendMessage({
        to: channelID,
        message: "<@"+userID + ">" + "You are not authorized to do that.",
        typing: true
    });
}

if(message === "!getMsgs") {
    bot.getMessages({
        channel: channelID,
        limit: 50
    }, function(messageArr){
        console.log(messageArr);
    });
}
if(message=== "!rawEvent")
{
    console.log(rawEvent);
}
// --------------------------------------

    // check to see if bot is mentioned
    function mentionedMe(rawEvent) {
        var mentionArr = rawEvent.d.mentions;
        for (var i=0; i<mentionArr.length; i++) {
            if (mentionArr[i].id === bot.id) {
                return true;
            }
        }
        return false;
    }

    // if bot is mentioned with having FU;
    if ( mentionedMe(rawEvent) && (message.search("fuck you") > 0 || message.search("FUCK YOU")>0)  ) {
        bot.sendMessage({
            to: channelID,
            message: "<@" + userID + ">"+" Why you mad!",
            typing: true
        });
    }

    if ( message.toLowerCase() === "fuck you") {
        bot.sendMessage({
            to: channelID,
            message: "http://4.bp.blogspot.com/-XWNXDprHibk/UYxniZERK6I/AAAAAAAAW1Y/RyvRcq_Q_cc/s640/vlcsnap-2011-11-10-19h19m39s159.png"
        });

    }

    //sample text
    if(message.toLowerCase() === "!sample text" || message.toLowerCase() === "!sp") {
        bot.sendMessage({
            to: channelID,
            message: "SampleText.MP4?\nhttps://www.youtube.com/watch?v=Tlr1L8FHp2U",
        });
    }

    //check ping
    if(message.toLowerCase() === "!ping") {
        bot.sendMessage({
            to: channelID,
            message: "<@" + userID + ">" + " Ping deez nuts in your mouth",
            typing: true
        });
    }

    // Say goodye
    if(message.toLowerCase()==="peace" || message.toLowerCase()==="goodnight") {
        bot.sendMessage({
            to: channelID,
            message: "Bye! :)",
            typing: true

        });
    }

    // for when somone didn't invite someone
    if(message.toLowerCase() === "no invite?") {
        bot.sendMessage({
            to: channelID,
            message:"That's cold blooded right there man.",
            typing: true
        });
    }

    // For when someone says rekt
    if(message.toLowerCase() === "!rekt" || message.toLowerCase() === "rekt") {
        bot.sendMessage({
            to: channelID,
            message: "https://giphy.com/gifs/rekt-vSR0fhtT5A9by"
        });
    }

    // For when someone says !1v1
    if (message.toLowerCase()=== "1v1" || message.toLowerCase() === "!1v1") {
        bot.sendMessage({
            to: channelID,
            message: "<@" + userID + ">"+" My nigga! Let's go then bitch!!",
            typing: true
        });
    }

    // for when someone says why?
    if (message.toLowerCase() === "why?") {
        bot.sendMessage({
            to: channelID,
            message: "<@" + userID + ">" + " Because fuck you! That's why!",
            typing: true
        });
    }
    if(message.toLowerCase() === "!doit") {
        bot.sendMessage({
            to: channelID,
            message: "https://media.giphy.com/media/TCaq4FekwSV5m/giphy.gif"
        });
    }

});

<commit_msg>Added colors to CLI, added function to output any message deletion request by members and date<commit_after>var DiscordClient = require('discord.io');
var colors = require('colors');
var bot = new DiscordClient({
    token: "{TOKEN}",
    autorun: true
});

bot.on('ready', function(rawEvent) {
    console.log(bot.username.magenta + " - (" + bot.id.cyan + ")" + " Token: " + "[[" + bot.internals.token.green + "]]");
    bot.setPresence({game: "Doom"});
     // Reminds the channel to
    setInterval(function(){
        bot.sendMessage({
            to: "102910652447752192",   // test-area channel
            message: "To see my commands type: *!Commands*",
            typing: true
        });
    },10800000); // @ every 3 hours
});

bot.on('presence', function(user, userID, status, gameName, rawEvent) {

 });

function getDate(){       // month-day-year
    var d = new Date();
    return d.toDateString().green;
}

function consoleMsgDel(user,msgDel){         // outputs any message deletion to console
    return console.log("Deleted "+ (msgDel-1) + " messages for " + user.cyan + " at "+ getDate().green );
}

bot.on('message', function(user, userID, channelID, message, rawEvent) {

    if(message.toLowerCase() === "!me"){
        bot.sendMessage({
            to: channelID,
            message: "```\nUsername: " + JSON.stringify(bot.servers["102910652447752192"].members[userID].user.username) +"\nID: "+bot.servers["102910652447752192"].members[userID].user.id +"\nAvatar: "+bot.servers["102910652447752192"].members[userID].user.avatar+"```"
        });
    }

    if(message.toLowerCase()==="!listmembers"){
        var listMembers = [];
        for(var i in bot.servers["102910652447752192"].members){
            listMembers.push(bot.servers["102910652447752192"].members[i].user.username);
           }

        bot.sendMessage({
            to: channelID,
            message: "```" + listMembers + "```"
            });
    }

    // -------------------------------------------
    if(message.toLowerCase() === "!commands") {
    bot.sendMessage({
        to: channelID,
         message: "<@" + userID + ">"+ "```Akephalos\nHere are my commands:\n\n1. @mentions: gives you a rude statement.\n2. !Sample text: Outputs Sample Text Youtube video.\n3. !ping: See ping status\n4. Peace or Godnight: Saying peace or goodnight will result in Akephalos also saying goodbye.\n5. No invite?: Results in saying that, that's cold.\n6. !rekt: Display's rekt meme gif.\n7. 1V1: Bot will fight you.\n8. !Yes: Creepy Jack gif\n9. Why?: Go ahead ask me why.\n10. !doit: JUST DO IT!```"
        });
    }

    if(message.toLowerCase() === "!yes") {
        bot.sendMessage({
            to: channelID,
            message:"https://media.giphy.com/media/3rgXBOmTlzyFCURutG/giphy.gif"
        });
       }

    if ((message.toLowerCase() === "!delete") && user === "Mesmaroth") {
         bot.getMessages({
            channel: channelID,
            limit: 5 //If 'limit' isn't added, it defaults to 50, the Discord default, 100 is the max.
        }, function(messageArr) {
            for(var i = 0; i < messageArr.length; i++)
            {
                var msgID = messageArr[i].id;
                bot.deleteMessage({
                    channel: channelID,
                    messageID: msgID
                })
            }
        });
    }
    else if((message.toLowerCase() === "!delete") && user !== "Mesmaroth") {
        bot.sendMessage({
            to: channelID,
            message: "<@" + userID + ">" + " You are not authorized to use this command.",
            typing: true
        });
    }

// Delete Bot messages only.
    if(message.toLowerCase() === "!delmsgakephalos" && user === "Mesmaroth"){
        bot.getMessages({
            channel: channelID,
            limit: 100
        }, function(messageArr){
            var msgsDel = 0;
            for(var i = 0; i < messageArr.length; i++) {
                if(messageArr[i].author.username === 'Akephalos(Bot)') {
                    bot.deleteMessage({
                        channel: channelID,
                        messageID: messageArr[i].id
                    });
                    msgsDel+=1;
                }
            }
            consoleMsgDel(bot.username, msgsDel);
        });
    }
    // Delete Mesmaroth messages only
    if(message.toLowerCase() === "!delmsgmes" && user === "Mesmaroth") {
        bot.getMessages({
            channel: channelID,
            limit: 100
        }, function(messageArr){
            var msgsDel = 0;
            for(var i = 0; i < messageArr.length; i++){
                if(messageArr[i].author.username === 'Mesmaroth'){
                    bot.deleteMessage({
                        channel: channelID,
                        messageID: messageArr[i].id
                    });
                    msgsDel+=1;
                }
            }
            consoleMsgDel(user,msgsDel);
        });
    }
    else if(message.toLowerCase() === "!delmsgmes" && user !== "Mesmaroth"){
        bot.sendMessage({
            to: channelID,
            message: "<@"+userID + ">" + "You are not authorized to do that."
        });
    }

// Delete gun messages only
    if(message.toLowerCase() === "$sudo rm gun -r" && user === "Gun") {
        bot.getMessages({
            channel: channelID,
            limit: 100
        }, function(messageArr){
            var msgsDel = 0;
            for(var i = 0; i < messageArr.length; i++){
                if(messageArr[i].author.username === 'Gun'){
                    bot.deleteMessage({
                        channel: channelID,
                        messageID: messageArr[i].id
                    });
                    msgsDel+=1;
                }
            }
            consoelMsgDel(user,msgsDel);
        });
    }
    else if(message.toLowerCase() === "$sudo rm gun -r" && user !== "Gun") {
        bot.sendMessage({
            to: channelID,
            message: "<@"+userID + ">" + "You are not authorized to do that."
        });
    }
// --------------------------------------

    // check to see if bot is mentioned
    function mentionedMe(rawEvent) {
        var mentionArr = rawEvent.d.mentions;
        for (var i=0; i<mentionArr.length; i++) {
            if (mentionArr[i].id === bot.id) {
                return true;
            }
        }
        return false;
    }

    // if bot is mentioned with having FU;
    if ( mentionedMe(rawEvent) && (message.search("fuck you") > 0 || message.search("FUCK YOU")>0)  ) {
        bot.sendMessage({
            to: channelID,
            message: "<@" + userID + ">"+" Why you mad!",
            typing: true
        });
    }

    if ( message.toLowerCase() === "fuck you") {
        bot.sendMessage({
            to: channelID,
            message: "http://4.bp.blogspot.com/-XWNXDprHibk/UYxniZERK6I/AAAAAAAAW1Y/RyvRcq_Q_cc/s640/vlcsnap-2011-11-10-19h19m39s159.png"
        });
    }

    //sample text
    if(message.toLowerCase() === "!sample text" || message.toLowerCase() === "!sp") {
        bot.sendMessage({
            to: channelID,
            message: "SampleText.MP4?\nhttps://www.youtube.com/watch?v=Tlr1L8FHp2U",
        });
    }

    //check ping
    if(message.toLowerCase() === "!ping") {
        bot.sendMessage({
            to: channelID,
            message: "<@" + userID + ">" + " Ping deez nuts in your mouth",
            typing: true
        });
    }

    // Say goodye
    if(message.toLowerCase()==="peace" || message.toLowerCase()==="goodnight") {
        bot.sendMessage({
            to: channelID,
            message: "Bye! :)",
            typing: true

        });
    }

    // for when somone didn't invite someone
    if(message.toLowerCase() === "no invite?") {
        bot.sendMessage({
            to: channelID,
            message:"That's cold blooded right there man.",
            typing: true
        });
    }

    // For when someone says rekt
    if(message.toLowerCase() === "!rekt" || message.toLowerCase() === "rekt") {
        bot.sendMessage({
            to: channelID,
            message: "https://giphy.com/gifs/rekt-vSR0fhtT5A9by"
        });
    }

    // For when someone says !1v1
    if (message.toLowerCase()=== "1v1" || message.toLowerCase() === "!1v1") {
        bot.sendMessage({
            to: channelID,
            message: "<@" + userID + ">"+" My nigga! Let's go then bitch!!",
            typing: true
        });
    }

    // for when someone says why?
    if (message.toLowerCase() === "why?") {
        bot.sendMessage({
            to: channelID,
            message: "<@" + userID + ">" + " Because fuck you! That's why!",
            typing: true
        });
    }
    if(message.toLowerCase() === "!doit") {
        bot.sendMessage({
            to: channelID,
            message: "https://media.giphy.com/media/TCaq4FekwSV5m/giphy.gif"
        });
    }

});
<|endoftext|>


<commit_before>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true}).bindPopup('to').addTo(map);
    var _this = this;
    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       console.log("cordenadas drag from ->",result);
       _this.cleanPolyline();
    });

    markerto.on('dragend', function(e){
        var marker = e.target;
        var result = marker.getLatLng();
        console.log("cordenadas drag to ->",result);
        _this.cleanPolyline();
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    console.log("mapa point to ->", to);
    var name = to[2];
    var circle = L.circle([to[0], to[1]], 20, {
        color: '#000',
        fillColor: '#ffffff',
        fillOpacity: 1,
        radius: number
    }).bindPopup(name).addTo(map);

    this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';
        console.log("imprime mode ->", mode);
        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        console.log("pintamos datos ->", this.polyline_creadas);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<commit_msg>adding console<commit_after>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true}).bindPopup('to').addTo(map);
    var _this = this;
    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       console.log("cordenadas drag from ->",result);
       _this.cleanPolyline();
    });

    markerto.on('dragend', function(e){
        var marker = e.target;
        var result = marker.getLatLng();
        console.log("cordenadas drag to ->",result);
        _this.cleanPolyline();
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    console.log("mapa point to ->", to);
    var name = to[2];
    var circle = L.circle([to[0], to[1]], 500, {
        color: '#000',
        fillColor: '#ffffff',
        fillOpacity: 1,
    }).bindPopup(name).addTo(map);

    var myZoom = {
      start:  map.getZoom(),
      end: map.getZoom()
    };

    map.on('zoomstart', function(e) {
       myZoom.start = map.getZoom();
    });

    map.on('zoomend', function(e) {
        myZoom.end = map.getZoom();
        var diff = myZoom.start - myZoom.end;
        if (diff > 0) {
            circle.setRadius(circle.getRadius() * 2);
        } else if (diff < 0) {
            circle.setRadius(circle.getRadius() / 2);
        }
    });

    this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';
        console.log("imprime mode ->", mode);
        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        console.log("pintamos datos ->", this.polyline_creadas);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<|endoftext|>


<commit_before>var ChannelModule = require("./module");
var db = require("../database");
var Flags = require("../flags");
var util = require("../utilities");
var Account = require("../account");
var Q = require("q");

const TYPE_UNBAN = {
    id: "number",
    name: "string"
};

function KickBanModule(channel) {
    ChannelModule.apply(this, arguments);

    if (this.channel.modules.chat) {
        this.channel.modules.chat.registerCommand("/kick", this.handleCmdKick.bind(this));
        this.channel.modules.chat.registerCommand("/kickanons", this.handleCmdKickAnons.bind(this));
        this.channel.modules.chat.registerCommand("/ban", this.handleCmdBan.bind(this));
        this.channel.modules.chat.registerCommand("/ipban", this.handleCmdIPBan.bind(this));
        this.channel.modules.chat.registerCommand("/banip", this.handleCmdIPBan.bind(this));
    }
}

KickBanModule.prototype = Object.create(ChannelModule.prototype);

function checkIPBan(cname, ip, cb) {
    db.channels.isIPBanned(cname, ip, function (err, banned) {
        if (err) {
            cb(false);
        } else {
            cb(banned);
        }
    });
}

function checkNameBan(cname, name, cb) {
    db.channels.isNameBanned(cname, name, function (err, banned) {
        if (err) {
            cb(false);
        } else {
            cb(banned);
        }
    });
}

KickBanModule.prototype.onUserPreJoin = function (user, data, cb) {
    if (!this.channel.is(Flags.C_REGISTERED)) {
        return cb(null, ChannelModule.PASSTHROUGH);
    }

    var cname = this.channel.name;
    checkIPBan(cname, user.realip, function (banned) {
        if (banned) {
            cb(null, ChannelModule.DENY);
            user.kick("Your IP address is banned from this channel.");
        } else {
            checkNameBan(cname, user.getName(), function (banned) {
                if (banned) {
                    cb(null, ChannelModule.DENY);
                    user.kick("Your username is banned from this channel.");
                } else {
                    cb(null, ChannelModule.PASSTHROUGH);
                }
            });
        }
    });

};

KickBanModule.prototype.onUserPostJoin = function (user) {
    if (!this.channel.is(Flags.C_REGISTERED)) {
        return;
    }

    var chan = this.channel;
    user.waitFlag(Flags.U_LOGGED_IN, function () {
        chan.activeLock.lock();
        db.channels.isNameBanned(chan.name, user.getName(), function (err, banned) {
            if (!err && banned) {
                user.kick("You are banned from this channel.");
                if (chan.modules.chat) {
                    chan.modules.chat.sendModMessage(user.getName() + " was kicked (" +
                                                     "name is banned)");
                }
            }
            chan.activeLock.release();
        });
    });

    var self = this;
    user.socket.on("requestBanlist", function () { self.sendBanlist([user]); });
    user.socket.typecheckedOn("unban", TYPE_UNBAN, this.handleUnban.bind(this, user));
};

KickBanModule.prototype.sendBanlist = function (users) {
    if (!this.channel.is(Flags.C_REGISTERED)) {
        return;
    }

    var perms = this.channel.modules.permissions;

    var bans = [];
    var unmaskedbans = [];
    db.channels.listBans(this.channel.name, function (err, banlist) {
        if (err) {
            return;
        }

        for (var i = 0; i < banlist.length; i++) {
            bans.push({
                id: banlist[i].id,
                ip: banlist[i].ip === "*" ? "*" : util.cloakIP(banlist[i].ip),
                name: banlist[i].name,
                reason: banlist[i].reason,
                bannedby: banlist[i].bannedby
            });
            unmaskedbans.push({
                id: banlist[i].id,
                ip: banlist[i].ip,
                name: banlist[i].name,
                reason: banlist[i].reason,
                bannedby: banlist[i].bannedby
            });
        }

        users.forEach(function (u) {
            if (!perms.canBan(u)) {
                return;
            }

            if (u.account.effectiveRank >= 255) {
                u.socket.emit("banlist", unmaskedbans);
            } else {
                u.socket.emit("banlist", bans);
            }
        });
    });
};

KickBanModule.prototype.sendUnban = function (users, data) {
    var perms = this.channel.modules.permissions;
    users.forEach(function (u) {
        if (perms.canBan(u)) {
            u.socket.emit("banlistRemove", data);
        }
    });
};

KickBanModule.prototype.handleCmdKick = function (user, msg, meta) {
    if (!this.channel.modules.permissions.canKick(user)) {
        return;
    }

    var args = msg.split(" ");
    args.shift(); /* shift off /kick */
    if (args.length === 0) {
        return user.socket.emit("errorMsg", {
            msg: "No kick target specified.  If you're trying to kick " +
                 "anonymous users, use /kickanons"
        });
    }
    var name = args.shift().toLowerCase();
    var reason = args.join(" ");
    var target = null;

    for (var i = 0; i < this.channel.users.length; i++) {
        if (this.channel.users[i].getLowerName() === name) {
            target = this.channel.users[i];
            break;
        }
    }

    if (target === null) {
        return;
    }

    if (target.account.effectiveRank >= user.account.effectiveRank) {
        return user.socket.emit("errorMsg", {
            msg: "You do not have permission to kick " + target.getName()
        });
    }

    target.kick(reason);
    this.channel.logger.log("[mod] " + user.getName() + " kicked " + target.getName() +
                            " (" + reason + ")");
    if (this.channel.modules.chat) {
        this.channel.modules.chat.sendModMessage(user.getName() + " kicked " +
                                                 target.getName());
    }
};

KickBanModule.prototype.handleCmdKickAnons = function (user, msg, meta) {
    if (!this.channel.modules.permissions.canKick(user)) {
        return;
    }

    var users = Array.prototype.slice.call(this.channel.users);
    users.forEach(function (u) {
        if (!u.is(Flags.U_LOGGED_IN)) {
            u.kick("anonymous user");
        }
    });

    this.channel.logger.log("[mod] " + user.getName() + " kicked anonymous users.");
    if (this.channel.modules.chat) {
        this.channel.modules.chat.sendModMessage(user.getName() + " kicked anonymous " +
                                                 "users");
    }
};

/* /ban - name bans */
KickBanModule.prototype.handleCmdBan = function (user, msg, meta) {
    var args = msg.split(" ");
    args.shift(); /* shift off /ban */
    if (args.length === 0) {
        return user.socket.emit("errorMsg", {
            msg: "No ban target specified."
        });
    }
    var name = args.shift().toLowerCase();
    var reason = args.join(" ");

    var chan = this.channel;
    chan.activeLock.lock();
    this.banName(user, name, reason, function (err) {
        chan.activeLock.release();
    });
};

/* /ipban - bans name and IP addresses associated with it */
KickBanModule.prototype.handleCmdIPBan = function (user, msg, meta) {
    var args = msg.split(" ");
    args.shift(); /* shift off /ipban */
    if (args.length === 0) {
        return user.socket.emit("errorMsg", {
            msg: "No ban target specified."
        });
    }
    var name = args.shift().toLowerCase();
    var range = false;
    if (args[0] === "range") {
        range = "range";
        args.shift();
    } else if (args[0] === "wrange") {
        range = "wrange";
        args.shift();
    }
    var reason = args.join(" ");

    var chan = this.channel;
    chan.activeLock.lock();
    this.banAll(user, name, range, reason, function (err) {
        chan.activeLock.release();
    });
};

KickBanModule.prototype.banName = function (actor, name, reason, cb) {
    var self = this;
    reason = reason.substring(0, 255);

    var chan = this.channel;
    var error = function (what) {
        actor.socket.emit("errorMsg", { msg: what });
        cb(what);
    };

    if (!chan.modules.permissions.canBan(actor)) {
        return error("You do not have ban permissions on this channel");
    }

    name = name.toLowerCase();
    if (name === actor.getLowerName()) {
        actor.socket.emit("costanza", {
            msg: "You can't ban yourself"
        });
        return cb("Attempted to ban self");
    }

    Q.nfcall(Account.rankForName, name, { channel: chan.name })
    .then(function (rank) {
        if (rank >= actor.account.effectiveRank) {
            throw "You don't have permission to ban " + name;
        }

        return Q.nfcall(db.channels.isNameBanned, chan.name, name);
    }).then(function (banned) {
        if (banned) {
            throw name + " is already banned";
        }

        if (chan.dead) { throw null; }

        return Q.nfcall(db.channels.ban, chan.name, "*", name, reason, actor.getName());
    }).then(function () {
        chan.logger.log("[mod] " + actor.getName() + " namebanned " + name);
        if (chan.modules.chat) {
            chan.modules.chat.sendModMessage(actor.getName() + " namebanned " + name,
                                             chan.modules.permissions.permissions.ban);
        }
        return true;
    }).then(function () {
        self.kickBanTarget(name, null);
        setImmediate(function () {
            cb(null);
        });
    }).catch(error).done();
};

KickBanModule.prototype.banIP = function (actor, ip, name, reason, cb) {
    var self = this;
    reason = reason.substring(0, 255);
    var masked = util.cloakIP(ip);

    var chan = this.channel;
    var error = function (what) {
        actor.socket.emit("errorMsg", { msg: what });
        cb(what);
    };

    if (!chan.modules.permissions.canBan(actor)) {
        return error("You do not have ban permissions on this channel");
    }

    Q.nfcall(Account.rankForIP, ip, { channel: chan.name }).then(function (rank) {
        if (rank >= actor.account.effectiveRank) {
            throw "You don't have permission to ban IP " + masked;
        }

        return Q.nfcall(db.channels.isIPBanned, chan.name, ip);
    }).then(function (banned) {
        if (banned) {
            throw masked + " is already banned";
        }

        if (chan.dead) { throw null; }

        return Q.nfcall(db.channels.ban, chan.name, ip, name, reason, actor.getName());
    }).then(function () {
        var cloaked = util.cloakIP(ip);
        chan.logger.log("[mod] " + actor.getName() + " banned " + cloaked + " (" + name + ")");
        if (chan.modules.chat) {
            chan.modules.chat.sendModMessage(actor.getName() + " banned " +
                                             cloaked + " (" + name + ")",
                                             chan.modules.permissions.permissions.ban);
        }
    }).then(function () {
        self.kickBanTarget(name, ip);
        setImmediate(function () {
            cb(null);
        });
    }).catch(error).done();
};

KickBanModule.prototype.banAll = function (actor, name, range, reason, cb) {
    var self = this;
    reason = reason.substring(0, 255);

    var chan = self.channel;
    var error = function (what) {
        cb(what);
    };

    if (!chan.modules.permissions.canBan(actor)) {
        return error("You do not have ban permissions on this channel");
    }

    self.banName(actor, name, reason, function (err) {
        if (err && err.indexOf("is already banned") === -1) {
            cb(err);
        } else {
            db.getIPs(name, function (err, ips) {
                if (err) {
                    return error(err);
                }
                var all = ips.map(function (ip) {
                    if (range === "range") {
                        ip = util.getIPRange(ip);
                    } else if (range === "wrange") {
                        ip = util.getWideIPRange(ip);
                    }
                    return Q.nfcall(self.banIP.bind(self), actor, ip, name, reason);
                });

                Q.all(all).then(function () {
                    setImmediate(cb);
                }).catch(error).done();
            });
        }
    });
};

KickBanModule.prototype.kickBanTarget = function (name, ip) {
    name = name.toLowerCase();
    for (var i = 0; i < this.channel.users.length; i++) {
        if (this.channel.users[i].getLowerName() === name ||
            this.channel.users[i].realip === ip) {
            this.channel.users[i].kick("You're banned!");
        }
    }
};

KickBanModule.prototype.handleUnban = function (user, data) {
    if (!this.channel.modules.permissions.canBan(user)) {
        return;
    }

    var self = this;
    this.channel.activeLock.lock();
    db.channels.unbanId(this.channel.name, data.id, function (err) {
        if (err) {
            return user.socket.emit("errorMsg", {
                msg: err
            });
        }

        self.sendUnban(self.channel.users, data);
        self.channel.logger.log("[mod] " + user.getName() + " unbanned " + data.name);
        if (self.channel.modules.chat) {
            var banperm = self.channel.modules.permissions.permissions.ban;
            self.channel.modules.chat.sendModMessage(user.getName() + " unbanned " +
                                                     data.name, banperm);
        }
        self.channel.activeLock.release();
    });
};

module.exports = KickBanModule;
<commit_msg>Fail /kick, /ban if the target name is blank<commit_after>var ChannelModule = require("./module");
var db = require("../database");
var Flags = require("../flags");
var util = require("../utilities");
var Account = require("../account");
var Q = require("q");

const TYPE_UNBAN = {
    id: "number",
    name: "string"
};

function KickBanModule(channel) {
    ChannelModule.apply(this, arguments);

    if (this.channel.modules.chat) {
        this.channel.modules.chat.registerCommand("/kick", this.handleCmdKick.bind(this));
        this.channel.modules.chat.registerCommand("/kickanons", this.handleCmdKickAnons.bind(this));
        this.channel.modules.chat.registerCommand("/ban", this.handleCmdBan.bind(this));
        this.channel.modules.chat.registerCommand("/ipban", this.handleCmdIPBan.bind(this));
        this.channel.modules.chat.registerCommand("/banip", this.handleCmdIPBan.bind(this));
    }
}

KickBanModule.prototype = Object.create(ChannelModule.prototype);

function checkIPBan(cname, ip, cb) {
    db.channels.isIPBanned(cname, ip, function (err, banned) {
        if (err) {
            cb(false);
        } else {
            cb(banned);
        }
    });
}

function checkNameBan(cname, name, cb) {
    db.channels.isNameBanned(cname, name, function (err, banned) {
        if (err) {
            cb(false);
        } else {
            cb(banned);
        }
    });
}

KickBanModule.prototype.onUserPreJoin = function (user, data, cb) {
    if (!this.channel.is(Flags.C_REGISTERED)) {
        return cb(null, ChannelModule.PASSTHROUGH);
    }

    var cname = this.channel.name;
    checkIPBan(cname, user.realip, function (banned) {
        if (banned) {
            cb(null, ChannelModule.DENY);
            user.kick("Your IP address is banned from this channel.");
        } else {
            checkNameBan(cname, user.getName(), function (banned) {
                if (banned) {
                    cb(null, ChannelModule.DENY);
                    user.kick("Your username is banned from this channel.");
                } else {
                    cb(null, ChannelModule.PASSTHROUGH);
                }
            });
        }
    });

};

KickBanModule.prototype.onUserPostJoin = function (user) {
    if (!this.channel.is(Flags.C_REGISTERED)) {
        return;
    }

    var chan = this.channel;
    user.waitFlag(Flags.U_LOGGED_IN, function () {
        chan.activeLock.lock();
        db.channels.isNameBanned(chan.name, user.getName(), function (err, banned) {
            if (!err && banned) {
                user.kick("You are banned from this channel.");
                if (chan.modules.chat) {
                    chan.modules.chat.sendModMessage(user.getName() + " was kicked (" +
                                                     "name is banned)");
                }
            }
            chan.activeLock.release();
        });
    });

    var self = this;
    user.socket.on("requestBanlist", function () { self.sendBanlist([user]); });
    user.socket.typecheckedOn("unban", TYPE_UNBAN, this.handleUnban.bind(this, user));
};

KickBanModule.prototype.sendBanlist = function (users) {
    if (!this.channel.is(Flags.C_REGISTERED)) {
        return;
    }

    var perms = this.channel.modules.permissions;

    var bans = [];
    var unmaskedbans = [];
    db.channels.listBans(this.channel.name, function (err, banlist) {
        if (err) {
            return;
        }

        for (var i = 0; i < banlist.length; i++) {
            bans.push({
                id: banlist[i].id,
                ip: banlist[i].ip === "*" ? "*" : util.cloakIP(banlist[i].ip),
                name: banlist[i].name,
                reason: banlist[i].reason,
                bannedby: banlist[i].bannedby
            });
            unmaskedbans.push({
                id: banlist[i].id,
                ip: banlist[i].ip,
                name: banlist[i].name,
                reason: banlist[i].reason,
                bannedby: banlist[i].bannedby
            });
        }

        users.forEach(function (u) {
            if (!perms.canBan(u)) {
                return;
            }

            if (u.account.effectiveRank >= 255) {
                u.socket.emit("banlist", unmaskedbans);
            } else {
                u.socket.emit("banlist", bans);
            }
        });
    });
};

KickBanModule.prototype.sendUnban = function (users, data) {
    var perms = this.channel.modules.permissions;
    users.forEach(function (u) {
        if (perms.canBan(u)) {
            u.socket.emit("banlistRemove", data);
        }
    });
};

KickBanModule.prototype.handleCmdKick = function (user, msg, meta) {
    if (!this.channel.modules.permissions.canKick(user)) {
        return;
    }

    var args = msg.split(" ");
    args.shift(); /* shift off /kick */
    if (args.length === 0 || args[0].trim() === "") {
        return user.socket.emit("errorMsg", {
            msg: "No kick target specified.  If you're trying to kick " +
                 "anonymous users, use /kickanons"
        });
    }
    var name = args.shift().toLowerCase();
    var reason = args.join(" ");
    var target = null;

    for (var i = 0; i < this.channel.users.length; i++) {
        if (this.channel.users[i].getLowerName() === name) {
            target = this.channel.users[i];
            break;
        }
    }

    if (target === null) {
        return;
    }

    if (target.account.effectiveRank >= user.account.effectiveRank) {
        return user.socket.emit("errorMsg", {
            msg: "You do not have permission to kick " + target.getName()
        });
    }

    target.kick(reason);
    this.channel.logger.log("[mod] " + user.getName() + " kicked " + target.getName() +
                            " (" + reason + ")");
    if (this.channel.modules.chat) {
        this.channel.modules.chat.sendModMessage(user.getName() + " kicked " +
                                                 target.getName());
    }
};

KickBanModule.prototype.handleCmdKickAnons = function (user, msg, meta) {
    if (!this.channel.modules.permissions.canKick(user)) {
        return;
    }

    var users = Array.prototype.slice.call(this.channel.users);
    users.forEach(function (u) {
        if (!u.is(Flags.U_LOGGED_IN)) {
            u.kick("anonymous user");
        }
    });

    this.channel.logger.log("[mod] " + user.getName() + " kicked anonymous users.");
    if (this.channel.modules.chat) {
        this.channel.modules.chat.sendModMessage(user.getName() + " kicked anonymous " +
                                                 "users");
    }
};

/* /ban - name bans */
KickBanModule.prototype.handleCmdBan = function (user, msg, meta) {
    var args = msg.split(" ");
    args.shift(); /* shift off /ban */
    if (args.length === 0 || args[0].trim() === "") {
        return user.socket.emit("errorMsg", {
            msg: "No ban target specified."
        });
    }
    var name = args.shift().toLowerCase();
    var reason = args.join(" ");

    var chan = this.channel;
    chan.activeLock.lock();
    this.banName(user, name, reason, function (err) {
        chan.activeLock.release();
    });
};

/* /ipban - bans name and IP addresses associated with it */
KickBanModule.prototype.handleCmdIPBan = function (user, msg, meta) {
    var args = msg.split(" ");
    args.shift(); /* shift off /ipban */
    if (args.length === 0 || args[0].trim() === "") {
        return user.socket.emit("errorMsg", {
            msg: "No ban target specified."
        });
    }
    var name = args.shift().toLowerCase();
    var range = false;
    if (args[0] === "range") {
        range = "range";
        args.shift();
    } else if (args[0] === "wrange") {
        range = "wrange";
        args.shift();
    }
    var reason = args.join(" ");

    var chan = this.channel;
    chan.activeLock.lock();
    this.banAll(user, name, range, reason, function (err) {
        chan.activeLock.release();
    });
};

KickBanModule.prototype.banName = function (actor, name, reason, cb) {
    var self = this;
    reason = reason.substring(0, 255);

    var chan = this.channel;
    var error = function (what) {
        actor.socket.emit("errorMsg", { msg: what });
        cb(what);
    };

    if (!chan.modules.permissions.canBan(actor)) {
        return error("You do not have ban permissions on this channel");
    }

    name = name.toLowerCase();
    if (name === actor.getLowerName()) {
        actor.socket.emit("costanza", {
            msg: "You can't ban yourself"
        });
        return cb("Attempted to ban self");
    }

    Q.nfcall(Account.rankForName, name, { channel: chan.name })
    .then(function (rank) {
        if (rank >= actor.account.effectiveRank) {
            throw "You don't have permission to ban " + name;
        }

        return Q.nfcall(db.channels.isNameBanned, chan.name, name);
    }).then(function (banned) {
        if (banned) {
            throw name + " is already banned";
        }

        if (chan.dead) { throw null; }

        return Q.nfcall(db.channels.ban, chan.name, "*", name, reason, actor.getName());
    }).then(function () {
        chan.logger.log("[mod] " + actor.getName() + " namebanned " + name);
        if (chan.modules.chat) {
            chan.modules.chat.sendModMessage(actor.getName() + " namebanned " + name,
                                             chan.modules.permissions.permissions.ban);
        }
        return true;
    }).then(function () {
        self.kickBanTarget(name, null);
        setImmediate(function () {
            cb(null);
        });
    }).catch(error).done();
};

KickBanModule.prototype.banIP = function (actor, ip, name, reason, cb) {
    var self = this;
    reason = reason.substring(0, 255);
    var masked = util.cloakIP(ip);

    var chan = this.channel;
    var error = function (what) {
        actor.socket.emit("errorMsg", { msg: what });
        cb(what);
    };

    if (!chan.modules.permissions.canBan(actor)) {
        return error("You do not have ban permissions on this channel");
    }

    Q.nfcall(Account.rankForIP, ip, { channel: chan.name }).then(function (rank) {
        if (rank >= actor.account.effectiveRank) {
            throw "You don't have permission to ban IP " + masked;
        }

        return Q.nfcall(db.channels.isIPBanned, chan.name, ip);
    }).then(function (banned) {
        if (banned) {
            throw masked + " is already banned";
        }

        if (chan.dead) { throw null; }

        return Q.nfcall(db.channels.ban, chan.name, ip, name, reason, actor.getName());
    }).then(function () {
        var cloaked = util.cloakIP(ip);
        chan.logger.log("[mod] " + actor.getName() + " banned " + cloaked + " (" + name + ")");
        if (chan.modules.chat) {
            chan.modules.chat.sendModMessage(actor.getName() + " banned " +
                                             cloaked + " (" + name + ")",
                                             chan.modules.permissions.permissions.ban);
        }
    }).then(function () {
        self.kickBanTarget(name, ip);
        setImmediate(function () {
            cb(null);
        });
    }).catch(error).done();
};

KickBanModule.prototype.banAll = function (actor, name, range, reason, cb) {
    var self = this;
    reason = reason.substring(0, 255);

    var chan = self.channel;
    var error = function (what) {
        cb(what);
    };

    if (!chan.modules.permissions.canBan(actor)) {
        return error("You do not have ban permissions on this channel");
    }

    self.banName(actor, name, reason, function (err) {
        if (err && err.indexOf("is already banned") === -1) {
            cb(err);
        } else {
            db.getIPs(name, function (err, ips) {
                if (err) {
                    return error(err);
                }
                var all = ips.map(function (ip) {
                    if (range === "range") {
                        ip = util.getIPRange(ip);
                    } else if (range === "wrange") {
                        ip = util.getWideIPRange(ip);
                    }
                    return Q.nfcall(self.banIP.bind(self), actor, ip, name, reason);
                });

                Q.all(all).then(function () {
                    setImmediate(cb);
                }).catch(error).done();
            });
        }
    });
};

KickBanModule.prototype.kickBanTarget = function (name, ip) {
    name = name.toLowerCase();
    for (var i = 0; i < this.channel.users.length; i++) {
        if (this.channel.users[i].getLowerName() === name ||
            this.channel.users[i].realip === ip) {
            this.channel.users[i].kick("You're banned!");
        }
    }
};

KickBanModule.prototype.handleUnban = function (user, data) {
    if (!this.channel.modules.permissions.canBan(user)) {
        return;
    }

    var self = this;
    this.channel.activeLock.lock();
    db.channels.unbanId(this.channel.name, data.id, function (err) {
        if (err) {
            return user.socket.emit("errorMsg", {
                msg: err
            });
        }

        self.sendUnban(self.channel.users, data);
        self.channel.logger.log("[mod] " + user.getName() + " unbanned " + data.name);
        if (self.channel.modules.chat) {
            var banperm = self.channel.modules.permissions.permissions.ban;
            self.channel.modules.chat.sendModMessage(user.getName() + " unbanned " +
                                                     data.name, banperm);
        }
        self.channel.activeLock.release();
    });
};

module.exports = KickBanModule;
<|endoftext|>


<commit_before>Template.editprofile.events = {
    'submit form': function(e) {
        e.preventDefault();
        Meteor.users.update({
            _id: Meteor.user()._id
        }, {
            $set: {
                "profile.name": $(e.target).find('[name=fullname]').val(),
                "username": $(e.target).find('[name=username]').val()
            }
        });
    }
};
Template.userkeys.events = {
    'submit form': function(e) {
        e.preventDefault();

        var crypt_private = new JSEncrypt({
            default_key_size: 2048
        });
        crypt_private.setKey($(e.target).find('[name=private_key]').val());

        var crypt_public = new JSEncrypt({
            default_key_size: 2048
        });
        crypt_public.setKey($(e.target).find('[name=public_key]').val());

        var text = 'CCMED Test Encryption';
        // Encrypt the data with the public key.
        var enc = crypt_public.encrypt(text);

        // Now decrypt the crypted text with the private key.
        var dec = crypt_private.decrypt(enc);

        console.log(dec);
        // Now a simple check to see if the round-trip worked.
        if (dec === text) {
            Meteor.users.update({
                _id: Meteor.user()._id
            }, {
                $set: {
                    "private_key": $(e.target).find('[name=private_key]').val(),
                    "public_key": $(e.target).find('[name=public_key]').val()
                }
            });
            return true;
        } else {
            alert('Unable to run encryption/decryption test with your private/public key. Are you sure they are valid?');
            return false;
        }
    },
    'click #generate_private_key': function(e, template) {
        $('#generate_private_key').text("Generating...");
        alert('Hit OK to start generating. Your browser may lock up for a moment.');

        //----------------- New RSA Stuff
        crypt = new JSEncrypt({
            default_key_size: 2048
        });
        var dt = new Date();
        var time = -(dt.getTime());
        crypt.getKey();
        dt = new Date();
        time += (dt.getTime());
        //----------------- End new RSA Stuff

        $('textarea[name="private_key"]').val(crypt.getPrivateKey());
        $('textarea[name="public_key"]').val(crypt.getPublicKey());
        $('#generate_private_key').text("Generate");
    },
    'click #show_private_key': function(e, template) {
        $('#private_key_wrap').fadeIn();
        $('#hide_private_key').show();
        $('#generate_private_key').show();
        $('#submit_private_key').show();
        $('#show_private_key').hide();
    },
    'click #hide_private_key': function(e, template) {
        $('#private_key_wrap').fadeOut();
        $('#hide_private_key').hide();
        $('#generate_private_key').hide();
        $('#submit_private_key').hide();
        $('#show_private_key').show();
    }
};
<commit_msg>Removed stale console.log<commit_after>Template.editprofile.events = {
    'submit form': function(e) {
        e.preventDefault();
        Meteor.users.update({
            _id: Meteor.user()._id
        }, {
            $set: {
                "profile.name": $(e.target).find('[name=fullname]').val(),
                "username": $(e.target).find('[name=username]').val()
            }
        });
    }
};
Template.userkeys.events = {
    'submit form': function(e) {
        e.preventDefault();

        var crypt_private = new JSEncrypt({
            default_key_size: 2048
        });
        crypt_private.setKey($(e.target).find('[name=private_key]').val());

        var crypt_public = new JSEncrypt({
            default_key_size: 2048
        });
        crypt_public.setKey($(e.target).find('[name=public_key]').val());

        var text = 'CCMED Test Encryption';
        // Encrypt the data with the public key.
        var enc = crypt_public.encrypt(text);

        // Now decrypt the crypted text with the private key.
        var dec = crypt_private.decrypt(enc);

        // Now a simple check to see if the round-trip worked.
        if (dec === text) {
            Meteor.users.update({
                _id: Meteor.user()._id
            }, {
                $set: {
                    "private_key": $(e.target).find('[name=private_key]').val(),
                    "public_key": $(e.target).find('[name=public_key]').val()
                }
            });
            return true;
        } else {
            alert('Unable to run encryption/decryption test with your private/public key. Are you sure they are valid?');
            return false;
        }
    },
    'click #generate_private_key': function(e, template) {
        $('#generate_private_key').text("Generating...");
        alert('Hit OK to start generating. Your browser may lock up for a moment.');

        //----------------- New RSA Stuff
        crypt = new JSEncrypt({
            default_key_size: 2048
        });
        var dt = new Date();
        var time = -(dt.getTime());
        crypt.getKey();
        dt = new Date();
        time += (dt.getTime());
        //----------------- End new RSA Stuff

        $('textarea[name="private_key"]').val(crypt.getPrivateKey());
        $('textarea[name="public_key"]').val(crypt.getPublicKey());
        $('#generate_private_key').text("Generate");
    },
    'click #show_private_key': function(e, template) {
        $('#private_key_wrap').fadeIn();
        $('#hide_private_key').show();
        $('#generate_private_key').show();
        $('#submit_private_key').show();
        $('#show_private_key').hide();
    },
    'click #hide_private_key': function(e, template) {
        $('#private_key_wrap').fadeOut();
        $('#hide_private_key').hide();
        $('#generate_private_key').hide();
        $('#submit_private_key').hide();
        $('#show_private_key').show();
    }
};
<|endoftext|>


<commit_before>import Relay from 'react-relay';

import OrganizationMemberRoleConstants from '../constants/OrganizationMemberRoleConstants';

export default class OrganizationInvitationCreate extends Relay.Mutation {
  static fragments = {
    organization: () => Relay.QL`
      fragment on Organization {
        id
      }
    `
  }

  getMutation() {
    return Relay.QL`
      mutation {
        organizationInvitationCreate
      }
    `;
  }

  getFatQuery() {
    return Relay.QL`
      fragment on OrganizationInvitationCreatePayload {
        invitationEdges {
          node {
            role
            user {
              name
            }
          }
        }
      }
    `;
  }

  getOptimisticResponse() {
    return {
      organizationInvitationEdge: {
        node: {
          role: OrganizationMemberRoleConstants.MEMBER
        }
      }
    };
  }

  getConfigs() {
    return [{
      type: 'RANGE_ADD',
      parentName: 'organization',
      parentID: this.props.organization.id,
      connectionName: 'invitations',
      edgeName: 'organizationInvitationEdge',
      rangeBehaviors: () => 'prepend'
    }];
  }

  getVariables() {
    return { id: this.props.organizationMember.id, role: this.props.role };
  }
}
<commit_msg>Add email to OrganizationInvitation query<commit_after>import Relay from 'react-relay';

import OrganizationMemberRoleConstants from '../constants/OrganizationMemberRoleConstants';

export default class OrganizationInvitationCreate extends Relay.Mutation {
  static fragments = {
    organization: () => Relay.QL`
      fragment on Organization {
        id
      }
    `
  }

  getMutation() {
    return Relay.QL`
      mutation {
        organizationInvitationCreate
      }
    `;
  }

  getFatQuery() {
    return Relay.QL`
      fragment on OrganizationInvitationCreatePayload {
        invitationEdges {
          node {
            role
            user {
              name
            }
          }
        }
      }
    `;
  }

  getOptimisticResponse() {
    return {
      organizationInvitationEdge: {
        node: {
          role: OrganizationMemberRoleConstants.MEMBER
        }
      }
    };
  }

  getConfigs() {
    return [{
      type: 'RANGE_ADD',
      parentName: 'organization',
      parentID: this.props.organization.id,
      connectionName: 'invitations',
      edgeName: 'organizationInvitationEdge',
      rangeBehaviors: () => 'prepend'
    }];
  }

  getVariables() {
    return {
      id: this.props.organizationMember.id,
      emails: this.props.emails,
      role: this.props.role
    };
  }
}
<|endoftext|>


<commit_before>import { Class, Enum } from 'meteor/jagi:astronomy';
import { Mongo } from 'meteor/mongo';

const collection = new Mongo.Collection('polls');

collection.allow({
  insert: () =>  true,
  update: () =>  true,
  remove: () =>  true
});

const Status = Enum.create({
  name: 'Status',
  identifiers: {
    CREATED: 'CREATED',
    PUBLISHED: 'PUBLISHED',
    CLOSED: 'CLOSED',
    CANCELED: 'CANCELED'
  }
});

const Type = Enum.create({
  name: 'Type',
  identifiers: {
    PUBLIC: 'PUBLIC',
    PRIVATE: 'PRIVATE'
  }
});

const model = Class.create({
  name: 'Poll',
  collection,
  behaviors: {
    timestamp: {}
  },
  field: {
    title: {
      type: String,
      validator: [{
        type: 'minLength',
        param: 3
      }, {
        type: 'maxLength',
        param: 256
      }]
    },
    status: {
      type: Status
    },
    type: {
      type: Type
    },
    createdBy: {
      type: Mongo.ObjectID,
      optional: true,
      immutable: true
    }
  },
  events: {
    beforeSave(e) {
      const doc = e.currentTarget;
      doc.status = Status.getIdentifier('CREATED');
    }
  }
});

export {
    collection as Polls,
    model as Poll
};
<commit_msg>Polls models were improved.<commit_after>import { Class, Enum } from 'meteor/jagi:astronomy';
import { Mongo } from 'meteor/mongo';

const polls = new Mongo.Collection('polls');

polls.allow({
  insert: () =>  true,
  update: () =>  true,
  remove: () =>  true
});

const status = Enum.create({
  name: 'PollStatus',
  identifiers: {
    CREATED: 'CREATED',
    PUBLISHED: 'PUBLISHED',
    CLOSED: 'CLOSED',
    CANCELED: 'CANCELED'
  }
});

const type = Enum.create({
  name: 'PollType',
  identifiers: {
    PUBLIC: 'PUBLIC',
    PRIVATE: 'PRIVATE'
  }
});

const question = Class.create({
  name: 'PollQuestion',
  fields: {
    title: {
      type: String,
      validator: [{
        type: 'minLength',
        param: 3
      }, {
        type: 'maxLength',
        param: 256
      }],
      answers: [Mongo.ObjectID]
    },
  }
});

const poll = Class.create({
  name: 'Poll',
  collection: polls,
  behaviors: {
    timestamp: {}
  },
  fields: {
    title: {
      type: String,
      validator: [{
        type: 'minLength',
        param: 3
      }, {
        type: 'maxLength',
        param: 256
      }]
    },
    status: {
      type: status
    },
    type: {
      type: type
    },
    createdBy: {
      type: Mongo.ObjectID,
      optional: true,
      immutable: true
    },
    multiple: {
      type: Boolean,
      default: false
    },
    questions: {
      type: [question]
    }
  },
  events: {
    beforeSave(e) {
      const doc = e.currentTarget;
      doc.status = status.getIdentifier('CREATED');
    }
  }
});

export {
    polls as Polls,
    status as PollStatus,
    type as PollType,
    question as PollQuestion,
    poll as Poll
};
<|endoftext|>


<commit_before>import '../console/console-frame.scss';
import * as consoleFrames from '../console/frames';
import * as scrolls from '../content/scrolls';
import * as navigates from '../content/navigates';
import Follow from '../content/follow';
import operations from '../operations';
import messages from '../messages';

consoleFrames.initialize(window.document);

const startFollows = (newTab) => {
  let follow = new Follow(window.document, newTab);
  follow.onActivated((element) => {
    switch (element.tagName.toLowerCase()) {
    case 'a':
      return browser.runtime.sendMessage({
        type: messages.OPEN_URL,
        url: element.href,
        newTab
      });
    case 'input':
      switch (element.type) {
      case 'file':
      case 'checkbox':
      case 'radio':
      case 'submit':
      case 'reset':
      case 'button':
      case 'image':
      case 'color':
        return element.click();
      default:
        return element.focus();
      }
    case 'textarea':
      return element.focus();
    case 'button':
      return element.click();
    }
  });
};

window.addEventListener('keypress', (e) => {
  if (e.target instanceof HTMLInputElement) {
    return;
  }
  browser.runtime.sendMessage({
    type: messages.KEYDOWN,
    code: e.which,
    ctrl: e.ctrlKey
  });
});

const execOperation = (operation) => {
  switch (operation.type) {
  case operations.SCROLL_LINES:
    return scrolls.scrollLines(window, operation.count);
  case operations.SCROLL_PAGES:
    return scrolls.scrollPages(window, operation.count);
  case operations.SCROLL_TOP:
    return scrolls.scrollTop(window);
  case operations.SCROLL_BOTTOM:
    return scrolls.scrollBottom(window);
  case operations.SCROLL_LEFT:
    return scrolls.scrollLeft(window);
  case operations.SCROLL_RIGHT:
    return scrolls.scrollRight(window);
  case operations.FOLLOW_START:
    return startFollows(operation.newTab);
  case operations.NAVIGATE_HISTORY_PREV:
    return navigates.historyPrev(window);
  case operations.NAVIGATE_HISTORY_NEXT:
    return navigates.historyNext(window);
  case operations.NAVIGATE_LINK_PREV:
    return navigates.linkPrev(window);
  case operations.NAVIGATE_LINK_NEXT:
    return navigates.linkNext(window);
  case operations.NAVIGATE_PARENT:
    return navigates.parent(window);
  case operations.NAVIGATE_ROOT:
    return navigates.root(window);
  }
};

const update = (state) => {
  if (!state.console.commandShown) {
    window.focus();
    consoleFrames.blur(window.document);
  }
};

browser.runtime.onMessage.addListener((action) => {
  switch (action.type) {
  case messages.STATE_UPDATE:
    return update(action.state);
  case messages.CONTENT_OPERATION:
    execOperation(action.operation);
    return Promise.resolve();
  default:
    return Promise.resolve();
  }
});
<commit_msg>click link and avoid invalid links<commit_after>import '../console/console-frame.scss';
import * as consoleFrames from '../console/frames';
import * as scrolls from '../content/scrolls';
import * as navigates from '../content/navigates';
import Follow from '../content/follow';
import operations from '../operations';
import messages from '../messages';

consoleFrames.initialize(window.document);

const startFollows = (newTab) => {
  let follow = new Follow(window.document);
  follow.onActivated((element) => {
    switch (element.tagName.toLowerCase()) {
    case 'a':
      if (newTab) {
        // getAttribute() to avoid to resolve absolute path
        let href = element.getibute('href');

        // eslint-disable-next-line no-script-url
        if (!href || href === '#' || href.startsWith('javascript:')) {
          return;
        }
        return browser.runtime.sendMessage({
          type: messages.OPEN_URL,
          url: element.href,
          newTab
        });
      }
      return element.click();
    case 'input':
      switch (element.type) {
      case 'file':
      case 'checkbox':
      case 'radio':
      case 'submit':
      case 'reset':
      case 'button':
      case 'image':
      case 'color':
        return element.click();
      default:
        return element.focus();
      }
    case 'textarea':
      return element.focus();
    case 'button':
      return element.click();
    }
  });
};

window.addEventListener('keypress', (e) => {
  if (e.target instanceof HTMLInputElement) {
    return;
  }
  browser.runtime.sendMessage({
    type: messages.KEYDOWN,
    code: e.which,
    ctrl: e.ctrlKey
  });
});

const execOperation = (operation) => {
  switch (operation.type) {
  case operations.SCROLL_LINES:
    return scrolls.scrollLines(window, operation.count);
  case operations.SCROLL_PAGES:
    return scrolls.scrollPages(window, operation.count);
  case operations.SCROLL_TOP:
    return scrolls.scrollTop(window);
  case operations.SCROLL_BOTTOM:
    return scrolls.scrollBottom(window);
  case operations.SCROLL_LEFT:
    return scrolls.scrollLeft(window);
  case operations.SCROLL_RIGHT:
    return scrolls.scrollRight(window);
  case operations.FOLLOW_START:
    return startFollows(operation.newTab);
  case operations.NAVIGATE_HISTORY_PREV:
    return navigates.historyPrev(window);
  case operations.NAVIGATE_HISTORY_NEXT:
    return navigates.historyNext(window);
  case operations.NAVIGATE_LINK_PREV:
    return navigates.linkPrev(window);
  case operations.NAVIGATE_LINK_NEXT:
    return navigates.linkNext(window);
  case operations.NAVIGATE_PARENT:
    return navigates.parent(window);
  case operations.NAVIGATE_ROOT:
    return navigates.root(window);
  }
};

const update = (state) => {
  if (!state.console.commandShown) {
    window.focus();
    consoleFrames.blur(window.document);
  }
};

browser.runtime.onMessage.addListener((action) => {
  switch (action.type) {
  case messages.STATE_UPDATE:
    return update(action.state);
  case messages.CONTENT_OPERATION:
    execOperation(action.operation);
    return Promise.resolve();
  default:
    return Promise.resolve();
  }
});
<|endoftext|>