-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
680 lines (589 loc) · 16.4 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
package main
import (
"encoding/json"
"flag"
"fmt"
"strings"
"time"
resty "github.com/go-resty/resty/v2"
"github.com/gopher1980/dynql"
"github.com/gopher1980/gormcrud"
"github.com/sclevine/agouti"
"io/ioutil"
"os"
"github.com/robertkrimen/otto"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
const (
frequencyDefault = 10
retryDefault = 1000
)
var (
pages map[string]*agouti.Page
agoutiDriver *agouti.WebDriver
debug bool
db *gorm.DB
)
func file2str(ilename string) string {
file, err := os.Open(ilename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
b, err := ioutil.ReadAll(file)
return string(b)
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
// Storage is struct for save data for test
type Storage struct {
ID uint `gorm:"primary_key" json:"id" `
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at"`
Name string `json:"name" gorm:"unique_index:storage_name"`
Strategy string `json:"strategy"`
Selector string `json:"selector"`
Value string `json:"value"`
//Frequency int64 `json:"frequency"`
//Retry int64 `json:"retry"`
}
// Actions is struct for save data for test
type Action struct {
ID uint `gorm:"primary_key" json:"id" `
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at"`
Name string `json:"name" gorm:"unique_index:action_name"`
Code string `json:"code"`
}
// Catalog is
type Catalog struct {
ID uint `gorm:"primary_key" json:"id" `
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at"`
Name string `json:"name"`
Code string `json:"code"`
}
// Param recive in method
type Param struct {
Session string `json:"session"`
Value string `json:"value"`
Option string `json:"option"`
Browser string `json:"browser"`
URL string `json:"url"`
Condition string `json:"condition"`
Selector string `json:"selector"`
Strategy string `json:"strategy"`
Duration int64 `json:"duration"`
Frequency int64 `json:"frequency"`
Retry int64 `json:"retry"`
CheckPage bool `json:"check_page"`
}
// ReturnStep is generic return
type ReturnStep struct {
Message string `json:"message"`
Action string `json:"action"`
}
func start(name string, ptr interface{}, r *http.Request, payload interface{}, parent interface{}) interface{} {
var err error
p := ptr.(*Param)
skey := p.Session
if skey == "" {
skey = r.URL.Query().Get("s")
}
if skey == "" {
return ReturnStep{Message: "Session can not empty", Action: name}
}
if pages[skey] != nil {
return ReturnStep{Message: "page is open", Action: name}
}
pages[skey], err = agoutiDriver.NewPage()
if p.Duration == 0 {
p.Duration = 40
}
if p.Duration != -1 {
go func() {
time.Sleep(time.Duration(p.Duration) * time.Second)
fmt.Println("page", skey, " Destroy ", pages[skey].String())
_ = pages[skey].Destroy()
pages[skey] = nil
}()
}
if err != nil {
return err
}
return ReturnStep{Message: "ok", Action: name}
}
func destroy(name string, ptr interface{}, r *http.Request, payload interface{}, parent interface{}) interface{} {
p := ptr.(*Param)
skey := p.Session
if skey == "" {
skey = r.URL.Query().Get("s")
}
page := pages[skey]
return page.Destroy()
}
func find(page *agouti.Page, selector string, frequency int, retry int) *agouti.Selection {
i := 0
elem := page.Find(selector)
count, err := elem.Count()
for count == 0 && err != nil && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.Find(selector)
count, err = elem.Count()
i++
}
return elem
}
func findByXPath(page *agouti.Page, selector string, frequency int, retry int) *agouti.Selection {
i := 0
elem := page.FindByXPath(selector)
count, err := elem.Count()
for count == 0 && err != nil && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByXPath(selector)
count, err = elem.Count()
i++
}
return elem
}
func findByClass(page *agouti.Page, selector string, frequency int, retry int) *agouti.Selection {
i := 0
elem := page.FindByClass(selector)
count, err := elem.Count()
for count == 0 && err != nil && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByClass(selector)
count, err = elem.Count()
i++
}
return elem
}
func findByID(page *agouti.Page, selector string, frequency int, retry int) *agouti.Selection {
i := 0
elem := page.FindByID(selector)
count, err := elem.Count()
for count == 0 && err != nil && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByID(selector)
count, err = elem.Count()
i++
}
return elem
}
func findByLink(page *agouti.Page, selector string, frequency int, retry int) *agouti.Selection {
i := 0
elem := page.FindByLink(selector)
count, err := elem.Count()
for count == 0 && err != nil && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByLink(selector)
count, err = elem.Count()
i++
}
return elem
}
func findByName(page *agouti.Page, selector string, frequency int, retry int) *agouti.Selection {
i := 0
elem := page.FindByName(selector)
count, err := elem.Count()
for count == 0 && err != nil && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByName(selector)
count, err = elem.Count()
i++
}
return elem
}
func findByButton(page *agouti.Page, selector string, frequency int, retry int) *agouti.Selection {
i := 0
elem := page.FindByButton(selector)
count, err := elem.Count()
for count == 0 && err != nil && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByButton(selector)
count, err = elem.Count()
i++
}
return elem
}
func findByLabel(page *agouti.Page, selector string, frequency int, retry int) *agouti.Selection {
i := 0
elem := page.FindByLabel(selector)
count, err := elem.Count()
for count == 0 && err != nil && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByLabel(selector)
count, err = elem.Count()
i++
}
return elem
}
func findByStrategy(page *agouti.Page, strategy string, selector string, frequency int, retry int) *agouti.Selection {
if frequency == 0 {
frequency = frequencyDefault
}
if retry == 0 {
retry = retryDefault
}
if strategy == "xpath" {
return findByXPath(page, selector, frequency, retry)
}
if strategy == "name" {
return findByName(page, selector, frequency, retry)
}
if strategy == "class" {
return findByClass(page, selector, frequency, retry)
}
if strategy == "id" {
return findByID(page, selector, frequency, retry)
}
if strategy == "link" {
return findByLink(page, selector, frequency, retry)
}
if strategy == "button" {
return findByButton(page, selector, frequency, retry)
}
if strategy == "label" {
return findByLabel(page, selector, frequency, retry)
}
if strategy == "storage" {
storage, _, exists := findInStorage(selector)
if !exists {
return nil
}
return findByStrategy(page, storage.Strategy, storage.Selector, frequency, retry)
}
return find(page, selector, frequency, retry)
}
func waitHide(page *agouti.Page, selector string, frequency int, retry int) bool {
i := 0
elem := page.Find(selector)
count, _ := elem.Count()
for count != 0 && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.Find(selector)
count, _ = elem.Count()
i++
}
if i >= retry {
return false
}
return true
}
func waitHideByLink(page *agouti.Page, selector string, frequency int, retry int) bool {
i := 0
elem := page.FindByLink(selector)
count, _ := elem.Count()
for count != 0 && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByLink(selector)
count, _ = elem.Count()
i++
}
if i >= retry {
return false
}
return true
}
func waitHideByLabel(page *agouti.Page, selector string, frequency int, retry int) bool {
i := 0
elem := page.FindByLabel(selector)
count, _ := elem.Count()
for count != 0 && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByLabel(selector)
count, _ = elem.Count()
i++
}
if i >= retry {
return false
}
return true
}
func waitHideByID(page *agouti.Page, selector string, frequency int, retry int) bool {
i := 0
elem := page.FindByID(selector)
count, _ := elem.Count()
for count != 0 && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByID(selector)
count, _ = elem.Count()
i++
}
if i >= retry {
return false
}
return true
}
func waitHideByXPath(page *agouti.Page, selector string, frequency int, retry int) bool {
i := 0
elem := page.FindByXPath(selector)
count, _ := elem.Count()
for count != 0 && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByXPath(selector)
count, _ = elem.Count()
i++
}
if i >= retry {
return false
}
return true
}
func waitHideByClass(page *agouti.Page, selector string, frequency int, retry int) bool {
i := 0
elem := page.FindByClass(selector)
count, _ := elem.Count()
for count != 0 && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByXPath(selector)
count, _ = elem.Count()
i++
}
if i >= retry {
return false
}
return true
}
func waitHideByName(page *agouti.Page, selector string, frequency int, retry int) bool {
i := 0
elem := page.FindByName(selector)
count, _ := elem.Count()
for count != 0 && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByName(selector)
count, _ = elem.Count()
i++
}
if i >= retry {
return false
}
return true
}
func waitHideByButton(page *agouti.Page, selector string, frequency int, retry int) bool {
i := 0
elem := page.FindByButton(selector)
count, _ := elem.Count()
for count != 0 && i < retry && page != nil {
time.Sleep(time.Duration(frequency) * time.Millisecond)
elem = page.FindByButton(selector)
count, _ = elem.Count()
i++
}
if i >= retry {
return false
}
return true
}
func waitHideByStrategy(page *agouti.Page, strategy string, selector string, frequency int, retry int) bool {
if frequency == 0 {
frequency = frequencyDefault
}
if retry == 0 {
retry = retryDefault
}
if strategy == "xpath" {
return waitHideByXPath(page, selector, frequency, retry)
}
if strategy == "name" {
return waitHideByName(page, selector, frequency, retry)
}
if strategy == "class" {
return waitHideByClass(page, selector, frequency, retry)
}
if strategy == "id" {
return waitHideByID(page, selector, frequency, retry)
}
if strategy == "link" {
return waitHideByLink(page, selector, frequency, retry)
}
if strategy == "button" {
return waitHideByButton(page, selector, frequency, retry)
}
if strategy == "label" {
return waitHideByLabel(page, selector, frequency, retry)
}
if strategy == "storage" {
storage, _, exists := findInStorage(selector)
if !exists {
return false
}
return waitHideByStrategy(page, storage.Strategy, storage.Selector, frequency, retry)
}
return waitHide(page, selector, frequency, retry)
}
func findInStorage(name string) (Storage, int64, bool) {
var count int64
storage := Storage{}
db.Where("name = ?", name).Find(&storage).Count(&count)
exists := true
if count == 0 {
exists = false
}
return storage, count, exists
}
func waitShowByStrategy(page *agouti.Page, strategy string, selector string, frequency int, retry int) bool {
elem := findByStrategy(page, strategy, selector, frequency, retry)
if elem == nil {
return false
}
count, err := elem.Count()
if count == 0 || err != nil {
return false
}
return true
}
func newClientResty() *resty.Client {
return resty.New()
}
func unmarshal(str string) map[string]interface{} {
ret := make(map[string]interface{})
json.Unmarshal([]byte(str), &ret)
return ret
}
// brew install chromedriver
func jsRun(name string, ptr interface{}, r *http.Request, payload interface{}, parent interface{}) interface{} {
var err error
p := ptr.(*Param)
skey := p.Session
if skey == "" {
skey = r.URL.Query().Get("s")
}
page := pages[skey]
if page == nil && p.CheckPage {
return ReturnStep{Message: "page nil", Action: name}
}
vm := otto.New()
_ = vm.Set("payload", payload)
if payload != nil {
var copyPayload interface{}
bytes, _ := json.Marshal(payload)
_ = json.Unmarshal(bytes, ©Payload)
_ = vm.Set("payload", copyPayload)
}
_ = vm.Set("parent", parent)
p.Condition = strings.ReplaceAll(p.Condition, "{", "")
p.Condition = strings.ReplaceAll(p.Condition, "}", "")
if p.Condition != "" {
v, err := vm.Run(p.Condition)
if err != nil {
return err
}
if v.IsBoolean() {
condition, _ := v.ToBoolean()
if !condition {
bytes, _ := json.Marshal(payload)
mapPayload := make(map[string]interface{})
_ = json.Unmarshal(bytes, &mapPayload)
mapPayload["action"] = "!" + name
mapPayload["message"] = "return false condition"
return mapPayload
}
} else {
return ReturnStep{Message: "Condition return not boolean", Action: name}
}
}
_ = vm.Set("session", skey)
_ = vm.Set("req", r)
_ = vm.Set("param", ptr.(*Param))
_ = vm.Set("page", page)
_ = vm.Set("action_name", name)
_ = vm.Set("sleep", time.Sleep)
_ = vm.Set("Second", time.Second)
_ = vm.Set("Millisecond", time.Millisecond)
_ = vm.Set("Microsecond", time.Microsecond)
_ = vm.Set("Nanosecond", time.Nanosecond)
_ = vm.Set("WaitShowByStrategy", waitShowByStrategy)
_ = vm.Set("WaitHideByStrategy", waitHideByStrategy)
_ = vm.Set("Find", findByStrategy)
_ = vm.Set("FindInStorage", findInStorage)
_ = vm.Set("NewClientResty", newClientResty)
_ = vm.Set("Unmarshal", unmarshal)
code := "function action { return {message:'action no exists'}; };\n"
method := "action"
if strings.Contains(name, ".") {
v := strings.Split(name, ".")
name = v[0]
method = v[1]
}
action := Action{}
ret := db.Where("name = ?", name).Find(&action)
if ret.RowsAffected == 0 {
return ReturnStep{Message: "action not found", Action: name}
}
code = action.Code
result, err := vm.Run(code + "\n " + method + "()")
if err != nil {
return err
}
export, err := result.Export()
if err != nil {
return err
}
return export
}
// brew install chromedriver
func main() {
var driver string
var addr string
flag.StringVar(&driver, "driver", "chrome", "[drive, phantomjs, selenium, firefox ]")
flag.StringVar(&addr, "addr", ":9090", "this is addr of this ListenAndServe")
flag.BoolVar(&debug, "debug", false, "sql debug")
flag.Parse()
if driver == "chrome" {
agoutiDriver = agouti.ChromeDriver()
}
if driver == "phantomjs" {
agoutiDriver = agouti.PhantomJS()
}
if driver == "selenium" {
agoutiDriver = agouti.Selenium()
}
if driver == "firefox" {
agoutiDriver = agouti.Selenium(agouti.Browser("firefox"))
}
err := agoutiDriver.Start()
if err != nil {
panic(err)
}
flag.Parse()
db, err = gorm.Open("sqlite3", "./storage.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
db.SingularTable(true)
db.AutoMigrate(&Storage{})
db.AutoMigrate(&Catalog{})
db.AutoMigrate(&Action{})
pages = make(map[string]*agouti.Page)
fmt.Println("OwlQA v0.0.1")
fmt.Println(driver)
dql := dynql.NewDQL()
dql.Put("start", start, Param{})
dql.Put("default", jsRun, Param{})
dql.Put("destroy", destroy, Param{})
r := mux.NewRouter()
rh := http.RedirectHandler("/site/queries.html", 307)
r.Handle("/", rh)
r.PathPrefix("/site/").Handler(http.StripPrefix("/site/", http.FileServer(http.Dir("site/"))))
r.PathPrefix("/webassembly/").Handler(http.StripPrefix("/webassembly/", http.FileServer(http.Dir("webassembly/"))))
gormcrud.MapMux(r, db).NewMap("/action", Action{}, []Action{}).Full()
gormcrud.MapMux(r, db).NewMap("/catalog", Catalog{}, []Catalog{}).Full()
gormcrud.MapMux(r, db).NewMap("/storage", Storage{}, []Storage{}).Full()
r.HandleFunc("/run", dql.Run).Methods(http.MethodPost)
http.Handle("/", r)
log.Fatal(http.ListenAndServe(addr, nil))
}