|
| 1 | +import os |
| 2 | +import errno |
| 3 | +import magic |
| 4 | +from pywaybackup.helper import url_split |
| 5 | + |
| 6 | +from pywaybackup.Arguments import Configuration as config |
| 7 | +from pywaybackup.Verbosity import Verbosity as vb |
| 8 | +import re |
| 9 | + |
| 10 | +class Converter: |
| 11 | + |
| 12 | + @classmethod |
| 13 | + def define_root_steps(cls, filepath) -> str: |
| 14 | + """ |
| 15 | + Define the steps (../) to the root directory. |
| 16 | + """ |
| 17 | + abs_path = os.path.abspath(filepath) |
| 18 | + webroot_path = os.path.abspath(f"{config.output}/{config.domain}/") # webroot is the domain folder in the output |
| 19 | + # common path between the two |
| 20 | + common_path = os.path.commonpath([abs_path, webroot_path]) |
| 21 | + # steps up to the common path |
| 22 | + rel_path_from_common = os.path.relpath(abs_path, common_path) |
| 23 | + steps_up = rel_path_from_common.count(os.path.sep) |
| 24 | + if steps_up <= 1: # if the file is in the root of the domain |
| 25 | + return "./" |
| 26 | + return "../" * steps_up |
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | + |
| 31 | + |
| 32 | + @classmethod |
| 33 | + def links(cls, filepath, status_message=None): |
| 34 | + """ |
| 35 | + Convert all links in a HTML / CSS / JS file to local paths. |
| 36 | + """ |
| 37 | + |
| 38 | + |
| 39 | + def extract_urls(content) -> list: |
| 40 | + """ |
| 41 | + Extract all links from a file. |
| 42 | + """ |
| 43 | + |
| 44 | + #content = re.sub(r'\s+', '', content) |
| 45 | + #content = re.sub(r'\n', '', content) |
| 46 | + |
| 47 | + html_types = ["src", "href", "poster", "data-src"] |
| 48 | + css_types = ["url"] |
| 49 | + links = [] |
| 50 | + for html_type in html_types: |
| 51 | + # possible formatings of the value: "url", 'url', url |
| 52 | + matches = re.findall(f"{html_type}=[\"']?([^\"'>]+)", content) |
| 53 | + links += matches |
| 54 | + for css_type in css_types: |
| 55 | + # possible formatings of the value: url(url) url('url') url("url") // ends with ) |
| 56 | + matches = re.findall(rf"{css_type}\((['\"]?)([^'\"\)]+)\1\)", content) |
| 57 | + links += [match[1] for match in matches] |
| 58 | + links = list(set(links)) |
| 59 | + return links |
| 60 | + |
| 61 | + |
| 62 | + def local_url(original_url, domain, count) -> str: |
| 63 | + """ |
| 64 | + Convert a given url to a local path. |
| 65 | + """ |
| 66 | + original_url_domain = url_split(original_url)[0] |
| 67 | + |
| 68 | + # check if the url is external or internal (external is returned as is because no need to convert) |
| 69 | + external = False |
| 70 | + if original_url_domain != domain: |
| 71 | + if "://" in original_url: |
| 72 | + external = True |
| 73 | + if original_url.startswith("//"): |
| 74 | + external = True |
| 75 | + if external: |
| 76 | + status_message.trace(status="", type=f"{count}/{len(links)}", message="External url") |
| 77 | + return original_url |
| 78 | + |
| 79 | + # convert the url to a relative path to the local root (download dir) if it's a valid path, else return the original url |
| 80 | + original_url_file = os.path.join(config.output, config.domain, normalize_url(original_url)) |
| 81 | + if validate_path(original_url_file): |
| 82 | + if original_url.startswith("/"): # if only starts with / |
| 83 | + original_url = f"{cls.define_root_steps(filepath)}{original_url.lstrip('/')}" |
| 84 | + if original_url.startswith(".//"): |
| 85 | + original_url = f"{cls.define_root_steps(filepath)}{original_url.lstrip('./')}" |
| 86 | + if original_url_domain == domain: # if url is like https://domain.com/path/to/file |
| 87 | + original_url = f"{cls.define_root_steps(filepath)}{original_url.split(domain)[1].lstrip('/')}" |
| 88 | + if original_url.startswith("../"): # if file is already ../ check if it's not too many steps up |
| 89 | + original_url = f"{cls.define_root_steps(filepath)}{original_url.split('../')[-1].lstrip('/')}" |
| 90 | + else: |
| 91 | + status_message.trace(status="", type="", message=f"{count}/{len(links)}: URL is not a valid path") |
| 92 | + |
| 93 | + return original_url |
| 94 | + |
| 95 | + |
| 96 | + |
| 97 | + |
| 98 | + |
| 99 | + def normalize_url(url) -> str: |
| 100 | + """ |
| 101 | + Normalize a given url by removing it's protocol, domain and parent directorie references. |
| 102 | +
|
| 103 | + Example1: |
| 104 | + - Example input: https://domain.com/path/to/file |
| 105 | + - Example output: /path/to/file |
| 106 | +
|
| 107 | + Example2 |
| 108 | + - input: ../path/to/file |
| 109 | + - output: /path/to/file |
| 110 | + """ |
| 111 | + try: |
| 112 | + url = "/" + url.split("../")[-1] |
| 113 | + except IndexError: |
| 114 | + pass |
| 115 | + if url.startswith("//"): |
| 116 | + url = "/" + url.split("//")[1] |
| 117 | + parsed_url = url_split(url) |
| 118 | + return f"{parsed_url[1]}/{parsed_url[2]}" |
| 119 | + |
| 120 | + |
| 121 | + def is_pathname_valid(pathname: str) -> bool: |
| 122 | + """ |
| 123 | + Check if a given pathname is valid. |
| 124 | + """ |
| 125 | + if not isinstance(pathname, str) or not pathname: |
| 126 | + return False |
| 127 | + |
| 128 | + try: |
| 129 | + os.lstat(pathname) |
| 130 | + except OSError as exc: |
| 131 | + if exc.errno == errno.ENOENT: |
| 132 | + return True |
| 133 | + elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}: |
| 134 | + return False |
| 135 | + return True |
| 136 | + |
| 137 | + def is_path_creatable(pathname: str) -> bool: |
| 138 | + """ |
| 139 | + Check if a given path is creatable. |
| 140 | + """ |
| 141 | + dirname = os.path.dirname(pathname) or os.getcwd() |
| 142 | + return os.access(dirname, os.W_OK) |
| 143 | + |
| 144 | + def is_path_exists_or_creatable(pathname: str) -> bool: |
| 145 | + """ |
| 146 | + Check if a given path exists or is creatable. |
| 147 | + """ |
| 148 | + return is_pathname_valid(pathname) or is_path_creatable(pathname) |
| 149 | + |
| 150 | + def validate_path(filepath: str) -> bool: |
| 151 | + """ |
| 152 | + Validate if a given path can exist. |
| 153 | + """ |
| 154 | + return is_path_exists_or_creatable(filepath) |
| 155 | + |
| 156 | + |
| 157 | + |
| 158 | + |
| 159 | + |
| 160 | + if os.path.isfile(filepath): |
| 161 | + if magic.from_file(filepath, mime=True).split("/")[1] == "javascript": |
| 162 | + status_message.trace(status="Error", type="", message="JS-file is not supported") |
| 163 | + return |
| 164 | + try: |
| 165 | + with open(filepath, "r") as file: |
| 166 | + domain = config.domain |
| 167 | + content = file.read() |
| 168 | + links = extract_urls(content) |
| 169 | + status_message.store(message=f"\n-----> Convert: [{len(links)}] links in file") |
| 170 | + count = 1 |
| 171 | + for original_link in links: |
| 172 | + status_message.trace(status="ORIG", type=f"{count}/{len(links)}", message=original_link) |
| 173 | + new_link = local_url(original_link, domain, count) |
| 174 | + if new_link != original_link: |
| 175 | + status_message.trace(status="CONV", type=f"{count}/{len(links)}", message=new_link) |
| 176 | + content = content.replace(original_link, new_link) |
| 177 | + count += 1 |
| 178 | + file = open(filepath, "w") |
| 179 | + file.write(content) |
| 180 | + file.close() |
| 181 | + except UnicodeDecodeError: |
| 182 | + status_message.trace(status="Error", type="", message="Could not decode file to convert links") |
0 commit comments