regexscalaplayframeworkuser-agentplayframework-2.1

Parse out user agent the scala way in Play2 application


I'm trying to write a helper method for my Controllers to determine if the device is mobile so that I can load the appropriate template. This is what I got so far:

def isMobile[A](implicit request: Request[A]): Boolean = {
    request.headers.get("User-Agent").exists(agent =>
      if (agent.matches("/(iPhone|webOS|iPod|Android|BlackBerry|mobile|SAMSUNG|IEMobile|OperaMobi)/"))
        true
      else false)
  }

This will not work since the user agent do not only provide us with the device but a string containing a whole lot of nice stuff eg:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25

What is the proper way of parsing this info? Should I create a dictionary with user agents and see if the current string contains one of them? Create a major crazy regexp that matches different user-agents? Maybe there is some scala library that I haven't found that do this?

Thank you!


Solution

  • One way to do this is of course, as Sniffer suggested, do a partial match with unanchored like this:

    val Pattern = "(iPhone|webOS|iPod|Android|BlackBerry|mobile|SAMSUNG|IEMobile|OperaMobi)".r.unanchored
    
      def isMobile[A](implicit request: Request[A]): Boolean = {
        request.headers.get("User-Agent").exists(agent => {
          agent match {
            case Pattern(a) => true
            case _ => false
          }
        })
      }
    

    Maybe there is some other better way?