summaryrefslogtreecommitdiff
path: root/tools/Tool.cpp
blob: f62c571775d2f1aac59bc72d4b3c999d22d8306d (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <config.h>

#include <unistd.h>

#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <thread>
#include <sysexits.h>

#include <Poco/Net/HTMLForm.h>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/FilePartSource.h>
#include <Poco/Net/SSLManager.h>
#include <Poco/Net/KeyConsoleHandler.h>
#include <Poco/Net/AcceptCertificateHandler.h>
#include <Poco/StreamCopier.h>
#include <Poco/URI.h>
#include <Poco/Util/Application.h>
#include <Poco/Util/OptionSet.h>

#include <Common.hpp>
#include <Protocol.hpp>
#include <Util.hpp>

/// Simple command-line tool for file format conversion.
class Tool: public Poco::Util::Application
{
    // Display help information on the console
    void displayHelp();

public:
    Tool();

    const std::string& getServerURI() const { return _serverURI; }
    const std::string& getDestinationFormat() const { return _destinationFormat; }
    const std::string& getDestinationDir() const { return _destinationDir; }

private:
    unsigned    _numWorkers;
    std::string _serverURI;
    std::string _destinationFormat;
    std::string _destinationDir;

protected:
    void defineOptions(Poco::Util::OptionSet& options) override;
    void handleOption(const std::string& name, const std::string& value) override;
    int  main(const std::vector<std::string>& args) override;
};


using namespace LOOLProtocol;

using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Runnable;
using Poco::URI;
using Poco::Util::Application;
using Poco::Util::OptionSet;

/// Thread class which performs the conversion.
class Worker: public Runnable
{
    Tool& _app;
    std::vector< std::string > _files;
public:
    Worker(Tool& app, const std::vector< std::string > & files) :
        _app(app), _files(files)
    {
    }

    void run() override
    {
        for (const auto& i : _files)
            convertFile(i);
    }

    void convertFile(const std::string& document)
    {
        Poco::URI uri(_app.getServerURI());

        Poco::Net::HTTPClientSession *session;
        if (_app.getServerURI().compare(0, 5, "https") == 0)
            session = new Poco::Net::HTTPSClientSession(uri.getHost(), uri.getPort());
        else
            session = new Poco::Net::HTTPClientSession(uri.getHost(), uri.getPort());

        Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/lool/convert-to");

        try {
            Poco::Net::HTMLForm form;
            form.setEncoding(Poco::Net::HTMLForm::ENCODING_MULTIPART);
            form.set("format", _app.getDestinationFormat());
            form.addPart("data", new Poco::Net::FilePartSource(document));
            form.prepareSubmit(request);

            // If this results in a Poco::Net::ConnectionRefusedException, loolwsd is not running.
            form.write(session->sendRequest(request));
        }
        catch (const Poco::Exception &e)
        {
            std::cerr << "Failed to write data: " << e.name() <<
                  ' ' << e.message() << '\n';
            return;
        }

        Poco::Net::HTTPResponse response;

        try {
            // receiveResponse() resulted in a Poco::Net::NoMessageException.
            std::istream& responseStream = session->receiveResponse(response);

            Poco::Path path(document);
            std::string outPath = _app.getDestinationDir() + '/' + path.getBaseName() + '.' + _app.getDestinationFormat();
            std::ofstream fileStream(outPath);

            Poco::StreamCopier::copyStream(responseStream, fileStream);
        }
        catch (const Poco::Exception &e)
        {
            std::cerr << "Exception converting: " << e.name() <<
                  ' ' << e.message() << '\n';
            return;
        }

        delete session;
    }
};

Tool::Tool() :
    _numWorkers(4),
#if ENABLE_SSL
    _serverURI("https://127.0.0.1:" + std::to_string(DEFAULT_CLIENT_PORT_NUMBER)),
#else
    _serverURI("http://127.0.0.1:" + std::to_string(DEFAULT_CLIENT_PORT_NUMBER)),
#endif
    _destinationFormat("txt")
{
}

void Tool::displayHelp()
{
    std::cout << "LibreOffice Online document converter tool.\n"
              << "Usage: " << commandName() << " [options] file...\n"
              << "Options are:\n"
              << "  --help                      Show this text\n"
              << "  --extension=format          File format to convert to\n"
              << "  --outdir=directory          Output directory for converted files\n"
              << "  --parallelism=threads       Number of simultaneous threads to use\n"
              << "  --server=uri                URI of LOOL server\n"
              << "  --no-check-certificate      Disable checking of SSL certificate\n"
              << "In addition, the options taken by the libreoffice command for its --convert-to\n"
              << "functionality can be used (but are ignored if irrelevant to this command)." << std::endl;
}

void Tool::defineOptions(OptionSet&)
{
    stopOptionsProcessing();
}

void Tool::handleOption(const std::string& optionName,
                        const std::string& value)
{
    if (optionName == "help")
    {
        displayHelp();
        std::exit(EX_OK);
    }
    else if (optionName == "extension"
             || optionName == "convert-to")
        _destinationFormat = value;
    else if (optionName == "outdir")
        _destinationDir = value;
    else if (optionName == "parallelism")
        _numWorkers = std::max(std::stoi(value), 1);
    else if (optionName == "server")
        _serverURI = value;
    else if (optionName == "no-check-certificate")
    {
        Poco::SharedPtr<Poco::Net::PrivateKeyPassphraseHandler> consoleClientHandler = new Poco::Net::KeyConsoleHandler(false);
        Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> invalidClientCertHandler = new Poco::Net::AcceptCertificateHandler(false);
        Poco::Net::Context::Ptr sslClientContext = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "");
        Poco::Net::SSLManager::instance().initializeClient(consoleClientHandler, invalidClientCertHandler, sslClientContext);
    }
}

int Tool::main(const std::vector<std::string>& origArgs)
{
    std::vector<std::string> args = origArgs;

    for (unsigned i = 0; i < origArgs.size(); ++i)
    {
        if (origArgs[i].length() > 0 && origArgs[i][0] != '-')
            break;

        // It's an option. Erase it from the file name vector.
        args.erase(args.begin());

        std::string optionName, value;

        // Accept either one or two dashes, like LibreOffice.
        if (origArgs[i].length() > 1 && origArgs[i][1] != '-')
            optionName = origArgs[i].substr(1);
        else if (origArgs[i].length() > 1 && origArgs[i][1] == '-')
            optionName = origArgs[i].substr(2);
        else
            break;

        std::string::size_type equals = optionName.find('=');

        // Handle LibreOffice-compatible options that don't have their value separated with an equals,
        // but as the next argument.
        if (equals == std::string::npos
            && (optionName == "convert-to"
                || optionName == "outdir")
            && i < origArgs.size()-1)
        {
            value = origArgs[i+1];
            args.erase(args.begin());
            ++i;
        }
        else if (equals != std::string::npos)
        {
            value = optionName.substr(equals+1);
            optionName = optionName.substr(0, equals);
        }
        handleOption(optionName, value);
    }

    if (args.empty())
    {
        std::cerr << "Nothing to do." << std::endl;
        displayHelp();
        return EX_NOINPUT;
    }

    std::vector<std::thread> clients;
    clients.reserve(_numWorkers);

    size_t chunk = (args.size() + _numWorkers - 1) / _numWorkers;
    size_t offset = 0;
    for (unsigned i = 0; i < _numWorkers; i++)
    {
        size_t toCopy = std::min(args.size() - offset, chunk);
        if (toCopy > 0)
        {
            std::vector< std::string > files( toCopy );
            std::copy( args.begin() + offset, args.begin() + offset + toCopy, files.begin() );
            offset += toCopy;
            clients.emplace_back([this, &files]{Worker(*this, files).run();});
        }
    }

    for (auto& client: clients)
    {
        client.join();
    }

    return EX_OK;
}

POCO_APP_MAIN(Tool)

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */