/
main.go
342 lines (326 loc) · 14.3 KB
/
main.go
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/*
Copyright (c) 2013, Aulus Egnatius Varialus <varialus@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// http://code.google.com/p/chromedriver/wiki/CapabilitiesAndSwitches
// http://code.google.com/p/chromedriver/wiki/GettingStarted
// http://code.google.com/p/chromedriver/wiki/TroubleshootingAndSupport
// http://code.google.com/p/selenium/source/browse/java/server/src/org/openqa/grid/common/defaults/DefaultNode.json
// http://code.google.com/p/selenium/source/browse/py/
// http://code.google.com/p/selenium/source/browse/py/selenium/webdriver/__init__.py
// http://code.google.com/p/selenium/source/browse/py/selenium/webdriver/chrome/__init__.py
// http://code.google.com/p/selenium/source/browse/py/selenium/webdriver/chrome/options.py
// http://code.google.com/p/selenium/source/browse/py/selenium/webdriver/chrome/service.py
// http://code.google.com/p/selenium/source/browse/py/selenium/webdriver/chrome/webdriver.py
// http://code.google.com/p/selenium/source/browse/py/selenium/webdriver/common/desired_capabilities.py
// http://code.google.com/p/selenium/source/browse/py/selenium/webdriver/common/utils.py
// http://code.google.com/p/selenium/source/browse/py/selenium/webdriver/remote/command.py
// http://code.google.com/p/selenium/source/browse/py/selenium/webdriver/remote/remote_connection.py
// http://code.google.com/p/selenium/source/browse/py/selenium/webdriver/remote/webdriver.py
// http://code.google.com/p/selenium/source/browse/py/README
// http://code.google.com/p/selenium/w/list
// http://code.google.com/p/selenium/wiki/ArchitecturalOverview
// http://code.google.com/p/selenium/wiki/ChromeDriver
// http://code.google.com/p/selenium/wiki/ChromeDriver#Overriding_the_Chrome_binary_location
// http://code.google.com/p/selenium/wiki/DefiningNewWireProtocolCommands
// http://code.google.com/p/selenium/wiki/DesiredCapabilities
// http://code.google.com/p/selenium/wiki/JsonWireProtocol
// http://code.google.com/p/selenium/wiki/RemoteWebDriver
// http://selenium.googlecode.com/git/docs/api/py/webdriver_remote/selenium.webdriver.remote.webdriver.html
// ChromeDriver Default Address 127.0.0.1:9515
// TODO: Recommendation: <mortdeus> varialus, fyi if you call your file main_linux_amd64.go, you can take out the runtime checks.
package main
import (
"archive/zip"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"os/user"
"path"
"runtime"
"strconv"
"strings"
"time"
)
// http://code.google.com/p/selenium/wiki/JsonWireProtocol
//
// /session
//
// POST /session
//
// Create a new session.
// The server should attempt to create a session that most closely matches the desired and required capabilities.
// Required capabilities have higher priority than desired capabilities and must be set for the session to be created.
//
// JSON Parameters:
// desiredCapabilities - {object} An object describing the session's desired capabilities.
// requiredCapabilities - {object} An object describing the session's required capabilities (Optional).
//
// Returns:
// {object} An object describing the session's capabilities.
//
// Potential Errors:
// SessionNotCreatedException - If a required capability could not be set.
func Session(url string, capabilities interface{}, v interface{}) error {
json_bytes, err := json.Marshal(capabilities)
if err != nil {
return fmt.Errorf("Error: problem while calling json.Marshal(%v); err == %s", capabilities, err.Error())
}
fmt.Println("json_bytes ==", json_bytes)
buffered_data := bytes.NewBuffer(json_bytes)
response, err := http.Post(url+"/session", "application/json", buffered_data)
if err != nil {
return fmt.Errorf("Error: problem while calling http.Post(%s, \"application/json\", json.Marshal(%v)); err == %s", url+"/session", capabilities, err.Error())
}
fmt.Println("response ==", response)
bytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return fmt.Errorf("Error: problem getting response while starting new session; %s", err.Error())
}
defer response.Body.Close()
fmt.Println("string(bytes) ==", string(bytes))
return json.Unmarshal(bytes, v)
}
func main() {
var browser_name string
if runtime.GOOS != "linux" {
fmt.Println(fmt.Errorf("Error: selenium not yet implemented on %s", runtime.GOOS))
return
}
if runtime.GOARCH != "amd64" {
fmt.Println(fmt.Errorf("Error: selenium not yet implemented on %s", runtime.GOARCH))
return
}
flag.StringVar(&browser_name, "browser", "chromium", "-browser=chromium|chrome|firefox|iceweasel|ie|opera")
flag.Parse()
if browser_name != "chromium" {
fmt.Println(fmt.Errorf("Error: selenium not yet implemented on %s", browser_name))
return
}
fmt.Println("browser ==", browser_name)
port, err := free_port()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("port ==", port)
go func() {
if err := startChromeDriver(true, port); err != nil {
go func() {
startChromeDriver(false, port)
}()
}
}()
defer stopChromeDriver(port)
waitForChromeDriver(port)
chrome_options := map[string]interface{}{
// function returns slice of extension *.crx files read as Python base64 data
// it gets called and formatted before it is sent to chromedriver
//"extensions": func()
"binary": "/usr/bin/chromium",
}
desired_chrome_capabilities := map[string]interface{}{
"browserName": "chrome",
"version": "",
"platform": "ANY",
"javascriptEnabled": true,
"chromeOptions": chrome_options,
}
fmt.Println("desired_chrome_capabilities ==", desired_chrome_capabilities)
//command_executor_url := "http://127.0.0.1:4444/wd/hub"
//command_executor_url := fmt.Sprintf("http://127.0.0.1:%d/wd/hub", port)
command_executor_url := fmt.Sprintf("http://127.0.0.1:%d", port)
fmt.Println("command_executor_url", command_executor_url)
commands := map[string][2]string{
"newSession": [2]string{"POST", "/session"},
}
fmt.Println("commands ==", commands)
driver_command_to_execute := "newSession"
fmt.Println("driver_command_to_execute ==", driver_command_to_execute)
params_to_execute := map[string]map[string]interface{}{
"desiredCapabilities": desired_chrome_capabilities,
}
fmt.Println("params_to_execute ==", params_to_execute)
var result interface{}
if err := Session(command_executor_url, params_to_execute, &result); err != nil {
fmt.Println(fmt.Errorf("Error: problem starting session; error == %s", err.Error()))
} else {
fmt.Println("result ==", result)
}
time.Sleep(1 * time.Second)
}
func linuxChrome64DriverURL(latest bool) (chrome_driver_url string, driver_version string, err error) {
chrome_drivers_url := "https://code.google.com/p/chromedriver/downloads/list"
resp, err := http.Get(chrome_drivers_url)
if err != nil {
err = fmt.Errorf("Error: unable to get latest driver from %s", chrome_drivers_url)
return chrome_driver_url, driver_version, err
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
err = fmt.Errorf("Error: unable to read bytes from body while getting driver from %s", chrome_drivers_url)
return chrome_driver_url, driver_version, err
}
chrome_driver_url = string(bytes)
if latest {
chrome_driver_url = chrome_driver_url[strings.Index(chrome_driver_url, "'//chromedriver.googlecode.com/files/chromedriver_linux64_"):strings.LastIndex(chrome_driver_url, "supports Chrome")]
driver_version = chrome_driver_url[strings.LastIndex(chrome_driver_url, "(")+1 : strings.LastIndex(chrome_driver_url, ")")]
chrome_driver_url = chrome_driver_url[strings.Index(chrome_driver_url, "//"):strings.Index(chrome_driver_url, "',")]
chrome_driver_url = "https:" + chrome_driver_url
} else {
chrome_driver_url = chrome_driver_url[strings.LastIndex(chrome_driver_url, "'//chromedriver.googlecode.com/files/chromedriver_linux64_"):strings.LastIndex(chrome_driver_url, "deprecated")]
driver_version = "v" + chrome_driver_url[strings.LastIndex(chrome_driver_url, "chromedriver_linux64_")+21:strings.LastIndex(chrome_driver_url, ".zip")]
chrome_driver_url = chrome_driver_url[strings.Index(chrome_driver_url, "//"):strings.Index(chrome_driver_url, "',")]
chrome_driver_url = "https:" + chrome_driver_url
}
return chrome_driver_url, driver_version, err
}
func userHomeDir() string {
usr, err := user.Current()
if err != nil {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
return usr.HomeDir
}
func free_port() (int, error) {
tcp_address := net.TCPAddr{net.ParseIP("127.0.0.1"), 0, ""}
tcp_listener, err := net.ListenTCP("tcp4", &tcp_address)
if err != nil {
return 0, errors.New("Error: unable to listen on ephemeral port")
}
defer tcp_listener.Close()
port, err := strconv.Atoi(tcp_listener.Addr().String()[strings.LastIndex(tcp_listener.Addr().String(), ":")+1:])
if err != nil {
return 0, errors.New("Error: unable to retrieve ephemeral port")
}
return port, nil
}
func getChromeDriver(latest bool) (driver_path string, err error) {
home_dir := userHomeDir()
chrome_driver_url, driver_version, err := linuxChrome64DriverURL(latest)
if err != nil {
driver_dir := path.Join(home_dir, ".selenium", "drivers", "chrome", driver_version)
driver_path = path.Join(driver_dir, "chromedriver")
fmt.Println("driver_path5 ==", driver_path)
return driver_path, err
}
driver_dir := path.Join(home_dir, ".selenium", "drivers", "chrome", driver_version)
driver_path = path.Join(driver_dir, "chromedriver")
fmt.Println("driver_path6 ==", driver_path)
fmt.Println("chrome_driver_url ==", chrome_driver_url)
fmt.Println("driver_version ==", driver_version)
fmt.Println("driver_dir ==", driver_dir)
if _, err := os.Stat(driver_dir); err != nil && os.IsNotExist(err) {
file_info, err := os.Stat(home_dir)
if err != nil && os.IsNotExist(err) {
fmt.Println(fmt.Errorf("Error: %s does not exist", home_dir))
return driver_path, fmt.Errorf("Error: %s does not exist; err == %s", home_dir, err.Error())
}
if err := os.MkdirAll(driver_dir, file_info.Mode()); err != nil {
return driver_path, fmt.Errorf("Error: unable to create %s; err == %s", driver_dir, err.Error())
}
}
if _, err := os.Stat(driver_path); err != nil && os.IsNotExist(err) {
zip_name := chrome_driver_url[strings.LastIndex(chrome_driver_url, "/")+1:]
zip_file, err := ioutil.TempFile("", zip_name)
if err != nil {
return driver_path, fmt.Errorf("Error: unable to create temporary file %s; err == %s", zip_name, err.Error())
}
defer zip_file.Close()
zip_path := zip_file.Name()
defer os.Remove(zip_path)
resp, err := http.Get(chrome_driver_url)
if err != nil {
return driver_path, fmt.Errorf("Error: unable to get response from %s; err == %s", chrome_driver_url, err.Error())
}
defer resp.Body.Close()
if _, err := io.Copy(zip_file, resp.Body); err != nil {
return driver_path, fmt.Errorf("Error: unable to download %s; err == %s", chrome_driver_url, err.Error())
}
zip_reader, err := zip.OpenReader(zip_path)
if err != nil {
return driver_path, fmt.Errorf("Error: unable to open file %s; err == %s", zip_path, err.Error())
}
defer zip_reader.Close()
for _, file := range zip_reader.File {
file_contents, err := file.Open()
if err != nil {
return driver_path, fmt.Errorf("Error: unable to open file %s within %s; err == %s", file.Name, zip_path, err.Error())
}
file_path := path.Join(driver_dir, file.Name)
chrome_driver, err := os.Create(file_path)
if err != nil {
return driver_path, fmt.Errorf("Error: unable to create file %s; err == %s", file_path, err.Error())
}
if _, err := io.Copy(chrome_driver, file_contents); err != nil {
return driver_path, fmt.Errorf("Error: unable to unzip %s into %s; err == %s", zip_path, file_path, err.Error())
}
chrome_driver.Close()
file_info, err := os.Stat(driver_path)
if err != nil {
return driver_path, fmt.Errorf("Error: unable to stat %s; err == %s", driver_path, err.Error())
}
file_mode := file_info.Mode()
fmt.Println("file_mode ==", file_mode)
file_mode = file_mode | 0100
fmt.Println("file_mode ==", file_mode)
if err := os.Chmod(driver_path, file_mode); err != nil {
return driver_path, fmt.Errorf("Error: unable to chmod %s; err == %s", driver_path, err.Error())
}
fmt.Println("Successfully downloaded and unzipped chromedriver")
return driver_path, err
}
}
return driver_path, err
}
func startChromeDriver(latest bool, port int) error {
// TODO: While making this work with multiple browsers, restructure to use existing driver while downloading new driver in goroutine for next use
driver_path, err := getChromeDriver(latest)
if err != nil {
fmt.Println("driver_path1 ==", driver_path)
return err
}
fmt.Println("driver_path2 ==", driver_path)
fmt.Println("port ==", port)
driver_command := exec.Command(driver_path, "--port="+strconv.Itoa(port))
var stdout_buffer bytes.Buffer
driver_command.Stdout = &stdout_buffer
var stderr_buffer bytes.Buffer
driver_command.Stderr = &stderr_buffer
if err := driver_command.Run(); err != nil {
fmt.Printf("latest driver_command.Stdout == %q\n", stdout_buffer.String())
fmt.Printf("latest driver_command.Stderr == %q\n", stderr_buffer.String())
return fmt.Errorf("Error: unable to run command, err == %s", err.Error())
}
fmt.Printf("latest driver_command.Stdout == %q\n", stdout_buffer.String())
fmt.Printf("latest driver_command.Stderr == %q\n", stderr_buffer.String())
return nil
}
func stopChromeDriver(port int) {
shutdown_url := "http://127.0.0.1:" + strconv.Itoa(port) + "/shutdown"
http.Get(shutdown_url)
}
func waitForChromeDriver(port int) {
counter := 0
for _, err := http.Get("http://127.0.0.1:" + strconv.Itoa(port)); err != nil && counter < 5000; _, err = http.Get("http://127.0.0.1:" + strconv.Itoa(port)) {
counter++
time.Sleep(time.Millisecond)
}
}