Advertisement
sashaatx

Untitled

Jul 22nd, 2023
1,896
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ;credit: https://github.com/TheArkive/JXON_ahk2
  2. ;credit: https://github.com/thqby/ahk2_lib
  3.  
  4. /*
  5.     @source https://github.com/samfisherirl/Github.ahk-API-for-AHKv2
  6.     @method Github.latest(Username,Repository_Name)
  7.  
  8.     return {
  9.         downloadURLs: [
  10.             "http://github.com/release.zip",
  11.             "http://github.com/release.rar"
  12.                     ],
  13.         version: "",
  14.         change_notes: "",
  15.         date: "",
  16.         }
  17.        
  18.     @method Github.historicReleases(Username,Repository_Name)
  19.         array of objects => [{
  20.             downloadURL: "",
  21.             version: "",
  22.             change_notes: "",
  23.             date: ""
  24.         }]
  25.     @func this.Download(url,path)
  26.         improves on download():
  27.         - if user provides wrong extension, function will apply proper extension
  28.         - allows user to provide directory
  29.         example:    Providing A_ScriptDir to Download will throw error
  30.                     Providing A_ScriptDir to Github.Download() will supply Download() with release name
  31. */
  32. class Github
  33. {
  34.     static source_zip := ""
  35.     static url := false
  36.     static usernamePlusRepo := false
  37.     static storage := {
  38.         repo: "",
  39.         source_zip: ""
  40.     }
  41.     static data := false
  42.  
  43.     static build(Username, Repository_Name) {
  44.         Github.usernamePlusRepo := Trim(Username) "/" Trim(Repository_Name)
  45.         Github.source_zip := "https://github.com/" Github.usernamePlusRepo "/archive/refs/heads/main.zip"
  46.         return "https://api.github.com/repos/" Github.usernamePlusRepo "/releases"
  47.         ;filedelete, "1.json"
  48.         ;this.Filetype := data["assets"][1]["browser_download_url"]
  49.     }
  50.     /*
  51.     return {
  52.         downloadURLs: [
  53.             "http://github.com/release.zip",
  54.             "http://github.com/release.rar"
  55.                     ],
  56.         version: "",
  57.         change_notes: "",
  58.         date: "",
  59.         }
  60.     */
  61.     static latest(Username, Repository_Name) {
  62.         url := Github.build(Username, Repository_Name)
  63.         data := Github.processRepo(url)
  64.         return Github.latestProp(data)
  65.     }
  66.     /*
  67.     static processRepo(url) {
  68.         Github.source_zip := "https://github.com/" Github.usernamePlusRepo "/archive/refs/heads/main.zip"
  69.         Github.data := Github.jsonDownload(url)
  70.         data := Github.data
  71.         return Jsons.Loads(&data)
  72.     }
  73.     */
  74.     static processRepo(url) {
  75.         Github.source_zip := "https://github.com/" Github.usernamePlusRepo "/archive/refs/heads/main.zip"
  76.         data := Github.jsonDownload(url)
  77.         return Jsons.Loads(&data)
  78.     }
  79.     /*
  80.     @example
  81.     repoArray := Github.historicReleases()
  82.         repoArray[1].downloadURL => string | link
  83.         repoArray[1].version => string | version data
  84.         repoArray[1].change_notes => string | change notes
  85.         repoArray[1].date => string | date of release
  86.    
  87.     @returns (array of release objects) => [{
  88.         downloadURL: "",
  89.         version: "",
  90.         change_notes: "",
  91.         date: ""
  92.         }]
  93.     */
  94.     static historicReleases(Username, Repository_Name) {
  95.         url := Github.build(Username, Repository_Name)
  96.         data := Github.processRepo(url)
  97.         repo_storage := []
  98.         url := "https://api.github.com/repos/" Github.usernamePlusRepo "/releases"
  99.         data := Github.jsonDownload(url)
  100.         data := Jsons.Loads(&data)
  101.         for release in data {
  102.             for asset in release["assets"] {
  103.                 repo_storage.Push(Github.repoDistribution(release, asset))
  104.             }
  105.         }
  106.         return repo_storage
  107.     }
  108.     static latestProp(data) {
  109.         for i in data {
  110.             baseData := i
  111.             assetMap := i["assets"]
  112.             date := i["created_at"]
  113.             if i["assets"].Length > 0 {
  114.                 length := i["assets"].Length
  115.                 releaseArray := Github.distributeReleaseArray(length, assetMap)
  116.                 break
  117.             }
  118.             else {
  119.                 releaseArray := ["https://github.com/" Github.usernamePlusRepo "/archive/" i["tag_name"] ".zip"]
  120.                 ;source url = f"https://github.com/{repo_owner}/{repo_name}/archive/{release_tag}.zip"
  121.                 break
  122.             }
  123.         }
  124.         ;move release array to first if
  125.         ;then add source
  126.         return {
  127.             downloadURLs: releaseArray,
  128.             version: baseData["tag_name"],
  129.             change_notes: baseData["body"],
  130.             date: date
  131.         }
  132.     }
  133.     /*
  134.     loop releaseURLCount {
  135.         assetArray.Push(JsonData[A_Index]["browser_download_url"])
  136.     }
  137.     return => assetArray[]
  138.     */
  139.     /*
  140.     loop releaseURLCount {
  141.         assetMap.Set(jsonData[A_Index]["name"], jsonData[A_Index]["browser_download_url"])
  142.     }
  143.     return => assetMap()
  144.     */
  145.     static jsonDownload(URL) {
  146.         Http := WinHttpRequest()
  147.         Http.Open("GET", URL)
  148.         Http.Send()
  149.         Http.WaitForResponse()
  150.         storage := Http.ResponseText
  151.         return storage ;Set the "text" variable to the response
  152.     }
  153.     static distributeReleaseArray(releaseURLCount, Jdata) {
  154.         assetArray := []
  155.         if releaseURLCount {
  156.             if (releaseURLCount > 1) {
  157.                 loop releaseURLCount {
  158.                     assetArray.Push(Jdata[A_Index]["browser_download_url"])
  159.                 }
  160.             }
  161.             else {
  162.                 assetArray.Push(Jdata[1]["browser_download_url"])
  163.             }
  164.             return assetArray
  165.         }
  166.     }
  167.     /*
  168.     download the latest main.zip source zip
  169.     */
  170.     static Source(Username, Repository_Name, Pathlocal := A_ScriptDir) {
  171.         url := Github.build(Username, Repository_Name)
  172.         data := Github.processRepo(url)
  173.  
  174.         Github.Download(URL := Github.source_zip, PathLocal)
  175.     }
  176.     /*
  177.     benefit over download() => handles users path, and applies appropriate extension.
  178.     IE: If user provides (Path:=A_ScriptDir "\download.zip") but extension is .7z, extension is modified for the user.
  179.     If user provides directory, name for file is applied from the path (download() will not).
  180.     Download (
  181.         @param URL to download
  182.         @param Path where to save locally
  183.     )
  184.     */
  185.     static Download(URL, PathLocal := A_ScriptDir) {
  186.         releaseExtension := Github.downloadExtensionSplit(URL)
  187.         pathWithExtension := Github.handleUserPath(PathLocal, releaseExtension)
  188.         try {
  189.             Download(URL, pathWithExtension)
  190.         } catch as e {
  191.             MsgBox(e.Message . "`nURL:`n" URL)
  192.         }
  193.     }
  194.     static emptyRepoMap() {
  195.         repo := {
  196.             downloadURL: "",
  197.             version: "",
  198.             change_notes: "",
  199.             date: "",
  200.             name: ""
  201.         }
  202.         return repo
  203.     }
  204.  
  205.     static repoDistribution(release, asset) {
  206.         return {
  207.             downloadURL: asset["browser_download_url"],
  208.             version: release["tag_name"],
  209.             change_notes: release["body"],
  210.             date: asset["created_at"],
  211.             name: asset["name"]
  212.         }
  213.     }
  214.     static downloadExtensionSplit(DL) {
  215.         Arrays := StrSplit(DL, ".")
  216.         filetype := Trim(Arrays[Arrays.Length])
  217.         return filetype
  218.     }
  219.  
  220.     static handleUserPath(PathLocal, releaseExtension) {
  221.         if InStr(PathLocal, "\") {
  222.             pathParts := StrSplit(PathLocal, "\")
  223.             FileName := pathParts[pathParts.Length]
  224.         }
  225.         else {
  226.             FileName := PathLocal
  227.             PathLocal := A_ScriptDir "\" FileName
  228.             pathParts := StrSplit(PathLocal, "\")
  229.         }
  230.         if InStr(FileName, ".") {
  231.             FileNameParts := StrSplit(FileName, ".")
  232.             UserExtension := FileNameParts[FileNameParts.Length]
  233.             if (releaseExtension != userExtension) {
  234.                 newName := ""
  235.                 for key, val in FileNameParts {
  236.                     if (A_Index == FileNameParts.Length) {
  237.                         break
  238.                     }
  239.                     newName .= val
  240.                 }
  241.                 newPath := ""
  242.                 for key, val in pathParts {
  243.                     if (A_Index == pathParts.Length) {
  244.                         break
  245.                     }
  246.                     newPath .= val
  247.                 }
  248.                 pathWithExtension := newPath newName "." releaseExtension
  249.             }
  250.             else {
  251.                 pathWithExtension := PathLocal
  252.             }
  253.         }
  254.         else {
  255.             pathWithExtension := PathLocal "." releaseExtension
  256.         }
  257.         return pathWithExtension
  258.     }
  259. }
  260. ;;;; AHK v2 - https://github.com/TheArkive/JXON_ahk2
  261. ;MIT License
  262. ;Copyright (c) 2021 TheArkive
  263. ;Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  264. ;The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  265. ;THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  266. ;
  267. ; originally posted by user coco on AutoHotkey.com
  268. ; https://github.com/cocobelgica/AutoHotkey-JSON
  269. class Jsons
  270. {
  271.     static Loads(&src, args*) {
  272.         key := "", is_key := false
  273.         stack := [tree := []]
  274.         next := '"{[01234567890-tfn'
  275.        pos := 0
  276.  
  277.        while ((ch := SubStr(src, ++pos, 1)) != "") {
  278.            if InStr(" `t`n`r", ch)
  279.                continue
  280.            if !InStr(next, ch, true) {
  281.                testArr := StrSplit(SubStr(src, 1, pos), "`n")
  282.  
  283.                ln := testArr.Length
  284.                col := pos - InStr(src, "`n", , -(StrLen(src) - pos + 1))
  285.  
  286.                msg := Format("{}: line {} col {} (char {})"
  287.                    , (next == "") ? ["Extra data", ch := SubStr(src, pos)][1]
  288.                    : (next == "'") ? "Unterminated string starting at"
  289.                        : (next == "\") ? "Invalid \escape"
  290.                            : (next == ":") ? "Expecting ':' delimiter"
  291.                                : (next == '"') ? "Expecting object key enclosed in double quotes"
  292.                                     : (next == '"}') ? "Expecting object key enclosed in double quotes or object closing '}'"
  293.                                        : (next == ",}") ? "Expecting ',' delimiter or object closing '}'"
  294.                                            : (next == ",]") ? "Expecting ',' delimiter or array closing ']'"
  295.                                                : ["Expecting JSON value(string, number, [true, false, null], object or array)"
  296.                                                , ch := SubStr(src, pos, (SubStr(src, pos) ~= "[\]\},\s]|$") - 1)][1]
  297.                                                , ln, col, pos)
  298.  
  299.                throw Error(msg, -1, ch)
  300.            }
  301.  
  302.            obj := stack[1]
  303.            is_array := (obj is Array)
  304.  
  305.            if i := InStr("{[", ch) { ; start new object / map?
  306.                val := (i = 1) ? Map() : Array()    ; ahk v2
  307.  
  308.                is_array ? obj.Push(val) : obj[key] := val
  309.                stack.InsertAt(1, val)
  310.  
  311.                next := '"' ((is_key := (ch == "{")) ? "}" : "{[]0123456789-tfn")
  312.             } else if InStr("}]", ch) {
  313.                 stack.RemoveAt(1)
  314.                 next := (stack[1] == tree) ? "" : (stack[1] is Array) ? ",]" : ",}"
  315.             } else if InStr(",:", ch) {
  316.                 is_key := (!is_array && ch == ",")
  317.                 next := is_key ? '"' : '"{[0123456789-tfn'
  318.             } else { ; string | number | true | false | null
  319.                 if (ch == '"') { ; string
  320.                    i := pos
  321.                    while i := InStr(src, '"', , i + 1) {
  322.                         val := StrReplace(SubStr(src, pos + 1, i - pos - 1), "\\", "\u005C")
  323.                         if (SubStr(val, -1) != "\")
  324.                             break
  325.                     }
  326.                     if !i ? (pos--, next := "'") : 0
  327.                         continue
  328.  
  329.                     pos := i ; update pos
  330.  
  331.                     val := StrReplace(val, "\/", "/")
  332.                     val := StrReplace(val, '\"', '"')
  333.                         , val := StrReplace(val, "\b", "`b")
  334.                         , val := StrReplace(val, "\f", "`f")
  335.                         , val := StrReplace(val, "\n", "`n")
  336.                         , val := StrReplace(val, "\r", "`r")
  337.                         , val := StrReplace(val, "\t", "`t")
  338.  
  339.                     i := 0
  340.                     while i := InStr(val, "\", , i + 1) {
  341.                         if (SubStr(val, i + 1, 1) != "u") ? (pos -= StrLen(SubStr(val, i)), next := "\") : 0
  342.                             continue 2
  343.  
  344.                         xxxx := Abs("0x" . SubStr(val, i + 2, 4)) ; \uXXXX - JSON unicode escape sequence
  345.                         if (xxxx < 0x100)
  346.                             val := SubStr(val, 1, i - 1) . Chr(xxxx) . SubStr(val, i + 6)
  347.                     }
  348.  
  349.                     if is_key {
  350.                         key := val, next := ":"
  351.                         continue
  352.                     }
  353.                 } else { ; number | true | false | null
  354.                     val := SubStr(src, pos, i := RegExMatch(src, "[\]\},\s]|$", , pos) - pos)
  355.  
  356.                     if IsInteger(val)
  357.                         val += 0
  358.                     else if IsFloat(val)
  359.                         val += 0
  360.                     else if (val == "true" || val == "false")
  361.                         val := (val == "true")
  362.                     else if (val == "null")
  363.                         val := ""
  364.                     else if is_key {
  365.                         pos--, next := "#"
  366.                         continue
  367.                     }
  368.  
  369.                     pos += i - 1
  370.                 }
  371.  
  372.                 is_array ? obj.Push(val) : obj[key] := val
  373.                 next := obj == tree ? "" : is_array ? ",]" : ",}"
  374.             }
  375.         }
  376.         return tree[1]
  377.     }
  378.     static Dump(obj, indent := "", lvl := 1) {
  379.         if IsObject(obj) {
  380.             ;if !obj.__Class = "Map" {
  381.             ;    convertedObject := Map()
  382.             ;    for k, v in obj.OwnProps() {
  383.             ;        convertedObject.Set(k, v)
  384.             ;    }
  385.             ;    obj := convertedObject
  386.             ;}
  387.             ;If !(obj is Array || obj is Map || obj is String || obj is Number)
  388.             ;    throw Error("Object type not supported.", -1, Format("<Object at 0x{:p}>", ObjPtr(obj)))
  389.  
  390.             if IsInteger(indent)
  391.             {
  392.                 if (indent < 0)
  393.                     throw Error("Indent parameter must be a postive integer.", -1, indent)
  394.                 spaces := indent, indent := ""
  395.  
  396.                 Loop spaces ; ===> changed
  397.                     indent .= " "
  398.             }
  399.             indt := ""
  400.  
  401.             Loop indent ? lvl : 0
  402.                 indt .= indent
  403.  
  404.             is_array := (obj is Array)
  405.  
  406.             lvl += 1, out := "" ; Make #Warn happy
  407.             if (obj is Map || obj is Array) {
  408.                 for k, v in obj {
  409.                     if IsObject(k) || (k == "")
  410.                         throw Error("Invalid object key.", -1, k ? Format("<Object at 0x{:p}>", ObjPtr(obj)) : "<blank>")
  411.  
  412.                     if !is_array ;// key ; ObjGetCapacity([k], 1)
  413.                         out .= (ObjGetCapacity([k]) ? Jsons.Dump(k) : escape_str(k)) (indent ? ": " : ":") ; token + padding
  414.  
  415.                     out .= Jsons.Dump(v, indent, lvl) ; value
  416.                         . (indent ? ",`n" . indt : ",") ; token + indent
  417.                 }
  418.             } else if IsObject(obj)
  419.                 for k, v in obj.OwnProps() {
  420.                     if IsObject(k) || (k == "")
  421.                         throw Error("Invalid object key.", -1, k ? Format("<Object at 0x{:p}>", ObjPtr(obj)) : "<blank>")
  422.                     out .= (ObjGetCapacity([k]) ? Jsons.Dump(k) : escape_str(k)) (indent ? ": " : ":") ; token + padding
  423.                     out .= Jsons.Dump(v, indent, lvl) ; value
  424.                         . (indent ? ",`n" . indt : ",") ; token + indent
  425.                 }
  426.  
  427.             ;Error("Object type not supported.", -1, Format("<Object at 0x{:p}>", ObjPtr(obj)))
  428.  
  429.             if (out != "") {
  430.                 out := Trim(out, ",`n" . indent)
  431.                 if (indent != "")
  432.                     out := "`n" . indt . out . "`n" . SubStr(indt, StrLen(indent) + 1)
  433.             }
  434.  
  435.             return is_array ? "[" . out . "]" : "{" . out . "}"
  436.  
  437.         } Else If (obj is Number)
  438.             return obj
  439.         Else ; String
  440.             return escape_str(obj)
  441.  
  442.         escape_str(obj) {
  443.             obj := StrReplace(obj, "\", "\\")
  444.             obj := StrReplace(obj, "`t", "\t")
  445.             obj := StrReplace(obj, "`r", "\r")
  446.             obj := StrReplace(obj, "`n", "\n")
  447.             obj := StrReplace(obj, "`b", "\b")
  448.             obj := StrReplace(obj, "`f", "\f")
  449.             obj := StrReplace(obj, "/", "\/")
  450.             obj := StrReplace(obj, '"', '\"')
  451.  
  452.             return '"' obj '"'
  453.         }
  454.     }
  455. }
  456. /************************************************************************
  457.  * @file: WinHttpRequest.ahk
  458.  * @description: 网络请求库
  459.  * @author thqby
  460.  * @date 2021/08/01
  461.  * @version 0.0.18
  462.  ***********************************************************************/
  463.  
  464. class WinHttpRequest {
  465.     static AutoLogonPolicy := { Always: 0, OnlyIfBypassProxy: 1, Never: 2 }
  466.     static Option := { UserAgentString: 0, URL: 1, URLCodePage: 2, EscapePercentInURL: 3, SslErrorIgnoreFlags: 4, SelectCertificate: 5, EnableRedirects: 6, UrlEscapeDisable: 7, UrlEscapeDisableQuery: 8, SecureProtocols: 9, EnableTracing: 10, RevertImpersonationOverSsl: 11, EnableHttpsToHttpRedirects: 12, EnablePassportAuthentication: 13, MaxAutomaticRedirects: 14, MaxResponseHeaderSize: 15, MaxResponseDrainSize: 16, EnableHttp1_1: 17, EnableCertificateRevocationCheck: 18, RejectUserpwd: 19
  467.     }
  468.     static PROXYSETTING := { PRECONFIG: 0, DIRECT: 1, PROXY: 2
  469.     }
  470.     static SETCREDENTIALSFLAG := { SERVER: 0, PROXY: 1
  471.     }
  472.     static SecureProtocol := { SSL2: 0x08, SSL3: 0x20, TLS1: 0x80, TLS1_1: 0x200, TLS1_2: 0x800, All: 0xA8
  473.     }
  474.     static SslErrorFlag := { UnknownCA: 0x0100, CertWrongUsage: 0x0200, CertCNInvalid: 0x1000, CertDateInvalid: 0x2000, Ignore_All: 0x3300
  475.     }
  476.  
  477.     __New(UserAgent := unset) {
  478.         this.whr := whr := ComObject('WinHttp.WinHttpRequest.5.1')
  479.         whr.Option[0] := IsSet(UserAgent) ? UserAgent : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.68'
  480.         this.IEvents := WinHttpRequest.RequestEvents.Call(ComObjValue(whr), this.id := ObjPtr(this))
  481.     }
  482.     __Delete() => (this.whr := this.IEvents := this.OnError := this.OnResponseDataAvailable := this.OnResponseFinished := this.OnResponseStart := 0)
  483.  
  484.     request(url, method := 'GET', data := '', headers := '') {
  485.         this.Open(method, url)
  486.         for k, v in (headers || {}).OwnProps()
  487.             this.SetRequestHeader(k, v)
  488.         this.Send(data)
  489.         return this.ResponseText
  490.     }
  491.  
  492.     ;#region IWinHttpRequest
  493.     SetProxy(ProxySetting, ProxyServer, BypassList) => this.whr.SetProxy(ProxySetting, ProxyServer, BypassList)
  494.     SetCredentials(UserName, Password, Flags) => this.whr.SetCredentials(UserName, Password, Flags)
  495.     SetRequestHeader(Header, Value) => this.whr.SetRequestHeader(Header, Value)
  496.     GetResponseHeader(Header) => this.whr.GetResponseHeader(Header)
  497.     GetAllResponseHeaders() => this.whr.GetAllResponseHeaders()
  498.     Send(Body := '') => this.whr.Send(Body)
  499.     Open(verb, url, async := false) {
  500.         this.readyState := 0
  501.         this.whr.Open(verb, url, this.async := !!async)
  502.         this.readyState := 1
  503.     }
  504.     WaitForResponse(Timeout := -1) => this.whr.WaitForResponse(Timeout)
  505.     Abort() => this.whr.Abort()
  506.     SetTimeouts(ResolveTimeout := 0, ConnectTimeout := 60000, SendTimeout := 30000, ReceiveTimeout := 30000) => this.whr.SetTimeouts(ResolveTimeout, ConnectTimeout, SendTimeout, ReceiveTimeout)
  507.     SetClientCertificate(ClientCertificate) => this.whr.SetClientCertificate(ClientCertificate)
  508.     SetAutoLogonPolicy(AutoLogonPolicy) => this.whr.SetAutoLogonPolicy(AutoLogonPolicy)
  509.     whr := 0, readyState := 0, IEvents := 0, id := 0, async := 0
  510.     OnResponseStart := 0, OnResponseFinished := 0
  511.     OnResponseDataAvailable := 0, OnError := 0
  512.     Status => this.whr.Status
  513.     StatusText => this.whr.StatusText
  514.     ResponseText => this.whr.ResponseText
  515.     ResponseBody {
  516.         get {
  517.             pSafeArray := ComObjValue(t := this.whr.ResponseBody)
  518.             pvData := NumGet(pSafeArray + 8 + A_PtrSize, 'ptr')
  519.             cbElements := NumGet(pSafeArray + 8 + A_PtrSize * 2, 'uint')
  520.             return ClipboardAll(pvData, cbElements)
  521.         }
  522.     }
  523.     ResponseStream => this.whr.responseStream
  524.     Option[Opt] {
  525.         get => this.whr.Option[Opt]
  526.         set => (this.whr.Option[Opt] := Value)
  527.     }
  528.     Headers {
  529.         get {
  530.             m := Map(), m.Default := ''
  531.             loop parse this.GetAllResponseHeaders(), '`r`n'
  532.                 if (p := InStr(A_LoopField, ':'))
  533.                     m[SubStr(A_LoopField, 1, p - 1)] .= LTrim(SubStr(A_LoopField, p + 1))
  534.             return m
  535.         }
  536.     }
  537.     ;#endregion
  538.     ;#region IWinHttpRequestEvents
  539.     class RequestEvents {
  540.         dwCookie := 0, pCPC := 0, UnkSink := 0
  541.         __New(pwhr, pparent) {
  542.             IConnectionPointContainer := ComObjQuery(pwhr, IID_IConnectionPointContainer := '{B196B284-BAB4-101A-B69C-00AA00341D07}')
  543.             DllCall("ole32\CLSIDFromString", "Str", IID_IWinHttpRequestEvents := '{F97F4E15-B787-4212-80D1-D380CBBF982E}', "Ptr", pCLSID := Buffer(16))
  544.             ComCall(4, IConnectionPointContainer, 'ptr', pCLSID, 'ptr*', &pCPC := 0)    ; IConnectionPointContainer->FindConnectionPoint
  545.             IWinHttpRequestEvents := Buffer(11 * A_PtrSize), offset := IWinHttpRequestEvents.Ptr + 4 * A_PtrSize
  546.             NumPut('ptr', offset, 'ptr', pwhr, 'ptr', pCPC, IWinHttpRequestEvents)
  547.             for nParam in StrSplit('3113213')
  548.                 offset := NumPut('ptr', CallbackCreate(EventHandler.Bind(A_Index), , Integer(nParam)), offset)
  549.             ComCall(5, pCPC, 'ptr', IWinHttpRequestEvents, 'uint*', &dwCookie := 0) ; IConnectionPoint->Advise
  550.             NumPut('ptr', dwCookie, IWinHttpRequestEvents, 3 * A_PtrSize)
  551.             this.dwCookie := dwCookie, this.pCPC := pCPC, this.UnkSink := IWinHttpRequestEvents
  552.             this.pwhr := pwhr
  553.  
  554.             EventHandler(index, pEvent, arg1 := 0, arg2 := 0) {
  555.                 req := ObjFromPtrAddRef(pparent)
  556.                 if (!req.async && index > 3 && index < 7) {
  557.                     req.readyState := index - 2
  558.                     return 0
  559.                 }
  560.                 ; critical('On')
  561.                 switch index {
  562.                     case 1: ; QueryInterface
  563.                         NumPut('ptr', pEvent, arg2)
  564.                     case 2, 3:  ; AddRef, Release
  565.                     case 4: ; OnResponseStart
  566.                         req.readyState := 2
  567.                         if (req.OnResponseStart)
  568.                             req.OnResponseStart(arg1, StrGet(arg2, 'utf-16'))
  569.                     case 5: ; OnResponseDataAvailable
  570.                         req.readyState := 3
  571.                         if (req.OnResponseDataAvailable) {
  572.                             pSafeArray := NumGet(arg1, 'ptr')
  573.                             pvData := NumGet(pSafeArray + 8 + A_PtrSize, 'ptr')
  574.                             cbElements := NumGet(pSafeArray + 8 + A_PtrSize * 2, 'uint')
  575.                             req.OnResponseDataAvailable(pvData, cbElements)
  576.                         }
  577.                     case 6: ; OnResponseFinished
  578.                         req.readyState := 4
  579.                         if (req.OnResponseFinished)
  580.                             req.OnResponseFinished()
  581.                     case 7: ; OnError
  582.                         if (req.OnError)
  583.                             req.OnError(arg1, StrGet(arg2, 'utf-16'))
  584.                 }
  585.             }
  586.         }
  587.         __Delete() {
  588.             try ComCall(6, this.pCPC, 'uint', this.dwCookie)
  589.             loop 7
  590.                 CallbackFree(NumGet(this.UnkSink, (A_Index + 3) * A_PtrSize, 'ptr'))
  591.             ObjRelease(this.pCPC), this.UnkSink := 0
  592.         }
  593.     }
  594.     ;#endregion
  595. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement