Advertisement
Guest User

Untitled

a guest
Jun 10th, 2014
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 4.64 KB | None | 0 0
  1. package controllers
  2.  
  3. import play.api._
  4. import play.api.mvc._
  5. import play.api.libs.ws.WS
  6. import scala.concurrent.Await
  7. import scala.concurrent.duration.Duration
  8. import models.Usuario
  9. import scala.concurrent._
  10. import play.api.libs.json.JsArray
  11. import play.api.libs.json.JsArray
  12. import play.api.libs.json.JsArray
  13. import models.Previsao
  14. import models.ResultadoPrevisao
  15. import models.GoogleAcesso
  16. import models.GoogleServer
  17. import models.GoogleLocal
  18. import play.api.mvc.Request
  19. import models.GoogleAcesso
  20.  
  21.  
  22.  
  23.  
  24. object Application extends Controller {
  25.  
  26.   implicit val context = scala.concurrent.ExecutionContext.Implicits.global
  27.   var usuarioP = new Usuario("", "");
  28.   val formate = new java.text.SimpleDateFormat("dd/MM/yyyy")
  29.  
  30.  
  31.   def index = Action { request =>
  32.     val isLocal = request.host == "localhost:9000" || request.host == "127.0.0.1:9000"
  33.     val loginUrl = if(isLocal) GoogleLocal.loginUrl else GoogleServer.loginUrl
  34.     val loginUrl2 : Option[String] = if(isLocal) Some(GoogleServer.loginUrl) else
  35.       None
  36.     Ok(views.html.index(loginUrl, loginUrl2)).discardingCookies("auth_token")
  37.    
  38.   }
  39.  
  40.   def googlecallback = Action.async{
  41.   request =>    
  42.     val optCode: Option[String] = request.getQueryString("code")
  43.     val isLocal = request.host == "localhost:9000" || request.host == "127.0.0.1:9000"
  44.  
  45.     val googleCredenciais : GoogleAcesso = if(request.host == "localhost:9000"|| request.host == "127.0.0.1:9000") GoogleLocal else GoogleServer
  46.  
  47.     optCode match {
  48.       case None => index.apply(request)
  49.       case Some(code) => {
  50.           val params = Map("code" -> Seq(code),
  51.                            "client_id" -> Seq(googleCredenciais.clientID),
  52.                            "client_secret" -> Seq(googleCredenciais.clientSecret),
  53.                            "redirect_uri" -> Seq(googleCredenciais.callbackURL),
  54.                            "grant_type" -> Seq("authorization_code"))
  55.  
  56.           val tokenRequest = WS.url("https://accounts.google.com/o/oauth2/token").post(params)
  57.           for {
  58.              resposta <- tokenRequest
  59.              respostaDados <- {
  60.                 val accessToken = (resposta.json \ "access_token").as[String]
  61.                 val url = s"https://www.googleapis.com/oauth2/v2/userinfo?access_token=$accessToken"
  62.                 WS.url(url).get
  63.              }
  64.           } yield {
  65.             val respJson = respostaDados.json
  66.             val usuario = new Usuario((respJson \ "picture").as[String], (respJson \ "name").as[String])
  67.             usuarioP = usuario;
  68.             Ok(views.html.pesquisa(usuario, Left("")))
  69.           }
  70.         }
  71.       }
  72.   }
  73.  
  74.  def pesquise(cidade: String, dia: String) = Action.async { request =>
  75.    
  76.             val diasMaisUm = dia.toInt + 1
  77.             val city = java.net.URLEncoder.encode(cidade, "UTF-8")
  78.             val url = s"http://api.openweathermap.org/data/2.5/forecast/daily/?q=$city&lang=pt&units=metric&cnt=$diasMaisUm&APPID=926700d7e887255b946acb938a6bdf20"
  79.  
  80.    
  81.             WS.url(url).get.map { resposta =>
  82.         val jsonResp = resposta.json
  83.         val cod: Int = (jsonResp \ "cod").as[String].toInt
  84.          cidade  match {
  85.           case t:String if(t.isEmpty()) => { Ok(views.html.pesquisa(usuarioP, Left("Preencha o campo cidade"), Option(cidade, dia))) }
  86.           case t:String if(!t.isEmpty()) => {
  87.      
  88.            
  89.           cod match{
  90.                                 case x: Int if(x != 200) => { Ok(views.html.pesquisa(usuarioP, Left("Cidade nao encontrada"), Option(cidade, dia))) }
  91.                                 case 200 => {
  92.        
  93.         val cidadeEncontrada: String = (jsonResp \ "city" \ "name").as[String]
  94.         val pais: String = (jsonResp \ "city" \ "country").as[String]
  95.         val lista = (jsonResp \ "list").asInstanceOf[JsArray].value.tail
  96.        
  97.        val previsoes = for(previsao <- lista)
  98.          yield {
  99.         val weather = (previsao \ "weather").asInstanceOf[JsArray](0)
  100.         val icon = (weather \ "icon").as[String]
  101.         val url_icon = s"http://openweathermap.org/img/w/$icon.png"
  102.          val data = formate.format(new java.util.Date(1000L * (previsao \ "dt").as[Long]))
  103.         val descricao = (weather \ "description").as[String]
  104.         val tempMin= (previsao \ "temp" \ "min").as[Float]
  105.         val tempMax = (previsao \ "temp" \ "max").as[Float]
  106.         val umidade = (previsao \ "humidity").as[Float]
  107.        
  108.         new Previsao(url_icon, data, descricao, tempMin, tempMax, umidade)
  109.        }
  110.        
  111.        val resultadoPesquisa = new ResultadoPrevisao(cidadeEncontrada, pais, previsoes.toList)
  112.        
  113.        
  114.         Ok(views.html.pesquisa(usuarioP, Right(resultadoPesquisa)))
  115.                                         }
  116.                                 }
  117.                 }
  118.         }
  119.         }
  120.              
  121.  }
  122. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement