/
__init__.py
1431 lines (1205 loc) · 40.8 KB
/
__init__.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# ____________
# ___/ | \_____________ _ _ ___
# / ___/ | _ __ _ _| | ___ __ _ __| | \
# / \___/ ______/ | '_ \ || | |__/ _ \/ _` / _` | \
# \ ◯ | | .__/\_, |____\___/\__,_\__,_| /
# \_______\ /_______|_| |__/________________________/
# \ /
# \/
import json
import os
import re
import time
from enum import IntFlag
from ..datatypes.data import *
from ..datatypes.enums import *
from ..datatypes.exceptions import *
from ..datatypes.pyfile import PyFile
from ..log_factory import LogFactory
from ..network.request_factory import get_url
from ..utils import fs, seconds
from ..utils.old.packagetools import parse_names
# contains function names mapped to their permissions
# unlisted functions are for admins only
perm_map = {}
# contains function names mapped to their legacy name
legacy_map = {}
# decorator only called on init, never initialized, so has no effect on runtime
def permission(bits):
class Wrapper:
def __new__(cls, func, *args, **kwargs):
perm_map[func.__name__] = bits
return func
return Wrapper
def legacy(legacy_name):
class Wrapper:
def __new__(cls, func, *args, **kwargs):
legacy_map[func.__name__] = legacy_name
return func
return Wrapper
urlmatcher = re.compile(
r"(?:https?|ftps?|xdcc|sftp):(?://|\\\\)+[\w\-._~:/?#\[\]@!$&'()*+,;=]*|magnet:\?.+",
re.IGNORECASE,
)
class Perms(IntFlag):
ANY = 0 #: requires no permission, but login
ADD = 1 #: can add packages
DELETE = 2 #: can delete packages
STATUS = 4 #: see and change server status
LIST = 16 #: see queue and collector
MODIFY = 32 #: modify some attribute of downloads
DOWNLOAD = 64 #: can download from webinterface
SETTINGS = 128 #: can access settings
ACCOUNTS = 256 #: can access accounts
LOGS = 512 #: can see server logs
class Role(IntFlag):
ADMIN = 0 #: admin has all permissions implicit
USER = 1
def has_permission(userperms, perms):
# bitwise or perms before if needed
return perms == (userperms & perms)
# API VERSION
__version__ = 1
class Api:
"""
**pyLoads API**
This is accessible either internal via core.api or via thrift backend.
see Thrift specification file remote/thriftbackend/pyload.thrift\
for information about data structures and what methods are usable with rpc.
Most methods requires specific permissions, please look at the source code if you need to know.\
These can be configured via webinterface.
Admin user have all permissions, and are the only ones who can access the methods with no specific permission.
"""
def __new__(cls, core):
obj = super(Api, cls).__new__(cls)
# add methods specified by the @legacy decorator
# also set legacy method permissions according to the @permissions decorator
for func_name, legacy_name in legacy_map.items():
func = getattr(obj, func_name)
setattr(obj, legacy_name, func)
permissions = perm_map.get(func_name)
if permissions is not None:
perm_map[legacy_name] = permissions
return obj
def __init__(self, core):
self.pyload = core
self._ = core._
def _convert_py_file(self, p):
f = FileData(
p["id"],
p["url"],
p["name"],
p["plugin"],
p["size"],
p["format_size"],
p["status"],
p["statusmsg"],
p["package"],
p["error"],
p["order"],
)
return f
def _convert_config_format(self, c):
sections = {}
for section_name, sub in c.items():
section = ConfigSection(section_name, sub["desc"])
items = []
for key, data in sub.items():
if key in ("desc", "outline"):
continue
item = ConfigItem()
item.name = key
item.description = data["desc"]
item.value = str(data["value"])
item.type = data["type"]
items.append(item)
section.items = items
sections[section_name] = section
if "outline" in sub:
section.outline = sub["outline"]
return sections
@legacy("getConfigValue")
@permission(Perms.SETTINGS)
def get_config_value(self, category, option, section="core"):
"""
Retrieve config value.
:param category: name of category, or plugin
:param option: config option
:param section: 'plugin' or 'core'
:return: config value
"""
if section == "core":
value = self.pyload.config[category][option]
else:
value = self.pyload.config.get_plugin(category, option)
return value
@legacy("setConfigValue")
@permission(Perms.SETTINGS)
def set_config_value(self, category, option, value, section="core"):
"""
Set new config value.
:param category:
:param option:
:param value: new config value
:param section: 'plugin' or 'core
"""
self.pyload.addon_manager.dispatch_event(
"config_changed", category, option, value, section
)
if section == "core":
self.pyload.config[category][option] = value
if option in (
"limit_speed",
"max_speed",
): #: not so nice to update the limit
self.pyload.request_factory.update_bucket()
elif section == "plugin":
self.pyload.config.set_plugin(category, option, value)
@legacy("getConfig")
@permission(Perms.SETTINGS)
def get_config(self):
"""
Retrieves complete config of core.
:return: list of `ConfigSection`
"""
return self._convert_config_format(self.pyload.config.config)
@legacy("getConfigDict")
def get_config_dict(self):
"""
Retrieves complete config in dict format, not for RPC.
:return: dict
"""
return self.pyload.config.config
@legacy("getPluginConfig")
@permission(Perms.SETTINGS)
def get_plugin_config(self):
"""
Retrieves complete config for all plugins.
:return: list of `ConfigSection`
"""
return self._convert_config_format(self.pyload.config.plugin)
@legacy("getPluginConfigDict")
def get_plugin_config_dict(self):
"""
Plugin config as dict, not for RPC.
:return: dict
"""
return self.pyload.config.plugin
@legacy("pauseServer")
@permission(Perms.STATUS)
def pause_server(self):
"""
Pause server: Tt wont start any new downloads, but nothing gets aborted.
"""
self.pyload.thread_manager.pause = True
@legacy("unpauseServer")
@permission(Perms.STATUS)
def unpause_server(self):
"""
Unpause server: New Downloads will be started.
"""
self.pyload.thread_manager.pause = False
@legacy("togglePause")
@permission(Perms.STATUS)
def toggle_pause(self):
"""
Toggle pause state.
:return: new pause state
"""
self.pyload.thread_manager.pause ^= True
return self.pyload.thread_manager.pause
@legacy("toggleReconnect")
@permission(Perms.STATUS)
def toggle_reconnect(self):
"""
Toggle reconnect activation.
:return: new reconnect state
"""
self.pyload.config.toggle("reconnect", "enabled")
return self.pyload.config.get("reconnect", "enabled")
@legacy("statusServer")
@permission(Perms.LIST)
def status_server(self):
"""
Some general information about the current status of pyLoad.
:return: `ServerStatus`
"""
server_status = ServerStatus(
self.pyload.thread_manager.pause,
len(self.pyload.thread_manager.processing_ids()),
self.pyload.files.get_queue_count(),
self.pyload.files.get_file_count(),
0,
not self.pyload.thread_manager.pause and self.is_time_download(),
self.pyload.config.get("reconnect", "enabled") and self.is_time_reconnect(),
self.is_captcha_waiting(),
)
for pyfile in [
x.active
for x in self.pyload.thread_manager.threads
if x.active and isinstance(x.active, PyFile)
]:
server_status.speed += pyfile.get_speed() #: bytes/s
return server_status
@legacy("freeSpace")
@permission(Perms.STATUS)
def free_space(self):
"""
Available free space at download directory in bytes.
"""
return fs.free_space(self.pyload.config.get("general", "storage_folder"))
@legacy("getServerVersion")
@permission(Perms.ANY)
def get_server_version(self):
"""
pyLoad Core version.
"""
return self.pyload.version
def kill(self):
"""
Clean way to quit pyLoad.
"""
self.pyload._do_exit = True
def restart(self):
"""
Restart pyload core.
"""
self.pyload._do_restart = True
@legacy("getLog")
@permission(Perms.LOGS)
def get_log(self, offset=0):
"""
Returns most recent log entries.
:param offset: line offset
:return: List of log entries
"""
filelog_folder = self.pyload.config.get("log", "filelog_folder")
if not filelog_folder:
filelog_folder = os.path.join(self.pyload.userdir, "logs")
path = os.path.join(filelog_folder, "pyload" + LogFactory.FILE_EXTENSION)
try:
with open(path) as fh:
lines = fh.readlines()
if offset >= len(lines):
return []
return lines[offset:]
except Exception:
return ["No log available"]
@legacy("isTimeDownload")
@permission(Perms.STATUS)
def is_time_download(self):
"""
Checks if pyload will start new downloads according to time in config.
:return: bool
"""
start = self.pyload.config.get("download", "start_time").split(":")
end = self.pyload.config.get("download", "end_time").split(":")
return seconds.compare(start, end)
@legacy("isTimeReconnect")
@permission(Perms.STATUS)
def is_time_reconnect(self):
"""
Checks if pyload will try to make a reconnect.
:return: bool
"""
start = self.pyload.config.get("reconnect", "start_time").split(":")
end = self.pyload.config.get("reconnect", "end_time").split(":")
return seconds.compare(start, end) and self.pyload.config.get(
"reconnect", "enabled"
)
@legacy("statusDownloads")
@permission(Perms.LIST)
def status_downloads(self):
"""
Status off all currently running downloads.
:return: list of `DownloadStatus`
"""
data = []
for pyfile in self.pyload.thread_manager.get_active_files():
if not isinstance(pyfile, PyFile):
continue
data.append(
DownloadInfo(
pyfile.id,
pyfile.name,
pyfile.get_speed(),
pyfile.get_eta(),
pyfile.format_eta(),
pyfile.get_bytes_left(),
pyfile.get_size(),
pyfile.format_size(),
pyfile.get_percent(),
pyfile.status,
pyfile.get_status_name(),
pyfile.format_wait(),
pyfile.wait_until,
pyfile.packageid,
pyfile.package().name,
pyfile.pluginname,
)
)
return data
@legacy("addPackage")
@permission(Perms.ADD)
def add_package(self, name, links, dest=Destination.QUEUE):
"""
Adds a package, with links to desired destination.
:param name: name of the new package
:param links: list of urls
:param dest: `Destination`
:return: package id of the new package
"""
if self.pyload.config.get("general", "folder_per_package"):
folder = name
else:
folder = ""
folder = (
folder.replace("http://", "")
.replace("https://", "")
.replace(":", "")
.replace("/", "_")
.replace("\\", "_")
)
package_id = self.pyload.files.add_package(name, folder, Destination(dest))
self.pyload.files.add_links(links, package_id)
self.pyload.log.info(
self._("Added package {name} containing {count:d} links").format(
name=name, count=len(links)
)
)
self.pyload.files.save()
return package_id
@legacy("parseURLs")
@permission(Perms.ADD)
def parse_urls(self, html=None, url=None):
"""
Parses html content or any arbitaty text for links and returns result of
`check_urls`
:param html: html source
:return:
"""
urls = []
if html:
urls += urlmatcher.findall(html)
if url:
page = get_url(url)
urls += urlmatcher.findall(page)
# remove duplicates
return self.check_urls(set(urls))
@legacy("checkURLs")
@permission(Perms.ADD)
def check_urls(self, urls):
"""
Gets urls and returns pluginname mapped to list of matches urls.
:param urls:
:return: {plugin: urls}
"""
data = self.pyload.plugin_manager.parse_urls(urls)
plugins = {}
for url, plugin in data:
if plugin in plugins:
plugins[plugin].append(url)
else:
plugins[plugin] = [url]
return plugins
@legacy("checkOnlineStatus")
@permission(Perms.ADD)
def check_online_status(self, urls):
"""
initiates online status check.
:param urls:
:return: initial set of data as `OnlineCheck` instance containing the result id
"""
data = self.pyload.plugin_manager.parse_urls(urls)
rid = self.pyload.thread_manager.create_result_thread(data, False)
tmp = [
(url, (url, OnlineStatus(url, pluginname, "unknown", 3, 0)))
for url, pluginname in data
]
data = parse_names(tmp)
result = {}
for k, v in data.items():
for url, status in v:
status.packagename = k
result[url] = status
return OnlineCheck(rid, result)
@legacy("checkOnlineStatusContainer")
@permission(Perms.ADD)
def check_online_status_container(self, urls, container, data):
"""
checks online status of urls and a submited container file.
:param urls: list of urls
:param container: container file name
:param data: file content
:return: online check
"""
with open(
os.path.join(
self.pyload.config.get("general", "storage_folder"), "tmp_" + container
),
"wb",
) as th:
th.write(data)
return self.check_online_status(urls + [th.name])
@legacy("pollResults")
@permission(Perms.ADD)
def poll_results(self, rid):
"""
Polls the result available for ResultID.
:param rid: `ResultID`
:return: `OnlineCheck`, if rid is -1 then no more data available
"""
result = self.pyload.thread_manager.get_info_result(rid)
if "ALL_INFO_FETCHED" in result:
del result["ALL_INFO_FETCHED"]
return OnlineCheck(-1, result)
else:
return OnlineCheck(rid, result)
@legacy("generatePackages")
@permission(Perms.ADD)
def generate_packages(self, links):
"""
Parses links, generates packages names from urls.
:param links: list of urls
:return: package names mapped to urls
"""
result = parse_names((x, x) for x in links)
return result
@legacy("generateAndAddPackages")
@permission(Perms.ADD)
def generate_and_add_packages(self, links, dest=Destination.COLLECTOR):
"""
Generates and add packages.
:param links: list of urls
:param dest: `Destination`
:return: list of package ids
"""
return [
self.add_package(name, urls, dest)
for name, urls in self.generate_packages(links).items()
]
@legacy("checkAndAddPackages")
@permission(Perms.ADD)
def check_and_add_packages(self, links, dest=Destination.COLLECTOR):
"""
Checks online status, retrieves names, and will add packages.
Because of this packages are not added immediatly, only for internal use.
:param links: list of urls
:param dest: `Destination`
:return: None
"""
data = self.pyload.plugin_manager.parse_urls(links)
self.pyload.thread_manager.create_result_thread(data, True)
@legacy("getPackageData")
@permission(Perms.LIST)
def get_package_data(self, package_id):
"""
Returns complete information about package, and included files.
:param package_id: package id
:return: `PackageData` with .links attribute
"""
data = self.pyload.files.get_package_data(int(package_id))
if not data:
raise PackageDoesNotExists(package_id)
pdata = PackageData(
data["id"],
data["name"],
data["folder"],
data["site"],
data["password"],
data["queue"],
data["order"],
links=[self._convert_py_file(x) for x in data["links"].values()],
)
return pdata
@legacy("getPackageInfo")
@permission(Perms.LIST)
def get_package_info(self, package_id):
"""
Returns information about package, without detailed information about containing
files.
:param package_id: package id
:return: `PackageData` with .fid attribute
"""
data = self.pyload.files.get_package_data(int(package_id))
if not data:
raise PackageDoesNotExists(package_id)
pdata = PackageData(
data["id"],
data["name"],
data["folder"],
data["site"],
data["password"],
data["queue"],
data["order"],
fids=[int(x) for x in data["links"]],
)
return pdata
@legacy("getFileData")
@permission(Perms.LIST)
def get_file_data(self, file_id):
"""
Get complete information about a specific file.
:param file_id: file id
:return: `FileData`
"""
info = self.pyload.files.get_file_data(int(file_id))
if not info:
raise FileDoesNotExists(file_id)
fileinfo = list(info.values())[0]
fdata = self._convert_py_file(fileinfo)
return fdata
@legacy("deleteFiles")
@permission(Perms.DELETE)
def delete_files(self, file_ids):
"""
Deletes several file entries from pyload.
:param file_ids: list of file ids
"""
for id in file_ids:
self.pyload.files.delete_link(int(id))
self.pyload.files.save()
@legacy("deletePackages")
@permission(Perms.DELETE)
def delete_packages(self, package_ids):
"""
Deletes packages and containing links.
:param package_ids: list of package ids
"""
for id in package_ids:
self.pyload.files.delete_package(int(id))
self.pyload.files.save()
@legacy("getQueue")
@permission(Perms.LIST)
def get_queue(self):
"""
Returns info about queue and packages, **not** about files, see `get_queue_data` \
or `get_package_data` instead.
:return: list of `PackageInfo`
"""
return [
PackageData(
pack["id"],
pack["name"],
pack["folder"],
pack["site"],
pack["password"],
pack["queue"],
pack["order"],
pack["linksdone"],
pack["sizedone"],
pack["sizetotal"],
pack["linkstotal"],
)
for pack in self.pyload.files.get_info_data(Destination.QUEUE).values()
]
@legacy("getQueueData")
@permission(Perms.LIST)
def get_queue_data(self):
"""
Return complete data about everything in queue, this is very expensive use it
sparely.
See `get_queue` for alternative.
:return: list of `PackageData`
"""
return [
PackageData(
pack["id"],
pack["name"],
pack["folder"],
pack["site"],
pack["password"],
pack["queue"],
pack["order"],
pack["linksdone"],
pack["sizedone"],
pack["sizetotal"],
links=[self._convert_py_file(x) for x in pack["links"].values()],
)
for pack in self.pyload.files.get_complete_data(Destination.QUEUE).values()
]
@legacy("getCollector")
@permission(Perms.LIST)
def get_collector(self):
"""
same as `get_queue` for collector.
:return: list of `PackageInfo`
"""
return [
PackageData(
pack["id"],
pack["name"],
pack["folder"],
pack["site"],
pack["password"],
pack["queue"],
pack["order"],
pack["linksdone"],
pack["sizedone"],
pack["sizetotal"],
pack["linkstotal"],
)
for pack in self.pyload.files.get_info_data(Destination.COLLECTOR).values()
]
@legacy("getCollectorData")
@permission(Perms.LIST)
def get_collector_data(self):
"""
same as `get_queue_data` for collector.
:return: list of `PackageInfo`
"""
return [
PackageData(
pack["id"],
pack["name"],
pack["folder"],
pack["site"],
pack["password"],
pack["queue"],
pack["order"],
pack["linksdone"],
pack["sizedone"],
pack["sizetotal"],
links=[self._convert_py_file(x) for x in pack["links"].values()],
)
for pack in self.pyload.files.get_complete_data(
Destination.COLLECTOR
).values()
]
@legacy("addFiles")
@permission(Perms.ADD)
def add_files(self, package_id, links):
"""
Adds files to specific package.
:param package_id: package id
:param links: list of urls
"""
self.pyload.files.add_links(links, int(package_id))
self.pyload.log.info(
self._("Added {count:d} links to package #{package:d} ").format(
count=len(links), package=package_id
)
)
self.pyload.files.save()
@legacy("pushToQueue")
@permission(Perms.MODIFY)
def push_to_queue(self, package_id):
"""
Moves package from Collector to Queue.
:param package_id: package id
"""
self.pyload.files.set_package_location(package_id, Destination.QUEUE)
@legacy("pullFromQueue")
@permission(Perms.MODIFY)
def pull_from_queue(self, package_id):
"""
Moves package from Queue to Collector.
:param package_id: package id
"""
self.pyload.files.set_package_location(package_id, Destination.COLLECTOR)
@legacy("restartPackage")
@permission(Perms.MODIFY)
def restart_package(self, package_id):
"""
Restarts a package, resets every containing files.
:param package_id: package id
"""
self.pyload.files.restart_package(int(package_id))
@legacy("restartFile")
@permission(Perms.MODIFY)
def restart_file(self, file_id):
"""
Resets file status, so it will be downloaded again.
:param file_id: file id
"""
self.pyload.files.restart_file(int(file_id))
@legacy("recheckPackage")
@permission(Perms.MODIFY)
def recheck_package(self, package_id):
"""
Probes online status of all files in a package, also a default action when
package is added.
:param package_id:
:return:
"""
self.pyload.files.recheck_package(int(package_id))
@legacy("stopAllDownloads")
@permission(Perms.MODIFY)
def stop_all_downloads(self):
"""
Aborts all running downloads.
"""
pyfiles = list(self.pyload.files.cache.values())
for pyfile in pyfiles:
pyfile.abort_download()
@legacy("stopDownloads")
@permission(Perms.MODIFY)
def stop_downloads(self, file_ids):
"""
Aborts specific downloads.
:param file_ids: list of file ids
:return:
"""
pyfiles = list(self.pyload.files.cache.values())
for pyfile in pyfiles:
if pyfile.id in file_ids:
pyfile.abort_download()
@legacy("setPackageName")
@permission(Perms.MODIFY)
def set_package_name(self, package_id, name):
"""
Renames a package.
:param package_id: package id
:param name: new package name
"""
pack = self.pyload.files.get_package(package_id)
pack.name = name
pack.sync()
@legacy("movePackage")
@permission(Perms.MODIFY)
def move_package(self, destination, package_id):
"""
Set a new package location.
:param destination: `Destination`
:param package_id: package id
"""
try:
dest = Destination(destination)
except ValueError:
pass
else:
self.pyload.files.set_package_location(package_id, dest)
@legacy("moveFiles")
@permission(Perms.MODIFY)
def move_files(self, file_ids, package_id):
"""
Move multiple files to another package.
:param file_ids: list of file ids
:param package_id: destination package
:return:
"""
# TODO: implement
pass
@legacy("uploadContainer")
@permission(Perms.ADD)
def upload_container(self, filename, data):
"""
Uploads and adds a container file to pyLoad.
:param filename: filename, extension is important so it can correctly decrypted
:param data: file content
"""
with open(
os.path.join(
self.pyload.config.get("general", "storage_folder"), "tmp_" + filename
),
"wb",
) as th:
th.write(data)
self.add_package(th.name, [th.name], Destination.COLLECTOR)
@legacy("orderPackage")
@permission(Perms.MODIFY)
def order_package(self, package_id, position):
"""
Gives a package a new position.
:param package_id: package id
:param position:
"""
self.pyload.files.reorder_package(package_id, position)
@legacy("orderFile")
@permission(Perms.MODIFY)
def order_file(self, file_id, position):
"""
Gives a new position to a file within its package.
:param file_id: file id
:param position:
"""
self.pyload.files.reorder_file(file_id, position)
@legacy("setPackageData")
@permission(Perms.MODIFY)
def set_package_data(self, package_id, data):
"""
Allows to modify several package attributes.
:param package_id: package id
:param data: dict that maps attribute to desired value
"""
p = self.pyload.files.get_package(package_id)
if not p:
raise PackageDoesNotExists(package_id)
for key, value in data.items():
if key == "id":
continue
setattr(p, key, value)
p.sync()