Completed
Push — master ( 2ee2b1...5f87df )
by John
10:21 queued 09:39
created

SpinManager   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 89.29%

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 44
ccs 25
cts 28
cp 0.8929
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 7 1
A loop() 0 12 3
A stop() 0 10 2
A start() 0 7 1
1
#!/usr/bin/env python3
2 3
"""This module is used for miscellaneous utilities."""
3
4 5
import os  # path work
5 5
import argparse  # argument parser for filters
6 5
import platform  # platform info
7 5
import glob  # cap grabbing
8 5
import hashlib  # base url creation
9 5
import threading  # get thread for spinner
10 5
import time  # spinner delay
11 5
import sys  # streams, version info
12 5
import itertools  # spinners gonna spin
13 5
import subprocess  # loader verification
14 5
from bbarchivist import bbconstants  # cap location, version, filename bits
15 5
from bbarchivist import compat  # backwards compat
16 5
from bbarchivist import dummy  # useless stdout
17 5
from bbarchivist import exceptions  # exceptions
18 5
from bbarchivist import iniconfig  # config parsing
19
20 5
__author__ = "Thurask"
21 5
__license__ = "WTFPL v2"
22 5
__copyright__ = "2015-2017 Thurask"
23
24
25 5
def grab_datafile(datafile):
26
    """
27
    Figure out where a datafile is.
28
29
    :param datafile: Datafile to check.
30
    :type datafile: bbconstants.Datafile
31
    """
32 5
    try:
33 5
        afile = glob.glob(os.path.join(os.getcwd(), datafile.filename))[0]
34 5
    except IndexError:
35 5
        afile = datafile.location if datafile.name == "cfp" else grab_capini(datafile)
36 5
    return os.path.abspath(afile)
37
38
39 5
def grab_capini(datafile):
40
    """
41
    Get cap location from .ini file, and write if it's new.
42
43
    :param datafile: Datafile to check.
44
    :type datafile: bbconstants.Datafile
45
    """
46
    try:
47
        apath = cappath_config_loader()
48
        afile = glob.glob(apath)[0]
49
    except IndexError:
50
        cappath_config_writer(datafile.location)
51
        return bbconstants.CAP.location  # no ini cap
52
    else:
53
        cappath_config_writer(os.path.abspath(afile))
54
        return os.path.abspath(afile)  # ini cap:
55
56
57 5
def grab_cap():
58
    """
59
    Figure out where cap is, local, specified or system-supplied.
60
    """
61 5
    return grab_datafile(bbconstants.CAP)
62
63
64 5
def grab_cfp():
65
    """
66
    Figure out where cfp is, local or system-supplied.
67
    """
68 5
    return grab_datafile(bbconstants.CFP)
69
70
71 5
def new_enough(minver):
72
    """
73
    Check if we're at or above a minimum Python version.
74
75
    :param minver: Minimum Python version (3.minver).
76
    :type minver: int
77
    """
78 5
    return False if minver > sys.version_info[1] else True
79
80
81 5
def dirhandler(directory, defaultdir):
82
    """
83
    If directory is None, turn it into defaultdir.
84
85
    :param directory: Target directory.
86
    :type directory: str
87
88
    :param defaultdir: Default directory.
89
    :type defaultdir: str
90
    """
91 5
    directory = defaultdir if directory is None else directory
92 5
    return directory
93
94
95 5
def fsizer(file_size):
96
    """
97
    Raw byte file size to human-readable string.
98
99
    :param file_size: Number to parse.
100
    :type file_size: float
101
    """
102 5
    fsize = prep_filesize(file_size)
103 5
    for sfix in ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB']:
104 5
        if fsize < 1024.0:
105 5
            size = "{0:3.2f}{1}".format(fsize, sfix)
106 5
            break
107
        else:
108 5
            fsize /= 1024.0
109
    else:
110 5
        size = "{0:3.2f}{1}".format(fsize, 'YB')
111 5
    return size
112
113
114 5
def prep_filesize(file_size):
115
    """
116
    Convert file size to float.
117
118
    :param file_size: Number to parse.
119
    :type file_size: float
120
    """
121 5
    if file_size is None:
122 5
        file_size = 0.0
123 5
    fsize = float(file_size)
124 5
    return fsize
125
126
127 5
def signed_file_args(files):
128
    """
129
    Check if there are between 1 and 6 files supplied to argparse.
130
131
    :param files: List of signed files, between 1 and 6 strings.
132
    :type files: list(str)
133
    """
134 5
    filelist = [file for file in files if file]
135 5
    if not 1 <= len(filelist) <= 6:
136 5
        raise argparse.ArgumentError(argument=None, message="Requires 1-6 signed files")
137 5
    return files
138
139
140 5
def file_exists(file):
141
    """
142
    Check if file exists, raise argparse error if it doesn't.
143
144
    :param file: Path to a file, including extension.
145
    :type file: str
146
    """
147 5
    if not os.path.exists(file):
148 5
        raise argparse.ArgumentError(argument=None, message="{0} not found.".format(file))
149 5
    return file
150
151
152 5
def positive_integer(input_int):
153
    """
154
    Check if number > 0, raise argparse error if it isn't.
155
156
    :param input_int: Integer to check.
157
    :type input_int: str
158
    """
159 5
    if int(input_int) <= 0:
160 5
        info = "{0} is not >=0.".format(str(input_int))
161 5
        raise argparse.ArgumentError(argument=None, message=info)
162 5
    return int(input_int)
163
164
165 5
def valid_method(method):
166
    """
167
    Check if compression method is valid, raise argparse error if it isn't.
168
169
    :param method: Compression method to check.
170
    :type method: str
171
    """
172 5
    methodlist = bbconstants.METHODS
173 5
    if not new_enough(3):
174 5
        methodlist = [x for x in bbconstants.METHODS if x != "txz"]
175 5
    if method not in methodlist:
176 5
        info = "Invalid method {0}.".format(method)
177 5
        raise argparse.ArgumentError(argument=None, message=info)
178 5
    return method
179
180
181 5
def valid_carrier(mcc_mnc):
182
    """
183
    Check if MCC/MNC is valid (1-3 chars), raise argparse error if it isn't.
184
185
    :param mcc_mnc: MCC/MNC to check.
186
    :type mcc_mnc: str
187
    """
188 5
    if not str(mcc_mnc).isdecimal():
189 5
        infod = "Non-integer {0}.".format(str(mcc_mnc))
190 5
        raise argparse.ArgumentError(argument=None, message=infod)
191 5
    if len(str(mcc_mnc)) > 3 or len(str(mcc_mnc)) == 0:
192 5
        infol = "{0} is invalid.".format(str(mcc_mnc))
193 5
        raise argparse.ArgumentError(argument=None, message=infol)
194
    else:
195 5
        return mcc_mnc
196
197
198 5
def escreens_pin(pin):
199
    """
200
    Check if given PIN is valid, raise argparse error if it isn't.
201
202
    :param pin: PIN to check.
203
    :type pin: str
204
    """
205 5
    if len(pin) == 8:
206 5
        try:
207 5
            int(pin, 16)  # hexadecimal-ness
208 5
        except ValueError:
209 5
            raise argparse.ArgumentError(argument=None, message="Invalid PIN.")
210
        else:
211 5
            return pin.lower()
212
    else:
213 5
        raise argparse.ArgumentError(argument=None, message="Invalid PIN.")
214
215
216 5
def escreens_duration(duration):
217
    """
218
    Check if Engineering Screens duration is valid.
219
220
    :param duration: Duration to check.
221
    :type duration: int
222
    """
223 5
    if int(duration) in (1, 3, 6, 15, 30):
224 5
        return int(duration)
225
    else:
226 5
        raise argparse.ArgumentError(argument=None, message="Invalid duration.")
227
228
229 5
def droidlookup_hashtype(method):
230
    """
231
    Check if Android autoloader lookup hash type is valid.
232
233
    :param method: None for regular OS links, "sha256/512" for SHA256 or 512 hash.
234
    :type method: str
235
    """
236 5
    if method.lower() in ("sha512", "sha256"):
237 5
        return method.lower()
238
    else:
239 5
        raise argparse.ArgumentError(argument=None, message="Invalid type.")
240
241
242 5
def droidlookup_devicetype(device):
243
    """
244
    Check if Android autoloader device type is valid.
245
246
    :param device: Android autoloader types to check.
247
    :type device: str
248
    """
249 5
    devices = ("Priv", "DTEK50", "DTEK60", "KEYone", "Aurora")
250 5
    if device is None:
251 5
        return None
252
    else:
253 5
        for dev in devices:
254 5
            if dev.lower() == device.lower():
255 5
                return dev
256 5
        raise argparse.ArgumentError(argument=None, message="Invalid device.")
257
258
259 5
def s2b(input_check):
260
    """
261
    Return Boolean interpretation of string input.
262
263
    :param input_check: String to check if it means True or False.
264
    :type input_check: str
265
    """
266 5
    return str(input_check).lower() in ("yes", "true", "t", "1", "y")
267
268
269 5
def is_amd64():
270
    """
271
    Check if script is running on an AMD64 system (Python can be 32/64, this is for subprocess)
272
    """
273 5
    return platform.machine().endswith("64")
274
275
276 5
def is_windows():
277
    """
278
    Check if script is running on Windows.
279
    """
280 5
    return platform.system() == "Windows"
281
282
283 5
def talkaprint(msg, talkative=False):
284
    """
285
    Print only if asked to.
286
287
    :param msg: Message to print.
288
    :type msg: str
289
290
    :param talkative: Whether to output to screen. False by default.
291
    :type talkative: bool
292
    """
293 5
    if talkative:
294 5
        print(msg)
295
296
297 5
def get_seven_zip(talkative=False):
298
    """
299
    Return name of 7-Zip executable.
300
    On POSIX, it MUST be 7za.
301
    On Windows, it can be installed or supplied with the script.
302
    :func:`win_seven_zip` is used to determine if it's installed.
303
304
    :param talkative: Whether to output to screen. False by default.
305
    :type talkative: bool
306
    """
307 5
    return win_seven_zip(talkative) if is_windows() else "7za"
308
309
310 5
def win_seven_zip(talkative=False):
311
    """
312
    For Windows, check where 7-Zip is ("where", pretty much).
313
    Consult registry first for any installed instances of 7-Zip.
314
315
    :param talkative: Whether to output to screen. False by default.
316
    :type talkative: bool
317
    """
318
    talkaprint("CHECKING INSTALLED FILES...", talkative)
319
    try:
320
        path = wsz_registry()
321
    except OSError as exc:
322
        if talkative:
323
            exceptions.handle_exception(exc, xit=None)
324
        talkaprint("TRYING LOCAL FILES...", talkative)
325
        return win_seven_zip_local(talkative)
326
    else:
327
        talkaprint("7ZIP USING INSTALLED FILES", talkative)
328
        return '"{0}"'.format(os.path.join(path[0], "7z.exe"))
329
330
331 5
def wsz_registry():
332
    """
333
    Check Windows registry for 7-Zip executable location.
334
    """
335
    import winreg  # windows registry
336
    hk7z = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\7-Zip")
337
    path = winreg.QueryValueEx(hk7z, "Path")
338
    return path
339
340
341 5
def win_seven_zip_local(talkative=False):
342
    """
343
    If 7-Zip isn't in the registry, fall back onto supplied executables.
344
    If *those* aren't there, return "error".
345
346
    :param talkative: Whether to output to screen. False by default.
347
    :type talkative: bool
348
    """
349
    filecount = wsz_filecount()
350
    if filecount == 2:
351
        szexe = wsz_local_good(talkative)
352
    else:
353
        szexe = wsz_local_bad(talkative)
354
    return szexe
355
356
357 5
def wsz_filecount():
358
    """
359
    Get count of 7-Zip executables in local folder.
360
    """
361
    filecount = len([x for x in os.listdir(os.getcwd()) if x in ["7za.exe", "7z.exe"]])
362
    return filecount
363
364
365 5
def wsz_local_good(talkative=False):
366
    """
367
    Get 7-Zip exe name if everything is good.
368
369
    :param talkative: Whether to output to screen. False by default.
370
    :type talkative: bool
371
    """
372
    talkaprint("7ZIP USING LOCAL FILES", talkative)
373
    szexe = "7za.64.exe" if is_amd64() else "7za.exe"
374
    return szexe
375
376
377 5
def wsz_local_bad(talkative=False):
378
    """
379
    Handle 7-Zip exe name in case of issues.
380
381
    :param talkative: Whether to output to screen. False by default.
382
    :type talkative: bool
383
    """
384
    talkaprint("NO LOCAL FILES", talkative)
385
    szexe = "error"
386
    return szexe
387
388
389 5
def get_core_count():
390
    """
391
    Find out how many CPU cores this system has.
392
    """
393 5
    try:
394 5
        cores = str(compat.enum_cpus())  # 3.4 and up
395
    except NotImplementedError:
396
        cores = "1"  # 3.2-3.3
397
    else:
398 5
        if compat.enum_cpus() is None:
399
            cores = "1"
400 5
    return cores
401
402
403 5
def prep_seven_zip_path(path, talkative=False):
404
    """
405
    Print p7zip path on POSIX, or notify if not there.
406
407
    :param path: Path to use.
408
    :type path: str
409
410
    :param talkative: Whether to output to screen. False by default.
411
    :type talkative: bool
412
    """
413 5
    if path is None:
414 5
        talkaprint("NO 7ZIP\nPLEASE INSTALL p7zip", talkative)
415 5
        return False
416
    else:
417 5
        talkaprint("7ZIP FOUND AT {0}".format(path), talkative)
418 5
        return True
419
420
421 5
def prep_seven_zip_posix(talkative=False):
422
    """
423
    Check for p7zip on POSIX.
424
425
    :param talkative: Whether to output to screen. False by default.
426
    :type talkative: bool
427
    """
428 5
    try:
429 5
        path = compat.where_which("7za")
430 5
    except ImportError:
431 5
        talkaprint("PLEASE INSTALL SHUTILWHICH WITH PIP", talkative)
432 5
        return False
433
    else:
434 5
        return prep_seven_zip_path(path, talkative)
435
436
437 5
def prep_seven_zip(talkative=False):
438
    """
439
    Check for presence of 7-Zip.
440
    On POSIX, check for p7zip.
441
    On Windows, check for 7-Zip.
442
443
    :param talkative: Whether to output to screen. False by default.
444
    :type talkative: bool
445
    """
446 5
    if is_windows():
447
        return get_seven_zip(talkative) != "error"
448
    else:
449 5
        return prep_seven_zip_posix(talkative)
450
451
452 5
def increment(version, inc=3):
453
    """
454
    Increment version by given number. For repeated lookups.
455
456
    :param version: w.x.y.ZZZZ, becomes w.x.y.(ZZZZ + increment).
457
    :type version: str
458
459
    :param inc: What to increment by. Default is 3.
460
    :type inc: str
461
    """
462 5
    splitos = version.split(".")
463 5
    splitos[3] = int(splitos[3])
464 5
    if splitos[3] > 9996:  # prevent overflow
465 5
        splitos[3] = 0
466 5
    splitos[3] += int(inc)
467 5
    splitos[3] = str(splitos[3])
468 5
    return ".".join(splitos)
469
470
471 5
def stripper(name):
472
    """
473
    Strip fluff from bar filename.
474
475
    :param name: Bar filename, must contain '-nto+armle-v7+signed.bar'.
476
    :type name: str
477
    """
478 5
    return name.replace("-nto+armle-v7+signed.bar", "")
479
480
481 5
def create_base_url(softwareversion):
482
    """
483
    Make the root URL for production server files.
484
485
    :param softwareversion: Software version to hash.
486
    :type softwareversion: str
487
    """
488
    # Hash software version
489 5
    swhash = hashlib.sha1(softwareversion.encode('utf-8'))
490 5
    hashedsoftwareversion = swhash.hexdigest()
491
    # Root of all urls
492 5
    baseurl = "http://cdn.fs.sl.blackberry.com/fs/qnx/production/{0}".format(hashedsoftwareversion)
493 5
    return baseurl
494
495
496 5
def format_app_name(appname):
497
    """
498
    Convert long reverse DNS name to short name.
499
500
    :param appname: Application name (ex. sys.pim.calendar -> "calendar")
501
    :type appname: str
502
    """
503 5
    final = appname.split(".")[-1]
504 5
    return final
505
506
507 5
def create_bar_url(softwareversion, appname, appversion, clean=False):
508
    """
509
    Make the URL for any production server file.
510
511
    :param softwareversion: Software version to hash.
512
    :type softwareversion: str
513
514
    :param appname: Application name, preferably like on server.
515
    :type appname: str
516
517
    :param appversion: Application version.
518
    :type appversion: str
519
520
    :param clean: Whether or not to clean up app name. Default is False.
521
    :type clean: bool
522
    """
523 5
    baseurl = create_base_url(softwareversion)
524 5
    if clean:
525 5
        appname = format_app_name(appname)
526 5
    return "{0}/{1}-{2}-nto+armle-v7+signed.bar".format(baseurl, appname, appversion)
527
528
529 5
def generate_urls(softwareversion, osversion, radioversion, core=False):
530
    """
531
    Generate a list of OS URLs and a list of radio URLs based on input.
532
533
    :param softwareversion: Software version to hash.
534
    :type softwareversion: str
535
536
    :param osversion: OS version.
537
    :type osversion: str
538
539
    :param radioversion: Radio version.
540
    :type radioversion: str
541
542
    :param core: Whether or not to return core URLs as well.
543
    :type core: bool
544
    """
545 5
    osurls = [
546
        create_bar_url(softwareversion, "winchester.factory_sfi.desktop", osversion),
547
        create_bar_url(softwareversion, "qc8960.factory_sfi.desktop", osversion),
548
        create_bar_url(softwareversion, "qc8960.factory_sfi.desktop", osversion),
549
        create_bar_url(softwareversion, "qc8974.factory_sfi.desktop", osversion)
550
    ]
551 5
    radiourls = [
552
        create_bar_url(softwareversion, "m5730", radioversion),
553
        create_bar_url(softwareversion, "qc8960", radioversion),
554
        create_bar_url(softwareversion, "qc8960.omadm", radioversion),
555
        create_bar_url(softwareversion, "qc8960.wtr", radioversion),
556
        create_bar_url(softwareversion, "qc8960.wtr5", radioversion),
557
        create_bar_url(softwareversion, "qc8930.wtr5", radioversion),
558
        create_bar_url(softwareversion, "qc8974.wtr2", radioversion)
559
    ]
560 5
    coreurls = []
561 5
    osurls, radiourls = filter_urls(osurls, radiourls, osversion)
562 5
    if core:
563 5
        coreurls = [x.replace(".desktop", "") for x in osurls]
564 5
    return osurls, radiourls, coreurls
565
566
567 5
def newer_103(splitos, third):
568
    """
569
    Return True if given split OS version is 10.3.X or newer.
570
571
    :param splitos: OS version, split on the dots: [10, 3, 3, 2205]
572
    :type: list(int)
573
574
    :param third: The X in 10.3.X.
575
    :type third: int
576
    """
577 5
    newer = True if ((splitos[1] >= 4) or (splitos[1] == 3 and splitos[2] >= third)) else False
578 5
    return newer
579
580
581 5
def filter_urls(osurls, radiourls, osversion):
582
    """
583
    Filter lists of OS and radio URLs.
584
585
    :param osurls: List of OS URLs.
586
    :type osurls: list(str)
587
588
    :param radiourls: List of radio URLs.
589
    :type radiourls: list(str)
590
591
    :param osversion: OS version.
592
    :type osversion: str
593
    """
594 5
    splitos = [int(i) for i in osversion.split(".")]
595 5
    osurls[2] = filter_1031(osurls[2], splitos, 5)  # Z3 10.3.1+
596 5
    osurls[3] = filter_1031(osurls[3], splitos, 6)  # Passport 10.3.1+
597 5
    osurls[0], radiourls[0] = pop_stl1(osurls[0], radiourls[0], splitos)  # STL100-1 10.3.3+
598 5
    return osurls, radiourls
599
600
601 5
def filter_1031(osurl, splitos, device):
602
    """
603
    Modify URLs to reflect changes in 10.3.1.
604
605
    :param osurl: OS URL to modify.
606
    :type osurl: str
607
608
    :param splitos: OS version, split and cast to int: [10, 3, 2, 2876]
609
    :type splitos: list(int)
610
611
    :param device: Device to use.
612
    :type device: int
613
    """
614 5
    if newer_103(splitos, 1):
615 5
        filterdict = {5: ("qc8960.factory_sfi", "qc8960.factory_sfi_hybrid_qc8x30"), 6: ("qc8974.factory_sfi", "qc8960.factory_sfi_hybrid_qc8974")}
616 5
        osurl = filter_osversion(osurl, device, filterdict)
617 5
    return osurl
618
619
620 5
def pop_stl1(osurl, radiourl, splitos):
621
    """
622
    Replace STL100-1 links in 10.3.3+.
623
624
    :param osurl: OS URL to modify.
625
    :type osurl: str
626
627
    :param radiourl: Radio URL to modify.
628
    :type radiourl: str
629
630
    :param splitos: OS version, split and cast to int: [10, 3, 3, 2205]
631
    :type splitos: list(int)
632
    """
633 5
    if newer_103(splitos, 3):
634 5
        osurl = osurl.replace("winchester", "qc8960")  # duplicates get filtered out later
635 5
        radiourl = radiourl.replace("m5730", "qc8960")
636 5
    return osurl, radiourl
637
638
639 5
def filter_osversion(osurl, device, filterdict):
640
    """
641
    Modify URLs based on device index and dictionary of changes.
642
643
    :param osurl: OS URL to modify.
644
    :type osurl: str
645
646
    :param device: Device to use.
647
    :type device: int
648
649
    :param filterdict: Dictionary of changes: {device : (before, after)}
650
    :type filterdict: dict(int:(str, str))
651
    """
652 5
    if device in filterdict.keys():
653 5
        osurl = osurl.replace(filterdict[device][0], filterdict[device][1])
654 5
    return osurl
655
656
657 5
def generate_lazy_urls(softwareversion, osversion, radioversion, device):
658
    """
659
    Generate a pair of OS/radio URLs based on input.
660
661
    :param softwareversion: Software version to hash.
662
    :type softwareversion: str
663
664
    :param osversion: OS version.
665
    :type osversion: str
666
667
    :param radioversion: Radio version.
668
    :type radioversion: str
669
670
    :param device: Device to use.
671
    :type device: int
672
    """
673 5
    splitos = [int(i) for i in osversion.split(".")]
674 5
    rads = ["m5730", "qc8960", "qc8960.omadm", "qc8960.wtr",
675
            "qc8960.wtr5", "qc8930.wtr4", "qc8974.wtr2"]
676 5
    oses = ["winchester.factory", "qc8960.factory", "qc8960.verizon",
677
            "qc8974.factory"]
678 5
    maps = {0:0, 1:1, 2:2, 3:1, 4:1, 5:1, 6:3}
679 5
    osurl = create_bar_url(softwareversion, "{0}_sfi.desktop".format(oses[maps[device]]), osversion)
680 5
    radiourl = create_bar_url(softwareversion, rads[device], radioversion)
681 5
    osurl = filter_1031(osurl, splitos, device)
682 5
    return osurl, radiourl
683
684
685 5
def bulk_urls(softwareversion, osversion, radioversion, core=False, altsw=None):
686
    """
687
    Generate all URLs, plus extra Verizon URLs.
688
689
    :param softwareversion: Software version to hash.
690
    :type softwareversion: str
691
692
    :param osversion: OS version.
693
    :type osversion: str
694
695
    :param radioversion: Radio version.
696
    :type radioversion: str
697
698
    :param device: Device to use.
699
    :type device: int
700
701
    :param core: Whether or not to return core URLs as well.
702
    :type core: bool
703
704
    :param altsw: Radio software release, if not the same as OS.
705
    :type altsw: str
706
    """
707 5
    baseurl = create_base_url(softwareversion)
708 5
    osurls, radurls, coreurls = generate_urls(softwareversion, osversion, radioversion, core)
709 5
    vzwos, vzwrad = generate_lazy_urls(softwareversion, osversion, radioversion, 2)
710 5
    osurls.append(vzwos)
711 5
    radurls.append(vzwrad)
712 5
    vzwcore = vzwos.replace("sfi.desktop", "sfi")
713 5
    if core:
714 5
        coreurls.append(vzwcore)
715 5
    osurls = list(set(osurls))  # pop duplicates
716 5
    radurls = list(set(radurls))
717 5
    if core:
718 5
        coreurls = list(set(coreurls))
719 5
    radurls = bulk_urls_altsw(radurls, baseurl, altsw)
720 5
    return osurls, coreurls, radurls
721
722
723 5
def bulk_urls_altsw(radurls, baseurl, altsw=None):
724
    """
725
    Handle alternate software release for radio.
726
727
    :param radurls: List of radio URLs.
728
    :type radurls: list(str)
729
730
    :param baseurl: Base URL (from http to hashed SW release).
731
    :type baseurl: str
732
733
    :param altsw: Radio software release, if not the same as OS.
734
    :type altsw: str
735
    """
736 5
    if altsw is not None:
737 5
        altbase = create_base_url(altsw)
738 5
        radiourls2 = [rad.replace(baseurl, altbase) for rad in radurls]
739 5
        radurls = radiourls2
740 5
        del radiourls2
741 5
    return radurls
742
743
744 5
def line_begin():
745
    """
746
    Go to beginning of line, to overwrite whatever's there.
747
    """
748 5
    sys.stdout.write("\r")
749 5
    sys.stdout.flush()
750
751
752 5
def spinner_clear():
753
    """
754
    Get rid of any spinner residue left in stdout.
755
    """
756 5
    sys.stdout.write("\b \b")
757 5
    sys.stdout.flush()
758
759
760 5
class Spinner(object):
761
    """
762
    A basic spinner using itertools. No need for progress.
763
    """
764
765 5
    def __init__(self):
766 5
        self.wheel = itertools.cycle(['-', '/', '|', '\\'])
767 5
        self.file = dummy.UselessStdout()
768
769 5
    def after(self):
770
        """
771
        Iterate over itertools.cycle, write to file.
772
        """
773 5
        try:
774 5
            self.file.write(next(self.wheel))
775 5
            self.file.flush()
776 5
            self.file.write("\b\r")
777 5
            self.file.flush()
778
        except (KeyboardInterrupt, SystemExit):
779
            self.stop()
780
781 5
    def stop(self):
782
        """
783
        Kill output.
784
        """
785 5
        self.file = dummy.UselessStdout()
786
787
788 5
class SpinManager(object):
789
    """
790
    Wraps around the itertools spinner, runs it in another thread.
791
    """
792
793 5
    def __init__(self):
794 5
        spinner = Spinner()
795 5
        self.spinner = spinner
796 5
        self.thread = threading.Thread(target=self.loop, args=())
797 5
        self.thread.daemon = True
798 5
        self.scanning = False
799 5
        self.spinner.file = dummy.UselessStdout()
800
801 5
    def start(self):
802
        """
803
        Begin the spinner.
804
        """
805 5
        self.spinner.file = sys.stderr
806 5
        self.scanning = True
807 5
        self.thread.start()
808
809 5
    def loop(self):
810
        """
811
        Spin if scanning, clean up if not.
812
        """
813 5
        while self.scanning:
814 5
            time.sleep(0.5)
815 5
            try:
816 5
                line_begin()
817 5
                self.spinner.after()
818
            except (KeyboardInterrupt, SystemExit):
819
                self.scanning = False
820
                self.stop()
821
822 5
    def stop(self):
823
        """
824
        Stop the spinner.
825
        """
826 5
        self.spinner.stop()
827 5
        self.scanning = False
828 5
        spinner_clear()
829 5
        line_begin()
830 5
        if not is_windows():
831 5
            print("\n")
832
833
834 5
def return_and_delete(target):
835
    """
836
    Read text file, then delete it. Return contents.
837
838
    :param target: Text file to read.
839
    :type target: str
840
    """
841 5
    with open(target, "r") as thefile:
842 5
        content = thefile.read()
843 5
    os.remove(target)
844 5
    return content
845
846
847 5
def verify_loader_integrity(loaderfile):
848
    """
849
    Test for created loader integrity. Windows-only.
850
851
    :param loaderfile: Path to loader.
852
    :type loaderfile: str
853
    """
854 5
    if not is_windows():
855 5
        pass
856
    else:
857 5
        excode = None
858 5
        try:
859 5
            with open(os.devnull, 'rb') as dnull:
860 5
                cmd = "{0} fileinfo".format(loaderfile)
861 5
                excode = subprocess.call(cmd, stdout=dnull, stderr=subprocess.STDOUT)
862 5
        except OSError:
863 5
            excode = -1
864 5
        return excode == 0  # 0 if OK, non-zero if something broke
865
866
867 5
def bulkfilter_printer(afile):
868
    """
869
    Print filename and verify a loader file.
870
871
    :param afile: Path to file.
872
    :type afile: str
873
    """
874 5
    print("TESTING: {0}".format(os.path.basename(afile)))
875 5
    if not verify_loader_integrity(afile):
876 5
        return os.path.basename(afile)
877
878
879 5
def bulkfilter(files):
880
    """
881
    Verify all loader files in a given list.
882
883
    :param files: List of files.
884
    :type files: list(str)
885
    """
886 5
    brokens = [bulkfilter_printer(file) for file in files if prepends(os.path.basename(file), bbconstants.PREFIXES, ".exe")]
887 5
    return brokens
888
889
890 5
def verify_bulk_loaders(ldir):
891
    """
892
    Run :func:`verify_loader_integrity` for all files in a dir.
893
894
    :param ldir: Directory to use.
895
    :type ldir: str
896
    """
897 5
    if not is_windows():
898 5
        pass
899
    else:
900 5
        files = verify_bulk_loaders_filefilter(ldir)
901 5
        brokens = verify_bulk_loaders_brokens(files)
902 5
        return brokens
903
904
905 5
def verify_bulk_loaders_filefilter(ldir):
906
    """
907
    Prepare file names for :func:`verify_bulk_loaders`.
908
909
    :param ldir: Directory to use.
910
    :type ldir: str
911
    """
912 5
    files = [os.path.join(ldir, file) for file in os.listdir(ldir) if not os.path.isdir(file)]
913 5
    return files
914
915
916 5
def verify_bulk_loaders_brokens(files):
917
    """
918
    Prepare filtered file list for :func:`verify_bulk_loaders`.
919
920
    :param files: List of files.
921
    :type files: list(str)
922
    """
923 5
    brokens = [file for file in bulkfilter(files) if file]
924 5
    return brokens
925
926
927 5
def list_workers(input_data, workerlimit):
928
    """
929
    Count number of threads, either length of iterable or provided limit.
930
931
    :param input_data: Input data, some iterable.
932
    :type input_data: list
933
934
    :param workerlimit: Maximum number of workers.
935
    :type workerlimit: int
936
    """
937 5
    runners = len(input_data) if len(input_data) < workerlimit else workerlimit
938 5
    return runners
939
940
941 5
def cpu_workers(input_data):
942
    """
943
    Count number of CPU workers, smaller of number of threads and length of data.
944
945
    :param input_data: Input data, some iterable.
946
    :type input_data: list
947
    """
948 5
    return list_workers(input_data, compat.enum_cpus())
949
950
951 5
def prep_logfile():
952
    """
953
    Prepare log file, labeling it with current date. Select folder based on frozen status.
954
    """
955 5
    logfile = "{0}.txt".format(time.strftime("%Y_%m_%d_%H%M%S"))
956 5
    root = os.getcwd() if getattr(sys, 'frozen', False) else os.path.expanduser("~")
957 5
    basefolder = os.path.join(root, "lookuplogs")
958 5
    os.makedirs(basefolder, exist_ok=True)
959 5
    record = os.path.join(basefolder, logfile)
960 5
    open(record, "w").close()
961 5
    return record
962
963
964 5
def prepends(file, pre, suf):
965
    """
966
    Check if filename starts with/ends with stuff.
967
968
    :param file: File to check.
969
    :type file: str
970
971
    :param pre: Prefix(es) to check.
972
    :type pre: str or list or tuple
973
974
    :param suf: Suffix(es) to check.
975
    :type suf: str or list or tuple
976
    """
977 5
    return file.startswith(pre) and file.endswith(suf)
978
979
980 5
def lprint(iterable):
981
    """
982
    A oneliner for 'for item in x: print item'.
983
984
    :param iterable: Iterable to print.
985
    :type iterable: list/tuple
986
    """
987 5
    for item in iterable:
988 5
        print(item)
989
990
991 5
def cappath_config_loader(homepath=None):
992
    """
993
    Read a ConfigParser file to get cap preferences.
994
995
    :param homepath: Folder containing ini file. Default is user directory.
996
    :type homepath: str
997
    """
998 5
    capini = iniconfig.generic_loader('cappath', homepath)
999 5
    cappath = capini.get('path', fallback=bbconstants.CAP.location)
1000 5
    return cappath
1001
1002
1003 5
def cappath_config_writer(cappath=None, homepath=None):
1004
    """
1005
    Write a ConfigParser file to store cap preferences.
1006
1007
    :param cappath: Method to use.
1008
    :type cappath: str
1009
1010
    :param homepath: Folder containing ini file. Default is user directory.
1011
    :type homepath: str
1012
    """
1013 5
    cappath = grab_cap() if cappath is None else cappath
1014 5
    results = {"path": cappath}
1015 5
    iniconfig.generic_writer("cappath", results, homepath)
1016
1017
1018 5
def def_args(dirs):
1019
    """
1020
    Return prepared argument list for most instances of :func:`cond_check:.
1021
1022
    :param dirs: List of directories.
1023
    :type dirs: list(str)
1024
    """
1025 5
    return [dirs[4], dirs[5], dirs[2], dirs[3]]
1026
1027
1028 5
def cond_do(dofunc, goargs, restargs=None, condition=True):
1029
    """
1030
    Do a function, check a condition, then do same function but swap first argument.
1031
1032
    :param dofunc: Function to do.
1033
    :type dofunc: function
1034
1035
    :param goargs: List of variable arguments.
1036
    :type goargs: list(str)
1037
1038
    :param restargs: Rest of arguments, which are constant.
1039
    :type restargs: list(str)
1040
1041
    :param condition: Condition to check in order to use secondarg.
1042
    :type condition: bool
1043
    """
1044 5
    restargs = [] if restargs is None else restargs
1045 5
    dofunc(goargs[0], *restargs)
1046 5
    if condition:
1047 5
        dofunc(goargs[1], *restargs)
1048
1049
1050 5
def cond_check(dofunc, goargs, restargs=None, condition=True, checkif=True, checkifnot=True):
1051
    """
1052
    Do :func:`cond_do` based on a condition, then do it again based on a second condition.
1053
1054
    :param dofunc: Function to do.
1055
    :type dofunc: function
1056
1057
    :param goargs: List of variable arguments.
1058
    :type goargs: list(str)
1059
1060
    :param restargs: Rest of arguments, which are constant.
1061
    :type restargs: list(str)
1062
1063
    :param condition: Condition to check in order to use secondarg.
1064
    :type condition: bool
1065
1066
    :param checkif: Do :func:`cond_do` if this is True.
1067
    :type checkif: bool
1068
1069
    :param checkifnot: Do :func:`cond_do` if this is False.
1070
    :type checkifnot: bool
1071
    """
1072 5
    if checkif:
1073 5
        cond_do(dofunc, goargs[0:2], restargs, condition)
1074 5
    if not checkifnot:
1075
        cond_do(dofunc, goargs[2:4], restargs, condition)
1076