OSDN Git Service

change ns_users_config table data format to hierarchial
[newslash/newslash.git] / src / newslash_web / lib / Newslash / Plugin / CustomBoxes.pm
1 package Newslash::Plugin::CustomBoxes;
2 use Mojo::Base 'Mojolicious::Plugin';
3 use DateTime;
4 use DateTime::Format::MySQL;
5
6 sub register {
7     my ($self, $app, $conf) = @_;
8     $self->{app} = $app;
9
10     $app->helper(custom_boxes => sub { state $custom_boxes = $self });
11 }
12
13 sub query {
14     my ($self, $model, $c, @rest) = @_;
15     my $params = {@rest};
16
17     return $self->_poll($params) if $model eq "poll";
18     return $self->_mysite($params) if $model eq "mysite";
19     return $self->_thisday($params) if $model eq "thisday";
20     return;
21 }
22
23 sub app { return shift->{app}; }
24
25 sub _poll {
26     my ($self, $params) = @_;
27     my $polls = $self->app->model("polls");
28     my $polls_config = $self->app->config("Polls") || {};
29     my $limit_timestamp;
30
31     if ($polls_config->{TTL} && 
32         $polls_config->{TTL_unit} =~ m/\A(years|months|days|hours|minutes|seconds)\z/) {
33         my $base_dt = DateTime->now;
34         $base_dt->subtract($polls_config->{TTL_unit} => $polls_config->{TTL});
35
36         $limit_timestamp = DateTime::Format::MySQL->format_datetime($base_dt);
37     }
38
39     my $poll = $polls->select(order_by => { create_time => "DESC" },
40                               create_time => { gt => $limit_timestamp },
41                               limit => 1);
42     if ($poll) {
43         return $poll;
44     }
45     return;
46 }
47
48 sub _mysite {
49     my ($self, $params) = @_;
50     my $user = $params->{_user} || {};
51     my $my_links = $user->{config}->{ui}->{my_links};;
52     $my_links = "" if !defined $my_links;
53
54     return [$my_links];
55 }
56
57 sub _thisday {
58     my ($self, $params) = @_;
59     my $user = $params->{_user} || {};
60     my $offset_sec = $user->{config}->{ui}->{offset_sec} || 0;
61     my $stories = $self->app->model("stories");
62
63     my $now = DateTime->now;
64     $now->add(seconds => -$offset_sec) if $offset_sec;
65
66     my @items;
67     for (my $year = $now->year; $year > 2000; $year--) {
68         my $rs = $stories->select(year => $year,
69                                   month => $now->month,
70                                   day => $now->day,
71                                   offset_sec => $offset_sec,
72                                   order_by => { hits => "DESC" },
73                                   limit => 1,
74                                  );
75         if ($rs && @$rs) {
76             $rs->[0]->{year} = $year;
77             push @items, @$rs;
78         }
79     }
80     my @rs = sort { $b->{hits} <=> $a->{hits} } @items;
81
82     my $limit = $params->{limit} || 8;
83     if (@rs > $limit) {
84         @rs = @rs[0..$limit];
85     }
86     @rs = sort { $b->{year} <=> $a->{year} } @rs;
87
88     return \@rs;
89 }
90
91 1;