remwharead  0.6.3
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
588  {
589  if (_uri.substr(0, 4) != "http")
590  {
591  return { false, "Only HTTP(S) is archivable.", "" };
592  }
593 
594  try
595  {
596  const string answer = make_request("https://web.archive.org/save/"
597  + _uri, true);
598 
599  if (!answer.empty())
600  {
601  return { true, "", "https://web.archive.org" + answer };
602  }
603  }
604  catch (const Poco::Exception &e)
605  {
606  return { false, e.displayText(), "" };
607  }
608 
609  return { false, "Unknown error.", "" };
610  }
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
216  {
217  const regex re_htmlfile("\\.(.?html?|xml|rss)$");
218  if (_uri.substr(0, 4) == "http" || regex_search(_uri, re_htmlfile))
219  {
220  smatch match;
221  const regex re("description\"[^>]+content=\"([^\"]+)", icase);
222  regex_search(html, match, re);
223  return remove_newlines(strip_html(match[1].str()));
224  }
225 
226  return "";
227  }
const string strip_html(const string &html)
Removes HTML tags and superflous spaces from an HTML page.
Definition: uri.cpp:229
const string remove_newlines(string text)
Replace newlines with spaces.
Definition: uri.cpp:612

◆ extract_title()

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

Extract the title from an HTML page.

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

◆ 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:229
const string extract_title(const string &html)
Extract the title from an HTML page.
Definition: uri.cpp:202
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:215

◆ 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 
156  HTTPRequest request(method, path, HTTPMessage::HTTP_1_1);
157  request.set("User-Agent", string("remwharead/") + global::version);
158 
159  HTTPResponse response;
160 
161  session->sendRequest(request);
162  istream &rs = session->receiveResponse(response);
163 
164  // Not using the constants because some are too new for Debian stretch.
165  switch (response.getStatus())
166  {
167  case 301: // HTTPResponse::HTTP_MOVED_PERMANENTLY
168  case 308: // HTTPResponse::HTTP_PERMANENT_REDIRECT
169  case 302: // HTTPResponse::HTTP_FOUND
170  case 303: // HTTPResponse::HTTP_SEE_OTHER
171  case 307: // HTTPResponse::HTTP_TEMPORARY_REDIRECT
172  {
173  string location = response.get("Location");
174  if (location.substr(0, 4) != "http")
175  {
176  location = poco_uri.getScheme() + "://" + poco_uri.getHost()
177  + location;
178  }
179  return make_request(location);
180  }
181  case HTTPResponse::HTTP_OK:
182  {
183  string answer;
184  if (archive)
185  {
186  answer = response.get("Content-Location");
187  }
188  else
189  {
190  StreamCopier::copyToString(rs, answer);
191  }
192  return answer;
193  }
194  default:
195  {
196  throw Poco::Exception(response.getReason());
197  return "";
198  }
199  }
200  }
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:587

◆ 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
250  {
251  // NOTE: I did this with regex_replace before, but libstdc++ segfaulted.
252  string out;
253  if (tag.empty())
254  {
255  size_t pos = 0;
256  while (pos != std::string::npos)
257  {
258  size_t startpos = html.find('<', pos);
259  size_t endpos = html.find('>', startpos);
260  out += html.substr(pos, startpos - pos);
261  pos = endpos;
262  if (pos != std::string::npos)
263  {
264  ++pos;
265  }
266  }
267  }
268  else
269  {
270  size_t pos = 0;
271  out = html;
272  while ((pos = out.find("<" + tag)) != std::string::npos)
273  {
274  size_t endpos = out.find("</" + tag, pos);
275  if (endpos == std::string::npos)
276  {
277  break;
278  }
279  endpos += 3 + tag.length(); // tag + </ + >
280  out.replace(pos, endpos - pos, "");
281  }
282  }
283 
284  return out;
285  }

◆ remove_newlines()

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

Replace newlines with spaces.

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

◆ 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
230  {
231  string out;
232 
233  out = remove_html_tags(html, "script"); // Remove JavaScript.
234  out = remove_html_tags(out, "style"); // Remove CSS.
235  out = remove_html_tags(out); // Remove tags.
236 
237  size_t pos = 0;
238  while ((pos = out.find("\r", pos)) != std::string::npos) // Remove CR.
239  {
240  out.replace(pos, 1, "");
241  }
242 
243  out = regex_replace(out, regex("\\s+\n"), "\n"); // Remove space at eol.
244  out = regex_replace(out, regex("\n{2,}"), "\n"); // Reduce newlines.
245 
246  return unescape_html(out);
247  }
const string remove_html_tags(const string &html, const string &tag="")
Remove HTML tags.
Definition: uri.cpp:249
const string unescape_html(const string &html)
Convert HTML entities to UTF-8.
Definition: uri.cpp:287

◆ unescape_html()

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

Convert HTML entities to UTF-8.

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

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