1use strict;
2use warnings;
3use HTTP::Session;
4use HTTP::Engine;
5use HTTP::Session::State::Cookie;
6use HTTP::Session::State::URI;
7use HTTP::Session::Store::Test;
8use HTTP::Session::State::MobileAttributeID;
9use HTTP::MobileAttribute plugins => [
10    qw/ IS /
11];
12use String::TT qw/tt strip/;
13
14my $store = HTTP::Session::Store::Test->new();
15
16&main; exit;
17
18sub main {
19    HTTP::Engine->new(
20        interface => {
21            module => 'ServerSimple',
22            args => {
23                port => 9999,
24            },
25            request_handler => \&request_handler,
26        }
27    )->run;
28}
29
30sub get_session_state {
31    my $req = shift;
32    my $ma = HTTP::MobileAttribute->new($req->headers);
33    my $gen_cookie_state = sub {
34        HTTP::Session::State::Cookie->new();
35    };
36    if ($ma->is_airh_phone || $ma->is_non_mobile) {
37        return $gen_cookie_state->();
38    } elsif ($ma->user_agent =~ /Google|Yahoo/) {
39        return $gen_cookie_state->();
40    } else {
41        if ($ma->user_id) {
42            return HTTP::Session::State::MobileAttributeID->new(
43                check_ip => 0,
44                mobile_attribute => $ma,
45            );
46        } else {
47            return HTTP::Session::State::URI->new();
48        }
49    }
50}
51
52sub get_session {
53    my $req = shift;
54    my $session = HTTP::Session->new(
55        state   => get_session_state($req),
56        store   => $store,
57        request => $req,
58    );
59}
60
61sub request_handler {
62    my $req     = shift;
63    my $session = get_session($req);
64    my $count = $session->get('count') || 0;
65    my $html = tt strip q{
66        <?xml version="1.0" encoding="utf-8"?>
67        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
68        <html xmlns="http://www.w3.org/1999/xhtml">
69            <head></head>
70            <body>
71                count is <a href="/">[% count |html %]</a><br />
72                state is [% session.state | html %]<br />
73                session id is [% session.session_id %].
74            </body>
75        </html>
76    };
77    $session->set( count => $count + 1 );
78    my $res = HTTP::Engine::Response->new(
79        status => 200,
80        body   => $html,
81    );
82    $res->header( 'Content-Type' => 'text/html' );
83    $session->response_filter($res);
84    return $res;
85}
86
87