-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.rb
85 lines (61 loc) · 1.7 KB
/
index.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
require 'nokogiri'
require 'open-uri'
require 'FileUtils'
require 'json'
DB_FILE = File.expand_path('~') + '/.wallhaven.db'
FileUtils.touch DB_FILE
file_content = File.read(DB_FILE)
file_content = '[]' if file_content.empty?
db = JSON.parse(file_content)
# arg = "{query}"
arg = "bed"
#
# 根据关键字查询并抓取图片
#
define_method :fetch_wallpaper do |search|
p "fetch wallpaper: #{search}"
base_url = "http://alpha.wallhaven.cc/search?q=#{search}"
doc = Nokogiri::HTML(open(base_url))
thumbs = doc.css(".thumbs-container ul li .preview")
if thumbs.empty?
p 'Not Found'
else
id = thumbs.to_a.sample.attributes['href'].value.split('/').last
wallpaper_url = "http://alpha.wallhaven.cc/wallpaper/#{id}"
wallpaper_doc = Nokogiri::HTML(open(wallpaper_url))
real_url = "http:" + wallpaper_doc.css('#wallpaper')[0].attributes['src'].value
# p real_url
file_name = real_url.split('/').last
tmp_file = "/tmp/#{file_name}"
open(tmp_file, 'wb') do |file|
file << open(real_url).read
end
script = <<-eos
osascript -e 'tell application \"Finder\" to set desktop picture to POSIX file \"#{tmp_file}\"'
eos
# 把 id 保存到文件里面
db.push tmp_file
File.open(DB_FILE,"w") do |f|
f.write(db.to_json)
end
system script
# FileUtils.rm(tmp_file)
p "壁纸 ID: #{id.to_i}"
end
end
#
# 复制当前壁纸文件到桌面
#
define_method :copy_to_desktop do
p "Like it"
tmp_file = db.last
# p tmp_file
dist_file = File.expand_path('~') + '/Desktop/' + File.basename(tmp_file)
# p dist_file
FileUtils.cp tmp_file, dist_file
end
if arg == 'like'
copy_to_desktop
else
fetch_wallpaper arg
end