#!/usr/bin/env ruby

require 'net/http'

user_agent='Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko'

# define the banned list
banned = [ "54523", "55282", "57063", "54527", "54570", "68992", "55476", "54682", "56310", "55333", "54683", "55369", "55419", "55675", "55812", "55678", "56312", "59882", "55160", "56071", "54618", "62255", "55300", "54726", "55679", "55149", "54619", "54644", "54534", "55284", "55338", "55587", "55276", "55212", "57476", "58311", "55243", "54788", "55805", "55033", "54811", "55222", "54701", "55235", "54809", "55247", "55348", "56096", "54937", "54673", "54684", "55886", "56178", "56237", "54923", "55772", "54532", "55327", "69550", "55585" ]

  puts "Gathering data from tweeterwall..."
  # GET request -> so the host can set his cookies and get the crucial data
  http = Net::HTTP.new('tweeterwall.mallplace.com')
  resp, data = http.get('/tw/fan-series/miley-cyrus-fans', {'User-Agent' => user_agent})
  cookies = resp.response['set-cookie']
  
  # get the country id
  re = Regexp.new('users-country" rel="(\d+)"')
  cid = re.match(data)[1]
  # get the token
  re = Regexp.new('id="edit-auto-submit-token" value="(\w+)"')
  token = re.match(data)[1]
  # get the number of pages
  re = Regexp.new('pager-last last.*?page=(\d+)')
  pages = re.match(data)[1]
  
  for page in (0..(Integer(pages)-1))
    puts "Upvoting ids on page #{page}/#{pages}"
    http = Net::HTTP.new('tweeterwall.mallplace.com')
    resp, data = http.get("/tw/fan-series/miley-cyrus-fans?page=#{page}", {'User-Agent' => user_agent})
    re = Regexp.new('twitter-pic(\d+)')
    ids = data.scan(re)
    
    # upvote each id from the page
    for match in ids
      uid = match[0]
      print "-" + uid
      if banned.include?(uid)
        puts "=> banned"
      else
        # vote for the user
      	headers = { "Referrer" => "http://tweeterwall.mallplace.com/tw/fan-series/miley-cyrus-fans", "Referer" => "http://tweeterwall.mallplace.com/tw/fan-series/miley-cyrus-fans", "Cookie" => cookies, 'User-Agent' => user_agent}
  	    url = URI.parse("http://tweeterwall.mallplace.com/tw/vote")
  	    req = Net::HTTP::Post.new(url.path, headers)
  	    req.set_form_data({'uid' => uid, 'country_id' => cid, 'token' => token})
  	    response = Net::HTTP.new(url.host, url.port).start { |http| http.request(req) }
  
  	    if response.body.include? "success"
  		    puts " => upvoted!"
  	    else
  		    puts " => failed :("
        end
      end
    end
  end