From 9c0b0e28d85f83715a3ae384c2c91bdaf48f260a Mon Sep 17 00:00:00 2001
From: Thulinma <jaron@vietors.com>
Date: Mon, 26 Dec 2022 13:20:34 +0100
Subject: [PATCH] Added HTTP::URL::getBase() and HTTP::URL::getLinkFrom()
 functions

Change-Id: I87dcefb4287e8c5c22a4ae59898cb97371c441de
---
 lib/url.cpp | 36 +++++++++++++++++++++++++++---------
 lib/url.h   |  2 ++
 2 files changed, 29 insertions(+), 9 deletions(-)

diff --git a/lib/url.cpp b/lib/url.cpp
index 1dc89ba5..6fab4748 100644
--- a/lib/url.cpp
+++ b/lib/url.cpp
@@ -271,6 +271,30 @@ std::string HTTP::URL::getBareUrl() const{
   return ret;
 }
 
+/// Returns a string guaranteed to end in a slash, pointing to the base directory-equivalent of the URL
+std::string HTTP::URL::getBase() const{
+  std::string tmpUrl = getBareUrl();
+  size_t slashPos = tmpUrl.rfind('/');
+  if (slashPos == std::string::npos){
+    tmpUrl += "/";
+  }else{
+    tmpUrl.erase(slashPos + 1);
+  }
+  return tmpUrl;
+}
+
+/// Returns a string that links to the URL from the given URL
+/// If the given URL is in a parent directory of the URL, it will be relative
+/// Otherwise, it will be absolute
+std::string HTTP::URL::getLinkFrom(const HTTP::URL & fromUrl) const{
+  std::string to = getUrl();
+  std::string from = fromUrl.getBase();
+  if (to.substr(0, from.size()) == from){
+    return to.substr(from.size());
+  }
+  return to;
+}
+
 /// Returns a URL object for the given link, resolved relative to the current URL object.
 HTTP::URL HTTP::URL::link(const std::string &l) const{
   // Full link
@@ -294,13 +318,7 @@ HTTP::URL HTTP::URL::link(const std::string &l) const{
     }
   }
   // Relative link
-  std::string tmpUrl = getBareUrl();
-  size_t slashPos = tmpUrl.rfind('/');
-  if (slashPos == std::string::npos){
-    tmpUrl += "/";
-  }else{
-    tmpUrl.erase(slashPos + 1);
-  }
-  DONTEVEN_MSG("Relative link: %s+%s", tmpUrl.c_str(), l.c_str());
-  return URL(tmpUrl + l);
+  std::string base = getBase();
+  DONTEVEN_MSG("Relative link: %s+%s", base.c_str(), l.c_str());
+  return URL(base + l);
 }
diff --git a/lib/url.h b/lib/url.h
index dfe58c72..934f78da 100644
--- a/lib/url.h
+++ b/lib/url.h
@@ -18,8 +18,10 @@ namespace HTTP{
     std::string getExt() const;
     std::string getUrl() const;
     std::string getFilePath() const;
+    std::string getBase() const;
     std::string getBareUrl() const;
     std::string getProxyUrl() const;
+    std::string getLinkFrom(const URL &) const;
     bool isLocalPath() const;
     std::string host;     ///< Hostname or IP address of URL
     std::string protocol; ///< Protocol of URL