Skip to content

Instantly share code, notes, and snippets.

@alex-cellcity
Created July 5, 2013 10:12
Show Gist options
  • Save alex-cellcity/5933548 to your computer and use it in GitHub Desktop.
Save alex-cellcity/5933548 to your computer and use it in GitHub Desktop.
PocketBook.rb
require "sinatra"
require "./lib/pocket.rb"
require "open-uri"
require "iconv"
require "json"
enable :sessions
CALLBACK_URL = "http://localhost:4567/oauth/callback"
Pocket.configure do |config|
config.consumer_key = '16106-8a9984eefb9d1522359292ae'
end
get '/reset' do
puts "GET /reset"
session.clear
end
get "/" do
puts "GET /"
puts "session: #{session}"
if session[:access_token]
'
<a href="/add?url=http://geknowm.com">Add Geknowm</a>
<a href="/retrieve">Retrieve items</a>
'
else
'<a href="/oauth/connect">Connect with Pocket</a>'
end
end
get "/oauth/connect" do
puts "OAUTH CONNECT"
session[:code] = Pocket.get_code(:redirect_uri => CALLBACK_URL)
new_url = Pocket.authorize_url(:code => session[:code], :redirect_uri => CALLBACK_URL)
puts "new_url: #{new_url}"
puts "session: #{session}"
redirect new_url
end
get "/oauth/callback" do
puts "OAUTH CALLBACK"
puts "request.url: #{request.url}"
puts "request.body: #{request.body.read}"
access_token = Pocket.get_access_token(session[:code], :redirect_uri => CALLBACK_URL)
session[:access_token] = access_token
puts "session: #{session}"
redirect "/"
end
get '/add' do
client = Pocket.client(:access_token => session[:access_token])
info = client.add :url => 'http://geknowm.com'
"<pre>#{info}</pre>"
end
get "/retrieve" do
client = Pocket.client(:access_token => session[:access_token])
info = client.retrieve :detailType => :complete, :tag=>'最终进化', :sort=>:newest
html = "<ul>"
info['list'].each do |key, item|
html << "<li><a href='http://getpocket.com/a/read/#{item['item_id']}' title='#{item['resolved_title']}'>#{item['resolved_title']}</a></li>"
end
html << "</ul>"
html
end
get "/biquge.com/:book_id" do
url = "http://www.biquge.com/#{params[:book_id]}/"
res = open(url) { |f| f.read }
html = Iconv.conv("utf-8", "GBK", res)
list = []
html.scan(%r{<dd><a href="(/.+/(\d+).html)">(.+)</a>}).each {|m| list.push({:link => m[0], :id => m[1].to_i, :title => m[2] }) }
# list.sort {|a,b| a[:link].split('/')[2] <=> b[:link].split('/')[2] }
list.sort_by!{|a| a[:id]}
list.uniq!{|a| a[:id]}
# list.to_json
index = list.find_index {|s| s[:id] == 448260}
news = list[index, 100]
client = Pocket.client(:access_token => session[:access_token])
msg = []
news.each do |item|
info = client.add :url => "http://www.biquge.com/#{item[:link]}", :tags => '最终进化', :title => item[:title]
msg.push(info)
end
msg.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment