Created
January 4, 2011 05:57
-
-
Save hoffrocket/764454 to your computer and use it in GitHub Desktop.
flickr api utility
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
import _root_.net.liftweb.util._ | |
import _root_.net.liftweb.json._ | |
import _root_.net.liftweb.common._ | |
import _root_.java.net.{HttpURLConnection, URL, URLEncoder} | |
import JsonAST._ | |
import JsonDSL._ | |
import JsonParser._ | |
import Helpers._ | |
//flickr uses some proprietary authentication mechanism instead of oauth | |
object Flickr { | |
def key = Props.get("flickr.key","") | |
def secret = Props.get("flickr.secret","") | |
val BASE_URL:String = "http://api.flickr.com/services/rest/" | |
def md5hex(in:String) =Helpers.hexEncode(Helpers.md5(in.getBytes("UTF-8"))) | |
def toQuery(paramMap:Map[String,String]) = "?" + (paramMap + apiKeyParam).map(p=> p._1 + "=" + p._2).mkString("&") | |
def signQuery(params:Map[String,String], auth: Box[String]) = { | |
val withAuthToken = auth.map(t=> params + ("auth_token" -> t)) openOr params | |
toQuery(withAuthToken + ("api_sig" -> md5hex(secret + (withAuthToken + apiKeyParam).toList.map(p=>p._1+p._2).sort(_ < _).mkString))) | |
} | |
def apiKeyParam = "api_key" -> key | |
def doRequest(params:Map[String,String], sign:Boolean, authToken:Box[String]):JValue = { | |
val withJsonParams = params + ("nojsoncallback"->"1") + ("format" -> "json") | |
val urlString = BASE_URL + (if (sign){ | |
signQuery(withJsonParams, authToken) | |
} else toQuery(withJsonParams)) | |
new URL(urlString).openConnection match { | |
case conn: HttpURLConnection => { | |
conn.setRequestMethod("GET") | |
conn.connect | |
import org.apache.commons.io.IOUtils | |
val str = IOUtils.toString(conn.getInputStream,"UTF-8") | |
println(str) | |
parse(str) | |
} | |
} | |
} | |
def authUrl:String = "http://flickr.com/services/auth/" + signQuery(Map("perms"->"read"),Empty) | |
def callMethod(method:String, sign:Boolean, auth:Box[String], params:Map[String,String]):JValue = { | |
doRequest(params + ("method" -> method), sign, auth) | |
} | |
case class User(nsid:String, username:String,fullname:String) | |
case class Auth(token:String, user:User) | |
def getToken(frob:String):Box[Auth] = { | |
implicit val formats = DefaultFormats | |
val json = callMethod("flickr.auth.getToken", true, Empty, Map("frob" -> frob)) | |
val auth = json\"auth" | |
val results = for (JString(token) <- (auth\"token"\"_content"); | |
JString(username) <- (auth\"user"\"username"); | |
JString(nsid) <- (auth\"user"\"nsid"); | |
JString(fullname) <- (auth\"user"\"fullname")) yield Auth(token, User(nsid, username, fullname)) | |
results.firstOption | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment