102 lines
2.4 KiB
C
102 lines
2.4 KiB
C
#include <curl/curl.h>
|
|
#include <libxml/parser.h>
|
|
#include <libxml/tree.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <time.h>
|
|
|
|
#include "craigslist.h"
|
|
#include "common.h"
|
|
|
|
static WINDOW* window = NULL;
|
|
static CURL* curl = NULL;
|
|
static int width = 0;
|
|
static int height = 0;
|
|
static struct MemoryStruct car_data;
|
|
|
|
void craigslist_init(WINDOW* win, int h, int w)
|
|
{
|
|
// setup curl
|
|
curl = curl_easy_init();
|
|
width = w;
|
|
height = h;
|
|
window = win;
|
|
|
|
mvwprintw(window, 0, START_COL, " Craigslist ");
|
|
mvwprintw(window, START_ROW, START_COL, "Pinging...");
|
|
if (curl == NULL)
|
|
{
|
|
wattron(window, COLOR_PAIR(COLORS_FAILURE));
|
|
mvwprintw(window, 0, TITLE_START_COL, " ERROR ");
|
|
mvwprintw(window, START_ROW, START_COL, "Failed to initialize libcurl!");
|
|
wattroff(window, COLOR_PAIR(COLORS_FAILURE));
|
|
curl_global_cleanup();
|
|
}
|
|
|
|
CURLcode res;
|
|
car_data = geturl(curl, "https://sapi.craigslist.org/web/v8/postings/search/full?batch=1-0-360-0-0&bundleDuplicates=1&cc=US&lang=en&language=5&max_price=2000&purveyor=owner&searchPath=cta", &res);
|
|
|
|
if (res != CURLE_OK)
|
|
{
|
|
on_curl_error(window, res);
|
|
}
|
|
|
|
wrefresh(window);
|
|
}
|
|
|
|
bool parse_rand_craigslist(const char* json, char* name, unsigned* price)
|
|
{
|
|
srand(time(NULL));
|
|
const char* items = strstr(json, ",\"items\":[[");
|
|
if (items == NULL)
|
|
return FALSE;
|
|
|
|
int r = rand() % 400;
|
|
int i = 0;
|
|
const char* start_item = items;
|
|
const char* end_item = items;
|
|
do
|
|
{
|
|
start_item = strstr(end_item, "],\"");
|
|
end_item = strstr(start_item, "\"]");
|
|
}
|
|
while (i++ < r && strstr(end_item, "],\""));
|
|
strncpy(name, start_item + 3, end_item - start_item - 3);
|
|
//*price = atoi();
|
|
*price = 0;
|
|
return TRUE;
|
|
}
|
|
|
|
void* craigslist_refresh(void* arg)
|
|
{
|
|
// clear status lines
|
|
for (int i = START_ROW; i < START_ROW+3; ++i)
|
|
{
|
|
for (int j = START_COL; j < width - 1; ++j)
|
|
mvwprintw(window, i, j, " ");
|
|
}
|
|
|
|
char result[256] = {0};
|
|
unsigned price;
|
|
if (parse_rand_craigslist(car_data.memory, result, &price))
|
|
{
|
|
mvwprintw(window, START_ROW, START_COL, "%s", result);
|
|
}
|
|
else
|
|
{
|
|
wattron(window, COLOR_PAIR(COLORS_FAILURE));
|
|
mvwprintw(window, START_ROW, START_COL, "Failed to parse Craigslist result");
|
|
wattroff(window, COLOR_PAIR(COLORS_FAILURE));
|
|
}
|
|
|
|
// refresh view
|
|
wrefresh(window);
|
|
}
|
|
|
|
void craigslist_destroy()
|
|
{
|
|
if (curl != NULL)
|
|
curl_easy_cleanup(curl);
|
|
free(car_data.memory);
|
|
}
|