0

I am connecting to a IMAP server and downloading a message with a ZIP attachment. I am running my script on my local machine, and on a remote machine. I am able to save the file correctly on both machines, but for some reason I am getting errors when unzipping on the remote machine.

My ruby code that saves the zip attachment:

attachment = imap.fetch(message_id, "BODY[2]")[0].attr["BODY[2]"]
save_path = "#{save_path_base}/#{fname}"
File.new(save_path, "wb+").write(attachment.unpack("m"))

On my local machine (OS X) running unzip file.zip on the file works perfectly, but on the remote machine (CentOS) the same command produces an error:

End-of-central-directory signature not found. Either this file is not a zipfile, or it constitutes one disk of a multi-part archive. In the latter case the central directory and zipfile comment will be found on the last disk(s) of this archive.

What could be causing the file to be saved correctly on my local machine and corruptedly on the remote machine? Or is my local unzip ignoring errors? On both machines unzip points to /usr/bin/unzip.

EDIT:

On my local machine, file file.zip gives me Zip archive data, at least v2.0 to extract. My local Ruby version is ruby 1.8.7 (2012-02-08 patchlevel 358)

On my remote server the command returns ASCII text, with very long lines, with no line terminators. My remote Ruby version is ruby 2.0.0p647 (2015-08-18)

How do I ensure the file is recognized as a ZIP on the remote machine?

EDIT: Solution added below as an answer

juuga
  • 1,274
  • 1
  • 13
  • 25

1 Answers1

0

The solution was, of course, figuring out what changed between Ruby versions. In this thread it is pointed out, that:

In 1.8 that is equivalent to calling join, in 1.9 it is equivalent to calling inspect. To get the behavior you want in both 1.8 and 1.9, call join instead of to_s.

So the solution was to change the line to

File.new(save_path, "wb+").write(attachment.unpack("m").join)

Because by default write calls to_s if something besides a string is supplied.

Community
  • 1
  • 1
juuga
  • 1,274
  • 1
  • 13
  • 25