-
Notifications
You must be signed in to change notification settings - Fork 7
/
clean_multi.py
473 lines (396 loc) · 17.1 KB
/
clean_multi.py
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#!/usr/bin/env python3
# --------------------------------------------------------------------------- #
# The MIT License (MIT) #
# #
# Copyright (c) 2021 Eliud Cabrera Castillo <[email protected]> #
# #
# Permission is hereby granted, free of charge, to any person obtaining #
# a copy of this software and associated documentation files #
# (the "Software"), to deal in the Software without restriction, including #
# without limitation the rights to use, copy, modify, merge, publish, #
# distribute, sublicense, and/or sell copies of the Software, and to permit #
# persons to whom the Software is furnished to do so, subject to the #
# following conditions: #
# #
# The above copyright notice and this permission notice shall be included #
# in all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL #
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER #
# DEALINGS IN THE SOFTWARE. #
# --------------------------------------------------------------------------- #
"""Functions to clean multiple downloaded claims from the LBRY network."""
import os
import lbrytools.funcs as funcs
import lbrytools.parse as parse
import lbrytools.resolve_ch as resch
import lbrytools.sort as sort
import lbrytools.clean as clean
def ch_cleanup(channel=None, number=2, what="media",
server="http://localhost:5279"):
"""Delete all claims from a channel, except for the latest ones.
Parameters
----------
channel: str
A channel's name, full or partial:
`'@MyChannel#5'`, `'MyChannel#5'`, `'MyChannel'`
If a simplified name is used, and there are various channels
with the same name, the one with the highest LBC bid will be selected.
Enter the full name to choose the right one.
number: int, optional
It defaults to 2.
The number of items to keep from `channel`.
These will be the newest ones according to their `'release_time'`
or `'timestamp'`, if the former is missing.
what: str, optional
It defaults to `'media'`, in which case only the full media file
(mp4, mp3, mkv, etc.) is deleted.
If it is `'blobs'`, it will delete only the blobs.
If it is `'both'`, it will delete both the media file
and the blobs.
server: str, optional
It defaults to `'http://localhost:5279'`.
This is the address of the `lbrynet` daemon, which should be running
in your computer before using any `lbrynet` command.
Normally, there is no need to change this parameter from its default
value.
Returns
-------
list of bool
It returns a list of booleans, where each boolean represents
a deleted item; `True` if the claim was deleted successfully,
and `False` if it was not.
False
If there is a problem or non existing channel,
it will return `False`.
"""
if not funcs.server_exists(server=server):
return False
if not channel or not isinstance(channel, str):
print("Clean up items from a single channel.")
print(f"channel={channel}")
return False
if (number is None or number is False
or not isinstance(number, int) or number < 0):
number = 2
print("Number must be a positive integer, "
f"set to default value, number={number}")
if (not isinstance(what, str)
or what not in ("media", "blobs", "both")):
print(">>> Error: what can only be 'media', 'blobs', 'both'")
print(f"what={what}")
return False
list_info_del = []
sorted_items = sort.sort_items(channel=channel,
server=server)
if not sorted_items:
return False
n_items = len(sorted_items)
remaining = n_items - 0
for it, item in enumerate(sorted_items, start=1):
if remaining <= number:
print(8*"-")
print(f"Finished deleting; remaining {remaining}")
break
print(f"Claim {it}/{n_items}")
del_info = clean.delete_single(cid=item["claim_id"], what=what,
server=server)
list_info_del.append(del_info)
remaining = n_items - it
if remaining > number:
print()
if remaining == 0:
print(8*"-")
print(f"Finished deleting; remaining {remaining}")
return list_info_del
def ch_cleanup_multi(channels=None, what="media", number=None,
server="http://localhost:5279"):
"""Delete all claims from a list of channels, except for the latest ones.
Parameters
----------
channels: list of lists
Each element in the list is a list of two elements.
The first element is a channel's name, full or partial;
the second element is an integer that indicates the number
of items from that channel that will be kept.
::
channels = [
['@MyChannel#5', 3],
['GoodChannel#f', 4],
['Fast_channel', 2]
]
what: str, optional
It defaults to `'media'`, in which case only the full media file
(mp4, mp3, mkv, etc.) is deleted.
If it is `'blobs'`, it will delete only the blobs.
If it is `'both'`, it will delete both the media file
and the blobs.
number: int, optional
It defaults to `None`.
If this is present, it will override the individual
numbers in `channels`.
That is, the number of claims that will be kept
will be the same for every channel.
server: str, optional
It defaults to `'http://localhost:5279'`.
This is the address of the `lbrynet` daemon, which should be running
in your computer before using any `lbrynet` command.
Normally, there is no need to change this parameter from its default
value.
Alternative input
-----------------
channels: list of str
The list of channels can also be specified as a list of strings.
::
channels = [
'@MyChannel#5',
'GoodChannel#f',
'Fast_channel'
]
number = 4
In this case `number` must be specified explicitly to control
the number of claims that will be kept for every channel.
Returns
-------
list of lists of bool
A list of lists, where each internal list represents one channel,
and this internal list has a boolean value for each deleted item;
`True` if the claim was deleted successfully, and `False` if it
was not.
False
If there is a problem, or an empty channel list,
it will return `False`.
"""
if not funcs.server_exists(server=server):
return False
if not channels or not isinstance(channels, (list, tuple)):
m = ["Delete items from a list of channels and numbers.",
" [",
" ['@MyChannel', 2],",
" ['@AwesomeCh:8', 1],",
" ['@A-B-C#a', 3]",
" ]"]
print("\n".join(m))
print(f"channels={channels}")
return False
if (not isinstance(what, str)
or what not in ("media", "blobs", "both")):
print(">>> Error: what can only be 'media', 'blobs', 'both'")
print(f"what={what}")
return False
DEFAULT_NUM = 2
if number:
if not isinstance(number, int) or number < 0:
number = DEFAULT_NUM
print("Number must be a positive integer, "
f"set to default value, number={number}")
print("Global value overrides per channel number, "
f"number={number}")
n_channels = len(channels)
if n_channels <= 0:
print(">>> No channels in the list")
return False
list_ch_del_info = []
# Each element of the `channels` list may be a string,
# a list with a single element, or a list with multiple elements (two).
# ch1 = "Channel"
# ch2 = ["@Ch1"]
# ch3 = ["Mychan", 2]
# channels = [ch1, ch2, ch3]
for it, channel in enumerate(channels, start=1):
ch_del_info = []
if isinstance(channel, str):
_number = DEFAULT_NUM
elif isinstance(channel, (list, tuple)):
if len(channel) < 2:
_number = DEFAULT_NUM
else:
_number = channel[1]
if not isinstance(_number, (int, float)) or _number < 0:
print(f">>> Number set to {DEFAULT_NUM}")
_number = DEFAULT_NUM
_number = int(_number)
channel = channel[0]
if not isinstance(channel, str):
print(f"Channel {it}/{n_channels}, {channel}")
print(">>> Error: channel must be a string. Skip channel.")
print()
list_ch_del_info.append(ch_del_info)
continue
if not channel.startswith("@"):
channel = "@" + channel
# Number overrides the individual number for all channels
if number:
_number = number
print(f"Channel {it}/{n_channels}, {channel}")
ch_del_info = ch_cleanup(channel=channel, number=_number, what=what,
server=server)
list_ch_del_info.append(ch_del_info)
return list_ch_del_info
def remove_media(never_delete=None,
server="http://localhost:5279"):
"""Remove all media files but leave the binary blobs.
This function is intended for systems that will only seed content.
It should be run after downloading various claims, for example,
with `download_single` or `ch_download_latest_multi`.
It will delete only the media files (mp4, mp3, mkv, etc.)
but leave the blobs intact to continue seeding them to the network.
Parameters
----------
never_delete: list of str, optional
It defaults to `None`.
If it exists it is a list with channel names.
The content produced by these channels will not be deleted
so the media files and blobs will remain in `main_dir`.
Using this parameter is slow as it needs to perform
an additional search for the channel.
server: str, optional
It defaults to `'http://localhost:5279'`.
This is the address of the `lbrynet` daemon, which should be running
in your computer before using any `lbrynet` command.
Normally, there is no need to change this parameter from its default
value.
Returns
-------
bool
It returns `True` if the older files were successfully deleted.
It returns `False` if there is a problem, or if there
was nothing to clean up.
"""
if not funcs.server_exists(server=server):
return False
if never_delete and not isinstance(never_delete, (list, tuple)):
print("Must be a list of channels that should never be deleted.")
print(f"never_delete={never_delete}")
return False
print(80 * "-")
print("Delete all media files")
claims = sort.sort_items(server=server)
n_claims = len(claims)
for num, claim in enumerate(claims, start=1):
name = claim["claim_name"]
out = f"{num:4d}/{n_claims:4d}; {name}; "
if never_delete:
channel = resch.find_channel(cid=claim["claim_id"],
full=False,
server=server)
if not channel:
continue
channel = channel.split("@")[1]
skip = False
for safe_channel in never_delete:
if channel in safe_channel:
skip = True
break
if skip:
print(out + f"item from {channel} will not be deleted. "
"Skipping.")
continue
path = claim["download_path"]
if path:
os.remove(path)
print(out + f"delete {path}")
else:
print(out + "no media found locally, probably already deleted.")
print("Media files deleted")
return True
def remove_claims(start=1, end=0, file=None, invalid=False,
what="media",
server="http://localhost:5279"):
"""Delete claims from a file, or delete the ones already present.
Parameters
----------
start: int, optional
It defaults to 1.
Operate on the item starting from this index in the internal list
of claims or in the claims provided by `file`.
end: int, optional
It defaults to 0.
Operate until and including this index in the internal list of claims
or in the claims provided by `file`.
If it is 0, it is the same as the last index.
file: str, optional
It defaults to `None`.
The file to read claims from. It is a comma-separated value (CSV)
list of claims, in which each row represents a claim,
and one element is the `'claim_id'` which can be used
with `delete_single` to delete that claim.
If `file=None` it will delete the claims obtained
from `sort_items` which should already be present
in the system fully or partially.
invalid: bool, optional
It defaults to `False`, in which case it will assume
the processed claims are still valid in the online database.
It will use `lbrynet claim search` to resolve the `claim_id`.
If it is `True` it will assume the claims are no longer valid,
that is, that the claims have been removed from the online database
and only exist locally.
In this case, it will use `lbrynet file list` to resolve
the `claim_id`.
Therefore this parameter is required if `file` is a document
containing 'invalid' claims, otherwise the claims won't be found
and won't be deleted.
what: str, optional
It defaults to `'media'`, in which case only the full media file
(mp4, mp3, mkv, etc.) is deleted.
If it is `'blobs'`, it will delete only the blobs.
If it is `'both'`, it will delete both the media file
and the blobs.
server: str, optional
It defaults to `'http://localhost:5279'`.
This is the address of the `lbrynet` daemon, which should be running
in your computer before using any `lbrynet` command.
Normally, there is no need to change this parameter from its default
value.
Returns
-------
list of bool
It returns a list of booleans, where each boolean represents
a deleted item; `True` if the claim was deleted successfully,
and `False` if it was not.
False
If there is a problem, non-existing claims, or non-existing file,
it will return `False`.
"""
if not funcs.server_exists(server=server):
return False
print(80 * "-")
if not file:
print("Remove claims from existing list")
sorted_items = sort.sort_items(server=server)
if not sorted_items:
print(">>> Error: no claims previously downloaded.")
return False
else:
if file and not isinstance(file, str) or not os.path.exists(file):
print("The file path must exist.")
print(f"file={file}")
return False
print("Remove claims from existing file")
sorted_items = parse.parse_claim_file(file=file)
print()
if not sorted_items:
print(">>> Error: the file must have a 'claim_id' "
"(40-character alphanumeric string); "
"could not parse the file.")
print(f"file={file}")
return False
n_items = len(sorted_items)
list_del_info = []
for it, item in enumerate(sorted_items, start=1):
if it < start:
continue
if end != 0 and it > end:
break
print(f"Claim {it}/{n_items}")
del_info = clean.delete_single(cid=item["claim_id"],
invalid=invalid,
what=what,
server=server)
list_del_info.append(del_info)
print()
return list_del_info