Created
November 28, 2015 21:13
-
-
Save brighid/c3d19f2c6749fbec30ed to your computer and use it in GitHub Desktop.
This is the core of an Octopress plugin that lets you put music data in posts' YAML front-matter and have a link to the iTunes Music Store show up in the post.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'cgi' | |
require 'json' | |
require 'net/http' | |
require 'uri' | |
module Jekyll | |
class MusicLink < Liquid::Tag | |
def initialize(tag_name, contents, tokens) | |
super | |
@contents = contents | |
end | |
def render(context) | |
@affiliateCode = 'secret' # Fill in yours! | |
page = context.environments.first['page'] | |
if page['music-artist'] && page['music-track'] | |
music_url, music_string = getMusic(page['music-artist'], page['music-track']) | |
return %(<span class='music-box'>Music: <a class='music-link' href="#{music_url}">#{music_string}</a></span>) | |
else | |
return %() | |
end | |
end | |
def makeItunesTarget(artist, track) | |
iTunesURL = URI("https://itunes.apple.com/search") | |
iTunesParams = { | |
:country => "us", :media => "music", | |
:limit => "5", :entity => "musicTrack", | |
:term => artist + " " + track, | |
} | |
iTunesURL.query = URI.encode_www_form(iTunesParams) | |
return iTunesURL | |
end | |
def getFromItunes(iTunesURL) | |
http = Net::HTTP.new(iTunesURL.host, iTunesURL.port) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_PEER | |
request = Net::HTTP::Get.new(iTunesURL.request_uri) | |
response = http.request(request) | |
if response.code == "200" | |
jsonResponse = JSON.load(response.body) | |
if jsonResponse['resultCount'] == 0 | |
jsonResponse = false | |
end | |
else | |
jsonResponse = false | |
end | |
return jsonResponse | |
end | |
def makeAnchorFromItunesData(iTunesJSON) | |
unless iTunesJSON | |
return iTunesJSON, iTunesJSON | |
end | |
primaryResult = iTunesJSON['results'].first | |
if @affiliateCode | |
urlRegex = /(https:\/\/itunes\.apple\.com\/[^?]+\?[^&]+).+/ | |
urlReplacement = '\1\2&partnerId=30&siteID=' + @affiliateCode | |
affiliatedTrackUrl= primaryResult['trackViewUrl'].sub(urlRegex, urlReplacement) | |
primaryResult['trackViewUrl'] = affiliatedTrackUrl | |
end | |
anchorURL = primaryResult['trackViewUrl'] | |
anchorString = CGI.escapeHTML("%s - %s" % [primaryResult['artistName'], primaryResult['trackName']]) | |
return anchorURL, anchorString | |
end | |
def getMusic(artist_name, track_name) | |
music_url, music_string = makeAnchorFromItunesData(getFromItunes(makeItunesTarget(artist_name, track_name))) | |
return music_url, music_string | |
end | |
end | |
end | |
Liquid::Template.register_tag('music', Jekyll::MusicLink) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment