diff options
Diffstat (limited to 'handler.c')
| -rw-r--r-- | handler.c | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/handler.c b/handler.c new file mode 100644 index 0000000..8e118f7 --- /dev/null +++ b/handler.c @@ -0,0 +1,62 @@ +#include <stdbool.h> +#include <tidy.h> +#include <tidybuffio.h> +#include <icclient.h> + +static void recurse_catalog(TidyDoc doc, TidyNode tnod, struct icclient_catalog **catalog) +{ + for (TidyNode child = tidyGetChild(tnod); child; child = tidyGetNext(child)) { + ctmbstr name = tidyNodeGetName(child); + if (!name) + continue; + if (strcmp(name, "img")) { + recurse_catalog(doc, child, catalog); + continue; + } + static const char *prefix = IMAGE_DIR"/thumb/"; + size_t prefix_len = strlen(prefix); + bool bail = false; + for (TidyAttr attr = tidyAttrFirst(child); attr; attr = tidyAttrNext(attr)) + if (!strcmp(tidyAttrName(attr), "src") && strncmp(tidyAttrValue(attr), prefix, prefix_len)) { + bail = true; + break; + } + if (bail) + continue; + struct icclient_product *product = malloc(sizeof(struct icclient_product)); + memset(product, '\0', sizeof(struct icclient_product)); + for (TidyAttr attr = tidyAttrFirst(child); attr; attr = tidyAttrNext(attr)) { + name = tidyAttrName(attr); + ctmbstr value = tidyAttrValue(attr); + if (!strcmp(name, "src")) { + size_t len = strlen(value) - prefix_len; + product->image = malloc(len + 1); + strncpy(product->image, value + prefix_len, len + 1); + } else if (!strcmp(name, "alt")) { + product->description = malloc(strlen(value) + 1); + strcpy(product->description, value); + } else if (!strcmp(name, "title")) { + product->sku = malloc(strlen(value + 1)); + strcpy(product->sku, value); + } + } + (*catalog)->length++; + *catalog = realloc(*catalog, sizeof(struct icclient_catalog) + + sizeof(struct icclient_product *[(*catalog)->length])); + (*catalog)->products[(*catalog)->length - 1] = product; + } +} + +struct icclient_catalog *catalog_data(const char *response) +{ + TidyDoc tdoc = tidyCreate(); + TidyBuffer output = {0}; + tidyParseString(tdoc, response); + tidySaveBuffer(tdoc, &output); + struct icclient_catalog *catalog = malloc(sizeof(struct icclient_catalog)); + catalog->length = 0; + recurse_catalog(tdoc, tidyGetRoot(tdoc), &catalog); + tidyBufFree(&output); + tidyRelease(tdoc); + return catalog; +} |