from ftplib import FTP

class FTP_(FTP):
    def storbinary(self, cmd, fp, blocksize=8192, callback=None):
        '''Store a file in binary mode and optionally
           use a callback func to provide a tuple containing
           number of bytes transmitted to the ftp server and total size
           '''
        self.voidcmd('TYPE I')
        conn = self.transfercmd(cmd)
        if callback:
            totalsent = 0
            fp.seek(0L, 2) # go to file end
            totalsize = fp.tell()
            fp.seek(0L, 0) # go to file start
            
        while 1:
            buf = fp.read(blocksize)
            if not buf: break   
            conn.sendall(buf)
            if callback:
                callback( (totalsent, totalsize) )
                totalsent += blocksize
        conn.close()
        return self.voidresp()


if __name__ == '__main__':
    def func(transmitted): print "transmitted:", transmitted
    
    import sys
    from constants import SF_FTP_SERVER, SF_FTP_DIRECTORY
    
    filename = sys.argv[1]
    f = open(filename, "rb")

    ftp = FTP_()
    ftp.connect(SF_FTP_SERVER)
    ftp.getwelcome()

    ftp.login("ftp", "releaseforge")
    ftp.cwd(SF_FTP_DIRECTORY)
    ftp.storbinary('STOR ' + filename, f, callback=func)
    ftp.close()
