1<?php
2/*
3 * vim:set softtabstop=4 shiftwidth=4 expandtab:
4 *
5 * LICENSE: GNU Affero General Public License, version 3 (AGPL-3.0-or-later)
6 * Copyright 2001 - 2020 Ampache.org
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU Affero General Public License for more details.
17 *
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
20 *
21 */
22declare(strict_types=0);
23
24namespace Ampache\Plugin;
25
26use Ampache\Config\AmpConfig;
27use Ampache\Repository\Model\Preference;
28use Ampache\Repository\Model\User;
29use Ampache\Module\Util\AmazonSearch;
30
31class AmpacheAmazon
32{
33    public $name        = 'Amazon';
34    public $categories  = 'metadata';
35    public $description = 'Amazon arts';
36    public $url         = 'http://www.amazon.com';
37    public $version     = '000001';
38    public $min_ampache = '370009';
39    public $max_ampache = '999999';
40
41    public $amazon_base_url;
42    public $amazon_max_results_pages;
43    public $amazon_developer_public_key;
44    public $amazon_developer_private_api_key;
45    public $amazon_developer_associate_tag;
46
47    /**
48     * Constructor
49     * This function does nothing
50     */
51    public function __construct()
52    {
53        $this->description = T_('Amazon art search');
54
55        return true;
56    }
57
58    /**
59     * install
60     * This is a required plugin function
61     */
62    public function install()
63    {
64        if (Preference::exists('amazon_base_url')) {
65            return false;
66        }
67
68        Preference::insert('amazon_base_url', T_('Amazon base url'), 'http://webservices.amazon.com', 75, 'string',
69            'plugins', $this->name);
70        Preference::insert('amazon_max_results_pages', T_('Amazon max results pages'), 1, 75, 'integer', 'plugins',
71            $this->name);
72        Preference::insert('amazon_developer_public_key', T_('Amazon Access Key ID'), '', 75, 'string', 'plugins',
73            $this->name);
74        Preference::insert('amazon_developer_private_api_key', T_('Amazon Secret Access Key'), '', 75, 'string',
75            'plugins', $this->name);
76        Preference::insert('amazon_developer_associate_tag', T_('Amazon associate tag'), '', 75, 'string', 'plugins',
77            $this->name);
78
79        return true;
80    } // install
81
82    /**
83     * uninstall
84     * This is a required plugin function
85     */
86    public function uninstall()
87    {
88        Preference::delete('amazon_base_url');
89        Preference::delete('amazon_max_results_pages');
90        Preference::delete('amazon_developer_public_key');
91        Preference::delete('amazon_developer_private_api_key');
92        Preference::delete('amazon_developer_associate_tag');
93
94        return true;
95    } // uninstall
96
97    /**
98     * load
99     * This is a required plugin function; here it populates the prefs we
100     * need for this object.
101     * @param User $user
102     * @return boolean
103     */
104    public function load($user)
105    {
106        $user->set_preferences();
107        $data = $user->prefs;
108        // load system when nothing is given
109        if (!strlen(trim($data['amazon_base_url'])) || !strlen(trim($data['amazon_developer_public_key'])) || !strlen(trim($data['amazon_developer_private_api_key'])) || !strlen(trim($data['amazon_max_results_pages'])) || !strlen(trim($data['amazon_developer_associate_tag']))) {
110            $data                                     = array();
111            $data['amazon_base_url']                  = Preference::get_by_user(-1, 'amazon_base_url');
112            $data['amazon_developer_public_key']      = Preference::get_by_user(-1, 'amazon_developer_public_key');
113            $data['amazon_developer_private_api_key'] = Preference::get_by_user(-1, 'amazon_developer_private_api_key');
114            $data['amazon_max_results_pages']         = Preference::get_by_user(-1, 'amazon_max_results_pages');
115            $data['amazon_developer_associate_tag']   = Preference::get_by_user(-1, 'amazon_developer_associate_tag');
116        }
117
118        if (strlen(trim($data['amazon_base_url']))) {
119            $this->amazon_base_url = trim($data['amazon_base_url']);
120        } else {
121            debug_event('amazon.plugin', 'No amazon base url, plugin skipped', 3);
122
123            return false;
124        }
125
126        if (strlen(trim($data['amazon_developer_public_key']))) {
127            $this->amazon_developer_public_key = trim($data['amazon_developer_public_key']);
128        } else {
129            debug_event('amazon.plugin', 'No amazon developer public key, plugin skipped', 3);
130
131            return false;
132        }
133
134        if (strlen(trim($data['amazon_developer_private_api_key']))) {
135            $this->amazon_developer_private_api_key = trim($data['amazon_developer_private_api_key']);
136        } else {
137            debug_event('amazon.plugin', 'No amazon developer private key, plugin skipped', 3);
138
139            return false;
140        }
141
142        if (strlen(trim($data['amazon_max_results_pages']))) {
143            $this->amazon_max_results_pages = (int)trim($data['amazon_max_results_pages']);
144        } else {
145            $this->amazon_max_results_pages = 1;
146        }
147
148        if (strlen(trim($data['amazon_developer_associate_tag']))) {
149            $this->amazon_developer_associate_tag = trim($data['amazon_developer_associate_tag']);
150        } else {
151            $this->amazon_developer_associate_tag = '';
152        }
153
154        return true;
155    } // load
156
157    /**
158     * gather_arts
159     * Returns arts for what we're passed in.
160     * @param string $type
161     * @param array $options
162     * @param integer $limit
163     * @return array
164     */
165    public function gather_arts($type, $options = array(), $limit = 5)
166    {
167        $images        = array();
168        $final_results = array();
169        $possible_keys = array(
170            'LargeImage',
171            'MediumImage',
172            'SmallImage'
173        );
174
175        $mediaType = ($type == 'album' || $type == 'artist') ? 'Music' : 'Video';
176
177        // Prevent the script from timing out
178        set_time_limit(0);
179
180        // Create the Search Object
181        $amazon = new AmazonSearch($this->amazon_developer_public_key, $this->amazon_developer_private_api_key,
182            $this->amazon_developer_associate_tag, $this->amazon_base_url);
183        if (AmpConfig::get('proxy_host') && AmpConfig::get('proxy_port')) {
184            $proxyhost = AmpConfig::get('proxy_host');
185            $proxyport = AmpConfig::get('proxy_port');
186            $proxyuser = AmpConfig::get('proxy_user');
187            $proxypass = AmpConfig::get('proxy_pass');
188            debug_event('amazon.plugin', 'setProxy', 5);
189            $amazon->setProxy($proxyhost, $proxyport, $proxyuser, $proxypass);
190        }
191
192        $search_results = array();
193
194        /* Set up the needed variables */
195        $max_pages_to_search = max($this->amazon_max_results_pages, $amazon->_default_results_pages);
196        // while we have pages to search
197        do {
198            $raw_results = $amazon->search(array('artist' => '', 'album' => '', 'keywords' => $options['keyword']),
199                $mediaType);
200            $total = count($raw_results) + count($search_results);
201
202            // If we've gotten more then we wanted
203            if ($limit && $total > $limit) {
204                $raw_results = array_slice($raw_results, 0, -($total - $limit), true);
205
206                debug_event('amazon.plugin', "Found $total, limit $limit; reducing and breaking from loop", 5);
207                // Merge the results and BREAK!
208                $search_results = array_merge($search_results, $raw_results);
209                break;
210            } // if limit defined
211
212            $search_results  = array_merge($search_results, $raw_results);
213            $pages_to_search = min($max_pages_to_search, $amazon->_maxPage);
214            debug_event('amazon.plugin',
215                "Searched results page " . ($amazon->_currentPage + 1) . "/" . $pages_to_search, 5);
216            $amazon->_currentPage++;
217        } while ($amazon->_currentPage < $pages_to_search);
218
219
220        // Only do the second search if the first actually returns something
221        if (count($search_results)) {
222            $final_results = $amazon->lookup($search_results);
223        }
224
225        /* Log this if we're doin debug */
226        debug_event('amazon.plugin', "Searched using " . $options['keyword'] . ", results: " . count($final_results),
227            5);
228
229        /* Foreach through what we've found */
230        foreach ($final_results as $result) {
231            $key = '';
232            /* Recurse through the images found */
233            foreach ($possible_keys as $k) {
234                if (strlen($result[$k])) {
235                    $key = $k;
236                    break;
237                }
238            } // foreach
239
240            if (!empty($key)) {
241                // Rudimentary image type detection, only JPG and GIF allowed.
242                if (substr($result[$key], -4) == '.jpg') {
243                    $mime = "image/jpeg";
244                } elseif (substr($result[$key], -4) == '.gif') {
245                    $mime = "image/gif";
246                } elseif (substr($result[$key], -4) == '.png') {
247                    $mime = "image/png";
248                } else {
249                    /* Just go to the next result */
250                    continue;
251                }
252
253                $data          = array();
254                $data['url']   = $result[$key];
255                $data['mime']  = $mime;
256                $data['title'] = $this->name;
257
258                $images[] = $data;
259
260                if (!empty($limit)) {
261                    if (count($images) >= $limit) {
262                        return $images;
263                    }
264                }
265            }
266        } // if we've got something
267
268        return $images;
269    } // gather_arts
270}
271