Add Zipper class and use it in CinemaKDMs.
[dcpomatic.git] / src / lib / zipper.cc
1 /*
2     Copyright (C) 2020 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 #include "zipper.h"
22 #include "exceptions.h"
23 #include "dcpomatic_assert.h"
24 #include <zip.h>
25 #include <boost/filesystem.hpp>
26 #include <stdexcept>
27
28 using std::string;
29 using std::runtime_error;
30 using boost::shared_ptr;
31
32
33 Zipper::Zipper (boost::filesystem::path file)
34 {
35         int error;
36         _zip = zip_open (file.string().c_str(), ZIP_CREATE | ZIP_EXCL, &error);
37         if (!_zip) {
38                 if (error == ZIP_ER_EXISTS) {
39                         throw FileError ("ZIP file already exists", file);
40                 }
41                 throw FileError ("could not create ZIP file", file);
42         }
43 }
44
45
46 void
47 Zipper::add (string name, string content)
48 {
49         shared_ptr<string> copy(new string(content));
50         _store.push_back (copy);
51
52         struct zip_source* source = zip_source_buffer (_zip, copy->c_str(), copy->length(), 0);
53         if (!source) {
54                 throw runtime_error ("could not create ZIP source");
55         }
56
57         if (zip_add(_zip, name.c_str(), source) == -1) {
58                 throw runtime_error ("failed to add data to ZIP archive");
59         }
60 }
61
62
63 void
64 Zipper::close ()
65 {
66         if (zip_close(_zip) == -1) {
67                 throw runtime_error ("failed to close ZIP archive");
68         }
69         _zip = 0;
70 }
71
72
73 Zipper::~Zipper ()
74 {
75         if (_zip) {
76                 zip_close(_zip);
77         }
78 }