<file_sep>$:.unshift File.expand_path('../lib', __FILE__)

require 'eventmachine'
require 'json'
require 'ayaneru'

run Ayaneru::Server

EM::defer do
  yesterday = Time.now.day - 1
  loop do
    today = Time.now.day
    if today != yesterday
      registered_tags = Ayaneru.redis.lrange 'tags', 0, -1
      registered_tags.each do |tag|
        r = Ayaneru.niconico.search(tag, 1).to_s.split("\n")
        results = JSON.parse(r[2])
        if results['values']
          results['values'].each do |value|
            begin
              ret = Ayaneru.niconico.reserve(value["cmsid"])
            rescue => exception
              puts exception.message
              begin
                Ayaneru.twitter.create_direct_message(Ayaneru.twitter.user.screen_name, "これ以上タイムシフト予約できません．『#{value['title']}』（http://live.nicovideo.jp/watch/#{value['cmsid']}）")
              rescue => exception
                puts exception.message
              end
            end
            begin
              Ayaneru.twitter.create_direct_message(Ayaneru.twitter.user.screen_name, "『#{value['title']}』（http://live.nicovideo.jp/watch/#{value['cmsid']}）をタイムシフト予約しました．") if ret
            rescue => exception
              puts exception.message
            end
          end
        end
      end
      yesterday = today
    end
    sleep 60*60*1
  end
end
<file_sep>require 'json'

module Ayaneru
  class Niconico
    def search(tag, until_days)
      logout
      post_data = {}
      data_filters = Array.new
      data_filters[0] = {
        "field" => "ss_adult",
        "type" => "equal",
        "value" => false
      }
      data_filters[1] = {
        "field" => "live_status",
        "type" => "equal",
        "value" => "reserved"
      }
      data_filters[2] = {
        "field" => "provider_type",
        "type" => "equal",
        "value" => "official"
      }
      data_filters[3] = {
        "field" => "start_time",
        "from" => Time.now.strftime("%Y-%m-%d %H:%M:%S"),
        "include_lower" => true,
        "include_upper" => true,
        "to" => Time.at(Time.now.to_i + until_days * 24 * 60 * 60).strftime("%Y-%m-%d %H:%M:%S"),
        "type" => "range"
      }
      data_filters[4] = {
        "field" => "timeshift_enabled",
        "type" => "equal",
        "value" => true
      }
      post_data["filters"] = data_filters
      post_data["from"] = 0
      post_data["issuer"] = "http://github.com/tsuwatch/autots"
      post_data["join"] = [
        "cmsid",
        "title",
        "description",
        "community_id",
        "open_time",
        "start_time",
        "live_end_time",
        "comment_counter",
        "score_timeshift_reserved",
        "provider_type",
        "channel_id",
        "live_status",
        "tags",
        "member_only"
      ]
      post_data["order"] = "desc"
      post_data["query"] = tag
      post_data["reason"] = "default"
      post_data["search"] = ["tags"]
      post_data["service"] = ["live"]
      post_data["size"] = 100
      post_data["sort_by"] = "_live_recent"
      post_data["timeout"] = 10000

      response = Ayaneru.niconico.agent.post(URL[:search], JSON.pretty_generate(post_data))
      response.body
    end
  end
end
<file_sep>FROM ruby:2.2.3

WORKDIR /app
ADD Gemfile /app/Gemfile
ADD Gemfile.lock /app/Gemfile.lock
RUN bundle install -j4
ADD . /app
<file_sep># A sample Gemfile
source "https://rubygems.org"
gem "sinatra"
gem "haml"
gem "mechanize"
gem "redis"
gem 'twitter'
gem 'eventmachine'
gem 'thin'
gem 'dotenv'
<file_sep>require 'sinatra/base'
require 'haml'

module Ayaneru
  class Server < Sinatra::Base

    use Rack::Auth::Basic, "Restricted Area" do |username, password|
      username == ENV['BASIC_USERNAME'] and password == ENV['BASIC_<PASSWORD>']
    end

    set :bind, '0.0.0.0'

    get '/' do
      @registered_tags = Ayaneru.redis.lrange 'tags', 0, -1
      @results = {}
      @registered_tags.each do |tag|
        chunks = Ayaneru.niconico.search(tag, 7).to_s.split("\n")
        chunks.each do |chunk|
          row = JSON.parse(chunk)
          next if !(row.has_value?('hits') and row.key?('values'))
          @results[tag] = row
          break
        end
      end

      haml :index
    end

    post '/' do
      Ayaneru.redis.rpush "tags", params[:tag]
      redirect '/'
    end

    post '/delete' do
      Ayaneru.redis.lrem "tags", 1, params[:tag]
      redirect '/'
    end
  end
end
