#!/usr/bin/rubyrequire"rubygems"require"nokogiri"require"open-uri"require"thread"require"iconv"require"rbconfig"requireFile.expand_path("../album",__FILE__)# Win环境?defon_windows?ifConfig::CONFIG["host_os"]=="mingw32"trueelsefalseendend# 任务类classAlbumDownloaddefinitializebeginget_cmd_paramsrescueArgumentError=>eputse.class.to_s,e.message,e.backtraceend@verified_urls=[]enddefgobeginverify_urls@verified_urls.eachdo|url|Album.factory(url).downloadendrescueInvalidUrlError=>eputse.class.to_s,e.message,e.backtraceexitendenddefdownloadendprotecteddefget_cmd_params# 没有命令行参数,抛出异常raiseArgumentError,"Please input an album url!"ifARGV.empty?@args=ARGVenddefverify_urls# 如果是有效链接,放入@verify_urls变量中# 命令行可以接收多个URL,但是实际用起来还是每次只输入一个就好。@args.eachdo|arg|@verified_urls<<argifvalid_album?(arg)endraiseInvalidUrlError,"Please input an valid album url!"if@verified_urls.empty?enddefvalid_album?(url)# 如果是豆瓣相册链接或者是人人相册链接douban_album?(url)||renren_album?(url)enddefdouban_album?(url)# 豆瓣相册URL正则验证DOUBAN_PUBLIC_ALBUM_URL_EXP=~urlenddefrenren_album?(url)# 人人相册URL正则验证RENREN_PUBLIC_ALBUM_URL_EXP=~urlendendif__FILE__==$0AlbumDownload.new.goend
classRenrenAlbum<Albumdefinitialize(url)super(url)@page_item=15endprotecteddefstart_downloadingcreate_album_folder(get_folder_name)(@sum/@page_item+1).timesdo|i|@page_threads<<Thread.newdourl=@current_url+"?curpage="+i.to_spage=Nokogiri::HTML(open(url))puts"Analyzing url #{url} ..."page.css("td.photoPan a").eachdo|link|@pic_threads<<Thread.newdourl=@current_url.scan(/http:\/\/[\w+\.]+/)[0].to_s+link.attribute("href").to_ssource=open(url).read.scan(/"large":"(http:[\\\/\w.]+\.jpg)"/)[0][0].gsub(/\\/,"")dest=/[\w_]+\.(jpg|jpeg|png)/i.match(source).to_swrite_file(source,File.join(@folder_name,dest))@lock.synchronize{puts"Created file #{dest} to #{@folder_name} from #{source} ... #{@download_count+=1}/#{@sum}"}endendendend@page_threads.each{|t|t.join}@pic_threads.each{|t|t.join}enddefget_folder_name@folder_name=/\d+$/.match(@current_url).to_s+"_"+@doc.css("div.pager-top span h3").inner_text.to_s@folder_name=Iconv.iconv("GB2312","UTF-8",@folder_name).to_sifon_windows?enddefget_album_pic_countre=@doc.css("div.pager-top span").inner_text.to_s.scan(/共(\d+)张/)raiseInvalidAlbumError,"This is an invalid ablum!"ifre.nil?@sum=re[0][0].to_iendend