about summary refs log tree commit diff stats
path: root/lib/UnsplashSource.pm
blob: 7704dc84707a1dd169167f580df8479322658ab7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/perl

package UnsplashSource;

use strict;
use warnings;

use URI;
use HTTP::Tiny;
use Carp qw( croak carp );

my $api = "https://source.unsplash.com";
my $http = HTTP::Tiny->new(
    agent => "crux - UnsplashSource.pm - HTTP::Tiny",
    max_redirect => 0,
    verify_SSL => 1,
    timeout => 60,

);

sub get {
    my ( %options ) = @_;

    if ( $options{daily} or $options{weekly} ) {
        return fixed( %options );
    } elsif ( $options{user} ) {
        return user_random( %options );
    } elsif ( ( scalar @{$options{search}} > 0 )
                  or $options{featured} ) {
        return random_search( %options );
    } elsif ( $options{collection_id} ) {
        return collection( %options );
    } else {
        return get_random( %options );
    }
}

sub get_random {
    my ( %options ) = @_;
    my $url = "$api/random/$options{resolution}";
    return $http->head($url);
}

sub random_search {
    my ( %options ) = @_;

    my $url = URI->new($api);

    my @segments;
    push @segments, "featured" if $options{featured};
    push @segments, $options{resolution};
    $url->path_segments( @segments );

    $url->query_keywords( \@{$options{search}} );

    return $http->head($url);
}

sub user_random {
    my ( %options ) = @_;
    my $url = "$api/user/$options{user}/";
    $url .= "likes/" if $options{user_likes};
    $url .= $options{resolution};
    return $http->head($url);
}

sub collection {
    my ( %options ) = @_;
    my $url = "$api/collection/$options{collection_id}/";
    $url .= $options{resolution};
    return $http->head($url);
}

sub fixed {
    my ( %options ) = @_;
    croak "Cannot use daily & weekly together"
        if $options{daily} and $options{weekly};
    my $url = "$api/";
    $url .= "user/$options{user}/" if $options{user};
    $url .= "daily/" if $options{daily};
    $url .= "weekly/" if $options{weekly};
    $url .= "?";
    $url .= "$_," foreach ( @{$options{search}});
    return $http->head($url);
}

1;