forked from Muskie/MashupCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
musicCollection.php
1136 lines (923 loc) · 37.6 KB
/
musicCollection.php
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* This class is for creating music mashups, it is a subclass of mCollection.php and has a subclass called albumCollection.php which is
* designed for manipulating albums, you know those things they used to release music on, groups of 10-12 songs on some physical format.
* Some of us still like albums.
*
* @author Muskie McKay <andrew@muschamp.ca>
* @link http://www.muschamp.ca
* @version 1.4.3
* @copyright Muskie McKay
* @license MIT
*/
/**
The MIT License
Copyright (c) 2010 Andrew "Muskie" McKay
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
require_once('mCollection.php');
require_once('lastfmapi/lastfmapi.php'); // Last.fm API by Matt Oakes
require_once('phpbrainz/phpBrainz.class.php'); // Adds support for MusicBrainz.org API which is occaisionally useful
class musicCollection extends mCollection
{
/**
* These are the keys and username needed for the LastFM API
* @access public static
* @var array
*/
static $lastFMVariables = array(
'apiKey' => myInfo::MY_LAST_FM_PUBLIC_KEY,
'secret' => myInfo::MY_LAST_FM_PRIVATE_KEY,
'username' => myInfo::MY_LAST_FM_USER_NAME
);
/**
* This is an authorized response from the LastFM API letting us make further requests to the API
* @access protected
* @var lastfmApiAuth Object
*/
protected $lastFMAuthority;
//Not sure why I need this, but you do need to say your application is enabled for the LastFM API to work properly
static $lastFMConfig = array(
'enabled' => true,
'path' => './lastfmapi/',
'cache_length' => 1800
);
/**
* This is an instance of tha LastFM API we need it to fetch data eventually
* @access protected
* @var lastfmApi Object
*/
protected $lastFMAPI;
/**
* This is an instance a phpBrainz object it is necessary to use phpBrainz and thus MusicBrainz.org easily
* @access private
* @var Facebook object
*/
protected $theBrainz;
/**
* Initialize a Music Collection
*
* I'm not sure if this is required or if I will do anything, the original constructor was always designed to handle various ways
* of getting the data into the class, from a CSV file to passing it in as an array to eventually database access...
*
* @param input can vary and what type determines how the class is initialized/created see parent method.
*/
public function __construct($input)
{
parent::__construct($input);
}
/**
* Initialize a Music Collection
*
* I haven't overided the constructer, but by overiding this method, I can add support for other APIs
*/
protected function initializeAPIs()
{
parent::initializeAPIs();
$this->lastFMAPI = new lastfmApi();
$this->lastFMAuthority = new lastfmApiAuth('setsession', musicCollection::$lastFMVariables);
$this->theBrainz = new phpBrainz();
}
// This method is the one place so far I make artist data requests from Last.fm
// The advantage of doing it in only one place, besides less code is I knew exactly where to put in the caching...
// It is public as I use it in my favouriteSongs mashup and that is a bit of a hack
public function getArtistInfoFromLastFM($artistName)
{
$strippedArtistName = $artistName;
$strippedArtistName = preg_replace("/[^a-zA-Z0-9]/", "", $strippedArtistName);
if(strlen($strippedArtistName) > 0)
{
$myCache = new Caching("./MashupCache/LastFM/", $strippedArtistName);
$artistClass = $this->lastFMAPI->getPackage($this->lastFMAuthority, 'artist', musicCollection::$lastFMConfig);
$methodVars = array(
'artist' => $artistName
);
if ($myCache->needToRenewData())
{
try
{
// result is an array not a simpleXML Object
$result = $artistClass->getInfo($methodVars);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$reformatedResult = serialize($result);
$myCache->saveSerializedDataToFile($reformatedResult);
}
else
{
// It doesn't need to be renewed so use local copy of array
$result = $myCache->getUnserializedData();
}
}
return $result;
}
// Although Matt's code is a bit unrefined and frequently Last.fm doesn't have all the information I need, it's album.getInfo
// is a good second choice to find track information or even image information. I still prefer to check Amazon.com first as
// They have a lot of higher res images, hopefully previewable tracks, and of course the potential of making money from referrals.
protected function getAlbumInfoFromLastFM($artistName, $albumTitle)
{
$fileName = $artistName . '-' . $albumTitle;
$fileName = preg_replace("/[^a-zA-Z0-9]/", "", $fileName); // I think this removes the slash, I just put in, but RegEx is not my specialty
if(strlen($fileName) > 0)
{
$myCache = new Caching("./MashupCache/LastFM/", $fileName); // This used to work for digable planets but now seems to not create a new cache...
$albumClass = $this->lastFMAPI->getPackage($this->lastFMAuthority, 'album', musicCollection::$lastFMConfig);
// Setup the variables
$methodVars = array(
'artist' => $artistName,
'album' => $albumTitle
);
// I think album titles with ' or ( or ) are causing Matt's code grief, this includes Digable Planets.
/*
print("Going to fetch Last.fm data for: ");
print_r("<pre>");
print($methodVars);
print_r("<pre>");
*/
if ($myCache->needToRenewData())
{
try
{
$result = $albumClass->getInfo($methodVars); // This method is problematic, Matt/My code needs more work...
// print("Fetched results from Last.fm for: " . $artistName);
}
catch (Exception $e)
{
// This getInfo method throws a lot more errors than artist does...
// This is not happening for Digable Planets the latest problematic data...
echo $e->getMessage();
}
$reformatedResult = serialize($result);
$myCache->saveSerializedDataToFile($reformatedResult);
}
else
{
// It doesn't need to be renewed so use local copy of array
$result = $myCache->getUnserializedData();
}
}
return $result;
}
// This method is an improvement on the out of the box Last.fm track.search as I then look through the results for a track that
// matches the current album's artist. This is cached as part of the LovedTracks features I've added.
private function getTrackBuyingInfoFromLastFM($artistName, $songTitle)
{
$fileName = $artistName . '-' . $songTitle;
$fileName = preg_replace("/[^a-zA-Z0-9]/", "", $fileName);
if(strlen($fileName) > 0)
{
$myCache = new Caching("./MashupCache/LovedTracks/", $fileName);
$trackClass = $this->lastFMAPI->getPackage($this->lastFMAuthority, 'track', musicCollection::$lastFMConfig);
// Setup the variables
$methodVars = array(
'artist' => $artistName,
'track' => $songTitle
);
if ($myCache->needToRenewData())
{
try
{
$result = $trackClass->getBuylinks($methodVars);
}
catch (Exception $e)
{
echo $e->getMessage();
}
$reformatedResult = serialize($result);
$myCache->saveSerializedDataToFile($reformatedResult);
}
else
{
// It doesn't need to be renewed so use local copy of array
$result = $myCache->getUnserializedData();
}
}
return $result;
}
/**
* Although I don't make many calls to iTunes as I use Amazon for the primary image source and Last.fm as the primary source for
* artist bios. Apple returns a lot of information when you make a search call, so I might as well cache it. Caching will be
* done the same way as for Last.fm using serialize and unserialize. Apple iTunes Store returns JSON formatted strings which can be
* turned into objects easily enough
*
* @param string
* @return JSON object decoded
*/
protected function getArtistResultsFromITunes($artistName)
{
$iTunesInfo = null;
$strippedArtistName = $artistName;
$strippedArtistName = preg_replace("/[^a-zA-Z0-9]/", "", $strippedArtistName);
if(is_string($artistName) && strlen($strippedArtistName) > 0)
{
$myCache = new Caching("./MashupCache/iTunes/", $strippedArtistName);
if ($myCache->needToRenewData())
{
try
{
$formattedArtistString = str_replace(' ', '+', $artistName);
// This string needs to change perhaps, not necessarily, maybe there are no previews anymore...
$iTunesSearchString = 'https://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=' . $formattedArtistString . '&entity=musicArtist';
$searchResult = fetchThisURL($iTunesSearchString);
$iTunesInfo = json_decode($searchResult);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$serializedObject = serialize($iTunesInfo);
$myCache->saveSerializedDataToFile($serializedObject);
}
else
{
// It doesn't need to be renewed so use local copy of array
$iTunesInfo = $myCache->getUnserializedData();
}
}
else
{
throw new Exception('Incorrect data type passed to getArtistResultsFromITunes()');
}
return $iTunesInfo;
}
// I made this method to add modularity to trackBuyLinkFor
protected function getBuyLinkFromITunesFor($artistName, $albumTitle)
{
$buyLink = '#'; // This has become a defacto error condition, originally I just wanted to reload the page href='#'
try
{
// Should make this it's own method perhaps
$iTunesArtistInfo = $this->getArtistResultsFromITunes($artistName);
if (($iTunesArtistInfo != null) && (count($iTunesArtistInfo->results) > 0))
{
$iTunesAlbumInfo = $this->getAlbumAndTracksFromITunes($iTunesArtistInfo->results[0]->artistId, $albumTitle);
if($iTunesAlbumInfo != null)
{
if( $iTunesAlbumInfo->resultCount > 0)
{
$buyLink = $iTunesAlbumInfo->results[0]->collectionViewUrl;
}
}
}
}
catch (Exception $e)
{
// Buy links aren't as difficult to find as track previews but if an exception is thrown, just catch and try another web service.
}
return $buyLink;
}
// This is the worker function for a method that I wrote to get the Facebook Badge, but then retired it in preference to the 'like' button
// I never got full Facebook integration working to my satisfaction, even with facebookLib, but I can search the Graph API using curl.
// This is returning a JSON Object that I decoded from Facebook's Open Graph
protected function getFacebookPageForArtist($artistName)
{
$facebookPage = null;
if ($artistName != null)
{
$this->facebook->setDecodeJson(true);
$possibleArtists = $this->facebook->search('page', $artistName);
if(($possibleArtists != null) && ( ! empty($possibleArtists->data))) // This is giving me grief for various artists...
{
$firstID = $possibleArtists->data[0]->id;
// This is a bit of fakery, an end around if you will
$graphURL = Facebook::$DOMAIN_MAP['graph'] . $firstID;
$resultingString = fetchThisURL($graphURL);
if(is_string($resultingString))
{
$facebookPage = json_decode($resultingString);
}
else
{
// We're not getting a string in JSON format WTF!
// Probably should throw exception here, haven't seen this error, but it must have happened once...
throw new Exception("Not getting a string in JSON format, got " . $resultingString);
}
}
}
return $facebookPage;
}
// To improve performance and to make the code more general, I created this method to fetch and cache Loved Tracks for a Last.fm user
static function getLovedTracksFor($lastFMUserName)
{
$strippedUserName = $lastFMUserName;
$strippedUserName = preg_replace("/[^a-zA-Z0-9]/", "", $strippedUserName);
if(strlen($strippedUserName) > 0)
{
$myCache = new Caching("./MashupCache/LovedTracks/", $strippedUserName);
$tempLastFMAPI = new lastfmApi();
$tempLastFMAuthority = new lastfmApiAuth('setsession', musicCollection::$lastFMVariables);
$lastFMUser = $tempLastFMAPI->getPackage($tempLastFMAuthority, 'user', musicCollection::$lastFMConfig);
// Setup the variables
$methodVars = array(
'user' => $lastFMUserName
);
if ($myCache->needToRenewData())
{
try
{
// result is an array not a simpleXML Object
$result = $lastFMUser->getLovedTracks($methodVars);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$reformatedResult = serialize($result);
$myCache->saveSerializedDataToFile($reformatedResult);
}
else
{
// It doesn't need to be renewed so use local copy of array
$result = $myCache->getUnserializedData();
}
}
return $result;
}
/**
* This returns a photo of the current album's artist in large and medium format. It returns the data in an array and gets the information from
* Last.fm Last.fm's large image isn't so large, they have bigger ones but they don't appear to want API users to have them.
*
* @return array
*/
public function getCurrentArtistPhotoFromLastFM()
{
$photoInfo = array();
$artistInfo = $this->getArtistInfoFromLastFM($this->currentArtist());
if ( ! empty($artistInfo))
{
$photoInfo['mediumURL'] = $artistInfo['image']['medium'];
$photoInfo['largeURL'] = $artistInfo['image']['large'];
}
return $photoInfo;
}
/**
* Last.fm doesn't give you very big photos, so we'll try our luck with Flickr. Flickr has some very high resolution photos, they also have
* a huge API, luckily it looks like phpFlickr is well supported and documented. Plus after all these other APIs I've started to recognize
* certain design patterns and I'm up on the REST, JSON, lingo.
*
* @return array
*/
public function getCurrentArtistPhotosFromFlickr()
{
// Returns an associated array. I fetch extra image URLs: t = tiny, s = small, m = medium, o = oversized or something...
// Should allow client to specify number of images per page perhaps, changing from 5 to 4 now...
// I need to build an associative array of arguments as this method/API call has so damn many:
// http://www.flickr.com/services/api/flickr.photos.search.html
// I probably don't need to pass in my API-key as I already did when I created the instance of phpFlickr.
$args = array(
'text' => $this->currentArtist(),
'sort' => 'relevance',
'content_type' => 1,
'per_page' => 4,
'extras' => 'url_t, url_s, url_m, url_o'
);
$flickrResults = $this->flickrAPI->photos_search($args);
return $flickrResults;
}
// Apple iTunes Music Store is one place I can get preview of tracks reliably.
// After getting this method to work like I wanted, including caching the information returned by the iTunes Music Store, I decided I might try
// and use this information to supplement my cover image fetching... I still won't make any money off of iTunes but the more album covers
// I find the better for my original album cover gallery.
// Apple iTunes store returns JSON formatted strings which can be turned into objects easily enough
protected function getAlbumAndTracksFromITunes($iTunesID, $albumName)
{
$iTunesInfo = null;
$properFileName = $iTunesID . $albumName;
$properFileName = preg_replace("/[^a-zA-Z0-9]/", "", $properFileName);
if(strlen($properFileName) > 0)
{
$myCache = new Caching("./MashupCache/iTunes/", $properFileName);
if ($myCache->needToRenewData())
{
try
{
// First get all the albums by an artist using a lookup request
$iTunesLookUpString = 'https://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsLookup?id=' . $iTunesID . '&entity=album';
$lookUpResult = fetchThisURL($iTunesLookUpString);
// Now we have the look up results but we need to find the $iTunesID for the correct album then get the tracks that go with it
// We need collectionName to equal $albumName
$lookUp = json_decode($lookUpResult);
if ( ! empty($lookUp))
{
$resultCount = $lookUp->resultCount; // This isn't always correct, maybe have to check more carefully what was returned...
$i = 1; // First result is the artist not an album, I already had the artist info.
$collectionID = null;
while(($i < $resultCount) && ($collectionID == null))
{
// Look for album in iTunes...
$collectionName = (string) $lookUp->results[$i]->collectionName;
if( strcasecmp($collectionName, $albumName) == 0)
{
// We have our match
$collectionID = $lookUp->results[$i]->collectionId;
}
// remember to increment!
$i++;
}
if( $collectionID != null)
{
// If collectionID isn't null... lookup album again in iTunes with tracks and that is what we really really want!
// cache and return...
$newLookupString = 'https://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsLookup?id=' . $collectionID . '&entity=song';
$newLookUpResult = fetchThisURL($newLookupString);
$iTunesInfo = json_decode($newLookUpResult);
$serializedObject = serialize($iTunesInfo);
$myCache->saveSerializedDataToFile($serializedObject);
}
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
else
{
// It doesn't need to be renewed so use local copy
$iTunesInfo = $myCache->getUnserializedData();
}
}
return $iTunesInfo;
}
/**
* This returns an array of similar artists, the array consists of artist name and a URL, just like tags method.
*
* @return array
*/
public function similarArtistsToCurrentArtist()
{
$similarArtists = array();
$artistInfo = $this->getArtistInfoFromLastFM($this->currentArtist());
if ( ! empty($artistInfo['similar']))
{
for( $i = 0; $i < count($artistInfo['similar']) ; $i++)
{
// There are always five similar artists...
$similarArtists[$i]['name'] = $artistInfo['similar'][$i]['name'];
$similarArtists[$i]['url'] = $artistInfo['similar'][$i]['url'];
}
}
return $similarArtists;
}
/**
* This method searchs the iTunes store for an audio sample we can link directly to. If I can't find that I search Amazon for
* a page I can link to that will have a preview on it. This method is bigger than I would like, but I'm torn as to where to
* add modularity...
*
* @param string song title
* @param string album title
* @param string artist name
* @return string
*/
protected function findAudioSample($songTitle, $albumTitle, $artistName)
{
$sampleURL = '';
// SOMETHING is going wrong, I'm not getting audio previews from iTunes, I've added conditionals to prevent errors but this
// was a killer feature of the mashup code base...
// Check input
if (( ! empty($songTitle)) && ( ! empty($albumTitle)) && ( ! empty($artistName)))
{
$sampleURL = $this->findTrackInITunesFor($songTitle, $albumTitle, $artistName);
// We need to search Amazon next...
if ($sampleURL == null)
{
// This method should by made modular
// need to use getMP3ForSongByArtist in this case
$amazonSearchResults = $this->amazonAPI->getMP3ForSongByArtist($songTitle, $artistName);
// The above returns a lot more tracks or at least ASINs than I want.
if( count($amazonSearchResults->Items->Item) > 0)
{
// We have multiple tracks or at least ASINs most likely, go with first one.
$furtherAmazonXML = $this->amazonAPI->getItemByAsin($amazonSearchResults->Items->Item[0]->ASIN);
$sampleURL = $furtherAmazonXML->Items->Item->DetailPageURL;
}
}
}
else if (( ! empty($albumTitle)) && ( ! empty($artistName)))
{
$iTunesArtistInfo = $this->getArtistResultsFromITunes($artistName);
// Had to change this if, but what changed elsewhere? Should read documentation yet again...
if (($iTunesArtistInfo != null) && ( count($iTunesArtistInfo->results) > 0))
{
$iTunesAlbumInfo = $this->getAlbumAndTracksFromITunes($iTunesArtistInfo->results[0]->artistId, $albumTitle);
if($iTunesAlbumInfo != null)
{
$sampleURL = $iTunesAlbumInfo->results[1]->previewUrl; // Track 1 is good enough, I can get them ranked by popularity perhaps...
}
}
if ($sampleURL == null)
{
$amazonSearchResults = $this->amazonAPI->getMP3sForAlbumByArtist($albumTitle, $artistName);
// The above returns a lot more tracks or at least ASINs than I want.
if( count($amazonSearchResults->Items->Item) > 0)
{
// We have multiple tracks or at least ASINs most likely, go with first one.
$furtherAmazonXML = $this->amazonAPI->getItemByAsin($amazonSearchResults->Items->Item[0]->ASIN);
// May need conditional around this but so far it works with my sample data set
$sampleURL = $furtherAmazonXML->Items->Item->DetailPageURL;
}
}
}
else if ( ! empty($artistName))
{
$sampleURL = $this->findAudioSampleForArtist($artistName);
}
else if ( ! empty($songTitle))
{
$sampleURL = $this->findAudioSampleFor($songTitle);
}
else
{
// No useful data passed in or just an album title
$sampleURL = $this->findAudioSampleFor($albumTitle);
}
return $sampleURL;
}
/**
* This method searches just iTunes for now, for the most popular track by the artist. It then returns the direct link to an audio preview
* eventually I may search other sources, but iTunes is the only one which I can get direct links to an audio sample.
*
* @param string artist name
* @return string URL or empty string
*/
public function findAudioSampleForArtist($name)
{
$previewURL = '';
// Tempted for now to just search iTunes.
// We probably have the artist search cached so get that and look for most popular track
$iTunesArtistInfo = $this->getArtistResultsFromITunes($name);
// We have a long way to go, assume first artist is the artist we want.
if( ! empty($iTunesArtistInfo->results))
{
$iTunesArtistID = $iTunesArtistInfo->results[0]->artistId;
// Now we want to perform a look up of songs, well just the top song really.
// Something like this:
// http://itunes.apple.com/lookup?id=909253&entity=song&limit=1
$prefix = 'http://itunes.apple.com/lookup?id=';
$limitingText = '&entity=song&limit=1';
$lookUpURL = $prefix . $iTunesArtistID . $limitingText;
$lookUpResult = fetchThisURL($lookUpURL);
$lookUp = json_decode($lookUpResult);
if ( ! empty($lookUp))
{
// Result number one is the artist info again, which I already had.
// Result number two is the most popular track by an artist so return that previewUrl
// For Luke Doucet "Broken One" neither this enlarged if statement nor the try & catch structure is stopping the offset Notice
if (( ! empty($lookUp->results)) && (is_array($lookUp->results)) && (count($lookUp->results)))
{
$previewURL = $lookUp->results[1]->previewUrl; // This generates a Notice for Luke Doucet "Broken One"
}
}
}
return $previewURL;
}
/**
* This method searches just iTunes for now, for the most popular track for the title, It is probably going to assume it is a song title but it
* could be an album title or any string. The method then returns the direct link to an audio preview
* eventually I may search other sources, but iTunes is the only one which I can get direct links to an audio sample.
*
* @param string artist name
* @return string URL or empty string
*/
public function findAudioSampleFor($title)
{
$previewURL = '';
// This one I have less confidence it will work perfectly. Sure iTunes or Amazon would return something, but it is a useful result?
// Want a querry something like:
// http://itunes.apple.com/search?term=jack+johnson&entity=song&limit=1
$prefix = 'http://itunes.apple.com/search?term=';
$limitingText = '&entity=song&limit=1';
// I need to to make sure the title is encoded correctly
$formattedTitle = str_replace(' ', '+', $title);
$lookUpURL = $prefix . $formattedTitle . $limitingText;
$lookUpResult = fetchThisURL($lookUpURL);
$lookUp = json_decode($lookUpResult);
if ( ! empty($lookUp))
{
// if we have results there is only one and that one what we return the previewUrl for
if ( count($lookUp->results) > 0)
{
$previewURL = $lookUp->results[0]->previewUrl;
}
}
return $previewURL;
}
/**
* This method searches the iTunes store primarily for an audio sample of the current album's favourite track which is stored
* in the albums array.
*
* This method expects addtional information in the array... Not sure what happens when you don't provide that information, need to test more.
*
* @return string
*/
public function audioSampleForCurrentAlbumsFavouriteSong()
{
$currentAlbumInfo = $this->currentMemberAsArray();
$artistName = $currentAlbumInfo[0];
$albumTitle = $currentAlbumInfo[1];
$favouriteTrackTitle = $currentAlbumInfo['songTitle'];
return $this->findAudioSample($favouriteTrackTitle, $albumTitle, $artistName);
}
/**
* Finds an audio sample for artist and album passed in. I can only find a direct link in iTunes but I can find an indirect link to
* an audio preview in Amazon or elsewhere.
*
* @param string $collectionTitle title of the collection
* @param string $artistName the name of the Artist
*
* @return string
*/
public function audioSampleFor($collectionTitle, $artistName)
{
return $this->findAudioSample(null, $collectionTitle, $artistName);
}
/**
* This method searches YouTube and potentially eventually other video services for a video clip featurning the passed in artist
* I now return the HTML necessary for an embeddable player
*
* @return array
*/
public function videoClipForCurrentArtist()
{
return $this->embeddableVideoClipFor($this->currentArtist());
}
/**
* This method searches YouTube and potentially eventually other video services for a video clip featurning the currentArtist and
* the passed in keywords corresponding to a song title.
*
* @param string
*
* @return array
*/
public function videoClipForCurrentArtistEntitled($songTitle)
{
$fullquery = '"' . $songTitle . '" by ' . $this->currentArtist();
return $this->embeddableVideoClipFor($fullquery);
}
/**
* Returns an array of the tags associated with the current member of the collection.
*
* @return array of tags
*/
public function lastFMAlbumTags()
{
$tags = array();
$currentMember = $this->currentMemberAsArray();
// This risks encountering a bug in Matt's last.fm code as I don't sanatize the album title prior to the call...
$albumInfo = $this->getAlbumInfoFromLastFM($currentMember[0], $currentMember[1]);
if ( ! empty($albumInfo))
{
if( ! empty($albumInfo['toptags']))
{
$tags = $albumInfo['toptags'];
}
}
return $tags;
}
/**
* Returns the current collection artist, ie the first item in currentMemberAsArray, last.fm has issues with artist's who an apostrophe in their
* name or at least Matt's code does so I'm stripping apostrophe's from artist names too.
*
* @return string
*/
public function currentArtist()
{
$anAlbum = $this->currentMemberAsArray();
$artistName = $anAlbum[0];
if ($artistName == null)
{
$artistName = "unknown"; // This is better than returning null or nothing...
}
else
{
// Doing this here may reduce strange last.fm bugs, but I don't always call this method, need to be vigilant.
$worrisomeChars = array("'"); // The problem seems to be with apostrophes...
$artistName = str_replace($worrisomeChars, '', $artistName);
}
return $artistName;
}
/**
* This method checks that the current artist is not "unknown". If the current artist is unknown or null, I return the string "unknown"
* in the method above. Checking for this prior to querry some APIs is more efficient.
*
* @return Boolean
*/
public function isCurrentArtistUnknown()
{
$isUnknown = false;
if (strcmp($this->currentArtist(), "unknown") == 0)
{
$isUnknown = true;
}
return $isUnknown;
}
/**
* This method I created as part of my favourite or loved tracks mashup. The code is for creating an instance of this
* class populated by the albums that correspond to a user's loved tracks in last.fm. By putting the code here as a static method
* future users of this class can populate their music collection with this info too.
*
* In the array I also put the track name and the url on Last.fm, I used non-numeric indices for this extra data.
*
* @return musicCollection
*/
static public function collectionFromLovedTracks()
{
$lovedTracksInfo = array();
$myLovedTracks = musicCollection::getLovedTracksFor(myInfo::MY_LAST_FM_USER_NAME);
// New Caching Code
$strippedUserName = preg_replace("/[^a-zA-Z0-9]/", "", myInfo::MY_LAST_FM_USER_NAME);
if(strlen($strippedUserName) > 0)
{
$strippedUserName = $strippedUserName . 'LovedTracks';
$myCache = new Caching("./MashupCache/LovedTracks/", $strippedUserName);
if ($myCache->needToRenewData())
{
$lovedTracksCount = count($myLovedTracks);
$artistName = '';
$albumTitle = '';
$songTitle = '';
$songURL = '';
$i = 0;
while ( $i < $lovedTracksCount)
{
// Need album titles
$formattedSongTitle = str_replace(' ', '+', $myLovedTracks[$i]['name']);
// http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=song+title&entity=musicTrack
$iTunesSearch = 'http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=' . $formattedSongTitle . '&media=music&entity=musicTrack&attribute=musicTrackTerm';
$iTunesSearchResults = fetchThisURL($iTunesSearch);
$iTunesResults = json_decode($iTunesSearchResults);
$artistName = $myLovedTracks[$i]['artist']['name'];
$songTitle = $myLovedTracks[$i]['name'];
$songURL = 'http://' . $myLovedTracks[$i]['url']; // This should solve some linking issues...
if($iTunesResults->resultCount > 0)
{
$j = 0;
$foundAlbum = false;
while( ($j < $iTunesResults->resultCount) && ( ! $foundAlbum) )
{
if ( strcmp($iTunesResults->results[$j]->artistName, $myLovedTracks[$i]['artist']['name']) == 0)
{
$albumTitle = $iTunesResults->results[$j]->collectionName;
$foundAlbum = true;
}
$j++;
}
// if we don't find one, such as in the case of Tom Waits "Looking for the heart of Saturday Night" , we are end up with the wrong data...
if ( ! $foundAlbum)
{
// This is necessary
$albumTitle = '';
}
}
else
{
$albumTitle = '';
}
$lovedTracksInfo[$i] = array(
0 => $artistName,
1 => $albumTitle,
'songTitle' => $songTitle,
'songURL' => $songURL
);
$i++;
}
$reformatedTracks = serialize($lovedTracksInfo);
$myCache->saveSerializedDataToFile($reformatedTracks);
}
else
{
// It doesn't need to be renewed so use local copy of array
$lovedTracksInfo = $myCache->getUnserializedData();
}
}
return new musicCollection($lovedTracksInfo);
}