-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter_composer.py
More file actions
307 lines (262 loc) · 11.7 KB
/
filter_composer.py
File metadata and controls
307 lines (262 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import argparse
import re
import json
from typing import Dict, List
class IFTTTFilterGenerator:
"""Generatore di Filter Code IFTTT da frammenti JS"""
def clean_snippet(self, snippet: str) -> str:
if not snippet:
return ""
snippet = re.sub(r'//.*?(?=\n|$)', '', snippet)
snippet = re.sub(r'/\*.*?\*/', '', snippet, flags=re.DOTALL)
lines = [ln.strip() for ln in snippet.split('\n')]
return '\n'.join([ln for ln in lines if ln])
# --- Normalizzazioni ----------------------------------------------------
def normalize_condition(self, condition: str) -> str:
if not condition:
return "true"
condition = condition.strip()
condition = re.sub(r'^\s*if\s*\(', '', condition, flags=re.IGNORECASE)
condition = re.sub(r'\)\s*$', '', condition)
# mapping rapido IT->JS
repl = {
' è uguale a ': ' === ',
' è diverso da ': ' !== ',
' contiene ': '.includes(',
' maggiore di ': ' > ',
' minore di ': ' < ',
' maggiore o uguale a ': ' >= ',
' minore o uguale a ': ' <= ',
' e ': ' && ',
' o ': ' || ',
' non ': ' !',
}
for k, v in repl.items():
condition = condition.replace(k, v)
# pattern temporali comuni
tps = [
(r'prima delle (\d+)', r'Meta.currentUserTime.hour() < \1'),
(r'dopo le (\d+)', r'Meta.currentUserTime.hour() > \1'),
]
for pat, rep in tps:
condition = re.sub(pat, rep, condition)
return condition.strip()
def normalize_trigger_guard(self, trigger_snippet: str) -> (str, str):
"""
Ritorna (preamble, guard):
- Se lo snippet del trigger sembra una chiamata (Service.Method[.Prop] [;]),
lo converte in guard 'if (Service.Method[.Prop]())' aggiungendo '()' se mancano.
- Altrimenti mette il trigger nello "preamble" e usa guard 'true'.
"""
t = self.clean_snippet(trigger_snippet)
if not t:
return ("", "true")
# un'unica riga e nessuna keyword di dichiarazione?
single_line = ('\n' not in t)
looks_like_ref = bool(re.match(r'^[A-Za-z_][\w.]*\s*;?$', t))
if single_line and looks_like_ref:
base = t.rstrip(';').strip()
# se termina con ')' assumiamo già chiamata
guard_call = base if base.endswith(')') else f"{base}()"
return ("", guard_call)
else:
# Mantieni come preparazione
return (t, "true")
# --- Azione: costruzione call/skip -------------------------------------
def build_action_calls(self, action_snippet: str) -> Dict[str, str]:
"""
Dato uno snippet azione generico, costruisce:
- action_call: versione senza skip, terminata da ';'
- skip_call: versione con .skip(), terminata da ';'
Regole:
- Se è già presente '.skip(' allora:
action_call = parte prima di '.skip(' (se sembra una call) altrimenti commento
skip_call = versione originale normalizzata a terminare con ';'
- Altrimenti:
action_call = snippet normalizzato a terminare con ';'
skip_call = action_call con '.skip()' appended (prima del ';')
"""
raw = self.clean_snippet(action_snippet)
if not raw:
return {"action_call": "// azione", "skip_call": 'skip("Condizione non soddisfatta");'}
# togli eventuale ';' di fine
core = raw.rstrip(';').strip()
# se include .skip(
idx = core.find('.skip(')
if idx != -1:
before = core[:idx].strip()
skip_full = core # già include .skip(...)
# normalizza terminatori
skip_call = skip_full + ';'
action_call = before + ';' if before else "// azione"
return {"action_call": action_call, "skip_call": skip_call}
# nessuno skip: costruisci entrambi
# azione base:
action_call = core + ';'
# aggiungi .skip() PRIMA del ';' finale
skip_call = core + '.skip();'
return {"action_call": action_call, "skip_call": skip_call}
# --- Commenti -----------------------------------------------------------
def generate_condition_comment(self, condition: str) -> str:
hour = re.search(r'Meta\.currentUserTime\.(?:hour|weekday)\(\)', condition)
if hour:
return "Se la condizione è vera."
return "Se la condizione è vera."
# --- Generatore principale ---------------------------------------------
def generate_filter_code(self, trigger_snippet: str, action_snippet: str, condition: str) -> Dict[str, str]:
cond = self.normalize_condition(condition)
preamble, guard = self.normalize_trigger_guard(trigger_snippet)
acts = self.build_action_calls(action_snippet)
comment = self.generate_condition_comment(cond)
# Compatto: solo condizione + azione.skip
compact_lines = [
# "// Compatto",
# f"// {comment}",
f"if ({cond}) {{",
f" {acts['skip_call']}",
"}",
]
compact = "\n".join(compact_lines)
# Verboso: guard trigger + if/else
verbose_lines = []
if preamble:
verbose_lines.append("// Trigger (preparazione)")
verbose_lines.append(preamble)
verbose_lines.append("")
verbose_lines += [
# "// Verboso",
f"if ({guard}) {{ // Trigger",
# f" // {comment}",
f" if ({cond}) {{",
f" {acts['skip_call']}",
" } else {",
f" {acts['action_call']}",
" }",
"}",
]
verbose = "\n".join(verbose_lines)
return {"compact": compact, "verbose": verbose}
# --- Analisi (come prima) ----------------------------------------------
def detect_code_type(self, code: str) -> str:
trigger_keywords = ['trigger.', 'Meta.currentUserTime', 'Meta.triggerTime']
action_keywords = ['action.', '.skip(', 'skip()']
if any(k in code for k in trigger_keywords):
return 'trigger'
if any(k in code for k in action_keywords):
return 'action'
return 'generic'
def extract_variables(self, code: str) -> List[str]:
patterns = [
r'trigger\.(\w+)', r'Meta\.(\w+)', r'(\w+)\s*=', r'let\s+(\w+)', r'const\s+(\w+)', r'var\s+(\w+)'
]
vars = set()
for p in patterns:
vars.update(re.findall(p, code))
return list(vars)
def analyze_snippets(self, trigger_snippet: str, action_snippet: str) -> Dict:
analysis = {
'trigger_type': self.detect_code_type(trigger_snippet),
'action_type': self.detect_code_type(action_snippet),
'trigger_variables': self.extract_variables(trigger_snippet),
'action_variables': self.extract_variables(action_snippet),
'complexity_score': 0
}
complexity = len(trigger_snippet) + len(action_snippet)
complexity += len(analysis['trigger_variables']) * 10
complexity += len(analysis['action_variables']) * 10
analysis['complexity_score'] = complexity
return analysis
def _minify_js(js: str) -> str:
js = re.sub(r'//[^\n]*', '', js)
js = re.sub(r'\s+', ' ', js)
return js.strip()
def main():
parser = argparse.ArgumentParser(
description='IFTTT Filter Code Generator - Test CLI',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Esempi di utilizzo:
1. Compatto e Verboso assieme (default pretty):
python filter_composer.py --trigger "Facebook.youAreTaggedInAPhoto.Link;" --action "Gmail.sendAnEmail.setBody(string: body)" --condition "Meta.currentUserTime.weekday() !== 3"
"""
)
parser.add_argument('--trigger', '-t', help='Snippet JS del trigger')
parser.add_argument('--action', '-a', help="Snippet JS dell'azione")
parser.add_argument('--condition', '-c', help='Condizione del filter (estratta da NLP)')
parser.add_argument('--trigger-file', help='File contenente lo snippet del trigger')
parser.add_argument('--action-file', help="File contenente lo snippet dell'azione")
parser.add_argument('--condition-file', help='File contenente la condizione')
parser.add_argument('--output', '-o', help='File di output (default: stdout)')
parser.add_argument('--analyze', action='store_true', help='Mostra analisi dettagliata dei frammenti')
parser.add_argument('--format', choices=['pretty', 'minified', 'json'], default='pretty', help="Formato dell'output")
args = parser.parse_args()
gen = IFTTTFilterGenerator()
trigger_snippet = args.trigger or ""
action_snippet = args.action or ""
condition = args.condition or ""
if args.trigger_file:
try:
with open(args.trigger_file, 'r', encoding='utf-8') as f:
trigger_snippet = f.read()
except FileNotFoundError:
print(f"Errore: File trigger non trovato: {args.trigger_file}")
return 1
if args.action_file:
try:
with open(args.action_file, 'r', encoding='utf-8') as f:
action_snippet = f.read()
except FileNotFoundError:
print(f"Errore: File action non trovato: {args.action_file}")
return 1
if args.condition_file:
try:
with open(args.condition_file, 'r', encoding='utf-8') as f:
condition = f.read().strip()
except FileNotFoundError:
print(f"Errore: File condition non trovato: {args.condition_file}")
return 1
if not condition:
print("Errore: Fornire almeno una condizione per il filter")
return 1
try:
codes = gen.generate_filter_code(trigger_snippet, action_snippet, condition)
result = {'compact': codes['compact'], 'verbose': codes['verbose'], 'status': 'success'}
if args.analyze:
result['analysis'] = gen.analyze_snippets(trigger_snippet, action_snippet)
if args.format == 'json':
output = json.dumps(result, indent=2, ensure_ascii=False)
elif args.format == 'minified':
compact_min = _minify_js(codes['compact'])
verbose_min = _minify_js(codes['verbose'])
output = f"// Compact {compact_min}\n// Verbose {verbose_min}"
else:
# pretty: COMPATTO prima, poi VERBOSO (come richiesto)
parts = []
parts.append("")
parts.append("==== Versione Compatta ====")
parts.append(codes['compact'])
parts.append("")
parts.append("==== Versione Verbosa ====")
parts.append(codes['verbose'])
if args.analyze:
a = result['analysis']
parts.append("")
parts.append("=" * 50 + " ANALISI " + "=" * 50)
parts.append(f"Tipo trigger: {a['trigger_type']}")
parts.append(f"Tipo action: {a['action_type']}")
parts.append(f"Variabili trigger: {', '.join(a['trigger_variables']) or 'Nessuna'}")
parts.append(f"Variabili action: {', '.join(a['action_variables']) or 'Nessuna'}")
parts.append(f"Punteggio complessità: {a['complexity_score']}")
output = "\n".join(parts)
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(output)
print(f"Filter Code generato e salvato in: {args.output}")
else:
print(output)
except Exception as e:
print(f"Errore durante la generazione: {str(e)}")
return 1
return 0
if __name__ == '__main__':
exit(main())