This repository was archived by the owner on Mar 4, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebHelpers.bas
3133 lines (2741 loc) · 108 KB
/
WebHelpers.bas
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
Attribute VB_Name = "WebHelpers"
''
' WebHelpers v4.1.6
' (c) Tim Hall - https://github.com/VBA-tools/VBA-Web
'
' Contains general-purpose helpers that are used throughout VBA-Web. Includes:
'
' - Logging
' - Converters and encoding
' - Url handling
' - Object/Dictionary/Collection/Array helpers
' - Request preparation / handling
' - Timing
' - Mac
' - Cryptography
' - Converters (JSON, XML, Url-Encoded)
'
' Errors:
' 11000 - Error during parsing
' 11001 - Error during conversion
' 11002 - No matching converter has been registered
' 11003 - Error while getting url parts
' 11099 - XML format is not currently supported
'
' @module WebHelpers
' @author [email protected]
' @license MIT (http://www.opensource.org/licenses/mit-license.php)
'' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ '
Option Explicit
' Contents:
' 1. Logging
' 2. Converters and encoding
' 3. Url handling
' 4. Object/Dictionary/Collection/Array helpers
' 5. Request preparation / handling
' 6. Timing
' 7. Mac
' 8. Cryptography
' 9. Converters
' VBA-JSON
' VBA-UTC
' AutoProxy
' --------------------------------------------- '
' Custom formatting uses the standard version of Application.Run,
' which is incompatible with some Office applications (e.g. Word 2011 for Mac)
'
' If you have compilation errors in ParseByFormat or ConvertToFormat,
' you can disable custom formatting by setting the following compiler flag to False
#Const EnableCustomFormatting = True
' === AutoProxy Headers
#If Mac Then
#ElseIf VBA7 Then
Private Declare PtrSafe Sub AutoProxy_CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(ByVal AutoProxy_lpDest As LongPtr, ByVal AutoProxy_lpSource As LongPtr, ByVal AutoProxy_cbCopy As Long)
Private Declare PtrSafe Function AutoProxy_SysAllocString Lib "oleaut32" Alias "SysAllocString" _
(ByVal AutoProxy_pwsz As LongPtr) As LongPtr
Private Declare PtrSafe Function AutoProxy_GlobalFree Lib "kernel32" Alias "GlobalFree" _
(ByVal AutoProxy_p As LongPtr) As LongPtr
Private Declare PtrSafe Function AutoProxy_GetIEProxy Lib "WinHTTP.dll" Alias "WinHttpGetIEProxyConfigForCurrentUser" _
(ByRef AutoProxy_proxyConfig As AUTOPROXY_IE_PROXY_CONFIG) As Long
Private Declare PtrSafe Function AutoProxy_GetProxyForUrl Lib "WinHTTP.dll" Alias "WinHttpGetProxyForUrl" _
(ByVal AutoProxy_hSession As LongPtr, ByVal AutoProxy_pszUrl As LongPtr, ByRef AutoProxy_pAutoProxyOptions As AUTOPROXY_OPTIONS, ByRef AutoProxy_pProxyInfo As AUTOPROXY_INFO) As Long
Private Declare PtrSafe Function AutoProxy_HttpOpen Lib "WinHTTP.dll" Alias "WinHttpOpen" _
(ByVal AutoProxy_pszUserAgent As LongPtr, ByVal AutoProxy_dwAccessType As Long, ByVal AutoProxy_pszProxyName As LongPtr, ByVal AutoProxy_pszProxyBypass As LongPtr, ByVal AutoProxy_dwFlags As Long) As LongPtr
Private Declare PtrSafe Function AutoProxy_HttpClose Lib "WinHTTP.dll" Alias "WinHttpCloseHandle" _
(ByVal AutoProxy_hInternet As LongPtr) As Long
Private Type AUTOPROXY_IE_PROXY_CONFIG
AutoProxy_fAutoDetect As Long
AutoProxy_lpszAutoConfigUrl As LongPtr
AutoProxy_lpszProxy As LongPtr
AutoProxy_lpszProxyBypass As LongPtr
End Type
Private Type AUTOPROXY_OPTIONS
AutoProxy_dwFlags As Long
AutoProxy_dwAutoDetectFlags As Long
AutoProxy_lpszAutoConfigUrl As LongPtr
AutoProxy_lpvReserved As LongPtr
AutoProxy_dwReserved As Long
AutoProxy_fAutoLogonIfChallenged As Long
End Type
Private Type AUTOPROXY_INFO
AutoProxy_dwAccessType As Long
AutoProxy_lpszProxy As LongPtr
AutoProxy_lpszProxyBypass As LongPtr
End Type
#Else
Private Declare Sub AutoProxy_CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
(ByVal AutoProxy_lpDest As Long, ByVal AutoProxy_lpSource As Long, ByVal AutoProxy_cbCopy As Long)
Private Declare Function AutoProxy_SysAllocString Lib "oleaut32" Alias "SysAllocString" _
(ByVal AutoProxy_pwsz As Long) As Long
Private Declare Function AutoProxy_GlobalFree Lib "kernel32" Alias "GlobalFree" _
(ByVal AutoProxy_p As Long) As Long
Private Declare Function AutoProxy_GetIEProxy Lib "WinHTTP.dll" Alias "WinHttpGetIEProxyConfigForCurrentUser" _
(ByRef AutoProxy_proxyConfig As AUTOPROXY_IE_PROXY_CONFIG) As Long
Private Declare Function AutoProxy_GetProxyForUrl Lib "WinHTTP.dll" Alias "WinHttpGetProxyForUrl" _
(ByVal AutoProxy_hSession As Long, ByVal AutoProxy_pszUrl As Long, ByRef AutoProxy_pAutoProxyOptions As AUTOPROXY_OPTIONS, ByRef AutoProxy_pProxyInfo As AUTOPROXY_INFO) As Long
Private Declare Function AutoProxy_HttpOpen Lib "WinHTTP.dll" Alias "WinHttpOpen" _
(ByVal AutoProxy_pszUserAgent As Long, ByVal AutoProxy_dwAccessType As Long, ByVal AutoProxy_pszProxyName As Long, ByVal AutoProxy_pszProxyBypass As Long, ByVal AutoProxy_dwFlags As Long) As Long
Private Declare Function AutoProxy_HttpClose Lib "WinHTTP.dll" Alias "WinHttpCloseHandle" _
(ByVal AutoProxy_hInternet As Long) As Long
Private Type AUTOPROXY_IE_PROXY_CONFIG
AutoProxy_fAutoDetect As Long
AutoProxy_lpszAutoConfigUrl As Long
AutoProxy_lpszProxy As Long
AutoProxy_lpszProxyBypass As Long
End Type
Private Type AUTOPROXY_OPTIONS
AutoProxy_dwFlags As Long
AutoProxy_dwAutoDetectFlags As Long
AutoProxy_lpszAutoConfigUrl As Long
AutoProxy_lpvReserved As Long
AutoProxy_dwReserved As Long
AutoProxy_fAutoLogonIfChallenged As Long
End Type
Private Type AUTOPROXY_INFO
AutoProxy_dwAccessType As Long
AutoProxy_lpszProxy As Long
AutoProxy_lpszProxyBypass As Long
End Type
#End If
#If Mac Then
#Else
' Constants for dwFlags of AUTOPROXY_OPTIONS
Const AUTOPROXY_AUTO_DETECT = 1
Const AUTOPROXY_CONFIG_URL = 2
' Constants for dwAutoDetectFlags
Const AUTOPROXY_DETECT_TYPE_DHCP = 1
Const AUTOPROXY_DETECT_TYPE_DNS = 2
#End If
' === End AutoProxy
' === VBA-JSON Headers
' === VBA-UTC Headers
#If Mac Then
#If VBA7 Then
' 64-bit Mac (2016)
Private Declare PtrSafe Function utc_popen Lib "/usr/lib/libc.dylib" Alias "popen" _
(ByVal utc_Command As String, ByVal utc_Mode As String) As LongPtr
Private Declare PtrSafe Function utc_pclose Lib "/usr/lib/libc.dylib" Alias "pclose" _
(ByVal utc_File As LongPtr) As LongPtr
Private Declare PtrSafe Function utc_fread Lib "/usr/lib/libc.dylib" Alias "fread" _
(ByVal utc_Buffer As String, ByVal utc_Size As LongPtr, ByVal utc_Number As LongPtr, ByVal utc_File As LongPtr) As LongPtr
Private Declare PtrSafe Function utc_feof Lib "/usr/lib/libc.dylib" Alias "feof" _
(ByVal utc_File As LongPtr) As LongPtr
#Else
' 32-bit Mac
Private Declare Function utc_popen Lib "libc.dylib" Alias "popen" _
(ByVal utc_Command As String, ByVal utc_Mode As String) As Long
Private Declare Function utc_pclose Lib "libc.dylib" Alias "pclose" _
(ByVal utc_File As Long) As Long
Private Declare Function utc_fread Lib "libc.dylib" Alias "fread" _
(ByVal utc_Buffer As String, ByVal utc_Size As Long, ByVal utc_Number As Long, ByVal utc_File As Long) As Long
Private Declare Function utc_feof Lib "libc.dylib" Alias "feof" _
(ByVal utc_File As Long) As Long
#End If
#ElseIf VBA7 Then
' http://msdn.microsoft.com/en-us/library/windows/desktop/ms724421.aspx
' http://msdn.microsoft.com/en-us/library/windows/desktop/ms724949.aspx
' http://msdn.microsoft.com/en-us/library/windows/desktop/ms725485.aspx
Private Declare PtrSafe Function utc_GetTimeZoneInformation Lib "kernel32" Alias "GetTimeZoneInformation" _
(utc_lpTimeZoneInformation As utc_TIME_ZONE_INFORMATION) As Long
Private Declare PtrSafe Function utc_SystemTimeToTzSpecificLocalTime Lib "kernel32" Alias "SystemTimeToTzSpecificLocalTime" _
(utc_lpTimeZoneInformation As utc_TIME_ZONE_INFORMATION, utc_lpUniversalTime As utc_SYSTEMTIME, utc_lpLocalTime As utc_SYSTEMTIME) As Long
Private Declare PtrSafe Function utc_TzSpecificLocalTimeToSystemTime Lib "kernel32" Alias "TzSpecificLocalTimeToSystemTime" _
(utc_lpTimeZoneInformation As utc_TIME_ZONE_INFORMATION, utc_lpLocalTime As utc_SYSTEMTIME, utc_lpUniversalTime As utc_SYSTEMTIME) As Long
#Else
Private Declare Function utc_GetTimeZoneInformation Lib "kernel32" Alias "GetTimeZoneInformation" _
(utc_lpTimeZoneInformation As utc_TIME_ZONE_INFORMATION) As Long
Private Declare Function utc_SystemTimeToTzSpecificLocalTime Lib "kernel32" Alias "SystemTimeToTzSpecificLocalTime" _
(utc_lpTimeZoneInformation As utc_TIME_ZONE_INFORMATION, utc_lpUniversalTime As utc_SYSTEMTIME, utc_lpLocalTime As utc_SYSTEMTIME) As Long
Private Declare Function utc_TzSpecificLocalTimeToSystemTime Lib "kernel32" Alias "TzSpecificLocalTimeToSystemTime" _
(utc_lpTimeZoneInformation As utc_TIME_ZONE_INFORMATION, utc_lpLocalTime As utc_SYSTEMTIME, utc_lpUniversalTime As utc_SYSTEMTIME) As Long
#End If
#If Mac Then
#If VBA7 Then
Private Type utc_ShellResult
utc_Output As String
utc_ExitCode As LongPtr
End Type
#Else
Private Type utc_ShellResult
utc_Output As String
utc_ExitCode As Long
End Type
#End If
#Else
Private Type utc_SYSTEMTIME
utc_wYear As Integer
utc_wMonth As Integer
utc_wDayOfWeek As Integer
utc_wDay As Integer
utc_wHour As Integer
utc_wMinute As Integer
utc_wSecond As Integer
utc_wMilliseconds As Integer
End Type
Private Type utc_TIME_ZONE_INFORMATION
utc_Bias As Long
utc_StandardName(0 To 31) As Integer
utc_StandardDate As utc_SYSTEMTIME
utc_StandardBias As Long
utc_DaylightName(0 To 31) As Integer
utc_DaylightDate As utc_SYSTEMTIME
utc_DaylightBias As Long
End Type
#End If
' === End VBA-UTC
Private Type json_Options
' VBA only stores 15 significant digits, so any numbers larger than that are truncated
' This can lead to issues when BIGINT's are used (e.g. for Ids or Credit Cards), as they will be invalid above 15 digits
' See: http://support.microsoft.com/kb/269370
'
' By default, VBA-JSON will use String for numbers longer than 15 characters that contain only digits
' to override set `JsonConverter.JsonOptions.UseDoubleForLargeNumbers = True`
UseDoubleForLargeNumbers As Boolean
' The JSON standard requires object keys to be quoted (" or '), use this option to allow unquoted keys
AllowUnquotedKeys As Boolean
' The solidus (/) is not required to be escaped, use this option to escape them as \/ in ConvertToJson
EscapeSolidus As Boolean
End Type
Public JsonOptions As json_Options
' === End VBA-JSON
#If Mac Then
#If VBA7 Then
Private Declare PtrSafe Function web_popen Lib "/usr/lib/libc.dylib" Alias "popen" (ByVal web_Command As String, ByVal web_Mode As String) As LongPtr
Private Declare PtrSafe Function web_pclose Lib "/usr/lib/libc.dylib" Alias "pclose" (ByVal web_File As LongPtr) As LongPtr
Private Declare PtrSafe Function web_fread Lib "/usr/lib/libc.dylib" Alias "fread" (ByVal web_OutStr As String, ByVal web_Size As LongPtr, ByVal web_Items As LongPtr, ByVal web_Stream As LongPtr) As LongPtr
Private Declare PtrSafe Function web_feof Lib "/usr/lib/libc.dylib" Alias "feof" (ByVal web_File As LongPtr) As LongPtr
#Else
Private Declare Function web_popen Lib "libc.dylib" Alias "popen" (ByVal web_Command As String, ByVal web_Mode As String) As Long
Private Declare Function web_pclose Lib "libc.dylib" Alias "pclose" (ByVal web_File As Long) As Long
Private Declare Function web_fread Lib "libc.dylib" Alias "fread" (ByVal web_OutStr As String, ByVal web_Size As Long, ByVal web_Items As Long, ByVal web_Stream As Long) As Long
Private Declare Function web_feof Lib "libc.dylib" Alias "feof" (ByVal web_File As Long) As Long
#End If
#End If
Public Const WebUserAgent As String = "VBA-Web v4.1.6 (https://github.com/VBA-tools/VBA-Web)"
' @internal
Public Type ShellResult
Output As String
ExitCode As Long
End Type
Private web_pDocumentHelper As Object
Private web_pElHelper As Object
Private web_pConverters As Dictionary
' --------------------------------------------- '
' Types and Properties
' --------------------------------------------- '
''
' Helper for common http status codes. (Use underlying status code for any codes not listed)
'
' @example
' ```VB.net
' Dim Response As WebResponse
'
' If Response.StatusCode = WebStatusCode.Ok Then
' ' Ok
' ElseIf Response.StatusCode = 418 Then
' ' I'm a teapot
' End If
' ```
'
' @property WebStatusCode
' @param Ok `200`
' @param Created `201`
' @param NoContent `204`
' @param NotModified `304`
' @param BadRequest `400`
' @param Unauthorized `401`
' @param Forbidden `403`
' @param NotFound `404`
' @param RequestTimeout `408`
' @param UnsupportedMediaType `415`
' @param InternalServerError `500`
' @param BadGateway `502`
' @param ServiceUnavailable `503`
' @param GatewayTimeout `504`
''
Public Enum WebStatusCode
Ok = 200
Created = 201
NoContent = 204
NotModified = 304
BadRequest = 400
Unauthorized = 401
Forbidden = 403
NotFound = 404
RequestTimeout = 408
UnsupportedMediaType = 415
InternalServerError = 500
BadGateway = 502
ServiceUnavailable = 503
GatewayTimeout = 504
End Enum
''
' @property WebMethod
' @param HttpGet
' @param HttpPost
' @param HttpGet
' @param HttpGet
' @param HttpGet
' @default HttpGet
''
Public Enum WebMethod
HttpGet = 0
HttpPost = 1
HttpPut = 2
HttpDelete = 3
HttpPatch = 4
HttpHead = 5
End Enum
''
' @property WebFormat
' @param PlainText
' @param Json
' @param FormUrlEncoded
' @param Xml
' @param Custom
' @default PlainText
''
Public Enum WebFormat
PlainText = 0
JSON = 1
FormUrlEncoded = 2
XML = 3
Custom = 9
End Enum
''
' @property UrlEncodingMode
' @param StrictUrlEncoding RFC 3986, ALPHA / DIGIT / "-" / "." / "_" / "~"
' @param FormUrlEncoding ALPHA / DIGIT / "-" / "." / "_" / "*", (space) -> "+", &...; UTF-8 encoding
' @param QueryUrlEncoding Subset of strict and form that should be suitable for non-form-urlencoded query strings
' ALPHA / DIGIT / "-" / "." / "_"
' @param CookieUrlEncoding strict / "!" / "#" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
' "/" / ":" / "<" / "=" / ">" / "?" / "@" / "[" / "]" / "^" / "`" / "{" / "|" / "}"
' @param PathUrlEncoding strict / "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" / ":" / "@"
''
Public Enum UrlEncodingMode
StrictUrlEncoding
FormUrlEncoding
QueryUrlEncoding
CookieUrlEncoding
PathUrlEncoding
End Enum
''
' Enable logging of requests and responses and other internal messages from VBA-Web.
' Should be the first step in debugging VBA-Web if something isn't working as expected.
' (Logs display in Immediate Window (`View > Immediate Window` or `ctrl+g`)
'
' @example
' ```VB.net
' Dim Client As New WebClient
' Client.BaseUrl = "https://api.example.com/v1/"
'
' Dim RequestWithTypo As New WebRequest
' RequestWithTypo.Resource = "peeple/{id}"
' RequestWithType.AddUrlSegment "idd", 123
'
' ' Enable logging before the request is executed
' WebHelpers.EnableLogging = True
'
' Dim Response As WebResponse
' Set Response = Client.Execute(Request)
'
' ' Immediate window:
' ' --> Request - (Time)
' ' GET https://api.example.com/v1/peeple/{id}
' ' Headers...
' '
' ' <-- Response - (Time)
' ' 404 ...
' ```
'
' @property EnableLogging
' @type Boolean
' @default False
''
Public EnableLogging As Boolean
''
' Store currently running async requests
'
' @property AsyncRequests
' @type Dictionary
''
Public AsyncRequests As Dictionary
' ============================================= '
' 1. Logging
' ============================================= '
''
' Log message (when logging is enabled with `EnableLogging`)
' with optional location where the message is coming from.
' Useful when writing extensions to VBA-Web (like an `IWebAuthenticator`).
'
' @example
' ```VB.net
' LogDebug "Executing request..."
' ' -> VBA-Web: Executing request...
'
' LogDebug "Executing request...", "Module.Function"
' ' -> Module.Function: Executing request...
' ```
'
' @method LogDebug
' @param {String} Message
' @param {String} [From="VBA-Web"]
''
Public Sub LogDebug(Message As String, Optional From As String = "VBA-Web")
If EnableLogging Then
Debug.Print From & ": " & Message
End If
End Sub
''
' Log warning (even when logging is disabled with `EnableLogging`)
' with optional location where the message is coming from.
' Useful when writing extensions to VBA-Web (like an `IWebAuthenticator`).
'
' @example
' ```VB.net
' WebHelpers.LogWarning "Something could go wrong"
' ' -> WARNING - VBA-Web: Something could go wrong
'
' WebHelpers.LogWarning "Something could go wrong", "Module.Function"
' ' -> WARNING - Module.Function: Something could go wrong
' ```
'
' @method LogWarning
' @param {String} Message
' @param {String} [From="VBA-Web"]
''
Public Sub LogWarning(Message As String, Optional From As String = "VBA-Web")
Debug.Print "WARNING - " & From & ": " & Message
End Sub
''
' Log error (even when logging is disabled with `EnableLogging`)
' with optional location where the message is coming from and error number.
' Useful when writing extensions to VBA-Web (like an `IWebAuthenticator`).
'
' @example
' ```VB.net
' WebHelpers.LogError "Something went wrong"
' ' -> ERROR - VBA-Web: Something went wrong
'
' WebHelpers.LogError "Something went wrong", "Module.Function"
' ' -> ERROR - Module.Function: Something went wrong
'
' WebHelpers.LogError "Something went wrong", "Module.Function", 100
' ' -> ERROR - Module.Function: 100, Something went wrong
' ```
'
' @method LogError
' @param {String} Message
' @param {String} [From="VBA-Web"]
' @param {Long} [ErrNumber=0]
''
Public Sub LogError(Message As String, Optional From As String = "VBA-Web", Optional ErrNumber As Long = 0)
Dim web_ErrorValue As String
If ErrNumber <> 0 Then
web_ErrorValue = ErrNumber
If ErrNumber < 0 Then
web_ErrorValue = web_ErrorValue & " (" & (ErrNumber - vbObjectError) & " / " & VBA.LCase$(VBA.Hex$(ErrNumber)) & ")"
End If
web_ErrorValue = web_ErrorValue & ", "
End If
Debug.Print "ERROR - " & From & ": " & web_ErrorValue & Message
End Sub
''
' Log details of the request (Url, headers, cookies, body, etc.).
'
' @method LogRequest
' @param {WebClient} Client
' @param {WebRequest} Request
''
Public Sub LogRequest(Client As WebClient, Request As WebRequest)
If EnableLogging Then
Debug.Print "--> Request - " & Format(Now, "Long Time")
Debug.Print MethodToName(Request.Method) & " " & Client.GetFullUrl(Request)
Dim web_KeyValue As Dictionary
For Each web_KeyValue In Request.Headers
Debug.Print web_KeyValue("Key") & ": " & web_KeyValue("Value")
Next web_KeyValue
For Each web_KeyValue In Request.Cookies
Debug.Print "Cookie: " & web_KeyValue("Key") & "=" & web_KeyValue("Value")
Next web_KeyValue
If Not IsEmpty(Request.Body) Then
Debug.Print vbNewLine & CStr(Request.Body)
End If
Debug.Print
End If
End Sub
''
' Log details of the response (Status, headers, content, etc.).
'
' @method LogResponse
' @param {WebClient} Client
' @param {WebRequest} Request
' @param {WebResponse} Response
''
Public Sub LogResponse(Client As WebClient, Request As WebRequest, Response As WebResponse)
If EnableLogging Then
Dim web_KeyValue As Dictionary
Debug.Print "<-- Response - " & Format(Now, "Long Time")
Debug.Print Response.StatusCode & " " & Response.StatusDescription
For Each web_KeyValue In Response.Headers
Debug.Print web_KeyValue("Key") & ": " & web_KeyValue("Value")
Next web_KeyValue
For Each web_KeyValue In Response.Cookies
Debug.Print "Cookie: " & web_KeyValue("Key") & "=" & web_KeyValue("Value")
Next web_KeyValue
Debug.Print vbNewLine & Response.Content & vbNewLine
End If
End Sub
''
' Obfuscate any secure information before logging.
'
' @example
' ```VB.net
' Dim Password As String
' Password = "Secret"
'
' WebHelpers.LogDebug "Password = " & WebHelpers.Obfuscate(Password)
' -> Password = ******
' ```
'
' @param {String} Secure Message to obfuscate
' @param {String} [Character = *] Character to obfuscate with
' @return {String}
''
Public Function Obfuscate(Secure As String, Optional Character As String = "*") As String
Obfuscate = VBA.String$(VBA.Len(Secure), Character)
End Function
' ============================================= '
' 2. Converters and encoding
' ============================================= '
'
' Parse JSON value to `Dictionary` if it's an object or `Collection` if it's an array.
'
' @method ParseJson
' @param {String} Json JSON value to parse
' @return {Dictionary|Collection}
'
' (Implemented in VBA-JSON embedded below)
'
' Convert `Dictionary`, `Collection`, or `Array` to JSON string.
'
' @method ConvertToJson
' @param {Dictionary|Collection|Array} Obj
' @return {String}
'
' (Implemented in VBA-JSON embedded below)
''
' Parse Url-Encoded value to `Dictionary`.
'
' @method ParseUrlEncoded
' @param {String} UrlEncoded Url-Encoded value to parse
' @return {Dictionary} Parsed
''
Public Function ParseUrlEncoded(Encoded As String) As Dictionary
Dim web_Items As Variant
Dim web_i As Integer
Dim web_Parts As Variant
Dim web_Key As String
Dim web_Value As Variant
Dim web_Parsed As New Dictionary
web_Items = VBA.Split(Encoded, "&")
For web_i = LBound(web_Items) To UBound(web_Items)
web_Parts = VBA.Split(web_Items(web_i), "=")
If UBound(web_Parts) - LBound(web_Parts) >= 1 Then
' TODO: Handle numbers, arrays, and object better here
web_Key = UrlDecode(VBA.CStr(web_Parts(LBound(web_Parts))))
web_Value = UrlDecode(VBA.CStr(web_Parts(LBound(web_Parts) + 1)))
web_Parsed(web_Key) = web_Value
End If
Next web_i
Set ParseUrlEncoded = web_Parsed
End Function
''
' Convert `Dictionary`/`Collection` to Url-Encoded string.
'
' @method ConvertToUrlEncoded
' @param {Dictionary|Collection|Variant} Obj Value to convert to Url-Encoded string
' @return {String} UrlEncoded string (e.g. a=123&b=456&...)
''
Public Function ConvertToUrlEncoded(obj As Variant, Optional EncodingMode As UrlEncodingMode = UrlEncodingMode.FormUrlEncoding) As String
Dim web_Encoded As String
If TypeOf obj Is Collection Then
Dim web_KeyValue As Dictionary
For Each web_KeyValue In obj
If VBA.Len(web_Encoded) > 0 Then: web_Encoded = web_Encoded & "&"
web_Encoded = web_Encoded & web_GetUrlEncodedKeyValue(web_KeyValue("Key"), web_KeyValue("Value"), EncodingMode)
Next web_KeyValue
Else
Dim web_Key As Variant
For Each web_Key In obj.keys()
If Len(web_Encoded) > 0 Then: web_Encoded = web_Encoded & "&"
web_Encoded = web_Encoded & web_GetUrlEncodedKeyValue(web_Key, obj(web_Key), EncodingMode)
Next web_Key
End If
ConvertToUrlEncoded = web_Encoded
End Function
''
' Parse XML value to `Dictionary`.
'
' _Note_ Currently, XML is not supported in 4.0.0 due to lack of Mac support.
' An updated parser is being created that supports Mac and Windows,
' but in order to avoid future breaking changes, ParseXml and ConvertToXml are not currently implemented.
'
' See https://github.com/VBA-tools/VBA-Web/wiki/XML-Support-in-4.0 for details on how to use XML in Windows in the meantime.
'
' @param {String} Encoded XML value to parse
' @return {Dictionary|Object} Parsed
' @throws 11099 - XML format is not currently supported
''
Public Function ParseXml(Encoded As String) As Object
Dim web_ErrorMsg As String
web_ErrorMsg = "XML is not currently supported (An updated parser is being created that supports Mac and Windows)." & vbNewLine & _
"To use XML parsing for Windows currently, use the instructions found here:" & vbNewLine & _
vbNewLine & _
"https://github.com/VBA-tools/VBA-Web/wiki/XML-Support-in-4.0"
LogError web_ErrorMsg, "WebHelpers.ParseXml", 11099
Err.Raise 11099, "WebHeleprs.ParseXml", web_ErrorMsg
End Function
''
' Convert `Dictionary` to XML string.
'
' _Note_ Currently, XML is not supported in 4.0.0 due to lack of Mac support.
' An updated parser is being created that supports Mac and Windows,
' but in order to avoid future breaking changes, ParseXml and ConvertToXml are not currently implemented.
'
' See https://github.com/VBA-tools/VBA-Web/wiki/XML-Support-in-4.0 for details on how to use XML in Windows in the meantime.
'
' @param {Dictionary|Variant} XML
' @return {String} XML string
' @throws 11099 / 80042b5b / -2147210405 - XML format is not currently supported
''
Public Function ConvertToXml(obj As Variant) As String
Dim web_ErrorMsg As String
web_ErrorMsg = "XML is not currently supported (An updated parser is being created that supports Mac and Windows)." & vbNewLine & _
"To use XML parsing for Windows currently, use the instructions found here:" & vbNewLine & _
vbNewLine & _
"https://github.com/VBA-tools/VBA-Web/wiki/XML-Support-in-4.0"
LogError web_ErrorMsg, "WebHelpers.ParseXml", 11099 + vbObjectError
Err.Raise 11099 + vbObjectError, "WebHeleprs.ParseXml", web_ErrorMsg
End Function
''
' Helper for parsing value to given `WebFormat` or custom format.
' Returns `Dictionary` or `Collection` based on given `Value`.
'
' @method ParseByFormat
' @param {String} Value Value to parse
' @param {WebFormat} Format
' @param {String} [CustomFormat=""] Name of registered custom converter
' @param {Variant} [Bytes] Bytes for custom convert (if `ParseType = "Binary"`)
' @return {Dictionary|Collection|Object}
' @throws 11000 - Error during parsing
''
Public Function ParseByFormat(Value As String, Format As WebFormat, _
Optional CustomFormat As String = "", Optional Bytes As Variant) As Object
On Error GoTo web_ErrorHandling
' Don't attempt to parse blank values
If Value = "" And CustomFormat = "" Then
Exit Function
End If
Select Case Format
Case WebFormat.JSON
Set ParseByFormat = ParseJson(Value)
Case WebFormat.FormUrlEncoded
Set ParseByFormat = ParseUrlEncoded(Value)
Case WebFormat.XML
Set ParseByFormat = ParseXml(Value)
End Select
Exit Function
web_ErrorHandling:
Dim web_ErrorDescription As String
web_ErrorDescription = "An error occurred during parsing" & vbNewLine & _
Err.Number & VBA.IIf(Err.Number < 0, " (" & VBA.LCase$(VBA.Hex$(Err.Number)) & ")", "") & ": " & Err.Description
LogError web_ErrorDescription, "WebHelpers.ParseByFormat", 11000
Err.Raise 11000, "WebHelpers.ParseByFormat", web_ErrorDescription
End Function
''
' Helper for converting value to given `WebFormat` or custom format.
'
' _Note_ Only some converters handle `Collection` or `Array`.
'
' @method ConvertToFormat
' @param {Dictionary|Collection|Variant} Obj
' @param {WebFormat} Format
' @param {String} [CustomFormat] Name of registered custom converter
' @return {Variant}
' @throws 11001 - Error during conversion
''
Public Function ConvertToFormat(obj As Variant, Format As WebFormat, Optional CustomFormat As String = "") As Variant
On Error GoTo web_ErrorHandling
Select Case Format
Case WebFormat.JSON
ConvertToFormat = ConvertToJson(obj)
Case WebFormat.FormUrlEncoded
ConvertToFormat = ConvertToUrlEncoded(obj)
Case WebFormat.XML
ConvertToFormat = ConvertToXml(obj)
Case Else
If VBA.VarType(obj) = vbString Then
' Plain text
ConvertToFormat = obj
End If
End Select
Exit Function
web_ErrorHandling:
Dim web_ErrorDescription As String
web_ErrorDescription = "An error occurred during conversion" & vbNewLine & _
Err.Number & VBA.IIf(Err.Number < 0, " (" & VBA.LCase$(VBA.Hex$(Err.Number)) & ")", "") & ": " & Err.Description
LogError web_ErrorDescription, "WebHelpers.ConvertToFormat", 11001
Err.Raise 11001, "WebHelpers.ConvertToFormat", web_ErrorDescription
End Function
''
' Encode string for URLs
'
' See https://github.com/VBA-tools/VBA-Web/wiki/Url-Encoding for details
'
' References:
' - RFC 3986, https://tools.ietf.org/html/rfc3986
' - form-urlencoded encoding algorithm,
' https://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
' - RFC 6265 (Cookies), https://tools.ietf.org/html/rfc6265
' Note: "%" is allowed in spec, but is currently excluded due to parsing issues
'
' @method UrlEncode
' @param {Variant} Text Text to encode
' @param {Boolean} [SpaceAsPlus = False] `%20` if `False` / `+` if `True`
' DEPRECATED Use EncodingMode:=FormUrlEncoding
' @param {Boolean} [EncodeUnsafe = True] Encode characters that could be misunderstood within URLs.
' (``SPACE, ", <, >, #, %, {, }, |, \, ^, ~, `, [, ]``)
' DEPRECATED This was based on an outdated URI spec and has since been removed.
' EncodingMode:=CookieUrlEncoding is the closest approximation of this behavior
' @param {UrlEncodingMode} [EncodingMode = StrictUrlEncoding]
' @return {String} Encoded string
''
Public Function UrlEncode(Text As Variant, _
Optional SpaceAsPlus As Boolean = False, Optional EncodeUnsafe As Boolean = True, _
Optional EncodingMode As UrlEncodingMode = UrlEncodingMode.StrictUrlEncoding) As String
If SpaceAsPlus = True Then
LogWarning "SpaceAsPlus is deprecated and will be removed in VBA-Web v5. " & _
"Use EncodingMode:=FormUrlEncoding instead", "WebHelpers.UrlEncode"
End If
If EncodeUnsafe = False Then
LogWarning "EncodeUnsafe has been removed as it was based on an outdated url encoding specification. " & _
"Use EncodingMode:=CookieUrlEncoding to approximate this behavior", "WebHelpers.UrlEncode"
End If
Dim web_UrlVal As String
Dim web_StringLen As Long
web_UrlVal = VBA.CStr(Text)
web_StringLen = VBA.Len(web_UrlVal)
If web_StringLen > 0 Then
Dim web_Result() As String
Dim web_i As Long
Dim web_CharCode As Integer
Dim web_Char As String
Dim web_Space As String
ReDim web_Result(web_StringLen)
' StrictUrlEncoding - ALPHA / DIGIT / "-" / "." / "_" / "~"
' FormUrlEncoding - ALPHA / DIGIT / "-" / "." / "_" / "*" / (space) -> "+"
' QueryUrlEncoding - ALPHA / DIGIT / "-" / "." / "_"
' CookieUrlEncoding - strict / "!" / "#" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
' "/" / ":" / "<" / "=" / ">" / "?" / "@" / "[" / "]" / "^" / "`" / "{" / "|" / "}"
' PathUrlEncoding - strict / "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" / ":" / "@"
' Set space value
If SpaceAsPlus Or EncodingMode = UrlEncodingMode.FormUrlEncoding Then
web_Space = "+"
Else
web_Space = "%20"
End If
' Loop through string characters
For web_i = 1 To web_StringLen
' Get character and ascii code
web_Char = VBA.Mid$(web_UrlVal, web_i, 1)
web_CharCode = VBA.asc(web_Char)
Select Case web_CharCode
Case 65 To 90, 97 To 122
' ALPHA
web_Result(web_i) = web_Char
Case 48 To 57
' DIGIT
web_Result(web_i) = web_Char
Case 45, 46, 95
' "-" / "." / "_"
web_Result(web_i) = web_Char
Case 32
' (space)
' FormUrlEncoding -> "+"
' Else -> "%20"
web_Result(web_i) = web_Space
Case 33, 36, 38, 39, 40, 41, 43, 58, 61, 64
' "!" / "$" / "&" / "'" / "(" / ")" / "+" / ":" / "=" / "@"
' PathUrlEncoding, CookieUrlEncoding -> Unencoded
' Else -> Percent-encoded
If EncodingMode = UrlEncodingMode.PathUrlEncoding Or EncodingMode = UrlEncodingMode.CookieUrlEncoding Then
web_Result(web_i) = web_Char
Else
web_Result(web_i) = "%" & VBA.Hex(web_CharCode)
End If
Case 35, 45, 46, 47, 60, 62, 63, 91, 93, 94, 95, 96, 123, 124, 125
' "#" / "-" / "." / "/" / "<" / ">" / "?" / "[" / "]" / "^" / "_" / "`" / "{" / "|" / "}"
' CookieUrlEncoding -> Unencoded
' Else -> Percent-encoded
If EncodingMode = UrlEncodingMode.CookieUrlEncoding Then
web_Result(web_i) = web_Char
Else
web_Result(web_i) = "%" & VBA.Hex(web_CharCode)
End If
Case 42
' "*"
' FormUrlEncoding, PathUrlEncoding, CookieUrlEncoding -> "*"
' Else -> "%2A"
If EncodingMode = UrlEncodingMode.FormUrlEncoding _
Or EncodingMode = UrlEncodingMode.PathUrlEncoding _
Or EncodingMode = UrlEncodingMode.CookieUrlEncoding Then
web_Result(web_i) = web_Char
Else
web_Result(web_i) = "%" & VBA.Hex(web_CharCode)
End If
Case 44, 59
' "," / ";"
' PathUrlEncoding -> Unencoded
' Else -> Percent-encoded
If EncodingMode = UrlEncodingMode.PathUrlEncoding Then
web_Result(web_i) = web_Char
Else
web_Result(web_i) = "%" & VBA.Hex(web_CharCode)
End If
Case 126
' "~"
' FormUrlEncoding, QueryUrlEncoding -> "%7E"
' Else -> "~"
If EncodingMode = UrlEncodingMode.FormUrlEncoding Or EncodingMode = UrlEncodingMode.QueryUrlEncoding Then
web_Result(web_i) = "%7E"
Else
web_Result(web_i) = web_Char
End If
Case 0 To 15
web_Result(web_i) = "%0" & VBA.Hex(web_CharCode)
Case Else
web_Result(web_i) = "%" & VBA.Hex(web_CharCode)
' TODO For non-ASCII characters,
'
' FormUrlEncoded:
'
' Replace the character by a string consisting of a U+0026 AMPERSAND character (&), a "#" (U+0023) character,
' one or more ASCII digits representing the Unicode code point of the character in base ten, and finally a ";" (U+003B) character.
'
' Else:
'
' Encode to sequence of 2 or 3 bytes in UTF-8, then percent encode
' Reference Implementation: https://www.w3.org/International/URLUTF8Encoder.java
End Select
Next web_i
UrlEncode = VBA.Join$(web_Result, "")
End If
End Function
''
' Decode Url-encoded string.
'
' @method UrlDecode
' @param {String} Encoded Text to decode
' @param {Boolean} [PlusAsSpace = True] Decode plus as space
' DEPRECATED Use EncodingMode:=FormUrlEncoding Or QueryUrlEncoding
' @param {UrlEncodingMode} [EncodingMode = StrictUrlEncoding]
' @return {String} Decoded string
''
Public Function UrlDecode(Encoded As String, _
Optional PlusAsSpace As Boolean = True, _
Optional EncodingMode As UrlEncodingMode = UrlEncodingMode.StrictUrlEncoding) As String
Dim web_StringLen As Long
web_StringLen = VBA.Len(Encoded)
If web_StringLen > 0 Then
Dim web_i As Long
Dim web_Result As String
Dim web_Temp As String
For web_i = 1 To web_StringLen
web_Temp = VBA.Mid$(Encoded, web_i, 1)
If web_Temp = "+" And _
(PlusAsSpace _
Or EncodingMode = UrlEncodingMode.FormUrlEncoding _
Or EncodingMode = UrlEncodingMode.QueryUrlEncoding) Then
web_Temp = " "
ElseIf web_Temp = "%" And web_StringLen >= web_i + 2 Then