Receive Dropbox file

Just starting out? Need help? Post your questions and find answers here.
User avatar
J@ckWhiteIII
Enthusiast
Enthusiast
Posts: 183
Joined: Fri May 25, 2012 7:39 pm

Receive Dropbox file

Post by J@ckWhiteIII »

Hey,
probably not the best thing to ask this in the "how to code..?"-section, but I don't really know where else to ask this.
My problem is the following:
I want to make an application that has a launcher (application is a runnable JAR file). This launcher should have an update function, so that it then downloads the specified .jar file. As I don't have a global server, I thought I'd just upload the jar file to DropBox and then receive it in PB using ReceiveNetworkFile/ReceiveNetworkData. Data would probably be the best way as ReceiveNetworkFile needs a file to be sent using SendNetworkFile.
Well, I couldn't even test that yet as I can't even open a network connection to the specified DropBox page. I am going to show you my code (worked with Java for too long now, forgot how to code "clean" in PB):

Code: Select all

EnableExplicit
InitNetwork()

;RunProgram("javaw","-jar Calculator.jar","") ;so that I don't forget

Global hwnd.i = OpenWindow(#PB_Any,0,0,300,200,"Minification Calc Launcher",#PB_Window_ScreenCentered|#PB_Window_SystemMenu)
Global updateButton.i = ButtonGadget (#PB_Any,215,140,80,20,"Update")
Global startButton.i = ButtonGadget (#PB_Any,215,170,80,20,"Launch!")
Global we.i

Procedure updateFiles()
  
  Protected Connection.i = OpenNetworkConnection("https://dl.dropbox.com/u/76620573/Calculator.jar",80) ;dunno what port to use..
  Protected *mem = AllocateMemory(5000)
  Protected success.i
  If(Connection)
    success = ReceiveNetworkData(Connection,*mem,5000)
  EndIf
  If success
    ;RunProgram("javaw","-jar Calculator.jar","")
  Else
    End
  EndIf
  
EndProcedure

Procedure CheckGadgets(we)
  
  Select we
    Case updateButton
      updateFiles()
      Debug "yes"
  EndSelect
  
EndProcedure

Repeat
  we = WindowEvent ()
  Select we
    Case #PB_Event_Gadget
      CheckGadgets(EventGadget())
  EndSelect
Until we = #PB_Event_CloseWindow
Apparently, Connection is always null meaning no connection could be created. Does anyone have an idea why?
Thank you in advance :)
infratec
Always Here
Always Here
Posts: 7582
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Receive Dropbox file

Post by infratec »

Hi,

PB from itself can not do https.
Maybe it works with http also.
But without a valid http header and so on, it will never work.

Search for 'receive http memory'

Bernd
User avatar
J@ckWhiteIII
Enthusiast
Enthusiast
Posts: 183
Joined: Fri May 25, 2012 7:39 pm

Re: Receive Dropbox file

Post by J@ckWhiteIII »

Hi,
I think DropBox only does https. I'll have to try another option. Maybe FTP and some webspace will do the job.
Thanks for your effort!
infratec
Always Here
Always Here
Posts: 7582
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Receive Dropbox file

Post by infratec »

Wrong!

This works:

Code: Select all

EnableExplicit


Procedure.i HTTPGet2Mem(URL$)
 
  Protected.i ConnectionID, TimeOutCounter, Laenge, Pos, Received, HelpLength, Length, HeaderEndPos, HeaderFinished, Size
  Protected Server$, Header$, String$, Result$, Page$, Parameter$, Host$, *Buffer, *HelpBuffer
 
 
  If LCase(Left(URL$, 7)) <> "http://"
    URL$ = "http://" + URL$
  EndIf
 
  ;Host$ = GetURLPart(URL$, #PB_URL_Site)
 
  Host$ = Mid(URL$, 8, FindString(URL$, "/", 8) - 8)
 
  Page$ = "/" + GetURLPart(URL$, #PB_URL_Path)
  Parameter$ = GetURLPart(URL$, #PB_URL_Parameters)
  If Parameter$
    Page$ + "&" + Parameter$
  EndIf
 
  ;Debug Host$
 
  ConnectionID = OpenNetworkConnection(Host$, 80)
 
  If ConnectionID
   
    ;Build header
       
    Header$ = "GET " + Page$ + " HTTP/1.1" + #CRLF$
    Header$ + "Host: " + Host$ + #CRLF$
    ;Header$ + "Accept: text/html" + #CRLF$
    Header$ + "Content-Type: application/x-www-form-urlencoded" + #CRLF$   
    ;String$ + "Connection: close" + #CRLF$
    Header$ + #CRLF$
    ; header is finished
   
    ;Debug Header$
   

    SendNetworkString(ConnectionID, Header$)
    TimeOutCounter = 1000
    Repeat
      If NetworkClientEvent(ConnectionID) = #PB_NetworkEvent_Data
        Break
      EndIf
      Delay(10)
      TimeOutCounter -1
    Until TimeOutCounter = 0
   
    If TimeOutCounter <> 0
      #Size = 10000
      *HelpBuffer = AllocateMemory(#Size)
     
      If *HelpBuffer
        String$ = ""     
        Repeat
          HelpLength = ReceiveNetworkData(ConnectionID, *HelpBuffer, #Size)
          If HelpLength > 0
            *Buffer = ReAllocateMemory(*Buffer, Length + HelpLength)
            CopyMemory(*HelpBuffer, *Buffer + Length, HelpLength)
            Length + HelpLength
           
            ;Debug Length
           
            If Not HeaderFinished
              HeaderEndPos = FindString(PeekS(*Buffer), #CRLF$ + #CRLF$)
              If HeaderEndPos
                HeaderFinished = #True
                Pos = FindString(PeekS(*Buffer), "Content-Length:")
                If Pos
                  Size = Val(PeekS(*Buffer + Pos + 15)) + HeaderEndPos + 3
                  ;Debug Size
                EndIf
              EndIf
            EndIf
           
            ;String$ = PeekS(*HelpBuffer + HelpLength - 10, 10, #PB_UTF8)
            ;String$ + PeekS(*HelpBuffer, -1, #PB_UTF8)
            ;Debug String$
          EndIf
          If Size > 0
            If Length >= Size
              Received = #True
            EndIf
          Else
            If FindString(String$, "</html") > 0
              Received = #True
            EndIf
          EndIf
        Until Received
        FreeMemory(*HelpBuffer)
      EndIf
    EndIf
     
    CloseNetworkConnection(ConnectionID)
  EndIf
 
  ProcedureReturn *Buffer
 
EndProcedure




Define *Buffer, Size.i, HeaderPos.i, File.i

UseJPEGImageDecoder()
InitNetwork()

*Buffer = HTTPGet2Mem("http://dl.dropbox.com/u/76620573/Calculator.jar")
If *Buffer <> #Null
  Size = MemorySize(*Buffer)
 
  HeaderPos = FindString(PeekS(*Buffer, 1024), #CRLF$ + #CRLF$)
  
  File = CreateFile(#PB_Any, "c:\tmp\Calculator.jar")
  If File
    WriteData(File, *Buffer + HeaderPos + 3, Size - HeaderPos - 3)
    CloseFile(File)
  EndIf
  
  FreeMemory(*Buffer)
 
Else
  MessageRequester("Error", "Not downloaded")
EndIf
Bernd

P.S.: You have to adjust the receive directory (c:\tmp\...)
User avatar
Thorsten1867
Addict
Addict
Posts: 1372
Joined: Wed Aug 24, 2005 4:02 pm
Location: Germany

Re: Receive Dropbox file

Post by Thorsten1867 »

I've tried to code something for DropBox, but not all works as expected and I quit it.

Code: Select all

#AppKey = "" ; You must register your APP to get it.
#AppSecret = "" ; You must register your APP to get it.
#AccessType = "app_folder"
#NOnce = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

#API_REQUEST_TOKEN_URL="https://api.dropbox.com/1/oauth/request_token"
#API_USER_AUTH_URL="https://www2.dropbox.com/1/oauth/authorize"
#API_ACCESS_TOKEN_URL="https://api.dropbox.com/1/oauth/access_token"
#API_INFO_URL="https://api.dropbox.com/1/account/info"
#API_UPLOAD_URL="https://api-content.dropbox.com/1/files_put/sandbox"
#API_METADATA_URL="https://api.dropbox.com/1/metadata/sandbox"
#API_DOWNLOAD_URL="https://api-content.dropbox.com/1/files/sandbox"

Structure OAuthStructure
  Token.s
  Token_Secret.s
  Access_Token.s
  Access_Token_Secret.s
  Access_UID.s
  Time.s
EndStructure
Global OAuth.OAuthStructure

XIncludeFile "WinHTTP.pbi" ; => http://www.purebasic.fr/german/viewtopic.php?f=8&t=19078&hilit=winhttp&start=10

InitNetwork()

If WinHttp_LoadDLL() = #False ;{ WinHTTP einbinden
  MessageRequester(" WinHTTP", "Fehler beim Laden der DLL!", #MB_OK|#MB_ICONERROR)
  End
EndIf ;}


;- Window

; Konstanten ggf. für eigenes Programm anpassen
#Window_DropBox_Login = 1
#Gadget_DropBox_Login_WebGadget = 1

Procedure Window_UserAuthorization(url.s)
  If OpenWindow(#Window_DropBox_Login,82,191,1024,600," Anmelden bei Box.net",#PB_Window_SystemMenu|#PB_Window_ScreenCentered|#PB_Window_Invisible)
    WebGadget(#Gadget_DropBox_Login_WebGadget,0,0,1024,600,url)
    HideWindow(#Window_DropBox_Login,0)
    ProcedureReturn WindowID(#Window_DropBox_Login)
  EndIf
EndProcedure


;- Authentication

Procedure DropBox_WebAuthorization(OAuth_Token.s)
  If Window_UserAuthorization(#API_USER_AUTH_URL+"?oauth_token="+OAuth_Token)
    quitDropBox_Login=0
    Repeat 
      If WaitWindowEvent() = #PB_Event_CloseWindow
        If EventWindow()=#Window_DropBox_Login
          quitDropBox_Login=1
        EndIf
      EndIf
    Until quitDropBox_Login
    CloseWindow(#Window_DropBox_Login)
  EndIf
  ProcedureReturn #False
EndProcedure

Procedure DropBox_GetAuthentication()
  time$ = Str(Date())
  ; --- Step 1 ---
  result$ = ReceiveHTTPString(#API_REQUEST_TOKEN_URL+"?oauth_consumer_key="+#AppKey+"&oauth_signature_method=PLAINTEXT&oauth_signature="+#AppSecret+"%26&oauth_timestamp="+time$+"&oauth_nonce="+#NOnce, "POST")
  OAuth\Token = RemoveString(StringField(result$, 2, "&"), "oauth_token=")
  OAuth\Token_Secret = RemoveString(StringField(result$, 1, "&"), "oauth_token_secret=")
  ; --- Step 2 ---
  DropBox_WebAuthorization(OAuth\Token) ; WebInterface
  ; --- Step 3 ---
  result$ = ReceiveHTTPString(#API_ACCESS_TOKEN_URL+"?oauth_consumer_key="+#AppKey+"&oauth_token="+OAuth\Token+"&oauth_signature_method=PLAINTEXT&oauth_signature="+#AppSecret+"%26"+OAuth\Token_Secret+"&oauth_timestamp="+time$+"&oauth_nonce="+#NOnce, "POST")
  OAuth\Access_Token = RemoveString(StringField(result$, 2, "&"), "oauth_token=")
  OAuth\Access_Token_Secret = RemoveString(StringField(result$, 1, "&"), "oauth_token_secret=")
  OAuth\Access_UID = RemoveString(StringField(result$, 3, "&"), "uid=")
  ; --- Save Access Token ---
  If CreatePreferences("DropBox.ini")
    WritePreferenceString("Token", OAuth\Access_Token)
    WritePreferenceString("Token_Secret", OAuth\Access_Token_Secret) 
    WritePreferenceString("UID", OAuth\Access_UID)
    ClosePreferences()
  EndIf
EndProcedure

Procedure DropBox_LoadConfig()
  If OpenPreferences("DropBox.ini")
    OAuth\Access_Token = ReadPreferenceString("Token", "")
    OAuth\Access_Token_Secret = ReadPreferenceString("Token_Secret", "")
    OAuth\Access_UID = ReadPreferenceString("UID", "")
    OAuth\Time = Str(Date())
    ClosePreferences()
  EndIf 
EndProcedure


;- Access DropBox 

Procedure.s DropBox_GetAccountInfo()
  ProcedureReturn ReceiveHTTPString(#API_INFO_URL+"?oauth_consumer_key="+#AppKey+"&oauth_token="+OAuth\Access_Token+"&oauth_signature_method=PLAINTEXT&oauth_signature="+#AppSecret+"%26"+OAuth\Access_Token_Secret+"&oauth_timestamp="+OAuth\Time+"&oauth_nonce="+#NOnce, "GET")
EndProcedure

Procedure DropBox_Upload(File$)
  param$ = "-k -s --show-error -i -o "+Chr(34)+"Upload.json"+Chr(34)+" --upload-File "+Chr(34)+File$+Chr(34)+" "+Chr(34)+#API_UPLOAD_URL+"?oauth_consumer_key="+#AppKey+"&OAuth_Token="+OAuth\Access_Token+"&oauth_signature_method=PLAINTEXT&oauth_signature="+#AppSecret+"%26"+OAuth\Access_Token_Secret+"&oauth_timestamp="+OAuth\Time+"&oauth_nonce="+#NOnce+Chr(34)
  RunPrg = RunProgram("curl.exe", param$, "", #PB_Program_Open|#PB_Program_Hide)
  If RunPrg
    WaitProgram(RunPrg, 30000) ; max. 30s warten
    If ProgramRunning(RunPrg) = #False 
      ExitCode = ProgramExitCode(RunPrg)
    EndIf
    CloseProgram(RunPrg)
  EndIf
  ProcedureReturn ExitCode
EndProcedure

Procedure DropBox_Download(FileSCR$, FileDST$)
  param$ = "-k -s --show-error -D "+Chr(34)+"Download.json"+Chr(34)+" -o "+Chr(34)+FileDST$+Chr(34)+" "+Chr(34)+#API_DOWNLOAD_URL+"/"+FileSCR$+"?oauth_consumer_key="+#AppKey+"&OAuth_Token="+OAuth\Access_Token+"&oauth_signature_method=PLAINTEXT&oauth_signature="+#AppSecret+"%26"+OAuth\Access_Token_Secret+"&oauth_timestamp="+OAuth\Time+"&oauth_nonce="+#NOnce+Chr(34)
  RunPrg = RunProgram("curl.exe", param$, "", #PB_Program_Open|#PB_Program_Hide)
  If RunPrg
    WaitProgram(RunPrg, 20000) ; max. 20s warten
    If ProgramRunning(RunPrg) = #False 
      ExitCode = ProgramExitCode(RunPrg)
    EndIf
    CloseProgram(RunPrg)
  EndIf
  ProcedureReturn ExitCode
EndProcedure

Procedure.s DropBox_ListDir()
  ProcedureReturn ReceiveHTTPString(#API_METADATA_URL+"?oauth_consumer_key="+#AppKey+"&OAuth_Token="+OAuth\Access_Token+"&oauth_signature_method=PLAINTEXT&oauth_signature="+#AppSecret+"%26"+OAuth\Access_Token_Secret+"&oauth_timestamp="+OAuth\Time+"&oauth_nonce="+#NOnce, "GET")
EndProcedure

;- ---- Test ---

DropBox_GetAuthentication()
DropBox_LoadConfig()
Debug DropBox_GetAccountInfo()
File$ = "E:\Temp\Zeugnis.xml"
;Debug DropBox_Upload(File$)
Debug DropBox_ListDir()
Debug DropBox_Download("Zeugnis.xml", File$)
Translated with http://www.DeepL.com/Translator

Download of PureBasic - Modules
Download of PureBasic - Programs

[Windows 11 x64] [PB V5.7x]
User avatar
J@ckWhiteIII
Enthusiast
Enthusiast
Posts: 183
Joined: Fri May 25, 2012 7:39 pm

Re: Receive Dropbox file

Post by J@ckWhiteIII »

Wow, thank you guys for your code! infratec's code worked for me, it was all correct! Thank you so much.
I'm going to look over your code, Thorsten1867, as soon as I've finished my launcher.
Once again, thank you!
User avatar
J@ckWhiteIII
Enthusiast
Enthusiast
Posts: 183
Joined: Fri May 25, 2012 7:39 pm

Re: Receive Dropbox file

Post by J@ckWhiteIII »

I have to ask again. My App worked for some days, but now I tried it once again..and the app just freezes when you click update.
Here the code (you'll have to commen out the Datasection and image stuff):

Code: Select all

InitNetwork()
UseJPEGImageDecoder()
UsePNGImageDecoder()

Global hwnd.i = OpenWindow(#PB_Any,0,0,300,200,"Minification Calc Launcher",#PB_Window_ScreenCentered|#PB_Window_SystemMenu)
Global updateButton.i = ButtonGadget (#PB_Any,215,140,80,20,"Update")
Global startButton.i = ButtonGadget (#PB_Any,215,170,80,20,"Launch!")
Global img.i = ImageGadget(#PB_Any,0,0,300,80,CatchImage(0,?LaunchPic))
Global webGadget = HyperLinkGadget(#PB_Any,7,180,120,15,"thecodingproject.bplaced.net",RGB(255,0,0))
Global we.i
Define *Buffer, Size.i, HeaderPos.i, File.i
Declare downloadFile(filename$)

Procedure.i checkFile(Directory$)
  If ExamineDirectory(0, Directory$, "*.jar")  
    While NextDirectoryEntry(0)
      If DirectoryEntryType(0) = #PB_DirectoryEntry_File
        Type$ = DirectoryEntryName(0)
        If Type$ = "Calculator.jar"
          If(DirectoryEntrySize(0))
            FinishDirectory(0)
            ProcedureReturn 1
          EndIf
        EndIf
      EndIf
    Wend
    FinishDirectory(0)
  EndIf
  ProcedureReturn 0
EndProcedure

Procedure CheckGadgets(we)
  
  Select we
    Case updateButton
      downloadFile("http://dl.dropbox.com/u/76620573/Calculator.jar")
      If checkFile("")
        RunProgram("javaw","-jar Calculator.jar","")
      EndIf
      End
    Case startButton
      If checkFile("")
        RunProgram("javaw","-jar Calculator.jar","")
      EndIf
      End
    Case webGadget
      RunProgram("http://www.thecodingproject.bplaced.net")
  EndSelect
  
EndProcedure

Repeat
  we = WindowEvent ()
  Select we
    Case #PB_Event_Gadget
      CheckGadgets(EventGadget())
  EndSelect
Until we = #PB_Event_CloseWindow

Procedure.i HTTPGet2Mem(URL$)
 
  Protected.i ConnectionID, TimeOutCounter, Laenge, Pos, Received, HelpLength, Length, HeaderEndPos, HeaderFinished, Size
  Protected Server$, Header$, String$, Result$, Page$, Parameter$, Host$, *Buffer, *HelpBuffer
 
 
  If LCase(Left(URL$, 7)) <> "http://"
    URL$ = "http://" + URL$
  EndIf
 
  ;Host$ = GetURLPart(URL$, #PB_URL_Site)
 
  Host$ = Mid(URL$, 8, FindString(URL$, "/", 8) - 8)
 
  Page$ = "/" + GetURLPart(URL$, #PB_URL_Path)
  Parameter$ = GetURLPart(URL$, #PB_URL_Parameters)
  If Parameter$
    Page$ + "&" + Parameter$
  EndIf
 
  ;Debug Host$
 
  ConnectionID = OpenNetworkConnection(Host$, 80)
 
  If ConnectionID
   
    ;Build header
       
    Header$ = "GET " + Page$ + " HTTP/1.1" + #CRLF$
    Header$ + "Host: " + Host$ + #CRLF$
    ;Header$ + "Accept: text/html" + #CRLF$
    Header$ + "Content-Type: application/x-www-form-urlencoded" + #CRLF$   
    ;String$ + "Connection: close" + #CRLF$
    Header$ + #CRLF$
    ; header is finished
   
    ;Debug Header$
   

    SendNetworkString(ConnectionID, Header$)
    TimeOutCounter = 1000
    Repeat
      If NetworkClientEvent(ConnectionID) = #PB_NetworkEvent_Data
        Break
      EndIf
      Delay(10)
      TimeOutCounter -1
    Until TimeOutCounter = 0
   
    If TimeOutCounter <> 0
      #Size = 10000
      *HelpBuffer = AllocateMemory(#Size)
     
      If *HelpBuffer
        String$ = ""     
        Repeat
          
          HelpLength = ReceiveNetworkData(ConnectionID, *HelpBuffer, #Size)
          If HelpLength > 0
            *Buffer = ReAllocateMemory(*Buffer, Length + HelpLength)
            CopyMemory(*HelpBuffer, *Buffer + Length, HelpLength)
            Length + HelpLength
           
            ;Debug Length
           
            If Not HeaderFinished
              HeaderEndPos = FindString(PeekS(*Buffer), #CRLF$ + #CRLF$)
              If HeaderEndPos
                HeaderFinished = #True
                Pos = FindString(PeekS(*Buffer), "Content-Length:")
                ;Debug Pos is zero!
                If Pos
                  Size = Val(PeekS(*Buffer + Pos + 15)) + HeaderEndPos + 3
                  ;Debug Size
                EndIf
              EndIf
            EndIf
           
            ;String$ = PeekS(*HelpBuffer + HelpLength - 10, 10, #PB_UTF8)
            ;String$ + PeekS(*HelpBuffer, -1, #PB_UTF8)
            ;Debug String$
          EndIf
          If Size > 0
            If Length >= Size
              Received = #True
            EndIf
          Else
            If FindString(String$, "</html") > 0
              Received = #True
            EndIf
          EndIf
        Until Received
        ;is never reached
        FreeMemory(*HelpBuffer)
      EndIf
    EndIf
     
    CloseNetworkConnection(ConnectionID)
  EndIf
 
  ProcedureReturn *Buffer
 
EndProcedure

Procedure downloadFile(filename$)
  
  *Buffer = HTTPGet2Mem(filename$)
If *Buffer <> #Null
  Size = MemorySize(*Buffer)
 
  HeaderPos = FindString(PeekS(*Buffer, 1024), #CRLF$ + #CRLF$)
  
  File = CreateFile(#PB_Any, "Calculator.jar")
  
  If File
    WriteData(File, *Buffer + HeaderPos + 3, Size - HeaderPos - 3)
    CloseFile(File)
  EndIf
  
  FreeMemory(*Buffer)
 
Else
  MessageRequester("Error", "Not downloaded")
EndIf
  
EndProcedure

DataSection
  LaunchPic:IncludeBinary "C:\Users\Marius\Pictures\MinificationLauncher.png"
EndDataSection
It seems like it freezes in the "header" part, but I really do not know why. As I said, I haven't changed the code after it worked..
I hope you can help me.
Thank you in advance
infratec
Always Here
Always Here
Posts: 7582
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Receive Dropbox file

Post by infratec »

Hi,

if you had a look into the receive buffer you had noticed that the server wanted to redirect you.
use:

Code: Select all

downloadFile("http://dl.dropboxusercontent.com/u/76620573/Calculator.jar")
and it works again.

Bernd
infratec
Always Here
Always Here
Posts: 7582
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Receive Dropbox file

Post by infratec »

Hi,

an other 'quick hack':

I implemented the redirection:

Code: Select all

InitNetwork()

Global hwnd.i = OpenWindow(#PB_Any,0,0,300,200,"Minification Calc Launcher",#PB_Window_ScreenCentered|#PB_Window_SystemMenu)
Global updateButton.i = ButtonGadget (#PB_Any,215,140,80,20,"Update")
Global startButton.i = ButtonGadget (#PB_Any,215,170,80,20,"Launch!")

Global webGadget = HyperLinkGadget(#PB_Any,7,180,120,15,"thecodingproject.bplaced.net",RGB(255,0,0))
Global we.i
Define *Buffer, Size.i, HeaderPos.i, File.i
Declare downloadFile(filename$)

Procedure.i checkFile(Directory$)
  If ExamineDirectory(0, Directory$, "*.jar") 
    While NextDirectoryEntry(0)
      If DirectoryEntryType(0) = #PB_DirectoryEntry_File
        Type$ = DirectoryEntryName(0)
        If Type$ = "Calculator.jar"
          If(DirectoryEntrySize(0))
            FinishDirectory(0)
            ProcedureReturn 1
          EndIf
        EndIf
      EndIf
    Wend
    FinishDirectory(0)
  EndIf
  ProcedureReturn 0
EndProcedure

Procedure CheckGadgets(we)
 
  Select we
    Case updateButton
      ;downloadFile("http://dl.dropboxusercontent.com/u/76620573/Calculator.jar")
      downloadFile("http://dl.dropbox.com/u/76620573/Calculator.jar")
      If checkFile("")
        RunProgram("javaw","-jar Calculator.jar","")
      EndIf
      End
    Case startButton
      If checkFile("")
        RunProgram("javaw","-jar Calculator.jar","")
      EndIf
      End
    Case webGadget
      RunProgram("http://www.thecodingproject.bplaced.net")
  EndSelect
 
EndProcedure

Repeat
  we = WindowEvent ()
  Select we
    Case #PB_Event_Gadget
      CheckGadgets(EventGadget())
  EndSelect
Until we = #PB_Event_CloseWindow

Procedure.i HTTPGet2Mem(URL$)
 
  Protected.i ConnectionID, TimeOutCounter, Laenge, Pos, Received, HelpLength, Length, HeaderEndPos, HeaderFinished, Size
  Protected Server$, Header$, String$, Result$, Page$, Parameter$, Host$, *Buffer, *HelpBuffer, Location$
 
 
  If LCase(Left(URL$, 7)) <> "http://"
    URL$ = "http://" + URL$
  EndIf
 
  ;Host$ = GetURLPart(URL$, #PB_URL_Site)
 
  Host$ = Mid(URL$, 8, FindString(URL$, "/", 8) - 8)
 
  Page$ = "/" + GetURLPart(URL$, #PB_URL_Path)
  Parameter$ = GetURLPart(URL$, #PB_URL_Parameters)
  If Parameter$
    Page$ + "&" + Parameter$
  EndIf
 
  ;Debug Host$
 
  ConnectionID = OpenNetworkConnection(Host$, 80)
 
  If ConnectionID
   
    ;Build header
       
    Header$ = "GET " + Page$ + " HTTP/1.1" + #CRLF$
    Header$ + "Host: " + Host$ + #CRLF$
    ;Header$ + "Accept: text/html" + #CRLF$
    Header$ + "Content-Type: application/x-www-form-urlencoded" + #CRLF$   
    ;String$ + "Connection: close" + #CRLF$
    Header$ + #CRLF$
    ; header is finished
   
    ;Debug Header$
   

    SendNetworkString(ConnectionID, Header$)
    TimeOutCounter = 1000
    Repeat
      If NetworkClientEvent(ConnectionID) = #PB_NetworkEvent_Data
        Break
      EndIf
      Delay(10)
      TimeOutCounter -1
    Until TimeOutCounter = 0
   
    If TimeOutCounter <> 0
      #Size = 10000
      *HelpBuffer = AllocateMemory(#Size)
     
      If *HelpBuffer
        String$ = ""     
        Repeat
         
          HelpLength = ReceiveNetworkData(ConnectionID, *HelpBuffer, #Size)
          If HelpLength > 0
            *Buffer = ReAllocateMemory(*Buffer, Length + HelpLength)
            CopyMemory(*HelpBuffer, *Buffer + Length, HelpLength)
            Length + HelpLength
           
            ;Debug Length
           
            If Not HeaderFinished
              HeaderEndPos = FindString(PeekS(*Buffer), #CRLF$ + #CRLF$)
              If HeaderEndPos
                Header$ = PeekS(*Buffer, HeaderEndPos)
                HeaderFinished = #True
                Pos = FindString(Header$, "Content-Length:")
                ;Debug Pos is zero!
                If Pos
                  ;Size = Val(PeekS(*Buffer + Pos + 15)) + HeaderEndPos + 3
                  Size = Val(Mid(Header$, Pos + 15))
                  Debug Size
                EndIf
                
                Pos = FindString(Header$, "302")
                If Pos                  
                  Pos = FindString(Header$, "Location:")
                  If Pos
                    Location$ = Mid(Header$, Pos + 10, FindString(Header$, #CRLF$, Pos + 10) - (Pos + 10))
                    Debug Location$
                    *Buffer = ReAllocateMemory(*Buffer, Len(Location$) + 1)
                    PokeS(*Buffer, Location$)
                    Received = #True
                  EndIf
                EndIf
                
              EndIf
            EndIf
           
            ;String$ = PeekS(*HelpBuffer + HelpLength - 10, 10, #PB_UTF8)
            ;String$ + PeekS(*HelpBuffer, -1, #PB_UTF8)
            ;Debug String$
          EndIf
          If Size > 0
            If Length >= Size
              Received = #True
            EndIf
          Else
            If FindString(String$, "</html") > 0
              Received = #True
            EndIf
          EndIf
        Until Received
        ;is never reached
        FreeMemory(*HelpBuffer)
      EndIf
    EndIf
     
    CloseNetworkConnection(ConnectionID)
  EndIf
 
  ProcedureReturn *Buffer
 
EndProcedure

Procedure downloadFile(filename$)
  
  While Len(filename$)
    *Buffer = HTTPGet2Mem(filename$)
    If *Buffer <> #Null
      Size = MemorySize(*Buffer)
      
      HeaderPos = FindString(PeekS(*Buffer, 1024), #CRLF$ + #CRLF$)
      If HeaderPos
        File = CreateFile(#PB_Any, "Calculator.jar")
        
        If File
          WriteData(File, *Buffer + HeaderPos + 3, Size - HeaderPos - 3)
          CloseFile(File)
        EndIf
        filename$ = ""
      Else
        filename$ = PeekS(*Buffer)
      EndIf
      FreeMemory(*Buffer)
    Else
      MessageRequester("Error", "Not downloaded")
      filename$ = ""
    EndIf
  Wend
 
EndProcedure
Now you are more 'save' :mrgreen:

Bernd
infratec
Always Here
Always Here
Posts: 7582
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Receive Dropbox file

Post by infratec »

If you want todo something for the community:

put the loop for redirection inside of HTTPGet2Mem(URL$)

Bernd
infratec
Always Here
Always Here
Posts: 7582
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Receive Dropbox file

Post by infratec »

Since I had a bit time:

HTTPGet2Mem() now with included redirect:

Code: Select all

InitNetwork()

Global hwnd.i = OpenWindow(#PB_Any,0,0,300,200,"Minification Calc Launcher",#PB_Window_ScreenCentered|#PB_Window_SystemMenu)
Global updateButton.i = ButtonGadget (#PB_Any,215,140,80,20,"Update")
Global startButton.i = ButtonGadget (#PB_Any,215,170,80,20,"Launch!")

Global webGadget = HyperLinkGadget(#PB_Any,7,180,120,15,"thecodingproject.bplaced.net",RGB(255,0,0))
Global we.i
Define *Buffer, Size.i, HeaderPos.i, File.i
Declare downloadFile(filename$)

Procedure.i checkFile(Directory$)
  If ExamineDirectory(0, Directory$, "*.jar") 
    While NextDirectoryEntry(0)
      If DirectoryEntryType(0) = #PB_DirectoryEntry_File
        Type$ = DirectoryEntryName(0)
        If Type$ = "Calculator.jar"
          If(DirectoryEntrySize(0))
            FinishDirectory(0)
            ProcedureReturn 1
          EndIf
        EndIf
      EndIf
    Wend
    FinishDirectory(0)
  EndIf
  ProcedureReturn 0
EndProcedure

Procedure CheckGadgets(we)
 
  Select we
    Case updateButton
      ;downloadFile("http://dl.dropboxusercontent.com/u/76620573/Calculator.jar")
      downloadFile("http://dl.dropbox.com/u/76620573/Calculator.jar")
      If checkFile("")
        RunProgram("javaw","-jar Calculator.jar","")
      EndIf
      End
    Case startButton
      If checkFile("")
        RunProgram("javaw","-jar Calculator.jar","")
      EndIf
      End
    Case webGadget
      RunProgram("http://www.thecodingproject.bplaced.net")
  EndSelect
 
EndProcedure

Repeat
  we = WindowEvent ()
  Select we
    Case #PB_Event_Gadget
      CheckGadgets(EventGadget())
  EndSelect
Until we = #PB_Event_CloseWindow



Procedure.i HTTPGet2Mem(URL$)
 
  Protected.i ConnectionID, TimeOutCounter, Pos, Received, HelpLength
  Protected.i Length, HeaderEndPos, HeaderFinished, Size, Redirect
  Protected Server$, Header$, Result$, Page$, Parameter$, Host$, *Buffer, *HelpBuffer, Location$, HeaderLCase$
 
 
  Repeat
   
    HeaderFinished = #False
    Redirect = #False
    Length = 0
    *Buffer = #Null
    Received = #False
    
    If LCase(Left(URL$, 6)) = "https:"
      Break
    EndIf
    
    If LCase(Left(URL$, 4)) <> "http"
      URL$ = "http://" + URL$
    EndIf
    
    ;Host$ = GetURLPart(URL$, #PB_URL_Site)
   
    Host$ = Mid(URL$, 8, FindString(URL$, "/", 8) - 8)
   
    Page$ = "/" + GetURLPart(URL$, #PB_URL_Path)
    Parameter$ = GetURLPart(URL$, #PB_URL_Parameters)
    If Parameter$
      Page$ + "&" + Parameter$
    EndIf
    ;Debug Host$
   
    ConnectionID = OpenNetworkConnection(Host$, 80)
   
    If ConnectionID
     
      ;Build header
      Header$ = "GET " + Page$ + " HTTP/1.1" + #CRLF$
      Header$ + "Host: " + Host$ + #CRLF$
      ;Header$ + "Accept: text/html" + #CRLF$
      Header$ + "Content-Type: application/x-www-form-urlencoded" + #CRLF$   
      Header$ + #CRLF$
      ; header is finished
      ;Debug Header$
     
      SendNetworkString(ConnectionID, Header$)
      TimeOutCounter = 1000
      Repeat
        If NetworkClientEvent(ConnectionID) = #PB_NetworkEvent_Data
          Break
        EndIf
        Delay(10)
        TimeOutCounter -1
      Until TimeOutCounter = 0
     
      If TimeOutCounter <> 0
        #Size = 10000
        *HelpBuffer = AllocateMemory(#Size)
       
        If *HelpBuffer
          Repeat
           
            HelpLength = ReceiveNetworkData(ConnectionID, *HelpBuffer, #Size)
            If HelpLength > 0
              If *Buffer = #Null
                *Buffer = AllocateMemory(Length + HelpLength)
              Else
                *Buffer = ReAllocateMemory(*Buffer, Length + HelpLength)
              EndIf
              CopyMemory(*HelpBuffer, *Buffer + Length, HelpLength)
              Length + HelpLength
             
              ;Debug Length
             
              If Not HeaderFinished
                HeaderEndPos = FindString(PeekS(*Buffer), #CRLF$ + #CRLF$)
                If HeaderEndPos
                  Header$ = PeekS(*Buffer, HeaderEndPos)
                  HeaderLCase$ = LCase(Header$)
                  HeaderFinished = #True
                 
                  Pos = FindString(HeaderLCase$, "content-length:")
                  ;Debug Pos is zero!
                  If Pos
                    ;Size = Val(PeekS(*Buffer + Pos + 15)) + HeaderEndPos + 3
                    Size = Val(Mid(Header$, Pos + 15))
                    Debug "Size: " + Str(Size)
                  EndIf
                 
                  Pos = FindString(Header$, "302")
                  If Pos                 
                    Pos = FindString(HeaderLCase$, "location:")
                    If Pos
                      Debug "Redirect"
                      URL$ = Mid(Header$, Pos + 10, FindString(Header$, #CRLF$, Pos + 10) - (Pos + 10))
                      FreeMemory(*Buffer)                     
                      Redirect = #True
                      Received = #True
                    EndIf
                  EndIf
                 
                EndIf
              EndIf
             
            EndIf
            If Size > 0
              If Length >= Size + HeaderEndPos + 3
                Received = #True
              EndIf
            Else
              If Length > 20
                If FindString(PeekS(*Buffer + Length - 20, 20), "</html") > 0
                  Received = #True
                EndIf
              EndIf
            EndIf
          Until Received
          FreeMemory(*HelpBuffer)
        EndIf
      EndIf
     
      CloseNetworkConnection(ConnectionID)
    EndIf
   
  Until Redirect = #False
 
  ProcedureReturn *Buffer
 
EndProcedure



Procedure downloadFile(filename$)
    
  *Buffer = HTTPGet2Mem(filename$)
  If *Buffer
    Size = MemorySize(*Buffer)
    
    HeaderPos = FindString(PeekS(*Buffer, 1024), #CRLF$ + #CRLF$)
    If HeaderPos
      File = CreateFile(#PB_Any, "c:\tmp\Calculator.jar")
      
      If File
        WriteData(File, *Buffer + HeaderPos + 3, Size - HeaderPos - 3)
        CloseFile(File)
      EndIf
      
    EndIf
    FreeMemory(*Buffer)
  Else
    MessageRequester("Error", "Not downloaded")
    filename$ = ""
  EndIf
 
EndProcedure
Bernd
Last edited by infratec on Wed Sep 17, 2014 10:59 am, edited 1 time in total.
User avatar
J@ckWhiteIII
Enthusiast
Enthusiast
Posts: 183
Joined: Fri May 25, 2012 7:39 pm

Re: Receive Dropbox file

Post by J@ckWhiteIII »

This works, thank you a lot for that!

I still do not understand what was the problem, though. Your first code was "...dl.dropbox.com/..." and it worked. In this new version, you used "...dl.dropboxusercontent.com/...". What difference did that make and why did the other URL worl before?

Again, thank you so much.
infratec
Always Here
Always Here
Posts: 7582
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: Receive Dropbox file

Post by infratec »

Hi,

it's simple:

They gave you a link for the download.
This one was working up to the point when they moved your file to an other server.
The old link is still working, but you are redirected to the new loaction.
Normally, if you use a web-browser, you didn't notice that, because the browser follows this redirection.
The first handmade version of HTTPGet did not follow this redirection.
So you needed the new location directly.
Than I programmed a workaround: HTTPGet2Mem() returned the new location.

Than, as ultimate solution, I included the redirection stuff into HTTPGet2Mem().

That's all,

Bernd
User avatar
J@ckWhiteIII
Enthusiast
Enthusiast
Posts: 183
Joined: Fri May 25, 2012 7:39 pm

Re: Receive Dropbox file

Post by J@ckWhiteIII »

Oooohhhhh, now it all makes sense! Very simple, indeed. You only need to know about this, which I didn't.
Thank you for telling me and explaining.
Regards, Marius
spacewalker
User
User
Posts: 19
Joined: Tue Apr 27, 2010 4:35 pm
Location: Germany

Re: Receive Dropbox file

Post by spacewalker »

Since I had a bit time:
HTTPGet2Mem() now with included redirect:
Hello,

this is an old thread but it covers exactly what I need (download a file from Dropbox)
The download link in the sourcode works in my browser, I can download the file.

But the code (HTTPGet2Mem() with redirect) doesn't work... what I see is that in HTTPGet2Mem() the result for HelpLength = ReceiveNetworkData(ConnectionID, *HelpBuffer, #Size) is always 0
So it seems to be a problem within ReceiveNetworkData() ?

The header that is built by the code looks like this:

Header=GET /u/76620573/Calculator.jar HTTP/1.1
Host: dl.dropbox.com
Content-Type: application/x-www-form-urlencoded


I use PB 5.30 32Bit with Windows2008

So maybe somebody knows how I could make this work
Thank you
Post Reply