The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#!/usr/bin/perl

# PODNAME: koha-coce-url
# ABSTRACT: Generate a JSON structure of Cover url via Coce

use Modern::Perl;
use utf8;
use Pod::Usage;
use C4::Context;
use C4::Biblio;
use MARC::Moose::Record;
use YAML;
use LWP;
use LWP::UserAgent;
use JSON;
use Business::ISBN;


binmode(STDOUT, ":encoding(utf8)");



sub usage {
    pod2usage( -verbose => 2 );
    exit;
} 


sub create_json_data {
    my ($query, $coce, $size) = @_;

    $size = "_SL" . $size . "_";
    my @bibs =
        map { $_->[0] }
        @{C4::Context->dbh->selectall_arrayref($query)};

    my $is_unimarc = C4::Context->preference('marcflavour') eq 'UNIMARC';
    my $tag = {
        isbn  => $is_unimarc ? '010' : '020',
        title => $is_unimarc ? '200' : '245',
    };

    my %record_per_isbn;
    for my $biblionumber (@bibs) {
        my $record = GetMarcBiblio($biblionumber);
        next unless $record;
        $record = MARC::Moose::Record::new_from($record, 'Legacy');
        my $field = $record->field($tag->{isbn});
        next unless $field;
        my $isbn = $field->subfield('a');
        next unless $isbn;
        # Clean ISBN
        $isbn = Business::ISBN->new($isbn);
        next unless $isbn;
        next unless $isbn->is_valid;
        $isbn = $isbn->isbn;
        my $title = $record->field($tag->{title});
        next unless $title;
        $title = $is_unimarc
            ? $title->subfield('a')
            : join(' ', map { $_->[1] } @{$title->subf});
        $record_per_isbn{$isbn} = [ $biblionumber, $title ];
    }

    my $url = $coce . "/cover?provider=aws&id=" . join(',', keys %record_per_isbn);
    my $ua = LWP::UserAgent->new(
        agent   => "Koha::Contrib::Tamil/1.0",
        timeout => 300,
    );
    my $req = HTTP::Request->new(GET => $url);
    my $res = $ua->request($req);
    if ( ! $res->is_success ) {
        say "ERREUR: $url";
        say $res->status_line;
        exit;
    }
    my $content = $res->content;
    my $image_per_isbn = from_json($content);
    my @ret;
    while ( my ($isbn, $image) =  each %$image_per_isbn ) {
        my $infos = $record_per_isbn{$isbn};
        next unless $infos;
        $image =~ s/_SL160_/$size/;
        push @$infos, $image;
        push  @ret, $infos;
    }
    say to_json(\@ret, {pretty => 1});
}



usage() unless @ARGV == 3;
create_json_data(@ARGV);

__END__

=pod

=encoding UTF-8

=head1 NAME

koha-coce-url - Generate a JSON structure of Cover url via Coce

=head1 VERSION

version 0.051

=head1 DESCRIPTION

This script generate a JSON array of Cover URLs for biblio records. For example:

 [
  [
    16618,
    "Responsable marketing",
    "https://images-na.ssl-images-amazon.com/images/I/41UUr1J8tqL._SL300_.jpg"
  ],
  [
    16907,
    "Les autruches ne mettent plus la tête dans le sable",
    "https://images-na.ssl-images-amazon.com/images/I/41ZJC0OjcbL._SL300_.jpg"
  ],
  [
    17844,
    "La valeur des idées",
    "https://images-na.ssl-images-amazon.com/images/I/41AVP5yuTnL._SL300_.jpg"
  ]
 ]

The script need three parameters:

=over

=item *

A query returning a list of biblionumber. For example:

  SELECT biblionumber
  FROM biblioitems
  WHERE isbn <> ""
  ORDER BY biblionumber DESC
  LIMIT 100

=item *

Address of a Coce server.

=item *

Size of images

=back

=head1 SYNOPSYS

 koha-coce-url "select biblionumber from biblio limit 100" 10 http:://coce.server 300

=head1 COPYRIGHT AND LICENSE

Copyright 2016 by Tamil, s.a.r.l.

L<http://www.tamil.fr>

This library is free software; you can redistribute it and/or modify it under
the same terms as Perl 5 itself.

=head1 AUTHOR

Frédéric Demians <f.demians@tamil.fr>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2017 by Fréderic Démians.

This is free software, licensed under:

  The GNU General Public License, Version 3, June 2007

=cut