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 <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 string archive ()
 Save URI in archive and return archive-URI. More...
 

Protected Member Functions

const string make_request (const string &uri) 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.

Constructor & Destructor Documentation

◆ URI()

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

Construct object and set URL.

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

Member Function Documentation

◆ archive()

const string remwharead::URI::archive ( )

Save URI in archive and return archive-URI.

569  {
570  if (_uri.substr(0, 4) != "http")
571  {
572  return "";
573  }
574 
575  try
576  {
577  const string answer = make_request("https://web.archive.org/save/"
578  + _uri);
579 
580  smatch match;
581  if (regex_search(answer, match, regex("Content-Location: (.+)\r")))
582  {
583  return "https://web.archive.org" + match[1].str();
584  }
585  else
586  {
587  cerr << "Error: Could not archive page.\n";
588  }
589  }
590  catch (const std::exception &e)
591  {
592  cerr << "Error in " << __func__ << ": " << e.what() << ".\n";
593  }
594 
595  return "";
596  }
const string make_request(const string &uri) const
Make a HTTP(S) request.
Definition: uri.cpp:129

◆ extract_description()

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

Extract the description from an HTML page.

198  {
199  const regex re_htmlfile("\\.(.?html?|xml|rss)$");
200  if (_uri.substr(0, 4) == "http" || regex_search(_uri, re_htmlfile))
201  {
202  smatch match;
203  const regex re("description\"[^>]+content=\"([^\"]+)", icase);
204  regex_search(html, match, re);
205  return remove_newlines(strip_html(match[1].str()));
206  }
207 
208  return "";
209  }
const string strip_html(const string &html)
Removes HTML tags and superflous spaces from an HTML page.
Definition: uri.cpp:211
const string remove_newlines(string text)
Replace newlines with spaces.
Definition: uri.cpp:598

◆ extract_title()

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

Extract the title from an HTML page.

185  {
186  const regex re_htmlfile("\\.(.?html?|xml|rss)$");
187  if (_uri.substr(0, 4) == "http" || regex_search(_uri, re_htmlfile))
188  {
189  smatch match;
190  regex_search(html, match, regex("<title>([^<]+)", icase));
191  return remove_newlines(unescape_html(match[1].str()));
192  }
193 
194  return "";
195  }
const string remove_newlines(string text)
Replace newlines with spaces.
Definition: uri.cpp:598
const string unescape_html(const string &html)
Convert HTML entities to UTF-8.
Definition: uri.cpp:268

◆ get()

const html_extract remwharead::URI::get ( )

Download URI and extract title, description and full text.

100  {
101  try
102  {
103  std::ostringstream oss;
104 
105  const string answer = make_request(_uri);
106  if (answer.empty())
107  {
108  cerr << "Error: Could not download page.\n";
109  }
110  else
111  {
112  return
113  {
114  extract_title(answer),
115  extract_description(answer),
116  strip_html(answer)
117  };
118  }
119  }
120  catch (const std::exception &e)
121  {
122  // Prints something like "SSL Exception", nothing specific.
123  cerr << "Error in " << __func__ << ": " << e.what() << endl;
124  }
125 
126  return { "", "", "" };
127  }
const string strip_html(const string &html)
Removes HTML tags and superflous spaces from an HTML page.
Definition: uri.cpp:211
const string extract_title(const string &html)
Extract the title from an HTML page.
Definition: uri.cpp:184
const string extract_description(const string &html)
Extract the description from an HTML page.
Definition: uri.cpp:197
const string make_request(const string &uri) const
Make a HTTP(S) request.
Definition: uri.cpp:129

◆ make_request()

const string remwharead::URI::make_request ( const string &  uri) const
protected

Make a HTTP(S) request.

130  {
131  Poco::URI poco_uri(uri);
132  string path = poco_uri.getPathAndQuery();
133  if (path.empty())
134  {
135  path = "/";
136  }
137 
138  unique_ptr<HTTPClientSession> session;
139  if (poco_uri.getScheme() == "https")
140  {
141  session = make_unique<HTTPSClientSession>(poco_uri.getHost(),
142  poco_uri.getPort());
143  }
144  else if (poco_uri.getScheme() == "http")
145  {
146  session = make_unique<HTTPClientSession>(poco_uri.getHost(),
147  poco_uri.getPort());
148  }
149 
150  HTTPRequest request(HTTPRequest::HTTP_GET, path,
151  HTTPMessage::HTTP_1_1);
152  request.set("User-Agent", string("remwharead/") + global::version);
153 
154  HTTPResponse response;
155 
156  session->sendRequest(request);
157  istream &rs = session->receiveResponse(response);
158 
159  // Not using the constants because some are too new for Debian stretch.
160  switch (response.getStatus())
161  {
162  case 301: // HTTPResponse::HTTP_MOVED_PERMANENTLY
163  case 308: // HTTPResponse::HTTP_PERMANENT_REDIRECT
164  case 302: // HTTPResponse::HTTP_FOUND
165  case 303: // HTTPResponse::HTTP_SEE_OTHER
166  case 307: // HTTPResponse::HTTP_TEMPORARY_REDIRECT
167  {
168  return make_request(response.get("Location"));
169  }
170  case HTTPResponse::HTTP_OK:
171  {
172  string answer;
173  StreamCopier::copyToString(rs, answer);
174  return answer;
175  }
176  default:
177  {
178  cerr << response.getStatus() << " " << response.getReason() << endl;
179  return "";
180  }
181  }
182  }
const string make_request(const string &uri) const
Make a HTTP(S) request.
Definition: uri.cpp:129

◆ 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.
231  {
232  // NOTE: I did this with regex_replace before, but libstdc++ segfaulted.
233  string out;
234  if (tag.empty())
235  {
236  size_t pos = 0;
237  while (pos != std::string::npos)
238  {
239  size_t startpos = html.find('<', pos);
240  size_t endpos = html.find('>', startpos);
241  out += html.substr(pos, startpos - pos);
242  pos = endpos;
243  if (pos != std::string::npos)
244  {
245  ++pos;
246  }
247  }
248  }
249  else
250  {
251  size_t pos = 0;
252  out = html;
253  while ((pos = out.find("<" + tag)) != std::string::npos)
254  {
255  size_t endpos = out.find("</" + tag, pos);
256  if (endpos == std::string::npos)
257  {
258  break;
259  }
260  endpos += 3 + tag.length(); // tag + </ + >
261  out.replace(pos, endpos - pos, "");
262  }
263  }
264 
265  return out;
266  }

◆ remove_newlines()

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

Replace newlines with spaces.

599  {
600  size_t posn = 0;
601  while ((posn = text.find('\n', posn)) != std::string::npos)
602  {
603  text.replace(posn, 1, " ");
604 
605  size_t posr = posn - 1;
606  if (text[posr] == '\r')
607  {
608  text.replace(posr, 1, " ");
609  }
610  ++posn;
611  }
612 
613  return text;
614  }

◆ strip_html()

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

Removes HTML tags and superflous spaces from an HTML page.

212  {
213  string out;
214 
215  out = remove_html_tags(html, "script"); // Remove JavaScript.
216  out = remove_html_tags(out, "style"); // Remove CSS.
217  out = remove_html_tags(out); // Remove tags.
218 
219  size_t pos = 0;
220  while ((pos = out.find("\r", pos)) != std::string::npos) // Remove CR.
221  {
222  out.replace(pos, 1, "");
223  }
224 
225  out = regex_replace(out, regex("\\s+\n"), "\n"); // Remove space at eol.
226  out = regex_replace(out, regex("\n{2,}"), "\n"); // Reduce newlines.
227 
228  return unescape_html(out);
229  }
const string remove_html_tags(const string &html, const string &tag="")
Remove HTML tags.
Definition: uri.cpp:230
const string unescape_html(const string &html)
Convert HTML entities to UTF-8.
Definition: uri.cpp:268

◆ unescape_html()

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

Convert HTML entities to UTF-8.

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

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