<?xml version="1.0" encoding="UTF-8"?>
<plugin-url>
  <approved type="boolean">true</approved>
  <author>Highgroove Studios</author>
  <cached-tag-list>google analytics, popularity</cached-tag-list>
  <canonical-name nil="true"></canonical-name>
  <code>require &quot;time&quot;

class GoogleAnalytics &lt; Scout::Plugin
  
  TEST_USAGE = &quot;#{File.basename($0)} user USER password PASSWORD account ACCOUNT profile PROFILE offset OFFSET&quot;
  
  USERAGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1'
  LANGUAGE = 'en-US'
  
  def require_libs
    require 'net/http'
    require 'net/https'
    require 'uri'
    require 'hpricot'
  end
  
  def run
    begin
      require_libs
    rescue LoadError
      begin
        require &quot;rubygems&quot;       
        require_libs
      rescue LoadError
        return { :error =&gt; { :subject =&gt; &quot;Couldn't load required libraries.&quot;,
                             :body    =&gt; &quot;Please see the required libaries in the README file&quot; } }
      end
    end

    # The following attributes are required:
    # - user
    # - password
    # - account
    # - profile
    if [@options[&quot;account&quot;],@options[&quot;profile&quot;],@options[&quot;user&quot;],@options[&quot;password&quot;]].map { |opt| opt.strip.length}.find { |v| v.zero? }
      return { :error =&gt; { :subject =&gt; &quot;The user, password, account, and profile must be provided.&quot; } }
    end
    
    init_request_vars
    unless login
      return { :error =&gt; { :subject =&gt; &quot;The user and/or password is invalid.&quot; } }
    end
    
    # grabs data from the current day
    data = visit_data(@options[&quot;account&quot;],@options[&quot;profile&quot;],Time.parse(Date.today.to_s).utc-(@options[&quot;offset&quot;].to_i*60*60),Time.parse(Date.today.to_s).utc-(@options[&quot;offset&quot;].to_i*60*60))
    
    { :report =&gt; data }
  rescue
    { :error =&gt; {:subject =&gt; &quot;Google Analytics data could not be collected&quot;,
                 :body    =&gt; &quot;#{$!.message}\n\n#{$!.backtrace}&quot;}
    }
  end # run

  # Vars that will be sent along with the request
  def init_request_vars
    @user = @options[&quot;user&quot;]
    @pass = @options[&quot;password&quot;]
  end
  
  # Logs into Google Analytics. 
  # Returns true if successful, false otherwise. 
  # Sets +@cookies+ for future requests.
  def login
    par = {'continue' =&gt;        'https://www.google.com/analytics/home/?et=reset&amp;hl=' + LANGUAGE,
     'service' =&gt;         'analytics',
     'nui' =&gt;	          'hidden',
     'hl' =&gt;              LANGUAGE,
     'GA3T'	=&gt;	  'ouVrvynQwUs',
     'Email' =&gt;           @user,
     'PersistentCookie'=&gt; 'yes',
     'Passwd' =&gt;          @pass}
  
    http = Net::HTTP.new(&quot;www.google.com&quot;, 443)
    http.use_ssl = true
    resp = nil
    http.start do |http|
      req = Net::HTTP::Post.new(&quot;/accounts/ServiceLoginBoxAuth&quot;)
      req.set_form_data(par)

      resp = http.request(req)
    end
   
    @cookies = resp.response['set-cookie'].split('; ')[0]
 
    if resp.code.to_i != 200
      false
    else
      true
    end
  end
  
  # Grabs the list of accounts for this user. Returns an Array of Hashes
  # that contains the account value and name.
  def list_accounts
    req = Hpricot(make_request('/analytics/home/?et=reset&amp;hl=' + LANGUAGE))
    # some logins are redirected
    title = req.search(&quot;title/text()&quot;).first
    options = if title.to_s =~ /301/           
                url = req.search(&quot;a&quot;).first['href']
                req = Hpricot(make_request(url))
                req.search(&quot;//select[@id='account']/option&quot;)
              else
                req.search(&quot;select[@name='account_list']/option&quot;)
              end
   if options.empty?
     if req.search(&quot;iframe[@id='login']&quot;)
       raise &quot;Unable to login to the Google Analytics with user [#{@options['user']}]. Please ensure the login and password is correct.&quot;
     end
   end
   accounts = []
   options.each do |opt|
   if opt['value'] != &quot;0&quot;
    acc = {}
    acc['value'] = opt['value']
    acc['name'] = opt.inner_html
    accounts &lt;&lt; acc
   end
   end
   accounts
  end
  
  # Lists profiles available under the +account_id+.
  def list_profiles_for_account(account_id)
    req = Hpricot(make_request(&quot;/analytics/home/admin?vid=1100&amp;scid=#{account_id}&quot;))
    find_profiles(req)
  end
  
  def find_profiles(req)
    options = req.search(&quot;select[@name='profile_list']/option&quot;)
     profiles = []
     options.each do |opt|
     if opt['value'] != &quot;0&quot;
      prof = {}
      prof['value'] = opt['value']
      prof['name'] = opt.inner_html
      profiles &lt;&lt; prof
     end
     end
     profiles
  end
  
  # Returns a 2-element hash with the number of visits and page_views over the specified range.
  def visit_data(account_name,profile_name,start_date,end_date)
    accounts = list_accounts
    account = accounts.find { |pair| pair[&quot;name&quot;] == account_name }
    
    if account.nil?
      error = &quot;Couldn't find the account with name: #{account_name}.&quot;
      if !accounts.any?
        error &lt;&lt; &quot; No accounts are available with the provided login information. Please ensure the user #{@options['user']} has access.&quot;
      else
        error &lt;&lt; &quot; #{accounts.size} Possible accounts: #{accounts.join(', ')}&quot;
      end
      raise error
    end
    
    account_id = account[&quot;value&quot;]
    
    profiles = list_profiles_for_account(account_id)
    profile  = profiles.find { |pair| pair[&quot;name&quot;] == profile_name }
    
    raise &quot;Couldn't find the profile with name: #{profile_name}&quot; if profile.nil?
          
    profile_id = profile[&quot;value&quot;]
    
    start_date = start_date.strftime(&quot;%Y%m%d&quot;)
    end_date   = end_date.strftime(&quot;%Y%m%d&quot;)
    
    req = Hpricot(make_request(&quot;/analytics/reporting/dashboard?id=#{profile_id}&amp;pdr=#{start_date}-#{end_date}&amp;cmp=average&quot;))
    
    visits = (req/&quot;//div[@id='VisitsSummary']//span[@class='primary_value']&quot;).inner_html.strip.gsub(/\D/,'').to_i
    page_views = (req/&quot;//div[@id='PageviewsSummary']//span[@class='primary_value']&quot;).inner_html.strip.gsub(/\D/,'').to_i
    
    {&quot;visits&quot; =&gt; visits, &quot;page_views&quot; =&gt; page_views}
  end
  
  def make_request(address)
    raise ScriptError, &quot;You should already be logged in!&quot; unless @cookies
      
    headers = {
       'Cookie' =&gt; @cookies,
       'User-Agent' =&gt; USERAGENT
  	}
    response, body = nil
    http = Net::HTTP.new(&quot;www.google.com&quot;, 443)
    http.use_ssl = true
    http.start do |http|
     req = Net::HTTP::Get.new(address, headers)
     response = http.request(req)
     body = response.body
    end
  
   body
  end
  
  
    
    
end # GoogleAnalytics
</code>
  <created-at type="datetime">2007-12-29T19:58:48-08:00</created-at>
  <default-triggers type="yaml" nil="true"></default-triggers>
  <description>Returns the number of page views and visits for the current day.&lt;br/&gt;

Code (and inspiration) taken and updated from Burnalytics:
http://www.eribium.org/blog/?p=51&lt;br/&gt;

*Dependencies*&lt;br/&gt;

Requires the following libraries:&lt;br/&gt;

require 'net/http'
require 'net/https'
require 'uri'
require 'rubygems'
require 'hpricot'</description>
  <featured type="boolean">false</featured>
  <id type="integer">9</id>
  <metadata type="yaml">--- |
options:
  user:
  password:
  account:
    name: Account
    notes: The name of the Google Analytics Account
  profile:
    name: Profile
    notes: The name of the profile
  offset:
    name: Offset
    notes: Time in hours that should be subtracted from UTC when grabbing the date

</metadata>
  <name>Google Analytics</name>
  <plugins-count type="integer">3</plugins-count>
  <rating-avg type="decimal" nil="true"></rating-avg>
  <rating-count type="integer" nil="true"></rating-count>
  <rating-total type="integer" nil="true"></rating-total>
  <readme>Google Analytics Plugin
======================
Created by [Highgroove Studios LLC](http://www.highgroove.com)

Returns the number of page views and visits for the current day. 

Code (and inspiration) taken and updated from [Burnalytics](http://www.eribium.org/blog/?p=51)

Dependencies
------------

Requires the [hpricot library](http://code.whytheluckystiff.net/hpricot/):

	sudo gem install hpricot

Compatibility 
-------------
Works fully on Linux and OSX. 



</readme>
  <schema type="yaml" nil="true"></schema>
  <scout-version type="integer">1</scout-version>
  <short-description>Returns the number of page views and visits for the current day. 

</short-description>
  <tested-platforms>linux macosx</tested-platforms>
  <total-usage-count type="integer">0</total-usage-count>
  <updated-at type="datetime">2009-09-23T23:03:11-07:00</updated-at>
  <url>http://github.com/highgroove/scout-plugins/raw/7d13f07023d2d284fefceca078a86718e928f4d0/google_analytics/google_analytics.rb</url>
</plugin-url>
