-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathGoodReads.php
More file actions
425 lines (398 loc) · 11.7 KB
/
Copy pathGoodReads.php
File metadata and controls
425 lines (398 loc) · 11.7 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
<?php
/**
* A quick-and-dirty API class for GoodReads.
*
* Methods implemented:
* - author.show (getAuthor)
* - author.books (getBooksByAuthor)
* - book.show (getBook)
* - book.show_by_isbn (getBookByISBN)
* - book.title (getBookByTitle)
* - reviews.list (getShelf|getLatestRead|getAllBooks)
* - review.show (getReview)
* - user.show (getUser|getUserByUsername)
*
* @author danielgwood <github.com/danielgwood>
*/
class GoodReads
{
/**
* Root URL of the API (no trailing slash).
*/
const API_URL = 'https://www.goodreads.com';
/**
* How long do cached items live for? (seconds)
*/
const CACHE_TTL = 3600;
/**
* How long to sleep between requests to prevent flooding/TOS violation (milliseconds).
*/
const SLEEP_BETWEEN_REQUESTS = 1000;
/**
* @var string Your API key.
*/
protected $apiKey = '';
/**
* @var string Cache directory (defaults to ./cache).
*/
protected $cacheDir = 'cache';
/**
* @var integer When was the last request made?
*/
protected $lastRequestTime = 0;
/**
* Initialise the API wrapper instance.
*
* @param string $apiKey
* @param string $cacheDirectory
*/
public function __construct($apiKey, $cacheDirectory = '')
{
$this->apiKey = (string)$apiKey;
$this->cacheDir = (string)$cacheDirectory;
$this->clearExpiredCache();
}
/**
* Get details for a given author.
*
* @param integer $authorId
* @return array
*/
public function getAuthor($authorId)
{
return $this->request(
'author/show',
array(
'key' => $this->apiKey,
'id' => (int)$authorId
)
);
}
/**
* Get books by a given author.
*
* @param integer $authorId
* @param integer $page Optional page offset, 1-N
* @return array
*/
public function getBooksByAuthor($authorId, $page = 1)
{
return $this->request(
'author/list',
array(
'key' => $this->apiKey,
'id' => (int)$authorId,
'page' => (int)$page
)
);
}
/**
* Get details for a given book.
*
* @param integer $bookId
* @return array
*/
public function getBook($bookId)
{
return $this->request(
'book/show',
array(
'key' => $this->apiKey,
'id' => (int)$bookId
)
);
}
/**
* Get details for a given book by ISBN.
*
* @param string $isbn
* @return array
*/
public function getBookByISBN($isbn)
{
return $this->request(
'book/isbn/' . urlencode($isbn),
array(
'key' => $this->apiKey
)
);
}
/**
* Get details for a given book by title.
*
* @param string $title
* @param string $author Optionally provide this for more accuracy.
* @return array
*/
public function getBookByTitle($title, $author = '')
{
return $this->request(
'book/title',
array(
'key' => $this->apiKey,
'title' => urlencode($title),
'author' => $author
)
);
}
/**
* Get details for a given user.
*
* @param integer $userId
* @return array
*/
public function getUser($userId)
{
return $this->request(
'user/show',
array(
'key' => $this->apiKey,
'id' => (int)$userId
)
);
}
/**
* Get details for a given user by username.
*
* @param string $username
* @return array
*/
public function getUserByUsername($username)
{
return $this->request(
'user/show',
array(
'key' => $this->apiKey,
'username' => $username
)
);
}
/**
* Get details for of a particular review
*
* @param integer $reviewId
* @param integer $page Optional page number of comments, 1-N
* @return array
*/
public function getReview($reviewId, $page = 1)
{
return $this->request(
'review/show',
array(
'key' => $this->apiKey,
'id' => (int)$reviewId,
'page' => (int)$page
)
);
}
/**
* Get a shelf for a given user.
*
* @param integer $userId
* @param string $shelf read|currently-reading|to-read etc
* @param string $sort title|author|rating|year_pub|date_pub|date_read|date_added|avg_rating etc
* @param integer $limit 1-200
* @param integer $page 1-N
* @return array
*/
public function getShelf($userId, $shelf, $sort = 'title', $limit = 100, $page = 1)
{
return $this->request(
'review/list',
array(
'v' => 2,
'format' => 'xml', // :( GoodReads still doesn't support JSON for this endpoint
'key' => $this->apiKey,
'id' => (int)$userId,
'shelf' => $shelf,
'sort' => $sort,
'page' => $page,
'per_page' => $limit
)
);
}
/**
* Get all books for a given user.
*
* @param integer $userId
* @param string $sort title|author|rating|year_pub|date_pub|date_read|date_added|avg_rating etc
* @param integer $limit 1-200
* @param integer $page 1-N
* @return array
*/
public function getAllBooks($userId, $sort = 'title', $limit = 100, $page = 1)
{
return $this->request(
'review/list',
array(
'v' => 2,
'format' => 'xml', // :( GoodReads still doesn't support JSON for this endpoint
'key' => $this->apiKey,
'id' => (int)$userId,
'sort' => $sort,
'page' => $page,
'per_page' => $limit
)
);
}
/**
* Get the details of an author.
*
* @param integer $authorId
* @return array
*/
public function showAuthor($authorId)
{
return $this->getAuthor($authorId);
}
/**
* Get the details of a user.
*
* @param integer $userId
* @return array
*/
public function showUser($userId)
{
return $this->getUser($userId);
}
/**
* Get the latest books read for a given user.
*
* @param integer $userId
* @param string $sort title|author|rating|year_pub|date_pub|date_read|date_added|avg_rating etc
* @param integer $limit 1-200
* @param integer $page 1-N
* @return array
*/
public function getLatestReads($userId, $sort = 'date_read', $limit = 100, $page = 1)
{
return $this->getShelf($userId, 'read', $sort, $limit, $page);
}
/**
* Makes requests to the API.
*
* @param string $endpoint A GoodReads API function name
* @param array $params Optional parameters
* @return array
* @throws Exception If it didn't work
*/
private function request($endpoint, array $params = array())
{
// Check the cache
$cachedData = $this->getCache($endpoint, $params);
if($cachedData !== false) {
return $cachedData;
}
// Prepare the URL and headers
$url = self::API_URL .'/'. $endpoint . '?' . ((!empty($params)) ? http_build_query($params, '', '&') : '');
$headers = array(
'Accept: application/xml',
);
if(isset($params['format']) && $params['format'] === 'json') {
$headers = array(
'Accept: application/json',
);
}
// Execute via CURL
$response = null;
if(extension_loaded('curl')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
usleep(self::SLEEP_BETWEEN_REQUESTS);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
$errorNumber = curl_errno($ch);
$errorMessage = curl_error($ch);
if($errorNumber > 0)
{
throw new Exception('Method failed: ' . $endpoint . ': ' . $errorMessage);
}
curl_close($ch);
} else {
throw new Exception('CURL library not loaded!');
}
// Try and cadge the results into a half-decent array
$results = null;
if(isset($params['format']) && $params['format'] === 'json') {
$results = json_decode($body);
} else {
$results = json_decode(json_encode((array)simplexml_load_string($body, 'SimpleXMLElement', LIBXML_NOCDATA)), 1); // I know, I'm a terrible human being
}
if($results !== null) {
// Cache & return results
$this->addCache($endpoint, $params, $results);
return $results;
} else {
throw new Exception('Server error on "' . $url . '": ' . $response);
}
}
/**
* Attempt to get something from the cache.
*
* @param string $endpoint
* @param array $params
* @return array|false
*/
private function getCache($endpoint, array $params = array())
{
if (file_exists($this->cacheDir) && is_writable($this->cacheDir)) {
$filename = str_replace('/', '_', $endpoint) . '-' . md5(serialize($params));
$filename = $this->cacheDir . '/' . $filename;
if(file_exists($filename)) {
$contents = unserialize(file_get_contents($filename));
if(!is_array($contents) || $contents['cache_expiry'] <= time()) {
unlink($filename);
return false;
} else {
unset($contents['cache_expiry']);
return $contents;
}
}
return false;
} else {
throw new Exception('Cache directory not writable.');
}
}
/**
* Add an item to the cache.
*
* @param string $endpoint
* @param array $params
* @param array $contents
* @return boolean
*/
private function addCache($endpoint, array $params = array(), array $contents)
{
if (file_exists($this->cacheDir) && is_writable($this->cacheDir)) {
$filename = str_replace('/', '_', $endpoint) . '-' . md5(serialize($params));
$filename = $this->cacheDir . '/' . $filename;
$contents['cache_expiry'] = time() + self::CACHE_TTL;
return file_put_contents($filename, serialize($contents));
} else {
throw new Exception('Cache directory not writable.');
}
}
/**
* Remove old cache items.
*/
private function clearExpiredCache()
{
if (file_exists($this->cacheDir) && is_writable($this->cacheDir)) {
foreach (new DirectoryIterator($this->cacheDir) as $file) {
if ($file->isDot()) {
continue;
}
if (time() - $file->getCTime() >= self::CACHE_TTL) {
unlink($file->getRealPath());
}
}
} else {
throw new Exception('Cache directory not writable.');
}
}
}