ptlibs 1.0.76__tar.gz → 1.0.78__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. {ptlibs-1.0.76/ptlibs.egg-info → ptlibs-1.0.78}/PKG-INFO +1 -1
  2. ptlibs-1.0.78/ptlibs/_version.py +1 -0
  3. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/parsers/http_request_parser.py +4 -3
  4. ptlibs-1.0.78/ptlibs/websources.py +242 -0
  5. {ptlibs-1.0.76 → ptlibs-1.0.78/ptlibs.egg-info}/PKG-INFO +1 -1
  6. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs.egg-info/SOURCES.txt +1 -0
  7. ptlibs-1.0.76/ptlibs/_version.py +0 -1
  8. {ptlibs-1.0.76 → ptlibs-1.0.78}/LICENSE +0 -0
  9. {ptlibs-1.0.76 → ptlibs-1.0.78}/MANIFEST.in +0 -0
  10. {ptlibs-1.0.76 → ptlibs-1.0.78}/README.md +0 -0
  11. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/__init__.py +0 -0
  12. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/app_dirs.py +0 -0
  13. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/argparse_wrapper.py +0 -0
  14. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/cachefile.py +0 -0
  15. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/cli.py +0 -0
  16. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/data/PSL.txt +0 -0
  17. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/data/iana_tlds.txt +0 -0
  18. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/data/user_agents.txt +0 -0
  19. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/dns_cache_hosts.py +0 -0
  20. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/http/__init__.py +0 -0
  21. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/http/http_client.py +0 -0
  22. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/http/modules/__init__.py +0 -0
  23. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/http/modules/cache.py +0 -0
  24. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/http/modules/fpd.py +0 -0
  25. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/http/raw_http_client.py +0 -0
  26. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/parsers/__init__.py +0 -0
  27. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/parsers/http_request_file_marker.py +0 -0
  28. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/parsers/http_response_parser.py +0 -0
  29. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/parsers/json_parser.py +0 -0
  30. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/parsers/url_parser.py +0 -0
  31. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/parsers/xml_parser.py +0 -0
  32. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/ptcharsethelper.py +0 -0
  33. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/ptdefs.py +0 -0
  34. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/ptjsonlib.py +0 -0
  35. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/ptmisclib.py +0 -0
  36. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/ptnethelper.py +0 -0
  37. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/ptpathtypedetector.py +0 -0
  38. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/ptprint.py +0 -0
  39. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/ptprinthelper.py +0 -0
  40. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/sockets.py +0 -0
  41. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/threads/__init__.py +0 -0
  42. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/threads/arraylock.py +0 -0
  43. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/threads/printlock.py +0 -0
  44. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/threads/ptthreads.py +0 -0
  45. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/tldparser.py +0 -0
  46. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs/workflow.py +0 -0
  47. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs.egg-info/dependency_links.txt +0 -0
  48. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs.egg-info/entry_points.txt +0 -0
  49. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs.egg-info/requires.txt +0 -0
  50. {ptlibs-1.0.76 → ptlibs-1.0.78}/ptlibs.egg-info/top_level.txt +0 -0
  51. {ptlibs-1.0.76 → ptlibs-1.0.78}/setup.cfg +0 -0
  52. {ptlibs-1.0.76 → ptlibs-1.0.78}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ptlibs
3
- Version: 1.0.76
3
+ Version: 1.0.78
4
4
  Summary: Support library for penterepTools
5
5
  Home-page: https://www.penterep.com/
6
6
  Author: Penterep
@@ -0,0 +1 @@
1
+ __version__ = "1.0.78"
@@ -142,13 +142,13 @@ class HttpRequestParser():
142
142
  try:
143
143
  http_request_str = self._load_and_validate_http_request(http_request)
144
144
  # Get method, path, and HTTP version from the first line
145
- first_line = http_request.split("\n")[0]
145
+ first_line = http_request_str.split("\n")[0]
146
146
  parts = first_line.split()
147
147
  method, path, self.HTTP_VERSION = parts[0], parts[1], parts[2]
148
148
 
149
149
  # Get headers and request data
150
- headers = dict(self.get_request_headers(http_request))
151
- request_data = self.get_request_data(http_request)
150
+ headers = dict(self.get_request_headers(http_request_str))
151
+ request_data = self.get_request_data(http_request_str)
152
152
  # Set host from headers
153
153
  self._host = headers.get("Host") # Set host based on the Host header
154
154
  # Check if host is set
@@ -400,6 +400,7 @@ class HttpRequestParser():
400
400
  raise TypeError("http_request must be a string or a file handler.")
401
401
 
402
402
  #print("BEFORE:", request)
403
+ request = request.replace("\r\n", "\n")
403
404
  self._validate_http_request(request)
404
405
  return request
405
406
 
@@ -0,0 +1,242 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import unicodedata
5
+ from collections import Counter, defaultdict
6
+ from urllib.parse import unquote, urlsplit
7
+
8
+ import filelock
9
+
10
+ from ptlibs.ptpathtypedetector import PtPathTypeDetector
11
+
12
+
13
+ class WebSources:
14
+ """
15
+ Removes previously sent duplicates and nodes over the template limit from the nodes of penterepTools results.
16
+
17
+ websources.json maps the URL of every webSource sent so far to its actions and their webInput names, e.g.
18
+ {"https://www.example.com/login.php": {"actions": [{"name": "POST login=&password=", "webHttpMethod": "webHttpMethodPost", "inputs": ["login", "password"]}]}}
19
+ """
20
+
21
+ FILE_NAME = "websources.json"
22
+ SOURCE_TYPE = "webSource"
23
+ ACTION_TYPE = "webPageAction"
24
+ INPUT_TYPE = "webInput"
25
+ TEMPLATE_LIMIT = 10
26
+ SLUG_MIN_WORDS = 3
27
+ HASH_LENGTHS = (32, 40, 64, 128)
28
+ GUID_PATTERN = r"[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}"
29
+ ACTION_WORDS = frozenset("""
30
+ activate add approve archive assign block cancel change checkout clear clone close compare confirm copy create
31
+ deactivate delete detail details disable download duplicate edit enable execute export filter find import insert
32
+ invite join list lock login logoff logout merge modify move new open order pay preview print process publish
33
+ register reject remove rename renew reorder reply report reset restore run save search send share show signin
34
+ signout signup sort start stop submit subscribe transfer unblock unlock unsubscribe update upgrade upload
35
+ validate verify view vote
36
+
37
+ aktivovat archivovat deaktivovat editace editovat filtrovat hledani hledat koupit kopirovat nahrat nova nove novy
38
+ objednat objednavka obnovit odebrat odeslat odhlaseni odhlasit odstranit otevrit platba potvrdit prejmenovat
39
+ presunout pridat prihlaseni prihlasit publikovat registrace registrovat schvalit sdilet smazat stahnout tisk
40
+ tisknout ulozit uprava upravit vlozit vyhledat vyhledavani vymazat vypis vypnout vytvorit zablokovat zamitnout
41
+ zaplatit zapnout zavrit zmenit zobrazit zrusit
42
+
43
+ editacia hladanie hladat kupit odhlasenie odobrat odoslat otvorit premenovat presunut prihlasenie registracia
44
+ stiahnut tlac tlacit vyhladat vyhladavanie vypnut zamietnut zapnut zatvorit zdielat zmazat
45
+ """.split())
46
+
47
+ def __init__(self, directory: str, limit: int = TEMPLATE_LIMIT):
48
+ """
49
+ Args:
50
+ directory (str): The directory of websources.json, e.g. the temp directory of ptmanager.
51
+ limit (int, optional): The most webSources with the same template that are sent, and the same for actions.
52
+ Defaults to TEMPLATE_LIMIT.
53
+ """
54
+ self.directory = directory
55
+ self.file_path = os.path.join(directory, self.FILE_NAME)
56
+ self.limit = limit
57
+ self.path_type_detector = PtPathTypeDetector()
58
+
59
+ def filter_nodes(self, nodes: list[dict]) -> list[dict]:
60
+ """
61
+ Removes the actions sent before and the nodes over the template limit from the given nodes and adds the new
62
+ webSources and actions left to websources.json.
63
+
64
+ Args:
65
+ nodes (list[dict]): The nodes of the results returned by a penterepTool.
66
+
67
+ Returns:
68
+ list[dict]: The given nodes without the removed ones, in the original order.
69
+
70
+ Note:
71
+ An action was sent before if websources.json has an action with the same webHttpMethod and the same
72
+ webInput names for the URL of its webSource. Such action is removed together with its webInput nodes.
73
+ A new webSource is removed together with all the nodes under it if the limit of webSources with its template
74
+ (see get_source_template) was sent already. A new action is removed together with its webInput nodes if the
75
+ limit of actions with its template was sent already. The template of an action is the template of its webSource,
76
+ its webHttpMethod and its webInput names. A webSource sent before is not counted again and is never removed for
77
+ its template. The first nodes in the given order are kept, every parent before its children.
78
+ A webSource whose action was removed is removed too if no other node is left under it, so the parent
79
+ of every remaining node is kept. Nodes without any webSource are returned unchanged and websources.json
80
+ is not created. The file is locked while it is read and written, so tools finishing at the same time
81
+ do not overwrite each other's records.
82
+ """
83
+
84
+ if not any(node["type"] == self.SOURCE_TYPE for node in nodes):
85
+ return nodes
86
+ os.makedirs(self.directory, exist_ok=True)
87
+ with filelock.FileLock(self.file_path + ".lock"):
88
+ websources = self._load()
89
+ removed_keys = self._get_removed_keys(nodes, websources)
90
+ self._save(websources)
91
+ return [node for node in nodes if node["key"] not in removed_keys]
92
+
93
+ def get_source_template(self, url: str) -> str:
94
+ """
95
+ Returns the template of the given webSource URL, which the URLs of the same kind of page share.
96
+
97
+ Args:
98
+ url (str): The URL of a webSource.
99
+
100
+ Returns:
101
+ str: The URL with every path segment generalized, e.g. https://www.example.com/clanky/{slug}
102
+ for https://www.example.com/clanky/1221--Zabrante-zneuziti-svych-dat.
103
+
104
+ Note:
105
+ An image becomes {image}. A GUID or a hexadecimal hash becomes {id}, keeping its extension. A segment of at least
106
+ SLUG_MIN_WORDS words separated by - or _ becomes {slug}, keeping its extension, unless one of the words is
107
+ in ACTION_WORDS. In any other segment every number becomes {id} and the rest is kept, e.g. product-{id}.html,
108
+ so names of one or two words, such as edit or hack-forum, never share a template.
109
+ """
110
+
111
+ parsed_url = urlsplit(url)
112
+ segments = [segment for segment in parsed_url.path.split("/") if segment]
113
+ return f"{parsed_url.scheme}://{parsed_url.netloc}" + "".join(f"/{self._get_segment_template(segment)}" for segment in segments)
114
+
115
+ def _get_segment_template(self, segment: str) -> str:
116
+ """Returns the template of one path segment, see get_source_template"""
117
+ if self.path_type_detector.get_type(segment.lower()) == "webSourceTypeImage":
118
+ return "{image}"
119
+ stem, extension = self._split_extension(unquote(segment))
120
+ if re.fullmatch(self.GUID_PATTERN, stem) or (len(stem) in self.HASH_LENGTHS and re.fullmatch(r"[0-9a-fA-F]+", stem)):
121
+ return "{id}" + extension
122
+ words = [word for word in re.split(r"[-_]+", stem) if word]
123
+ if len(words) >= self.SLUG_MIN_WORDS and not any(self._get_plain_word(word) in self.ACTION_WORDS for word in words):
124
+ return "{slug}" + extension
125
+ return re.sub(r"[0-9]+", "{id}", stem) + extension
126
+
127
+ def _split_extension(self, name: str) -> tuple[str, str]:
128
+ """Returns the name without its extension and the extension with its dot, or the name and an empty extension"""
129
+ stem, dot, extension = name.rpartition(".")
130
+ if stem and re.fullmatch(r"[A-Za-z0-9]{1,5}", extension):
131
+ return stem, dot + extension
132
+ return name, ""
133
+
134
+ def _get_plain_word(self, word: str) -> str:
135
+ """Returns the word in lowercase without diacritics, as in ACTION_WORDS"""
136
+ return unicodedata.normalize("NFKD", word).encode("ascii", "ignore").decode().lower()
137
+
138
+ def _get_removed_keys(self, nodes: list[dict], websources: dict) -> set[str]:
139
+ """Returns the keys of the nodes to remove and adds the new webSources and actions left to websources"""
140
+ children = defaultdict(list)
141
+ for node in nodes:
142
+ children[node["parent"]].append(node)
143
+ sent_action_ids = {url: {self._get_action_id(action) for action in source["actions"]} for url, source in websources.items()}
144
+ source_templates = {url: self.get_source_template(url) for url in websources}
145
+ source_counts = Counter(source_templates.values())
146
+ action_counts = Counter(self._get_action_template(source_templates[url], action) for url, source in websources.items() for action in source["actions"])
147
+
148
+ removed_keys = set()
149
+ sources_with_removed_action = {}
150
+ for source in self._get_sources_parents_first(nodes):
151
+ if source["key"] in removed_keys:
152
+ continue
153
+ url = source["properties"]["url"]
154
+ if url not in websources:
155
+ template = self.get_source_template(url)
156
+ if source_counts[template] >= self.limit:
157
+ removed_keys.update(self._get_subtree_keys(source, children))
158
+ continue
159
+ source_counts[template] += 1
160
+ source_templates[url] = template
161
+ websources[url] = {"actions": []}
162
+ actions = websources[url]["actions"]
163
+ for action in (node for node in children[source["key"]] if node["type"] == self.ACTION_TYPE):
164
+ inputs = [node for node in children[action["key"]] if node["type"] == self.INPUT_TYPE]
165
+ record = {
166
+ "name": action["properties"]["name"],
167
+ "webHttpMethod": action["properties"]["webHttpMethod"],
168
+ "inputs": sorted(node["properties"]["name"] for node in inputs),
169
+ }
170
+ if self._get_action_id(record) in sent_action_ids.get(url, ()):
171
+ removed_keys.update(node["key"] for node in [action, *inputs])
172
+ sources_with_removed_action[source["key"]] = source
173
+ elif self._get_action_id(record) not in map(self._get_action_id, actions):
174
+ template = self._get_action_template(source_templates[url], record)
175
+ if action_counts[template] >= self.limit:
176
+ removed_keys.update(node["key"] for node in [action, *inputs])
177
+ sources_with_removed_action[source["key"]] = source
178
+ else:
179
+ action_counts[template] += 1
180
+ actions.append(record)
181
+ return removed_keys | self._get_removable_sources(nodes, sources_with_removed_action, removed_keys)
182
+
183
+ def _get_sources_parents_first(self, nodes: list[dict]) -> list[dict]:
184
+ """Returns the webSource nodes in the given order, except that every parent is before its children"""
185
+ parents = {node["key"]: node["parent"] for node in nodes}
186
+
187
+ def get_depth(key: str) -> int:
188
+ depth, seen = 0, {key}
189
+ while parents.get(key) in parents and parents[key] not in seen:
190
+ key = parents[key]
191
+ seen.add(key)
192
+ depth += 1
193
+ return depth
194
+
195
+ return sorted((node for node in nodes if node["type"] == self.SOURCE_TYPE), key=lambda node: get_depth(node["key"]))
196
+
197
+ def _get_subtree_keys(self, node: dict, children: dict) -> set[str]:
198
+ """Returns the keys of the given node and of all the nodes under it"""
199
+ keys, stack = set(), [node]
200
+ while stack:
201
+ node = stack.pop()
202
+ if node["key"] not in keys:
203
+ keys.add(node["key"])
204
+ stack.extend(children[node["key"]])
205
+ return keys
206
+
207
+ def _get_removable_sources(self, nodes: list[dict], sources: dict[str, dict], removed_keys: set[str]) -> set[str]:
208
+ """Returns the keys of the given webSources with no node left under them, going from the leaves up"""
209
+ left_children = Counter(node["parent"] for node in nodes if node["key"] not in removed_keys)
210
+ removable = set()
211
+ stack = [key for key in sources if not left_children[key]]
212
+ while stack:
213
+ key = stack.pop()
214
+ removable.add(key)
215
+ parent = sources[key]["parent"]
216
+ left_children[parent] -= 1
217
+ if parent in sources and not left_children[parent]:
218
+ stack.append(parent)
219
+ return removable
220
+
221
+ def _get_action_id(self, action: dict) -> tuple:
222
+ """Returns what identifies a recorded action: its method and its input names"""
223
+ return action["webHttpMethod"], tuple(action["inputs"])
224
+
225
+ def _get_action_template(self, source_template: str, action: dict) -> tuple:
226
+ """Returns what the actions of the same kind share: the template of their webSource, their method and their input names"""
227
+ return (source_template, *self._get_action_id(action))
228
+
229
+ def _load(self) -> dict:
230
+ """Returns the content of websources.json, or an empty dictionary if it does not exist yet"""
231
+ try:
232
+ with open(self.file_path) as file:
233
+ return json.load(file)
234
+ except FileNotFoundError:
235
+ return {}
236
+
237
+ def _save(self, websources: dict) -> None:
238
+ """Writes websources.json through a temporary file, so it is never left half written"""
239
+ temp_path = self.file_path + ".tmp"
240
+ with open(temp_path, "w") as file:
241
+ json.dump(websources, file, indent=4)
242
+ os.replace(temp_path, self.file_path)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ptlibs
3
- Version: 1.0.76
3
+ Version: 1.0.78
4
4
  Summary: Support library for penterepTools
5
5
  Home-page: https://www.penterep.com/
6
6
  Author: Penterep
@@ -19,6 +19,7 @@ ptlibs/ptprint.py
19
19
  ptlibs/ptprinthelper.py
20
20
  ptlibs/sockets.py
21
21
  ptlibs/tldparser.py
22
+ ptlibs/websources.py
22
23
  ptlibs/workflow.py
23
24
  ptlibs.egg-info/PKG-INFO
24
25
  ptlibs.egg-info/SOURCES.txt
@@ -1 +0,0 @@
1
- __version__ = "1.0.76"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes