Skip to content

Instantly share code, notes, and snippets.

@noelwelsh
Created January 22, 2013 20:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noelwelsh/4598180 to your computer and use it in GitHub Desktop.
Save noelwelsh/4598180 to your computer and use it in GitHub Desktop.
Mixpanel API client for Play 2.0
package myna
package app
import bigtop.util.Uuid
import myna.model.external.User
import myna.util.Base64
import play.api.libs.ws._
import play.api.libs.json._
import play.api.libs.concurrent.Promise
import play.api.mvc.Request
import scala.collection.immutable.Map
object Mixpanel {
val token = "zomgsecret!"
val url = "http://api.mixpanel.com/"
val ws = WS.url(url)
/** user is either an optional tracking code or the user if they're logged in */
def track(event: String, properties: Map[String, String] = Map(), user: Either[Option[Uuid], User] = Left(None)): Unit = {
// Only track events in production:
if(Configuration.api.mode.isProduction) {
val fullProperties = (user match {
case Left(None) =>
properties
case Left(Some(code)) =>
properties + ("distinct_id" -> code.toString)
case Right(user) =>
properties + ("distinct_id" -> user.trackingCode.toString) + ("email" -> user.email.toString)
}) + ("token" -> token)
//"ip" -> request.remoteAddress, // Requires Play 2.0.2+
val data: JsValue =
Json.toJson(
Map(
"event" -> Json.toJson(event),
"properties" -> Json.toJson(fullProperties)
)
)
val content: Array[Byte] =
Base64.encode(Json.stringify(data)).toBytes
val queryString = "data=" + new String(content)
WS.url(url + "track/?" + queryString).get()
}
}
implicit object UserWriter extends Writes[User] {
def writes(user: User): JsValue = {
Json.toJson(
Map(
"$set" ->
Json.toJson(
Map(
("$first_name" -> user.firstName),
("$last_name" -> user.lastName),
("$email" -> user.email.toString)
)
),
"$token" -> Json.toJson(token),
"$distinct_id" -> Json.toJson(user.trackingCode.toString)
)
)
}
}
def create(user: User): Promise[Response] = {
val data = Json.toJson(user)
val content: Array[Byte] =
Base64.encode(Json.stringify(data)).toBytes
val queryString = "data=" + new String(content)
WS.url(url + "engage/?" + queryString).get()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment