Supporters update.
[dcpomatic.git] / src / lib / unzipper.cc
1 /*
2     Copyright (C) 2024 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 "unzipper.h"
25 #include <dcp/filesystem.h>
26 #include <dcp/scope_guard.h>
27 #include <zip.h>
28 #include <boost/filesystem.hpp>
29 #include <stdexcept>
30
31 #include "i18n.h"
32
33
34 using std::runtime_error;
35 using std::shared_ptr;
36 using std::string;
37
38
39 Unzipper::Unzipper(boost::filesystem::path file)
40 {
41         int error;
42 #ifdef DCPOMATIC_HAVE_ZIP_RDONLY
43         _zip = zip_open(dcp::filesystem::fix_long_path(file).string().c_str(), ZIP_RDONLY, &error);
44 #else
45         _zip = zip_open(dcp::filesystem::fix_long_path(file).string().c_str(), 0, &error);
46 #endif
47         if (!_zip) {
48                 throw FileError("could not open ZIP file", file);
49         }
50 }
51
52
53 Unzipper::~Unzipper()
54 {
55         zip_close(_zip);
56 }
57
58
59 string
60 Unzipper::get(string const& filename)
61 {
62         auto file = zip_fopen(_zip, filename.c_str(), 0);
63         if (!file) {
64                 throw runtime_error(String::compose(_("Could not find file %1 in ZIP file"), filename));
65         }
66
67         dcp::ScopeGuard sg = [file]() { zip_fclose(file); };
68
69         int constexpr maximum = 65536;
70
71         dcp::ArrayData data(maximum);
72         int remaining = maximum;
73         uint8_t* next = data.data();
74
75         while (remaining > 0) {
76                 auto read = zip_fread(file, next, remaining);
77                 if (read == 0) {
78                         break;
79                 } else if (read == -1) {
80                         throw runtime_error("Could not read from ZIP file");
81                 }
82
83                 next += read;
84                 remaining -= read;
85         }
86
87         if (remaining == 0) {
88                 throw runtime_error("File from ZIP is too big");
89         }
90
91         return string(reinterpret_cast<char*>(data.data()), maximum - remaining);
92 }
93