Jump to content

Recommended Posts

Posted

hey guys,

I'm trying to upload some file to Github but I kept getting Error waiting response from the server. I will appreciate any help.

Basically I tried to mimic the following Javascript:

var axios = require('axios'); 
var fs = require('fs');
    var base64 = require('base-64');
    

    let token = "ghp_SgpPBp7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    let file = fs.readFileSync("abc.txt").toString();
    console.log(file);
    var content = base64.encode(file);
    console.log(content);
    uploadFileApi(token, content)
    
    
function uploadFileApi(token, content) {

    
        var data = JSON.stringify({
            "message": "txt file",
            "content": `${content}`
        });
    
        var config = {
            method: 'put',
            url: 'https://api.github.com/repos/sumit-s03/Test/contents/abc.txt',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            data: data
        };
    
        axios(config)
            .then(function (response) {
                console.log(JSON.stringify(response.data));
            })
            .catch(function (error) {
                console.log(error);
            });
    }

and here is my script:

#include <array.au3>
#include "WinHttp.au3"

Global $User = 'user'
Global $Token = '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'
Global $Address = 'https://api.github.com/repos/repositoryfolder/repositorysubfolder' ;Error waiting response from the server.
Global $FileToUpload = Base64Encode(@ScriptDir & "\test1.txt")

FilePost($Address, $User, $Token, $FileToUpload)

Func FilePost($Address, $User, $Token, $FileToUpload)
    Local $Open = _WinHttpOpen()
    Local $Connect = _WinHttpConnect($Open, $Address, 443) ;$INTERNET_DEFAULT_HTTPS_PORT=443
    Local $Request = _WinHttpOpenRequest($Connect, 'PUT', $Address, 'HTTP/1.1') ;PUT required to upload files to Github
    _WinHttpAddRequestHeaders($Request, "Autorization: Bearer " & $Token)
    _WinHttpAddRequestHeaders($Request, 'Content-Type: application/json; charset=utf-8')

    Local $Body = '{"file_name": "' & "test1.txt" & _
            '", "file_type": "' & "txt file" & _
            '", "content": "' & $FileToUpload & '"}' & @CRLF
    ConsoleWrite("--->Json: " & $Body & @CRLF)
    ConsoleWrite("$Address " & $Address & @CRLF)
    _WinHttpSendRequest($Request, Default, $Body)

    _WinHttpReceiveResponse($Request) ;Receive server response
    If @error Then
        _WinHttpCloseHandle($Request)
        _WinHttpCloseHandle($Connect)
        _WinHttpCloseHandle($Open)
        ConsoleWrite('Error waiting response from the server.' & @CRLF)
        Return
    EndIf
    $Chunk = ''
    $Data = ''
    If _WinHttpQueryDataAvailable($Request) Then ;See if there is data to read
        While 1
            $Chunk = _WinHttpReadData($Request)
            If @error Then ExitLoop
            $Data &= $Chunk
        WEnd
    Else
        ConsoleWrite('Site is experiencing problems.' & @CRLF)
        Return
    EndIf
    ;Response headers ----------------------------------------------------------------
    $headers = '' ;extract Response headers for logs view
    $headers = _WinHttpQueryHeaders($Request) ;Brings all response headers
    ConsoleWrite($headers & @CRLF)

    ConsoleWrite($Data & @CRLF)

    _WinHttpCloseHandle($Request)
    _WinHttpCloseHandle($Connect)
    _WinHttpCloseHandle($Open)

EndFunc   ;==>FilePost

Thanks in advance.

Posted

Did you take a look on my GHAPI.au3 ?

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

  Reveal hidden contents

Signature last update: 2023-04-24

Posted

Hey mLipok,

I just navigate your GHAPI.au3 post but didn't find any function to submit a file to Github. I also navigate all github links but didn't find anything to for e.g. the json format to upload a file or something related to upload a file.

 

Posted (edited)
  On 9/21/2022 at 2:27 PM, jcpetu said:

I will appreciate any help.

Expand  

You can help yourself by reading the relevant API information on the Github site.

Below is a working example of adding a file to an existing repo.  If you enter the correct access token and repo info into the constants at the top of the script, you should get a similar result.  If you try to add a file that is already there, you will get a 422 response code.  If you want to update a file, you need to add the existing file's SHA hash to the request body's JSON, everything else is the same.

I didn't show an example of converting a file's content to base64.  I used an already converted value.  You should be able to figure out how to do base64 encoding.  There are numerous examples in the forum.

 

#AutoIt3Wrapper_AU3Check_Parameters=-w 3 -w 4 -w 5 -w 6 -d

#include <Constants.au3>
#include <json.au3>

github_api_add_file_example()

Func github_api_add_file_example()

    Const $GITHUB_ACCESS_TOKEN = "ghp_6---------yQMkk-----t1---m-3B---NhJh"
    Const $REPO_OWNER          = "GithubAccount"  ;Not case-sensitive
    Const $REPO_NAME           = "test"           ;Not case-sensitive
    Const $REPO_FILE_PATH      = "newfile.txt"    ;Do not include leading "/", case-sensitive

    Const $REQUEST_BODY        = _                ;The content is just a couple lines of sample text.
              '{' & _
              '  "message": "Testing API to add a file to the repo.",' & _
              '  "content": "VGhpcyBpcyBhIGR1bW15LnR4dCBmaWxlLgpUaGlzIGlzIGEgbmV3IGxpbmUu"' & _
              '}'

    Local $sURL = ""
    Local $oComErr = Null


    ;Set up local COM error handler
    $oComErr = ObjEvent("AutoIt.Error", com_error_handler)
    #forceref $oComErr

    With ObjCreate("winhttp.winhttprequest.5.1")
        ;Build request URL
        $sURL = StringFormat("https://api.github.com/repos/%s/%s/contents/%s", $REPO_OWNER, $REPO_NAME, $REPO_FILE_PATH)

        ;Open the request
        .Open("PUT", $sURL)
        If @error Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", "WinHTTP open failed. See console for details.")

        ;Set request headers
        .SetRequestHeader("User-Agent"   , "AutoIt Script")
        .SetRequestHeader("Accept"       , "application/vnd.github+json")
        .SetRequestHeader("Authorization", "Bearer " & $GITHUB_ACCESS_TOKEN)

        ;Send the request
        .Send($REQUEST_BODY)
        If @error Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", "WinHTTP Send failed. See console for details.")

        ;Display response info
        ConsoleWrite("Response Code: " & .status & " (" & .StatusText & ")" & @CRLF & @CRLF)
        ConsoleWrite("Response:" & @CRLF)
        ConsoleWrite(Json_Encode(Json_Decode(.ResponseText), $JSON_PRETTY_PRINT + $JSON_UNESCAPED_SLASHES) & @CRLF)
    EndWith

EndFunc

Func com_error_handler($oError)
    With $oError
        ConsoleWrite(@CRLF & "COM ERROR DETECTED!" & @CRLF)
        ConsoleWrite("  Error ScriptLine....... " & .scriptline & @CRLF)
        ConsoleWrite("  Error Number........... " & "0x" & Hex(.number) & " (" & .number & ")" & @CRLF)
        ConsoleWrite("  Error WinDescription... " & StringStripWS(.windescription, $STR_STRIPTRAILING) & @CRLF)
        ConsoleWrite("  Error RetCode.......... " & "0x" & Hex(Number(.retcode)) & " (" & Number(.retcode) & ")" & @CRLF)
        ConsoleWrite("  Error Description...... " & StringStripWS(.description   , $STR_STRIPTRAILING) & @CRLF)
    EndWith
    Return ;Return to allow calling function to handle error
EndFunc

Output (some information has been redcated)

Response Code: 201 (Created)

Response:
{
    "content": {
        "name": "newfile.txt",
        "path": "newfile.txt",
        "sha": "47eb6286e280e7e63ce363d6e083de1ed4568e11",
        "size": 45,
        "url": "https://api.github.com/repos/<redacted>/test/contents/newfile.txt?ref=main",
        "html_url": "https://github.com/<redacted>/test/blob/main/newfile.txt",
        "git_url": "https://api.github.com/repos/<redacted>/test/git/blobs/47eb6286e280e7e63ce363d6e083de1ed4568e11",
        "download_url": "https://raw.githubusercontent.com/<redacted>/test/main/newfile.txt",
        "type": "file",
        "_links": {
            "self": "https://api.github.com/repos/<redacted>/test/contents/newfile.txt?ref=main",
            "git": "https://api.github.com/repos/<redacted>/test/git/blobs/47eb6286e280e7e63ce363d6e083de1ed4568e11",
            "html": "https://github.com/<redacted>/test/blob/main/newfile.txt"
        }
    },
    "commit": {
        "sha": "016378742afda96a40f75183cfef6a1c8facb00f",
        "node_id": "C_kwDOICqUhtoAKDAxNjM3ODc0MmFm----mE0MGY3NTE4M2NmZWY2YTFjOGZhY2IwMGY",
        "url": "https://api.github.com/repos/<redacted>/test/git/commits/016378742afda96a40f75183cfef6a1c8facb00f",
        "html_url": "https://github.com/<redacted>/test/commit/016378742afda96a40f75183cfef6a1c8facb00f",
        "author": {
            "name": "<redacted>",
            "email": "28315316+<redacted>@users.noreply.github.com",
            "date": "2022-09-21T21:26:30Z"
        },
        "committer": {
            "name": "<redacted>",
            "email": "28315316+<redacted>@users.noreply.github.com",
            "date": "2022-09-21T21:26:30Z"
        },
        "tree": {
            "sha": "84238b20518491320aae8cced99eebca74b160bc",
            "url": "https://api.github.com/repos/<redacted>/test/git/trees/84238b20518491320aae8cced99eebca74b160bc"
        },
        "message": "Testing API to add a file to the repo.",
        "parents": [
            {
                "sha": "e13e6ca11004aeb5b9f3e646adb6aecde923ade9",
                "url": "https://api.github.com/repos/<redacted>/test/git/commits/e13e6ca11004aeb5b9f3e646adb6aecde923ade9",
                "html_url": "https://github.com/<redacted>/test/commit/e13e6ca11----b5b9f3e646adb6aecde923ade9"
            }
        ],
        "verification": {
            "verified": false,
            "reason": "unsigned",
            "signature": null,
            "payload": null
        }
    }
}

Image of repo after API to add "newfile.txt"

image.png.cd6fa277823c4cfe444e88533e10c504.png

Edited by TheXman
Posted
Posted
  On 9/21/2022 at 2:27 PM, jcpetu said:

Global $Token = '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'

Expand  

Please delete this token ASAP or get ready to have your account hacked. Just make a new one and don't post it anywhere.

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Posted
  On 9/21/2022 at 9:47 PM, jcpetu said:

Hey mLipok,

I just navigate your GHAPI.au3 post but didn't find any function to submit a file to Github. I also navigate all github links but didn't find anything to for e.g. the json format to upload a file or something related to upload a file.

 

Expand  

 

 

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

  Reveal hidden contents

Signature last update: 2023-04-24

Posted (edited)
  On 9/21/2022 at 11:20 PM, TheDcoder said:

Please delete this token ASAP or get ready to have your account hacked. Just make a new one and don't post it anywhere.

Expand  

But, he cant delete your quote. :D

 

/edit, doh, guess you meant he should delete it on GH, not here, it was fun for a minute though. 😛

Edited by Werty

Some guy's script + some other guy's script = my script!

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.
×
×
  • Create New...