This repository has been archived by the owner on Jun 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
common.py
1273 lines (991 loc) · 36.7 KB
/
common.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 -*-
#
# Copyright (C) 2007,2008 Andrew Resch <andrewresch@gmail.com>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#
"""Common functions for various parts of Deluge to use."""
from __future__ import division, print_function, unicode_literals
import base64
import datetime
import functools
import glob
import locale
import logging
import numbers
import os
import platform
import re
import subprocess
import sys
import tarfile
import time
import chardet
import pkg_resources
from deluge.decorators import deprecated
from deluge.error import InvalidPathError
try:
from urllib.parse import unquote_plus, urljoin
from urllib.request import pathname2url
except ImportError:
# PY2 fallback
from urlparse import urljoin # pylint: disable=ungrouped-imports
from urllib import pathname2url, unquote_plus # pylint: disable=ungrouped-imports
DBUS_FILEMAN = None
# gi makes dbus available on Window but don't import it as unused.
if platform.system() not in ('Windows', 'Microsoft', 'Darwin'):
try:
import dbus
except ImportError:
pass
else:
try:
bus = dbus.SessionBus()
DBUS_FILEMAN = bus.get_object('org.freedesktop.FileManager1', '/org/freedesktop/FileManager1')
except dbus.DBusException:
pass
log = logging.getLogger(__name__)
TORRENT_STATE = [
'Allocating',
'Checking',
'Downloading',
'Seeding',
'Paused',
'Error',
'Queued',
'Moving'
]
# The output formatting for json.dump
JSON_FORMAT = {'indent': 4, 'sort_keys': True, 'ensure_ascii': False}
PY2 = sys.version_info.major == 2
def get_version():
"""
Returns the program version from the egg metadata
:returns: the version of Deluge
:rtype: string
"""
return pkg_resources.require('Deluge')[0].version
def get_default_config_dir(filename=None):
"""
:param filename: if None, only the config path is returned, if provided,
a path including the filename will be returned
:type filename: string
:returns: a file path to the config directory and optional filename
:rtype: string
"""
if windows_check():
def save_config_path(resource):
app_data_path = os.environ.get('APPDATA')
if not app_data_path:
try:
import winreg
except ImportError:
import _winreg as winreg # For Python 2.
hkey = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders')
app_data_reg = winreg.QueryValueEx(hkey, 'AppData')
app_data_path = app_data_reg[0]
winreg.CloseKey(hkey)
return os.path.join(app_data_path, resource)
else:
from xdg.BaseDirectory import save_config_path
if not filename:
filename = ''
try:
return decode_bytes(os.path.join(save_config_path('deluge'), filename))
except OSError as ex:
log.error('Unable to use default config directory, exiting... (%s)', ex)
sys.exit(1)
def get_default_download_dir():
"""
:returns: the default download directory
:rtype: string
"""
download_dir = ''
if not windows_check():
from xdg.BaseDirectory import xdg_config_home
try:
with open(os.path.join(xdg_config_home, 'user-dirs.dirs'), 'r') as _file:
for line in _file:
if not line.startswith('#') and line.startswith('XDG_DOWNLOAD_DIR'):
download_dir = os.path.expandvars(line.partition('=')[2].rstrip().strip('"'))
break
except IOError:
pass
if not download_dir:
download_dir = os.path.join(os.path.expanduser('~'), 'Downloads')
return download_dir
def archive_files(arc_name, filepaths):
"""Compress a list of filepaths into timestamped tarball in config dir.
The archiving config directory is 'archive'.
Args:
arc_name (str): The archive output filename (appended with timestamp).
filepaths (list): A list of the files to be archived into tarball.
Returns:
str: The full archive filepath.
"""
from deluge.configmanager import get_config_dir
# Set archive compression to lzma with bz2 fallback.
arc_comp = 'xz' if not PY2 else 'bz2'
archive_dir = os.path.join(get_config_dir(), 'archive')
timestamp = datetime.datetime.now().replace(microsecond=0).isoformat().replace(':', '-')
arc_filepath = os.path.join(archive_dir, arc_name + '-' + timestamp + '.tar.' + arc_comp)
max_num_arcs = 20
if not os.path.exists(archive_dir):
os.makedirs(archive_dir)
else:
old_arcs = glob.glob(os.path.join(archive_dir, arc_name) + '*')
if len(old_arcs) > max_num_arcs:
# TODO: Remove oldest timestamped archives.
log.warning('More than %s tarballs in config archive', max_num_arcs)
try:
with tarfile.open(arc_filepath, 'w:' + arc_comp) as tf:
for filepath in filepaths:
tf.add(filepath, arcname=os.path.basename(filepath))
except OSError:
log.error('Problem occurred archiving filepaths: %s', filepaths)
return False
else:
return arc_filepath
def windows_check():
"""
Checks if the current platform is Windows
:returns: True or False
:rtype: bool
"""
return platform.system() in ('Windows', 'Microsoft')
def vista_check():
"""
Checks if the current platform is Windows Vista
:returns: True or False
:rtype: bool
"""
return platform.release() == 'Vista'
def osx_check():
"""
Checks if the current platform is Mac OS X
:returns: True or False
:rtype: bool
"""
return platform.system() == 'Darwin'
def linux_check():
"""
Checks if the current platform is Linux
:returns: True or False
:rtype: bool
"""
return platform.system() == 'Linux'
def get_os_version():
"""Parse and return the os version information.
Converts the platform ver tuple to a string.
Returns:
str: The os version info.
"""
if windows_check():
os_version = platform.win32_ver()
elif osx_check():
os_version = list(platform.mac_ver())
os_version[1] = '' # versioninfo always empty.
elif linux_check():
os_version = platform.linux_distribution()
else:
os_version = (platform.release(), )
return ' '.join(filter(None, os_version))
def get_pixmap(fname):
"""
Provides easy access to files in the deluge/ui/data/pixmaps folder within the Deluge egg
:param fname: the filename to look for
:type fname: string
:returns: a path to a pixmap file included with Deluge
:rtype: string
"""
return resource_filename('deluge', os.path.join('ui', 'data', 'pixmaps', fname))
def resource_filename(module, path):
"""While developing, if there's a second deluge package, installed globally
and another in develop mode somewhere else, while pkg_resources.require('Deluge')
returns the proper deluge instance, pkg_resources.resource_filename does
not, it returns the first found on the python path, which is not good
enough.
This is a work-around that.
"""
return pkg_resources.require('Deluge>=%s' % get_version())[0].get_resource_filename(
pkg_resources._manager, os.path.join(*(module.split('.') + [path]))
)
def open_file(path, timestamp=None):
"""Opens a file or folder using the system configured program.
Args:
path (str): The path to the file or folder to open.
timestamp (int, optional): An event request timestamp.
"""
if windows_check():
os.startfile(path)
elif osx_check():
subprocess.Popen(['open', path])
else:
if timestamp is None:
timestamp = int(time.time())
env = os.environ.copy()
env['DESKTOP_STARTUP_ID'] = '%s-%u-%s-xdg_open_TIME%d' % \
(os.path.basename(sys.argv[0]), os.getpid(), os.uname()[1], timestamp)
subprocess.Popen(['xdg-open', '%s' % path], env=env)
def show_file(path, timestamp=None):
"""Shows (highlights) a file or folder using the system configured file manager.
Args:
path (str): The path to the file or folder to show.
timestamp (int, optional): An event request timestamp.
"""
if windows_check():
subprocess.Popen(['explorer', '/select,', path])
elif osx_check():
subprocess.Popen(['open', '-R', path])
else:
if timestamp is None:
timestamp = int(time.time())
startup_id = '%s_%u_%s-dbus_TIME%d' % (os.path.basename(sys.argv[0]), os.getpid(), os.uname()[1], timestamp)
if DBUS_FILEMAN:
paths = [urljoin('file:', pathname2url(path))]
DBUS_FILEMAN.ShowItems(paths, startup_id, dbus_interface='org.freedesktop.FileManager1')
else:
env = os.environ.copy()
env['DESKTOP_STARTUP_ID'] = startup_id.replace('dbus', 'xdg-open')
# No option in xdg to highlight a file so just open parent folder.
subprocess.Popen(['xdg-open', os.path.dirname(path.rstrip('/'))], env=env)
def open_url_in_browser(url):
"""
Opens a url in the desktop's default browser
:param url: the url to open
:type url: string
"""
import webbrowser
webbrowser.open(url)
# Formatting text functions
byte_txt = 'B'
kib_txt = 'KiB'
mib_txt = 'MiB'
gib_txt = 'GiB'
tib_txt = 'TiB'
kib_txt_short = 'K'
mib_txt_short = 'M'
gib_txt_short = 'G'
tib_txt_short = 'T'
def translate_size_units():
"""For performance reasons these units are translated outside the function"""
global byte_txt, kib_txt, mib_txt, gib_txt, tib_txt
global kib_txt_short, mib_txt_short, gib_txt_short, tib_txt_short
byte_txt = _('B')
kib_txt = _('KiB')
mib_txt = _('MiB')
gib_txt = _('GiB')
tib_txt = _('TiB')
kib_txt_short = _('K')
mib_txt_short = _('M')
gib_txt_short = _('G')
tib_txt_short = _('T')
def fsize(fsize_b, precision=1, shortform=False):
"""Formats the bytes value into a string with KiB, MiB or GiB units.
Args:
fsize_b (int): The filesize in bytes.
precision (int): The filesize float precision.
Returns:
str: A formatted string in KiB, MiB or GiB units.
Examples:
>>> fsize(112245)
'109.6 KiB'
>>> fsize(112245, precision=0)
'110 KiB'
Note:
This function has been refactored for perfomance with the
fsize units being translated outside the function.
"""
if fsize_b >= 1024 ** 4:
return '%.*f %s' % (precision, fsize_b / 1024 ** 4, tib_txt_short if shortform else tib_txt)
elif fsize_b >= 1024 ** 3:
return '%.*f %s' % (precision, fsize_b / 1024 ** 3, gib_txt_short if shortform else gib_txt)
elif fsize_b >= 1024 ** 2:
return '%.*f %s' % (precision, fsize_b / 1024 ** 2, mib_txt_short if shortform else mib_txt)
elif fsize_b >= 1024:
return '%.*f %s' % (precision, fsize_b / 1024, kib_txt_short if shortform else kib_txt)
else:
return '%d %s' % (fsize_b, byte_txt)
def fpcnt(dec, precision=2):
"""Formats a string to display a percentage with <precision> places.
Args:
dec (float): The ratio in the range [0.0, 1.0].
precision (int): The percentage float precision.
Returns:
str: A formatted string representing a percentage.
Examples:
>>> fpcnt(0.9311)
'93.11%'
>>> fpcnt(0.9311, precision=0)
'93%'
"""
pcnt = (dec * 100)
if pcnt == 0 or pcnt == 100:
precision = 0
return '%.*f%%' % (precision, pcnt)
def fspeed(bps, precision=1, shortform=False):
"""Formats a string to display a transfer speed.
Args:
bps (int): The speed in bytes per second.
Returns:
str: A formatted string representing transfer speed.
Examples:
>>> fspeed(43134)
'42.1 KiB/s'
"""
if bps < 1024 ** 2:
return '%.*f %s' % (precision, bps / 1024, _('K/s') if shortform else _('KiB/s'))
elif bps < 1024 ** 3:
return '%.*f %s' % (precision, bps / 1024 ** 2, _('M/s') if shortform else _('MiB/s'))
elif bps < 1024 ** 4:
return '%.*f %s' % (precision, bps / 1024 ** 3, _('G/s') if shortform else _('GiB/s'))
else:
return '%.*f %s' % (precision, bps / 1024 ** 4, _('T/s') if shortform else _('TiB/s'))
def fpeer(num_peers, total_peers):
"""Formats a string to show 'num_peers' ('total_peers').
Args:
num_peers (int): The number of connected peers.
total_peers (int): The total number of peers.
Returns:
str: A formatted string 'num_peers (total_peers)' or total_peers < 0, just 'num_peers'.
Examples:
>>> fpeer(10, 20)
'10 (20)'
>>> fpeer(10, -1)
'10'
"""
if total_peers > -1:
return '{:d} ({:d})'.format(num_peers, total_peers)
else:
return '{:d}'.format(num_peers)
def ftime(secs):
"""Formats a string to show time in a human readable form.
Args:
secs (int): The number of seconds.
Returns:
str: A formatted time string or empty string if value is 0.
Examples:
>>> ftime(23011)
'6h 23m'
Note:
This function has been refactored for perfomance.
"""
if secs <= 0:
time_str = ''
elif secs < 60:
time_str = '{:d}s'.format(secs)
elif secs < 3600:
time_str = '{:d}m {:d}s'.format(secs // 60, secs % 60)
elif secs < 86400:
time_str = '{:d}h {:d}m'.format(secs // 3600, secs // 60 % 60)
elif secs < 604800:
time_str = '{:d}d {:d}h'.format(secs // 86400, secs // 3600 % 24)
elif secs < 31449600:
time_str = '{:d}w {:d}d'.format(secs // 604800, secs // 86400 % 7)
else:
time_str = '{:d}y {:d}w'.format(secs // 31449600, secs // 604800 % 52)
return time_str
def fdate(seconds, date_only=False, precision_secs=False):
"""Formats a date time string in the locale's date representation based on the systems timezone.
Args:
seconds (float): Time in seconds since the Epoch.
precision_secs (bool): Include seconds in time format.
Returns:
str: A string in the locale's datetime representation or "" if seconds < 0
"""
if seconds < 0:
return ''
time_format = '%x %X' if precision_secs else '%x %H:%M'
if date_only:
time_format = time_format.split()[0]
return time.strftime(time_format, time.localtime(seconds))
def tokenize(text):
"""
Tokenize a text into numbers and strings.
Args:
text (str): The text to tokenize (a string).
Returns:
list: A list of strings and/or numbers.
This function is used to implement robust tokenization of user input
It automatically coerces integer and floating point numbers, ignores
whitespace and knows how to separate numbers from strings even without
whitespace.
"""
tokenized_input = []
for token in re.split(r'(\d+(?:\.\d+)?)', text):
token = token.strip()
if re.match(r'\d+\.\d+', token):
tokenized_input.append(float(token))
elif token.isdigit():
tokenized_input.append(int(token))
elif token:
tokenized_input.append(token)
return tokenized_input
size_units = (dict(prefix='b', divider=1, singular='byte', plural='bytes'),
dict(prefix='KiB', divider=1024**1),
dict(prefix='MiB', divider=1024**2),
dict(prefix='GiB', divider=1024**3),
dict(prefix='TiB', divider=1024**4),
dict(prefix='PiB', divider=1024**5),
dict(prefix='KB', divider=1000**1),
dict(prefix='MB', divider=1000**2),
dict(prefix='GB', divider=1000**3),
dict(prefix='TB', divider=1000**4),
dict(prefix='PB', divider=1000**5),
dict(prefix='m', divider=1000**2))
class InvalidSize(Exception):
pass
def parse_human_size(size):
"""
Parse a human readable data size and return the number of bytes.
Args:
size (str): The human readable file size to parse (a string).
Returns:
int: The corresponding size in bytes.
Raises:
InvalidSize: when the input can't be parsed.
"""
tokens = tokenize(size)
if tokens and isinstance(tokens[0], numbers.Number):
# If the input contains only a number, it's assumed to be the number of bytes.
if len(tokens) == 1:
return int(tokens[0])
# Otherwise we expect to find two tokens: A number and a unit.
if len(tokens) == 2:
try:
normalized_unit = tokens[1].lower()
except AttributeError:
pass
else:
# Try to match the first letter of the unit.
for unit in size_units:
if normalized_unit.startswith(unit['prefix'].lower()):
return int(tokens[0] * unit['divider'])
# We failed to parse the size specification.
msg = 'Failed to parse size! (input %r was tokenized as %r)'
raise InvalidSize(msg % (size, tokens))
def is_url(url):
"""
A simple test to check if the URL is valid
:param url: the url to test
:type url: string
:returns: True or False
:rtype: bool
:Example:
>>> is_url('http://deluge-torrent.org')
True
"""
return url.partition('://')[0] in ('http', 'https', 'ftp', 'udp')
def is_infohash(infohash):
"""
A check to determine if a string is a valid infohash.
Args:
infohash (str): The string to check.
Returns:
bool: True if valid infohash, False otherwise.
"""
return len(infohash) == 40 and infohash.isalnum()
MAGNET_SCHEME = 'magnet:?'
XT_BTIH_PARAM = 'xt=urn:btih:'
DN_PARAM = 'dn='
TR_PARAM = 'tr='
def is_magnet(uri):
"""
A check to determine if a uri is a valid bittorrent magnet uri
:param uri: the uri to check
:type uri: string
:returns: True or False
:rtype: bool
:Example:
>>> is_magnet('magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN')
True
"""
if uri.startswith(MAGNET_SCHEME) and XT_BTIH_PARAM in uri:
return True
return False
def get_magnet_info(uri):
"""Parse torrent information from magnet link.
Args:
uri (str): The magnet link.
Returns:
dict: Information about the magnet link.
Format of the magnet dict::
{
"name": the torrent name,
"info_hash": the torrents info_hash,
"files_tree": empty value for magnet links
}
"""
tr0_param = 'tr.'
tr0_param_regex = re.compile('^tr.(\d+)=(\S+)')
if not uri.startswith(MAGNET_SCHEME):
return {}
name = None
info_hash = None
trackers = {}
tier = 0
for param in uri[len(MAGNET_SCHEME):].split('&'):
if param.startswith(XT_BTIH_PARAM):
xt_hash = param[len(XT_BTIH_PARAM):]
if len(xt_hash) == 32:
try:
info_hash = base64.b32decode(xt_hash.upper()).encode('hex')
except TypeError as ex:
log.debug('Invalid base32 magnet hash: %s, %s', xt_hash, ex)
break
elif is_infohash(xt_hash):
info_hash = xt_hash.lower()
else:
break
elif param.startswith(DN_PARAM):
name = unquote_plus(param[len(DN_PARAM):])
elif param.startswith(TR_PARAM):
tracker = unquote_plus(param[len(TR_PARAM):])
trackers[tracker] = tier
tier += 1
elif param.startswith(tr0_param):
try:
tier, tracker = re.match(tr0_param_regex, param).groups()
trackers[tracker] = tier
except AttributeError:
pass
if info_hash:
if not name:
name = info_hash
return {'name': name, 'info_hash': info_hash, 'files_tree': '', 'trackers': trackers}
else:
return {}
def create_magnet_uri(infohash, name=None, trackers=None):
"""Creates a magnet uri
Args:
infohash (str): The info-hash of the torrent.
name (str, optional): The name of the torrent.
trackers (list or dict, optional): A list of trackers or dict or {tracker: tier} pairs.
Returns:
str: A magnet uri string.
"""
try:
infohash = infohash.decode('hex')
except AttributeError:
pass
uri = [MAGNET_SCHEME, XT_BTIH_PARAM, base64.b32encode(infohash)]
if name:
uri.extend(['&', DN_PARAM, name])
if trackers:
try:
for tracker in sorted(trackers, key=trackers.__getitem__):
uri.extend(['&', 'tr.%d=' % trackers[tracker], tracker])
except TypeError:
for tracker in trackers:
uri.extend(['&', TR_PARAM, tracker])
return ''.join(uri)
def get_path_size(path):
"""
Gets the size in bytes of 'path'
:param path: the path to check for size
:type path: string
:returns: the size in bytes of the path or -1 if the path does not exist
:rtype: int
"""
if not os.path.exists(path):
return -1
if os.path.isfile(path):
return os.path.getsize(path)
dir_size = 0
for (p, dummy_dirs, files) in os.walk(path):
for _file in files:
filename = os.path.join(p, _file)
dir_size += os.path.getsize(filename)
return dir_size
def free_space(path):
"""
Gets the free space available at 'path'
:param path: the path to check
:type path: string
:returns: the free space at path in bytes
:rtype: int
:raises InvalidPathError: if the path is not valid
"""
if not path or not os.path.exists(path):
raise InvalidPathError('%s is not a valid path' % path)
if windows_check():
from win32file import GetDiskFreeSpaceEx
return GetDiskFreeSpaceEx(path)[0]
else:
disk_data = os.statvfs(path.encode('utf8'))
block_size = disk_data.f_frsize
return disk_data.f_bavail * block_size
def is_ip(ip):
"""A test to see if 'ip' is a valid IPv4 or IPv6 address.
Args:
ip (str): The IP to test.
Returns:
bool: Whether IP is valid is not.
Examples:
>>> is_ip("192.0.2.0")
True
>>> is_ip("2001:db8::")
True
"""
return is_ipv4(ip) or is_ipv6(ip)
def is_ipv4(ip):
"""A test to see if 'ip' is a valid IPv4 address.
Args:
ip (str): The IP to test.
Returns:
bool: Whether IP is valid is not.
Examples:
>>> is_ipv4("192.0.2.0")
True
"""
import socket
try:
if windows_check():
return socket.inet_aton(ip)
else:
return socket.inet_pton(socket.AF_INET, ip)
except socket.error:
return False
def is_ipv6(ip):
"""A test to see if 'ip' is a valid IPv6 address.
Args:
ip (str): The IP to test.
Returns:
bool: Whether IP is valid is not.
Examples:
>>> is_ipv6("2001:db8::")
True
"""
try:
import ipaddress
except ImportError:
import socket
try:
return socket.inet_pton(socket.AF_INET6, ip)
except (socket.error, AttributeError):
if windows_check():
log.warning('Unable to verify IPv6 Address on Windows.')
return True
else:
try:
return ipaddress.IPv6Address(decode_bytes(ip))
except ipaddress.AddressValueError:
pass
return False
def decode_bytes(byte_str, encoding='utf8'):
"""Decodes a byte string and return unicode.
If it cannot decode using `encoding` then it will try latin1,
and if that fails, try to detect the string encoding. If that fails,
decode with ignore.
Args:
byte_str (bytes): The byte string to decode.
encoding (str): The encoding to try first when decoding.
Returns:
str: A unicode string.
"""
if not byte_str:
return ''
elif not isinstance(byte_str, bytes):
return byte_str
encodings = [lambda: ('utf8', 'strict'),
lambda: ('iso-8859-1', 'strict'),
lambda: (chardet.detect(byte_str)['encoding'], 'strict'),
lambda: (encoding, 'ignore')]
if encoding is not 'utf8':
encodings.insert(0, lambda: (encoding, 'strict'))
for l in encodings:
try:
return byte_str.decode(*l())
except UnicodeDecodeError:
pass
return ''
@deprecated
def decode_string(byte_str, encoding='utf8'):
"""Deprecated: Use decode_bytes"""
decode_bytes(byte_str, encoding)
@deprecated
def utf8_encoded(str_, encoding='utf8'):
"""Deprecated: Use encode or decode_bytes if needed"""
decode_bytes(str_, encoding).encode('utf8')
def utf8_encode_structure(data):
"""Recursively convert all unicode keys and values in a data structure to utf8.
e.g. converting keys and values for a dict with nested dicts and lists etc.
Args:
data (any): This can be any structure, dict, list or tuple.
Returns:
input type: The data with unicode keys and values converted to utf8.
"""
if isinstance(data, (list, tuple)):
return type(data)([utf8_encode_structure(d) for d in data])
elif isinstance(data, dict):
return dict([utf8_encode_structure(d) for d in data.items()])
elif not isinstance(data, bytes):
try:
return data.encode('utf8')
except AttributeError:
pass
return data
@functools.total_ordering
class VersionSplit(object):
"""
Used for comparing version numbers.
:param ver: the version
:type ver: string
"""
def __init__(self, ver):
version_re = re.compile(r"""
^
(?P<version>\d+\.\d+) # minimum 'N.N'
(?P<extraversion>(?:\.\d+)*) # any number of extra '.N' segments
(?:
(?P<prerel>[abc]|rc) # 'a'=alpha, 'b'=beta, 'c'=release candidate
# 'rc'= alias for release candidate
(?P<prerelversion>\d+(?:\.\d+)*)
)?
(?P<postdev>(\.post(?P<post>\d+))?(\.dev(?P<dev>\d+))?)?
$""", re.VERBOSE)
# Check for PEP 386 compliant version
match = re.search(version_re, ver)
if match:
group = [(x if x is not None else '') for x in match.group(1, 2, 3, 4, 8)]
vs = [''.join(group[0:2]), ''.join(group[2:4]), group[4].lstrip('.')]
else:
ver = ver.lower()
vs = ver.replace('_', '-').split('-')
self.version = [int(x) for x in vs[0].split('.') if x.isdigit()]
self.version_string = ''.join(str(x) for x in vs[0].split('.') if x.isdigit())
self.suffix = None
self.dev = False
if len(vs) > 1:
if vs[1].startswith(('rc', 'a', 'b', 'c')):
self.suffix = vs[1]
if vs[-1].startswith('dev'):
self.dev = vs[-1]