Geturl.zip erreur help svp [update]

Vous débutez et vous avez besoin d'aide ? N'hésitez pas à poser vos questions
Avatar de l’utilisateur
Le psychopathe
Messages : 764
Inscription : jeu. 03/mars/2005 19:23

Geturl.zip erreur help svp [update]

Message par Le psychopathe »

Voilà j'ai un petit problème. Je comprends pas une source pure.
Elle est assez compliquée et comme je suis pas encore niveau moyen moyen en pure...

Sinon en compilant vous comprendrez que c'est un programme qui télécharge des fichiers sur le web avec une barre de progression.

Quelqu'un pourrait t-il l'expliquer ?
C'est assez long

Code : Tout sélectionner

; --------------------------------------------------------- 
; Backrgound downloading with UrlDownloadToFile_() 
; Tutorial for creating a COM object with PB 
; 
; 10/09/2003 by Timo 'Fr34k' Harter 
; http://freak.purearea.net 
; --------------------------------------------------------- 
; 
; First, I want to say, that not everything here came from 
; my mind, i had some input from a C++ program found here: 
; http://www.codeproject.com/internet/urlfile.asp 
; 
; This tutorial is a complete PB executable, that can be executed 
; as it is, with hopefully enough comments for you to understand. 
; 
; Intro: 
; Ok, much people know the UrlDownloadToFile_() Api, which is 
; a very comfortable way to download a file, because you don't 
; have to worry about the protocol you use, and reading headers 
; and stuff with raw network commands. 
; Now the problem with that command was, no easy way display the 
; status of the download operation. This is possible by creating 
; an own IBindStatusCallback Interface to handle this. Now actually 
; you don't need any of PB's new Interface stuff to do this, as you 
; can see in this code. Only till now i didn't have the knowledge how 
; to do this. 
; I will show here, how to create an object with a IBindStatusCallback 
; Interface, and how to do a nice background downloaading with that. 
; 
; But that is unfortunately not all. UrlDownloadToFile_() stops the 
; program flow, till the download is done, and we need a way around 
; that. To do this, we put the function in a seperate thread. The 
; problem then is, that the methods of our IBindStatusCallback 
; Interface are then also called in this thread's conext, and so we 
; can't update our user interface from there, as it is in a different 
; thread. So, in order to communicate between the threads, we use 
; SendMessage_() and send 2 userdefined messages. 
; 
; To get more info on UrlDownLoadToFile_(), go here: 
; http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wceurlmn/html/cerefurldownloadtofile.asp 
; 
; Read more about the IBindStatusCallback Interface here: 
; http://msdn.microsoft.com/library/default.asp?url=/library/en-us/guide_ppc/htm/urlmon1_rgqn.asp 
; 
; So much for the general way this program functions, let's get started... 
; 
; --------------------------------------------------------- 


; These Global variables are used by the thread to start the download, and 
; to post the messages, so they may only be manipulated BEFORE a download is 
; started, changing them while a download is running may have unexpected 
; results (most likely a crash) 
Global Url.s, SaveTo.s, MainWindow.l 
; Url is the Source address. May be something like "www.purebasic.com" or a direct file. 
; SaveTo is the target filename on disk 
; MainWindow is a WindowID() of an open Window, where the messages will be sent to 

; This value is Global, but not used from the thread. We use it to indicate, that 
; the download should be aborted (if it is #TRUE) 
Global Abort.l 

; This structure is used to communicate between the thread and the WindowCallback 
Structure ProgressData 
  Progress.l    ; bytes downloaded 
  ProgressMax.l ; bytes total (this value might change during the download) 
  StatusCode.l  ; A code indicating what is happening 
EndStructure 

Structure IID  ; Interface Identifier structure. a IID is a 16byte value, that uniquely 
  Data1.l       ; identifys each interface. 
  Data2.w 
  Data3.w 
  Data4.b[8] 
EndStructure 

; Now these are the 2 messages we send. One to indicate a progress status 
; and one to inbdicate the download end. Values above #WM_USER are free for use 
; inside programs. 
#WM_DOWNLOADPROGRESS = #WM_USER + 1 
#WM_DOWNLOADEND      = #WM_USER + 2 

; these are the values that StatusCode.l of the ProgressData Structure might get. 
; Note: as IBindStatusCallback can also be used for other things than downloads, 
; some of these values may never occur with UrlDownloadToFile_() 
; Go here for more info on those values: 
; http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wceurlmn/html/cerefBINDSTATUS.asp 
Enumeration 1 
  #BINDSTATUS_FINDINGRESOURCE 
  #BINDSTATUS_CONNECTING 
  #BINDSTATUS_REDIRECTING 
  #BINDSTATUS_BEGINDOWNLOADDATA 
  #BINDSTATUS_DOWNLOADINGDATA 
  #BINDSTATUS_ENDDOWNLOADDATA 
  #BINDSTATUS_BEGINDOWNLOADCOMPONENTS 
  #BINDSTATUS_INSTALLINGCOMPONENTS 
  #BINDSTATUS_ENDDOWNLOADCOMPONENTS 
  #BINDSTATUS_USINGCACHEDCOPY 
  #BINDSTATUS_SENDINGREQUEST 
  #BINDSTATUS_CLASSIDAVAILABLE 
  #BINDSTATUS_MIMETYPEAVAILABLE 
  #BINDSTATUS_CACHEFILENAMEAVAILABLE 
  #BINDSTATUS_BEGINSYNCOPERATION 
  #BINDSTATUS_ENDSYNCOPERATION 
  #BINDSTATUS_BEGINUPLOADDATA 
  #BINDSTATUS_UPLOADINGDATA 
  #BINDSTATUS_ENDUPLOADINGDATA 
  #BINDSTATUS_PROTOCOLCLASSID 
  #BINDSTATUS_ENCODING 
  #BINDSTATUS_VERFIEDMIMETYPEAVAILABLE 
  #BINDSTATUS_CLASSINSTALLLOCATION 
  #BINDSTATUS_DECODING 
  #BINDSTATUS_LOADINGMIMEHANDLER 
  #BINDSTATUS_CONTENTDISPOSITIONATTACH 
  #BINDSTATUS_FILTERREPORTMIMETYPE 
  #BINDSTATUS_CLSIDCANINSTANTIATE 
  #BINDSTATUS_IUNKNOWNAVAILABLE 
  #BINDSTATUS_DIRECTBIND 
  #BINDSTATUS_RAWMIMETYPE 
  #BINDSTATUS_PROXYDETECTING 
  #BINDSTATUS_ACCEPTRANGES 
EndEnumeration 

; --------------------------------------------------------- 
; StatusObject 
; --------------------------------------------------------- 

; Ok, now we implement our IBindStatusCallback Interface. The 
; object we create it in i call 'StatusObject'. 
; 
; Let's first discuss how such an object looks like. Basically, it 
; is a structure containing pointers to other structures (which represent 
; the interfaces), which themselves contain pointers To functions. 
; (which are the methods of this interface) 
; 
; It is not as complicated as it sounds, let's take it step by step: 
; First we need to know how the Interface we want looks like. There will 
; be a comfortable InterfaceViewer soon, but for now, you have to peek in 
; in the *.pb files at http://cvs.purebasic.com (/Residents/Windows/Interface) 
; The important thing is to get the order of the methods right (methods are 
; simply the functions of a interface) 
; 
; IBindStatusCallback looks like this: 
; 
; Interface IBindStatusCallback 
;   QueryInterface(a.l, b.l) 
;   AddRef() 
;   Release() 
;   OnStartBinding(a.l, b.l) 
;   GetPriority(a.l) 
;   OnLowResource(a.l) 
;   OnProgress(a.l, b.l, c.l, d.l) 
;   OnStopBinding(a.l, b.l) 
;   GetBindInfo(a.l, b.l) 
;   OnDataAvailable(a.l, b.l, c.l, d.l) 
;   OnObjectAvailable(a.l, b.l) 
; EndInterface 

; Now first, we need a Structure, that can hold pointers to all our 
; functions for this interface, this looks almost the same then: 

Structure IBindStatusCallback_Functions 
  QueryInterface.l 
  AddRef.l 
  Release.l 
  OnStartBinding.l 
  GetPriority.l 
  OnLowResource.l 
  OnProgress.l 
  OnStopBinding.l 
  GetBindInfo.l 
  OnDataAvailable.l 
  OnObjectAvailable.l 
EndStructure 

; let's make a structured variable out of it. We will fill the pointers in, 
; after we created the functions. 
IBindStatusCallback_Functions.IBindStatusCallback_Functions 

; This is called the Virtual Table, it is where the caller to our Interface 
; will find the addresses of the method (function) he want's to call. 

; Now an interface is always part of an object. An object can contain multiple 
; interfaces, or just one. The object is again a structure, that then contains 
; the pointer to the virtual table of our interface: 

Structure StatusObject 
  *IBindStatusCallback.IBindStatusCallback_Functions 
EndStructure 

; We have only one interface in there. Well actually 2, because IBindStatusCallback 
; has the IUnknown interface inside. The structure can also hold extra data fields, 
; that our functions can access to store data for this object, but we don't need 
; that now. 

; Let's make also a structured variable for our object. We can pass the pointer to 
; that variable to everybody who want's to call our interface then. It has to be 
; Global, so it is also known inside the thread. 
Global StatusObject.StatusObject 

; set the pointer to the virtual table of our interface: 
StatusObject\IBindStatusCallback = IBindStatusCallback_Functions 

; --------------------------------------------------------- 

; Now we can create the methods for our interface. 
; Note: It is quite simple: We create one Procedure for each method, with the 
; arguments the method needs (look at the description of the Interface), with the 
; only addition that each Procedure has a *THIS.MyObject pointer as first value. 
; There it always get's the pointer to the object on which it is called. In the 
; documentation by MS for eaxample, this is never mentioned, because in other 
; languages, this parameter is hidden, but it is always there. 
; For what the method should do and return, see the documentation. 


; QueryInterface is a method that comes from the IUnknown interface, and is called, 
; in order to get different interfaces on one object. We need to check the IID that 
; is provided, and return the right pointer. As we only have one Interface with 
; an IUnknown inside, this is quite simple: 
Procedure.l StatusObject_QueryInterface(*THIS.StatusObject, *iid.IID, *Object.LONG) 

  ; compare the IID to the IID's in our DataSection 
  If CompareMemory(*iid, ?IID_IUnknown, SizeOf(IID)) Or CompareMemory(*iid, ?IID_IBindStatusCallback, SizeOf(IID)) 
  
    ; return the object itself. See this is why this *THIS pointer is usefull 
    *Object\l = *THIS    
    ProcedureReturn #S_OK 
  Else    
    
    ; Ok, the caller requests an interface we don't have, so let's tell him: 
    *Object\l = 0 
    ProcedureReturn #E_NOINTERFACE 
  EndIf 
EndProcedure 


; In AddRef we just have to increase a counter, of how much references exist to 
; our object, and return that number: 
Procedure.l StatusObject_AddRef(*THIS.StatusObject) 
  Shared StatusObject_Count.l 
  StatusObject_Count + 1 
  ProcedureReturn StatusObject_Count 
EndProcedure 

; Release is the same the other way around: 
Procedure.l StatusObject_Release(*THIS.StatusObject) 
  Shared StatusObject_Count.l 
  StatusObject_Count - 1 
  ProcedureReturn StatusObject_Count 
EndProcedure 

; --------------------------------------------------------- 
; Ok, now for the IBindStatusCallback specific methods: 
; We basically only need the OnProgress method, so we just return 
; #S_OK everywhere we don't need to take any action, and #E_NOTIMPL, where 
; we would need to do something (to tell that we didn't implement the method) 

Procedure.l StatusObject_OnStartBinding(*THIS.StatusObject, Reserved.l, *IB.IBinding) 
  ProcedureReturn #S_OK 
EndProcedure 

Procedure.l StatusObject_GetPriority(*THIS.StatusObject, *Priority.LONG) 
  ProcedureReturn #E_NOTIMPL 
EndProcedure 

Procedure.l StatusObject_OnLowResource(*THIS.StatusObject) 
  ProcedureReturn #E_NOTIMPL 
EndProcedure 

; Now we come to the interresting part: OnProgress 
; Remember: this is called from inside the second thread, so we can't use 
; any Strings in there for example. We basically just pass on every information 
; to the main thread via SendMessage, and do nothing else here: 
Procedure.l StatusObject_OnProgress(*THIS.StatusObject, Progress.l, ProgressMax.l, StatusCode.l, szStatusText.l) 

  ; Make a ProgressData structure, fill it with the information we have: 
  ProgressData.ProgressData 
  ProgressData\Progress = Progress 
  ProgressData\ProgressMax = ProgressMax 
  ProgressData\StatusCode = StatusCode 
  
  ; szStatusText contains additional information, unfortunately, in UNICODE format. 
  ; So we have to convert it. For more information on that, search the forum, there 
  ; are several examples for UNICODE strings. 
  
  ; get length of string 
  Length = WideCharToMultiByte_(#CP_ACP, 0, szStatusText, -1, 0, 0, 0, 0) 
  
  ; now we allocate some memory for that string, we can't use AllocateMemory(), because 
  ; it requeres a fixed number, we don't want to use. 
  *String = HeapAlloc_(GetProcessHeap_(), 0, Length) 
  
  ; convert string    
  WideCharToMultiByte_(#CP_ACP, 0, szStatusText, -1, *String, Length, 0, 0) 
  
  ; we use SendMessage to send the information, the address of the ProgressData 
  ; structure as wParam, and the address of the string as lParam. 
  ; SendMessage waits until the WindowCallback of the main thread has processed 
  ; the message, so the threads are syncronized like that, and we can destroy our 
  ; string afterwards. 
  Result =  SendMessage_(MainWindow, #WM_DOWNLOADPROGRESS, @ProgressData, *String) 
  
  ; free the string 
  HeapFree_(GetProcessHeap_(), 0, *String) 
  
  ; From the Windowcallback, we return the value of the Global 'Abort' variable. If it 
  ; is #TRUE, we return #E_ABORT here, to stop the download: 
  If Result = #True 
    ProcedureReturn #E_ABORT 
  Else 
    ProcedureReturn #S_OK 
  EndIf 
EndProcedure 

; another couple of unused methods, but they need to be there: 
Procedure.l StatusObject_OnStopBinding(*THIS.StatusObject, Result.l, szError.l) 
  ProcedureReturn #S_OK 
EndProcedure 

Procedure.l StatusObject_GetBindInfo(*THIS.StatusObject, BINDF.l, *bindinfo) 
  ProcedureReturn #S_OK 
EndProcedure 

Procedure.l StatusObject_OnDataAvailable(*THIS.StatusObject, BSCF.l, Size.l, *formatec, *stgmed) 
  ProcedureReturn #S_OK 
EndProcedure 

Procedure.l StatusObject_OnObjectAvailable(*THIS.StatusObject, *iid.IID, *UNK.IUnknown) 
  ProcedureReturn #S_OK 
EndProcedure 

; --------------------------------------------------------- 

; Ok, now that all methods are there, we fill the virtual table with the 
; addresses: 

IBindStatusCallback_Functions\QueryInterface    = @StatusObject_QueryInterface() 
IBindStatusCallback_Functions\AddRef            = @StatusObject_AddRef() 
IBindStatusCallback_Functions\Release           = @StatusObject_Release() 
IBindStatusCallback_Functions\OnStartBinding    = @StatusObject_OnStartBinding() 
IBindStatusCallback_Functions\GetPriority       = @StatusObject_GetPriority() 
IBindStatusCallback_Functions\OnLowResource     = @StatusObject_OnLowResource() 
IBindStatusCallback_Functions\OnProgress        = @StatusObject_OnProgress() 
IBindStatusCallback_Functions\OnStopBinding     = @StatusObject_OnStopBinding() 
IBindStatusCallback_Functions\GetBindInfo       = @StatusObject_GetBindInfo() 
IBindStatusCallback_Functions\OnDataAvailable   = @StatusObject_OnDataAvailable() 
IBindStatusCallback_Functions\OnObjectAvailable = @StatusObject_OnObjectAvailable() 

; Here's the DataSection with the IID's for IUnknown and IBindStatusCallback 
; I put them here, because they belong to the Interface stuff, not to the GUI part. 
DataSection 
  IID_IUnknown:  ; {00000000-0000-0000-C000-000000000046} 
    Data.l $00000000 
    Data.w $0000, $0000 
    Data.b $C0, $00, $00, $00, $00, $00, $00, $46 
    
  IID_IBindStatusCallback:  ; {79eac9c1-baf9-11ce-8c82-00aa004ba90b} 
    Data.l $79eac9c1 
    Data.w $baf9, $11ce 
    Data.b $8c, $82, $00, $aa, $00, $4b, $a9, $0b    
EndDataSection 

; That was actually all that was there to do to implement a IBindStatusCallback 
; Interface in our program. We now have a 'StatusObject' object structure containing 
; our Interface. That's all we need. 

; GUI part comes next. Let's first create a nice GUI with the Visual Designer: 

; --------------------------------------------------------- 

; PureBasic Visual Designer v3.80 build 1249 


; Window Constants 
; 
Enumeration 
  #DownloadWindow 
EndEnumeration 

; Gadget Constants 
; 
Enumeration 
  #Gadget_1 
  #Gadget_2 
  #Gadget_Url 
  #Gadget_SaveTo 
  #Gadget_ChooseFile 
  #Gadget_Status 
  #Gadget_Progress 
  #Gadget_Start 
  #Gadget_Stop 
  #Gadget_Close 
  #Gadget_StatusText 
EndEnumeration 


Procedure Open_DownloadWindow() 
  If OpenWindow(#DownloadWindow, 414, 385, 447, 230,  #PB_Window_SystemMenu | #PB_Window_TitleBar | #PB_Window_ScreenCentered , "File download:") 
    If CreateGadgetList(WindowID()) 
      TextGadget(#Gadget_1, 5, 10, 60, 20, "Url:", #PB_Text_Right) 
      TextGadget(#Gadget_2, 5, 35, 60, 20, "SaveTo:", #PB_Text_Right) 
      StringGadget(#Gadget_Url, 70, 5, 320, 20, "") 
      StringGadget(#Gadget_SaveTo, 70, 30, 320, 20, "") 
      ButtonGadget(#Gadget_ChooseFile, 395, 30, 50, 20, "...") 
      ListViewGadget(#Gadget_Status, 5, 55, 385, 120) 
      ProgressBarGadget(#Gadget_Progress, 5, 180, 385, 20, 0, 100) 
      ButtonGadget(#Gadget_Start, 395, 80, 50, 20, "Start") 
      ButtonGadget(#Gadget_Stop, 395, 105, 50, 20, "Abort") 
      ButtonGadget(#Gadget_Close, 395, 205, 50, 20, "Close") 
      TextGadget(#Gadget_StatusText, 5, 205, 385, 20, "", #PB_Text_Center | #PB_Text_Border) 
      
    EndIf 
  EndIf 
EndProcedure 
; --------------------------------------------------------- 

; Ok, next we need a Procedure for our thread. It does nothing than 
; call the UrlDownloadToFile_() function with our Global settings and, of course 
; our Interface, and then SendMessage the result back to the main thread. 
; A thread procedure MUST have one argument, but as we don't need 
; it, we call it Dummy. 
Procedure BackgroundDownload(Dummy.l) 
  Result.l = URLDownloadToFile_(0, @Url, @SaveTo, 0, @StatusObject) 
  SendMessage_(MainWindow, #WM_DOWNLOADEND, 0, Result) 
EndProcedure 

; Next is the WindowCallback procedure. Here we handle, what comes back from 
; our OnProgress method, and from the thread procedure: 
Procedure WindowCallback(Window.l, Message.l, wParam.l, lParam.l) 
  Result.l = #PB_ProcessPureBasicEvents 
  
  ; download is in progress... 
  If Message = #WM_DOWNLOADPROGRESS 
    
    ; in wParam, we habe a pointer to the infor structure: 
    *Progress.ProgressData = wParam 
    
    ; let's update the ProgressBar: 
    ; Progress may be always equal to ProgressMax, for example if the real size 
    ; is unknown. 
    If *Progress\Progress = *Progress\ProgressMax Or *Progress\ProgressMax = 0 
      SetGadgetState(#Gadget_Progress, 0) 
    Else 
      SetGadgetState(#Gadget_Progress, (*Progress\Progress*100)/*Progress\ProgressMax) 
    EndIf 
    
    ; a pointer to the extra text is in lParam: 
    StatusText.s = PeekS(lParam) 
    
    ; now we check those StatusCodes, that are used for downloads, and set up a nice 
    ; message: 
    Select *Progress\StatusCode 
      Case #BINDSTATUS_FINDINGRESOURCE:   Text.s = "Finding "+StatusText 
      Case #BINDSTATUS_CONNECTING:        Text.s = "Connecting to "+StatusText        
      Case #BINDSTATUS_REDIRECTING:       Text.s = "Resolved to "+StatusText 
      Case #BINDSTATUS_BEGINDOWNLOADDATA: Text.s = "Downloading "+StatusText 
      Case #BINDSTATUS_ENDDOWNLOADDATA:   Text.s = "Finished downloading "+StatusText 
      Case #BINDSTATUS_USINGCACHEDCOPY:   Text.s = "Receiving file from cache." 
      Case #BINDSTATUS_MIMETYPEAVAILABLE: Text.s = "MIME Type is "+StatusText 
      Case #BINDSTATUS_PROXYDETECTING:    Text.s = "A Proxy Server was detected" 
      Default: Text.s = "" 
    EndSelect 
    If Text <> "" 
      AddGadgetItem(#Gadget_Status, -1, Text) 
    EndIf 
    
    ; scroll down to the end: 
    SetGadgetState(#Gadget_Status, CountGadgetItems(#GAdget_Status)-1) 
    
    ; Set the sizes also in our TextGadget 
    SetGadgetText(#Gadget_StatusText, Str(*Progress\Progress) + " of " + Str(*Progress\ProgressMax) + " Bytes complete") 
    
    ProcedureReturn Abort 
    
  ; download finished: 
  ; Note: there is also a StatusCode for finished, but it is not sent on errors, so 
  ; we also need this one: 
  ElseIf Message = #WM_DOWNLOADEND 
  
    ; lParam contains the result of the UrlDownLoadToFile_() Api: 
    If lParam = #S_OK        
      ;jippeeeee :) 
      AddGadgetItem(#Gadget_Status, -1, "Download complete.") 
      SetGadgetState(#Gadget_Progress, 100) 
    Else 
      ; damn :( 
      AddGadgetItem(#Gadget_Status, -1, "Download failed!!") 
      SetGadgetState(#Gadget_Progress, 0) 
    EndIf 
    SetGadgetState(#Gadget_Status, CountGadgetItems(#GAdget_Status)-1)    
    
    ; switch Start/Stop button: 
    DisableGadget(#Gadget_Start, #False) 
    DisableGadget(#Gadget_Stop, #True)                
    
  EndIf 
  
  ProcedureReturn Result 
EndProcedure 

; --------------------------------------------------------- 

; Now that's finally where our program starts: 

; open the window and set the WindowCallback: 
Open_DownloadWindow() 
SetWindowCallback(@WindowCallback()) 

; who needs an 'abort' button now? 
DisableGadget(#Gadget_Stop, #True) 

; A nice little extra for the StringGadgets: AutoComplete feature 
; only present on IE5+, so we load the function manually: 
#SHACF_URLALL = 2|4 
#SHACF_FILESYSTEM = 1 
CoInitialize_(0) 
If OpenLibrary(0, "shlwapi.dll")  
  CallFunction(0, "SHAutoComplete", GadgetID(#Gadget_Url), #SHACF_URLALL) 
  CallFunction(0, "SHAutoComplete", GadgetID(#Gadget_SaveTo), #SHACF_FILESYSTEM)  
  CloseLibrary(0) 
EndIf 

; finally: the main loop: 
Repeat 
  Select WaitWindowEvent() 
    Case #PB_EventCloseWindow: End 
    Case #PB_EventGadget 
      Select EventGadgetID() 
        Case #Gadget_Close: End 
        
        Case #Gadget_ChooseFile 
          File.s = SaveFileRequester("Save File to...", GetGadgetText(#Gadget_SaveTo), "All Files|*.*", 0) 
          If File <> "": SetGadgetText(#Gadget_SaveTo, File): EndIf 
          
        ; download starts: 
        Case #Gadget_Start 
          ; set Abort to false, so our download doesn't get stopped imediately 
          Abort = #False 
          
          ; switch start/stop 
          DisableGadget(#Gadget_Start, #True) 
          DisableGadget(#Gadget_Stop, #False) 
          
          ; cleat gadgets: 
          SetGadgetState(#Gadget_Progress, 0) 
          ClearGadgetItemList(#Gadget_Status) 
          
          ; set our global values: 
          Url = GetGadgetText(#Gadget_Url) 
          SaveTo = GetGadgetText(#Gadget_SaveTo) 
          
          ; this one is important for our messages to work: 
          MainWindow = WindowID(#DownloadWindow) 
          
          ; finally, start the download by creating the thread: 
          CreateThread(@BackgroundDownload(), 0) 
          
        Case #Gadget_Stop 
        
          ; to stop, we set Abort to #TRUE, and on the next time, the 
          ; OnProgress method get's called, the download is aborted. 
          Abort = #True 
        
      EndSelect 
  EndSelect 
ForEver 

; --------------------------------------------------------- 
; 
; WOW, now my fingers really hurt! 
; 
; I hope, you were able to understand all the stuff i was talking here, 
; and that it helps you getting into COM (and doing nice downloads). 
; If you have further questions, feel free to ask me or anybody else on 
; the PureBasic forums (http://jconserv.net/purebasic) or send me an 
; email (freak@purearea.net) 
; 
; btw: forgive me for all the typos, but there is unfortunately no spell 
; checking feature in the PB Editor :D ... and english is not my native language. 
; (well, i doubt that my german is much better though :) ) 
; 
; 
; Timo 
; --------------------------------------------------------- 
:wink:
Dernière modification par Le psychopathe le mar. 27/déc./2005 12:11, modifié 3 fois.
Dr. Dri
Messages : 2527
Inscription : ven. 23/janv./2004 18:10

Message par Dr. Dri »

bah les commentaires ne suffisent pas ?

Dri
Avatar de l’utilisateur
Le psychopathe
Messages : 764
Inscription : jeu. 03/mars/2005 19:23

Message par Le psychopathe »

Le problème c'est que moi et l'anglais c'est pas super et même en français je crois que j'aurais du mal^^
Avatar de l’utilisateur
Droopy
Messages : 1151
Inscription : lun. 19/juil./2004 22:31

Message par Droopy »

Le code à l'air très chaud 8O

Si tu veux faire la même chose sans te compliquer tu pourrais utiliser la lib GetURL
Download of files with progress value and retrieving the file date
Tu peux la télécharger ici : http://www.purearea.net/pb/download/userlibs/GetUrl.zip
Avatar de l’utilisateur
Le psychopathe
Messages : 764
Inscription : jeu. 03/mars/2005 19:23

Message par Le psychopathe »

J'ai essayé mais cela ne fonctionne pas et je n'arrive pas à supprimer l'erreur car mon niveau en pure basic est encore faible. Je vous met le code avec le lieu de l'erreur d'après moi.^^ Si quelqu'un pouvez la corriger cela serait sympa !

Code : Tout sélectionner



;/// This structure is required to send the data to the GetUrl Command Set
Structure filedata
  url.s ; Url path
  savepath.s ; Local HD save path (no file name)
  buffer.l ; Internet incoming buffer
  proxy.s ; Proxy Address
  puser.s ; Proxy User name
  ppass.s ; Proxy Password
  wwwuser.s ; www user name
  wwwpass.s ; www password
EndStructure

;ici je pense////////////////////////////////////////////////

urlfile.filedata
urlfile\url="http://www.purearea.net/pb/download/CodeArchiv.zip"
urlfile\savepath="c:\"
urlfile\buffer=10240

;jusque là /////////////////////////////////////////////////

If InitNetwork()
  
  OpenConsole()
  PrintN("***Getting file date***")
  PrintN("Last Modified Date: "+GetUrlLastMod(@urlfile))
  PrintN("<any key to continue>")
  PrintN(" ")
  Input()
  
  
  PrintN("***Getting file***")
  If GetUrlFile(@urlfile)
    ConsoleLocate(1,5)
    Print("Getting : "+urlfile\url)
    
    Repeat
      progress.l=GetUrlProgress() ;/// Get current file progress
      ConsoleLocate(1,6)
      Print("Complete: "+Str(progress)+"%")
      Delay(10)
    Until progress=100
    
    PrintN(" ")
    PrintN(" ")
    PrintN("Done! <any key to end>")
    
  EndIf
  
  Input()
  CloseConsole()
EndIf
End


Avatar de l’utilisateur
Le psychopathe
Messages : 764
Inscription : jeu. 03/mars/2005 19:23

Message par Le psychopathe »

Personne pourrait corriger ce petit code de 30 lignes jsute celui du dessus ??? :cry:
Heis Spiter
Messages : 1092
Inscription : mer. 28/janv./2004 16:22
Localisation : 76
Contact :

Message par Heis Spiter »

Quelle est l'erreur ?
Heis Spiter, webmaster du site http://www.heisspiter.net
Développeur principal et administrateur du projet Bird Chat
Parti courir au bonheur du dév. public et GPL :D
Avatar de l’utilisateur
Le psychopathe
Messages : 764
Inscription : jeu. 03/mars/2005 19:23

Message par Le psychopathe »

Alors voilà, j'ai téléchargé la lib au dessus et ce la ne fonctionne pas.
Voilà l'erreur :
Image
Heis Spiter
Messages : 1092
Inscription : mer. 28/janv./2004 16:22
Localisation : 76
Contact :

Message par Heis Spiter »

D'après le message d'erreur, elle ne doit pas être comptatible avec les nouvelles versions de PB.
Heis Spiter, webmaster du site http://www.heisspiter.net
Développeur principal et administrateur du projet Bird Chat
Parti courir au bonheur du dév. public et GPL :D
Avatar de l’utilisateur
Le psychopathe
Messages : 764
Inscription : jeu. 03/mars/2005 19:23

Message par Le psychopathe »

:x :cry: :x :cry: Bon plus qu'à bosser pour faire ma propre lib dessus.
Je mis met ! lol :wink:
merci de ta réponse
Avatar de l’utilisateur
Droopy
Messages : 1151
Inscription : lun. 19/juil./2004 22:31

Message par Droopy »

Ces lib semble ne plus fonctionner avec PB 3.94 :?

J'ai trouvé ça sur le forum anglais ( Auteur=? ) qui devrait convenir

Code : Tout sélectionner

Enumeration 
  #Window 
  #cmdStart 
  #progressbar 
  #Frame 
  #cmdExit 
  #Label 
  #Label2 
  #URL 
EndEnumeration 


Procedure.s Reverse(s.s) 
  O.s=Mid(s,Len(s),1) 
  P=Len(s)-1 
  While P>0 
    O.s=O+Mid(s,P,1) 
    P=P-1 
  Wend 
  ProcedureReturn O 
EndProcedure 

Procedure SetProgressbarRange(Gadget.l, Minimum.l, Maximum.l) 
  ;? SetProgressbarRange(#progressbar, 0, 100) 
  PBM_SETRANGE32 = $400 + 6 
  SendMessage_(GadgetID(Gadget), PBM_SETRANGE32, Minimum, Maximum) 
EndProcedure 

Procedure DoEvents() 
  msg.MSG 
  If PeekMessage_(msg,0,0,0,1) 
    TranslateMessage_(msg) 
    DispatchMessage_(msg) 
  Else 
    Sleep_(1) 
  EndIf 
EndProcedure 

Procedure.s GetQueryInfo(hHttpRequest.l, iInfoLevel.l) 
  lBufferLength.l=0 
  lBufferLength = 1024 
  sBuffer.s=Space(lBufferLength) 
  HttpQueryInfo_(hHttpRequest, iInfoLevel, sBuffer, @lBufferLength, 0) 
  ProcedureReturn Left(sBuffer, lBufferLength) 
EndProcedure 

Procedure UrlToFileWithProgress(myFile.s, Url.s) 
  isLoop.b=1 
  Bytes.l=0 
  fBytes.l=0 
  Buffer.l=4096 
  res.s="" 
  tmp.s="" 
  
  OpenType.b=1 
  INTERNET_FLAG_RELOAD.l = $80000000 
  INTERNET_DEFAULT_HTTP_PORT.l = 80 
  INTERNET_SERVICE_HTTP.l = 3 
  HTTP_QUERY_STATUS_CODE.l = 19 
  HTTP_QUERY_STATUS_TEXT.l = 20 
  HTTP_QUERY_RAW_HEADERS.l = 21 
  HTTP_QUERY_RAW_HEADERS_CRLF.l = 22 
  
  *xx=AllocateMemory(Buffer) 
  
  Result = CreateFile(1, myFile) 
  hInet = InternetOpen_("", OpenType, #Null, #Null, 0) 
  hURL = InternetOpenUrl_(hInet, Url, #Null, 0, INTERNET_FLAG_RELOAD, 0) 
  
  ;get Filesize 
  domain.s = ReplaceString(Left(Url,(FindString(Url, "/",8) - 1)),"http://","") 
  hInetCon = InternetConnect_(hInet,domain, INTERNET_DEFAULT_HTTP_PORT, #Null, #Null, INTERNET_SERVICE_HTTP, 0, 0) 
  If hInetCon > 0 
    hHttpOpenRequest = HttpOpenRequest_(hInetCon, "HEAD", ReplaceString(Url,"http://"+domain+"/",""), "http/1.1", #Null, 0, INTERNET_FLAG_RELOAD, 0) 
    If hHttpOpenRequest > 0 
      iretval = HttpSendRequest_(hHttpOpenRequest, #Null, 0, 0, 0) 
      If iretval > 0 
        tmp = GetQueryInfo(hHttpOpenRequest, HTTP_QUERY_STATUS_CODE) 
        If Trim(tmp) = "200" 
          tmp = GetQueryInfo(hHttpOpenRequest, HTTP_QUERY_RAW_HEADERS_CRLF) 
          If FindString(tmp,"Content-Length:",1)>0 
            ii.l=FindString(tmp, "Content-Length:",1) + Len("Content-Length:") 
            tmp = Mid(tmp, ii, Len(tmp)-ii) 
            myMax = Val(Trim(tmp)) 
          EndIf 
        EndIf 
      EndIf 
    EndIf 
  EndIf 
  
  SetGadgetText(#Label, "Filesize: " + Str(myMax)) 
  SetProgressbarRange(#progressbar,0,myMax) 
  
  ;start downloading 
  Repeat 
    InternetReadFile_(hURL, *xx, Buffer, @Bytes) 
    If Bytes = 0 
      isLoop=0 
    Else 
      fBytes=fBytes+Bytes 
      SetGadgetText(#Label2, "Received Bytes: " + Str(fBytes)) 
      If myMax >= fBytes: SetGadgetState(#progressbar, fBytes): EndIf 
      UseFile(1) 
      WriteData(*xx, Bytes) 
    EndIf 
    DoEvents() 
  Until isLoop=0 
  InternetCloseHandle_(hURL) 
  InternetCloseHandle_(hInet) 
  SetGadgetState(#progressbar, 0) 
  CloseFile(1)    
  FreeMemory(0) 
EndProcedure 



If OpenWindow(#Window, 0, 0, 400, 175, #PB_Window_SystemMenu | #PB_Window_TitleBar | #PB_Window_ScreenCentered , "Download with Progress") 
  
  If CreateGadgetList(WindowID()) 
    StringGadget(#URL, 10, 10, 380, 20, "http://www.largeformatphotography.info/qtluong/sequoias.big.jpeg") 
    ProgressBarGadget(#progressbar, 10, 40, 380, 30, 0,100 , #PB_ProgressBar_Smooth) 
    TextGadget(#Label, 10, 80,300,20,"Filesize:") 
    TextGadget(#Label2, 10, 100,300,20,"Bytes received:") 
    Frame3DGadget(#Frame, -10, 120, 420, 110, "") 
    ButtonGadget(#cmdExit, 160, 140, 110, 25, "Exit") 
    ButtonGadget(#cmdStart, 280, 140, 110, 25, "Start", #PB_Button_Default) 
  EndIf 
  
  Repeat 
    EventID.l = WaitWindowEvent() 
    If EventID = #PB_EventGadget    
      Select EventGadgetID() 
        Case #cmdStart 
          
          Url.s = GetGadgetText(#URL) 
          
          ;get filename (checking /) 
          myFile.s= Right(Url, FindString(Reverse(Url),"/",1)-1) 
          ;request path 
          myFolder.s = PathRequester ("Where do you want to save '" + myFile + "'?", "C:\") 
          
          UrlToFileWithProgress(myFolder + myFile, Url) 
        Case #cmdExit 
          End 
      EndSelect 
    EndIf               
  Until EventID = #PB_EventCloseWindow 
EndIf 
End 
Avatar de l’utilisateur
Droopy
Messages : 1151
Inscription : lun. 19/juil./2004 22:31

Message par Droopy »

Il y a aussi ce code de lionel_om qui fait la même chose :

Code : Tout sélectionner

; Author : lionel_om
; PureBasic 3.93
; Http library from another !


;{/ Librairie HTTP
#HTTP_Ok = 1 
#HTTP_Error = 0 
#HTTP_ProxyData_Needed = -2 
#HTTP_Authentication_Needed =-3 
#HTTP_Invalid_URL = -4 
#HTTP_FileNotFound = -5 
#HTTP_FileMoved = -6 
#HTTP_TimeOut = -7 
#HTTP_UnknowFileSize = -8 
#HTTP_UnknowDate = -9 
#HTTP_Downloading = 2 
#HTTP_DownloadEnd = 3 

#HTTP_Action_Get2File = 2 
#HTTP_Action_Get2Mem = 3 
#HTTP_Action_GetInfo = 4 


Procedure HTTP_Init();Start HTTP library 
  If InitNetwork() 
    
    Global InBuffer.l,Last_Error.l 
    InBuffer=10240 
    
    NewList http_data.http() 
    If AddElement(http_data()) : EndIf 
    
    
    ;-URL-Commands 
    ;{Day,Month 
    Dim wkday$(6) 
    Dim weekday$(6) 
    Dim Month$(12) 
    wkday$(1)="MON" 
    wkday$(2)="TUE" 
    wkday$(3)="WED" 
    wkday$(4)="THU" 
    wkday$(5)="FRI" 
    wkday$(6)="SAT" 
    wkday$(0)="SUN" 
    weekday$(1)="MONDAY" 
    weekday$(2)="TUESDAY" 
    weekday$(3)="WEDNESDAY" 
    weekday$(4)="THURSDAY" 
    weekday$(5)="FRIDAY" 
    weekday$(6)="SATURDAY" 
    weekday$(0)="SUNDAY" 
    Month$(1)="JAN" 
    Month$(2)="FEB" 
    Month$(3)="MAR" 
    Month$(4)="APR" 
    Month$(5)="MAY" 
    Month$(6)="JUN" 
    Month$(7)="JUL" 
    Month$(8)="AUG" 
    Month$(9)="SEP" 
    Month$(10)="OCT" 
    Month$(11)="NOV" 
    Month$(12)="DEC" 
    ;} 
    
    ProcedureReturn #HTTP_Ok 
  Else 
    ProcedureReturn #HTTP_Error 
  EndIf 
EndProcedure 
  
Procedure.s HTTP_LastError_Description();Textual error description 
  
  Select Last_Error 
    Case #HTTP_Invalid_URL 
      text.s="L'URL est invalide." 
      
    Case #HTTP_ProxyData_Needed 
      text.s="Proxy authentication needed" 
      
    Case #HTTP_Authentication_Needed 
      text.s="Vous devez vous identifier." 
      
    Case #HTTP_FileNotFound 
      text.s="Fichier introuvable." 
      
    Case #HTTP_FileMoved 
      text.s="Fichier déplacé." 
      
    Case #HTTP_TimeOut 
      text.s="Délai de connexion expiré." 
      
    Default 
      text.s="Une erreur est survenue." 
  EndSelect 
  
  ProcedureReturn text.s 
  
EndProcedure 
  
Procedure HTTP_LastError_ID();Last error return code 
  ProcedureReturn Last_Error 
EndProcedure 

;///// internal procedures 

Procedure int_AnalyseDate(TestTime$) 
  ;Thank to GPI for this code :P 
  
  TestTime$=ReplaceString(Trim(UCase(TestTime$)),"  "," ") 
  day=0:Month$="":year=0:Time$="" 
  For i=0 To 6 
    If Left(TestTime$,4)=wkday$(i)+","                        ;{"rfc1123-Date" 
      day=Val(StringField(TestTime$,2," ")) 
      Month$=StringField(TestTime$,3," ") 
      year=Val(StringField(TestTime$,4," ")) 
      Time$=StringField(TestTime$,5," ") 
      Break 
      ;} 
    ElseIf Left(TestTime$,Len(weekday$(i))+1)=weekday$(i)+"," ;{"rfc850-Date" 
      SubTime$=StringField(TestTime$,2," ") 
      day=Val(StringField(SubTime$,1,"-")) 
      Month$=StringField(SubTime$,2,"-") 
      year=Val(StringField(SubTime$,3,"-")) 
      If year>80:year+1900:Else:year+2000:EndIf 
      Time$=StringField(TestTime$,3," ") 
      Break 
      ;} 
    ElseIf Left(TestTime$,4)=wkday$(i)+" "                    ;{"asctime-Date" 
      day=Val(StringField(TestTime$,3," ")) 
      Month$=StringField(TestTime$,2," ") 
      year=Val(StringField(TestTime$,5," ")) 
      Time$=StringField(TestTime$,4," ") 
      Break 
      ;} 
    EndIf 
  Next 
  For i=1 To 12 
    If Month$(i)=Month$ : month=i:Break : EndIf 
  Next 
  Date=ParseDate("%hh:%ii:%ss",Time$) 
  Hour=Hour(Date) 
  Min=Minute(Date) 
  Sec=Second(Date) 
  
  ProcedureReturn Date(year,month,day,Hour,Min,Sec) 
EndProcedure  

Procedure int_Parse_URL(ConnectionID.l,Url.s) 
  Url=LCase(Url) 
  
  If FindString(Url,"http://",0)=#True 
    Url=RemoveString(Url,"http://") 
  EndIf 
  
  Url=ReplaceString(Url,"\","/",1) 
  
  server.s=StringField(Url,1,"/") 
  If server<>"" 
    http_data()\server=StringField(Url,1,"/") 
    
    out.s="" 
    For a=2 To CountString(Url,"/") 
      out.s+"/"+StringField(Url,a,"/") 
    Next 
    out.s+"/" 
    
    If out<>"/" 
      http_data()\path=out 
    Else 
      http_data()\path="" 
    EndIf 
    
    file.s=StringField(Url,CountString(Url,"/")+1,"/") 
    
    If file<>"" 
      http_data()\file=file 
    Else 
      ProcedureReturn #HTTP_Invalid_URL 
    EndIf 
    
    ProcedureReturn #HTTP_Ok 
    
  Else 
    
    ProcedureReturn #HTTP_Invalid_URL 
    
  EndIf 
  
EndProcedure 

Procedure int_Action(in_data.l) 
  
  command.s=PeekS(in_data) 
  
  
  
  ConnectionID.l=Val(StringField(command,1,"|")) 
  Action.l=Val(StringField(command,2,"|")) 
  
  If SelectElement(http_data(),ConnectionID)=0 
    ProcedureReturn #HTTP_Error 
  EndIf 
  
  
  
  If http_data()\proxy<>"" 
    conc$=http_data()\puser+":"+http_data()\ppass 
    OutputBuffer = AllocateMemory(Len(conc$)) 
    Base64Encoder(conc$,Len(conc$),OutputBuffer,OutputBuffer*2) 
    penc$=PeekS(OutputBuffer) 
    internetID = OpenNetworkConnection(proxyserver$, Val(proxyport$)) 
  Else 
    internetID = OpenNetworkConnection(server$, Val(port$)) 
  EndIf 
  
  If http_data()\wwwpass<>"" 
    conc$=http_data()\wwwuser +":"+http_data()\wwwpass 
    OutputBuffer = AllocateMemory(Len(conc$)) 
    Base64Encoder(conc$,Len(conc$),OutputBuffer,OutputBuffer*2) 
    wenc$=PeekS(OutputBuffer) 
  EndIf 
  
  header=#False 
  download=#False 
  file_size=0 
  
  resend: 
  
  If http_data()\proxy<>"" 
    internetID = OpenNetworkConnection(http_data()\proxy, http_data()\pport) 
  Else 
    internetID = OpenNetworkConnection(http_data()\server,http_data()\url_port) 
  EndIf 
  
  If internetID 
    
    ;{ /// File Information 
    com$="HEAD "+http_data()\path+http_data()\file+" HTTP/1.1"+Chr(13)+Chr(10) 
    com$+"Accept: */*"+Chr(13)+Chr(10) 
    com$+"Host: "+http_data()\server+Chr(13)+Chr(10) 
    com$+"User-Agent: PureDownload 1.0"+Chr(13)+Chr(10) 
    If http_data()\proxy<>"" 
      com$+"Proxy-Authorization: Basic "+enc$+Chr(13)+Chr(10) 
    EndIf 
    If http_data()\wwwuser<>"" 
      com$+"Authorization: Basic "+wenc$+Chr(13)+Chr(10) 
    EndIf 
    If cookie$<>"" 
      com$+"Cookie: "+cookie$+Chr(13)+Chr(10) 
    EndIf 
    If location$<>"" 
      com$+"Location: "+location$+Chr(13)+Chr(10) 
    EndIf 
    
    com$+Chr(13)+Chr(10) 
    res = SendNetworkData(internetID,@com$,Len(com$)) 
    
    If res < 0 
      CloseNetworkConnection(internetID) 
      Last_Error=#HTTP_Error 
      ProcedureReturn #HTTP_Error 
    EndIf 
    
    Repeat 
      
      index.l=ListIndex(http_data()) 
      
      If index<0 
        ProcedureReturn 
      EndIf 
      
      Result = NetworkClientEvent(internetID) 
      
      If Result=2 ;/// Raw data received 
        Content$ = Space(14500) 
        ReceiveNetworkData(internetID,@Content$,14500) 
        
        Content$=Trim(LCase(Content$)) 
        
        ;/// File not found handle 
        If FindString(Content$,"404",1) 
          CloseNetworkConnection(internetID) 
          Last_Error=#HTTP_FileNotFound 
          ProcedureReturn #HTTP_FileNotFound 
        EndIf 
        
        ;/// File moved 
        If FindString(Content$,"301",1) 
          CloseNetworkConnection(internetID) 
          Last_Error=#HTTP_FileMoved 
          ProcedureReturn #HTTP_FileMoved 
        EndIf 
        
        ;/// www authorization required 
        If FindString(Content$,"401",1) 
          CloseNetworkConnection(internetID) 
          Last_Error=#HTTP_Authentication_Needed 
          ProcedureReturn #HTTP_Authentication_Needed 
        EndIf 
        
        ;/// File found handle but redirect 
        If FindString(Content$,"302",1) 
          location$="" 
          loc=FindString(Content$,"location: ",1) 
          If loc>0 
            temploc.s=Mid(Content$,loc+10,Len(Content$)) 
            For a=1 To Len(temploc) 
              tcok.s=Mid(temploc,a,1) 
              If tcok<>Chr(13) 
                location$+tcok 
              Else 
                Break 1 
              EndIf 
            Next 
          EndIf 
        EndIf 
        
        ;/// Site sends cookie authentication 
        cok=FindString(Content$,"set-cookie: ",1) 
        cookie$="" 
        
        If cok>0 
          tempcok.s=Mid(Content$,cok+12,Len(Content$)) 
          For a=1 To Len(tempcok) 
            tcok.s=Mid(tempcok,a,1) 
            If tcok<>";" 
              cookie$+tcok 
            Else 
              Break 1 
            EndIf 
          Next 
          Goto resend 
        EndIf 
        
        
        ;/// File found handle 
        If FindString(Content$,"200",1) 
          
          pos=FindString(Content$,"content-length:" , 1) 
          If pos 
            pos=FindString(Content$," " , pos+15) 
            file_size=Val(Mid(Content$,pos+1,Len(Content$))) 
            http_data()\file_size=file_size 
          Else 
            CloseNetworkConnection(internetID) 
            Last_Error=#HTTP_UnknowFileSize 
            ProcedureReturn #HTTP_UnknowFileSize 
          EndIf 
          
          pos=FindString(LCase(Content$),"modified: " , 1) 
          pos1=FindString(Content$,Chr(13)+Chr(10),pos) 
          If pos 
            Date.s=Mid(Content$,pos+10,(pos1-pos-10)) 
            http_data()\file_date=int_AnalyseDate(Date.s) 
          Else 
            CloseNetworkConnection(internetID) 
            Last_Error=#HTTP_UnknowDate 
            ProcedureReturn #HTTP_UnknowDate 
          EndIf 
          
          
        Else 
          CloseNetworkConnection(internetID) 
          Last_Error=#HTTP_FileNotFound 
          ProcedureReturn #HTTP_FileNotFound 
        EndIf 
        header=#True 
      EndIf 
      
      
      
    Until header=#True 
    ;} 
    
    If Action=#HTTP_Action_Get2File 
      ;{ /// File Download 
      com$="GET "+http_data()\path+http_data()\file+" HTTP/1.1"+Chr(13)+Chr(10) 
      com$+"Accept: */*"+Chr(13)+Chr(10) 
      com$+"Host: "+http_data()\server+Chr(13)+Chr(10) 
      com$+"User-Agent: PureDownload 1.0"+Chr(13)+Chr(10) 
      If http_data()\proxy<>"" 
        com$+"Proxy-Authorization: Basic "+enc$+Chr(13)+Chr(10) 
      EndIf 
      If http_data()\wwwuser<>"" 
        com$+"Authorization: Basic "+wenc$+Chr(13)+Chr(10) 
      EndIf 
      If cookie$<>"" 
        com$+"Cookie: "+cookie$+Chr(13)+Chr(10) 
      EndIf 
      If location$<>"" 
        com$+"Location: "+location$+Chr(13)+Chr(10) 
      EndIf 
      
      com$+Chr(13)+Chr(10) 
      res = SendNetworkData(internetID,@com$,Len(com$)) 
      
      If res < 0 
        CloseNetworkConnection(internetID) 
        Last_Error=#HTTP_Error 
        ProcedureReturn #HTTP_Error 
      EndIf 
      
      http_data()\file_progress=0 
      
      
      If CreateFile(0,http_data()\file) 
        incoming_buffer=AllocateMemory(http_data()\in_buffer) 
        
        time.l=ElapsedMilliseconds() 
        
        Repeat 
          Delay(1) 
          
          index.l=ListIndex(http_data()) 
          
          If index<0 
            ProcedureReturn 
          EndIf 
          
          Result = NetworkClientEvent(internetID) 
          
          If Result=0 ;/// time out counter 
            now=ElapsedMilliseconds() 
            If now-time > 2000 
              Last_Error=#HTTP_TimeOut 
              ProcedureReturn #HTTP_TimeOut 
            EndIf 
            
          ElseIf Result=2 ;/// Raw data received 
            size=ReceiveNetworkData(internetID,incoming_buffer,http_data()\in_buffer) 
            
            offset.l=FindString(PeekS(incoming_buffer),Chr(13)+Chr(10)+Chr(13)+Chr(10),1) 
            If offset>0 
              offset+3 
            EndIf 
            
            http_data()\file_progress+size-offset 
            
            
            If size>0 
              WriteData(incoming_buffer+offset,size-offset) 
              If http_data()\file_size=http_data()\file_progress 
                file=#True 
              EndIf 
              time=ElapsedMilliseconds() 
            EndIf 
            
          EndIf 
        Until file=#True 
        CloseFile(0) 
        FreeMemory(incoming_buffer) 
        
        CloseNetworkConnection(internetID) 
        
        ProcedureReturn #HTTP_DownloadEnd 
      EndIf 
      
      ;} 
      
    EndIf 
    
    
    If Action=#HTTP_Action_Get2Mem 
      ;{ /// Memory Download 
      com$="GET "+http_data()\path+http_data()\file+" HTTP/1.1"+Chr(13)+Chr(10) 
      com$+"Accept: */*"+Chr(13)+Chr(10) 
      com$+"Host: "+http_data()\server+Chr(13)+Chr(10) 
      com$+"User-Agent: PureDownload 1.0"+Chr(13)+Chr(10) 
      If http_data()\proxy<>"" 
        com$+"Proxy-Authorization: Basic "+enc$+Chr(13)+Chr(10) 
      EndIf 
      If http_data()\wwwuser<>"" 
        com$+"Authorization: Basic "+wenc$+Chr(13)+Chr(10) 
      EndIf 
      If cookie$<>"" 
        com$+"Cookie: "+cookie$+Chr(13)+Chr(10) 
      EndIf 
      If location$<>"" 
        com$+"Location: "+location$+Chr(13)+Chr(10) 
      EndIf 
      
      com$+Chr(13)+Chr(10) 
      res = SendNetworkData(internetID,@com$,Len(com$)) 
      
      If res < 0 
        CloseNetworkConnection(internetID) 
        Last_Error=#HTTP_Error 
        ProcedureReturn #HTTP_Error 
      EndIf 
      
      http_data()\file_progress=0 
      
      If http_data()\membuffer 
        incoming_buffer=AllocateMemory(http_data()\in_buffer) 
        
        time.l=ElapsedMilliseconds() 
        
        Repeat 
          Delay(1) 
          
          index.l=ListIndex(http_data()) 
          
          If index<0 
            ProcedureReturn 
          EndIf 
          
          Result = NetworkClientEvent(internetID) 
          
          If Result=0 ;/// time out counter 
            now=ElapsedMilliseconds() 
            If now-time > 2000 
              Last_Error=#HTTP_TimeOut 
              ProcedureReturn #HTTP_TimeOut 
            EndIf 
            
          ElseIf Result=2 ;/// Raw data received 
            size=ReceiveNetworkData(internetID,incoming_buffer,http_data()\in_buffer) 
            
            offset.l=FindString(PeekS(incoming_buffer),Chr(13)+Chr(10)+Chr(13)+Chr(10),1) 
            If offset>0 
              offset+3 
            EndIf 
            
            If size>0 
              CopyMemory(incoming_buffer+offset,http_data()\membuffer+http_data()\file_progress,size-offset) 
              If http_data()\file_size=http_data()\file_progress 
                file=#True 
              EndIf 
              time=ElapsedMilliseconds() 
            EndIf 
            
            http_data()\file_progress+size-offset 
            
          EndIf 
        Until file=#True 
        FreeMemory(incoming_buffer) 
      EndIf 
      CloseNetworkConnection(internetID) 
      
      ProcedureReturn #HTTP_DownloadEnd 
      ;} 
    EndIf 
    
    CloseNetworkConnection(internetID) 
    ProcedureReturn #HTTP_Ok 
    
  EndIf 
  
EndProcedure 
  
  ;///// External procedures 
Procedure HTTP_New_Connection(Url.s,Port.l) ;Create a new HTTP connection, if file exists returns ConnectionID 
  
  If Port=0 
    Port=80 
  EndIf 
  
  
  If AddElement(http_data()) 
    Result = int_Parse_URL(ListIndex(http_data()),Url) 
    
    If Result<>#HTTP_Ok 
      DeleteElement(http_data()) 
      Last_Error=#HTTP_Invalid_URL 
      ProcedureReturn #HTTP_Error 
    EndIf 
    index.l=ListIndex(http_data()) 
    
    http_data()\url_port=Port 
    http_data()\in_buffer=InBuffer 
    
    line.s=Str(index)+"|0" 
    size=int_Action(@line) 
    
    If size<>#HTTP_Ok 
      ProcedureReturn HTTP_LastError_ID() 
    EndIf 
    
    ProcedureReturn index 
    
  Else 
    ProcedureReturn #HTTP_Error 
  EndIf 
  
EndProcedure 
  
Procedure HTTP_Delete_Connection(ConnectionID.l);Delete specified connection 
  If SelectElement(http_data(),ConnectionID) 
    DeleteElement(http_data()) 
    ProcedureReturn #HTTP_Ok 
  Else 
    ProcedureReturn #HTTP_Error 
  EndIf 
EndProcedure 
  
Procedure HTTP_Set_InBuffer(Buffer_size.l) ;Set Global incoming data buffer size 
  InBuffer=Buffer_size 
EndProcedure 
  
Procedure HTTP_Get_InBuffer();Get Global incoming data buffer size 
  ProcedureReturn InBuffer 
EndProcedure 
  
Procedure HTTP_File_Size(ConnectionID.l);Get file size 
  
  If SelectElement(http_data(),ConnectionID) 
    ProcedureReturn http_data()\file_size 
  Else 
    ProcedureReturn #HTTP_Error 
  EndIf 
  
EndProcedure 
 
Procedure HTTP_Download_ToFile(ConnectionID.l ,Filename.s);Download HTTP data to file 
  http_data()\file_progress=0 
  
  If SelectElement(http_data(),ConnectionID) 
    http_data()\savefile=Filename 
    ThreadID = CreateThread(@int_Action(),Str(ConnectionID)+"|"+Str(#HTTP_Action_Get2File)) 
    If ThreadID 
      ProcedureReturn ThreadID 
    Else 
      ProcedureReturn #HTTP_Error 
    EndIf 
  Else 
    ProcedureReturn #HTTP_Error 
  EndIf 
  
EndProcedure 
  
Procedure HTTP_Get_Progress(ConnectionID.l);Returns downloaded size in bytes 
  If SelectElement(http_data(),ConnectionID) 
    ProcedureReturn http_data()\file_progress 
  Else 
    ProcedureReturn #HTTP_Error 
  EndIf 
EndProcedure 
  
Procedure HTTP_Stop();Stops HTTP library 
  ClearList(http_data()) 
EndProcedure
;}


#PROJECT_NAME = "Update PCC 2005" 

;- Window Constants 
; 

Enumeration 
  #Window_1 
EndEnumeration 

Enumeration 
  #Frame3D_0 
  #ProgressBar_1 
  #Text_0 
  #Text_1 
  #Text_2 
  #Text_3 
  #Text_4 
  #Button_1 
EndEnumeration 

Procedure Open_Window_1() 
  If OpenWindow(#Window_1, 545, 215, 317, 153,  #PB_Window_SystemMenu | #PB_Window_TitleBar | #PB_Window_ScreenCentered , #PROJECT_NAME) 
    If CreateGadgetList(WindowID()) 
      Frame3DGadget(#Frame3D_0, 10, 0, 300, 125, "") 
      ProgressBarGadget(#ProgressBar_1, 20, 50, 280, 20, 0, 100) 
      TextGadget(#Text_0, 20, 30, 170, 20, "Version de la mise à jour :") 
      TextGadget(#Text_1, 20, 80, 140, 20, "Etat du téléchargement : ") 
      TextGadget(#Text_2, 200, 80, 90, 20, "") 
      TextGadget(#Text_3, 20, 100, 110, 20, "Vitesse de transfert :") 
      TextGadget(#Text_4, 200, 100, 90, 20, "") 
      ButtonGadget(#Button_1, 120, 130, 80, 20, "Annuler") 
    EndIf 
  EndIf 
EndProcedure 

Procedure.s GetWebFilePart(lastUpdate.s) 
  
  lastUpdate = ReplaceString(lastUpdate, "http://www." , "c:\") 
  lastUpdate = ReplaceString(lastUpdate, "/" , "\") 
  ProcedureReturn GetFilePart(lastUpdate) 
  
EndProcedure 

Procedure SetTransfertRate(gadget, nbOctets.f, rate) 
  
  unite$ = "o/s" 
  nbOctets = nbOctets * (1000 / rate) 
  
  If nbOctets > 1000 
    
    nbOctets = nbOctets / 100 
    nbOctets = nbOctets / 10.0 
    unite$ = "Ko/s" 
    
    If nbOctets > 1000 
      
      nbOctets = nbOctets / 100 
      nbOctets = nbOctets / 10.0 
      unite$ = "Mo/s" 
      
    EndIf 
    
  EndIf    
  
  SetGadgetText(gadget, Str(nbOctets) + " " + unite$) 
  
EndProcedure 

Procedure SetTransfertState(gadget, actuel, total) 
  
  SetGadgetText(gadget, Str(actuel) + "/" + Str(total)) 
  
EndProcedure 

; *_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_* 

; fichier à télécharger 
url$ = "http://www.largeformatphotography.info/qtluong/sequoias.big.jpeg" 

  ; Téléchargement du fichier 
  ; ------------------------- 
If HTTP_Init() 
  
  Result= HTTP_New_Connection(url$,80)  
  If Result>0 ;All error are negative numbers 
    
    size.l=HTTP_File_Size(Result) 
    Open_Window_1()  ; Création de la fenêtre 
     
    ; Fonction pour Dl le fichier 
    ThreadID = HTTP_Download_ToFile(Result,GetWebFilePart(url$)) 
    If ThreadID 
      
      current = 0 
      rate = 500 
      
      ; Boucle 
      Repeat 
        
        EventID.l = WindowEvent() 
        
        
        If EventID = #PB_Event_CloseWindow  ; If the user has pressed on the close button 
          KillThread(ThreadID) 
          End 
        EndIf 
        
        If EventID = #PB_Event_Gadget 
          If EventGadgetID() = #Button_1 
            KillThread(ThreadID) 
            End 
          EndIf 
        EndIf 
        
        Tempo+1
        If Tempo=rate
          ; Actualisation de la fenêtre 
          exSize = current 
          current.l=HTTP_Get_Progress(Result) 
          SetTransfertRate(#Text_4, current - exSize, rate) 
          SetTransfertState(#Text_2, current, size) 
          SetGadgetState(#ProgressBar_1, (current*100)/size) 
          SetWindowTitle(#Window_1, #PROJECT_NAME + " - " + Str((current*100)/size) + "%") 
          Tempo=0
        EndIf
         
        ; On attend (pour ne pas oqp tout l'UC) 
        Delay(1) 
        
      Until size=current 
      
    Else 
      
      MessageRequester("Erreur", HTTP_LastError_Description(),#MB_ICONERROR) 
      End 
      
    EndIf 
    
  Else 
    
    MessageRequester("Erreur",HTTP_LastError_Description(),#MB_ICONERROR ) 
    End 
    
  EndIf 
  
EndIf
Avatar de l’utilisateur
Le psychopathe
Messages : 764
Inscription : jeu. 03/mars/2005 19:23

Message par Le psychopathe »

Merci, en tout cas pour cette fonction là les codes sont toujours aussi compliqués.
Il me manque plsu qu'une ilumination :idea:
lionel_om
Messages : 1500
Inscription : jeu. 25/mars/2004 11:23
Localisation : Sophia Antipolis (Nice)
Contact :

Message par lionel_om »

Euh... Ce n'est pas mon code...
je l'avais choppé sur le forum anglais (désolé si je n'ai pas mentionné la source... :? )
Webmestre de Basic-univers
Participez à son extension: ajouter vos programmes et partagez vos codes !
Avatar de l’utilisateur
Droopy
Messages : 1151
Inscription : lun. 19/juil./2004 22:31

Message par Droopy »

Si tu l'a mentionné dans le source :
Http library from another !
Répondre