Net-WURFL-ScientiaMobile

 view release on metacpan or  search on metacpan

lib/Net/WURFL/ScientiaMobile.pm  view on Meta::CPAN

        if (exists $exceptions_by_status{$response->message}) {
            ("Net::WURFL::ScientiaMobile::Exception::" . $exceptions_by_status{$response->message})->throw
                (error => $response->status_line, response => $response);
        } else {
            Net::WURFL::ScientiaMobile::Exception::HTTP->throw(
                error    => "Unable to contact server: " . $response->status_line,
                response => $response,
            );
        }
    }
    try {
        $self->_json(decode_json($response->content));
    } catch {
        Net::WURFL::ScientiaMobile::Exception::HTTP->throw(
            error    => "Unable to parse JSON response from server: $_",
            response => $response,
            code     => ERROR_BAD_RESPONSE,
        );
    };
    
    $self->_errors($self->_json->{errors});
    $self->_api_version($self->_json->{apiVersion} || '');
    $self->_loaded_date($self->_json->{mtime} || '');
    $self->capabilities->{id} = $self->_json->{id} || '';
    $self->capabilities->{$_} = $self->_json->{capabilities}{$_}
        for keys %{$self->_json->{capabilities}};
}

sub getLoadedDate {
    my $self = shift;
    $self->_loaded_date($self->cache->getMtime) unless $self->_loaded_date;
    return $self->_loaded_date;
}

sub _validateCache {
    my $self = shift;
    
    my $cache_mtime = $self->cache->getMtime;
    if (!$cache_mtime || $cache_mtime != $self->_loaded_date) {
        $self->cache->setMtime($self->_loaded_date);
        $self->cache->purge if $self->auto_purge;
    }
}

=head1 NAME

Net::WURFL::ScientiaMobile - Client for the ScientiaMobile cloud webservice

=head1 SYNOPSIS

    use Net::WURFL::ScientiaMobile;
    
    my $scientiamobile = Net::WURFL::ScientiaMobile->new(
        api_key => '...',
    );
    
    # process this HTTP request
    $scientiamobile->detectDevice($env);
    
    # check if the device is mobile
    if ($scientiamobile->getDeviceCapability('ux_full_desktop')) {
        print "This is a desktop browser.";
    }

=head1 DESCRIPTION

The WURFL Cloud Service by ScientiaMobile, Inc. is a cloud-based
mobile device detection service that can quickly and accurately
detect over 500 capabilities of visiting devices.  It can differentiate
between portable mobile devices, desktop devices, SmartTVs and any 
other types of devices that have a web browser.

This is the Perl Client for accessing the WURFL Cloud Service, and
it requires a free or paid WURFL Cloud account from ScientiaMobile:
L<http://www.scientiamobile.com/cloud>

This module analyzes the C<$env> data structure of your incoming HTTP request and extracts
the device identifier string(s). It then queries the WURFL Cloud Service or the local cache 
(if any is configured) to get the device capabilities.

If you use a PSGI-compatible web framework (such as L<Catalyst>, L<Dancer>, L<Mojo> and others),
the easiest way to use this client is to apply the L<Plack::Middleware::WURFL::ScientiaMobile> 
module to your application. It will provide the device capabilities to your request handlers
automatically with minimal programming effort.

=head1 CONSTRUCTOR

The C<new> constructor accepts the following named arguments.

=head2 api_key

Required. The full API key provided by the WURFL Cloud Service.

=head2 cache

A L<Net::WURFL::ScientiaMobile::Cache> object (or class name as string). If none is provided, 
no caching will happen.

=head2 http_timeout

The timeout in milliseconds to wait for the WURFL Cloud request to complete. Defaults to 1000.

=head2 compression

Boolean flag to enable/disable compression for querying the WURFL Cloud Service. 
Using compression can increase CPU usage in very high traffic environments, but will decrease 
network traffic and latency. Defaults to true.

=head2 auto_purge

If true, the entire cache (e.g. memcache, etc.) will be cleared if the WURFL Cloud Service has
been updated. This option should not be enabled for production use since it will result in a
massive cache purge, which will result in higher latency lookups. Defaults to false.

=head2 report_interval

The interval in seconds that after which API will report its performance.

=head2 wcloud_servers

WURFL Cloud servers to use for uncached requests. The "weight" field can contain any positive 
number, the weights are relative to each other. Use this if you want to override the built-in 
server list. For example:

    my $scientiamobile = Net::WURFL::ScientiaMobile->new(
        api_key => '...',
        wcloud_servers => {
            # nickname => [ host => weight ],
            'wurfl_cloud' => [ 'api.wurflcloud.com' => 80 ],
        },
    );

=head1 METHODS FOR CAPABILITY DETECTION

=head2 detectDevice

    $scientiamobile->detectDevice($env);
    $scientiamobile->detectDevice($env, ['ux_full_desktop', 'brand_name']);

Get the requested capabilities from the WURFL Cloud for the given HTTP Request. If the second
argument is not provided, all available capabilities will be fetched.

Refer to the documentation of your web framework to learn how to access C<$env>. For example,
L<Catalyst> provides it in C<$ctx-E<gt>request-E<gt>env>, L<Dancer> provides it in 
C<request-E<gt>env>, L<Mojo> provides it in C<$self-E<gt>tx-E<gt>req-E<gt>env>.

Instead of the C<$env> hashref you can also supply a L<HTTP::Headers> or a L<Mojo::Headers> object.
This is handy when you're not running in a PSGI environment and your web server doesn't supply
a PSGI-compatible C<$env> hashref (for example, when running C<./myapp.pl daemon> in a 
L<Mojolicious::Lite> application. Note that the L<Dancer> built-in web server still provides
a PSGI-compatible C<$env>).

=head2 getDeviceCapability

    my $is_wireless = $scientiamobile->getDeviceCapability('is_wireless_device');

Returns the value of the requested capability. If the capability does not exist, returns undef.

=head2 capabilities

Flat capabilities hashref, thus containing I<'key' => 'value'> pairs. 
Since it is 'flattened', there are no groups in this array, just individual capabilities.

=head1 METHODS FOR SERVERS POOL MANAGEMENT

=head2 addCloudServer

    $scientiamobile->addCloudServer('wurfl_cloud', 'api.wurflcloud.com', 80);

Adds the specified WURFL Cloud Server. The last argument is the server's weight. It specifies 
the chances that this server will be chosen over the other servers in the pool. This number is 
relative to the other servers' weights.

=head2 clearServers

    $scientiamobile->clearServers;

Removes the WURFL Cloud Servers.

=head2 getWeightedServer

    my $server = $scientiamobile->getWeightedServer;

Uses a weighted-random algorithm to chose a server from the pool. It returns an arrayref whose 
first argument is the host and the second argument is the weight.
You don't need to call this method usually. It is called internally when the client prepares the
request to the WURFL Cloud Service.

=head1 UTILITY METHODS

=head2 getUserAgent

    my $user_agent = $scientiamobile->getUserAgent($env);

Reads the user agent string from C<$env>.

=head2 getLoadedDate



( run in 1.549 second using v1.01-cache-2.11-cpan-b16cb0d3907 )