remwharead  0.8.4
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 (string uri)
 Construct object and set URL. More...
 
 URI (const URI &other)=default
 
URIoperator= (const URI &other)=default
 
 URI (URI &&other)=default
 
URIoperator= (URI &&other)=default
 
html_extract get ()
 Download URI and extract title, description and full text. More...
 
archive_answer archive ()
 Save URI in archive and return archive-URI. More...
 

Protected Member Functions

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

Protected Attributes

string _uri
 

Detailed Description

Download, archive and process an URI.

Since
0.6.0

Constructor & Destructor Documentation

◆ URI()

remwharead::URI::URI ( 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
67  :_uri(move(uri))
68 {
69  Poco::Net::initializeSSL();
70 
71  set_proxy();
72 }
void set_proxy()
Set proxy server.
Definition: uri.cpp:74

Member Function Documentation

◆ archive()

archive_answer remwharead::URI::archive ( )

Save URI in archive and return archive-URI.

Since
0.6.0

◆ extract_description()

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

Extract the description from an HTML page.

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

◆ extract_title()

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

Extract the title from an HTML page.

Since
0.6.0
224 {
225  const RegEx re_htmlfile(".*\\.(.?html?|xml|rss)$", RegEx::RE_CASELESS);
226  if (_uri.substr(0, 4) == "http" || re_htmlfile.match(_uri))
227  {
228  const RegEx re_title("<title>([^<]+)", RegEx::RE_CASELESS);
229  vector<string> matches;
230  re_title.split(html, matches);
231  if (matches.size() >= 2)
232  {
233  return remove_newlines(unescape_html(matches[1]));
234  }
235  }
236 
237  return "";
238 }
string unescape_html(string html)
Convert HTML entities to UTF-8.
string remove_newlines(string text)
Replace newlines with spaces.
Definition: uri.cpp:641

◆ get()

html_extract remwharead::URI::get ( )

Download URI and extract title, description and full text.

Since
0.6.0
127 {
128  try
129  {
130  const string answer = make_request(_uri);
131  if (!answer.empty())
132  {
133  return
134  {
135  true,
136  "",
137  extract_title(answer),
138  extract_description(answer),
139  strip_html(answer)
140  };
141  }
142  }
143  catch (const Poco::Exception &e)
144  {
145  return { false, e.displayText(), "", "", "" };
146  }
147 
148  return { false, "Unknown error.", "", "", "" };
149 }
string make_request(const string &uri, bool archive=false) const
Make a HTTP(S) request.
Definition: uri.cpp:151
string strip_html(const string &html)
Removes HTML tags and superflous spaces from an HTML page.
string extract_title(const string &html)
Extract the title from an HTML page.
Definition: uri.cpp:223
string extract_description(const string &html)
Extract the description from an HTML page.
Definition: uri.cpp:240

◆ make_request()

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

Make a HTTP(S) request.

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

◆ remove_html_tags()

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

◆ remove_newlines()

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

Replace newlines with spaces.

Since
0.6.0
642 {
643  size_t posn = 0;
644  while ((posn = text.find('\n', posn)) != std::string::npos)
645  {
646  text.replace(posn, 1, " ");
647 
648  size_t posr = posn - 1;
649  if (text[posr] == '\r')
650  {
651  text.replace(posr, 1, " ");
652  }
653  ++posn;
654  }
655 
656  return text;
657 }

◆ set_proxy()

void remwharead::URI::set_proxy ( )
protected

Set proxy server.

Since
0.8.5
75 {
76  try
77  {
78  HTTPClientSession::ProxyConfig proxy;
79  const string env_proxy = Environment::get("http_proxy");
80  const RegEx re_proxy("^(?:https?://)?(?:([^:]+):?([^@]*)@)?" // user:pw
81  "([^:/]+)(?::([\\d]{1,5}))?/?$"); // host:port
82  vector<string> matches;
83 
84  if (re_proxy.split(env_proxy, matches) < 4)
85  {
86  return;
87  }
88 
89  proxy.username = matches[1];
90  proxy.password = matches[2];
91  proxy.host = matches[3];
92  if (!matches[4].empty())
93  {
94  const std::uint32_t &port = std::stoul(matches[4]);
95  if (port > 65535)
96  {
97  throw std::invalid_argument("Proxy port number out of range");
98  }
99  proxy.port = port;
100  }
101  HTTPClientSession::setGlobalProxyConfig(proxy);
102  }
103  catch (const Poco::RegularExpressionException &e)
104  {
105  cerr << "Error: Proxy could not be set (" << e.displayText() << ")\n";
106  }
107  catch (const std::invalid_argument &e)
108  {
109  cerr << "Error: " << e.what() << endl;
110  }
111  catch (const Poco::NotFoundException &)
112  {
113  // No proxy found, no problem.
114  }
115  catch (const std::exception &e)
116  {
117  cerr << "Unexpected exception: " << e.what() << endl;
118  }
119 }

◆ strip_html()

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

Removes HTML tags and superflous spaces from an HTML page.

Since
0.6.0

◆ unescape_html()

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

Convert HTML entities to UTF-8.

Since
0.6.0

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