forked from weapp/flats2telegram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
115 lines (91 loc) · 2.62 KB
/
app.rb
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
107
108
109
110
111
112
113
114
115
#!/usr/bin/env ruby
%w(logger json ostruct yaml/store bundler/setup).each(&method(:require))
Bundler.require(:default, ENV["APP_ENV"] || "development")
Dir[File.dirname(__FILE__) + "/lib/**/*.rb"].sort.each { |file| require file }
Dotenv.load
class Store
def self.store
@store ||= YAML::Store.new "store.yaml"
end
def self.visited
store.transaction do
store["visited"] ||= []
end
end
def self.visited= value
store.transaction do
store["visited"] = value
end
end
end
class App
def self.config
@_config = YAML.load_file('config.yml')
end
def self.sites_config
@_sites_config = config['sites']
end
def self.logger
@logger ||= Logger.new(STDOUT)
end
def self.debug(obj)
Pry::ColorPrinter.pp(obj)
obj
end
def self.env
ENV["APP_ENV"] || "development"
end
def self.pb(total=100)
@pb ||= ProgressBar.create format: "%a |%b>%i| %P% (%c/%C)",
total: total
end
def self.telegram
@telegram ||= Clients::Telegram.new
end
def self.run(site)
puts "fetching #{Time.now} #{site}!"
config = sites_config[site]
client = Clients::Web.new(url: config['url'],
rate_limit: config['rate_limit'],
response_class: Object.const_get("FlatsResponse::#{site.capitalize}"))
config['search_paths'].each do |url|
send_flats(client.fetch_flats(url))
end
rescue => e
puts "#{Time.now}: fail! #{e}"
end
def self.send_flats(flats)
p flats.map { |flat| flat[:id] }
send_message("#{Time.now}: Doesn't work: #{site.class.name}!", false) if flats.count == 0
flats.each do |flat|
next if Store.visited.include?(flat[:id])
Store.visited = (Store.visited << flat[:id]).uniq
flat = OpenStruct.new(flat)
App.debug send_message("*#{flat.title}*\n#{flat.details}\n\n#{flat.desc}\n\n#{flat.href}".gsub("\n\n\n\n", "\n\n"), flat[:md])
end
end
def self.send_message(text, md)
msg_attrs = {text: text, chat_id: config['chat_id']}
msg_attrs[:parse_mode] = 'Markdown' if md
telegram.send_message(msg_attrs)
end
def self.run!
loop do
run('idealista')
run('fotocasa')
# run(enalquiler)
sleep(30)
end
end
def self.list_hash
Hash.new { |hash, key| hash[key] = [] }
end
def self.html(html)
source = HtmlBeautifier.beautify html.to_s
formatter = Rouge::Formatters::Terminal256.new#(theme: 'monokai')
lexer = Rouge::Lexers::HTML.new
puts formatter.format(lexer.lex(source))
end
end
# App.run! if __FILE__ == $PROGRAM_NAME
App.run!(*ARGV) if __FILE__ == $PROGRAM_NAME