#!/usr/bin/env python """This script is published under the MIT License Copyright (c) 2008 Nick Jensen 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.""" import os, socket, sys, re, urllib, urllib2 socket.setdefaulttimeout(10) class SimpleWGET(urllib.FancyURLopener): ''' a simple class to download and save files ''' def __init__(self): urllib.FancyURLopener.__init__(self) urllib._urlopener = self def fetch(self, url, dst="."): fn = os.sep.join([dst, urllib.unquote_plus(url.split('/').pop())]) if os.path.isfile(fn): print "Skipping... %s already exists!" % fn return if sys.stdout.isatty(): try: urllib.urlretrieve(url, fn, lambda nb,bs,fs,url=url,fn=fn: self._reporthook(nb,bs,fs,url,fn) ) sys.stdout.write('\n') except IOError, e: print str(e) except Exception, e: pass else: urllib.urlretrieve(url, fn) def _reporthook(self, numblocks, blocksize, filesize, url=None, fn=None): try: percent = min((numblocks*blocksize*100)/filesize, 100) except: percent = 100 if numblocks != 0: sys.stdout.write('\r') if len(fn) > 65: third = round(len(fn) / 3) fn = '%s...%s' % (fn[:third],fn[third*2:]) sys.stdout.write("%3s%% - Downloading - %s" % (percent,fn)) sys.stdout.flush() def http_error_default(self, *args, **kw): print "Oops... %s - %s" % (args[2],args[3]) class Google: ''' search google and return a list of result links ''' @classmethod def search(class_, params, num_results='10'): valid_num_results = [ '5', '10', '25', '50', '100' ] if num_results in valid_num_results: # build the query url = 'http://www.google.com/search?num=%s&q=%s' % (num_results, params) # spoof the user-agent headers = {'User-Agent':'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'} req = urllib2.Request(url, None, headers) html = urllib2.urlopen(req).read() results = [] # regex the results atags = re.compile(r'', re.IGNORECASE) href = re.compile(r'(?<=href=(\"|\')).*?(?=\1)', re.IGNORECASE) for link in atags.findall(html): if "class=l" in link: results.append(href.search(link).group()) return results else: raise ValueError( "num_results must be either %s" % ', '.join(valid_num_results) ) class MediaFinder(SimpleWGET): def __init__(self): SimpleWGET.__init__(self) def find_music(self, term, results_to_search='10', strict=True): ''' do a smart google search for music, crawl the result pages and download all audio files found. ''' audio_ext = ['mp3','m4a','wma','wav','ogg','flac'] audio_options = { '-inurl' : ['(htm|html|php|shtml|asp|jsp|pls|txt|aspx|jspx)'], 'intitle' : ['index.of', '"last modified"', 'description', 'size', '(%s)' % '|'.join(audio_ext)] } vars = '' for opt, val in audio_options.items(): vars = '%s%s:%s ' % (vars, opt, ' '.join(val)) query = urllib.quote_plus(' '.join([vars,term])) try: google_results = Google.search( query, results_to_search ) except urllib2.URLError, e: print "Error fetching google results: %s" % e i = 1 for url in google_results: print "Searching %s of %s pages." % (i, len(google_results)) if strict: self.download_all(url, audio_ext, term) else: self.download_all(url, audio_ext) i += 1 def download_all(self, url, extensions=['avi','divx','mpeg','mpg','wmv','flv','mp3','m4a','wma','wav','ogg','flac'], term=''): ''' download all files found on a web page that have an extension listed. (optionally match a term found in the URL) ''' media = re.compile(r'(?<=href=(\"|\'))[^\"\']+?\.(%s)(?=\1)' % '|'.join(extensions), re.IGNORECASE) try: req = urllib.urlopen(url) html = req.readlines() req.close() found = [] for line in html: match = media.search(line) if match: link = match.group() if 'http://' in link: # absolute url found.append(link) elif link[0] == '/': # from web root root_url = url[0:url.find('/',7)] found.append(''.join([root_url,link])) else: # relative urls ../ ./ etc. link_dir = url[0:url.rfind('/')].split('/') for piece in link.split('../')[:-1]: link_dir.pop() filename = re.search('[^.\/].*$',link).group() link_dir.append(filename) found.append('/'.join(link_dir)) if not found: print "No media found..." else: print "Found %s files!" % len(found) for url in found: if not term or \ strip_and_tolower(term) in strip_and_tolower(url): self.fetch(url) except IOError, e: print "Error: %s" % e def strip_and_tolower(url): strip = re.compile('[^\w]', re.IGNORECASE) return strip.sub('', urllib.unquote_plus(url.lower())) if __name__ == "__main__": finder = MediaFinder() args = sys.argv if len(args) in range(2,6): term = args[1] results_to_search = '10' strict = True if '-r' in args: results_to_search = str(args[args.index('-r')+1]) if '--non-strict' in args: strict = False try: finder.find_music( """%s""" % term, results_to_search, strict ) except: print "\n" else: print """usage: %s "search terms" [-r (5|10|25|50|100) [--non-strict]]""" % args[0]