#! /usr/bin/python
# -*- coding: iso-8859-1 -*-
#
__author__='Lorenzo Carbonell'
__date__ ='$10/06/2011'
#
#
# Copyright (C) 2011 Lorenzo Carbonell
# lorenzo.carbonell.cerezo@gmail.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
import urllib2
import re
import sys
import os
from os.path import basename
from urlparse import urlsplit

EXTENSIONS = ['.jpg','.png','.gif','.jpeg']

def download_images_from_url(url):
	if not url.lower().startswith('http://') and not url.lower().startswith('https://'):
		url = 'http://%s'%url
	print 'Downloading from %s...'%url
	urlContent = urllib2.urlopen(url).read()
	# HTML image tag: <img src="url" alt="some_text"/>
	imgUrls = re.findall('img .*?src="(.*?)"', urlContent)

	# download all images
	for imgUrl in imgUrls:		
		imgData = urllib2.urlopen(imgUrl).read()
		fileName = basename(urlsplit(imgUrl)[2])
		base,ext = os.path.splitext(fileName)
		ext = ext.lower()
		fileName = base + ext
		print fileName
		try:
			if ext in EXTENSIONS:
				print 'Downloading %s...'%fileName
				output = open(fileName,'wb')
				output.write(imgData)
				output.close()
		except Exception,e:
			print e
if __name__ == '__main__':
	args = sys.argv
	if len(args) < 2:
		print 'I need an url to download images'
		exit(-1)
	print args[1]
	download_images_from_url(args[1])
	exit(0)
