Supporters update.
[dcpomatic.git] / src / lib / zipper.cc
1 /*
2     Copyright (C) 2020-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 #include "dcpomatic_assert.h"
23 #include "exceptions.h"
24 #include "zipper.h"
25 #include <dcp/filesystem.h>
26 #include <zip.h>
27 #include <boost/filesystem.hpp>
28 #include <stdexcept>
29
30
31 using std::runtime_error;
32 using std::shared_ptr;
33 using std::string;
34
35
36 Zipper::Zipper (boost::filesystem::path file)
37 {
38         int error;
39         _zip = zip_open(dcp::filesystem::fix_long_path(file).string().c_str(), ZIP_CREATE | ZIP_EXCL, &error);
40         if (!_zip) {
41                 if (error == ZIP_ER_EXISTS) {
42                         throw FileError ("ZIP file already exists", file);
43                 }
44                 throw FileError ("could not create ZIP file", file);
45         }
46 }
47
48
49 void
50 Zipper::add (string name, string content)
51 {
52         shared_ptr<string> copy(new string(content));
53         _store.push_back (copy);
54
55         auto source = zip_source_buffer (_zip, copy->c_str(), copy->length(), 0);
56         if (!source) {
57                 throw runtime_error ("could not create ZIP source");
58         }
59
60 #ifdef DCPOMATIC_HAVE_ZIP_FILE_ADD
61         if (zip_file_add(_zip, name.c_str(), source, ZIP_FL_ENC_GUESS) == -1) {
62 #else
63         if (zip_add(_zip, name.c_str(), source) == -1) {
64 #endif
65                 throw runtime_error(String::compose("failed to add data to ZIP archive (%1)", zip_strerror(_zip)));
66         }
67 }
68
69
70 void
71 Zipper::close ()
72 {
73         if (zip_close(_zip) == -1) {
74                 throw runtime_error ("failed to close ZIP archive");
75         }
76         _zip = 0;
77 }
78
79
80 Zipper::~Zipper ()
81 {
82         if (_zip) {
83                 zip_close(_zip);
84         }
85 }