secret
Created

  • Download Gist
config.ru
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13
require 'rubygems'
require 'sinatra'
require 'service'
root_dir = ::File.dirname(__FILE__)
set :environment, ENV['RACK_ENV'].to_sym
set :app_file, ::File.join(root_dir, 'service.rb')
set :root, root_dir
disable :run
run Sinatra::Application
service.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
#!/usr/bin/env ruby
# encoding: utf-8
 
require 'json'
require 'sinatra'
require 'open-uri'
require 'datamapper'
 
Reddit = 'http://www.reddit.com'
Database = "/var/www/applications/reverse_reddit/reddit.db"
 
Thread.abort_on_exception = true
DataMapper.setup :default, "sqlite3://#{Database}"
 
class Submission
include DataMapper::Resource
 
property :id, Serial
property :url, Text
property :name, Text
property :nsfw, Boolean
property :subreddit, String
property :permalink, Text
 
def self.create_from_json json
new.tap do |this|
this.url = json['url']
this.name = json['title']
this.nsfw = json['over_18']
this.subreddit = json['subreddit']
this.permalink = json['permalink']
end.save
end
 
def to_json
{
url: url,
nsfw: nsfw,
title: name,
status: 200,
subreddit: subreddit,
permalink: permalink
}.to_json
end
end
 
# 1. a person who has the charge or care of something, esp a building, or someone
class Warden
def self.work
Warden.new do |warden|
loop do
warden.patrol and sleep 30 # bacon
end
end
end
 
def initialize
yield self if block_given?
end
 
def patrol
open "#{Reddit}/r/all/new.json?sort=new" do |response|
json = JSON.parse response.read
json['data']['children'].each do |submission|
data = submission['data']
 
if not Submission.first permalink: data['permalink']
if Submission.create_from_json data
puts "==> new submission: #{data['title'].inspect} ..."
end
end
end
end
end
end
 
# Preload the database
DataMapper.auto_upgrade!
 
# Let the Warden work in the background
Thread.new &Warden.method(:work)
 
# /reverse?url=<url>
get '/reverse' do
if not params[:url]
{ status: 400, error: "missing url" }.to_json
else
if submission = Submission.first(url: params[:url])
submission.to_json
else
{ status: 404, error: "no reddit submission found" }.to_json
end
end
end
 
get '/all' do
[?[, Submission.all.map(&:to_json), ?]].join
end
 
error do
{ status: 500, error: "internal server error" }.to_json
end
 
not_found do
{ status: 404, error: "unknown method" }.to_json
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.