Dump entire photos in Facebook album with Python

Simple dumping photos from albums in facebook by python. in this case, we must got an authorization before dump the albums. first of all, we have to login to the facebook required user and password. afterwards we have to fetching a couples of line called token key which that it’s an authorization key for grab the data.

#!/usr/bin/python
# -*- coding: utf-8 -*-
#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library 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
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the 
#      Free Software Foundation, Inc., 
#      59 Temple Place, Suite 330, 
#      Boston, MA  02111-1307  USA
#
#   by pulpn.com

import json, random, re
import urllib, urllib2
import sys, os
import cookielib

# Random user-agents
user_agents = [
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
    'Opera/9.25 (Windows NT 5.1; U; en)',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
    'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
    'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9'
]

# Facebook photo dumper
class _fbphotosdumper_(object):
	def __init__(self, user, pswd, album_name):
    		self.dictid 	= {}
    		self.count 	= {}
    		self.user 	= user
    		self.pswd 	= pswd
    		self.album_name = album_name
    		self.value 	= {'post_form_id' : '42d7f2c5ff3976d42ead29cbda1561ec',
                  	      	   'email':user,
                  	           'pass' :pswd}
    		self.home 	= 'http://m.facebook.com/home.php'
    		self.url 	= 'https://www.facebook.com/login.php?m=m&refsrc=http%3A%2F%2Fm.facebook.com%2F&refid=8'
    		self.cj 	= cookielib.CookieJar()
    		self.opener 	= urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
  	def login(self):
    		login_data 		= urllib.urlencode(self.value)
    		self.opener.addheaders 	= [('User-agent', random.choice(user_agents))]
    		self.opener.open(self.url,login_data)

	# Doesn't need profile id, this is token rules. Get token key from developers.facebook.com
  	def get_token(self):
    		url_api = self.opener.open('https://developers.facebook.com/docs/reference/api/')
    		rurl_api = url_api.read()
    		get = re.search(r'access_token=(.*)">',rurl_api)
    		if get:
      			return get.group(1)
  	def get_albums(self):
    		url_album 	= self.opener.open('https://graph.facebook.com/me/albums?access_token=%s&limit=99'%(self.get_token()))
    		rurl_album 	= url_album.read()
    		_albumfilter_ 	= json.loads(rurl_album)
    		for i in _albumfilter_['data']:
      			try:
        			name 	= i['name']
        			albumid = i['id']
        			psum 	= i['count']
        			self.dictid[name] = albumid
        			self.count[name] = psum
        			#return name,psum
      			except:
       	 			pass
  	def get_photos(self):
    		self.get_albums()
    		sys.stdout.write('Downloading %s photos from "%s" album\n'%(self.count[self.album_name],self.album_name))
 	   	url_photos = self.opener.open('https://graph.facebook.com/%s/photos?access_token=%s&limit=99'%(self.dictid[self.album_name],
												   	       self.get_token()))
    		rurl_photos = url_photos.read()
    		_photosfilter_ = json.loads(rurl_photos)
    		image = urllib.URLopener()
    		for x in _photosfilter_['data']:
			try:
	      			link = x['source']
      				os.chdir(current)
      				image.retrieve(link,'%s'%link.split('/')[-1])
      				print link.split('/')[-1],'Saved in "%s"'%(current)
			except KeyboardInterrupt:
				sys.stdout.write('Download interrupted\n')
def main():
	global current
	if len(sys.argv) == 4:
		# Create a directory for fetched images from facebook album
		folder= 'Facebook Album - %s'%(sys.argv[3])
		current = os.getcwd()+'/%s'%folder
		os.system('mkdir "%s"'%folder)#"%s"'%folder
		facebook = _fbphotosdumper_(sys.argv[1],sys.argv[2],sys.argv[3])
		try:
			facebook.login()
		except:
			print 'Login Error'
		try:
			facebook.get_photos()
		except:
			print 'No album named "%s"'%(sys.argv[3])
	else:
		print 'Facebook Photos dumper'
		print '----------------------------------------'
		print 'Usage\t: %s user pswd "Album name"'%sys.argv[0]
		print 'Example\t: %s foo@bar.com fubar "Foo Bar"'%sys.argv[0]
		sys.exit(1)
if __name__ == '__main__':
	main()