aboutsummaryrefslogtreecommitdiffhomepage
path: root/tools/skiaserve/urlhandlers/PostHandler.cpp
blob: 34beefae11cd414c0c1c0efc3ead487b23fe2287 (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
/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "UrlHandler.h"

#include "microhttpd.h"
#include "../Request.h"
#include "../Response.h"

using namespace Response;

static const size_t kBufferSize = 1024;

static int process_upload_data(void* cls, enum MHD_ValueKind kind,
                               const char* key, const char* filename,
                               const char* content_type, const char* transfer_encoding,
                               const char* data, uint64_t off, size_t size) {
    struct UploadContext* uc = reinterpret_cast<UploadContext*>(cls);

    if (0 != size) {
        uc->fStream.write(data, size);
    }
    return MHD_YES;
}

bool PostHandler::canHandle(const char* method, const char* url) {
    return 0 == strcmp(method, MHD_HTTP_METHOD_POST) &&
           0 == strcmp(url, "/new");
}

int PostHandler::handle(Request* request, MHD_Connection* connection,
                        const char* url, const char* method,
                        const char* upload_data, size_t* upload_data_size) {
    UploadContext* uc =  request->fUploadContext;

    // New connection
    if (!uc) {
        // TODO make this a method on request
        uc = new UploadContext;
        uc->connection = connection;
        uc->fPostProcessor = MHD_create_post_processor(connection, kBufferSize,
                                                       &process_upload_data, uc);
        SkASSERT(uc->fPostProcessor);

        request->fUploadContext = uc;
        return MHD_YES;
    }

    // in process upload
    if (0 != *upload_data_size) {
        SkASSERT(uc->fPostProcessor);
        MHD_post_process(uc->fPostProcessor, upload_data, *upload_data_size);
        *upload_data_size = 0;
        return MHD_YES;
    }

    // end of upload
    MHD_destroy_post_processor(uc->fPostProcessor);
    uc->fPostProcessor = nullptr;

    if (!request->initPictureFromStream(request->fUploadContext->fStream.detachAsStream())) {
        fprintf(stderr, "Could not create picture from stream.\n");
        return MHD_NO;
    }

    // clear upload context
    delete request->fUploadContext;
    request->fUploadContext = nullptr;

    return SendTemplate(connection, true, "/");
}