<commit_before>require "rubygems"
require "twilio-ruby"
require "yaml"
require "sinatra"

$config = YAML::load(File.read("./config.yml"))

$validator = Twilio::Util::RequestValidator.new($config["twilio"]["token"])
$client = Twilio::REST::Client.new($config["twilio"]["sid"], $config["twilio"]["token"])

# General door handling
# Need to move this to a thread or unlink it from the initial Twilio response.
# Maybe use <Redirect>
def notify_arrival(data)
  return if data["mode"] == "none"
  $client.account.sms.messages.create(:from => $config["send_from"], :to => data["phone"], :body => data["message"])
end

def verify_call
  #unless $validator.validate(request.url, params, request.env["HTTP_X_TWILIO_SIGNATURE"])
  #  return (Twilio::TwiML::Response.new {|r| r.Say("We're sorry, your call could not be verified.")}).text
  #end

  unless params[:From] == $config["require_from"]
    return (Twilio::TwiML::Response.new {|r| r.Say("We're sorry, your call could not be verified.") }).text
  end

  nil
end

post "/" do
  if ( data = verify_call )
    return data
  end

  # Open the door since we're still automatically opening
  if $config["auto_open"]["ends_at"] and $config["auto_open"]["ends_at"] > Time.now.utc.to_i
    twiml = Twilio::TwiML::Response.new do |r|
      # DTMF tones can't be arbitrarily played back in Twilio.
      # http://www.dialabc.com/sound/generate/ will generate the DTMF sound easily
      r.Play($config["open_file"])
      r.Say("Welcome")
    end

    $config["auto_open"]["codes"].each do |code|
      notify_arrival($config["codes"][code])
    end
  # Require a passcode
  else
    code_length = $config["codes"].keys.first.to_s.length

    twiml = Twilio::TwiML::Response.new do |r|
      r.Gather(:numDigits => code_length, :timeout => $config["timeout"], :finishOnKey => "#", :action => "/code") do |g|
        g.Say("Please enter the #{code_length} digit code.")
      end
    end
  end

  return twiml.text
end

post "/code" do
  if ( data = verify_call )
    return data
  end

  if ( data = $config["codes"][params[:Digits].to_i] )
    notify_arrival(data)

    twiml = Twilio::TwiML::Response.new do |r|
      r.Play($config["open_file"])
      r.Say("Welcome")
    end
  else
    twiml = Twilio::TwiML::Response.new {|r| r.say("Sorry, that code is incorrect.")}
  end

  twiml.text
end

# Admin
def flush_config
  file = File.open("./config.yml", "w+")
  file.write(YAML.dump($config))
  file.close
end

def parse_number(number)
  number = number.gsub(/[^0-9]/, "")

  case number.length
    when 10 then "+1#{number}"
    when 11 then "+#{number}"
    else nil
  end
end

def format_phone(number)
  number.gsub(/\+1([0-9]{3})([0-9]{3})([0-9]{4})/, "(\\1) \\2-\\3")
end

def verify_admin
  #unless $validator.validate(request.url, params, request.env["HTTP_X_TWILIO_SIGNATURE"])
  #  return (Twilio::TwiML::Response.new {|r| r.SMS("Sorry, your request is invalid.")}).text
  #end

  nil
end

post "/sms" do
  if ( data = verify_admin )
    return data
  end

  twiml = nil
  cmd, args = params[:Body].split(" ", 2)
  cmd = cmd.downcase

  # Basic auth/deauth
  if cmd == "authorize"
    if $config["admin"]["password"] == data
      $config["admin"]["authorized"].push(params[:From])
      flush_config

      twiml = Twilio::TwiML::Response.new {|r| r.SMS("Authorized!")}
    else
      twiml = Twilio::TwiML::Response.new {|r| r.SMS("Access Denied.")}
    end

    return twiml.respond
  elsif cmd == "unauthorize"
    if $config["admin"]["password"] == data
      $config["admin"]["authorized"].delete(params[:From])
      flush_config

      twiml = Twilio::TwiML::Response.new {|r| r.SMS("Unauthorized this phone.")}
    else
      twiml = Twilio::TwiML::Response.new {|r| r.SMS("Access Denied.")}
    end

    return twiml.text
  end

  # Anything after we need to actually be authorized to this
  unless $config["admin"]["authorized"].include?(params[:From])
    return (Twilio::TwiML::Response.new {|r| r.SMS("Access Denied.")}).text
  end

  # Automatically unlock anytime someone asks it to for a set time limit
  if cmd == "unlock"
    amount, unit, codes = args.split(" ", 3)
    amount = amount.to_i

    $config["auto_open"]["ends_at"] = Time.now.utc
    $config["auto_open"]["codes"] = []
    if unit =~ /^seconds{0,}$/i
      $config["auto_open"]["ends_at"] += amount<commit_msg>Fix typo from old Twilio API<commit_after>require "rubygems"
require "twilio-ruby"
require "yaml"
require "sinatra"

$config = YAML::load(File.read("./config.yml"))

$validator = Twilio::Util::RequestValidator.new($config["twilio"]["token"])
$client = Twilio::REST::Client.new($config["twilio"]["sid"], $config["twilio"]["token"])

# General door handling
# Need to move this to a thread or unlink it from the initial Twilio response.
# Maybe use <Redirect>
def notify_arrival(data)
  return if data["mode"] == "none"
  $client.account.sms.messages.create(:from => $config["send_from"], :to => data["phone"], :body => data["message"])
end

def verify_call
  #unless $validator.validate(request.url, params, request.env["HTTP_X_TWILIO_SIGNATURE"])
  #  return (Twilio::TwiML::Response.new {|r| r.Say("We're sorry, your call could not be verified.")}).text
  #end

  unless params[:From] == $config["require_from"]
    return (Twilio::TwiML::Response.new {|r| r.Say("We're sorry, your call could not be verified.") }).text
  end

  nil
end

post "/" do
  if ( data = verify_call )
    return data
  end

  # Open the door since we're still automatically opening
  if $config["auto_open"]["ends_at"] and $config["auto_open"]["ends_at"] > Time.now.utc.to_i
    twiml = Twilio::TwiML::Response.new do |r|
      # DTMF tones can't be arbitrarily played back in Twilio.
      # http://www.dialabc.com/sound/generate/ will generate the DTMF sound easily
      r.Play($config["open_file"])
      r.Say("Welcome")
    end

    $config["auto_open"]["codes"].each do |code|
      notify_arrival($config["codes"][code])
    end
  # Require a passcode
  else
    code_length = $config["codes"].keys.first.to_s.length

    twiml = Twilio::TwiML::Response.new do |r|
      r.Gather(:numDigits => code_length, :timeout => $config["timeout"], :finishOnKey => "#", :action => "/code") do |g|
        g.Say("Please enter the #{code_length} digit code.")
      end
    end
  end

  return twiml.text
end

post "/code" do
  if ( data = verify_call )
    return data
  end

  if ( data = $config["codes"][params[:Digits].to_i] )
    notify_arrival(data)

    twiml = Twilio::TwiML::Response.new do |r|
      r.Play($config["open_file"])
      r.Say("Welcome")
    end
  else
    twiml = Twilio::TwiML::Response.new {|r| r.say("Sorry, that code is incorrect.")}
  end

  twiml.text
end

# Admin
def flush_config
  file = File.open("./config.yml", "w+")
  file.write(YAML.dump($config))
  file.close
end

def parse_number(number)
  number = number.gsub(/[^0-9]/, "")

  case number.length
    when 10 then "+1#{number}"
    when 11 then "+#{number}"
    else nil
  end
end

def format_phone(number)
  number.gsub(/\+1([0-9]{3})([0-9]{3})([0-9]{4})/, "(\\1) \\2-\\3")
end

def verify_admin
  #unless $validator.validate(request.url, params, request.env["HTTP_X_TWILIO_SIGNATURE"])
  #  return (Twilio::TwiML::Response.new {|r| r.SMS("Sorry, your request is invalid.")}).text
  #end

  nil
end

post "/sms" do
  if ( data = verify_admin )
    return data
  end

  twiml = nil
  cmd, args = params[:Body].split(" ", 2)
  cmd = cmd.downcase

  # Basic auth/deauth
  if cmd == "authorize"
    if $config["admin"]["password"] == data
      $config["admin"]["authorized"].push(params[:From])
      flush_config

      twiml = Twilio::TwiML::Response.new {|r| r.SMS("Authorized!")}
    else
      twiml = Twilio::TwiML::Response.new {|r| r.SMS("Access Denied.")}
    end

    return twiml.text
  elsif cmd == "unauthorize"
    if $config["admin"]["password"] == data
      $config["admin"]["authorized"].delete(params[:From])
      flush_config

      twiml = Twilio::TwiML::Response.new {|r| r.SMS("Unauthorized this phone.")}
    else
      twiml = Twilio::TwiML::Response.new {|r| r.SMS("Access Denied.")}
    end

    return twiml.text
  end

  # Anything after we need to actually be authorized to this
  unless $config["admin"]["authorized"].include?(params[:From])
    return (Twilio::TwiML::Response.new {|r| r.SMS("Access Denied.")}).text
  end

  # Automatically unlock anytime someone asks it to for a set time limit
  if cmd == "unlock"
    amount, unit, codes = args.split(" ", 3)
    amount = amount.to_i

    $config["auto_open"]["ends_at"] = Time.now.utc
    $config["auto_open"]["codes"] = []
    if unit =~ /^seconds{0,}$/i
      $config["auto_open"]["ends_at"] += amount
{'fraction_non_alphanumeric': 0.1742528735632184, 'fraction_numerical': 0.0052873563218390806, 'mean_word_length': 3.718546637744035, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '1289001', 'n_tokens_mistral': 3122, 'n_tokens_neox': 3083, 'n_words': 722}