<commit_before>#!/usr/bin/env ruby

$LOAD_PATH.unshift File.dirname(__FILE__) + '/lib'

require 'sinatra'
require "sinatra/json"
require 'tweetstream'
require 'yaml'
require 'twitter'
require 'httparty'
require 'geo2gov'
require 'sinatra/activerecord'
require 'uri'
require './mailer'

# If we're on Heroku use its database else use a local sqlite3 database. Nice and easy!
db = URI.parse(ENV['DATABASE_URL'] || 'sqlite3:///development.db')

ActiveRecord::Base.establish_connection(
  :adapter  => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
  :host     => db.host,
  :username => db.user,
  :password => <PASSWORD>,
  :database => db.path[1..-1],
  :encoding => 'utf8'
)

# At this point, you can access the ActiveRecord::Base class using the
# "database" object:
#puts "the authorities table doesn't exist" if !database.table_exists?('authorities')

class Authority < ActiveRecord::Base
  def self.find_by_location(location)
    geo2gov_response = Geo2gov.new(location)
    lga_code = geo2gov_response.lga_code[3..-1] if geo2gov_response.lga_code
    find_by_lga_code(lga_code.to_i) if lga_code
  end
end

get "/" do
  "Hello World!"
end

get '/api' do
  haml :api
end

get '/api/authorities.json' do
  json Authority.all
end

get '/api/authority.json' do
  if params[:location]
    json Authority.find_by_location(params[:location])
  elsif params[:lng] and params[:lat]
    json Authority.find_by_location("#{params[:lng]},#{params[:lat]}")
  end
end

# Set config from local file for development (and use environment variables on Heroku)
if File.exists? 'configuration.yaml'
  configuration = YAML.load_file('configuration.yaml')
  ENV['CONSUMER_KEY'] = configuration['consumer']['key']
  ENV['CONSUMER_SECRET'] = configuration['consumer']['secret']
  ENV['OAUTH_TOKEN'] = configuration['oauth']['token']
  ENV['OAUTH_TOKEN_SECRET'] = configuration['oauth']['token_secret']
end

def respond_to_tweet(status)
  if status.geo
    geo2gov_response = Geo2gov.new("#{status.geo.coordinates[1]},#{status.geo.coordinates[0]}")
    lga_code = geo2gov_response.lga_code[3..-1] if geo2gov_response.lga_code
    if lga_code
      authority = Authority.find_by_lga_code(lga_code.to_i)
      if authority
        if authority.twitter_screen_name
          Twitter.update("#{authority.twitter_screen_name} RT @#{status.user.screen_name}: #{status.text.gsub('#tmyc', '')}")
        elsif authority.contact_email
          AuthorityMailer.email(authority.contact_email, status.text.gsub('#tmyc', ''), "https://twitter.com/#{status.user.screen_name}/status/#{status.id_str}").deliver
          Twitter.update(
            "@#{status.user.screen_name} #{authority.name} is not on Twitter, I've emailed your tweet to #{authority.contact_email}",
            :in_reply_to_status_id => status.id.to_i
          )
        elsif authority.website_url
          Twitter.update(
            "@#{status.user.screen_name} #{authority.name} is not on Twitter, try #{authority.website_url}",
            :in_reply_to_status_id => status.id.to_i
          )
        else
          Twitter.update(
            "@#{status.user.screen_name} #{authority.name} is not on Twitter",
            :in_reply_to_status_id => status.id.to_i
          )
        end
      else
        Twitter.update(
          "@#{status.user.screen_name} I found you but I don't know about LGA code #{lga_code}",
          :in_reply_to_status_id => status.id.to_i
        )
      end
    else
      Twitter.update("@#{status.user.screen_name} I found you but it doesn't look like you're in Australia",
        :in_reply_to_status_id => status.id.to_i
      )
    end
  else
    Twitter.update("@#{status.user.screen_name} You need to add location information to your Tweet so I know where you are",
      :in_reply_to_status_id => status.id.to_i
    )
  end
end

EM.schedule do
  TweetStream.configure do |config|
    config.consumer_key = ENV['CONSUMER_KEY']
    config.consumer_secret = ENV['CONSUMER_SECRET']
    config.oauth_token = ENV['OAUTH_TOKEN']
    config.oauth_token_secret = ENV['OAUTH_TOKEN_SECRET']
    config.auth_method = :oauth
  end

  Twitter.configure do |config|
    config.consumer_key = ENV['CONSUMER_KEY']
    config.consumer_secret = ENV['CONSUMER_SECRET']<commit_msg>Extracted method for just returning the response back to the original user<commit_after>#!/usr/bin/env ruby

$LOAD_PATH.unshift File.dirname(__FILE__) + '/lib'

require 'sinatra'
require "sinatra/json"
require 'tweetstream'
require 'yaml'
require 'twitter'
require 'httparty'
require 'geo2gov'
require 'sinatra/activerecord'
require 'uri'
require './mailer'

# If we're on Heroku use its database else use a local sqlite3 database. Nice and easy!
db = URI.parse(ENV['DATABASE_URL'] || 'sqlite3:///development.db')

ActiveRecord::Base.establish_connection(
  :adapter  => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
  :host     => db.host,
  :username => db.user,
  :password => <PASSWORD>,
  :database => db.path[1..-1],
  :encoding => 'utf8'
)

# At this point, you can access the ActiveRecord::Base class using the
# "database" object:
#puts "the authorities table doesn't exist" if !database.table_exists?('authorities')

class Authority < ActiveRecord::Base
  def self.find_by_location(location)
    geo2gov_response = Geo2gov.new(location)
    lga_code = geo2gov_response.lga_code[3..-1] if geo2gov_response.lga_code
    find_by_lga_code(lga_code.to_i) if lga_code
  end
end

get "/" do
  "Hello World!"
end

get '/api' do
  haml :api
end

get '/api/authorities.json' do
  json Authority.all
end

get '/api/authority.json' do
  if params[:location]
    json Authority.find_by_location(params[:location])
  elsif params[:lng] and params[:lat]
    json Authority.find_by_location("#{params[:lng]},#{params[:lat]}")
  end
end

# Set config from local file for development (and use environment variables on Heroku)
if File.exists? 'configuration.yaml'
  configuration = YAML.load_file('configuration.yaml')
  ENV['CONSUMER_KEY'] = configuration['consumer']['key']
  ENV['CONSUMER_SECRET'] = configuration['consumer']['secret']
  ENV['OAUTH_TOKEN'] = configuration['oauth']['token']
  ENV['OAUTH_TOKEN_SECRET'] = configuration['oauth']['token_secret']
end

def response_to_tweet(status, lga_code, authority)
  if status.geo
    if lga_code
      if authority
        if authority.twitter_screen_name
          nil
        elsif authority.contact_email
          "#{authority.name} is not on Twitter, I've emailed your tweet to #{authority.contact_email}"
        elsif authority.website_url
          "#{authority.name} is not on Twitter, try #{authority.website_url}"
        else
          "#{authority.name} is not on Twitter"
        end
      else
        "I found you but I don't know about LGA code #{lga_code}"
      end
    else
      "I found you but it doesn't look like you're in Australia"
    end
  else
    "You need to add location information to your Tweet so I know where you are"
  end
end

def respond_to_tweet(status)
  if status.geo
    geo2gov_response = Geo2gov.new("#{status.geo.coordinates[1]},#{status.geo.coordinates[0]}")
    lga_code = geo2gov_response.lga_code[3..-1] if geo2gov_response.lga_code
    if lga_code
      authority = Authority.find_by_lga_code(lga_code.to_i)
      if authority
        if authority.twitter_screen_name
          Twitter.update("#{authority.twitter_screen_name} RT @#{status.user.screen_name}: #{status.text.gsub('#tmyc', '')}")
        elsif authority.contact_email
          AuthorityMailer.email(authority.contact_email, status.text.gsub('#tmyc', ''), "https://twitter.com/#{status.user.screen_name}/status/#{status.id_str}").deliver
        end
      end
    end
  end

  # Now send a response back to the user that sent the original tweet (if necessary)
  r = response_to_tweet(status, lga_code, authority)
  Twitter.update("@#{status.user.screen_name} #{r}", :in_reply_to_status_id => status.id.to_i) if r    
end

EM.schedule do
  TweetStream.configure do |config|
    config.consumer_key = ENV['CONSUMER_KEY']
    config.consumer_secret = ENV['CONSUMER_SECRET']
    config.oauth_token = ENV['OAUTH_TOKEN']
    config.oauth_token_secret = ENV['OAUTH_TOKEN_SECRET']
    config.auth_method = :oauth
  end

  Twitter.configure do |config|
    config.consumer_key = ENV['CONSUMER_KEY']
    config.consumer_secret = ENV['CONSUMER_SECRET']
{'fraction_non_alphanumeric': 0.1259870782483848, 'fraction_numerical': 0.004785833931562575, 'mean_word_length': 3.854239256678281, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 24, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '383718', 'n_tokens_mistral': 2854, 'n_tokens_neox': 2799, 'n_words': 631}