Jump to content

Recommended Posts

I'd like to create a dropbox uploader (and downloader) to provide a simple file sync without using the dropbox app.

The following is my current code (cadged and modified from other posts and websites), but I can't even figure out how to get initial authorization. Can anyone help?

NB I would be quite happy to use the oauth2 Generated access token if it bypassed a lot of this, but I'm not sure how to do this.

(If you can't guess, I know virtually nothing about http calls)

Alternatively if there is a working autoit dropbox up/downloader, I'm more than happy not to write my own (but couldn't find one)

Thanks

 

#include "WinHttp.au3"

; set the dropbox tokens
;to get the dropbox app_key and app_secret tokens, browse to https://www.dropbox.com/developers/apply?cont=/developers/apps and create a new app
If $App_Key = "" Then
    $File = ""
    $App_Key = ""
    $App_secret = ""
    $Oauth_access_token = ""
    $Oauth_access_token_secret = ""     ; this could possibly the personal Oauth2 Generated access token
    $App_folder = ""            ; this is the name of your app - it's not currently needed in this code
                                            ; the folder where the uploaded file will be stored is: Dropbox/Apps/$App_folder
EndIf

Local $sURL = "https://api.dropbox.com/1/oauth/request_token " & _
  "Authorization: OAuth oauth_version=""1.0"", oauth_signature_method=""PLAINTEXT"", " & _
  "oauth_consumer_key="""  & $App_Key & """, " & _
  "oauth_signature=""" & $App_secret & "&"""

$hOpen = _WinHttpOpen()
$FileHandle = FileOpen($File)
$hConnect = _WinHttpConnect($hOpen, $sURL)
$hRequest = _WinHttpOpenRequest($hConnect, "POST")
_WinHttpReceiveResponse($hRequest)
$sResult = ""
Do
    $sResult &= _WinHttpReadData($hRequest)
Until @error
;MsgBox(0, "", $sResult)
ConsoleWrite($sResult & @CRLF)

_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)


; response should be:
;oauth_token=<request-token>&oauth_token_secret=<request-token-secret>

;user will have to browse to the following and authorise the app
;https://www.dropbox.com/1/oauth/authorize?oauth_token=<request-token>

; you now need to generate an access token
; POST https://api.dropbox.com/1/oauth/access_token
; Header will be:
;Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="<app-key>", oauth_token="<request-token>", oauth_signature="<app-secret>&<request-token-secret>"

;reponse will be:
;oauth_token=<access-token>&oauth_token_secret=<access-token-secret>&uid=<user-id>

;now you can access the account and undertake actions

;eg get account info:
;GET https://api.dropbox.com/1/account/info
;Header:
;Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="<app-key>", oauth_token="<access-token>", oauth_signature="<app-secret>&<access-token-secret>"



; this function doesn't work, it will need to be modified to allow upload
func upload($App_Key, $App_secret, $Oauth_access_token, $Oauth_access_token_secret, $File="")
    trayseticon("C:\Program Files\AutoIt3\Icons\cute panda.ico", -1)

    ; Get the file to upload
    Local $sDrive = "", $sDir = "", $sFilename = "", $sExtension = ""
    local $time=@HOUR & ":" & @MIN & ":" & @SEC
    local $Random = Random(0,32767,1)

    ; if a filename isn't passed to the function, then ask the user for one
    If $File = "" Then
        $File = fileopendialog("Pick something to upload", @desktopdir,  "All (*.*)|Text files (*.txt)" )
    EndIf
    ;message($File)

    ; Now open the file and load the data into memory
    local $array = _PathSplit($File,$sDrive, $sDir, $sFilename, $sExtension) ; get the file name and extension
    Local $i = UBound($array) - 1
    local $sFile = fileopen($File,16)
    Local $data = fileread($sFile)
    local $size = @extended
    FileClose($File)

    ;set up the dropbox upload URL
    ;to get the dropbox tokens, browse to https://www.dropbox.com/developers/apply?cont=/developers/apps and create a new app
    ;$array[$i-1] is the file name of the file the user wants to upload and $array[$i] is the extension
    Local $sUrl = ("https://api-content.dropbox.com/1/files_put/dropbox"&"/"& $array[$i-1] & $array[$i] & _
      '?oauth_consumer_key=' & $App_Key & _
      " & oauth_token=" & $Oauth_access_token & _
      " & oauth_signature_method=PLAINTEXT & oauth_signature=" & $App_secret & "%26" & $Oauth_access_token_secret & _
      " & oauth_timestamp=" & $time & _
      " & oauth_nonce=" & $RANDOM)


;Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT",
;oauth_consumer_key="<app-key>", oauth_token="<access-token>",
;oauth_signature="<app-secret>&<access-token-secret>"




    msgbox(1,"URL",$sUrl)

    ; now attempt to upload the file with the generated dropbox URL
    Local $obj = ObjCreate("WinHttp.WinHttpRequest.5.1")
    ;message("here")
    $obj.Open("PUT", $sURL, False)
    If @error Then
        MsgBox(1,"ERROR","@1unable to upload" & " " &$array[$i-1] & $array[$i])
    else
        ; message("request opened")

        $obj.SetRequestHeader("User-Agent", "User-Agent=Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")
        ;$obj.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
        $obj.SetRequestHeader("Content-Length", $size)
;       if _FindNetwork() = "xavier" Then
;       $obj.SetProxy(2, "number")
;       endif

        ;   message($sFile)

        $obj.Send($data) ; send the file to uploaded

        $oReceived  = $obj.ResponseText
        $oStatusCode = $obj.Status
        If $obj.Status <> $HTTP_STATUS_OK Then
;           local $FindError = FindError($oStatusCode)
;           message($oReceived)
            msgbox(0 , "Error", "@2" & $oStatusCode & " :unable to upload " & $array[$i-1] & $array[$i])
        else
            msgbox(0 , "success", "uploaded " & $array[$i-1] & $array[$i])
        endif
        trayseticon("C:\Program Files\AutoIt3\Icons\panda.ico", -1)
    endif
endfunc

 

Edited by dgm5555
Link to post
Share on other sites

I dusted off an old Flikr uploader.  It could probably be coded a lot more efficiently but it was working using oAuth.  Maybe it can get you started to authorize your app.

;flikr API call - will be used to upload pictures to Flikr

#Include <String.au3>
#include<Array.au3>
#include <Crypt.au3>
#include <IE.au3>

#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#Region ### START Koda GUI section ### Form=
$Form1 = GUICreate("Form1", 169, 122, 192, 124)
$Label1 = GUICtrlCreateLabel("running", 24, 8, 39, 17)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

dim $getFrobSignature,$frobSignature,$getFrobURL

$apiKey="YOUR KEY"
$secret="YOUR SECRET"
; ****************************
$frobSigString=$secret&"api_key"&$apiKey&"methodflickr.auth.getFrob"
;MsgBox("","This is the string that we will Md5 has to get our signature",$frobSigString)
$frobSignature=_Crypt_HashData($frobSigString,$CALG_MD5)
;MsgBox("","This the MD5 $getFrobSignature :",$getFrobSignature)
$frobSignatureTrimmed=StringTrimLeft($frobSignature,2)
;MsgBox("","This the trimmed MD5 $getFrobSignature :",$frobSignatureTrimmed)
$getFrobURL="http://api.flickr.com/services/rest/?method=flickr.auth.getFrob&api_key="&$apiKey&"&api_sig="&$frobSignatureTrimmed

;call gets FROB required session authentication
$fob2=InetRead ($getFrobURL)
;MsgBox("","This the frob that was returned",$fob2)
;FROB response is hexidecimal this changes it to a string
$fob2=_HexToString($fob2)
;MsgBox("","This the string of the frob that was returned",$fob2)
;now I take the exact FROB from all the stuff returned - it is in an array
$fob2=_StringBetween($fob2,"<frob>","</frob>"); returns an array
;this converts it back to a string
$fob2=$fob2[0]; assigns it back to a string
;MsgBox("","",$fob2)
;*************************************************************************


;create Create a login link
;This is secret + 'api_key' + [api_key] + 'frob' + [frob] + 'perms' + [perms]. We then take the MD5 sum of the string - this is our [api_sig] value. We can then build our full login URL:
$secretPlusAPIString=$secret&"api_key"&$apiKey&"frob"&$fob2&"permswrite"
;MsgBox("","","This is the URL that we will need to hash: "&$secretPlusAPIString)
$apiSigValue=_Crypt_HashData($secretPlusAPIString,$CALG_MD5)
;trim the hex intro off
$apiSigValue= StringTrimLeft($apiSigValue,2)
;MsgBox("","sigvalue",$apiSigValue)
;now this is the url that will be required to authorize your desktop application
$authorizeURL="http://www.flickr.com/services/auth/?api_key="&$apiKey&"&perms=write&frob="&$fob2&"&api_sig="&$apiSigValue
;MsgBox("","authorize url value",$authorizeURL)
;this brings you to a page where the site prompts the user to authorize the application
_IECreate($authorizeURL)
MsgBox("","","don't do anything until I authorize")
;*************************************************************************


$getTokenValue=$secret&"api_key"&$apiKey&"frob"&$fob2&"methodflickr.auth.getToken"
;MsgBox("","this is the get token value string",$getTokenValue)
$getTokenSignature=_Crypt_HashData($getTokenValue,$CALG_MD5)
$getTokenSignatureTrimmed=stringTrimLeft($getTokenSignature,2)
;MsgBox("","","This is the get token signature "&$getTokenSignature)
$getTokenURL="http://flickr.com/services/rest/?method=flickr.auth.getToken&api_key="&$apiKey&"&frob="&$fob2&"&api_sig="&$getTokenSignatureTrimmed
;MsgBox("","This is the get Token URL call",$getTokenURL)
$token=InetRead($getTokenURL)
$token=_HexToString($token)
MsgBox("","This is the token message",$token)
;extract the actual token
$token=_StringBetween($token,"<token>","</token>"); returns an array
;this converts it back to a string
$token=$token[0]; assigns it back to a string
MsgBox("","This is the actual token",$token)

;now lets make an authenticated call and do something!
;CHANGE THE METHOD TO WHATEVER YOU WANT FROM THE API LIST
func _authenticatedFlikrCall();this one requires a token - otherwise could be modified for the unauthenicated calls
$method="methodflickr.blogs.getList"
$methodString=$secret&"api_key"&$apiKey&"auth_token"&$token&$method
$methodMd5=_Crypt_HashData($methodString,$CALG_MD5)
$methodMd5Trimmed = StringTrimLeft($methodMd5,2)
$getMethodUrl="http://flickr.com/services/rest/?method="&$method&"&api_key="&$apiKey&"&auth_token="&$token&"&api_sig="&$methodMd5Trimmed
$methodData=InetRead($getMethodURL)
$methodData=_HexToString($methodData)
MsgBox("","This is the information about your blogs",$methodData)
EndFunc


$oIE = _IECreate ()
$somePhoto=@ScriptDir&"\1.jpg"
;create upload signature
$uploadSig=""
$uploadSigString = $secret&"api_key"&$apikey&"auth_token"&$token&"submitUpload"
;MsgBox("","This is the upload signature string pre-Md5",$uploadSigString)
$md5upload=_Crypt_HashData($uploadSigString,$CALG_MD5)
;MsgBox("","This is the upload string after Md5",$md5upload)
$uploadSig = StringTrimLeft($md5upload,2)
MsgBox("","This is the upload string after Md5",$md5upload)
;****************************
$sHTML = ""
$sHTML &='<form enctype="multipart/form-data" method="post"  action="http://api.flickr.com/services/upload/">   '& @CR
$sHTML &='<input type="file" name="photo"/>'   & @CR
$sHTML &='<input type="hidden" name="api_key" value="'&$apikey&'"/>'& @CR
$sHTML &='<input type="hidden" name="auth_token" value="'&$token&'"/>'  & @CR
$sHTML &='<input type="hidden" name="api_sig" value="'&$uploadSig&'"/>'   & @CR
$sHTML &='<input type="submit" name ="submit" value="Upload"/>'  & @CR
$sHTML &='</form>'  & @CR

_IEDocWriteHTML ($oIE, $sHTML)
_IEAction ($oIE, "refresh")
sleep(1000)
;$oForm = _IEFormGetObjByName ($oIE, "flickrUpload")
;_IEFormSubmit ($oForm)


While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit

    EndSwitch
WEnd

 

Edited by Jfish

Build your own poker game with AutoIt: pokerlogic.au3 | Learn To Program Using FREE Tools with AutoIt

Link to post
Share on other sites

Looks likes Gimerly has created a dropbox authenticator, as well as an uploader

Unfortunately the authenticator doesn't work for me yet. It produced the some of the required tokens, as a debug message in the SciTE console then crashed, but I'm working on it.

The uploader - is included in the above post, but reckon I'm 90% there with that (hopefully it will work when the tokens are correct:

I've posted my current code anyway

 

; Original code posted by Gimerly:-
;   https://www.autoitscript.com/forum/files/file/290-dropbox-authenticator/
;   https://www.autoitscript.com/forum/topic/161633-uploading-a-file-to-http-server/
; Modified by David Mckenzie 19/07/2015


#include <File.au3>
#include <WinHttp.au3>
#include <Date.au3>
#include <Array.au3>
#include <String.au3>

; set the dropbox tokens
If $App_Key = "" Then
    $File = ""
    $App_Key = ""
    $App_secret = ""
    $Oauth_access_token = ""
    $Oauth_access_token_secret = ""     ; this the personal Oauth2 Generated access token
    $App_folder = "autoitUploader"          ; this is (probably) the name of your app - it's not currently needed in this code
EndIf

getAuth($App_Key, $App_secret)
upload($App_Key, $App_secret, $Oauth_access_token, $Oauth_access_token_secret, $File)

Func upload($App_Key, $App_secret, $Oauth_access_token, $Oauth_access_token_secret, $File="")
;   trayseticon("C:\Program Files\AutoIt3\Icons\cute panda.ico", -1)

    ; Get the file to upload
    Local $sDrive = "", $sDir = "", $sFilename = "", $sExtension = ""
    local $time= CurrentTime()
    local $Random = Random(0,32767,1)

    ; if a filename isn't passed to the function, then ask the user for one
    If $File = "" Then
        $File = fileopendialog("Pick something to upload", @desktopdir,  "All (*.*)|Text files (*.txt)" )
    EndIf
    ;ConsoleWriteTS($File)

    ; Now open the file and load the data into memory
    local $array = _PathSplit($File,$sDrive, $sDir, $sFilename, $sExtension) ; get the file name and extension
    Local $i = UBound($array) - 1
    local $sFile = fileopen($File,16)
    Local $data = fileread($sFile)
    local $size = @extended
    FileClose($File)

    ;set up the dropbox upload URL
    ;to get the dropbox tokens, browse to https://www.dropbox.com/developers/apply?cont=/developers/apps and create a new app
    ;$array[$i-1] is the file name of the file the user wants to upload and $array[$i] is the extension
    Local $sUrl = ("https://api-content.dropbox.com/1/files_put/dropbox" & "/" & $array[$i-1] & $array[$i] & _
      "?oauth_consumer_key=" & $App_Key & _
      "&oauth_token=" & $Oauth_access_token & _
      "&oauth_signature_method=PLAINTEXT" & _
      "&oauth_signature=" & $App_secret & "&" & $Oauth_access_token_secret & _
      "&oauth_timestamp=" & $time & _
      "&oauth_nonce=" & $RANDOM)

    ConsoleWriteTS("URL: " & $sUrl)

    ; now attempt to upload the file with the generated dropbox URL
    Local $obj = ObjCreate("WinHttp.WinHttpRequest.5.1")
    $obj.Open("PUT", $sURL, False)
    ConsoleWriteTS("Open PUT")
    If @error Then
        ConsoleWriteTS("@1:unable to open PUT" & " " &$array[$i-1] & $array[$i])
    else
        ConsoleWriteTS("request opened")

        $obj.SetRequestHeader("User-Agent", "User-Agent=Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")
        ;$obj.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
        $obj.SetRequestHeader("Content-Length", $size)
;       if _FindNetwork() = "xavier" Then
;       $obj.SetProxy(2, "number")
;       endif

        ConsoleWriteTS("@2:" & $sFile)

        $obj.Send($data) ; send the file to uploaded

        $oReceived  = $obj.ResponseText
        $oStatusCode = $obj.Status
        If $obj.Status <> $HTTP_STATUS_OK Then
            $FindError = FindError($oStatusCode)
            ConsoleWriteTS($oReceived)
            ConsoleWriteTS("@3:" & $oStatusCode & ":" & $FindError & " :unable to upload " & $array[$i-1] & $array[$i])
        else
            ConsoleWriteTS("uploaded " & $array[$i-1] & $array[$i])
        endif
;       trayseticon("C:\Program Files\AutoIt3\Icons\panda.ico", -1)
    endif
EndFunc

Func CurrentTime()
    return _DateDiff('s', "1970/01/01 00:00:00", _NowCalc())
EndFunc

 Func FindError($apple)
    switch 1
    case $apple = 400
       return "Bad input parameter"
    case $apple = 401
       return "Bad or expired token."
    case $apple = 403
       return "Bad OAuth request (wrong consumer key, bad nonce, expired timestamp...). "
    case $apple = 404
       return "File or folder not found at the specified path."
    case $apple = 405
       return "Request method not expected (generally should be GET or POST)."
    case $apple = 429
       return "Your app is making too many requests and is being rate limited"
    case $apple = 503
       return "OAuth 1.0 app is being rate limited. "
    case $apple = 507
       return "User is over Dropbox storage quota."
    case $apple = 5&"xx"
       return "server error"
    endswitch

 EndFunc

 Func ConsoleWriteTS($pea)
   ; consolewrite writes whatever value you want to the stdout stream
    ConsoleWrite(@Mday&"/"&@mon&" "&@hour&":"&@min&":"&@sec&" --> " & $pea & @CRLF)
EndFunc




Exit


;*********************  Dropbox authenticator  ********************

DirCreate(@desktopdir & "\Dropbox authenticator")
;fileinstall("C:\Users\jcampbell\Desktop\AutoIT\tokens.txt", @desktopdir & "\Dropbox authenticator\tokens.txt")
;fileinstall("C:\Users\jcampbell\Desktop\AutoIT\url.txt", @desktopdir & "\Dropbox authenticator\url.txt")


Func getAuth($App_Key="", $App_secret="")
    ConsoleWriteTS("starting Func GetToken")

    If $App_Key = "" Then
        Msgbox(0,"Welcome", "This was created to make getting your oauth_token and secret easier. When you first run this program it will create an empty folder on your desktop (please leave it as it needs to be on the desktop). As your progress though the program text files will be created as they are needed. make sure not to click ok on the ConsoleWriteTSbox without reading as it is vitial each step be complete before going onto the next.")

        $App_Key = inputbox("App key", "Please enter your app key" & @CRLF & "To get the initial dropbox tokens, browse to https://www.dropbox.com/developers/apply?cont=/developers/apps and create a new app", "https://www.dropbox.com/developers/apply?cont=/developers/apps" )
        $App_Secret = inputbox("App secret", "Please enter your app secret")
    EndIf

    Local $obj = ObjCreate("WinHttp.WinHttpRequest.5.1")
    local $time=currenttime()
    local $Random = Random(0,32767,1)
    ; using my fucntion _FindNetwork I can determine whether or not I need to set a proxy. This is so the user doesn't have to do anything and is all automated.
    ;if _FindNetwork() = "xavier" Then  $obj.SetProxy(2, "proxy.school:3128")
    ;$obj.SetTimeouts(30000,60000,30000,400000) ;wait a max of 6.6 minutes for request to timeout

    Local $sUrl = ("https://api.dropbox.com/1/oauth/request_token" & _
      "?oauth_consumer_key=" & $App_Key & _
      "&oauth_token=" & $Oauth_access_token & _
      "&oauth_signature_method=PLAINTEXT" & _
      "&oauth_signature=" & $App_secret & "&" & _
      "&oauth_timestamp=" & $time & _
      "&oauth_nonce=" & $RANDOM)

    ConsoleWriteTS("URL: " & $sUrl)

    $obj.Open("POST", $sURL , False)
    ConsoleWriteTS("Open POST")

    $obj.Send($sUrl)

    local $status = $obj.Status
    local $Recieved = $obj.ResponseText
    local $FindError = FindError($status)
    If $obj.Status <> 200 Then
        $FindError = FindError($status)
        ConsoleWriteTS($FindError)
        Exit
    else
        ConsoleWriteTS($obj.ResponseText)
        ConsoleWriteTS($Recieved)
        $secret = GetSecret($Recieved)
        ConsoleWriteTS("secret:" & " "&$secret)
        $token = GetToken1($Recieved)
        ConsoleWriteTS("token:" & " "&$token)
        authorize($secret, $token)
        ;pause(100)
        local $url = "https://www.dropbox.com/1/oauth/authorize"&"?oauth_consumer_key="&$App_Key&"&oauth_token="&$token&"&oauth_signature="&$App_Secret&"&"&$secret&"&oauth_signature_method=PLAINTEXT"

        ConsoleWriteTS("Copy and paste the following url into your browser and click the ok button when you have accepted authorization" & @CRLF & $url & @CRLF)
        InputBox("Instructions", "Copy and paste the following url into your browser and click the ok button when you have accepted authorization", $url)
        AccessToken($secret, $token)


    endif

EndFunc

Func AccessToken($secret, $token)
    ConsoleWriteTS("starting Func AccessToken")

    Local $obj = ObjCreate("WinHttp.WinHttpRequest.5.1")
    local $time = currenttime()
    local $Random = Random(0,32767,1)
    ;ConsoleWriteTS("App key" & " " & $App_Key)
    ConsoleWriteTS($token)

    Local $sUrl = ("https://api.dropbox.com/1/oauth/access_token" & _
      "?oauth_consumer_key=" & $App_Key & _
      "&oauth_token=" & $token & _
      "&oauth_signature_method=PLAINTEXT" & _
      "&oauth_signature=" & $App_secret & "&" & $secret & _
      "&oauth_timestamp=" & $time & _
      "&oauth_nonce=" & $RANDOM)

    ConsoleWriteTS("URL: " & $sUrl)

    ;$size = stringlen($token)
    $obj.Open("POST", $sUrl , False)
    ConsoleWriteTS("Open POST")

    ;$obj.SetResponseHeaders("content-length", $size)
    ;$obj.SetRequestHeader("User-Agent", "User-Agent=Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")

    $obj.send($sUrl)
    local $Recieved = $obj.ResponseText

    If $obj.Status <> 200 Then
        ConsoleWriteTS($obj.status)
        ConsoleWriteTS($obj.ResponseText)
        MsgBox(0, "Error", "Unable to retrieve your Oauth_token and secret at this time")
    else
        ;iniwrite(@scriptdir & "/
        ;ConsoleWriteTS($Recieved)
        ;$oauth_token_secret = GetSecret1($Recieved)
        ;$oauth_token = GetOauth($Recieved)
        msgbox(0, "Success", "Go to the dropbox authenticator folder, open tokens.txt and the last line has your most recent Oauth_token and secret")
        local $sFile = fileopen(@desktopdir & "\Dropbox authenticator\tokens.txt",1)
        filewrite($sFile, $Recieved)
        fileclose($sFile)
    endif


EndFunc

Func GetOauth($data)
    local $array = _StringBetween($data, "oauth_token=","&")
    return $array[0]
EndFunc

Func GetSecret1($data)
    local $array = _StringBetween($data, "oauth_token_secret=", "&")
    return $array[0]
EndFunc

Func authorize($token_secret, $access_token)
    local $time=currenttime()
    local $Random = Random(0,32767,1)
    local $url = "https://www.dropbox.com/1/oauth/authorize"&"?oauth_consumer_key="&$App_Key&"&oauth_token="&$access_token&"&oauth_signature="&$App_Secret&"&"&$token_secret&"&oauth_signature_method=PLAINTEXT"&"&oauth_timestamp="&$time&"&oauth_nonce="&$RANDOM
    local $Random = Random(0,32767,1)
    ConsoleWriteTS("url is " & " "&$url)
    Local $obj = ObjCreate("WinHttp.WinHttpRequest.5.1")
    $obj.Open("GET", $url , False)
    ;if _FindNetwork() = "xavier" Then  $obj.SetProxy(2, "proxy.school:3128")
    ;ConsoleWriteTS($url)
    local $size = stringlen($url)
    $obj.SetResponseHeaders("content-length", $size)
    $obj.SetRequestHeader("User-Agent", "User-Agent=Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")
    $obj.Send($url)

    local $status = $obj.Status
    local $Recieved = $obj.ResponseText
    If $obj.Status <> 200 Then
        local $FindError = FindError($status)
        ConsoleWriteTS($FindError)
    else
        ConsoleWriteTS($obj.Status)
    endif

EndFunc

Func GetToken1($str)
    Local $pie = _StringBetween($str, "oauth_token=","") ; gets the text starting from oauth_token to the end of the file
    if $pie = 1 then
        ConsoleWriteTS("error")
    else
        return $pie[0]
    endif
EndFunc

Func GetSecret($str)
    local $pie = _StringBetween($str,"oauth_token_secret=","&")
    if $pie = 1 then
        ConsoleWriteTS(@error)
    else
        ConsoleWriteTS("pie is" & " " &$pie[0])
        return $pie[0]
    endif
EndFunc

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By mLipok
      I try to download some file with winhttp.au3
      I use code from here:

      My code looks like:
      #include <FileConstants.au3> #include "WinHttp.au3" #AutoIt3Wrapper_Run_AU3Check=N _Example() Func _Example() ; Initialize and get session handle Local $hOpen = _WinHttpOpen() ; Get connection handle Local $hConnect = _WinHttpConnect($hOpen, "https://MY_URL") Local $CurrentOption = _WinHttpQueryOption($hConnect, $WINHTTP_OPTION_SECURITY_FLAGS) Local $Options = BitOR($CurrentOption, _ $SECURITY_FLAG_IGNORE_UNKNOWN_CA, _ $SECURITY_FLAG_IGNORE_CERT_CN_INVALID, _ $SECURITY_FLAG_IGNORE_CERT_DATE_INVALID) _WinHttpSetOption($hConnect, $WINHTTP_OPTION_SECURITY_FLAGS, $Options) If @error Then ConsoleWrite("! ---> @error=" & @error & " @extended=" & @extended & _ " : _WinHttpSetOption" & @CRLF) ; Specify the reguest Local $hRequest = _WinHttpOpenRequest($hConnect, Default, "MY_FILE") ; Send request _WinHttpSendRequest($hRequest) ; Wait for the response _WinHttpReceiveResponse($hRequest) ProgressOn("Downloading", "In Progress...") Progress(_WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_CONTENT_LENGTH)) Local $sData ; Check if there is data available... If _WinHttpQueryDataAvailable($hRequest) Then While 1 $sChunk = _WinHttpReadData_Ex($hRequest, Default, Default, Default, Progress) If @error Then ExitLoop $sData &= $sChunk Sleep(20) WEnd Else MsgBox(48, "Error", "Site is experiencing problems (or you).") EndIf Sleep(1000) ProgressOff() ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) Local $hFile = FileOpen(@ScriptDir & "\MY_FILE", $FO_OVERWRITE + $FO_CREATEPATH + $FO_BINARY) FileWrite($hFile, $sData) FileClose($hFile) EndFunc ;==>_Example Func Progress($iSizeAll, $iSizeChunk = 0) Local Static $iMax, $iCurrentSize If $iSizeAll Then $iMax = $iSizeAll $iCurrentSize += $iSizeChunk Local $iPercent = Round($iCurrentSize / $iMax * 100, 0) ProgressSet($iPercent, $iPercent & " %") EndFunc ;==>Progress Func _WinHttpReadData_Ex($hRequest, $iMode = Default, $iNumberOfBytesToRead = Default, $pBuffer = Default, $vFunc = Default) __WinHttpDefault($iMode, 0) __WinHttpDefault($iNumberOfBytesToRead, 8192) __WinHttpDefault($vFunc, 0) Local $tBuffer, $vOutOnError = "" If $iMode = 2 Then $vOutOnError = Binary($vOutOnError) Switch $iMode Case 1, 2 If $pBuffer And $pBuffer <> Default Then $tBuffer = DllStructCreate("byte[" & $iNumberOfBytesToRead & "]", $pBuffer) Else $tBuffer = DllStructCreate("byte[" & $iNumberOfBytesToRead & "]") EndIf Case Else $iMode = 0 If $pBuffer And $pBuffer <> Default Then $tBuffer = DllStructCreate("char[" & $iNumberOfBytesToRead & "]", $pBuffer) Else $tBuffer = DllStructCreate("char[" & $iNumberOfBytesToRead & "]") EndIf EndSwitch Local $sReadType = "dword*" If BitAND(_WinHttpQueryOption(_WinHttpQueryOption(_WinHttpQueryOption($hRequest, $WINHTTP_OPTION_PARENT_HANDLE), $WINHTTP_OPTION_PARENT_HANDLE), $WINHTTP_OPTION_CONTEXT_VALUE), $WINHTTP_FLAG_ASYNC) Then $sReadType = "ptr" Local $aCall = DllCall($hWINHTTPDLL__WINHTTP, "bool", "WinHttpReadData", _ "handle", $hRequest, _ "struct*", $tBuffer, _ "dword", $iNumberOfBytesToRead, _ $sReadType, 0) If @error Or Not $aCall[0] Then Return SetError(1, 0, "") If Not $aCall[4] Then Return SetError(-1, 0, $vOutOnError) If IsFunc($vFunc) Then $vFunc(0, $aCall[4]) If $aCall[4] < $iNumberOfBytesToRead Then Switch $iMode Case 0 Return SetExtended($aCall[4], StringLeft(DllStructGetData($tBuffer, 1), $aCall[4])) Case 1 Return SetExtended($aCall[4], BinaryToString(BinaryMid(DllStructGetData($tBuffer, 1), 1, $aCall[4]), 4)) Case 2 Return SetExtended($aCall[4], BinaryMid(DllStructGetData($tBuffer, 1), 1, $aCall[4])) EndSwitch Else Switch $iMode Case 0, 2 Return SetExtended($aCall[4], DllStructGetData($tBuffer, 1)) Case 1 Return SetExtended($aCall[4], BinaryToString(DllStructGetData($tBuffer, 1), 4)) EndSwitch EndIf EndFunc ;==>_WinHttpReadData_Ex
      As a result I get file with this contents:
       
      As so far I found this:
        

      So I even with added:
      Local $CurrentOption = _WinHttpQueryOption($hConnect, $WINHTTP_OPTION_SECURITY_FLAGS) Local $Options = BitOR($CurrentOption, _ $SECURITY_FLAG_IGNORE_UNKNOWN_CA, _ $SECURITY_FLAG_IGNORE_CERT_CN_INVALID, _ $SECURITY_FLAG_IGNORE_CERT_DATE_INVALID) _WinHttpSetOption($hConnect, $WINHTTP_OPTION_SECURITY_FLAGS, $Options) If @error Then ConsoleWrite("! ---> @error=" & @error & " @extended=" & @extended & _ " : _WinHttpSetOption" & @CRLF)
      I still get the same errors.

      Anyone know a way how to fix this problem?

      Regards,
      mLipok
       
    • By adityaparakh
      Hello ,
      I am trying to use Websockets in AutoIt.
      It is to fetch live stock market prices , API is provided and documentation available for python language.
      The link for the code snippet is :
      https://symphonyfintech.com/xts-market-data-front-end-api-v2/#tag/Introduction
      https://symphonyfintech.com/xts-market-data-front-end-api-v2/#tag/Instruments/paths/~1instruments~1subscription/post
       
      https://github.com/symphonyfintech/xts-pythonclient-api-sdk
       
      Second Link is to subscribe to a list of ExchangeInstruments.
      Now I would like to get live stock ltp (LastTradedPrice) for a few stocks whose "ExchangeInstrumentID" I know.
      I am able to use the WinHttp object to perform actions using simple codes like below :
      I have the secretKey and appkey and can generate the needed token. And get the unique ExchangeInstrumentID.

      Below code is just for example of how I am using WinHttp. Unrelated to socket part.
      Global $InteractiveAPItoken = IniRead(@ScriptDir & "\Config.ini", "token", "InteractiveAPItoken", "NA") $baseurl = "https://brokerlink.com/interactive/" $functionurl = "orders" $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("POST", $baseurl & $functionurl, False) $oHTTP.SetRequestHeader("Content-Type", "application/json;charset=UTF-8") $oHTTP.SetRequestHeader("authorization", $InteractiveAPItoken) $pD = '{ "exchangeSegment": "NSEFO", "exchangeInstrumentID": ' & $exchangeInstrumentID & ', "productType": "' & $producttype & '", "orderType": "MARKET", "orderSide": "' & $orderside & '", "timeInForce": "DAY", "disclosedQuantity": 0, "orderQuantity": ' & $qty & ', "limitPrice": 0, "stopPrice": 0, "orderUniqueIdentifier": "' & $orderidentifier & '"}' $oHTTP.Send($pD) $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status
          
          
      But am struggling to understand and use socket.
      Would be of great help if you can have a look at the link mentioned above and help with the code sample for AutoIt.
      To connect and listen to a socket.
      Thanks a lot
       
    • By Colduction
      Hi AutoIt Members and Programmers, i have a problem with Telegram UDF that does not work on some of my servers, Telegram is not restricted in these machines, here is console output in Windows 7 (Server):
      >"C:\Program Files (x86)\AutoIt3\SciTE\..\AutoIt3.exe" "C:\Program Files (x86)\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.au3" /run /prod /ErrorStdOut /in "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3" /UserParams +>20:20:40 Starting AutoIt3Wrapper (19.1127.1402.0} from:SciTE.exe (4.2.0.0) Keyboard:00000429 OS:WIN_7/Service Pack 1 CPU:X64 OS:X64 Environment(Language:0409) CodePage:0 utf8.auto.check:4 +> SciTEDir => C:\Program Files (x86)\AutoIt3\SciTE UserDir => C:\Users\.NetFramework\AppData\Local\AutoIt v3\SciTE\AutoIt3Wrapper SCITE_USERHOME => C:\Users\.NetFramework\AppData\Local\AutoIt v3\SciTE >Running AU3Check (3.3.14.5) from:C:\Program Files (x86)\AutoIt3 input:C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3 +>20:20:40 AU3Check ended.rc:0 >Running:(3.3.14.5):C:\Program Files (x86)\AutoIt3\autoit3.exe "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3" +>Setting Hotkeys...--> Press Ctrl+Alt+Break to Restart or Ctrl+BREAK to Stop. Test file for Telegram UDF (https://github.com/xLinkOut/telegram-udf-autoit). This file need a valid ChatID of a Telegram user who has already sent at least a message to the bot, and a valid token given by @BotFather. Insert this data in the source code. "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\src\Telegram.au3" (1098) : ==> The requested action with this object has failed.: $oHTTP.Send() $oHTTP^ ERROR ->20:20:41 AutoIt3.exe ended.rc:1 +>20:20:41 AutoIt3Wrapper Finished. >Exit code: 1 Time: 1.56 It's really annoying problem in WinHTTP
    • By nacerbaaziz
      goodmorning autoit team
      today am comming with some winhttp problems, i hope that you can help me to solve them.
      the first problem
      is when opening a request
      my forums api allow me to delete any post using the api key
      all functions work, i mean post / get
      but when i tried to use the delete verb it's gave me an html 404 error
      here is what am tried
      #include "WinHttp.au3" ; Open needed handles Global $hOpen = _WinHttpOpen() Global $hConnect = _WinHttpConnect($hOpen, "xxxxxxxx.com") ; Specify the reguest: Global $hRequest = _WinHttpOpenRequest($hConnect, "Delete", "/vb/Api/posts/10447/?hard_delete=true", default, default) _WinHttpAddRequestHeaders($hRequest, "XF-Api-Key:xxxxx") _WinHttpAddRequestHeaders($hRequest, "XF-Api-User:xxxxx") ; Send request _WinHttpSendRequest($hRequest) ; Wait for the response _WinHttpReceiveResponse($hRequest) Global $sHeader = 0, $sReturned = 0 ; If there is data available... If _WinHttpQueryDataAvailable($hRequest) Then $sHeader = _WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_CONTENT_DISPOSITION) ;Or maybe: ; $sHeader = _WinHttpQueryHeaders($hRequest, BitOR($WINHTTP_QUERY_RAW_HEADERS_CRLF, $WINHTTP_QUERY_CUSTOM), "Content-Disposition") Do $sReturned &= _WinHttpReadData($hRequest) Until @error msgBox(64, "", $sReturned) endIf ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen)  
      and here is the error message
      <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>403 Forbidden</title> </head><body> <h1>Forbidden</h1> <p>You don't have permission to access /vb/Api/posts/10447/ on this server.<br /> </p> </body></html>  
      i hope you can help me 
      thanks in advance
    • By FengHuangWuShen
      So I was playing with INet and downloading files and made a simple video downloader, or it can even be used for any file really.
      Just follow the reference section in INet_Settings.ini , and then run the script.
       
      Main Script <snip>
      INet_Settings.ini  URL - The target URL of the video you're trying to grab Data - This is the starting string, and ending string reference to look for the download URL itself. Settings - Only setting here currently, is the delay in which to wait for the file to download ### Reference for Start and End points for various websites <snip>
      Credits to : https://www.autoitscript.com/forum/profile/31965-progandy/  for the URL Encode and Decode.
×
×
  • Create New...