-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.rb
executable file
·63 lines (52 loc) · 1.55 KB
/
main.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
#!/usr/bin/env ruby
require './initializer.rb'
require 'pry'
first_page = "http://class.ruten.com.tw/user/index00.php?s=club5271"
client = Crawler.new first_page
client.fetch
total_page = client.total_page
all_items = []
# Import first page
data = client.items
Item.batch_import(data)
all_items += data
# Import rest of the pages
(1..total_page.to_i-1).each do |page|
url = "#{first_page}&p=#{page}"
client = Crawler.new url
client.fetch
data = client.items
Item.batch_import(data)
all_items += data
end
grouped_items = all_items.group_by { |hash| hash[:status] }
output = ""
if grouped_items[Item::STATUS_REFILL]
output << "========== 有補貨到了喔! ==========\n"
grouped_items[Item::STATUS_REFILL].each do |item|
output << "#{item[:url]} #{item[:name]} #{item[:price]}\n"
end
end
if grouped_items[Item::STATUS_NEW]
output << "========== 有新貨上架了喔! ===========\n"
grouped_items[Item::STATUS_NEW].each do |item|
output << "#{item[:url]} #{item[:name]} #{item[:price]}\n"
end
end
if output.length > 0
email = YAML.load_file('config/email.yml')
message = <<MESSAGE_END
From: 好大一把斧 <#{email["gmail"]["account"]}>
To: #{email["recipients"].join(",")}
Subject: 團子屋貼心訂閱
#{output}
MESSAGE_END
smtp = Net::SMTP.new 'smtp.gmail.com', 587
smtp.enable_starttls
smtp.start('gmail.com', email["gmail"]["account"], email["gmail"]["password"], :login)
smtp.send_message message, email["gmail"]["account"], email["recipients"]
smtp.finish
puts "Email sent."
else
puts "Nothing new, do nothing."
end