zip.rb 14.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
require 'stringio'
require 'zlib'
require 'stdrubyext'

module Zip

    LOCAL_ENTRY_SIGNATURE = 0x04034b50
    LOCAL_ENTRY_STATIC_HEADER_LENGTH = 30
    DATA_BLOCK_SIGNATURE = 0x08074b50
    CENTRAL_ENTRY_SIGNATURE = 0x02014b50
    CENTRAL_ENTRY_HEADER_LENGTH = 46
    END_OF_CENTRAL_DIRECTORY_SIGNATURE = 0x06054b50
    STATIC_EOCD_SIZE = 22


  class Inflate
    def initialize
      @zlibInflater = Zlib::Inflate.new(-Zlib::MAX_WBITS)
    end

    def decompress(data)
      output_stream = @zlibInflater.inflate(data)
      @zlibInflater.finish
      @zlibInflater.close
      output_stream
    end
  end

  class Zip


    def initialize
      @local_entry = LocalEntry.new
      @central_entry = CentralEnter.new
    end


    def local_entry_block
      @local_entry.local_block_list
    end

    def local_central_block
      @central_entry.central_block_list
    end
    #initialize zip arxiv from file
    #you can also make initialize from ather source in your file
    # object = StringIO.new(source)
    #read(object)
    def initialize_from_file(file)
      object = StringIO.new(File.read(file))
      read(object)
    end
    #generate arxiv. return StringIO
    def generate_arhive
      @output_stream = StringIO.open("","w+b")
      @local_entry.write(@output_stream)

      offset_central_block = @output_stream.tell
      @central_entry.write(@output_stream,local_entry_block)
      end_central_block = @output_stream.tell

      @output_stream.write(
        [END_OF_CENTRAL_DIRECTORY_SIGNATURE,
        0 , # @numberOfThisDisk
        0 , # @numberOfDiskWithStartOfCDir
        @central_entry.count_block ,
        @central_entry.count_block ,
        end_central_block - offset_central_block,
        offset_central_block,
        0 ].pack('VvvvvVVv'))

     
      @output_stream
    end
    #save generated arxiv into file
    def save_to_file(file_name)
      @output_stream.seek(0)
      File.open(file_name,'wb'){|file|
        file.write(@output_stream.read)
      }
    end
    def get_zip_content
      @output_stream.seek(0)
      @output_stream.read
    end

    #функция читает с объекта stringio список файлов, находящихся в архиве и их содержимое
    def read(object)
      position_in_file = 0
      @input_stream = object
    
      while position_in_file < @input_stream.length
        @input_stream.seek(position_in_file)
        signature = @input_stream.read(4)
        if signature.unpack('V')[0] == LOCAL_ENTRY_SIGNATURE
          @input_stream.seek(position_in_file)
          @local_entry.add_block_from_exist_file(@input_stream)
        end
        if signature.unpack('V')[0] == CENTRAL_ENTRY_SIGNATURE
           @input_stream.seek(position_in_file)
           @central_entry.add_block_from_exist_file(@input_stream)
        end
        position_in_file = position_in_file + 1
      end
    end

    # добавляем содержимое просто из строки
    def add_content(file_name,content)
      if @local_entry.add_block(file_name,content) and   @central_entry.add_block(file_name,content)
        return true
      else
        return false
      end
    end

    # добавляем файл в архив
    def add_file(file_name,path)
      File.open(path,'rb') do |file|
        if add_content(file_name,file.read)
          return true
        else
          return false
        end
      end
    end

    # получаем содержимое по имени файла
    def get_content(file_name)
      local_entry_block[file_name] ? local_entry_block[file_name][:content] : nil
    end

    def get_list_file
      local_entry_block.keys
    end

    # получаем содержимое по имени и записываем в файл
    def get_file(file_name,path)
      content = get_content(file_name)
      File.open(path,"w") do |file|
        file.write content
      end
    end

    def remove_content(file_name)
      if @local_entry.delete(file_name) and @central_entry.delete(file_name)
        return true
      else
        return false
      end
    end

    def change_content(file_name,content)
      if @local_entry.change(file_name,content)
        return true
      else
        return false
      end
    end

  end

  class LocalEntry
    attr_reader :local_block_list

    def initialize
      @local_block_list = Hash.new
    end

    def add_block_from_exist_file(input_stream)
      @input_stream = input_stream
      local_file_header_hash = Hash.new
      local_file_header_hash[:header_signature]       ,
       local_file_header_hash[:version]              ,
       local_file_header_hash[:fstype]               ,
       local_file_header_hash[:general_purpose_flag] ,
       local_file_header_hash[:compressed_method]    ,
       local_file_header_hash[:last_mod_time]        ,
       local_file_header_hash[:last_mod_date]        ,
       local_file_header_hash[:crc_32]               ,
       local_file_header_hash[:compressed_size]      ,
       local_file_header_hash[:uncompressed_size]    ,
       local_file_header_hash[:file_name_length]     ,
       local_file_header_hash[:extra_field_length] = @input_stream.read(LOCAL_ENTRY_STATIC_HEADER_LENGTH).unpack('VCCvvvvVVVvv')


      local_file_header_hash[:file_name] = @input_stream.read(local_file_header_hash[:file_name_length])
      local_file_header_hash[:extra] = @input_stream.read(local_file_header_hash[:extra_field_length])

      #не используем на данный момент доп параметры в файлах архива
      local_file_header_hash[:extra_field_length] = 0

      local_file_header_hash[:content] =  get_file_content(local_file_header_hash)
      @local_block_list[local_file_header_hash[:file_name]] = local_file_header_hash
    end

    def add_block(file_name,file_content)
      delete file_name if @local_block_list.has_key?(file_name)
      options = Hash.new

      options[:header_signature] = LOCAL_ENTRY_SIGNATURE
      options[:version] = 0
      options[:fstype] = 0
      options[:general_purpose_flag] = 0
      options[:compressed_method] = 8
      #options[:compressed_method] = 0
      options[:last_mod_time] = Time.now.to_binary_dos_time
      options[:last_mod_date] = Time.now.to_binary_dos_date
      options[:file_name_length] = file_name.length
      options[:extra_field_length] = 0
      options[:crc_32] = 0

      options[:file_name] = file_name
      options[:content] = file_content

      @local_block_list[file_name] = options
    end

    def delete(file_name)
      if @local_block_list.has_key?(file_name)
        @local_block_list.delete_if { |key,value| key == file_name  }
        return true
      else
        false
      end
    end

    def change(file_name,content)
      if @local_block_list.has_key?(file_name)
        @local_block_list[file_name][:content] = content
        return true
      else
        return false
      end
    end

    def write(output_stream)
      @local_block_list.each{|key,value|
        value[:offset] = output_stream.tell

        if value[:compressed_method] == 8
          zlibDeflater = Zlib::Deflate.new(Zlib::DEFAULT_COMPRESSION, -Zlib::MAX_WBITS)
          crc = Zlib::crc32
          crc = Zlib::crc32(value[:content], crc)
          content = ''
          content << zlibDeflater.deflate(value[:content])
          content << zlibDeflater.finish
          value[:crc_32] = crc
        else
          content = value[:content]
        end


        #value[:compressed_size] = content.length
        #value[:uncompressed_size] = value[:content].length

        value[:compressed_size] = content.bytesize
        if value[:content].class.name == 'String'
          value[:uncompressed_size] = value[:content].bytesize
        else
          value[:uncompressed_size] = value[:content].length        
        end


        output_stream <<
           [value[:header_signature]       ,
            value[:version]              ,
            value[:fstype]               ,
            value[:general_purpose_flag],
            value[:compressed_method]    ,
            value[:last_mod_time]        ,
            value[:last_mod_date]        ,
            value[:crc_32]               ,
            value[:compressed_size]      ,
            value[:uncompressed_size]    ,
            value[:file_name_length]     ,
            value[:extra_field_length] ].pack('VCCvvvvVVVvv')


        output_stream.write(value[:file_name])


        output_stream.write(content)

       }
    end

   private
    #получаем содержимое файла
    def get_file_content(local_file_header_hash)
      local_file_header_hash[:general_purpose_flag] > 0 ? content_flag = local_file_header_hash[:general_purpose_flag].to_s(2)[-4].chr : content_flag = '0'
      decompressor = Inflate.new
      if content_flag == '0' # мы знаемм размер содержимого файла 
        pos = @input_stream.tell
        signature = @input_stream.read(4)
        # проверяем идёт ли перет содержимым файла сигнатура
        signature.unpack('V')[0] == DATA_BLOCK_SIGNATURE ? content = @input_stream.read(local_file_header_hash[:compressed_size]) : (@input_stream.seek(pos);content = @input_stream.read(local_file_header_hash[:compressed_size]) )
        content = decompressor.decompress(content) if local_file_header_hash[:compressed_method] == 8 # если файл сжат то распакуем его. на данный момент поддерживается только один алгорим сжатия
      else
        pos = @input_stream.tell
        pos_start = pos
        j = pos
        while(data = @input_stream.read(4) and (data.unpack('V')[0]!=DATA_BLOCK_SIGNATURE or j == pos) and (data.unpack('V')[0]!=LOCAL_ENTRY_SIGNATURE)  and (data.unpack('V')[0]!=CENTRAL_ENTRY_SIGNATURE) and ( data.unpack('V')[0]!= END_OF_CENTRAL_DIRECTORY_SIGNATURE))
          pos_start = pos_start + 1 if (j == pos and data.unpack('V')[0]==DATA_BLOCK_SIGNATURE) # пропускаем если идёт вначале сигнатура
          j = j + 1
          @input_stream.seek(j)
        end
        @input_stream.seek(pos_start)
        content = @input_stream.read(j - pos_start)
        @input_stream.seek(j + 1)

        # читаем заголовок после содержимого если эта файл а не папка
        local_file_header_hash[:crc_32]               ,
        local_file_header_hash[:compressed_size]      ,
        local_file_header_hash[:uncompressed_size]  = @input_stream.read(12).unpack('VVV') if j > pos_start

        content = decompressor.decompress(content) if local_file_header_hash[:compressed_method] == 8 # распаковываем если установлен метод сжатия. Поддерживается только один метод сжатия

      end
      return content
    end
  end

  class CentralEnter
    attr_reader :central_block_list, :count_block

    def initialize
      @central_block_list = Hash.new
      @count_block = 0
    end

    def add_block_from_exist_file(input_stream)
      @input_stream = input_stream
      @count_block = @count_block + 1

      central_file_header_hash = Hash.new
      central_file_header_hash[:header_signature],
      central_file_header_hash[:version] ,
      central_file_header_hash[:fstype] ,
      central_file_header_hash[:versionNeededToExtract],
      central_file_header_hash[:gp_flags] ,
      central_file_header_hash[:compression_method] ,
      central_file_header_hash[:lastModTime] ,
      central_file_header_hash[:lastModDate] ,
      central_file_header_hash[:crc] ,
      central_file_header_hash[:compressed_size],
      central_file_header_hash[:size],
      central_file_header_hash[:nameLength],
      central_file_header_hash[:extraLength] ,
      central_file_header_hash[:commentLength] ,
      central_file_header_hash[:diskNumberStart] ,
      central_file_header_hash[:internalFileAttributes],
      central_file_header_hash[:externalFileAttributes],
      central_file_header_hash[:localHeaderOffset]  = @input_stream.read(CENTRAL_ENTRY_HEADER_LENGTH).unpack('VCCvvvvvVVVvvvvvVV')

      central_file_header_hash[:file_name] = @input_stream.read(central_file_header_hash[:nameLength])
      central_file_header_hash[:extraLength]   = 0 # не используем доп параметры
      central_file_header_hash[:commentLength] = 0 # не используем комментарии

      @central_block_list[central_file_header_hash[:file_name]] = central_file_header_hash
    end

    def add_block(file_name,file_content)
      if @central_block_list.has_key?(file_name)
        delete(file_name)
      end
      @count_block = @count_block + 1
      options = Hash.new
      options[:header_signature] = CENTRAL_ENTRY_SIGNATURE
      options[:version] = 0
      options[:fstype] = 0
      options[:versionNeededToExtract] = 0
      options[:gp_flags] = 0
      options[:compression_method] = 8
      options[:lastModTime] = Time.now.to_binary_dos_time
      options[:lastModDate] = Time.now.to_binary_dos_date
      options[:nameLength] = file_name.length
      options[:extraLength] = 0
      options[:commentLength] = 0
      options[:diskNumberStart] = 0
      options[:internalFileAttributes] = 0
      options[:externalFileAttributes] = 0

      options[:file_name] = file_name
     
      @central_block_list[file_name] = options
    end

    def delete(file_name)
      if @central_block_list.has_key?(file_name)
        @count_block = @count_block - 1
        @central_block_list.delete_if { |key,value| key == file_name  }
        return true
      else
        return false
      end
    end

    def write(output_stream,local_entry_block)
      @central_block_list.each{|key,value|
        output_stream.write(
          [value[:header_signature],
          value[:version] ,
          value[:fstype] ,
          value[:versionNeededToExtract],
          value[:gp_flags] ,
          value[:compression_method] ,
          value[:lastModTime] ,
          value[:lastModDate] ,
          local_entry_block[value[:file_name]][:crc_32],
          local_entry_block[value[:file_name]][:compressed_size],
          local_entry_block[value[:file_name]][:uncompressed_size],
          value[:nameLength],
          value[:extraLength] ,
          value[:commentLength] ,
          value[:diskNumberStart] ,
          value[:internalFileAttributes],
          value[:externalFileAttributes],
          local_entry_block[value[:file_name]][:offset]].pack('VCCvvvvvVVVvvvvvVV')
        )
        output_stream.write(value[:file_name])
      }
    end


  end

end