Jump to content

Github file upload - Error waiting response from the server.


Recommended Posts

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.

Link to post
Share on other sites

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 for other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2022-03-07

Link to post
Share on other sites

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.

 

Link to post
Share on other sites
7 hours ago, jcpetu said:

I will appreciate any help.

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
Link to post
Share on other sites
8 hours ago, jcpetu said:

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

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

Link to post
Share on other sites
8 hours ago, 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.

 

 

 

 

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 for other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2022-03-07

Link to post
Share on other sites
10 hours ago, 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.

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!

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.

×
×
  • Create New...