Refactor.

This commit is contained in:
retoor 2025-01-27 19:06:59 +01:00
parent 91598ce1ef
commit 35b53a586a
10 changed files with 235 additions and 291 deletions

11
auth.h
View File

@ -1,11 +1,12 @@
// Written by retoor@molodetz.nl // Written by retoor@molodetz.nl
// This source code declares a constant character pointer variable with a value representing an API key. // This source code declares a constant character pointer variable that retrieves an API key from environment variables or falls back to a hardcoded key if not found.
// Uses standard library functions from stdlib.h and stdio.h to manage environment variables and output error messages.
// MIT License // MIT License
#ifndef R_AUTH_H #ifndef R_AUTH_H
#define R_AUTH_H #define R_AUTH_H
#include <stdlib.h> #include <stdlib.h>
@ -15,13 +16,11 @@ const char * resolve_api_key(){
static char *api_key = NULL; static char *api_key = NULL;
#ifndef FREE_VERSION #ifndef FREE_VERSION
api_key = getenv("R_KEY"); api_key = getenv("R_KEY");
if(api_key) if (api_key) {
{
return api_key; return api_key;
} }
api_key = getenv("OPENAI_API_KEY"); api_key = getenv("OPENAI_API_KEY");
if(api_key) if (api_key) {
{
return api_key; return api_key;
} }
fprintf(stderr, "\nThere is no API key configured in environment.\n"); fprintf(stderr, "\nThere is no API key configured in environment.\n");

9
chat.h
View File

@ -35,10 +35,10 @@
#include "messages.h" #include "messages.h"
#include "http.h" #include "http.h"
#ifndef FREE_VERSION #ifdef FREE_VERSION
char *prompt_model = "gpt-4o-mini";
#else
char *prompt_model = "gpt-3.5-turbo"; char *prompt_model = "gpt-3.5-turbo";
#else
char *prompt_model = "gpt-4o-mini";
#endif #endif
int prompt_max_tokens = 2048; int prompt_max_tokens = 2048;
double prompt_temperature = 0.5; double prompt_temperature = 0.5;
@ -46,8 +46,9 @@ double prompt_temperature = 0.5;
json_object *_prompt = NULL; json_object *_prompt = NULL;
void chat_free() { void chat_free() {
if (_prompt == NULL) if (_prompt == NULL) {
return; return;
}
json_object_put(_prompt); json_object_put(_prompt);
_prompt = NULL; _prompt = NULL;

163
http.h
View File

@ -1,6 +1,6 @@
// Written by retoor@molodetz.nl // Written by retoor@molodetz.nl
// The source code provides functionality for making HTTP POST and GET requests over SSL/TLS using OpenSSL. It includes initialization and cleanup of the OpenSSL library, creation of SSL context, socket creation and connection, and sending requests with handling responses. Furthermore, it interfaces with JSON and handles authentication using an external "auth.h" file. // The source code provides functionality for making HTTP POST and GET requests over SSL/TLS using OpenSSL. It includes initialization and cleanup of the OpenSSL library, creation of SSL context, socket creation and connection, and sending requests with handling responses. It also interfaces with JSON and handles authentication using an external "auth.h" file.
// Includes: "auth.h", <json-c/json.h> // Includes: "auth.h", <json-c/json.h>
@ -22,55 +22,45 @@
#include <stdbool.h> #include <stdbool.h>
#include "url.h" #include "url.h"
void init_openssl() void init_openssl() {
{
SSL_load_error_strings(); SSL_load_error_strings();
OpenSSL_add_ssl_algorithms(); OpenSSL_add_ssl_algorithms();
} }
void cleanup_openssl() void cleanup_openssl() {
{
EVP_cleanup(); EVP_cleanup();
} }
SSL_CTX *create_context() SSL_CTX *create_context() {
{
const SSL_METHOD *method = TLS_method(); const SSL_METHOD *method = TLS_method();
SSL_CTX *ctx = SSL_CTX_new(method); SSL_CTX *ctx = SSL_CTX_new(method);
SSL_CTX_load_verify_locations(ctx, "/etc/ssl/certs/ca-certificates.crt", NULL); SSL_CTX_load_verify_locations(ctx, "/etc/ssl/certs/ca-certificates.crt", NULL);
return ctx; return ctx;
} }
SSL_CTX *create_context2() SSL_CTX *create_context2() {
{
const SSL_METHOD *method = TLS_client_method(); const SSL_METHOD *method = TLS_client_method();
SSL_CTX *ctx = SSL_CTX_new(method); SSL_CTX *ctx = SSL_CTX_new(method);
if (!ctx) if (!ctx) {
{
perror("Unable to create SSL context"); perror("Unable to create SSL context");
ERR_print_errors_fp(stderr); ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
return ctx; return ctx;
} }
int create_socket(const char *hostname, int port) int create_socket(const char *hostname, int port) {
{
struct hostent *host; struct hostent *host;
struct sockaddr_in addr; struct sockaddr_in addr;
host = gethostbyname(hostname); host = gethostbyname(hostname);
if (!host) if (!host) {
{
perror("Unable to resolve host"); perror("Unable to resolve host");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
int sock = socket(AF_INET, SOCK_STREAM, 0); int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) if (sock < 0) {
{
perror("Unable to create socket"); perror("Unable to create socket");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -79,8 +69,7 @@ int create_socket(const char *hostname, int port)
addr.sin_port = htons(port); addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long *)(host->h_addr); addr.sin_addr.s_addr = *(long *)(host->h_addr);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
{
perror("Unable to connect to host"); perror("Unable to connect to host");
close(sock); close(sock);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
@ -91,68 +80,54 @@ int create_socket(const char *hostname, int port)
typedef struct ssl_st ssl_stt; typedef struct ssl_st ssl_stt;
char *read_until_ssl(ssl_stt * sock, char *until) char *read_until_ssl(ssl_stt *sock, char *until) {
{
static char data[1024 * 1024]; static char data[1024 * 1024];
data[0] = 0; data[0] = 0;
int index = 0; int index = 0;
char chunk[2]; char chunk[2];
while (SSL_read(sock, chunk, 1) == 1) while (SSL_read(sock, chunk, 1) == 1) {
{
data[index] = chunk[0]; data[index] = chunk[0];
index++; index++;
data[index] = 0; data[index] = 0;
if (strstr(data, until) != NULL) if (strstr(data, until) != NULL) {
{
return data; return data;
} }
} }
return NULL; return NULL;
} }
char *read_until(int sock, char *until) char *read_until(int sock, char *until) {
{
static char data[1024 * 1024]; static char data[1024 * 1024];
data[0] = 0; data[0] = 0;
int index = 0; int index = 0;
char chunk[2]; char chunk[2];
while (recv(sock, chunk, 1,0) == 1) while (recv(sock, chunk, 1, 0) == 1) {
{
data[index] = chunk[0]; data[index] = chunk[0];
index++; index++;
data[index] = 0; data[index] = 0;
if (strstr(data, until) != NULL) if (strstr(data, until) != NULL) {
{
return data; return data;
} }
} }
return NULL; return NULL;
} }
size_t hex_to_int(const char *hex) size_t hex_to_int(const char *hex) {
{
size_t result = 0; size_t result = 0;
while (*hex) while (*hex) {
{
char c = *hex++; char c = *hex++;
if (c >= '0' && c <= '9') if (c >= '0' && c <= '9') {
{
result = result * 16 + (c - '0'); result = result * 16 + (c - '0');
} } else if (c >= 'a' && c <= 'f') {
else if (c >= 'a' && c <= 'f')
{
result = result * 16 + (c - 'a' + 10); result = result * 16 + (c - 'a' + 10);
} } else if (c >= 'A' && c <= 'F') {
else if (c >= 'A' && c <= 'F')
{
result = result * 16 + (c - 'A' + 10); result = result * 16 + (c - 'A' + 10);
} }
} }
return result; return result;
} }
char *https_post(char *url, char *data) char *https_post(char *url, char *data) {
{
url_t parsed_url; url_t parsed_url;
parse_url(url, &parsed_url); parse_url(url, &parsed_url);
char *hostname = parsed_url.hostname; char *hostname = parsed_url.hostname;
@ -167,16 +142,13 @@ char *https_post(char *url, char *data)
SSL_set_fd(ssl, sock); SSL_set_fd(ssl, sock);
int buffer_size = 1024 * 1024; int buffer_size = 1024 * 1024;
char *buffer = (char *)malloc(buffer_size); char *buffer = malloc(buffer_size);
size_t chunk_size_total = 0; size_t chunk_size_total = 0;
if (SSL_connect(ssl) <= 0) if (SSL_connect(ssl) <= 0) {
{
ERR_print_errors_fp(stderr); ERR_print_errors_fp(stderr);
} } else {
else
{
size_t len = strlen(data); size_t len = strlen(data);
char *request = (char *)malloc(len + 1024*1024); char *request = malloc(len + 1024 * 1024);
sprintf(request, sprintf(request,
"POST %s HTTP/1.1\r\n" "POST %s HTTP/1.1\r\n"
"Content-Length: %ld\r\n" "Content-Length: %ld\r\n"
@ -193,22 +165,19 @@ char *https_post(char *url, char *data)
(void)headers; (void)headers;
size_t actual_buffer_size = buffer_size; size_t actual_buffer_size = buffer_size;
while (true) while (true) {
{
char *header = read_until_ssl(ssl, "\r\n"); char *header = read_until_ssl(ssl, "\r\n");
size_t chunk_size = hex_to_int(header); size_t chunk_size = hex_to_int(header);
if (chunk_size == 0) if (chunk_size == 0)
break; break;
size_t remaining = chunk_size; size_t remaining = chunk_size;
while (remaining > 0) while (remaining > 0) {
{
size_t to_read = (remaining < buffer_size) ? remaining : buffer_size; size_t to_read = (remaining < buffer_size) ? remaining : buffer_size;
buffer = (char *)realloc(buffer, actual_buffer_size + to_read + 1); buffer = realloc(buffer, actual_buffer_size + to_read + 1);
actual_buffer_size += to_read; actual_buffer_size += to_read;
size_t bytes_read = SSL_read(ssl, buffer + chunk_size_total, to_read); size_t bytes_read = SSL_read(ssl, buffer + chunk_size_total, to_read);
chunk_size_total += bytes_read; chunk_size_total += bytes_read;
if (bytes_read <= 0) if (bytes_read <= 0) {
{
fprintf(stderr, "Error reading chunk data\n"); fprintf(stderr, "Error reading chunk data\n");
return NULL; return NULL;
} }
@ -226,8 +195,7 @@ char *https_post(char *url, char *data)
return buffer; return buffer;
} }
char *https_get(char *url) char *https_get(char *url) {
{
url_t parsed_url; url_t parsed_url;
parse_url(url, &parsed_url); parse_url(url, &parsed_url);
char *hostname = parsed_url.hostname; char *hostname = parsed_url.hostname;
@ -243,14 +211,11 @@ char *https_get(char *url)
SSL_set_fd(ssl, sock); SSL_set_fd(ssl, sock);
int buffer_size = 1024 * 1024; int buffer_size = 1024 * 1024;
char *buffer = (char *)malloc(buffer_size); char *buffer = malloc(buffer_size);
if (SSL_connect(ssl) <= 0) if (SSL_connect(ssl) <= 0) {
{
ERR_print_errors_fp(stderr); ERR_print_errors_fp(stderr);
} } else {
else
{
char request[buffer_size]; char request[buffer_size];
sprintf(request, sprintf(request,
"GET %s HTTP/1.1\r\n" "GET %s HTTP/1.1\r\n"
@ -265,22 +230,19 @@ char *https_get(char *url)
(void)headers; (void)headers;
size_t chunk_size_total = 0; size_t chunk_size_total = 0;
size_t actual_buffer_size = buffer_size; size_t actual_buffer_size = buffer_size;
while (true) while (true) {
{
char *header = read_until_ssl(ssl, "\r\n"); char *header = read_until_ssl(ssl, "\r\n");
size_t chunk_size = hex_to_int(header); size_t chunk_size = hex_to_int(header);
if (chunk_size == 0) if (chunk_size == 0)
break; break;
size_t remaining = chunk_size; size_t remaining = chunk_size;
while (remaining > 0) while (remaining > 0) {
{
size_t to_read = (remaining < buffer_size) ? remaining : buffer_size; size_t to_read = (remaining < buffer_size) ? remaining : buffer_size;
buffer = (char *)realloc(buffer, actual_buffer_size + to_read + 1); buffer = realloc(buffer, actual_buffer_size + to_read + 1);
actual_buffer_size += to_read; actual_buffer_size += to_read;
size_t bytes_read = SSL_read(ssl, buffer + chunk_size_total, to_read); size_t bytes_read = SSL_read(ssl, buffer + chunk_size_total, to_read);
chunk_size_total += bytes_read; chunk_size_total += bytes_read;
if (bytes_read <= 0) if (bytes_read <= 0) {
{
fprintf(stderr, "Error reading chunk data\n"); fprintf(stderr, "Error reading chunk data\n");
return NULL; return NULL;
} }
@ -298,8 +260,7 @@ char *https_get(char *url)
return buffer; return buffer;
} }
char *http_post(char *url, char *data) char *http_post(char *url, char *data) {
{
url_t parsed_url; url_t parsed_url;
parse_url(url, &parsed_url); parse_url(url, &parsed_url);
char *hostname = parsed_url.hostname; char *hostname = parsed_url.hostname;
@ -308,11 +269,11 @@ char *http_post(char *url, char *data)
int sock = create_socket(hostname, port); int sock = create_socket(hostname, port);
int buffer_size = 1024 * 1024; int buffer_size = 1024 * 1024;
char *buffer = (char *)malloc(buffer_size); char *buffer = malloc(buffer_size);
size_t chunk_size_total = 0; size_t chunk_size_total = 0;
size_t len = strlen(data) + strlen(path) + strlen(resolve_api_key()) + 10; size_t len = strlen(data) + strlen(path) + strlen(resolve_api_key()) + 10;
char *request = (char *)malloc(len + buffer_size); char *request = malloc(len + buffer_size);
sprintf(request, sprintf(request,
"POST %s HTTP/1.1\r\n" "POST %s HTTP/1.1\r\n"
"Content-Length: %ld\r\n" "Content-Length: %ld\r\n"
@ -323,53 +284,44 @@ char *http_post(char *url, char *data)
path, len, resolve_api_key(), data); path, len, resolve_api_key(), data);
send(sock, request, strlen(request), 0); send(sock, request, strlen(request), 0);
free(request); free(request);
char *headers = read_until(sock, "\r\n\r\n"); char *headers = read_until(sock, "\r\n\r\n");
(void)headers; (void)headers;
size_t actual_buffer_size = buffer_size; size_t actual_buffer_size = buffer_size;
while (true) while (true) {
{
char *header = read_until(sock, "\r\n"); char *header = read_until(sock, "\r\n");
size_t chunk_size = hex_to_int(header); size_t chunk_size = hex_to_int(header);
if (chunk_size == 0) if (chunk_size == 0) {
{ printf("END\n"); printf("END\n");
break; break;
} }
size_t remaining = chunk_size; size_t remaining = chunk_size;
while (remaining > 0) while (remaining > 0) {
{
size_t to_read = (remaining < buffer_size) ? remaining : buffer_size; size_t to_read = (remaining < buffer_size) ? remaining : buffer_size;
buffer = (char *)realloc(buffer, actual_buffer_size + to_read + 10); buffer = realloc(buffer, actual_buffer_size + to_read + 10);
actual_buffer_size += to_read; actual_buffer_size += to_read;
size_t bytes_read = recv(sock, buffer + chunk_size_total, to_read, 0); size_t bytes_read = recv(sock, buffer + chunk_size_total, to_read, 0);
if (bytes_read <= 0) if (bytes_read <= 0) {
{
fprintf(stderr, "Error reading chunk data\n"); fprintf(stderr, "Error reading chunk data\n");
return NULL; return NULL;
} }
chunk_size_total += bytes_read; chunk_size_total += bytes_read;
// fwrite(buffer, 1, bytes_read, stdout); // Output chunk data
remaining -= bytes_read; remaining -= bytes_read;
} }
} }
printf("HIERRR!\n"); printf("HERE!\n");
buffer[chunk_size_total] = 0; buffer[chunk_size_total] = 0;
close(sock); close(sock);
return buffer; return buffer;
} }
char *http_get(char *url) char *http_get(char *url) {
{
url_t parsed_url; url_t parsed_url;
parse_url(url, &parsed_url); parse_url(url, &parsed_url);
char *hostname = parsed_url.hostname; char *hostname = parsed_url.hostname;
@ -377,10 +329,8 @@ char *http_get(char *url)
int port = atoi(parsed_url.port); int port = atoi(parsed_url.port);
int sock = create_socket(hostname, port); int sock = create_socket(hostname, port);
int buffer_size = 1024 * 1024; int buffer_size = 1024 * 1024;
char *buffer = (char *)malloc(buffer_size); char *buffer = malloc(buffer_size);
char request[buffer_size]; char request[buffer_size];
sprintf(request, sprintf(request,
@ -396,22 +346,19 @@ char *http_get(char *url)
(void)headers; (void)headers;
size_t chunk_size_total = 0; size_t chunk_size_total = 0;
size_t actual_buffer_size = buffer_size; size_t actual_buffer_size = buffer_size;
while (true) while (true) {
{
char *header = read_until(sock, "\r\n"); char *header = read_until(sock, "\r\n");
size_t chunk_size = hex_to_int(header); size_t chunk_size = hex_to_int(header);
if (chunk_size == 0) if (chunk_size == 0)
break; break;
size_t remaining = chunk_size; size_t remaining = chunk_size;
while (remaining > 0) while (remaining > 0) {
{
size_t to_read = (remaining < buffer_size) ? remaining : buffer_size; size_t to_read = (remaining < buffer_size) ? remaining : buffer_size;
buffer = (char *)realloc(buffer, actual_buffer_size + to_read + 1); buffer = realloc(buffer, actual_buffer_size + to_read + 1);
actual_buffer_size += to_read; actual_buffer_size += to_read;
size_t bytes_read = recv(sock, buffer + chunk_size_total, to_read, 0); size_t bytes_read = recv(sock, buffer + chunk_size_total, to_read, 0);
chunk_size_total += bytes_read; chunk_size_total += bytes_read;
if (bytes_read <= 0) if (bytes_read <= 0) {
{
fprintf(stderr, "Error reading chunk data\n"); fprintf(stderr, "Error reading chunk data\n");
return NULL; return NULL;
} }
@ -421,9 +368,7 @@ char *http_get(char *url)
buffer[chunk_size_total] = 0; buffer[chunk_size_total] = 0;
close(sock); close(sock);
return buffer; return buffer;
} }
#endif #endif

View File

@ -1,3 +1,26 @@
// Written by retoor@molodetz.nl
// This code defines a simple HTTP client using libcurl in C, providing a function `curl_post` to make POST requests with JSON data, including authorization via a bearer token.
// Uses libcurl for HTTP requests and includes a custom "auth.h" for API key resolution.
// MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: the above copyright
// notice and this permission notice shall be included in all copies or substantial
// portions of the Software. The Software is provided "as is", without warranty of
// any kind, express or implied, including but not limited to the warranties of
// merchantability, fitness for a particular purpose and noninfringement. In no
// event shall the authors or copyright holders be liable for any claim, damages
// or other liability, whether in an action of contract, tort or otherwise, arising
// from, out of or in connection with the software or the use or other dealings in
// the Software.
#ifndef HTTP_CURL #ifndef HTTP_CURL
#define HTTP_CURL #define HTTP_CURL
#include <stdio.h> #include <stdio.h>
@ -6,77 +29,53 @@
#include <curl/curl.h> #include <curl/curl.h>
#include "auth.h" #include "auth.h"
// Buffer to store the response
struct ResponseBuffer { struct ResponseBuffer {
char *data; // Pointer to the response data char *data;
size_t size; // Size of the data size_t size;
}; };
// Callback function to handle the response
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) { static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t total_size = size * nmemb; size_t total_size = size * nmemb;
struct ResponseBuffer *response = (struct ResponseBuffer *)userp; struct ResponseBuffer *response = (struct ResponseBuffer *)userp;
// Reallocate memory to fit new data
char *ptr = realloc(response->data, response->size + total_size + 1); char *ptr = realloc(response->data, response->size + total_size + 1);
if (ptr == NULL) { if (ptr == NULL) {
fprintf(stderr, "Failed to allocate memory for response\n"); fprintf(stderr, "Failed to allocate memory for response\n");
return 0; // Returning 0 will signal libcurl to abort the request return 0;
} }
// Assign the newly allocated memory to response->data
response->data = ptr; response->data = ptr;
// Copy the new data into the buffer
memcpy(&(response->data[response->size]), contents, total_size); memcpy(&(response->data[response->size]), contents, total_size);
// Update the size of the buffer
response->size += total_size; response->size += total_size;
// Null-terminate the string
response->data[response->size] = '\0'; response->data[response->size] = '\0';
return total_size; return total_size;
} }
char *curl_post(const char *url, const char *data) { char *curl_post(const char *url, const char *data) {
CURL *curl; CURL *curl;
CURLcode res; CURLcode res;
struct ResponseBuffer response; struct ResponseBuffer response;
response.data = (char *)malloc(1); response.data = malloc(1);
response.size = 0; response.size = 0;
curl = curl_easy_init(); curl = curl_easy_init();
if (curl) { if (curl) {
struct curl_slist *headers = NULL; struct curl_slist *headers = NULL;
curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_URL, url);
headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "Content-Type: application/json");
char *bearer_header = malloc(1337);
char * bearer_header = (char *)malloc(1337);
sprintf(bearer_header, "Authorization: Bearer %s", resolve_api_key()); sprintf(bearer_header, "Authorization: Bearer %s", resolve_api_key());
headers = curl_slist_append(headers, bearer_header); headers = curl_slist_append(headers, bearer_header);
free(bearer_header); free(bearer_header);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
res = curl_easy_perform(curl); res = curl_easy_perform(curl);
if (res != CURLE_OK) { if (res != CURLE_OK) {
fprintf(stderr, "Error occured: %s\n", curl_easy_strerror(res)); fprintf(stderr, "An error occurred: %s\n", curl_easy_strerror(res));
} }
curl_slist_free_all(headers); curl_slist_free_all(headers);
curl_easy_cleanup(curl); curl_easy_cleanup(curl);
return response.data; return response.data;
} }
return NULL;
return 0;
} }
#endif #endif

View File

@ -10,6 +10,8 @@
#include <regex.h> #include <regex.h>
#include "http.h" #include "http.h"
#include "url.h" #include "url.h"
#include <stdlib.h>
#include <string.h>
void extract_urls(const char *input, char **urls, int *url_count) { void extract_urls(const char *input, char **urls, int *url_count) {
const char *pattern = "https?://[^ ]+"; const char *pattern = "https?://[^ ]+";
@ -29,18 +31,18 @@ void extract_urls(const char *input, char **urls, int *url_count) {
regfree(&regex); regfree(&regex);
} }
void inplace_urls_markdown_style(char *input, char **urls, char **contents, int url_count) { void inplace_urls_markdown_style(char **input, char **urls, char **contents, int url_count) {
for (int i = 0; i < url_count; i++) { for (int i = 0; i < url_count; i++) {
char *found = strstr(input, urls[i]); char *found = strstr(*input, urls[i]);
if (found) { if (found) {
char *new_text = (char *)malloc(strlen(input) + strlen(contents[i]) - strlen(urls[i]) + 1); char *new_text = (char *)malloc(strlen(*input) + strlen(contents[i]) - strlen(urls[i]) + 1);
strncpy(new_text, input, found - input); strncpy(new_text, *input, found - *input);
new_text[found - input] = '\0'; new_text[found - *input] = '\0';
strcat(new_text, contents[i]); strcat(new_text, contents[i]);
strcat(new_text, found + strlen(urls[i])); strcat(new_text, found + strlen(urls[i]));
free(input); free(*input);
input = new_text; *input = new_text;
} }
} }
} }

2
line.h
View File

@ -10,6 +10,8 @@
#include <readline/readline.h> #include <readline/readline.h>
#include <readline/history.h> #include <readline/history.h>
#include <string.h>
#include <stdbool.h>
#define HISTORY_FILE "~/.calpaca_history" #define HISTORY_FILE "~/.calpaca_history"

View File

@ -1,6 +1,6 @@
// Written by retoor@molodetz.nl // Written by retoor@molodetz.nl
// This program provides functionality to highlight keywords in source code with ANSI color formatting and to convert Markdown syntax into ANSI-colored text output. // This program provides functionality to highlight the keywords in source code using ANSI color formatting and convert Markdown syntax into ANSI-colored text output.
// Uses standard C libraries: <stdio.h>, <string.h>. Also utilizes ANSI escape codes for text formatting. // Uses standard C libraries: <stdio.h>, <string.h>. Also utilizes ANSI escape codes for text formatting.
@ -106,8 +106,9 @@ void parse_markdown_to_ansi(const char *markdown) {
} }
} }
code_buffer[index] = 0; code_buffer[index] = 0;
if(index) if (index) {
highlight_code(code_buffer); highlight_code(code_buffer);
}
} else { } else {
if (strncmp(ptr, "**", 2) == 0) { if (strncmp(ptr, "**", 2) == 0) {
printf(BOLD); printf(BOLD);
@ -115,15 +116,13 @@ void parse_markdown_to_ansi(const char *markdown) {
while (*ptr && strncmp(ptr, "**", 2) != 0) putchar(*ptr++); while (*ptr && strncmp(ptr, "**", 2) != 0) putchar(*ptr++);
if (*ptr == '*' && *(ptr + 1) == '*') ptr += 2; if (*ptr == '*' && *(ptr + 1) == '*') ptr += 2;
printf(RESET); printf(RESET);
} } else if (*ptr == '*' && (ptr == markdown || *(ptr - 1) != '*')) {
else if (*ptr == '*' && (ptr == markdown || *(ptr - 1) != '*')) {
printf(ITALIC); printf(ITALIC);
ptr++; ptr++;
while (*ptr && *ptr != '*') putchar(*ptr++); while (*ptr && *ptr != '*') putchar(*ptr++);
if (*ptr == '*') ptr++; if (*ptr == '*') ptr++;
printf(RESET); printf(RESET);
} } else if (strncmp(ptr, "### ", 4) == 0) {
else if (strncmp(ptr, "### ", 4) == 0) {
printf(BOLD FG_YELLOW); printf(BOLD FG_YELLOW);
ptr += 4; ptr += 4;
while (*ptr && *ptr != '\n') putchar(*ptr++); while (*ptr && *ptr != '\n') putchar(*ptr++);

View File

@ -2,7 +2,7 @@
// This code manages a collection of messages using JSON objects. It provides functions to retrieve all messages as a JSON array, add a new message with a specified role and content, and free the allocated resources. // This code manages a collection of messages using JSON objects. It provides functions to retrieve all messages as a JSON array, add a new message with a specified role and content, and free the allocated resources.
// Includes external library <json-c/json.h> for JSON manipulation // Uses the external library <json-c/json.h> for JSON manipulation
// MIT License // MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
@ -11,18 +11,19 @@
#ifndef R_MESSAGES_H #ifndef R_MESSAGES_H
#define R_MESSAGES_H #define R_MESSAGES_H
#include "json-c/json.h" #include "json-c/json.h"
struct json_object *_message_array = NULL; struct json_object *message_array = NULL;
struct json_object *message_list() { struct json_object *message_list() {
if (_message_array == NULL) { if (!message_array) {
_message_array = json_object_new_array(); message_array = json_object_new_array();
} }
return _message_array; return message_array;
} }
struct json_object *message_add(char *role, char *content) { struct json_object *message_add(const char *role, const char *content) {
struct json_object *messages = message_list(); struct json_object *messages = message_list();
struct json_object *message = json_object_new_object(); struct json_object *message = json_object_new_object();
json_object_object_add(message, "role", json_object_new_string(role)); json_object_object_add(message, "role", json_object_new_string(role));
@ -36,9 +37,10 @@ char *message_json() {
} }
void message_free() { void message_free() {
if (_message_array != NULL) { if (message_array) {
json_object_put(_message_array); json_object_put(message_array);
_message_array = NULL; message_array = NULL;
} }
} }
#endif #endif

View File

@ -27,7 +27,6 @@ bool openai_system(char *content) {
char* data = chat_json("system", content); char* data = chat_json("system", content);
char* result = curl_post(url, data); char* result = curl_post(url, data);
bool is_done = result != NULL; bool is_done = result != NULL;
free(result); free(result);
return is_done; return is_done;
} }
@ -69,9 +68,7 @@ char *openai_chat(char *role, char *content) {
free(data); free(data);
free(result); free(result);
char* final_result = strdup(content_str); char* final_result = strdup(content_str);
json_object_put(parsed_json); json_object_put(parsed_json);
return final_result; return final_result;
} }

View File

@ -17,13 +17,12 @@
bool plugin_initialized = false; bool plugin_initialized = false;
bool plugin_construct() { bool plugin_construct() {
if (plugin_initialized) if (plugin_initialized) return true;
return true;
Py_Initialize(); Py_Initialize();
if (!Py_IsInitialized()) { if (!Py_IsInitialized()) {
fprintf(stderr, "Failed to initialize Python interpreter\n"); fprintf(stderr, "Failed to initialize the Python interpreter\n");
return plugin_initialized; return plugin_initialized;
} }
plugin_initialized = true; plugin_initialized = true;
@ -54,6 +53,5 @@ void plugin_run(char *src) {
} }
void plugin_destruct() { void plugin_destruct() {
if (plugin_initialized) if (plugin_initialized) Py_Finalize();
Py_Finalize();
} }