remwharead  0.7.1
Public Member Functions | Protected Member Functions | Protected Attributes | List of all members
remwharead::URI Class Reference

Download, archive and process an URI. More...

#include <remwharead/uri.hpp>

Public Member Functions

 URI (const string &uri)
 Construct object and set URL. More...
 
const html_extract get ()
 Download URI and extract title, description and full text. More...
 
const archive_answer archive ()
 Save URI in archive and return archive-URI. More...
 

Protected Member Functions

const string make_request (const string &uri, bool archive=false) const
 Make a HTTP(S) request. More...
 
const string extract_title (const string &html)
 Extract the title from an HTML page. More...
 
const string extract_description (const string &html)
 Extract the description from an HTML page. More...
 
const string strip_html (const string &html)
 Removes HTML tags and superflous spaces from an HTML page. More...
 
const string remove_html_tags (const string &html, const string &tag="")
 Remove HTML tags. More...
 
const string unescape_html (const string &html)
 Convert HTML entities to UTF-8. More...
 
const string remove_newlines (string text)
 Replace newlines with spaces. More...
 

Protected Attributes

string _uri
 

Detailed Description

Download, archive and process an URI.

Since
0.6.0

Constructor & Destructor Documentation

◆ URI()

remwharead::URI::URI ( const string &  uri)
explicit

Construct object and set URL.

Initializes TLS and sets proxy from the environment variable http_proxy, if possible.

Since
0.6.0
65  :_uri(uri)
66  {
67  Poco::Net::initializeSSL();
68 
69  try
70  {
71  HTTPClientSession::ProxyConfig proxy;
72  string proxy_env = Environment::get("http_proxy");
73  size_t pos;
74 
75  // Only keep text between // and /.
76  if ((pos = proxy_env.find("//")) != string::npos)
77  {
78  proxy_env = proxy_env.substr(pos + 2);
79  }
80  if ((pos = proxy_env.find('/')) != string::npos)
81  {
82  proxy_env = proxy_env.substr(0, pos);
83  }
84 
85  if ((pos = proxy_env.find(':')) != string::npos)
86  {
87  proxy.host = proxy_env.substr(0, pos);
88  proxy.port = std::stoi(proxy_env.substr(pos + 1));
89  }
90  else
91  {
92  proxy.host = proxy_env;
93  }
94 
95  HTTPClientSession::setGlobalProxyConfig(proxy);
96  }
97  catch (const std::exception &)
98  {
99  // No proxy found, no problem.
100  }
101  }

Member Function Documentation

◆ archive()

const archive_answer remwharead::URI::archive ( )

Save URI in archive and return archive-URI.

Since
0.6.0
592  {
593  if (_uri.substr(0, 4) != "http")
594  {
595  return { false, "Only HTTP(S) is archivable.", "" };
596  }
597 
598  try
599  {
600  const string answer = make_request("https://web.archive.org/save/"
601  + _uri, true);
602 
603  if (!answer.empty())
604  {
605  return { true, "", "https://web.archive.org" + answer };
606  }
607  }
608  catch (const Poco::Exception &e)
609  {
610  return { false, e.displayText(), "" };
611  }
612 
613  return { false, "Unknown error.", "" };
614  }
const string make_request(const string &uri, bool archive=false) const
Make a HTTP(S) request.
Definition: uri.cpp:133

◆ extract_description()

const string remwharead::URI::extract_description ( const string &  html)
protected

Extract the description from an HTML page.

Since
0.6.0
220  {
221  const regex re_htmlfile("\\.(.?html?|xml|rss)$");
222  if (_uri.substr(0, 4) == "http" || regex_search(_uri, re_htmlfile))
223  {
224  smatch match;
225  const regex re("description\"[^>]+content=\"([^\"]+)", icase);
226  regex_search(html, match, re);
227  return remove_newlines(strip_html(match[1].str()));
228  }
229 
230  return "";
231  }
const string strip_html(const string &html)
Removes HTML tags and superflous spaces from an HTML page.
Definition: uri.cpp:233
const string remove_newlines(string text)
Replace newlines with spaces.
Definition: uri.cpp:616

◆ extract_title()

const string remwharead::URI::extract_title ( const string &  html)
protected

Extract the title from an HTML page.

Since
0.6.0
207  {
208  const regex re_htmlfile("\\.(.?html?|xml|rss)$");
209  if (_uri.substr(0, 4) == "http" || regex_search(_uri, re_htmlfile))
210  {
211  smatch match;
212  regex_search(html, match, regex("<title>([^<]+)", icase));
213  return remove_newlines(unescape_html(match[1].str()));
214  }
215 
216  return "";
217  }
const string remove_newlines(string text)
Replace newlines with spaces.
Definition: uri.cpp:616
const string unescape_html(const string &html)
Convert HTML entities to UTF-8.
Definition: uri.cpp:291

◆ get()

const html_extract remwharead::URI::get ( )

Download URI and extract title, description and full text.

Since
0.6.0
109  {
110  try
111  {
112  const string answer = make_request(_uri);
113  if (!answer.empty())
114  {
115  return
116  {
117  true,
118  "",
119  extract_title(answer),
120  extract_description(answer),
121  strip_html(answer)
122  };
123  }
124  }
125  catch (const Poco::Exception &e)
126  {
127  return { false, e.displayText(), "", "", "" };
128  }
129 
130  return { false, "Unknown error.", "", "", "" };
131  }
const string strip_html(const string &html)
Removes HTML tags and superflous spaces from an HTML page.
Definition: uri.cpp:233
const string extract_title(const string &html)
Extract the title from an HTML page.
Definition: uri.cpp:206
const string make_request(const string &uri, bool archive=false) const
Make a HTTP(S) request.
Definition: uri.cpp:133
const string extract_description(const string &html)
Extract the description from an HTML page.
Definition: uri.cpp:219

◆ make_request()

const string remwharead::URI::make_request ( const string &  uri,
bool  archive = false 
) const
protected

Make a HTTP(S) request.

Since
0.6.0
134  {
135  Poco::URI poco_uri(uri);
136  string method =
137  archive ? HTTPRequest::HTTP_HEAD : HTTPRequest::HTTP_GET;
138  string path = poco_uri.getPathAndQuery();
139  if (path.empty())
140  {
141  path = "/";
142  }
143 
144  unique_ptr<HTTPClientSession> session;
145  if (poco_uri.getScheme() == "https")
146  {
147  session = make_unique<HTTPSClientSession>(poco_uri.getHost(),
148  poco_uri.getPort());
149  }
150  else if (poco_uri.getScheme() == "http")
151  {
152  session = make_unique<HTTPClientSession>(poco_uri.getHost(),
153  poco_uri.getPort());
154  }
155  else
156  {
157  throw Poco::Exception("Protocol not supported.");
158  }
159 
160  HTTPRequest request(method, path, HTTPMessage::HTTP_1_1);
161  request.set("User-Agent", string("remwharead/") + global::version);
162 
163  HTTPResponse response;
164 
165  session->sendRequest(request);
166  istream &rs = session->receiveResponse(response);
167 
168  // Not using the constants because some are too new for Debian stretch.
169  switch (response.getStatus())
170  {
171  case 301: // HTTPResponse::HTTP_MOVED_PERMANENTLY
172  case 308: // HTTPResponse::HTTP_PERMANENT_REDIRECT
173  case 302: // HTTPResponse::HTTP_FOUND
174  case 303: // HTTPResponse::HTTP_SEE_OTHER
175  case 307: // HTTPResponse::HTTP_TEMPORARY_REDIRECT
176  {
177  string location = response.get("Location");
178  if (location.substr(0, 4) != "http")
179  {
180  location = poco_uri.getScheme() + "://" + poco_uri.getHost()
181  + location;
182  }
183  return make_request(location);
184  }
185  case HTTPResponse::HTTP_OK:
186  {
187  string answer;
188  if (archive)
189  {
190  answer = response.get("Content-Location");
191  }
192  else
193  {
194  StreamCopier::copyToString(rs, answer);
195  }
196  return answer;
197  }
198  default:
199  {
200  throw Poco::Exception(response.getReason());
201  return "";
202  }
203  }
204  }
const string make_request(const string &uri, bool archive=false) const
Make a HTTP(S) request.
Definition: uri.cpp:133
const archive_answer archive()
Save URI in archive and return archive-URI.
Definition: uri.cpp:591

◆ remove_html_tags()

const string remwharead::URI::remove_html_tags ( const string &  html,
const string &  tag = "" 
)
protected

Remove HTML tags.

Parameters
htmlHTML page.
tagIf set, only remove this tag.
Since
0.6.0
254  {
255  // NOTE: I did this with regex_replace before, but libstdc++ segfaulted.
256  string out;
257  if (tag.empty())
258  {
259  size_t pos = 0;
260  while (pos != std::string::npos)
261  {
262  size_t startpos = html.find('<', pos);
263  size_t endpos = html.find('>', startpos);
264  out += html.substr(pos, startpos - pos);
265  pos = endpos;
266  if (pos != std::string::npos)
267  {
268  ++pos;
269  }
270  }
271  }
272  else
273  {
274  size_t pos = 0;
275  out = html;
276  while ((pos = out.find("<" + tag)) != std::string::npos)
277  {
278  size_t endpos = out.find("</" + tag, pos);
279  if (endpos == std::string::npos)
280  {
281  break;
282  }
283  endpos += 3 + tag.length(); // tag + </ + >
284  out.replace(pos, endpos - pos, "");
285  }
286  }
287 
288  return out;
289  }

◆ remove_newlines()

const string remwharead::URI::remove_newlines ( string  text)
protected

Replace newlines with spaces.

Since
0.6.0
617  {
618  size_t posn = 0;
619  while ((posn = text.find('\n', posn)) != std::string::npos)
620  {
621  text.replace(posn, 1, " ");
622 
623  size_t posr = posn - 1;
624  if (text[posr] == '\r')
625  {
626  text.replace(posr, 1, " ");
627  }
628  ++posn;
629  }
630 
631  return text;
632  }

◆ strip_html()

const string remwharead::URI::strip_html ( const string &  html)
protected

Removes HTML tags and superflous spaces from an HTML page.

Since
0.6.0
234  {
235  string out;
236 
237  out = remove_html_tags(html, "script"); // Remove JavaScript.
238  out = remove_html_tags(out, "style"); // Remove CSS.
239  out = remove_html_tags(out); // Remove tags.
240 
241  size_t pos = 0;
242  while ((pos = out.find("\r", pos)) != std::string::npos) // Remove CR.
243  {
244  out.replace(pos, 1, "");
245  }
246 
247  out = regex_replace(out, regex("\\s+\n"), "\n"); // Remove space at eol.
248  out = regex_replace(out, regex("\n{2,}"), "\n"); // Reduce newlines.
249 
250  return unescape_html(out);
251  }
const string remove_html_tags(const string &html, const string &tag="")
Remove HTML tags.
Definition: uri.cpp:253
const string unescape_html(const string &html)
Convert HTML entities to UTF-8.
Definition: uri.cpp:291

◆ unescape_html()

const string remwharead::URI::unescape_html ( const string &  html)
protected

Convert HTML entities to UTF-8.

Since
0.6.0
292  {
293  string buffer = html;
294  string output;
295 
296  // Used to convert int to utf-8 char.
297  std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> u8c;
298  regex re_entity("&#(x)?([[:alnum:]]{1,8});");
299  smatch match;
300 
301  while (regex_search(buffer, match, re_entity))
302  {
303  char32_t codepoint = 0;
304  // 'x' in front of the number means it's hexadecimal, else decimal.
305  if (match[1].length() == 1)
306  {
307  codepoint = std::stoi(match[2].str(), nullptr, 16);
308  }
309  else
310  {
311  codepoint = std::stoi(match[2].str(), nullptr, 10);
312  }
313  output += match.prefix().str() + u8c.to_bytes(codepoint);
314  buffer = match.suffix().str();
315  }
316  output += buffer;
317 
318  // Source: https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_
319  // entity_references#Character_entity_references_in_HTML
320  const array<const std::pair<const string, const char32_t>, 258> names =
321  {{
322  { "exclamation", 0x0021 },
323  { "quot", 0x0022 },
324  { "percent", 0x0025 },
325  { "amp", 0x0026 },
326  { "apos", 0x0027 },
327  { "add", 0x002B },
328  { "lt", 0x003C },
329  { "equal", 0x003D },
330  { "gt", 0x003E },
331  { "nbsp", 0x00A0 },
332  { "iexcl", 0x00A1 },
333  { "cent", 0x00A2 },
334  { "pound", 0x00A3 },
335  { "curren", 0x00A4 },
336  { "yen", 0x00A5 },
337  { "brvbar", 0x00A6 },
338  { "sect", 0x00A7 },
339  { "uml", 0x00A8 },
340  { "copy", 0x00A9 },
341  { "ordf", 0x00AA },
342  { "laquo", 0x00AB },
343  { "not", 0x00AC },
344  { "shy", 0x00AD },
345  { "reg", 0x00AE },
346  { "macr", 0x00AF },
347  { "deg", 0x00B0 },
348  { "plusmn", 0x00B1 },
349  { "sup2", 0x00B2 },
350  { "sup3", 0x00B3 },
351  { "acute", 0x00B4 },
352  { "micro", 0x00B5 },
353  { "para", 0x00B6 },
354  { "middot", 0x00B7 },
355  { "cedil", 0x00B8 },
356  { "sup1", 0x00B9 },
357  { "ordm", 0x00BA },
358  { "raquo", 0x00BB },
359  { "frac14", 0x00BC },
360  { "frac12", 0x00BD },
361  { "frac34", 0x00BE },
362  { "iquest", 0x00BF },
363  { "Agrave", 0x00C0 },
364  { "Aacute", 0x00C1 },
365  { "Acirc", 0x00C2 },
366  { "Atilde", 0x00C3 },
367  { "Auml", 0x00C4 },
368  { "Aring", 0x00C5 },
369  { "AElig", 0x00C6 },
370  { "Ccedil", 0x00C7 },
371  { "Egrave", 0x00C8 },
372  { "Eacute", 0x00C9 },
373  { "Ecirc", 0x00CA },
374  { "Euml", 0x00CB },
375  { "Igrave", 0x00CC },
376  { "Iacute", 0x00CD },
377  { "Icirc", 0x00CE },
378  { "Iuml", 0x00CF },
379  { "ETH", 0x00D0 },
380  { "Ntilde", 0x00D1 },
381  { "Ograve", 0x00D2 },
382  { "Oacute", 0x00D3 },
383  { "Ocirc", 0x00D4 },
384  { "Otilde", 0x00D5 },
385  { "Ouml", 0x00D6 },
386  { "times", 0x00D7 },
387  { "Oslash", 0x00D8 },
388  { "Ugrave", 0x00D9 },
389  { "Uacute", 0x00DA },
390  { "Ucirc", 0x00DB },
391  { "Uuml", 0x00DC },
392  { "Yacute", 0x00DD },
393  { "THORN", 0x00DE },
394  { "szlig", 0x00DF },
395  { "agrave", 0x00E0 },
396  { "aacute", 0x00E1 },
397  { "acirc", 0x00E2 },
398  { "atilde", 0x00E3 },
399  { "auml", 0x00E4 },
400  { "aring", 0x00E5 },
401  { "aelig", 0x00E6 },
402  { "ccedil", 0x00E7 },
403  { "egrave", 0x00E8 },
404  { "eacute", 0x00E9 },
405  { "ecirc", 0x00EA },
406  { "euml", 0x00EB },
407  { "igrave", 0x00EC },
408  { "iacute", 0x00ED },
409  { "icirc", 0x00EE },
410  { "iuml", 0x00EF },
411  { "eth", 0x00F0 },
412  { "ntilde", 0x00F1 },
413  { "ograve", 0x00F2 },
414  { "oacute", 0x00F3 },
415  { "ocirc", 0x00F4 },
416  { "otilde", 0x00F5 },
417  { "ouml", 0x00F6 },
418  { "divide", 0x00F7 },
419  { "oslash", 0x00F8 },
420  { "ugrave", 0x00F9 },
421  { "uacute", 0x00FA },
422  { "ucirc", 0x00FB },
423  { "uuml", 0x00FC },
424  { "yacute", 0x00FD },
425  { "thorn", 0x00FE },
426  { "yuml", 0x00FF },
427  { "OElig", 0x0152 },
428  { "oelig", 0x0153 },
429  { "Scaron", 0x0160 },
430  { "scaron", 0x0161 },
431  { "Yuml", 0x0178 },
432  { "fnof", 0x0192 },
433  { "circ", 0x02C6 },
434  { "tilde", 0x02DC },
435  { "Alpha", 0x0391 },
436  { "Beta", 0x0392 },
437  { "Gamma", 0x0393 },
438  { "Delta", 0x0394 },
439  { "Epsilon", 0x0395 },
440  { "Zeta", 0x0396 },
441  { "Eta", 0x0397 },
442  { "Theta", 0x0398 },
443  { "Iota", 0x0399 },
444  { "Kappa", 0x039A },
445  { "Lambda", 0x039B },
446  { "Mu", 0x039C },
447  { "Nu", 0x039D },
448  { "Xi", 0x039E },
449  { "Omicron", 0x039F },
450  { "Pi", 0x03A0 },
451  { "Rho", 0x03A1 },
452  { "Sigma", 0x03A3 },
453  { "Tau", 0x03A4 },
454  { "Upsilon", 0x03A5 },
455  { "Phi", 0x03A6 },
456  { "Chi", 0x03A7 },
457  { "Psi", 0x03A8 },
458  { "Omega", 0x03A9 },
459  { "alpha", 0x03B1 },
460  { "beta", 0x03B2 },
461  { "gamma", 0x03B3 },
462  { "delta", 0x03B4 },
463  { "epsilon", 0x03B5 },
464  { "zeta", 0x03B6 },
465  { "eta", 0x03B7 },
466  { "theta", 0x03B8 },
467  { "iota", 0x03B9 },
468  { "kappa", 0x03BA },
469  { "lambda", 0x03BB },
470  { "mu", 0x03BC },
471  { "nu", 0x03BD },
472  { "xi", 0x03BE },
473  { "omicron", 0x03BF },
474  { "pi", 0x03C0 },
475  { "rho", 0x03C1 },
476  { "sigmaf", 0x03C2 },
477  { "sigma", 0x03C3 },
478  { "tau", 0x03C4 },
479  { "upsilon", 0x03C5 },
480  { "phi", 0x03C6 },
481  { "chi", 0x03C7 },
482  { "psi", 0x03C8 },
483  { "omega", 0x03C9 },
484  { "thetasym", 0x03D1 },
485  { "upsih", 0x03D2 },
486  { "piv", 0x03D6 },
487  { "ensp", 0x2002 },
488  { "emsp", 0x2003 },
489  { "thinsp", 0x2009 },
490  { "zwnj", 0x200C },
491  { "zwj", 0x200D },
492  { "lrm", 0x200E },
493  { "rlm", 0x200F },
494  { "ndash", 0x2013 },
495  { "mdash", 0x2014 },
496  { "horbar", 0x2015 },
497  { "lsquo", 0x2018 },
498  { "rsquo", 0x2019 },
499  { "sbquo", 0x201A },
500  { "ldquo", 0x201C },
501  { "rdquo", 0x201D },
502  { "bdquo", 0x201E },
503  { "dagger", 0x2020 },
504  { "Dagger", 0x2021 },
505  { "bull", 0x2022 },
506  { "hellip", 0x2026 },
507  { "permil", 0x2030 },
508  { "prime", 0x2032 },
509  { "Prime", 0x2033 },
510  { "lsaquo", 0x2039 },
511  { "rsaquo", 0x203A },
512  { "oline", 0x203E },
513  { "frasl", 0x2044 },
514  { "euro", 0x20AC },
515  { "image", 0x2111 },
516  { "weierp", 0x2118 },
517  { "real", 0x211C },
518  { "trade", 0x2122 },
519  { "alefsym", 0x2135 },
520  { "larr", 0x2190 },
521  { "uarr", 0x2191 },
522  { "rarr", 0x2192 },
523  { "darr", 0x2193 },
524  { "harr", 0x2194 },
525  { "crarr", 0x21B5 },
526  { "lArr", 0x21D0 },
527  { "uArr", 0x21D1 },
528  { "rArr", 0x21D2 },
529  { "dArr", 0x21D3 },
530  { "hArr", 0x21D4 },
531  { "forall", 0x2200 },
532  { "part", 0x2202 },
533  { "exist", 0x2203 },
534  { "empty", 0x2205 },
535  { "nabla", 0x2207 },
536  { "isin", 0x2208 },
537  { "notin", 0x2209 },
538  { "ni", 0x220B },
539  { "prod", 0x220F },
540  { "sum", 0x2211 },
541  { "minus", 0x2212 },
542  { "lowast", 0x2217 },
543  { "radic", 0x221A },
544  { "prop", 0x221D },
545  { "infin", 0x221E },
546  { "ang", 0x2220 },
547  { "and", 0x2227 },
548  { "or", 0x2228 },
549  { "cap", 0x2229 },
550  { "cup", 0x222A },
551  { "int", 0x222B },
552  { "there4", 0x2234 },
553  { "sim", 0x223C },
554  { "cong", 0x2245 },
555  { "asymp", 0x2248 },
556  { "ne", 0x2260 },
557  { "equiv", 0x2261 },
558  { "le", 0x2264 },
559  { "ge", 0x2265 },
560  { "sub", 0x2282 },
561  { "sup", 0x2283 },
562  { "nsub", 0x2284 },
563  { "sube", 0x2286 },
564  { "supe", 0x2287 },
565  { "oplus", 0x2295 },
566  { "otimes", 0x2297 },
567  { "perp", 0x22A5 },
568  { "sdot", 0x22C5 },
569  { "lceil", 0x2308 },
570  { "rceil", 0x2309 },
571  { "lfloor", 0x230A },
572  { "rfloor", 0x230B },
573  { "lang", 0x2329 },
574  { "rang", 0x232A },
575  { "loz", 0x25CA },
576  { "spades", 0x2660 },
577  { "clubs", 0x2663 },
578  { "hearts", 0x2665 },
579  { "diams", 0x2666 }
580  }};
581 
582  for (auto &pair : names)
583  {
584  const regex re('&' + pair.first + ';');
585  output = regex_replace(output, re, u8c.to_bytes(pair.second));
586  }
587 
588  return output;
589  }

The documentation for this class was generated from the following files: