aboutsummaryrefslogtreecommitdiff
path: root/src/parse.c
blob: fe7b2b1fffd7b689fc569f3a3c6536ec213b45ba (plain) (blame)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#include "parse.h"

#include <curl/curl.h>
#include <libxml/HTMLparser.h>
#include <libxml/xpath.h>
#include <string.h>
#include <time.h>

#include "log.h"

static void extract_text_from_html(xmlChar* body, xmlChar** output) {
  htmlDocPtr doc = NULL;
  xmlXPathContextPtr xpath_ctx = NULL;
  xmlXPathObjectPtr xpath_obj = NULL;
  *output = NULL;

  if (!(doc = htmlParseDoc(body, "UTF-8"))) {
    return;
  }

  if (!(xpath_ctx = xmlXPathNewContext(doc))) {
    goto done;
  }

  if (!(xpath_obj =
            xmlXPathEvalExpression(BAD_CAST "//child::text()", xpath_ctx))) {
    goto done;
  }

  size_t len = 0;
  *output = calloc(RSSMAIL_POST_MAX_FIELD_LENGTH, sizeof(xmlChar));
  for (int i = 0; i < xpath_obj->nodesetval->nodeNr; ++i) {
    xmlNodePtr node = xpath_obj->nodesetval->nodeTab[i];
    xmlChar* contents = xmlNodeGetContent(node);
    if (contents != NULL) {
      size_t contents_len =
          strnlen((char*)contents, RSSMAIL_POST_MAX_FIELD_LENGTH - len);
      if (contents_len + len < RSSMAIL_POST_MAX_FIELD_LENGTH) {
        strncat(&((char*)(*output))[len], (char*)contents, contents_len);
      } else {
        LOG_DEBUG(
            "Maximum field length (%d) was met while parsing HTML; text will "
            "be "
            "truncated",
            RSSMAIL_POST_MAX_FIELD_LENGTH);

        free(contents);

        break;
      }

      free(contents);
    }
  }

done:
  if (xpath_obj != NULL) {
    xmlXPathFreeObject(xpath_obj);
  }

  if (xpath_ctx != NULL) {
    xmlXPathFreeContext(xpath_ctx);
  }

  if (doc != NULL) {
    xmlFreeDoc(doc);
  }
}

static void extract_content_by_xpath(xmlXPathContextPtr xpath_ctx,
                                     xmlNodePtr parent, const xmlChar* expr,
                                     xmlChar** output) {
  xmlXPathObjectPtr obj = xmlXPathNodeEval(parent, expr, xpath_ctx);

  if (obj == NULL) {
    LOG_ERROR("Failed to evaluate XPath expression \"%s\"", expr);
    *output = NULL;
    return;
  }

  *output = obj->nodesetval->nodeNr == 0
                ? NULL
                : xmlNodeGetContent(obj->nodesetval->nodeTab[0]);

  if (*output == NULL) {
    LOG_DEBUG("Couldn't find any content matching xpath expression \"%s\"",
              expr);
  }

  xmlXPathFreeObject(obj);
}

static void extract_parts_from_node(xmlXPathContextPtr xpath_ctx,
                                    xmlNodePtr node, xmlChar** title,
                                    xmlChar** desc, xmlChar** url) {
  extract_content_by_xpath(xpath_ctx, node, BAD_CAST "title[1]", title);

  extract_content_by_xpath(xpath_ctx, node, BAD_CAST "link[1]", url);

  xmlChar* desc_body;
  extract_content_by_xpath(xpath_ctx, node,
                           BAD_CAST "description/descendant-or-self::*/text()",
                           &desc_body);

  if (desc_body != NULL) {
    extract_text_from_html(desc_body, desc);
    xmlFree(desc_body);
  } else {
    *desc = NULL;
  }

  // perform some debug logging
  // (the rest of the function after this line should be optimized away on
  // release builds)

  if (title != NULL && *title != NULL) {
    LOG_DEBUG("Title: %s", *title);
  } else {
    LOG_DEBUG("Missing title");
  }

  if (desc != NULL && *desc != NULL) {
    LOG_DEBUG("Description: %s", *desc);
  } else {
    LOG_DEBUG("Missing description");
  }

  if (url != NULL && *url != NULL) {
    LOG_DEBUG("URL: %s", *url);
  } else {
    LOG_DEBUG("Missing URL");
  }
}

static int get_node_published_age(xmlXPathContextPtr xpath_ctx,
                                  xmlNodePtr node) {
  xmlChar* text = NULL;
  extract_content_by_xpath(xpath_ctx, node, BAD_CAST "pubDate[1]", &text);
  if (text != NULL) {
    time_t timestamp = curl_getdate((char*)text, NULL);
    xmlFree(text);
    return (int)(difftime(time(NULL), timestamp) / 60.0);
  }

  LOG_DEBUG(
      "Couldn't determine the publication date of a post, so it will be "
      "included");

  // couldn't get age, return 0 to guarantee inclusion
  return 0;
}

post_item_t* parse_posts_from_doc(xmlDocPtr doc, int* count,
                                  rss_config_t* config) {
  xmlXPathContextPtr xpath_ctx = NULL;
  xmlXPathObjectPtr xpath_obj = NULL;
  post_item_t* buffer = NULL;

  // create xpath context
  if (!(xpath_ctx = xmlXPathNewContext(doc))) {
    LOG_ERROR("Failed to create new XPath context prior to parsing post items");
    goto done;
  }

  if (!(xpath_obj = xmlXPathEvalExpression(BAD_CAST "//item", xpath_ctx))) {
    LOG_ERROR("Failed to evaluate top-level 'item' xpath expression");
    goto done;
  }

  int node_count = xpath_obj->nodesetval->nodeNr;
  int n = 0;

  // for (int i = *count - 1; i >= 0; --i) {
  for (int i = 0; i < node_count; ++i) {
    LOG_DEBUG("Reading node %d of %d", i + 1, node_count);

    xmlNodePtr node = xpath_obj->nodesetval->nodeTab[node_count - i - 1];

    // check age of the post
    int age = get_node_published_age(xpath_ctx, node);
    if (age > config->max_age) {
      LOG_DEBUG(
          "Skipping post with an age of %d minutes over maximum "
          "allowed (age is %d minutes)",
          age - config->max_age, age);
      continue;
    }

    LOG_DEBUG("Post is of a permissible age (%d minutes)", age);

    // if age is good, add the post to the buffer
    post_item_t* expanded = realloc(buffer, (n + 1) * sizeof(post_item_t));
    if (expanded == NULL) {
      LOG_ERROR(
          "Ran out of memory attempting to extract the contents of feed "
          "entries");
      break;
    }

    buffer = expanded;

    post_item_t* item = &buffer[n++];
    extract_parts_from_node(xpath_ctx, node, (xmlChar**)&item->title,
                            (xmlChar**)&item->description,
                            (xmlChar**)&item->url);
  }

  *count = n;

done:
  if (xpath_obj != NULL) {
    xmlXPathFreeObject(xpath_obj);
  }

  if (xpath_ctx != NULL) {
    xmlXPathFreeContext(xpath_ctx);
  }

  return buffer;
}

void init_parse(void) {
  LOG_DEBUG("Initializing LibXML global resources");
  xmlInitParser();
  LIBXML_TEST_VERSION;
}

void cleanup_parse(void) {
  LOG_DEBUG("Cleaning up LibXML global resources");
  xmlCleanupParser();
}