saliacoel commited on
Commit
7351a7c
·
verified ·
1 Parent(s): 9451a1c

Upload Backblaze_Files_Renamer.py

Browse files
Files changed (1) hide show
  1. Backblaze_Files_Renamer.py +533 -0
Backblaze_Files_Renamer.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""ComfyUI node: Backblaze_Files_Renamer.
2
+
3
+ INSTALL
4
+ 1. Install into the Python environment used by ComfyUI:
5
+ python -m pip install "b2sdk>=2.5,<3"
6
+ Windows portable (from the ComfyUI_windows_portable directory):
7
+ .\python_embeded\python.exe -m pip install "b2sdk>=2.5,<3"
8
+ 2. Put this file in ComfyUI/custom_nodes/ and restart ComfyUI.
9
+ 3. Add Salia > Backblaze > Backblaze_Files_Renamer.
10
+
11
+ BEHAVIOR
12
+ BAM records are NUMBER.Name, optional, ignored, tags,
13
+ Only Name is used as the exact, case-sensitive top-level folder name.
14
+ Only <Name>/<before_filename> is renamed to <Name>/<after_filename>.
15
+ Missing folders/files and existing destinations are skipped and reported.
16
+ Every queued execution runs again, even when its inputs are unchanged.
17
+
18
+ Uses the official Backblaze SDK and server-side copies, including multipart
19
+ copies for large files; video data is never downloaded or re-encoded.
20
+ The copy is verified before hiding the old filename and deleting the exact
21
+ source version. A hide marker prevents older versions from reappearing.
22
+ Historical versions are NOT renamed or purged; they remain hidden under
23
+ their original name, subject to the bucket's existing lifecycle rules.
24
+ The report distinguishes a completed rename with a cleanup warning from
25
+ failures before completion. Existing destinations are never intentionally
26
+ replaced. B2 rename is not atomic; avoid concurrent writes to these names.
27
+
28
+ Customer-key-encrypted (SSE-C) files require a separate encryption key and
29
+ are reported as errors without changing the source. Object Lock is never
30
+ bypassed. Credentials are held in memory by the SDK for this execution.
31
+
32
+ Official references:
33
+ https://www.backblaze.com/apidocs/b2-copy-file
34
+ https://www.backblaze.com/apidocs/b2-hide-file
35
+ https://www.backblaze.com/apidocs/b2-delete-file-version
36
+ https://b2-sdk-python.readthedocs.io/en/stable/api/bucket.html
37
+ """
38
+
39
+ import re
40
+ from collections import Counter
41
+
42
+
43
+ DEFAULT_BAM = """0001.Tira,
44
+ 0002.Anita,
45
+ 0003.Antonia,
46
+ 0004.Applie,
47
+ 0005.Scarmil,
48
+ 0006.Blakey,
49
+ 0007.Chandy, leg.skirtish,
50
+ 0008.Chaps,
51
+ 0009.Clea,
52
+ 0010.Clive,
53
+ 0011.Corva,
54
+ 0012.Dimi,
55
+ 0013.Eileen, leg.skirtish,
56
+ 0014.Esmeralda, leg.skirtish,
57
+ 0015.Flix,
58
+ 0016.Fura,
59
+ 0017.Yana,
60
+ 0018.Fuma,
61
+ 0019.Taya,
62
+ 0020.Gemma,
63
+ 0021.Tola,
64
+ 0022.Gina,
65
+ 0023.Yoko,
66
+ 0024.Gloria,
67
+ 0025.Gia, leg.skirtish,
68
+ 0026.Grethe, leg.skirtish,
69
+ 0027.Riff,
70
+ 0028.Hellia, leg.skirtish,
71
+ 0029.Hira,
72
+ 0030.Hixy,
73
+ 0031.Hana, leg.skirtish,
74
+ 0032.Helga,
75
+ 0033.Ivanka, leg.skirtish,
76
+ 0034.Jasmin, leg.skirtish,
77
+ 0035.Jenna, leg.skirtish,
78
+ 0036.Jule,
79
+ 0037.Justina,
80
+ 0038.Kunade, leg.skirtish,
81
+ 0039.Kaya,
82
+ 0040.Katrine,
83
+ 0041.Laila,
84
+ 0042.Hazila, leg.skirtish,
85
+ 0043.Kassia,
86
+ 0044.Kasumi,
87
+ 0045.Karma,
88
+ 0046.Klaudia, leg.skirtish,
89
+ 0047.Linsi, leg.skirtish,
90
+ 0048.Kiki,
91
+ 0049.Kornelia,
92
+ 0050.Kumimi,
93
+ 0051.Mayli,
94
+ 0052.Kwanda,
95
+ 0053.Leejin, leg.skirtish,
96
+ 0054.Lesra, leg.skirtish,
97
+ 0055.Mathilde, leg.skirtish,
98
+ 0056.Lorelei, leg.skirtish,
99
+ 0057.Lotta, leg.skirtish,
100
+ 0058.Luca,
101
+ 0059.Mathea,
102
+ 0060.Macey, leg.skirtish,
103
+ 0061.Marcelia,
104
+ 0062.Maggie, leg.skirtish,
105
+ 0063.Marise,
106
+ 0064.Melissa, leg.skirtish,
107
+ 0065.Mesa,
108
+ 0066.Merel, leg.skirtish,
109
+ 0067.Melodie, leg.skirtish,
110
+ 0068.Ksandra,
111
+ 0069.Mireille,
112
+ 0070.Minnie, leg.skirtish,
113
+ 0071.Sacha,
114
+ 0072.Paola,
115
+ 0073.Renata,
116
+ 0074.Silvia, leg.skirtish,
117
+ 0075.Serena,
118
+ 0076.Tala,
119
+ 0077.Valeria, leg.skirtish,
120
+ 0078.Quin, leg.skirtish,
121
+ 0079.Ruca,
122
+ 0080.Robelle, leg.skirtish,
123
+ 0081.Diane,
124
+ 0082.Teresa, leg.skirtish,
125
+ 0083.Sarella,
126
+ 0084.Serra, leg.skirtish,
127
+ 0085.Shirei, leg.skirtish,
128
+ 0086.Sheena,
129
+ 0087.Sario,
130
+ 0088.Sidey,
131
+ 0089.Sylvia, leg.skirtish,
132
+ 0090.Sonya, leg.skirtish,
133
+ 0091.Tali,
134
+ 0092.Tenshi, leg.skirtish,
135
+ 0093.Tessa, leg.skirtish,
136
+ 0094.Victorya, leg.skirtish,
137
+ 0095.Tara,
138
+ 0096.Tarly, leg.skirtish,
139
+ 0097.Vasper,
140
+ 0098.Vanga,
141
+ 0099.Vicaria,
142
+ 0100.Ulyeta,
143
+ 0101.Yanasha, leg.skirtish,
144
+ 0102.Virginia, leg.skirtish,
145
+ 0103.Rosabel,
146
+ 0104.Defna,
147
+ 0105.Zhenji, leg.skirtish,
148
+ 0106.Nettie,
149
+ 0107.Valina,
150
+ 0108.Alena,
151
+ 0109.Adali,
152
+ 0110.Agnes, leg.skirtish,
153
+ 0111.Arlene,
154
+ 0112.Asma, leg.skirtish,
155
+ 0113.Ayox,
156
+ 0114.Beria, leg.skirtish,
157
+ 0115.Blix,
158
+ 0116.Bubble, leg.skirtish,
159
+ 0117.Cecilia,
160
+ 0118.Chae, leg.skirtish,
161
+ 0119.Clesha,
162
+ 0120.Clovie,
163
+ 0121.Conli,
164
+ 0122.Criza,
165
+ 0123.Daizy, leg.skirtish,
166
+ 0124.Darta,
167
+ 0125.Dellie,
168
+ 0126.Draga,
169
+ 0127.Astrid,
170
+ 0128.Ellen,
171
+ 0129.Atium,
172
+ 0130.Eshonai, leg.skirtish,
173
+ 0131.Feizhi, leg.skirtish,
174
+ 0132.Felya,
175
+ 0133.Fiella, leg.skirtish,
176
+ 0134.Fils,
177
+ 0135.Filsie,
178
+ 0136.Flidry,
179
+ 0137.Floret,
180
+ 0138.Florina, leg.skirtish,
181
+ 0139.Flynia, leg.skirtish,
182
+ 0140.Frile, leg.skirtish,
183
+ 0141.Gabie, leg.skirtish,
184
+ 0142.Ginie,
185
+ 0143.Grima,
186
+ 0144.Hase,
187
+ 0145.Helen, leg.skirtish,
188
+ 0146.Helia,
189
+ 0147.Hirama, leg.skirtish,
190
+ 0148.Hive,
191
+ 0149.Idavie, leg.skirtish,
192
+ 0150.Ilaye, leg.skirtish,
193
+ 0151.Ildra,
194
+ 0152.Jacria,
195
+ 0153.Jeria, leg.skirtish,
196
+ 0154.Jewel,
197
+ 0155.Juni,
198
+ 0156.Kaelie,
199
+ 0157.Kali, leg.skirtish,
200
+ 0158.Keris, leg.skirtish,
201
+ 0159.Kesai,
202
+ 0160.Kiras,
203
+ 0161.Klee,
204
+ 0162.Lania, leg.skirtish,
205
+ 0163.Lansia,
206
+ 0164.Larim,
207
+ 0165.Larin,
208
+ 0166.Layan, leg.skirtish,
209
+ 0167.Leaf,
210
+ 0168.Leejay,
211
+ 0169.Lenity, leg.skirtish,
212
+ 0170.Lift,
213
+ 0171.Lise,
214
+ 0172.Lite, leg.skirtish,
215
+ 0173.Lorah,
216
+ 0174.Lucky,
217
+ 0175.Mabel, leg.skirtish,
218
+ 0176.Walrune, leg.skirtish,
219
+ 0177.Hazel,
220
+ 0178.Moren, leg.skirtish,
221
+ 0179.Nadja,
222
+ 0180.Nalia,
223
+ 0181.Navanie, leg.skirtish,
224
+ 0182.Oxana,
225
+ 0183.Palim, leg.skirtish,
226
+ 0184.Panari, leg.skirtish,
227
+ 0185.Hayata,
228
+ 0186.Piena,
229
+ 0187.Prava,
230
+ 0188.Primm, leg.skirtish,
231
+ 0189.Rangle,
232
+ 0190.Rayn,
233
+ 0191.Ream,
234
+ 0192.Reese,
235
+ 0193.Refala, leg.skirtish,
236
+ 0194.Rela, leg.skirtish,
237
+ 0195.Rita,
238
+ 0196.Riva,
239
+ 0197.Sata,
240
+ 0198.Scilla, leg.skirtish,
241
+ 0199.Shallan,
242
+ 0200.Shavira,
243
+ 0201.Shika, leg.skirtish,
244
+ 0202.Eizia, leg.skirtish,
245
+ 0203.Sliver,
246
+ 0204.Stara,
247
+ 0205.Stern, leg.skirtish,
248
+ 0206.Stria,
249
+ 0207.Telsin,
250
+ 0208.Tetra,
251
+ 0209.Thevaria,
252
+ 0210.Thyme,
253
+ 0211.Valenta,
254
+ 0212.Vanira,
255
+ 0213.Vanissa,
256
+ 0214.Variena,
257
+ 0215.Venli,
258
+ 0216.Vivenna,
259
+ 0217.Elvani, leg.skirtish,
260
+ 0218.Melahan, leg.skirtish,
261
+ 0219.Mina, leg.skirtish,
262
+ 0220.Peidra, leg.skirtish,
263
+ 0221.Amelia, leg.skirtish, crotch.pantyhose,
264
+ 0222.Sarke,
265
+ 0223.Nagatora, leg.skirtish,
266
+ 0224.Maryn, leg.skirtish, crotch.pantyhose,
267
+ 0225.Areda,
268
+ 0226.Ghislaine,
269
+ 0227.Piper, leg.skirtish, crotch.pantyhose,
270
+ 0228.Topline, leg.skirtish,
271
+ 0229.Lavinia, leg.skirtish,
272
+ 0230.Pernel, leg.skirtish,
273
+ 0231.Semra, leg.skirtish,
274
+ 0232.Myra, leg.skirtish, crotch.pantyhose,
275
+ 0233.Pencil,
276
+ 9998.Mannequin,
277
+ 9999.JoAhn, leg.skirtish,"""
278
+
279
+
280
+ def _validate_component(value, label):
281
+ value = str(value).strip()
282
+ if not value or value in (".", ".."):
283
+ raise ValueError("{} must not be empty, '.' or '..'.".format(label))
284
+ if "/" in value or "\\" in value or any(ord(c) < 32 or ord(c) == 127 for c in value):
285
+ raise ValueError("{} must be a single name without slashes or control characters.".format(label))
286
+ return value
287
+
288
+
289
+ def parse_bam(text):
290
+ """Return unique names in BAM order and notes about duplicate records.
291
+
292
+ Accepts newline-separated or comma-separated NUMBER.Name records. Tokens
293
+ after the first comma, such as leg.skirtish, are ignored unless they start
294
+ a new numbered record. Conflicting IDs abort before any remote changes.
295
+ """
296
+ pattern = r"(?:^|[,\r\n])[ \t]*(\d+)[ \t]*\.[ \t]*([^,\r\n]+)"
297
+ names, notes, by_id, seen_names = [], [], {}, set()
298
+ for match in re.finditer(pattern, str(text).lstrip("\ufeff")):
299
+ number = int(match.group(1))
300
+ name = _validate_component(match.group(2), "Character name")
301
+ if number in by_id and by_id[number] != name:
302
+ raise ValueError("BAM ID {} has conflicting names: {!r} and {!r}.".format(number, by_id[number], name))
303
+ by_id[number] = name
304
+ if name in seen_names:
305
+ notes.append("Duplicate character ignored: {}".format(name))
306
+ continue
307
+ seen_names.add(name)
308
+ names.append(name)
309
+ if not names:
310
+ raise ValueError("BAM contains no valid records. Use entries like 0109.Adali, leg.skirtish,")
311
+ return names, notes
312
+
313
+
314
+ def _current_file(bucket, name):
315
+ """Return the latest visible exact-name version, respecting hide markers."""
316
+ for version in bucket.list_file_versions(name, fetch_count=1):
317
+ if version.file_name != name:
318
+ return None
319
+ if version.action in ("upload", "copy"):
320
+ return version
321
+ if version.action == "hide":
322
+ return None
323
+ if version.action != "start":
324
+ raise RuntimeError("Unexpected Backblaze file action: {}".format(version.action))
325
+ return None
326
+
327
+
328
+ def _folder_exists(bucket, name):
329
+ # B2 folders are prefixes; a marker or one visible child is enough.
330
+ return next(bucket.ls(name + "/", latest_only=True, recursive=True, fetch_count=1), None) is not None
331
+
332
+
333
+ def _sha1(version):
334
+ digest = str(version.content_sha1 or "").removeprefix("unverified:")
335
+ if not re.fullmatch(r"[0-9a-fA-F]{40}", digest):
336
+ digest = str((version.file_info or {}).get("large_file_sha1", ""))
337
+ return digest.lower() if re.fullmatch(r"[0-9a-fA-F]{40}", digest) else None
338
+
339
+
340
+ def _verify_copy(source, copied, destination_name):
341
+ if copied.file_name != destination_name or copied.size != source.size:
342
+ raise RuntimeError("Destination filename or byte size does not match the source.")
343
+ source_sha1, copied_sha1 = _sha1(source), _sha1(copied)
344
+ if source_sha1 and copied_sha1 and source_sha1 != copied_sha1:
345
+ raise RuntimeError("Destination SHA-1 does not match the source.")
346
+ if source.content_type != copied.content_type:
347
+ raise RuntimeError("Destination content type does not match the source.")
348
+ for key, value in (source.file_info or {}).items():
349
+ if (copied.file_info or {}).get(key) != value:
350
+ raise RuntimeError("Destination metadata does not match the source: {}".format(key))
351
+
352
+
353
+ def _rename_one(bucket, source, destination_name):
354
+ """Return an optional cleanup warning; raise on an incomplete rename."""
355
+ encryption = getattr(source, "server_side_encryption", None)
356
+ mode = getattr(getattr(encryption, "mode", None), "value", None)
357
+ if mode == "SSE-C":
358
+ raise RuntimeError("SSE-C encryption requires a customer encryption key; source unchanged.")
359
+
360
+ options = {
361
+ # Explicit length enables the SDK's multipart path for >5 GB files.
362
+ "length": source.size if source.size else None,
363
+ "content_type": source.content_type,
364
+ "file_info": dict(source.file_info or {}),
365
+ }
366
+ if mode == "SSE-B2":
367
+ options["destination_encryption"] = encryption
368
+ retention = getattr(source, "file_retention", None)
369
+ if getattr(getattr(retention, "mode", None), "value", None) in ("governance", "compliance"):
370
+ options["file_retention"] = retention
371
+ hold = getattr(source, "legal_hold", None)
372
+ if getattr(hold, "value", None) in ("on", "off"):
373
+ options["legal_hold"] = hold
374
+
375
+ try:
376
+ copied = bucket.copy(source.id_, destination_name, **options)
377
+ except Exception as exc:
378
+ raise RuntimeError("Copy failed; source version retained. A destination copy may exist if the response was lost. {}".format(exc)) from exc
379
+
380
+ try:
381
+ confirmed = bucket.get_file_info_by_id(copied.id_)
382
+ if confirmed.id_ != copied.id_:
383
+ raise RuntimeError("Destination version ID mismatch.")
384
+ _verify_copy(source, confirmed, destination_name)
385
+ current_destination = _current_file(bucket, destination_name)
386
+ if current_destination is None or current_destination.id_ != copied.id_:
387
+ raise RuntimeError("Destination changed during copying.")
388
+ current_source = _current_file(bucket, source.file_name)
389
+ if current_source is None or current_source.id_ != source.id_:
390
+ raise RuntimeError("Source changed during copying.")
391
+ except Exception as exc:
392
+ raise RuntimeError("Copy could not be verified; source version retained. Inspect destination {} (version {}). {}".format(destination_name, copied.id_, exc)) from exc
393
+
394
+ try:
395
+ # Hide BEFORE deleting: otherwise an older source version may resurface.
396
+ bucket.hide_file(source.file_name)
397
+ if _current_file(bucket, source.file_name) is not None:
398
+ raise RuntimeError("Source filename is still visible; it may have been changed concurrently.")
399
+ except Exception as exc:
400
+ raise RuntimeError("Destination verified, but hiding the old filename could not be confirmed; source version retained. {}".format(exc)) from exc
401
+
402
+ try:
403
+ bucket.delete_file_version(source.id_, source.file_name)
404
+ except Exception as exc:
405
+ return "Old filename hidden, but deletion of source version {} was not confirmed: {}".format(source.id_, exc)
406
+ return ""
407
+
408
+
409
+ def _open_bucket(key_id, key, bucket_name):
410
+ # Lazy import keeps this node discoverable even before installing b2sdk.
411
+ try:
412
+ from b2sdk.v2 import B2Api, InMemoryAccountInfo
413
+ except ImportError as exc:
414
+ raise RuntimeError('Missing dependency. In ComfyUI\'s Python environment run: python -m pip install "b2sdk>=2.5,<3"') from exc
415
+ api = B2Api(InMemoryAccountInfo())
416
+ api.authorize_account("production", key_id, key)
417
+ return api.get_bucket_by_name(bucket_name)
418
+
419
+
420
+ def _check_interrupted():
421
+ try:
422
+ import comfy.model_management as model_management
423
+ except ImportError:
424
+ return
425
+ model_management.throw_exception_if_processing_interrupted()
426
+
427
+
428
+ def _progress_bar(total):
429
+ try:
430
+ from comfy.utils import ProgressBar
431
+ except ImportError:
432
+ return None
433
+ return ProgressBar(total)
434
+
435
+
436
+ class Backblaze_Files_Renamer:
437
+ @classmethod
438
+ def INPUT_TYPES(cls):
439
+ return {"required": {
440
+ "backblaze_master_key": ("STRING", {"default": "", "dynamicPrompts": False}),
441
+ "backblaze_master_key_ID": ("STRING", {"default": "", "dynamicPrompts": False}),
442
+ "BAM": ("STRING", {"default": DEFAULT_BAM, "multiline": True, "dynamicPrompts": False}),
443
+ "bucket_name": ("STRING", {"default": "FemuChars", "dynamicPrompts": False}),
444
+ "before_filename": ("STRING", {"default": "Front_To_Reartaunt_00000.mp4", "dynamicPrompts": False}),
445
+ "after_filename": ("STRING", {"default": "Front_To_Reartaunt.mp4", "dynamicPrompts": False}),
446
+ }}
447
+
448
+ RETURN_TYPES = ("STRING", "INT", "INT", "INT")
449
+ RETURN_NAMES = ("status_report", "renamed_count", "skipped_count", "error_count")
450
+ FUNCTION = "rename_files"
451
+ CATEGORY = "Salia/Backblaze"
452
+ OUTPUT_NODE = True
453
+ DESCRIPTION = "Rename one exact filename across character folders parsed from BAM. Missing files/folders and existing destinations are skipped."
454
+
455
+ @classmethod
456
+ def IS_CHANGED(cls, **kwargs):
457
+ # Remote state may change even when widget values are unchanged.
458
+ return float("nan")
459
+
460
+ def rename_files(self, backblaze_master_key, backblaze_master_key_ID,
461
+ BAM, bucket_name, before_filename, after_filename):
462
+ key = str(backblaze_master_key).strip()
463
+ key_id = str(backblaze_master_key_ID).strip()
464
+
465
+ def safe_error(exc):
466
+ message = str(exc)
467
+ for secret in sorted((key, key_id), key=len, reverse=True):
468
+ if secret:
469
+ message = message.replace(secret, "[REDACTED]")
470
+ return message.replace("\r", " ").replace("\n", " ")
471
+
472
+ def result(report, renamed=0, skipped=0, errors=0):
473
+ print("[Backblaze_Files_Renamer]\n" + report, flush=True)
474
+ return {"ui": {"text": [report]}, "result": (report, renamed, skipped, errors)}
475
+
476
+ try:
477
+ names, notes = parse_bam(BAM)
478
+ bucket_name = _validate_component(bucket_name, "bucket_name")
479
+ before = _validate_component(before_filename, "before_filename")
480
+ after = _validate_component(after_filename, "after_filename")
481
+ if before == after:
482
+ return result("Nothing renamed: before_filename and after_filename are identical.", skipped=len(names))
483
+ if not key or not key_id:
484
+ raise ValueError("Enter both the Backblaze master key and master key ID.")
485
+ bucket = _open_bucket(key_id, key, bucket_name)
486
+ except Exception as exc:
487
+ return result("ERROR: " + safe_error(exc), errors=1)
488
+
489
+ counts = Counter()
490
+ details = ["BAM NOTE: " + note for note in notes]
491
+ progress = _progress_bar(len(names))
492
+ for name in names:
493
+ _check_interrupted()
494
+ old_name, new_name = name + "/" + before, name + "/" + after
495
+ try:
496
+ source = _current_file(bucket, old_name)
497
+ if source is None:
498
+ if _folder_exists(bucket, name):
499
+ tag, detail = "MISSING_FILE", old_name + " (no visible source file)"
500
+ else:
501
+ tag, detail = "MISSING_FOLDER", name + "/ (no visible files or folder marker)"
502
+ counts["skipped"] += 1
503
+ elif _current_file(bucket, new_name) is not None:
504
+ tag, detail = "DESTINATION_EXISTS", new_name + " (skipped; source unchanged)"
505
+ counts["skipped"] += 1
506
+ else:
507
+ warning = _rename_one(bucket, source, new_name)
508
+ counts["renamed"] += 1
509
+ tag, detail = "RENAMED", old_name + " -> " + new_name
510
+ if warning:
511
+ counts["warnings"] += 1
512
+ tag = "RENAMED_WITH_WARNING"
513
+ detail += " | " + safe_error(warning)
514
+ except Exception as exc:
515
+ counts["errors"] += 1
516
+ tag, detail = "ERROR", old_name + " | " + safe_error(exc)
517
+ line = "[{}] {}".format(tag, detail)
518
+ details.append(line)
519
+ print("[Backblaze_Files_Renamer] " + line, flush=True)
520
+ if progress is not None:
521
+ progress.update(1)
522
+
523
+ summary = (
524
+ "Backblaze_Files_Renamer\n"
525
+ "Bucket: {}\nBefore: {}\nAfter: {}\n"
526
+ "Characters: {} | Renamed: {} | Skipped: {} | Errors: {} | Cleanup warnings: {}\n"
527
+ ).format(bucket_name, before, after, len(names), counts["renamed"], counts["skipped"], counts["errors"], counts["warnings"])
528
+ report = summary + "\n" + "\n".join(details)
529
+ return result(report, counts["renamed"], counts["skipped"], counts["errors"])
530
+
531
+
532
+ NODE_CLASS_MAPPINGS = {"Backblaze_Files_Renamer": Backblaze_Files_Renamer}
533
+ NODE_DISPLAY_NAME_MAPPINGS = {"Backblaze_Files_Renamer": "Backblaze_Files_Renamer"}