-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.rb
executable file
·253 lines (224 loc) · 6.75 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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#!/usr/bin/env ruby
# - * - coding: UTF-8 - * -
require 'fileutils'
require 'socket'
require 'uri'
require 'json'
require 'securerandom'
require_relative 'lib/const'
require_relative 'lib/color'
require_relative 'lib/desktop_file'
require_relative 'lib/function'
require_relative 'lib/http_server'
require_relative 'lib/icon_finder'
FileUtils.mkdir_p [ "#{TMPDIR}/cmdlog/", CONFIGDIR ]
Process.setproctitle 'Chromebrew Launcher'
def getUUID (arg)
# get desktop entry file path from package's filelist if a package name is given
if arg[0] != '/'
file = DesktopFile.find(arg)
else
file = arg
end
matched_file = `grep -l "\\"desktop_entry_file\\":\\"#{file}\\"" #{CONFIGDIR}/*.json 2> /dev/null`.lines(chomp: true)
return File.basename(matched_file[0], '.json') if matched_file.any?
end
def getPID
if File.exist?("#{TMPDIR}/daemon.pid")
return File.read("#{TMPDIR}/daemon.pid").to_i
else
return 0
end
end
def stopExistingDaemon
# kill existing server daemon
begin
daemon_pid = getPID
if daemon_pid > 0
Process.kill(15, daemon_pid)
FileUtils.rm_f "#{TMPDIR}/daemon.pid"
puts "crew-launcher server daemon with PID #{daemon_pid} stopped.".lightred
end
rescue Errno::ESRCH
end
end
def CreateProfile(arg)
# get desktop entry file path from package's filelist if a package name is given
#if arg[0] != '/'
file = DesktopFile.find(arg)
#else
# file = arg
#end
abort "crew-launcher: No such file or directory -- '#{file}'".lightred unless File.exist?(file)
# convert parsed hash into json format
desktop = DesktopFile.parse(file)
duplicate_profile_uuid = getUUID(file)
if Args['update'] and duplicate_profile_uuid
uuid = duplicate_profile_uuid
else
uuid = SecureRandom.uuid
File.delete("#{CONFIGDIR}/#{duplicate_profile_uuid}.json") if duplicate_profile_uuid
end
iconPath, iconSize, iconType = IconFinder.find(arg, desktop['Desktop Entry']['Icon'])
profile = {
desktop_entry_file: "#{file}",
background_color: "black",
theme_color: "black",
name: desktop['Desktop Entry']['Name'],
short_name: desktop['Desktop Entry']['GenericName'],
description: desktop['Desktop Entry']['Comment'],
start_url: "/#{uuid}/run",
scope: "/#{uuid}/",
display: "standalone",
exec: desktop['Desktop Entry']['Exec'].sub(/%[A-Za-z]/, ''),
icons: [
{
src: "/#{uuid}/appicon",
path: iconPath,
sizes: iconSize,
type: iconType
}
],
shortcuts:
desktop.select {|k, v| k =~ /^Desktop Action/ } .map do |k, v|
action = k.scan(/^Desktop Action (.*)$/)[0][0]
url = "/#{uuid}/run?shortcut=#{action}"
exec = v['Exec'].sub(/%[A-Za-z]/, '')
{ action: action, name: v['Name'], url: url, exec: exec}
end
}
File.write("#{CONFIGDIR}/#{uuid}.json", profile.to_json)
return uuid, profile
end
def InstallPWA (file)
uuid, manifest = CreateProfile(file)
# open a new tab in Chrome OS using dbus
system 'dbus-send',
'--system',
'--type=method_call',
'--print-reply',
'--dest=org.chromium.UrlHandlerService',
'/org/chromium/UrlHandlerService',
'org.chromium.UrlHandlerServiceInterface.OpenUrl',
"string:http://localhost:#{PORT}/#{uuid}/installer.html"
HTTPServer.start do |sock, uri, method|
filename = File.basename(uri.path)
case filename
when 'manifest.webmanifest'
sock.print HTTPHeader(200, 'application/manifest+json')
sock.write File.read("#{CONFIGDIR}/#{uuid}.json")
when 'appicon'
sock.print HTTPHeader(200, manifest[:icons][0][:type])
sock.write File.binread(manifest[:icons][0][:path])
when 'stop'
sock.print HTTPHeader(200)
return
else
# search requested file in `pwa/` directory
if File.file?("#{APPDIR}/pwa/#{filename}")
sock.print HTTPHeader(200, MimeType[ File.extname(filename) ])
sock.write File.read("#{APPDIR}/pwa/#{filename}")
else
sock.print HTTPHeader(404)
end
end
end
end
def StartWebDaemon
def LaunchApp(uuid, shortcut: false)
file = "#{CONFIGDIR}/#{uuid}.json"
unless File.exist?(file)
error "#{uuid}: Profile not found!"
retuen false
end
profile = JSON.parse(File.read(file), symbolize_names: true)
if shortcut
cmd = profile[:shortcuts].select {|h| h[:action] == shortcut} [0][:exec]
else
cmd = profile[:exec]
end
log = "#{TMPDIR}/cmdlog/#{uuid}.log"
spawn(cmd, {[:out, :err] => File.open(log, 'w')})
puts <<~EOT, nil
Profile: #{file}
CmdLine: #{cmd}
Output: #{log}
EOT
end
# turn into a background process
Process.daemon(true, true)
puts "crew-launcher server daemon with PID #{Process.pid} started.".lightgreen
# redirect output to log
log = File.open("#{TMPDIR}/daemon.log", 'w')
log.sync = true
STDOUT.reopen(log)
STDERR.reopen(log)
File.write("#{TMPDIR}/daemon.pid", Process.pid)
HTTPServer.start do |sock, uri, method|
_, uuid, action = uri.path.split('/', 3)
params = URI.decode_www_form(uri.query.to_s).to_h
unless File.exist?("#{CONFIGDIR}/#{uuid}.json")
sock.print HTTPHeader(404)
next
end
case action
when 'run'
LaunchApp(uuid, shortcut: params['shortcut'])
sock.print HTTPHeader(200, 'text/html')
sock.write File.read("#{APPDIR}/pwa/app.html")
when 'stop'
sock.print HTTPHeader(200)
sock.print 'crew-launcher server terminated: User interrupt.'
exit 0
end
end
end
case ARGV[0]
when 'list', 'show'
puts 'Installed launcher apps:'
Dir["#{CONFIGDIR}/*.json"].each do |json|
desktop_file = JSON.parse( File.read(json) )['desktop_entry_file']
app_name = File.basename(desktop_file, '.desktop')
uuid = File.basename(json, '.json')
puts "#{app_name}: #{uuid}"
end
when 'add', 'new'
stopExistingDaemon()
InstallPWA(ARGV[1])
StartWebDaemon()
when 'start', 'start-server'
stopExistingDaemon()
StartWebDaemon()
when 'stat', 'status'
daemon_pid = getPID
if daemon_pid > 0
puts "crew-launcher server daemon with PID #{daemon_pid} is running.".lightgreen
else
puts "crew-launcher server daemon is not running.".lightred
end
when 'stop', 'stop-server'
stopExistingDaemon()
when 'remove'
uuid = getUUID(ARGV[1])
if uuid
File.delete("#{CONFIGDIR}/#{uuid}.json")
puts "Profile #{CONFIGDIR}/#{uuid}.json removed!".lightgreen
else
error "Error: Cannot find a profile for #{ARGV[1]} :/"
end
when 'uuid'
ARGV.drop(1).each do |arg|
if (uuid = getUUID(arg))
puts uuid
else
error "#{arg}: No matching profile found."
end
end
when 'help', 'h', nil
puts HELP
else
print <<~EOT.lightred
crew-launcher: invalid option '#{ARGV[0]}'
Run `crew-launcher help` for more information.
EOT
end