view scid/pageutil.c @ 80:71cd8447e3a4

misc: update copyright years
author David Demelier <markand@malikania.fr>
date Wed, 01 Feb 2023 13:14:46 +0100
parents b474f0985e39
children
line wrap: on
line source

/*
 * pageutil.c -- page utilities
 *
 * Copyright (c) 2021-2023 David Demelier <markand@malikania.fr>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <assert.h>

#include "pageutil.h"
#include "scid.h"
#include "theme.h"
#include "util.h"

void
pageutil_render(struct kreq *req,
                enum khttp status,
                enum kmime mime,
                const char *content)
{
	assert(req);

	khttp_head(req, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[mime]);
	khttp_head(req, kresps[KRESP_STATUS], "%s", khttps[status]);

	if (content) {
		khttp_body(req);
		khttp_printf(req, "%s", content);
	}

	khttp_free(req);
}

static const int statustab[] = {
	[KHTTP_200] = 200,
	[KHTTP_400] = 400,
	[KHTTP_401] = 401,
	[KHTTP_404] = 404,
	[KHTTP_500] = 500
};

static const char * const statusmsg[] = {
	[KHTTP_200] = "OK",
	[KHTTP_400] = "Bad Request",
	[KHTTP_401] = "Unauthorized",
	[KHTTP_404] = "Not Found",
	[KHTTP_500] = "Internal Server Error"
};

void
pageutil_status(struct kreq *req, enum khttp status)
{
	assert(req);

	char *body;

	/*
	 * KHTTP_ are numbered like a standard enum, the Javascript code must
	 * get the appropriate HTTP code instead.
	 */
	body = theme_status(statustab[status], statusmsg[status]);
	pageutil_render(req, status, KMIME_TEXT_HTML, body);
	free(body);
}

void
pageutil_json(struct kreq *req, enum khttp status, json_t *doc)
{
	assert(req);

	char *body;

	khttp_head(req, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME_APP_JSON]);
	khttp_head(req, kresps[KRESP_STATUS], "%s", khttps[status]);
	khttp_body(req);

	if (doc) {
		body = util_json_dump(doc);
		khttp_printf(req, "%s", body);
		json_decref(doc);
	}

	khttp_free(req);
}