def search_for_itunes_track(track, artist, album=None): if album: logging.debug("Searching for '{0}' by '{1}' in '{2}'".format( track, artist, album)) results = itunes.search("{0} {1} {2}".format(artist, album, track), "music") else: logging.debug("Searching for '{0}' by '{1}'".format(track, artist)) results = itunes.search("{0} {1}".format(artist, track), "music") return results
def music_info(artist='', song=''): ''' Get genre information from given artist and song Returns cleaned artist and song names along with genre ''' import itunes term_artist = artist.strip() if artist else '' term_song = song.strip() if song else '' payload = { 'query' : u'{0} {1}'.format(term_artist, term_song).lower(), 'media' : 'music', 'store' : 'GB' } if not payload['query']: return None try: response = itunes.search(**payload) if response: # Get the genre for the given artist and song, along with corrected artist and song names # # If the song name is not given, it'll fetch the most popular song by the given artist artist_name, song_name, genre_name = response[0].get_artist().get_name(),\ response[0].get_name(),\ response[0].get_genre() # But if the song name is given and is incorrect or doesn't fetch a result, just use the artist info and get the stuff elif term_artist and term_artist.strip(): # Get the primary genre for the given artist if nothing matches with the song payload.update({'query' : term_artist.lower()}) response = itunes.search(**payload) if response: artist_name, song_name, genre_name = response[0].get_name(),\ response[0].get_tracks(limit=1).get_name(),\ response[0].get_genre() else: return None else: return None return artist_name, song_name, genre_name except Exception, e: return None
def _grab(self): try: results = itunes.search(query=self.search_term, media=self.MEDIA, limit=self.LIMIT, offset=self.offset) except (itunes.ServiceException, Exception) as e: raise return results
def findAppFromApple2(iosapp): try: appList = itunes.search(query=iosapp.trackName, media='software') except: return False for app in appList: artistName= app.get_artistName() trackName = app.get_trackName() sellerUrl = app.get_seller_url() sellerName= app.get_sellerName() if iosapp.artistName == artistName: print "!!!!!!!!!!!!in app got it for %s" % trackName trackId = app.get_id() bundleId = app.get_bundleId() artistId = app.get_artistId() icon = app.get_icon() link = app.get_link() primaryGenreId=app.get_primaryGenreId() primaryGenreName=app.get_primaryGenreName() iosapp.trackId = trackId iosapp.bundleId = bundleId iosapp.artistId = artistId iosapp.icon = icon iosapp.link = link iosapp.primaryGenreId = primaryGenreId iosapp.primaryGenreName = primaryGenreName if sellerUrl != None: iosapp.artistUrl = sellerUrl try: iosapp.save() except Exception,e: print str(e)
def get_song_artwork(song): try: song_name = song['name'] song_artist = song['artist'] song_player = song['player'] song_album = song['album'] print("Name: {}".format(song_name)) print("Album: {}".format(song_album)) print("Artist: {}".format(song_artist)) print("Player: {}".format(song_player)) # search itunes store to get our album art results = itunes.search(query="{} {}".format(song_artist, song_name)) try: desired_song = results[0] # the first result is most likely our desired result desired_artwork_url = desired_song.artwork['600'] response = requests.get(desired_artwork_url) img = Image.open(BytesIO(response.content)) img.save('art.png') get_color_palette_from_cover(song_name) except IndexError: print("Could not get album art for this song so no color values.") except AttributeError: print("Something went wrong. Fix it boi.")
def get_artwork(song): song_name = re.sub(r"\([^)]*\)", "", song[1]).strip().lower() artist = song[0].lower() results = itunes.search("%s %s" % (song_name, artist), limit=1) if not results: return {} return results[0].artwork
def detail(artist_name): itunes_search = itunes.search(artist_name, limit=1) if len(itunes_search): itunes_data = itunes.lookup(itunes_search[0]['artistId']) lastfm_data = lastfm.get_artist(itunes_data['artistName']) song_fields = ['trackName', 'previewUrl', 'artworkUrl100', 'collectionName', 'trackPrice', 'collectionViewUrl'] itunes_songs = itunes.search(itunes_data['artistName'])[:3] itunes_songs = [dict((k, song[k]) for k in song_fields if k in song) for song in itunes_songs] return render_template('detail.html', **{ 'name': itunes_data['artistName'], 'picture': lastfm_data['image'][2]['#text'], 'on_tour': True, 'other_songs': itunes_songs, 'description': ', '.join(tag['name'] for tag in lastfm_data['tags']['tag'][:3]), })
def get_itunes_info(self): if self.type.name == 'iOS': try: item = itunes.search(query=self.name, media='software')[0] self.store_name = item.name self.store_cost = item.price #self.store_description = unicode(item.get_description()).encode('utf8') self.store_link = item.url self.store_avg_rating = item.avg_rating self.store_num_ratings = item.num_ratings except: pass
def findAppFromApple(name,artist,appAnnieLink,artistLink,country): try: appList = itunes.search(query=name,store=countryCode[country], media='software') except: return False for app in appList: artistName= app.get_artistName() trackName = app.get_trackName() sellerUrl = app.get_seller_url() sellerName= app.get_sellerName() if artist == artistName: print "!!!!!!!!!!!!in app got it for %s" % trackName trackId = app.get_id() bundleId = app.get_bundleId() artistId = app.get_artistId() icon = app.get_icon() link = app.get_link() primaryGenreId=app.get_primaryGenreId() primaryGenreName=app.get_primaryGenreName() try: appInDB = IosApp.objects.get(trackId=trackId) except: try: appInDB = IosApp.objects.create(company=matchAppWithComp(sellerUrl), trackId=trackId, trackName=trackName, bundleId=bundleId, artistId=artistId, artistName=artistName, sellerName=sellerName, primaryGenreId=primaryGenreId, primaryGenreName=primaryGenreName, appAnnieLink=appAnnieLink, artistLink=artistLink, icon=icon, link=link ) except Exception, e: print str(e) print "create error " return False else: print "create app %s for id %s " % (trackName,str(appInDB.id)) else: if appInDB.appAnnieLink=='': appInDB.appAnnieLink = appAnnieLink appInDB.artistLink = artistLink appInDB.save() return appInDB
def itunesm(msg): api.sendMsg(msg.channel, "Loading...") resultz = {} if len(msg.message.split(" ")) < 2: api.sendMsg(msg.channel, __Usage__) try: _msg = msg.message.split(" ") _msg2 = msg.message.split('"') _query = _msg2[1] _cmd = _msg[0] _mode = _msg[1] _page = _msg2[2] except: print "Except" _page = 1 _mode = _msg[1] if _mode == "help": api.sendMsg(msg.channel, __Usage__) else: result = itunes.search(query=_query, media=_mode) x = 0 y = 1 m = 0 final = {} for item in result: x += 1 m += 1 if x > 5: y += 1 x = 0 else: try: if y in final.keys(): final[y].append( "[%s] %s by %s (%s) [%s]" % (m, item.get_name(), item.get_artist(), item.get_release_date(), shorten(item.get_url())) ) else: final[y] = [ "[%s] %s by %s (%s) [%s]" % (m, item.get_name(), item.get_artist(), item.get_release_date(), shorten(item.get_url())) ] except: pass for item in final[int(_page.strip(" "))]: api.sendMsg(msg.channel, item)
def autocomplete(self,arg): try: shows = itunes.search(query=arg, media="tvShow")[:3] return [x.name for x in shows] except Exception as e: print (e)
def process_item(self, item, spider): if(item['true_date'] > self.last_date_in_db): print "true_date is is more recent than last_date_in_db, add it to db" # Okay, now we have a new track, let's get the itunes info based on # artist and track name. try: iTunes_track = itunes.search(query="" + item['artist_name_text'] + " " + item['track_name_text'] + "", media='music') except: iTunes_track = None # please be advised, this is a nasty race condition. if iTunes_track: print iTunes_track[0].get_name() print iTunes_track[0].get_artist() print iTunes_track[0].get_id() print iTunes_track[0].get_artist().get_id() item['artist'] = iTunes_track[0].get_artist().get_id() item['track'] = iTunes_track[0].get_id() # While we have the itunes song, check the db for its existence, and if not there, just add it. # This is where we get all the url and image info for display #''' Start of long comment try: check_track = ItunesTrackInfo.objects.get(track_id=item['track']) except: check_track = None print check_track if check_track: print "%s already exists in local iTunes table. Skip it." % (item['track']) else: print "%s is not in local iTunes Table, add it." % (item['track']) found_this_track = ItunesTrackInfo() found_this_track.date_added = item['true_date'] found_this_track.wrapper_type = iTunes_track[0].type found_this_track.kind = iTunes_track[0].type found_this_track.artist_id = iTunes_track[0].get_artist().get_id() if iTunes_track[0].get_album().get_id(): found_this_track.collection_Id = iTunes_track[0].get_album().get_id() else: found_this_track.collection_Id = 0 found_this_track.track_id = iTunes_track[0].get_id() found_this_track.artist_name = iTunes_track[0].get_artist() if iTunes_track[0].get_album(): found_this_track.collection_name = iTunes_track[0].get_album() else: found_this_track.collection_name = '' found_this_track.track_name = iTunes_track[0].get_name() found_this_track.collection_censored_name = '' found_this_track.track_censored_name = '' found_this_track.artist_view_URL = iTunes_track[0].get_artist().get_url() found_this_track.collection_view_URL = iTunes_track[0].get_album().get_url() found_this_track.track_view_URL = iTunes_track[0].get_url() found_this_track.preview_URL = iTunes_track[0].get_preview_url() found_this_track.artwork_URL_30 = iTunes_track[0].get_artwork()['30'] found_this_track.artwork_URL_60 = iTunes_track[0].get_artwork()['60'] found_this_track.artwork_URL_100 = iTunes_track[0].get_artwork()['100'] found_this_track.collection_price = iTunes_track[0].get_price() found_this_track.track_price = iTunes_track[0].get_price() found_this_track.release_date = iTunes_track[0].get_release_date() found_this_track.collection_explicitness = '' found_this_track.track_explicitness = '' found_this_track.disc_count = '' found_this_track.disc_number = iTunes_track[0].get_disc_number() found_this_track.track_count = '' found_this_track.track_number = '' found_this_track.track_time_millis = iTunes_track[0].get_duration() found_this_track.country = '' found_this_track.currency = '' found_this_track.primary_genre_name = iTunes_track[0].get_genre() found_this_track.content_advisory_rating = '' # found_this_track.short_description = iTunes_track[0].get_description() # found_this_track.long_description = iTunes_track[0].get_description() found_this_track.save() # End of long comment ''' # if no search result, set artist and track to 0. else: item['artist'] = 0 item['track'] = 0 # then put it in the DB like all is perfect. try: item.save() except MySQLdb.Error, e: print "exception found" print "Error %d: %s" % (e.args[0], e.args[1])
def test_movie_as_track(): item = itunes.search(query='the godfather', media='movie')[0] assert_equal(item.get_artist(), None)
def itunes(book): item = itunes_.search(query=book['title'] + ' ' + book['author'], media='ebook')[0] book['itunes_id'] = item.id book['itunes'] = item.price
def getCompanyApp(company): try: appList = itunes.search(query=company.name, media='software') except: company.appFetched = True company.save() return url = trimUrl(company.website) count = 0 for app in appList: if count == 10: return count+=1 sellerUrl = trimUrl(app.get_seller_url()) artistName= app.get_artistName() avgRating = app.get_avg_rating() if avgRating == None: avgRating = 0 ratingNum = app.get_num_ratings() if ratingNum == None: ratingNum = 0 sellerName = app.get_sellerName() trackName = app.get_trackName() isApp = 0 if sellerUrl!=None and sellerUrl.lower() == url.lower()>0: print "find sellerUrl %s" % sellerUrl isApp+=1 if artistName!=None and artistName.lower()==company.name.lower(): print "find artistName %s " % artistName.lower() isApp+=1 if sellerName!=None and sellerName.lower()==company.name.lower(): print "find sellerName %s " % sellerName.lower() isApp+=1 if isApp>0: print "rating avg %s for number %s " % (avgRating,ratingNum) print "find app %s for company %s" % (trackName, company.name) trackId = app.get_id() bundleId = app.get_bundleId() artistId = app.get_artistId() icon = app.get_icon() link = app.get_link() primaryGenreId=app.get_primaryGenreId() primaryGenreName=app.get_primaryGenreName() try: gotApp = IosApp.objects.get(trackId=trackId) except: try: IosApp.objects.create(company=company, trackId=trackId, trackName=trackName, bundleId=bundleId, artistId=artistId, artistName=artistName, primaryGenreId=primaryGenreId, primaryGenreName=primaryGenreName, icon=icon, link=link, avgRating=avgRating, ratingCount=ratingNum ) except Exception, e: print str(e) print "create error " else: if gotApp.company == None: gotApp.company = company gotApp.ratingNum = ratingNum gotApp.avgRating = avgRating gotApp.save() print "linked company %s with app %s " %(company.name,gotApp.trackName)
def test_movie_as_track(): item = itunes.search(query='the godfather', media='movie')[0] assert item.artist == None
# If there is a value for check_track, then we don't need to do anything except add the song/track to running_playlist logging.warning("The track relationship already exists, just save the item to running playlists.") try: logging.warning("Item should be saved here.") rp = RunningPlaylist.objects.create(processing_time = pt, Unique_ID=row['Unique_ID'], date_added=row['date_added'], time_played=row['time_played'], radio_station=rs, artist_name_text=row['artist_name_text'], track_name_text=row['track_name_text'], artist=ra, track=rt) #item.save() except MySQLdb.Error, e: logging.warning("Exception found", level=log.ERROR) logging.warning("Error %d: %s" % (e.args[0], e.args[1]), level=log.ERROR) # If there is no check_track, then we dont know anything about the relationship. else: logging.warning("The track relationship doesnt exist, create the track relationship. See if iTunes has any information on it.") logging.warning("Get information from iTunes.") try: # Grab the information from iTunes to marry to the track and the artist. iTunes_track = itunes.search(query="" + row['artist_name_text'] + " " + row['track_name_text'] + "", media='music') logging.warning("Info from iTunes: Track name: " + iTunes_track[0].get_name() + " | iTunes Track ID: " + unicode(iTunes_track[0].get_id()) + " | Artist name: " + iTunes_track[0].get_artist().get_name() + " | iTunes Artist ID: " + unicode(iTunes_track[0].get_artist().get_id()) + " ") except: # Couldn't get anything from iTunes. iTunes_track = None logging.warning("Unable to gather data from iTunes.") if iTunes_track: logging.warning("Grabbed track_id [ %i ] from iTunes, let's do some work with it." % (iTunes_track[0].get_id())) found_this_track = ItunesTrackInfo() found_this_track.date_added = row['date_added'] found_this_track.wrapper_type = iTunes_track[0].type found_this_track.kind = iTunes_track[0].type found_this_track.artist_id = iTunes_track[0].get_artist().get_id() try: album = iTunes_track[0].get_album()
def search(self,arg): return itunes.search(query=arg, media="tvShow")
def process_item(self, item, spider): if(item['true_date'] > self.last_date_in_db): log.msg("true_date is is more recent than last_date_in_db, add it to db", level=log.INFO) item['processing_time'].number_of_tracks_added_this_batch += 1 item['processing_time'].save() a_name = item['artist_name_text'] if a_name and a_name[-1] == "*": a_name = a_name[:-1] log.msg("Stripped trailing * from artist name text.", level=log.INFO) t_name = item['track_name_text'] if t_name and t_name[-1] == "*": t_name = t_name[:-1] log.msg("Stripped trailing * from track name text", level=log.INFO) ### New flow here # Compare item artist_name_text to artist.name - if exists do something, if not add it. try: log.msg("ARTIST name from radio station: [" + a_name + "].", level=log.INFO) check_for_artist = Artist.objects.get(name__iexact=""+a_name+"") log.msg("Checking local ARTIST table by name: [" + check_for_artist.name + "].", level=log.INFO) if check_for_artist: item['artist'] = check_for_artist log.msg("ARTIST exists in table, setting current ARTIST to existing ARTIST from table.", level=log.INFO) else: #add_artist = Artist.objects.create(name=item['artist_name_text']) #item['artist'] = add_artist log.msg("<><><><><><><><><><><><><><><> strange race condition here.", level=log.WARNING) except: #print "Error %d: %s" % (e.args[0], e.args[1]) try: add_artist = Artist.objects.create(name=a_name, date_added=item['true_date']) item['artist'] = add_artist log.msg("ARTIST doesn't exist in table, creating new ARTIST and setting current ARTIST to new ARTIST.", level=log.INFO) except: log.msg("Something failed with grabbing or creating an ARTIST, setting to default ARTIST.", level=log.ERROR) item['artist'] = Artist.objects.get(pk=1) # Compare item track_name_text to track.name - if exists do something, if not, add it. try: log.msg("TRACK name from radio station: [" + t_name + "].", level=log.INFO) check_for_track = Track.objects.get(name =""+t_name+"") log.msg("Checking local TRACK table for TRACK by name: [" + check_for_track.name + "].", level=log.INFO) if check_for_artist: item['track'] = check_for_track log.msg("TRACK exists in table, setting current TRACK to existing TRACK from table.",level=log.INFO ) else: log.msg("><><><><><><><><><><><><><><> strange race condition here.", level=log.INFO) except: try: add_track = Track.objects.create(name=t_name, date_added=item['true_date'], artist=item['artist']) item['track'] = add_track log.msg("TRACK doesn't exist in table, creating new TRACK and setting current TRACK to new TRACK.", level=log.INFO) except: log.msg("Something failed with grabbing or creating a TRACK, setting to default TRACK.", level=log.WARNING) item['track'] = Track.objects.get(pk=1) # We now have a track and an artist object, let's see if we have seen it before anywhere. # Create the Music Service object. try: ms = MusicServices.objects.get(pk=1) log.msg("Created MUSICSERVICE [ms]." + ms.name + ". ", level=log.INFO) except: log.msg("Unable to instantiate MUSICSERVICE.", level=log.WARNING) # Okay, we have the music service object. Have we seen this track from iTunes before? # Look in the MusicService_Track_Lookup table for this track at iTunes. try: check_track = MusicServices_Track_Lookup.objects.filter(track=item['track'], music_service=ms) log.msg("Checking to see if this TRACK already exists in local tables. ", level=log.INFO) log.msg("item [" + item['track'].name + "]", level=log.DEBUG) except: check_track = None log.msg("TRACK relationship not found in local tables. : " + unicode(check_track) + "", level=log.INFO) if check_track: # If there is a value for check_track, then we don't need to do anything except add the song/track to running_playlist log.msg("The track relationship already exists, just save the item to running playlists.", level=log.INFO) try: log.msg("Item should be saved here.", level=log.INFO) item.save() except MySQLdb.Error, e: log.msg("Exception found", level=log.ERROR) log.msg("Error %d: %s" % (e.args[0], e.args[1]), level=log.ERROR) # If there is no check_track, then we dont know anything about the relationship. else: log.msg("The track relationship doesnt exist, create the track relationship. See if iTunes has any information on it.", level=log.INFO) log.msg("Get information from iTunes.", level=log.INFO) try: # Grab the information from iTunes to marry to the track and the artist. iTunes_track = itunes.search(query="" + item['artist_name_text'] + " " + item['track_name_text'] + "", media='music') log.msg("Info from iTunes: Track name: " + iTunes_track[0].get_name() + " | iTunes Track ID: " + unicode(iTunes_track[0].get_id()) + " | Artist name: " + iTunes_track[0].get_artist().get_name() + " | iTunes Artist ID: " + unicode(iTunes_track[0].get_artist().get_id()) + " ", level=log.INFO) except: # Couldn't get anything from iTunes. iTunes_track = None log.msg("Unable to gather data from iTunes.", level=log.WARNING) if iTunes_track: log.msg("Grabbed track_id [ %i ] from iTunes, let's do some work with it." % (iTunes_track[0].get_id()), level=log.INFO) found_this_track = ItunesTrackInfo() found_this_track.date_added = item['true_date'] found_this_track.wrapper_type = iTunes_track[0].type found_this_track.kind = iTunes_track[0].type found_this_track.artist_id = iTunes_track[0].get_artist().get_id() if iTunes_track[0].get_album().get_id(): found_this_track.collection_Id = iTunes_track[0].get_album().get_id() else: found_this_track.collection_Id = 0 found_this_track.track_id = iTunes_track[0].get_id() found_this_track.artist_name = iTunes_track[0].get_artist() if iTunes_track[0].get_album(): found_this_track.collection_name = iTunes_track[0].get_album() else: found_this_track.collection_name = '' found_this_track.track_name = iTunes_track[0].get_name() found_this_track.collection_censored_name = '' found_this_track.track_censored_name = '' found_this_track.artist_view_URL = iTunes_track[0].get_artist().get_url() found_this_track.collection_view_URL = iTunes_track[0].get_album().get_url() found_this_track.track_view_URL = iTunes_track[0].get_url() found_this_track.preview_URL = iTunes_track[0].get_preview_url() found_this_track.artwork_URL_30 = iTunes_track[0].get_artwork()['30'] found_this_track.artwork_URL_60 = iTunes_track[0].get_artwork()['60'] found_this_track.artwork_URL_100 = iTunes_track[0].get_artwork()['100'] found_this_track.collection_price = iTunes_track[0].get_price() found_this_track.track_price = iTunes_track[0].get_price() found_this_track.release_date = iTunes_track[0].get_release_date() found_this_track.collection_explicitness = '' found_this_track.track_explicitness = '' found_this_track.disc_count = '' found_this_track.disc_number = iTunes_track[0].get_disc_number() found_this_track.track_count = '' found_this_track.track_number = '' found_this_track.track_time_millis = iTunes_track[0].get_duration() found_this_track.country = '' found_this_track.currency = '' found_this_track.primary_genre_name = iTunes_track[0].get_genre() found_this_track.content_advisory_rating = '' # found_this_track.short_description = iTunes_track[0].get_description() # found_this_track.long_description = iTunes_track[0].get_description() if found_this_track.track_id: try: check_local_iTunes = ItunesTrackInfo.objects.get(track_id=found_this_track.track_id) log.msg("Checking if this track_id already exists in local iTunes table.", level=log.INFO) except: check_local_iTunes = None log.msg("Track_id doesn't exist in local iTunes table.", level=log.INFO) if check_local_iTunes: log.msg("Track_id exists in local itunes table, skipping.", level=log.INFO) else: log.msg("Track_id doesn't exist, saving to database.", level=log.INFO) found_this_track.save() # Now that we have iTunes info, create the relationships to ARTIST and TRACK. try: check_a_msl = MusicServices_Artist_Lookup.objects.filter(artist=item['artist'], music_service_object_id_from_web=found_this_track.artist_id) #log.msg("ARTIST relationship exists in table, skipping.", level=log.INFO) except: check_a_msl = None log.msg("Setting ARTIST relationship to none.", level=log.WARNING) if not check_a_msl: try: a_msl = MusicServices_Artist_Lookup.objects.create(date_added=datetime.datetime.now(), artist=item['artist'], music_service=ms, music_service_object_id_from_web=found_this_track.artist_id) log.msg("Created a new ARTIST lookup relationship", level=log.INFO) except Exception as e: log.msg("Unable to assign ARTIST relationship to MusicServiceLookupTable.", level=log.ERROR) log.msg( e, level=log.ERROR) try: check_t_msl = MusicServices_Track_Lookup.objects.filter(track=item['track'], music_service_object_id_from_web=found_this_track.track_id) #log.msg("TRACK relationship exists in table, skipping.", level=log.INFO) except: check_t_msl = None log.msg("Setting TRACK relationship to none.", level=log.WARNING) if not check_t_msl: try: t_msl = MusicServices_Track_Lookup.objects.create(date_added=item['processing_time'].start_time, track=item['track'], music_service=ms, music_service_object_id_from_web=found_this_track.track_id) log.msg("Created a new TRACK lookup relationship", level=log.INFO) except: log.msg("Unable to assign TRACK relationship to MusicServiceLookupTable.", level=log.ERROR) log.msg( e, level=log.ERROR) try: log.msg("Item should be saved here.", level=log.INFO) item.save() log.msg("Looks like save was successful!", level=log.INFO) except MySQLdb.Error, e: log.msg("Exception found", level=log.ERROR) log.msg("Error %d: %s" % (e.args[0], e.args[1]), level=log.ERROR)