Refactored sending of HipChat room messages.

This commit is contained in:
Nick Winter 2015-02-04 16:17:53 -08:00
parent 8f996a44b0
commit a189e32948
8 changed files with 61 additions and 58 deletions

View file

@ -461,8 +461,9 @@ module.exports = class Handler
sendwithus.api.send context, (err, result) ->
sendChangedHipChatMessage: (options) ->
message = "#{options.creator.get('name')} saved a change to <a href=\"#{options.docLink}\">#{options.target.get('name')}</a>: #{options.target.get('commitMessage')}"
hipchat.sendHipChatMessage message
message = "#{options.creator.get('name')} saved a change to <a href=\"#{options.docLink}\">#{options.target.get('name')}</a>: #{options.target.get('commitMessage') or '(no commit message)'}"
rooms = if /Diplomat submission/.test(message) then ['main'] else ['main', 'artisans']
hipchat.sendHipChatMessage message, rooms
makeNewInstance: (req) ->
model = new @modelClass({})

View file

@ -2,32 +2,34 @@ config = require '../server_config'
request = require 'request'
log = require 'winston'
module.exports.sendHipChatMessage = sendHipChatMessage = (message) ->
return unless key = config.hipchatAPIKey
return unless config.isProduction
roomID = 254598
form =
color: 'yellow'
notify: false
message: message
messageFormat: 'html'
url = "https://api.hipchat.com/v2/room/#{roomID}/notification?auth_token=#{key}"
request.post {uri: url, json: form}, (err, res, body) ->
return log.error 'Error sending HipChat patch request:', err or body if err or /error/i.test body
#log.info "Got HipChat patch response:", body
roomIDMap =
main: 254598
artisans: 1146994
tower: 318356
module.exports.sendTowerHipChatMessage = sendTowerHipChatMessage = (message) ->
secondsFromEpoch = Math.floor(new Date().getTime() / 1000)
link = "<a href=\"https://papertrailapp.com/groups/488214/events?time=#{secondsFromEpoch}\">PaperTrail</a>"
message = "#{message} #{link}"
return unless key = config.hipchatTowerAPIKey
module.exports.sendHipChatMessage = sendHipChatMessage = (message, rooms, options) ->
return unless config.isProduction
roomID = 318356
form =
color: 'red'
notify: true
message: message
messageFormat: 'html'
url = "https://api.hipchat.com/v2/room/#{roomID}/notification?auth_token=#{key}"
request.post {uri: url, json: form}, (err, res, body) ->
return log.error 'Error sending HipChat Tower message:', err or body if err or /error/i.test body
rooms ?= ['main']
options ?= {}
for room in rooms
unless roomID = roomIDMap[room]
log.error "Unknown HipChat room #{room}."
continue
unless key = config.hipchat[room]
log.info "No HipChat API key for room #{room}."
continue
form =
color: options.color or 'yellow'
notify: false
message: message
messageFormat: 'html'
if options.papertrail
secondsFromEpoch = Math.floor(new Date().getTime() / 1000)
link = "<a href=\"https://papertrailapp.com/groups/488214/events?time=#{secondsFromEpoch}\">PaperTrail</a>"
form.message = "#{message} #{link}"
form.color = options.color or 'red'
form.notify = true
url = "https://api.hipchat.com/v2/room/#{roomID}/notification?auth_token=#{key}"
request.post {uri: url, json: form}, (err, res, body) ->
return log.error 'Error sending HipChat message:', err or body if err or /error/i.test body
#log.info "Got HipChat message response:", body

View file

@ -101,6 +101,6 @@ PatchHandler = class PatchHandler extends Handler
sendPatchCreatedHipChatMessage: (options) ->
message = "#{options.creator.get('name')} submitted a patch to <a href=\"#{options.docLink}\">#{options.target.get('name')}</a>: #{options.patch.get('commitMessage')}"
hipchat.sendHipChatMessage message
hipchat.sendHipChatMessage message, ['main']
module.exports = new PatchHandler()

View file

@ -35,7 +35,7 @@ PaymentHandler = class PaymentHandler extends Handler
editableProperties: []
postEditableProperties: ['purchased']
jsonSchema: require '../../app/schemas/models/payment.schema'
get: (req, res) ->
return res.send([]) unless req.user
q = Payment.find({recipient:req.user._id})
@ -43,7 +43,7 @@ PaymentHandler = class PaymentHandler extends Handler
return @sendDatabaseError(res, err) if err
res.send(payments)
)
logPaymentError: (req, msg) ->
console.warn "Payment Error: #{req.user.get('slug')} (#{req.user._id}): '#{msg}'"
@ -57,10 +57,10 @@ PaymentHandler = class PaymentHandler extends Handler
post: (req, res, pathName) ->
if pathName is 'check-stripe-charges'
return @checkStripeCharges(req, res)
if (not req.user) or req.user.isAnonymous()
return @sendForbiddenError(res)
appleReceipt = req.body.apple?.rawReceipt
appleTransactionID = req.body.apple?.transactionID
appleLocalPrice = req.body.apple?.localPrice
@ -146,7 +146,7 @@ PaymentHandler = class PaymentHandler extends Handler
if validation.valid is false
@logPaymentError(req, 'Invalid apple payment object.')
return @sendBadInputError(res, validation.errors)
payment.save((err) =>
if err
@logPaymentError(req, 'Apple payment save error.'+err)
@ -170,24 +170,24 @@ PaymentHandler = class PaymentHandler extends Handler
# First, make sure we save the payment info as a Customer object, if we haven't already.
if token
customerID = req.user.get('stripe')?.customerID
if customerID
# old customer, new token. Save it.
stripe.customers.update customerID, { card: token }, (err, customer) =>
@beginStripePayment(req, res, timestamp, productID)
else
newCustomer = {
card: token
email: req.user.get('email')
metadata: { id: req.user._id + '', slug: req.user.get('slug') }
}
stripe.customers.create newCustomer, (err, customer) =>
if err
@logPaymentError(req, 'Stripe customer creation error. '+err)
return @sendDatabaseError(res, err)
stripeInfo = _.cloneDeep(req.user.get('stripe') ? {})
stripeInfo.customerID = customer.id
req.user.set('stripe', stripeInfo)
@ -223,7 +223,7 @@ PaymentHandler = class PaymentHandler extends Handler
((err, results) =>
if err
@logPaymentError(req, 'Stripe async load db error. '+err)
return @sendDatabaseError(res, err)
return @sendDatabaseError(res, err)
[payment, charge] = results
if not (payment or charge)
@ -285,7 +285,7 @@ PaymentHandler = class PaymentHandler extends Handler
timestamp: parseInt(charge.metadata.timestamp)
chargeID: charge.id
}
validation = @validateDocumentInput(payment.toObject())
if validation.valid is false
@logPaymentError(req, 'Invalid stripe payment object.')
@ -302,9 +302,9 @@ PaymentHandler = class PaymentHandler extends Handler
)
)
#- Confirm all Stripe charges are recorded on our server
checkStripeCharges: (req, res) ->
return @sendSuccess(res) unless customerID = req.user.get('stripe')?.customerID
async.parallel([
@ -366,7 +366,7 @@ PaymentHandler = class PaymentHandler extends Handler
sendPaymentHipChatMessage: (options) ->
try
message = "#{options.user?.get('name')} bought #{options.payment?.get('amount')} via #{options.payment?.get('service')}."
hipchat.sendHipChatMessage message
hipchat.sendHipChatMessage message, ['tower']
catch e
log.error "Couldn't send HipChat message on payment because of error: #{e}"

View file

@ -4,8 +4,6 @@ Handler = require '../commons/Handler'
{handlers} = require '../commons/mapping'
mongoose = require 'mongoose'
log = require 'winston'
sendwithus = require '../sendwithus'
hipchat = require '../hipchat'
PurchaseHandler = class PurchaseHandler extends Handler
modelClass: Purchase
@ -19,22 +17,22 @@ PurchaseHandler = class PurchaseHandler extends Handler
purchase.set 'recipient', req.user._id
purchase.set 'created', new Date().toISOString()
purchase
post: (req, res) ->
purchased = req.body.purchased
purchaser = req.user._id
purchasedOriginal = purchased?.original
Handler = require '../commons/Handler'
return @sendBadInputError(res) if not Handler.isID(purchasedOriginal)
collection = purchased?.collection
return @sendBadInputError(res) if not collection in @jsonSchema.properties.purchased.properties.collection.enum
handler = require('../' + handlers[collection])
criteria = { 'original': purchasedOriginal }
sort = { 'version.major': -1, 'version.minor': -1 }
handler.modelClass.findOne(criteria).sort(sort).exec (err, purchasedItem) =>
gemsOwned = req.user.get('earned')?.gems or 0
return @sendDatabaseError(res, err) if err
@ -51,7 +49,7 @@ PurchaseHandler = class PurchaseHandler extends Handler
if purchase
@addPurchaseToUser(req, res)
return @sendSuccess(res, @formatEntity(req, purchase))
else
super(req, res)

View file

@ -48,7 +48,7 @@ module.exports.setup = (app) ->
log.error(error.stack)
# TODO: Generally ignore this error: error: Error trying db method get route analytics.log.event from undefined: Error: Cannot find module '../undefined'
unless "#{parts}" in ['analytics.users.active']
hipchat.sendTowerHipChatMessage errorMessage
hipchat.sendHipChatMessage errorMessage, ['tower'], papertrail: true
errors.notFound(res, "Route #{req?.path} not found.")
getSchema = (req, res, moduleName) ->

View file

@ -249,7 +249,6 @@ UserHandler = class UserHandler extends Handler
sendOneTimeEmail: (req, res) ->
# TODO: should this API be somewhere else?
# TODO: hipchat tower success message shows up as a misleading PaperTrail error message
return @sendForbiddenError(res) unless req.user
email = req.query.email or req.body.email
type = req.query.type or req.body.type
@ -276,7 +275,7 @@ UserHandler = class UserHandler extends Handler
req.user.save (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, {result: 'success'})
hipchat.sendTowerHipChatMessage "#{req.user.get('name') or req.user.get('email')} just submitted subscribe modal parent email #{email}."
hipchat.sendHipChatMessage "#{req.user.get('name') or req.user.get('email')} just submitted subscribe modal parent email #{email}.", ['tower']
AnalyticsLogEvent.logEvent req.user, 'Sent one time email', email: email, type: type
agreeToCLA: (req, res) ->
@ -295,7 +294,7 @@ UserHandler = class UserHandler extends Handler
req.user.save (err) =>
return @sendDatabaseError(res, err) if err
@sendSuccess(res, {result: 'success'})
hipchat.sendHipChatMessage "#{req.body.githubUsername or req.user.get('name')} just signed the CLA."
hipchat.sendHipChatMessage "#{req.body.githubUsername or req.user.get('name')} just signed the CLA.", ['main']
avatar: (req, res, id) ->
@modelClass.findById(id).exec (err, document) =>

View file

@ -48,8 +48,11 @@ config.mail =
cronHandlerPublicIP: process.env.COCO_CRON_PUBLIC_IP or ''
cronHandlerPrivateIP: process.env.COCO_CRON_PRIVATE_IP or ''
config.hipchatAPIKey = process.env.COCO_HIPCHAT_API_KEY or ''
config.hipchatTowerAPIKey = process.env.COCO_HIPCHAT_TOWER_API_KEY or ''
config.hipchat =
main: process.env.COCO_HIPCHAT_API_KEY or ''
tower: process.env.COCO_HIPCHAT_TOWER_API_KEY or ''
artisans: process.env.COCO_HIPCHAT_ARTISANS_API_KEY or ''
config.queue =
accessKeyId: process.env.COCO_AWS_ACCESS_KEY_ID or ''
secretAccessKey: process.env.COCO_AWS_SECRET_ACCESS_KEY or ''