-
Notifications
You must be signed in to change notification settings - Fork 71
/
scriptlib.ahk
1754 lines (1628 loc) · 51.2 KB
/
scriptlib.ahk
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
-----------------------------
UI Test Automation Library
version 1.4
Updated: Mar. 21, 2017
Created by: Feng Wu ([email protected])
--------------------------------
*/
;SetWorkingDir, %A_ScriptDir%
;AHK Standard Library
#Include ../../Lib/Gdip_All.ahk
#Include ../../Lib/HTTPRequest.ahk
#Include ../../Lib/StrX.ahk
#Include ../../Lib/UnHTM.ahk
#Include ../../Lib/json.ahk
/*
-------------------------------------Update History------------------------------
03/21/2017
Replace Gdip.ahk with Gdip_All.ahk to support AHK: 32, 64, unicode, ansi
Solve printScreen does not work with Gdip on Win10 64bit
PrtScreen / PrtFromScreen
https://autohotkey.com/boards/viewtopic.php?f=6&t=6517
02/12/2014
update WaitForImageVanish
12/08/2013
v1.4
- separate module lib from scriptlib
- add WX11Lib, Email libraries
- remove ini.ahk library to improve the performance of case execution
- add GetAllKVFromFile and GetSectionKVFromFile
- rewrite WaitForImage, WaitForImageVanish, WaitForPixelColor, WaitForPixelColorVanish
-
11/12/2013
change HT< login only via CI
LoginSPICall -> LoginSPICallV13
SendSpiCall -> SendSpiCallV13
09/23/13
1.2.3- add an API - ClearCookies
05/03/13
Update if statement
1.2.2 - 11/14/12
Modify it to correct logic __GetEmailIDByEmailCode
Add 9 APIs for email testing in Outlook2007/2010
GetFirstEmailFromOL, SearchEmailByTopicFromOL, InstantSearchEmailFromOL
SearchEmailByTopicFromOL_AD, DeleteEmailFromOL, DeleteAllEmailsFromOL, ReceiveEmailFromOL
GetHTMLEmailBodyFromOL, GetPlainTextEmailBodyFromOL
Fixed: GetEmailIDByTopic - GET method in HTTPRequest is not available, so change the url
1.2.1 - 10/10/12
Add 5 APIs
ParseJsonStrToArr, GetEmailIDByTopic, OpenPageWithBrowser
EmailPageURL, GoToPageLinkedInEmail
1.2
1. Add some APIs to get email templates information from free email server and verify results
ToDo:
1. Verify and Wait
2. Report
3. Configuration case dependency
4. relative path issue
1.1
1. Rname GetHTMLSourceCode to GetHTMLCodeFromServ
2. Add GetHTMLCodeFromClient(), GetTextFromHtml()
1.0.1
1. modify PrtScreen() - change default directory to "capture_screen" in each module
2. Import AHK standard library
3. Fix GetTextFromPage() bug: if offset="", the behavior is wrong
4. Fix GetIniFile() bug: filePattern should be file_path
5. Add "`r`n" to error_msg
1.0
-Fix ActiveBrowserWin timeout issue
Add new APIs:
- SendEmailFromOL
- Highlight
- CreateEmailAccount
- GetHTMLSourceCode
0.9
getKVObjFromIni(ini)- change the parameter
MoveMouseToImage-remove time parameter
WaitForImage-Add "image_dir" parameter
Remove local
ErrorLevel, error_message, isError
0.8
- fix GetTextFromPage bug
Add new APIs:
- PrtImgFromScreen
- EvalString(inputstr)
v0.7
Add new APIs:
- LoginWAPI(wapiBaseURL, username, pwd)
- SendWAPICall(cmd, task, wapiCall)
- ClickImage(image)
v0.6
Add new APIs:
- UriEncode/UriDecode/StrPutVar
- Spicall
- improve waitForImage : *n Share the same images with various browsers
v0.5 GetTextFromPage(strReg)2.modify parameter default value expression
v0.4 remove offsetx,offsety from clickElement and MoveMouseToCoor
v0.3
GetKVObjFromIni(iniFileWithPath)
v0.2
add - MoveMouseToCoor
----------------------------------------------------------------------------------
*/
/*
------------------------------------Utils-----------------------------------------
GetAllKVFromFile, GetSectionKVFromFile, GetSplittedObj,
ShowTooltip, CopyURLFromAddressBar, GoToURLByPaste, GetTextFromPage,
UriEncode, UriDecode, EvalString, Highlight
GetHTMLCodeFromServ, GetHTMLCodeFromClient, GetTextFromHtml, GetValFromStr
ParseJsonStrToArr
----------------------------------------------------------------------------------
*/
;-------------------------------------------------------------------------------
;
; Function: GetAllKVFromFile
; Description:
; Generate an object which stores all keys and values of the INI file
; Syntax: GetAllKVFromFile(file_path)
; Parameters:
; file_path - the path of the ini file
; Return Value:
; return an object which stores all keys and values of the INI file
; Related:
; GetSectionKVFromFile
; Example:
; cfgobj := GetAllKVFromFile("c:\config.ini")
;
;-------------------------------------------------------------------------------
GetAllKVFromFile(file_path) {
obj := object()
IniRead, secs, %file_path%
Loop, parse, secs, `n
{
section_name := A_LoopField
IniRead, content, %file_path%, %section_name%
Loop, parse, content, `r`n
{
field := A_LoopField
StringGetPos, pos, field, `#
if !ErrorLevel
continue
StringSplit, kv, field, `=
obj[kv1] := kv2
}
}
return obj
}
;-------------------------------------------------------------------------------
;
; Function: GetSectionKVFromFile
; Description:
; Generate an object which stores keys and values belongs to specified section in the INI file
; Syntax: GetSectionKVFromFile(file_path, section_name)
; Parameters:
; file_path - the path of the ini file
; section_name - section name
; Return Value:
; return an object which stores keys and values belongs to specified section in the INI file
; Related:
; GetAllKVFromFile
; Example:
; secobj := GetSectionKVFromFile("c:\config.ini", "section1")
;
;-------------------------------------------------------------------------------
GetSectionKVFromFile(file_path, section_name) {
obj := object()
IniRead, content, %file_path%, %section_name%
if (!content){
msg := "[" . A_ThisFunc . "] Warring - [" . section_name . "] does not exist in [" . file_path . "]"
Debug(msg)
return
}
Loop, parse, content, `r`n
{
field := A_LoopField
StringGetPos, pos, field, `#
if !ErrorLevel
continue
StringSplit, kv, field, `=
obj[kv1] := kv2
}
return obj
}
;-------------------------------------------------------------------------------
;
; Function: GetSplittedObj
; Description:
; Split string to array object
; Syntax: GetSplittedObj(str)
; Parameters:
; str - string includes "," for example "w,x,y, y, z"
; Return Value:
; array object - for example: object( 1, w, 2, x, 3, y, 4, z )
; Remarks:
; Real arrays don't exist in AutoHotkey. You can use global or object instead.
; http://www.autohotkey.com/forum/topic45148.html&highlight=return+array
; http://www.autohotkey.com/forum/topic54446.html&postdays=0&postorder=asc&highlight=return+array&start=0
; Related: [bbcode]None.
; Example:
; xy := GetSplittedObj(strcoors)
; x := xy[1] y:= xy[2]
;
;-------------------------------------------------------------------------------
GetSplittedObj(str) {
global @error_msg
try
{
obj := object()
StringSplit, arr, str, `, ; real arrays don't exist in AutoHotkey. You can use global or object instead.
loop, %arr0%
{
obj[A_Index] := Trim(arr%A_Index%)
}
return obj
}
catch
{
@error_msg := "[" . A_ThisFunc . "] Err - Format of string is wrong [ " . str . "]`r`n"
Gosub, ErrorLabel
}
}
;-------------------------------------------------------------------------------
;
; Function: ShowTooltip
; Description:
; Show tooltip for a while
; Syntax: ShowTooltip(msg[, t])
; Parameters:
; msg - content
; t - show t milliseconds
; Related: [bbcode]None.
; Example:
; ShowTooltip("The script is running `n[ESC]-Stop`n[Pause]-Pause/Resume`n[PrintScreen]-Print Screen", 1000)
;
;-------------------------------------------------------------------------------
ShowTooltip(msg, t = 1000) {
ToolTip, %msg%
Sleep, %t%
ToolTip
}
;-------------------------------------------------------------------------------
;
; Function: CopyURLFromAddressBar
; Description:
; Copy URL from address bar of browser to clipboard
; Syntax: CopyURLFromAddressBar()
; Return Value:
; URL String
; Related:
; GoToURLByPaste
; Example:
; url := CopyURLFromAddressBar()
;
;-------------------------------------------------------------------------------
CopyURLFromAddressBar() {
clipboard=
Send !d
Sleep, 200
Send ^c
ClipWait, 2
return clipboard
}
;-------------------------------------------------------------------------------
;
; Function: GoToURLByPaste
; Description:
; Go to URL site via pasting clipboard (URL) to address bar of browser
; Syntax: GoToURLByPaste()
; Related:
; [bbcode]CopyURLFromAddressBar
; Remarks:
; Make sure clipboard is URL
;
;-------------------------------------------------------------------------------
GoToURLByPaste() {
Send !d
Sleep, 500
Send ^v
Sleep, 500
Send, {Enter}
}
;-------------------------------------------------------------------------------
;
; Function: GetTextFromPage
; Description:
; Get text in a region
; Syntax: GetTextFromPage(strcoors [, speed = "", offset = ""])
; Parameters:
; strcoors - "x1, y1, x2, y2"
; x1,y1: The x1/y1 coordinates of the drag's starting position
; x2,y2: The x2/y2 coordinates to drag the mouse to
; speed - (Optional) Mouse movement speed
; offset - (Optional)
; R (Default): The x1/y1 coordinates will be treated as offsets from the current mouse position
; x2 and y2 coordinates will be treated as offsets from the x1 and y1 coordinates
; W: Coordinates are relative to the active window (Mouse Position In active window)
; Return Value:
; Text in the region (strcoors)
; Remarks:
; The function is for text assertion
; Related: [bbcode]None.
; Example:
; text := GetTextFromPage("40, 205, 100, 2")
; text := GetTextFromPage("285,268,390,288",,"W")
;
;-------------------------------------------------------------------------------
GetTextFromPage(strcoors, speed = 15, offset = "R") {
global @error_msg
xys := GetSplittedObj(strcoors)
if (offset == "R")
{
yy := Abs(xys[4]//2)
}
else
{
y := Abs((xys[4] - xys[2]) // 2)
yy := xys[2] > xys[4] ? xys[2] - y : xys[2] + y
}
if (!!xys)
{
if (offset == "R")
{
MouseClickDrag, Left, % xys[1], xys[2], xys[3], yy, speed, R
}
else if (offset == "W")
{
MouseClickDrag, Left, % xys[1], yy, xys[3], yy, speed
}
else
{
@error_msg := "[" . A_ThisFunc . "] Err - The parameter offset [" . offset . "] is wrong. `r`n"
Gosub, ErrorLabel
}
Sleep, 200
Send ^c
ClipWait, 2
return Trim(clipboard)
}
else
{
@error_msg := "[" . A_ThisFunc . "] Err - strcoors [" . strcoors . "] is wrong `r`n"
Gosub, ErrorLabel
}
}
;-------------------------------------------------------------------------------
;
; Function: UriEncode
; Description:
; Encode Uri
; Syntax: UriEncode(Uri [, Enc = "UTF-8"])
; Parameters:
; Uri - value of parameter in Uri
; Enc - (Optional) default encoding is UTF-8
; Return Value:
; Encode Ur
; Related:
; UriDecode, SendSpiCall
; Example:
; encode_wbx11Ticket := UriEncode(wbx11Ticket)
;
;-------------------------------------------------------------------------------
UriEncode(Uri, Enc = "UTF-8") {
StrPutVar(Uri, Var, Enc)
f := A_FormatInteger
SetFormat, IntegerFast, H
Loop
{
Code := NumGet(Var, A_Index - 1, "UChar")
If (!Code)
Break
If (Code >= 0x30 && Code <= 0x39 ; 0-9
|| Code >= 0x41 && Code <= 0x5A ; A-Z
|| Code >= 0x61 && Code <= 0x7A) ; a-z
Res .= Chr(Code)
Else
Res .= "%" . SubStr(Code + 0x100, -1)
}
SetFormat, IntegerFast, %f%
Return, Res
}
;-------------------------------------------------------------------------------
;
; Function: UriDecode
; Description:
; Decode Uri
; Syntax: UriDecode(Uri [, Enc = "UTF-8"])
; Parameters:
; Uri - value of parameter in Uri
; Enc - (Optional) default encoding is UTF-8
; Return Value:
; Decode Uri
; Related:
; UriEncode, SendSpiCall
; Example:
; encode_wbx11Ticket := UriEncode(wbx11Ticket)
; wbx11Ticket := UriDecode(encode_wbx11Ticket)
;
;-------------------------------------------------------------------------------
UriDecode(Uri, Enc = "UTF-8") {
Pos := 1
Loop
{
Pos := RegExMatch(Uri, "i)(?:%[\da-f]{2})+", Code, Pos++)
If (Pos = 0)
Break
VarSetCapacity(Var, StrLen(Code) // 3, 0)
StringTrimLeft, Code, Code, 1
Loop, Parse, Code, `%
NumPut("0x" . A_LoopField, Var, A_Index - 1, "UChar")
StringReplace, Uri, Uri, `%%Code%, % StrGet(&Var, Enc), All
}
Return, Uri
}
;-------------------------------------------------------------------------------
;
; Function: EvalString
; Description:
; Get the real string without variables
; Syntax: EvalString(inputstr)
; Parameters:
; inputstr - String with variable(s)eg: "this string has ${var}"
; Return Value:
; Real string without variable(s) - "this string has real variable"
; Related:
; SendSpiCall, SendWapiCall
; Example:
; 1. replace existing variables.
; global var := "real variable" str := "this string has ${var}" retstr := EvalString(str) - "this string has real variable"
; 2. non-existing variable will be blank
; str := "this string has ${nonexistingvar}" retstr := EvalString(str) - "this string has "
; 3. getUsrinfoSPI(e)
; {
; global email := e
; __spiCall := "[{'service':'account','spi':'checkEmails','parameters':{'emails':'${email}'}}]"
; spiCall := EvalString(__spiCall)
; return SendSpiCall(spiCall)
; }
;
;-------------------------------------------------------------------------------
EvalString(inputstr) {
pos :=1
retstr := inputstr
While pos:=RegExMatch(inputstr,"\${([\w]+)}", m, Pos+StrLen(m))
{
;retStr := RegExReplace(retStr, m, %m1%)
StringReplace, retstr, retstr, %m%, % %m1% ;m: #var# m1: var
}
Debug("[" . A_ThisFunc . "] " . retstr)
return retstr
}
;-------------------------------------------------------------------------------
;
; Function: Highlight
; Description:
; Show a red rectangle outline to highlight specified region, it's useful to debug
; Syntax: Highlight(region [, delay = 1500])
; Parameters:
; reg - The region for highlight
; delay - Show time (milliseconds)
; Return Value:
; Real string without variable(s) - "this string has real variable"
; Related:
; SendSpiCall, SendWapiCall
; Remarks:
; #Include, Gdip.ahk
; Example:
; Highlight("100,200,300,400")
; Highlight("100,200,300,400", 1000)
;
;-------------------------------------------------------------------------------
Highlight(reg, delay=1500 {
global @reg_global
; Start gdi+
If !pToken := Gdip_Startup()
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
StringSplit, g_coors, @reg_global, `,
; Set the width and height we want as our drawing area, to draw everything in. This will be the dimensions of our bitmap
Width := g_coors3
Height := g_coors4
; Create a layered window (+E0x80000 : must be used for UpdateLayeredWindow to work!) that is always on top (+AlwaysOnTop), has no taskbar entry or caption
Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
; Show the window
Gui, 1: Show, NA
; Get a handle to this window we have created in order to update it later
hwnd1 := WinExist()
; Create a gdi bitmap with width and height of what we are going to draw into it. This is the entire drawing area for everything
hbm := CreateDIBSection(Width, Height)
; Get a device context compatible with the screen
hdc := CreateCompatibleDC()
; Select the bitmap into the device context
obm := SelectObject(hdc, hbm)
; Get a pointer to the graphics of the bitmap, for use with drawing functions
G := Gdip_GraphicsFromHDC(hdc)
; Set the smoothing mode to antialias = 4 to make shapes appear smother (only used for vector drawing and filling)
Gdip_SetSmoothingMode(G, 4)
; Create a slightly transparent (66) blue pen (ARGB = Transparency, red, green, blue) to draw a rectangle
; This pen is wider than the last one, with a thickness of 10
pPen := Gdip_CreatePen(0xffff0000, 2)
; Draw a rectangle onto the graphics of the bitmap using the pen just created
; Draws the rectangle from coordinates (250,80) a rectangle of 300x200 and outline width of 10 (specified when creating the pen)
StringSplit, reg_coors, reg, `,
x := reg_coors1
y := reg_coors2
w := reg_coors3 - reg_coors1
h := reg_coors4 - reg_coors2
Gdip_DrawRectangle(G, pPen, x, y, w, h)
; Delete the brush as it is no longer needed and wastes memory
Gdip_DeletePen(pPen)
; Update the specified window we have created (hwnd1) with a handle to our bitmap (hdc), specifying the x,y,w,h we want it positioned on our screen
; So this will position our gui at (0,0) with the Width and Height specified earlier
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
; Select the object back into the hdc
SelectObject(hdc, obm)
; Now the bitmap may be deleted
DeleteObject(hbm)
; Also the device context related to the bitmap may be deleted
DeleteDC(hdc)
; The graphics may now be deleted
Gdip_DeleteGraphics(G)
Sleep, %delay%
Gui, 1: Show, Hide
Gdip_Shutdown(pToken)
}
;-------------------------------------------------------------------------------
;
; Function: GetHTMLCodeFromServ
; Description:
; Get html source code before page renderred by Javascript
; Syntax: GetHTMLCodeFromServ()
; Parameters:
; None
; Return Value:
; clipboard - html source code as string
; Remarks:
; The html source is from server without executing javascript, so does not include DOM source
; Use GetHTMLCodeFromClient to get the whole html including DOM source
; Related:
; GetHTMLCodeFromClient
; Example:
; brexe := "iexplore.exe"
; html_source_code := GetHTMLCodeFromServ()
;
;-------------------------------------------------------------------------------
GetHTMLCodeFromServ() {
global @brexe, @error_msg
clipboard=
if (@brexe == "iexplore.exe")
{
Send, {alt down}vc{alt up}
WinWaitActive, ahk_class SOURCE_VIEWER
Send, ^a
Sleep, 200
Send, ^c
ClipWait, 2
WinClose, ahk_class SOURCE_VIEWER
return clipboard
}
else if (@brexe == "firefox.exe")
{
Send, ^u
WinWaitActive, Source of:,,1
Send, ^a
Sleep, 200
Send, ^c
ClipWait, 2
WinClose
return clipboard
}
else if (@brexe == "chrome.exe")
{
Send, ^u
WinWaitActive, view-source:,,1
Send, ^a
Sleep, 200
Send ^c
ClipWait, 2
Send, ^w
Sleep, 200
return clipboard
}
else
{
@error_msg := "[" . A_ThisFunc . "] Err - Make sure brexe [" . @brexe . "] value in sysconfig.ini is correct. `r`n"
Gosub, ErrorLabel
}
}
;-----------------------------
;
; Function: GetHTMLCodeFromClient
; Description:
; Get HTML code after page renderred completely
; Syntax: GetHTMLCodeFromClient(is_saved)
; Parameters:
; is_saved - true: get html code from existing temporary file false: write html code to a temporary file
; Remarks:
; Some time we need do verification, so need get critical information from page such as text on page, parameter value
; from html code. the method will return html code for further handling.
; Related:
; GetHTMLCodeFromServ, GetTextFromHtml
; Example:
; brexe := "firefox.exe"
; x := GetHTMLCodeFromClient(false)
; MsgBox, %x%
;
;-------------------------------------------------------------------------------
GetHTMLCodeFromClient(is_saved) {
if (is_saved)
{
FileRead, htmlcode, tmp/__htmlsource__.txt
return htmlcode
}
else
{
IfExist, tmp/__htmlsource__.txt
FileDelete, tmp/__htmlsource__.txt
return __GetHTMLCodeFromBrowsers()
}
}
__GetHTMLCodeFromBrowsers() {
global @brexe, @error_msg
Clipboard := ""
if (@brexe == "chrome.exe")
{
Send, {F12}
Sleep, 1500
Send, ^c
ClipWait, 1
Send, {F12}
}
else if (@brexe == "firefox.exe")
{
Send, ^a
Sleep, 500
MouseClick, right
Sleep, 500
Send, {e}
Sleep, 1000
WinGet, active_id, ID, A
Send, ^c
ClipWait, 1
WinClose, ahk_id %active_id% ; close source code window
Sleep, 500
MouseClick, left, 1,250
Sleep, 500
}
else if (@brexe == "iexplore.exe")
{
Send, {F12}
Sleep, 1500
WinWaitActive, ahk_class IEDEVTOOLS,,2
Send, ^g
WinWaitActive, ahk_class HTMLSOURCEVIEW,,5
Send, ^a
Sleep, 500
Send, ^c
ClipWait, 1
WinClose
WinClose, ahk_class IEDEVTOOLS
}
else
{
; Debug("[" . A_ThisFunc . "] Err - Make sure brexe [" . @brexe . "] value in sysconfig.ini is correct. `r`n" )
;return
@error_msg := "[" . A_ThisFunc . "] Err - Make sure brexe [" . @brexe . "] value in sysconfig.ini is correct. `r`n"
Gosub, ErrorLabel
}
FileAppend, %Clipboard%, tmp/__htmlsource__.txt
return Clipboard
}
;-----------------------------
;
; Function: GetTextFromHtml
; Description:
; Get text (innerText) from html code, html tag will be removed
; Syntax: GetTextFromHtml(html, begin_html_str, end_html_str)
; Parameters:
; html - html code
; begin_html_str - any html before matched text
; end_html_str - any html after matched text
; Remarks:
; 1. The method is usually to get innertext in html
; 2. Both beginHtmlStr and endHtmlStr are included in the string returned by StrX
; Related:
; GetHTMLCodeFromServ, GetHTMLCodeFromClient, GetValFromStr
; Example:
; Example 1:
; html := "<li class=""nav_home"" module=""home""><a href=""/collabs/#/home"" class=""btn"" data-monitor-id=""headerHome""><span>Home</span></a></li>"
; home := GetTextFromHtml(html, "<li", "</li>") ; return Home
; home := GetTextFromHtml(html, "<li class=""nav_home"" module=""home"">", "</li>") ;return Home
;
;-------------------------------------------------------------------------------
GetTextFromHtml(html, begin_html_str, end_html_str) {
return UnHTM(StrX(html, begin_html_str, N, 0, end_html_str, 1, 0, N)) ; Both beginHtmlStr and endHtmlStr are included in the string returned by StrX
}
;-----------------------------
;
; Function: GetValFromStr
; Description:
; Get paramter value from string or html text, html tag will be removed
; Syntax: GetValFromStr(str, beginStr, endStr)
; Parameters:
; str - string or html text
; beginStr - any string before matched text
; endStr - any string after matched text
; Remarks:
; 1. The method is usually to get parameter's value in html or sub-String between beginStr and endStr
; 2. Both beginStr and endStr are excluded from the string returned by StrX
; Related:
; GetHTMLCodeFromServ, GetHTMLCodeFromClient, GetTextFromHtml
; Example:
; Example 1:
; html =
; (`
; <li class="nav_home" module="home"><a href="/collabs/#/home" class="btn" data-monitor-id="headerHome"><span>Home</span></a></li>
; )
; home := GetValFromStr(html, "<li class=""nav_home"" module=""home"">", "</li>") ;return Home
; Example 2:
; a =
; (`
; <script type="text/javascript">
; var WBX_HEADER = {
; 'baseUrl': 'https://wlc.webex.com' + '/',
; 'cover':'https://bt3.ciscowebex.com/collabs/resource/images/support/shedule_video_4.png',
; 'playUrl':'/players/video/hqvideo.swf',
; 'loginUserID': "UF34GWCXFLNHV65WBQ347YIUZE-1BZ"
; }
; ...
; </script>
; )
; playUrlValue := GetValFromStr(a, "'playUrl':'", "',") ; return /players/video/hqvideo.swf
;
;-------------------------------------------------------------------------------
GetValFromStr(str, beginStr, endStr) {
return UnHTM(StrX(str, beginStr, N, StrLen(beginStr), endStr, 1, strLen(endStr), N)) ; both beginStr and endStr are excluded from the string returned by StrX
}
;-----------------------------
;
; Function: ParseJsonStrToArr(v1.2.1)
; Description:
; Parse Json string to an array
; Syntax: ParseJsonStrToArr(json_data)
; Parameters:
; json_data - json string
; Return Value:
; return an array
; Remarks:
; Each item in the array still is string type
; Related:
; N/A
; Example:
; j := "[{'id':'a1','subject':'s1'},{'id':'a2','subject':'s2},{'id':'a3','subject':'s3'}]"
; arr = ParseJsonStrToArr(j)
;
;-------------------------------------------------------------------------------
ParseJsonStrToArr(json_data) {
arr := []
pos :=1
While pos:=RegExMatch(json_data,"((?:{)[\s\S][^{}]+(?:}))", j, pos+StrLen(j))
{
arr.Insert(j1) ; insert json string to array arr=[{"id":"a1","subject":"s1"},{"id":"a2","subject":"s2"},{"id":"a3","subject":"s3"}]
}
return arr
}
/*
------------------------------------Core----------------------------------------
WaitForImage, WaitForImageVanish, WaitForPixelColor,
WaitForPixelColorVanish, OpenSiteWithBrowser, ClearCookies
ActiveBrowserWin, PrtScreen, PrtFromScreen,
Debug
-------------------------------------------------------------------------------
*/
;-------------------------------------------------------------------------------
;
; Function: WaitForImage
; Description:
; Search the image in some region
; Syntax: WaitForImage(i_keyimage [, i_reg, i_timeout, n])
; Parameters:
; i_keyimage - the key image for searching
; i_reg - the search region, the default is fullscreen(0, 0, 1440, 900)
; i_timeout - searching the key image should be in the specified time
; n - Specify for n a number between 0 (accurately represent an image)and 255 (does not accurately)
; to indicate the allowed number of shades of variation in either direction for the intensity of the red, green,
; and blue components of each pixel's color. For example, *2 would allow two shades of variation
; Return Value:
; [FoundX,FoundY] if found keyimage otherwise return none
; Remarks:
; 1. The same image on the IE/FF/Chrome/.. are different, so need prepare to key image on different browsers
; Related: [bbcode] WaitForImageVanish, WaitForPixelColor, WaitForPixelColorVanish
; Example:
; logoXY := WaitForImage("wbxlogo.png", "0, 0, 1440, 900", 10000, 50)
;
;-------------------------------------------------------------------------------
WaitForImage(ByRef i_keyimage, i_reg = "", i_timeout = "", n = 50) {
global @reg_global, @timeout, @image_dir, @isDebug, @error_msg
i_reg := i_reg ? i_reg : @reg_global
i_timeout := i_timeout ? i_timeout : @timeout
i_img_fullpath := @image_dir . "/" . i_keyimage
i_start := A_TickCount
i_coords := []
n := n == "" ? 50 : n
StringSplit, coords, i_reg, `,
Debug(coords1)
Loop
{
ImageSearch, foundX, foundY, %coords1%, %coords2%, %coords3%, %coords4%, *%n% %i_img_fullpath%
if (ErrorLevel = 0)
{
if(@isDebug and !!i_reg)
{
Highlight(i_reg)
}
i_coords.Insert(foundX)
i_coords.Insert(foundY)
return i_coords
}
if (ErrorLevel = 2)
{
@error_msg := "[" . A_ThisFunc . "] Err - [" . i_img_fullpath . "] Could not conduct the search. (such as failure to open the image file or a badly formatted option)."
gosub, ErrorLabel
i_keyimage := ""
return
}
If (A_TickCount - i_start >= i_timeout)
{
@error_msg := "[" . A_ThisFunc . "] Err - [" . i_img_fullpath . "] was not found in " . i_timeout . " ms `r`n"
gosub, ErrorLabel
i_keyimage := ""
return
}
}
}
;-------------------------------------------------------------------------------
;
; Function: WaitForImageVanish
; Description:
; Wait for the image vanish in some region
; Syntax: WaitForImageVanish(i_keyimage [, i_reg, i_timeout, n])
; Parameters:
; i_keyimage - the key image for searching, default image directory is set by "@image_dir" in sysconfig.ini
; i_reg - the search region, the default is fullscreen(0, 0, 1440, 900)
; i_timeout - searching the key image should be in the specified time
; n - Specify for n a number between 0 (accurately represent an image)and 255 (does not accurately)
; to indicate the allowed number of shades of variation in either direction for the intensity of the red, green,
; and blue components of each pixel's color. For example, *2 would allow two shades of variation
; Return Value:
; None
; Remarks:
; 1. The same image on the IE/FF/Chrome/.. are different, so need prepare to key image on different browsers[br]
; Related:
; [bbcode] WaitForImage, WaitForPixelColor, WaitForPixelColorVanish
; Example:
; WaitForImageVanish("wbxlogo.png", "0, 0, 1440, 900", 10000, 50)
;
;-------------------------------------------------------------------------------
WaitForImageVanish(ByRef i_keyimage, i_reg = "", i_timeout = "", n = 50) {
global @reg_global, @timeout, @image_dir, @isDebug, @error_msg
i_reg := i_reg ? i_reg : @reg_global
i_timeout := i_timeout ? i_timeout : @timeout
i_img_fullpath := @image_dir . "/" . i_keyimage
i_start := A_TickCount
i_coords := []
n := n == "" ? 50 : n
StringSplit, coords, i_reg, `,
if(@isDebug and !!i_reg)
{
Highlight(i_reg)
}
While A_TickCount - i_start <= i_timeout
{
ImageSearch, foundX, foundY, %coords1%, %coords2%, %coords3%, %coords4%, *%n% %i_img_fullpath%
if (ErrorLevel = 0)
{
Sleep, 1000
continue
}
if (ErrorLevel = 2)
{
@error_msg := "[" . A_ThisFunc . "] Err - [" . i_img_fullpath . "] Could not conduct the search. (such as failure to open the image file or a badly formatted option)."
gosub, ErrorLabel
i_keyimage := ""
return
}
if (ErrorLevel = 1)
{
return
}
}
@error_msg := "[" . A_ThisFunc . "] Err - [" . i_img_fullpath . "] was still found in " . i_timeout . " ms `r`n"
gosub, ErrorLabel
return
}
;-------------------------------------------------------------------------------
;
; Function: WaitForPixelColor
; Description:
; Search special color in some region
; Syntax: WaitForPixelColor(p_colorid [, p_reg, p_timeout])
; Parameters:
; p_colorid - The decimal or hexadecimal color ID to search for, in [b]Blue-Green-Red (BGR)[/b] format,
; which can be an expression. Color IDs can be determined using Window Spy (accessible from the tray menu)
; or via PixelGetColor. For example: 0x9d6346
; p_reg - Search region
; p_timeout - searching the colorid should be in the specified time
; Return Value:
; [FoundX,FoundY] if found colorid otherwise return none
; Remarks:
; 1. The colorid on the IE/FF/Chrome/.. are different, so need prepare to each colorid on different browsers
; Related:
; [bbcode] WaitForImage,WaitForImageVanish, WaitForPixelColorVanish
; Example:
; pixelXY := WaitForPixelColor("0x24B577", "100, 200, 200, 400", 10000)
;
;-------------------------------------------------------------------------------
WaitForPixelColor(ByRef p_colorid, p_reg, p_timeout = "") {
global @timeout, @isDebug, @error_msg
p_timeout := p_timeout ? p_timeout : @timeout
p_start := A_TickCount
p_coords := []
StringSplit, coords, p_reg, `,
Loop
{
PixelSearch, foundX, foundY, %coords1%, %coords2%, %coords3%, %coords4%, %p_colorid%,,Fast RGB
if (!ErrorLevel)
{
if(@isDebug)
{
Highlight(p_reg)
}
p_coords.Insert(foundX)
p_coords.Insert(foundY)
return p_coords