Skip to content

Instantly share code, notes, and snippets.

@aaronlifton3
Created March 29, 2013 00:45
Show Gist options
  • Save aaronlifton3/5267973 to your computer and use it in GitHub Desktop.
Save aaronlifton3/5267973 to your computer and use it in GitHub Desktop.
Scala 2.10 + Play 2.1 + Pusher
class Pusher {
val appId = Play.configuration.getString("pusher.appId")
val key = Play.configuration.getString("pusher.key")
val secret = Play.configuration.getString("pusher.secret")
import java.security.MessageDigest
import java.math.BigInteger
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
def trigger(channel:String, event:String, message:String): ws.Response = {
val domain = "api.pusherapp.com"
val url = "/apps/"+appId+"/channels/"+channel+"/events";
val body = message
val params = List(
("auth_key", key),
("auth_timestamp", (new Date().getTime()/1000) toInt ),
("auth_version", "1.0"),
("name", event),
("body_md5", md5(body))
).sortWith((a,b) => a._1 < b._1 ).map( o => o._1+"="+URLEncoder.encode(o._2.toString)).mkString("&");
val signature = sha256(List("POST", url, params).mkString("\n"), secret.get);
val signatureEncoded = URLEncoder.encode(signature, "UTF-8");
implicit val timeout = Timeout(5 seconds)
val f = WS.url("http://"+domain+url+"?"+params+"&auth_signature="+signatureEncoded).post(body)
Await.result(f,timeout.duration)
}
def byteArrayToString(data: Array[Byte]) = {
val hash = new BigInteger(1, data).toString(16);
"0"*(32-hash.length) + hash
}
def md5(s: String):String = byteArrayToString(MessageDigest.getInstance("MD5").digest(s.getBytes("US-ASCII")));
def sha256(s: String, secret: String):String = {
val mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec( secret.getBytes(), "HmacSHA256"));
val digest = mac.doFinal(s.getBytes());
String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest));
}
}
object WebSockets extends Pusher {
val channel = "test_channel" // Play.configuration.getString("websockets.channel")
def trigger(event:String, message:String): ws.Response = trigger(channel, event, message)
}
object Test {
def test = WebSockets.trigger("hello", "{ \"message\": \"test\" }")
}
object Application extends Controller {
def testPusher = Action {
Test.test
Ok("lol internet")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment