Created
August 6, 2011 14:38
-
-
Save gre/1129391 to your computer and use it in GitHub Desktop.
Using Pusher API with Play framework in scala for publishing events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Implementing the publishing Pusher REST API | |
| // @see http://pusher.com/docs/rest_api | |
| object Pusher { | |
| val appId = "your_pusher_app_id" | |
| val key = "your_pusher_key" | |
| val secret = "your_pusher_secret" | |
| import play.libs.WS | |
| import play.libs.ws.FunctionalWebResponse._ | |
| import java.security.MessageDigest | |
| import play.libs.WS.HttpResponse | |
| import java.math.BigInteger | |
| import javax.crypto.Mac | |
| import javax.crypto.spec.SecretKeySpec | |
| def byteArrayToString(data: Array[Byte]) = { | |
| val bigInteger = new BigInteger(1,data); | |
| var hash = bigInteger.toString(16); | |
| while(hash.length() < 32 ){ | |
| hash = "0" + hash; | |
| } | |
| hash; | |
| } | |
| def md5(s: String):String = { | |
| val messageDigest = MessageDigest.getInstance("MD5"); | |
| val digest = messageDigest.digest(s.getBytes("US-ASCII")); | |
| byteArrayToString(digest); | |
| } | |
| def sha256(s: String, secret: String):String = { | |
| val signingKey = new SecretKeySpec( secret.getBytes(), "HmacSHA256"); | |
| val mac = Mac.getInstance("HmacSHA256"); | |
| mac.init(signingKey); | |
| var digest = mac.doFinal(s.getBytes("UTF-8")); | |
| digest = mac.doFinal(s.getBytes()); | |
| val bigInteger = new BigInteger(1,digest); | |
| String.format("%0" + (digest.length << 1) + "x", bigInteger); | |
| } | |
| def trigger(channel:String, event:String, message:String):HttpResponse = { | |
| 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)) | |
| ).sort( (a,b) => a._1 < b._1 ).map( o => o._1+"="+WS.encode(o._2.toString) ).mkString("&"); | |
| val signature = sha256( List("POST", url, params).mkString("\n"), secret ); | |
| WS.url("http://"+domain+url+"?"+params+"&auth_signature="+WS.encode(signature)).body(body).post() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment