class Utils RECORDING_SRC_PREFIX = 'rec_' RECORDING_SOURCES = ["#{RECORDING_SRC_PREFIX}youtube", "#{RECORDING_SRC_PREFIX}soundcloud"] USERNAME_SITES = %W{youtube facebook soundcloud bandcamp fandalism twitter reverbnation} SITE_TYPES = ['url'].concat(USERNAME_SITES).concat(RECORDING_SOURCES) USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36" def self.recording_source?(site) RECORDING_SOURCES.include?(site) end def self.extract_recording_data(site, recording_url) recording_url.strip! rec_data = {} case site when 'rec_youtube' # regex derived from: https://gist.github.com/afeld/1254889 watch = (recording_url =~ /(youtu.be\/|youtube.com\/(watch\?(.*&)?v=|(embed|v)\/))([^\?&\"\'>]+)/) rec_data["id"] = $5 if watch uri = URI.parse("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=#{$5}&key=#{APP_CONFIG.google_public_server_key}") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' req = Net::HTTP::Get.new(uri) response = http.request(req) if response && response.body.length > 2 json = response.body.force_encoding("UTF-8")# .encode('UTF-8', :invalid => :replace, :replace => '') json_hash = JSON.parse(json) if watch && json_hash["items"] && json_hash["items"].length == 1 rec_data["title"] = json_hash["items"][0]["snippet"]["title"] end end when 'rec_soundcloud' if recording_url =~ /^https?:\/\/.*soundcloud.com\/.+/ tmpfile = Tempfile.new(site) tmpfile.close curl_args = "-A '#{USER_AGENT}' -L --output #{tmpfile.path} --fail --show-error " `curl #{curl_args} '#{recording_url}' 2>&1` result = File.read(tmpfile.path) File.delete(tmpfile.path) if result =~ /"soundcloud:\/\/sounds:(\d+)"/ rec_data["id"] = $1 end if result =~ /property=\"og:title\" content=\"([\w\W]+)\">