Completed
Push — master ( 8ea8b2...72dabb )
by John
03:38
created

tcl_prd_print()   B

Complexity

Conditions 3

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
dl 0
loc 25
ccs 9
cts 9
cp 1
crap 3
rs 8.8571
c 0
b 0
f 0
1
#!/usr/bin/env python3
2 5
"""This module contains various utilities for the scripts folder."""
3
4 5
import os  # path work
5 5
import getpass  # invisible password
6 5
import argparse  # generic parser
7 5
import hashlib  # hashes
8 5
import sys  # getattr
9 5
import shutil  # folder removal
10 5
import subprocess  # running cfp/cap
11 5
import glob  # file lookup
12 5
import threading  # run stuff in background
13 5
import requests  # session
14 5
from bbarchivist import utilities  # little things
15 5
from bbarchivist import decorators  # decorating functions
16 5
from bbarchivist import barutils  # file system work
17 5
from bbarchivist import archiveutils  # archive support
18 5
from bbarchivist import bbconstants  # constants
19 5
from bbarchivist import gpgutils  # gpg
20 5
from bbarchivist import hashutils  # file hashes
21 5
from bbarchivist import networkutils  # network tools
22 5
from bbarchivist import textgenerator  # writing text to file
23 5
from bbarchivist import smtputils  # email
24 5
from bbarchivist import sqlutils  # sql
25
26 5
__author__ = "Thurask"
27 5
__license__ = "WTFPL v2"
28 5
__copyright__ = "2015-2017 Thurask"
29
30
31 5
def shortversion():
32
    """
33
    Get short app version (Git tag).
34
    """
35 5
    if not getattr(sys, 'frozen', False):
36 5
        ver = bbconstants.VERSION
37
    else:
38 5
        verfile = glob.glob(os.path.join(os.getcwd(), "version.txt"))[0]
39 5
        with open(verfile) as afile:
40 5
            ver = afile.read()
41 5
    return ver
42
43
44 5
def longversion():
45
    """
46
    Get long app version (Git tag + commits + hash).
47
    """
48 5
    if not getattr(sys, 'frozen', False):
49 5
        ver = (bbconstants.LONGVERSION, bbconstants.COMMITDATE)
50
    else:
51 5
        verfile = glob.glob(os.path.join(os.getcwd(), "longversion.txt"))[0]
52 5
        with open(verfile) as afile:
53 5
            ver = afile.read().split("\n")
54 5
    return ver
55
56
57 5
def default_parser(name=None, desc=None, flags=None, vers=None):
58
    """
59
    A generic form of argparse's ArgumentParser.
60
61
    :param name: App name.
62
    :type name: str
63
64
    :param desc: App description.
65
    :type desc: str
66
67
    :param flags: Tuple of sections to add.
68
    :type flags: tuple(str)
69
70
    :param vers: Versions: [git commit hash, git commit date]
71
    :param vers: list(str)
72
    """
73 5
    if vers is None:
74 5
        vers = longversion()
75 5
    parser = argparse.ArgumentParser(
76
        prog=name,
77
        description=desc,
78
        epilog="https://github.com/thurask/bbarchivist")
79 5
    parser.add_argument(
80
        "-v",
81
        "--version",
82
        action="version",
83
        version="{0} {1} committed {2}".format(parser.prog, vers[0], vers[1]))
84 5
    if flags is not None:
85 5
        if "folder" in flags:
86 5
            parser.add_argument(
87
                "-f",
88
                "--folder",
89
                dest="folder",
90
                help="Working folder",
91
                default=None,
92
                metavar="DIR",
93
                type=utilities.file_exists)
94 5
        if "osr" in flags:
95 5
            parser.add_argument(
96
                "os",
97
                help="OS version")
98 5
            parser.add_argument(
99
                "radio",
100
                help="Radio version, 10.x.y.zzzz",
101
                nargs="?",
102
                default=None)
103 5
            parser.add_argument(
104
                "swrelease",
105
                help="Software version, 10.x.y.zzzz",
106
                nargs="?",
107
                default=None)
108 5
    return parser
109
110
111 5
def generic_windows_shim(scriptname, scriptdesc, target, version):
112
    """
113
    Generic CFP/CAP runner; Windows only.
114
115
    :param scriptname: Script name, 'bb-something'.
116
    :type scriptname: str
117
118
    :param scriptdesc: Script description, i.e. scriptname -h.
119
    :type scriptdesc: str
120
121
    :param target: Path to file to execute.
122
    :type target: str
123
124
    :param version: Version of target.
125
    :type version: str
126
    """
127 5
    parser = default_parser(scriptname, scriptdesc)
128 5
    capver = "|{0}".format(version)
129 5
    parser = external_version(parser, capver)
130 5
    parser.parse_known_args(sys.argv[1:])
131 5
    if utilities.is_windows():
132 5
        subprocess.call([target] + sys.argv[1:])
133
    else:
134 5
        print("Sorry, Windows only.")
135
136
137 5
def arg_verify_none(argval, message):
138
    """
139
    Check if an argument is None, error out if it is.
140
141
    :param argval: Argument to check.
142
    :type argval: str
143
144
    :param message: Error message to print.
145
    :type message: str
146
    """
147 5
    if argval is None:
148 5
        raise argparse.ArgumentError(argument=None, message=message)
149
150
151 5
def external_version(parser, addition):
152
    """
153
    Modify the version string of argparse.ArgumentParser, adding something.
154
155
    :param parser: Parser to modify.
156
    :type parser: argparse.ArgumentParser
157
158
    :param addition: What to add.
159
    :type addition: str
160
    """
161 5
    verarg = [arg for arg in parser._actions if isinstance(arg, argparse._VersionAction)][0]
162 5
    verarg.version = "{1}{0}".format(addition, verarg.version)
163 5
    return parser
164
165
166 5
def return_radio_version(osversion, radioversion=None):
167
    """
168
    Increment radio version, if need be.
169
170
    :param osversion: OS version.
171
    :type osversion: str
172
173
    :param radioversion: Radio version, None if incremented.
174
    :type radioversion: str
175
    """
176 5
    if radioversion is None:
177 5
        radioversion = utilities.increment(osversion, 1)
178 5
    return radioversion
179
180
181 5
def sw_check_contingency(softwareversion):
182
    """
183
    Ask in the event software release isn't found.
184
185
    :param softwareversion: Software release version.
186
    :type softwareversion: str
187
    """
188 5
    if softwareversion == "SR not in system":
189 5
        print("SOFTWARE RELEASE NOT FOUND")
190 5
        cont = utilities.s2b(input("INPUT MANUALLY? Y/N: "))
191 5
        if cont:
192 5
            softwareversion = input("SOFTWARE RELEASE: ")
193 5
            swchecked = False
194
        else:
195 5
            print("\nEXITING...")
196 5
            raise SystemExit  # bye bye
197
    else:
198 5
        swchecked = True
199 5
    return softwareversion, swchecked
200
201
202 5
def return_sw_checked(softwareversion, osversion):
203
    """
204
    Check software existence, return boolean.
205
206
    :param softwareversion: Software release version.
207
    :type softwareversion: str
208
209
    :param osversion: OS version.
210
    :type osversion: str
211
    """
212 5
    if softwareversion is None:
213 5
        serv = bbconstants.SERVERS["p"]
214 5
        softwareversion = networkutils.sr_lookup(osversion, serv)
215 5
        softwareversion, swchecked = sw_check_contingency(softwareversion)
216
    else:
217 5
        swchecked = True
218 5
    return softwareversion, swchecked
219
220
221 5
def return_radio_sw_checked(altsw, radioversion):
222
    """
223
    Check radio software existence, return boolean.
224
225
    :param altsw: Software release version.
226
    :type altsw: str
227
228
    :param radioversion: Radio version.
229
    :type radioversion: str
230
    """
231 5
    if altsw == "checkme":
232 5
        serv = bbconstants.SERVERS["p"]
233 5
        testos = utilities.increment(radioversion, -1)
234 5
        altsw = networkutils.sr_lookup(testos, serv)
235 5
        altsw, altchecked = sw_check_contingency(altsw)
236
    else:
237 5
        altchecked = True
238 5
    return altsw, altchecked
239
240
241 5
def check_sw(baseurl, softwareversion, swchecked, altsw=False):
242
    """
243
    Check existence of software release.
244
245
    :param baseurl: Base URL (from http to hashed SW release).
246
    :type basurl: str
247
248
    :param softwareversion: Software release.
249
    :type softwareversion: str
250
251
    :param swchecked: If we checked the sw release already.
252
    :type swchecked: bool
253
254
    :param altsw: If this is the radio-only release. Default is false.
255
    :type altsw: bool
256
    """
257 5
    message = "CHECKING RADIO SOFTWARE RELEASE..." if altsw else "CHECKING SOFTWARE RELEASE..."
258 5
    print(message)
259 5
    if not swchecked:
260 5
        avlty = networkutils.availability(baseurl)
261 5
        if avlty:
262 5
            print("SOFTWARE RELEASE {0} EXISTS".format(softwareversion))
263
        else:
264 5
            print("SOFTWARE RELEASE {0} NOT FOUND".format(softwareversion))
265 5
            cont = utilities.s2b(input("CONTINUE? Y/N: "))
266 5
            if not cont:
267 5
                print("\nEXITING...")
268 5
                raise SystemExit
269
    else:
270 5
        print("SOFTWARE RELEASE {0} EXISTS".format(softwareversion))
271
272
273 5
def check_radio_sw(alturl, altsw, altchecked):
274
    """
275
    Check existence of radio software release.
276
277
    :param alturl: Radio base URL (from http to hashed SW release).
278
    :type alturl: str
279
280
    :param altsw: Radio software release.
281
    :type altsw: str
282
283
    :param altchecked: If we checked the sw release already.
284
    :type altchecked: bool
285
    """
286 5
    return check_sw(alturl, altsw, altchecked, True)
287
288
289 5
def check_altsw(altcheck=False):
290
    """
291
    Ask for and return alternate software release, if needed.
292
293
    :param altcheck: If we're using an alternate software release.
294
    :type altcheck: bool
295
    """
296 5
    if altcheck:
297 5
        altsw = input("RADIO SOFTWARE RELEASE (PRESS ENTER TO GUESS): ")
298 5
        if not altsw:
299 5
            altsw = "checkme"
300
    else:
301 5
        altsw = None
302 5
    return altsw
303
304
305 5
def check_os_single(osurl, osversion, device):
306
    """
307
    Check existence of single OS link.
308
309
    :param radiourl: Radio URL to check.
310
    :type radiourl: str
311
312
    :param radioversion: Radio version.
313
    :type radioversion: str
314
315
    :param device: Device family.
316
    :type device: int
317
    """
318 5
    osav = networkutils.availability(osurl)
319 5
    if not osav:
320 5
        print("{0} NOT AVAILABLE FOR {1}".format(osversion, bbconstants.DEVICES[device]))
321 5
        cont = utilities.s2b(input("CONTINUE? Y/N: "))
322 5
        if not cont:
323 5
            print("\nEXITING...")
324 5
            raise SystemExit
325
326
327 5
def check_os_bulk(osurls):
328
    """
329
    Check existence of list of OS links.
330
331
    :param osurls: OS URLs to check.
332
    :type osurls: list(str)
333
    """
334 5
    sess = requests.Session()
335 5
    for url in osurls:
336 5
        osav = networkutils.availability(url, sess)
337 5
        if osav:
338 5
            break
339
    else:
340 5
        print("OS VERSION NOT FOUND")
341 5
        cont = utilities.s2b(input("CONTINUE? Y/N: "))
342 5
        if not cont:
343 5
            print("\nEXITING...")
344 5
            raise SystemExit
345
346
347 5
def check_radio_single(radiourl, radioversion):
348
    """
349
    Check existence of single radio link.
350
351
    :param radiourl: Radio URL to check.
352
    :type radiourl: str
353
354
    :param radioversion: Radio version.
355
    :type radioversion: str
356
    """
357 5
    radav = networkutils.availability(radiourl)
358 5
    if not radav:
359 5
        print("RADIO VERSION NOT FOUND")
360 5
        cont = utilities.s2b(input("INPUT MANUALLY? Y/N: "))
361 5
        if cont:
362 5
            rad2 = input("RADIO VERSION: ")
363 5
            radiourl = radiourl.replace(radioversion, rad2)
364 5
            radioversion = rad2
365
        else:
366 5
            going = utilities.s2b(input("KEEP GOING? Y/N: "))
367 5
            if not going:
368 5
                print("\nEXITING...")
369 5
                raise SystemExit
370 5
    return radiourl, radioversion
371
372
373 5
def check_radio_bulk(radiourls, radioversion):
374
    """
375
    Check existence of list of radio links.
376
377
    :param radiourls: Radio URLs to check.
378
    :type radiourls: list(str)
379
380
    :param radioversion: Radio version.
381
    :type radioversion: str
382
    """
383 5
    sess = requests.Session()
384 5
    for url in radiourls:
385 5
        radav = networkutils.availability(url, sess)
386 5
        if radav:
387 5
            break
388
    else:
389 5
        radiourls, radioversion = check_radio_bulk_notfound(radiourls, radioversion)
390 5
    return radiourls, radioversion
391
392
393 5
def check_radio_bulk_notfound(radiourls, radioversion):
394
    """
395
    What to do if radio links aren't found.
396
397
    :param radiourls: Radio URLs to check.
398
    :type radiourls: list(str)
399
400
    :param radioversion: Radio version.
401
    :type radioversion: str
402
    """
403 5
    print("RADIO VERSION NOT FOUND")
404 5
    cont = utilities.s2b(input("INPUT MANUALLY? Y/N: "))
405 5
    if cont:
406 5
        radiourls, radioversion = check_radio_bulk_go(radiourls, radioversion)
407
    else:
408 5
        check_radio_bulk_stop()
409 5
    return radiourls, radioversion
410
411
412 5
def check_radio_bulk_go(radiourls, radioversion):
413
    """
414
    Replace radio version and URLs, and keep going.
415
416
    :param radiourls: Radio URLs to check.
417
    :type radiourls: list(str)
418
419
    :param radioversion: Radio version.
420
    :type radioversion: str
421
    """
422 5
    rad2 = input("RADIO VERSION: ")
423 5
    radiourls = [url.replace(radioversion, rad2) for url in radiourls]
424 5
    radioversion = rad2
425 5
    return radiourls, radioversion
426
427
428 5
def check_radio_bulk_stop():
429
    """
430
    Ask if we should keep going once no radio has been found.
431
    """
432 5
    going = utilities.s2b(input("KEEP GOING? Y/N: "))
433 5
    if not going:
434 5
        print("\nEXITING...")
435 5
        raise SystemExit
436
437
438 5
def bulk_avail(urllist):
439
    """
440
    Filter 404 links out of URL list.
441
442
    :param urllist: URLs to check.
443
    :type urllist: list(str)
444
    """
445 5
    sess = requests.Session()
446 5
    url2 = [x for x in urllist if networkutils.availability(x, sess)]
447 5
    return url2
448
449
450 5
def get_baseurls(softwareversion, altsw=None):
451
    """
452
    Generate base URLs for bar links.
453
454
    :param softwareversion: Software version.
455
    :type softwareversion: str
456
457
    :param altsw: Radio software version, if necessary.
458
    :type altsw: str
459
    """
460 5
    baseurl = utilities.create_base_url(softwareversion)
461 5
    alturl = utilities.create_base_url(altsw) if altsw else None
462 5
    return baseurl, alturl
463
464
465 5
def get_sz_executable(compmethod):
466
    """
467
    Get 7z executable.
468
469
    :param compmethod: Compression method.
470
    :type compmethod: str
471
    """
472 5
    if compmethod != "7z":
473 5
        szexe = ""
474
    else:
475 5
        print("CHECKING PRESENCE OF 7ZIP...")
476 5
        psz = utilities.prep_seven_zip(True)
477 5
        if psz:
478 5
            print("7ZIP OK")
479 5
            szexe = utilities.get_seven_zip(False)
480
        else:
481 5
            szexe = ""
482 5
            print("7ZIP NOT FOUND")
483 5
            cont = utilities.s2b(input("CONTINUE? Y/N "))
484 5
            if cont:
485 5
                print("FALLING BACK TO ZIP...")
486 5
                compmethod = "zip"
487
            else:
488 5
                print("\nEXITING...")
489 5
                raise SystemExit  # bye bye
490 5
    return compmethod, szexe
491
492
493 5
def test_bar_files(localdir, urllist):
494
    """
495
    Test bar files after download.
496
497
    :param localdir: Directory.
498
    :type localdir: str
499
500
    :param urllist: List of URLs to check.
501
    :type urllist: list(str)
502
    """
503 5
    brokenlist = []
504 5
    print("TESTING BAR FILES...")
505 5
    for file in os.listdir(localdir):
506 5
        brokenlist = test_bar_files_individual(file, localdir, urllist, brokenlist)
507 5
    if brokenlist:
508 5
        print("SOME FILES ARE BROKEN!")
509 5
        utilities.lprint(brokenlist)
510 5
        raise SystemExit
511
    else:
512 5
        print("BAR FILES DOWNLOADED OK")
513
514
515 5
def test_bar_files_individual(file, localdir, urllist, brokenlist):
516
    """
517
    Test bar file after download.
518
519
    :param file: Bar file to check.
520
    :type file: str
521
522
    :param localdir: Directory.
523
    :type localdir: str
524
525
    :param urllist: List of URLs to check.
526
    :type urllist: list(str)
527
528
    :param brokenlist: List of URLs to download later.
529
    :type brokenlist: list(str)
530
    """
531 5
    if file.endswith(".bar"):
532 5
        print("TESTING: {0}".format(file))
533 5
        thepath = os.path.abspath(os.path.join(localdir, file))
534 5
        brokens = barutils.bar_tester(thepath)
535 5
        if brokens is not None:
536 5
            os.remove(brokens)
537 5
            for url in urllist:
538 5
                if brokens in url:
539 5
                    brokenlist.append(url)
540 5
    return brokenlist
541
542
543 5
def test_signed_files(localdir):
544
    """
545
    Test signed files after extract.
546
547
    :param localdir: Directory.
548
    :type localdir: str
549
    """
550 5
    print("TESTING SIGNED FILES...")
551 5
    for file in os.listdir(localdir):
552 5
        if file.endswith(".bar"):
553 5
            print("TESTING: {0}".format(file))
554 5
            signname, signhash = barutils.retrieve_sha512(os.path.join(localdir, file))
555 5
            sha512ver = barutils.verify_sha512(os.path.join(localdir, signname.decode("utf-8")), signhash)
556 5
            if not sha512ver:
557 5
                print("{0} IS BROKEN".format((file)))
558 5
                break
559
    else:
560 5
        print("ALL FILES EXTRACTED OK")
561
562
563 5
def test_loader_files(localdir):
564
    """
565
    Test loader files after creation.
566
567
    :param localdir: Directory.
568
    :type localdir: str
569
    """
570 5
    if not utilities.is_windows():
571 5
        pass
572
    else:
573 5
        print("TESTING LOADER FILES...")
574 5
        brokens = utilities.verify_bulk_loaders(localdir)
575 5
        if brokens:
576 5
            print("BROKEN FILES:")
577 5
            utilities.lprint(brokens)
578 5
            raise SystemExit
579
        else:
580 5
            print("ALL FILES CREATED OK")
581
582
583 5
def test_single_loader(loaderfile):
584
    """
585
    Test single loader file after creation.
586
587
    :param loaderfile: File to check.
588
    :type loaderfile: str
589
    """
590 5
    if not utilities.is_windows():
591 5
        pass
592
    else:
593 5
        print("TESTING LOADER...")
594 5
        if not utilities.verify_loader_integrity(loaderfile):
595 5
            print("{0} IS BROKEN!".format(os.path.basename(loaderfile)))
596 5
            raise SystemExit
597
        else:
598 5
            print("LOADER CREATED OK")
599
600
601 5
def prod_avail(results, mailer=False, osversion=None, password=None):
602
    """
603
    Clean availability for production lookups for autolookup script.
604
605
    :param results: Result dict.
606
    :type results: dict(str: str)
607
608
    :param mailer: If we're mailing links. Default is false.
609
    :type mailer: bool
610
611
    :param osversion: OS version.
612
    :type osversion: str
613
614
    :param password: Email password.
615
    :type password: str
616
    """
617 5
    prel = results['p']
618 5
    if prel != "SR not in system" and prel is not None:
619 5
        pav = "PD"
620 5
        baseurl = utilities.create_base_url(prel)
621 5
        avail = networkutils.availability(baseurl)
622 5
        is_avail = "Available" if avail else "Unavailable"
623 5
        prod_avail_mailprep(prel, avail, osversion, mailer, password)
624
    else:
625 5
        pav = "  "
626 5
        is_avail = "Unavailable"
627 5
    return prel, pav, is_avail
628
629
630 5
def prod_avail_mailprep(prel, avail, osversion=None, mailer=False, password=None):
631
    """
632
    Do SQL/SMTP prep work after a good production lookup hit.
633
634
    :param prel: Software lookup result.
635
    :type prel: str
636
637
    :param avail: If software lookup result is available for download.
638
    :type avail: bool
639
640
    :param osversion: OS version.
641
    :type osversion: str
642
643
    :param mailer: If we're mailing links. Default is false.
644
    :type mailer: bool
645
646
    :param password: Email password.
647
    :type password: str
648
    """
649 5
    if avail and mailer:
650 5
        sqlutils.prepare_sw_db()
651 5
        if not sqlutils.check_exists(osversion, prel):
652 5
            rad = utilities.increment(osversion, 1)
653 5
            linkgen(osversion, rad, prel, temp=True)
654 5
            smtputils.prep_email(osversion, prel, password)
655
656
657 5
def comp_joiner(rootdir, localdir, filelist):
658
    """
659
    Join rootdir, localdir to every file in filelist.
660
661
    :param rootdir: Root directory.
662
    :type rootdir: str
663
664
    :param localdir: Subfolder inside rootdir.
665
    :type localdir: str
666
667
    :param filelist: List of files to return this path for.
668
    :type filelist: list(str)
669
    """
670 5
    joinedfiles = [os.path.join(rootdir, localdir, os.path.basename(x)) for x in filelist]
671 5
    return joinedfiles
672
673
674 5
def kernchecker_prep(kernlist):
675
    """
676
    Prepare output from kernel list.
677
678
    :param kernlist: List of kernel branches.
679
    :type kernlist: list(str)
680
    """
681 5
    splitkerns = [x.split("/") for x in kernlist]
682 5
    platforms = list({x[0] for x in splitkerns})
683 5
    kerndict = kernchecker_dict(splitkerns, platforms)
684 5
    return kerndict
685
686
687 5
def kernchecker_dict(splitkerns, platforms):
688
    """
689
    Prepare results dictionary.
690
691
    :param splitkerns: Split kernel branches.
692
    :type splitkerns: list(str)
693
694
    :param platforms: List of platform dicts.
695
    :type platforms: list(dict)
696
    """
697 5
    kerndict = {x: [] for x in platforms}
698 5
    for kernel in splitkerns:
699 5
        kerndict[kernel[0]].append("\t{0}".format(kernel[1]))
700 5
    return kerndict
701
702
703 5
def tclloader_prep(loaderfile, directory=False):
704
    """
705
    Prepare directory name and OS version.
706
707
    :param loaderfile: Path to input file/folder.
708
    :type loaderfile: str
709
710
    :param directory: If the input file is a folder. Default is False.
711
    :type directory: bool
712
    """
713 5
    loaderdir = loaderfile if directory else loaderfile.replace(".zip", "")
714 5
    osver = loaderdir.split("-")[-1]
715 5
    return loaderdir, osver
716
717
718 5
def tclloader_filename(loaderdir, osver, loadername=None):
719
    """
720
    Prepare platform and filename.
721
722
    :param loaderdir: Path to input folder.
723
    :type loaderdir: str
724
725
    :param osver: OS version.
726
    :type osver: str
727
728
    :param loadername: Name of final autoloader. Default is auto-generated.
729
    :type loadername: str
730
    """
731 5
    platform = os.listdir(os.path.join(loaderdir, "target", "product"))[0]
732 5
    if loadername is None:
733 5
        loadername = "{0}_autoloader_user-all-{1}".format(platform, osver)
734 5
    return loadername, platform
735
736
737 5
def tcl_download(downloadurl, filename, filesize, filehash):
738
    """
739
    Download autoloader file, rename, and verify.
740
741
    :param downloadurl: Download URL.
742
    :type downloadurl: str
743
744
    :param filename: Name of autoloader file.
745
    :type filename: str
746
747
    :param filesize: Size of autoloader file.
748
    :type filesize: str
749
750
    :param filehash: SHA-1 hash of autoloader file.
751
    :type filehash: str
752
    """
753 5
    print("FILENAME: {0}".format(filename))
754 5
    print("LENGTH: {0}".format(utilities.fsizer(filesize)))
755 5
    networkutils.download(downloadurl)
756 5
    print("DOWNLOAD COMPLETE")
757 5
    os.rename(downloadurl.split("/")[-1], filename)
758 5
    method = hashutils.get_engine("sha1")
759 5
    shahash = hashutils.hashlib_hash(filename, method)
760 5
    if shahash == filehash:
761 5
        print("HASH CHECK OK")
762
    else:
763 5
        print(shahash)
764 5
        print("HASH FAILED!")
765
766
767 5
def tcl_prd_scan(curef, download=False, mode=4, fvver="AAM481"):
768
    """
769
    Scan one PRD and produce download URL and filename.
770
771
    :param curef: PRD of the phone variant to check.
772
    :type curef: str
773
774
    :param download: If we'll download the file that this returns. Default is False.
775
    :type download: bool
776
777
    :param mode: 4 if downloading autoloaders, 2 if downloading OTA deltas.
778
    :type mode: int
779
780
    :param fvver: Initial software version, must be specific if downloading OTA deltas.
781
    :type fvver: str
782
    """
783 5
    sess = requests.Session()
784 5
    ctext = networkutils.tcl_check(curef, sess, mode, fvver)
785 5
    if ctext is None:
786 5
        raise SystemExit
787 5
    tvver, firmwareid, filename, filesize, filehash = networkutils.parse_tcl_check(ctext)
788 5
    salt = networkutils.tcl_salt()
789 5
    vkhsh = networkutils.vkhash(curef, tvver, firmwareid, salt, mode, fvver)
790 5
    updatetext = networkutils.tcl_download_request(curef, tvver, firmwareid, salt, vkhsh, sess, mode, fvver)
791 5
    downloadurl, encslave = networkutils.parse_tcl_download_request(updatetext)
792 5
    statcode = networkutils.getcode(downloadurl, sess)
793 5
    tcl_prd_print(downloadurl, filename, statcode, encslave, sess)
794 5
    if statcode == 200 and download:
795 5
        tcl_download(downloadurl, filename, filesize, filehash)
796
797
798 5
def tcl_prd_print(downloadurl, filename, statcode, encslave, session):
799
    """
800
    :param downloadurl: File to download.
801
    :type downloadurl: str
802
803
    :param filename: File name from download URL.
804
    :type filename: str
805
806
    :param statcode: Status code of download URL.
807
    :type statcode: int
808
809
    :param encslave: Server hosting header script.
810
    :type encslave: str
811
812
    :param session: Session object.
813
    :type session: requests.Session
814
    """
815 5
    print("{0}: HTTP {1}".format(filename, statcode))
816 5
    print(downloadurl)
817 5
    if encslave is not None:
818 5
        address = "/{0}".format(downloadurl.split("/", 3)[3:][0])
819 5
        print("CHECKING HEADER...")
820 5
        sentinel = networkutils.encrypt_header(address, encslave, session)
821 5
        if sentinel is not None:
822 5
            print(sentinel)
823
824
825 5
def linkgen_sdk_dicter(indict, origtext, newtext):
826
    """
827
    Prepare SDK radio/OS dictionaries.
828
829
    :param indict: Dictionary of radio and OS pairs.
830
    :type: dict(str:str)
831
832
    :param origtext: String in indict's values that must be replaced.
833
    :type origtext: str
834
835
    :param newtext: What to replace origtext with.
836
    :type newtext: str
837
    """
838 5
    return {key: val.replace(origtext, newtext) for key, val in indict.items()}
839
840
841 5
def linkgen_sdk(sdk, oses, cores):
842
    """
843
    Generate SDK debrick/core images.
844
845
    :param sdk: If we specifically want SDK images. Default is False.
846
    :type sdk: bool
847
848
    :param oses: Dictionary of radio and debrick pairs.
849
    :type oses: dict(str:str)
850
851
    :param cores: Dictionary of radio and core pairs.
852
    :type cores: dict(str:str)
853
    """
854 5
    if sdk:
855 5
        oses2 = linkgen_sdk_dicter(oses, "factory_sfi", "sdk")
856 5
        cores2 = linkgen_sdk_dicter(cores, "factory_sfi", "sdk")
857 5
        oses = linkgen_sdk_dicter(oses2, "verizon_sfi", "sdk")
858 5
        cores = linkgen_sdk_dicter(cores2, "verizon_sfi", "sdk")
859 5
    return oses, cores
860
861
862 5
def linkgen(osversion, radioversion=None, softwareversion=None, altsw=None, temp=False, sdk=False):
863
    """
864
    Generate debrick/core/radio links for given OS, radio, software release.
865
866
    :param osversion: OS version, 10.x.y.zzzz.
867
    :type osversion: str
868
869
    :param radioversion: Radio version, 10.x.y.zzzz. Can be guessed.
870
    :type radioversion: str
871
872
    :param softwareversion: Software version, 10.x.y.zzzz. Can be guessed.
873
    :type softwareversion: str
874
875
    :param altsw: Radio software release, if not the same as OS.
876
    :type altsw: str
877
878
    :param temp: If file we write to is temporary. Default is False.
879
    :type temp: bool
880
881
    :param sdk: If we specifically want SDK images. Default is False.
882
    :type sdk: bool
883
    """
884 5
    radioversion = return_radio_version(osversion, radioversion)
885 5
    softwareversion, swc = return_sw_checked(softwareversion, osversion)
886 5
    del swc
887 5
    if altsw is not None:
888 5
        altsw, aswc = return_radio_sw_checked(altsw, radioversion)
889 5
        del aswc
890 5
    baseurl = utilities.create_base_url(softwareversion)
891 5
    oses, cores, radios = textgenerator.url_gen(osversion, radioversion, softwareversion)
892 5
    if altsw is not None:
893 5
        del radios
894 5
        dbks, cors, radios = textgenerator.url_gen(osversion, radioversion, altsw)
895 5
        del dbks
896 5
        del cors
897 5
    avlty = networkutils.availability(baseurl)
898 5
    oses, cores = linkgen_sdk(sdk, oses, cores)
899 5
    prargs = (softwareversion, osversion, radioversion, oses, cores, radios, avlty, False, None, temp, altsw)
900 5
    lthr = threading.Thread(target=textgenerator.write_links, args=prargs)
901 5
    lthr.start()
902
903
904 5
def clean_swrel(swrelset):
905
    """
906
    Clean a list of software release lookups.
907
908
    :param swrelset: List of software releases.
909
    :type swrelset: set(str)
910
    """
911 5
    for i in swrelset:
912 5
        if i != "SR not in system" and i is not None:
913 5
            swrelease = i
914 5
            break
915
    else:
916 5
        swrelease = ""
917 5
    return swrelease
918
919
920 5
def autolookup_logger(record, out):
921
    """
922
    Write autolookup results to file.
923
924
    :param record: The file to log to.
925
    :type record: str
926
927
    :param out: Output block.
928
    :type out: str
929
    """
930 5
    with open(record, "a") as rec:
931 5
        rec.write("{0}\n".format(out))
932
933
934 5
def autolookup_printer(out, avail, log=False, quiet=False, record=None):
935
    """
936
    Print autolookup results, logging if specified.
937
938
    :param out: Output block.
939
    :type out: str
940
941
    :param avail: Availability. Can be "Available" or "Unavailable".
942
    :type avail: str
943
944
    :param log: If we're logging to file.
945
    :type log: bool
946
947
    :param quiet: If we only note available entries.
948
    :type quiet: bool
949
950
    :param record: If we're logging, the file to log to.
951
    :type record: str
952
    """
953 5
    if not quiet:
954 5
        avail = "Available"  # force things
955 5
    if avail.lower() == "available":
956 5
        if log:
957 5
            lthr = threading.Thread(target=autolookup_logger, args=(record, out))
958 5
            lthr.start()
959 5
        print(out)
960
961
962 5
def autolookup_output_sql(osversion, swrelease, avail, sql=False):
963
    """
964
    Add OS to SQL database.
965
966
    :param osversion: OS version.
967
    :type osversion: str
968
969
    :param swrelease: Software release.
970
    :type swrelease: str
971
972
    :param avail: "Unavailable" or "Available".
973
    :type avail: str
974
975
    :param sql: If we're adding this to our SQL database.
976
    :type sql: bool
977
    """
978 5
    if sql:
979 5
        sqlutils.prepare_sw_db()
980 5
        if not sqlutils.check_exists(osversion, swrelease):
981 5
            sqlutils.insert(osversion, swrelease, avail.lower())
982
983
984 5
def autolookup_output(osversion, swrelease, avail, avpack, sql=False):
985
    """
986
    Prepare autolookup block, and add to SQL database.
987
988
    :param osversion: OS version.
989
    :type osversion: str
990
991
    :param swrelease: Software release.
992
    :type swrelease: str
993
994
    :param avail: "Unavailable" or "Available".
995
    :type avail: str
996
997
    :param avpack: Availabilities: alpha 1 and 2, beta 1 and 2, production.
998
    :type avpack: list(str)
999
1000
    :param sql: If we're adding this to our SQL database.
1001
    :type sql: bool
1002
    """
1003 5
    othr = threading.Thread(target=autolookup_output_sql, args=(osversion, swrelease, avail, sql))
1004 5
    othr.start()
1005 5
    avblok = "[{0}|{1}|{2}|{3}|{4}]".format(*avpack)
1006 5
    out = "OS {0} - SR {1} - {2} - {3}".format(osversion, swrelease, avblok, avail)
1007 5
    return out
1008
1009
1010 5
def clean_barlist(cleanfiles, stoppers):
1011
    """
1012
    Remove certain bars from barlist based on keywords.
1013
1014
    :param cleanfiles: List of files to clean.
1015
    :type cleanfiles: list(str)
1016
1017
    :param stoppers: List of keywords (i.e. bar names) to exclude.
1018
    :type stoppers: list(str)
1019
    """
1020 5
    finals = [link for link in cleanfiles if all(word not in link for word in stoppers)]
1021 5
    return finals
1022
1023
1024 5
def prep_export_cchecker(files, npc, hwid, osv, radv, swv, upgrade=False, forced=None):
1025
    """
1026
    Prepare carrierchecker lookup links to write to file.
1027
1028
    :param files: List of file URLs.
1029
    :type files: list(str)
1030
1031
    :param npc: MCC + MNC (ex. 302220).
1032
    :type npc: int
1033
1034
    :param hwid: Device hardware ID.
1035
    :type hwid: str
1036
1037
    :param osv: OS version.
1038
    :type osv: str
1039
1040
    :param radv: Radio version.
1041
    :type radv: str
1042
1043
    :param swv: Software release.
1044
    :type swv: str
1045
1046
    :param upgrade: Whether or not to use upgrade files. Default is false.
1047
    :type upgrade: bool
1048
1049
    :param forced: Force a software release. None to go for latest.
1050
    :type forced: str
1051
    """
1052 5
    if not upgrade:
1053 5
        newfiles = networkutils.carrier_query(npc, hwid, True, False, forced)
1054 5
        cleanfiles = newfiles[3]
1055
    else:
1056 5
        cleanfiles = files
1057 5
    osurls, coreurls, radiourls = textgenerator.url_gen(osv, radv, swv)
1058 5
    stoppers = ["8960", "8930", "8974", "m5730", "winchester"]
1059 5
    finals = clean_barlist(cleanfiles, stoppers)
1060 5
    return osurls, coreurls, radiourls, finals
1061
1062
1063 5
def export_cchecker(files, npc, hwid, osv, radv, swv, upgrade=False, forced=None):
1064
    """
1065
    Write carrierchecker lookup links to file.
1066
1067
    :param files: List of file URLs.
1068
    :type files: list(str)
1069
1070
    :param npc: MCC + MNC (ex. 302220).
1071
    :type npc: int
1072
1073
    :param hwid: Device hardware ID.
1074
    :type hwid: str
1075
1076
    :param osv: OS version.
1077
    :type osv: str
1078
1079
    :param radv: Radio version.
1080
    :type radv: str
1081
1082
    :param swv: Software release.
1083
    :type swv: str
1084
1085
    :param upgrade: Whether or not to use upgrade files. Default is false.
1086
    :type upgrade: bool
1087
1088
    :param forced: Force a software release. None to go for latest.
1089
    :type forced: str
1090
    """
1091 5
    if files:
1092 5
        osurls, coreurls, radiourls, finals = prep_export_cchecker(files, npc, hwid, osv, radv, swv, upgrade, forced)
1093 5
        textgenerator.write_links(swv, osv, radv, osurls, coreurls, radiourls, True, True, finals)
1094 5
        print("\nFINISHED!!!")
1095
    else:
1096 5
        print("CANNOT EXPORT, NO SOFTWARE RELEASE")
1097
1098
1099 5
def generate_blitz_links(files, osv, radv, swv):
1100
    """
1101
    Generate blitz URLs (i.e. all OS and radio links).
1102
    :param files: List of file URLs.
1103
    :type files: list(str)
1104
1105
    :param osv: OS version.
1106
    :type osv: str
1107
1108
    :param radv: Radio version.
1109
    :type radv: str
1110
1111
    :param swv: Software release.
1112
    :type swv: str
1113
    """
1114 5
    coreurls = [
1115
        utilities.create_bar_url(swv, "winchester.factory_sfi", osv),
1116
        utilities.create_bar_url(swv, "qc8960.factory_sfi", osv),
1117
        utilities.create_bar_url(swv, "qc8960.factory_sfi", osv),
1118
        utilities.create_bar_url(swv, "qc8960.factory_sfi_hybrid_qc8974", osv)
1119
    ]
1120 5
    radiourls = [
1121
        utilities.create_bar_url(swv, "m5730", radv),
1122
        utilities.create_bar_url(swv, "qc8960", radv),
1123
        utilities.create_bar_url(swv, "qc8960.wtr", radv),
1124
        utilities.create_bar_url(swv, "qc8960.wtr5", radv),
1125
        utilities.create_bar_url(swv, "qc8930.wtr5", radv),
1126
        utilities.create_bar_url(swv, "qc8974.wtr2", radv)
1127
    ]
1128 5
    return files + coreurls + radiourls
1129
1130
1131 5
def package_blitz(bardir, swv):
1132
    """
1133
    Package and verify a blitz package.
1134
1135
    :param bardir: Path to folder containing bar files.
1136
    :type bardir: str
1137
1138
    :param swv: Software version.
1139
    :type swv: str
1140
    """
1141 5
    print("\nCREATING BLITZ...")
1142 5
    barutils.create_blitz(bardir, swv)
1143 5
    print("\nTESTING BLITZ...")
1144 5
    zipver = archiveutils.zip_verify("Blitz-{0}.zip".format(swv))
1145 5
    if not zipver:
1146 5
        print("BLITZ FILE IS BROKEN")
1147 5
        raise SystemExit
1148
    else:
1149 5
        shutil.rmtree(bardir)
1150
1151
1152 5
def slim_preamble(appname):
1153
    """
1154
    Standard app name header.
1155
1156
    :param appname: Name of app.
1157
    :type appname: str
1158
    """
1159 5
    print("~~~{0} VERSION {1}~~~".format(appname.upper(), shortversion()))
1160
1161
1162 5
def standard_preamble(appname, osversion, softwareversion, radioversion, altsw=None):
1163
    """
1164
    Standard app name, OS, radio and software (plus optional radio software) print block.
1165
1166
    :param appname: Name of app.
1167
    :type appname: str
1168
1169
    :param osversion: OS version, 10.x.y.zzzz. Required.
1170
    :type osversion: str
1171
1172
    :param radioversion: Radio version, 10.x.y.zzzz. Can be guessed.
1173
    :type radioversion: str
1174
1175
    :param softwareversion: Software release, 10.x.y.zzzz. Can be guessed.
1176
    :type softwareversion: str
1177
1178
    :param altsw: Radio software release, if not the same as OS.
1179
    :type altsw: str
1180
    """
1181 5
    slim_preamble(appname)
1182 5
    print("OS VERSION: {0}".format(osversion))
1183 5
    print("OS SOFTWARE VERSION: {0}".format(softwareversion))
1184 5
    print("RADIO VERSION: {0}".format(radioversion))
1185 5
    if altsw is not None:
1186 5
        print("RADIO SOFTWARE VERSION: {0}".format(altsw))
1187
1188
1189 5
def questionnaire_device(message=None):
1190
    """
1191
    Get device from questionnaire.
1192
    """
1193 5
    message = "DEVICE (XXX100-#): " if message is None else message
1194 5
    device = input(message)
1195 5
    if not device:
1196 5
        print("NO DEVICE SPECIFIED!")
1197 5
        decorators.enter_to_exit(True)
1198 5
        if not getattr(sys, 'frozen', False):
1199 5
            raise SystemExit
1200 5
    return device
1201
1202
1203 5
def verify_gpg_credentials():
1204
    """
1205
    Read GPG key/pass from file, verify if incomplete.
1206
    """
1207 5
    gpgkey, gpgpass = gpgutils.gpg_config_loader()
1208 5
    if gpgkey is None or gpgpass is None:
1209 5
        print("NO PGP KEY/PASS FOUND")
1210 5
        cont = utilities.s2b(input("CONTINUE (Y/N)?: "))
1211 5
        if cont:
1212 5
            gpgkey = verify_gpg_key(gpgkey)
1213 5
            gpgpass, writebool = verify_gpg_pass(gpgpass)
1214 5
            gpgpass2 = gpgpass if writebool else None
1215 5
            gpgutils.gpg_config_writer(gpgkey, gpgpass2)
1216
        else:
1217 5
            gpgkey = None
1218 5
    return gpgkey, gpgpass
1219
1220
1221 5
def verify_gpg_key(gpgkey=None):
1222
    """
1223
    Verify GPG key.
1224
1225
    :param gpgkey: Key, use None to take from input.
1226
    :type gpgkey: str
1227
    """
1228 5
    if gpgkey is None:
1229 5
        gpgkey = input("PGP KEY (0x12345678): ")
1230 5
        if not gpgkey.startswith("0x"):
1231 5
            gpgkey = "0x{0}".format(gpgkey)   # add preceding 0x
1232 5
    return gpgkey
1233
1234
1235 5
def verify_gpg_pass(gpgpass=None):
1236
    """
1237
    Verify GPG passphrase.
1238
1239
    :param gpgpass: Passphrase, use None to take from input.
1240
    :type gpgpass: str
1241
    """
1242 5
    if gpgpass is None:
1243 5
        gpgpass = getpass.getpass(prompt="PGP PASSPHRASE: ")
1244 5
        writebool = utilities.s2b(input("SAVE PASSPHRASE (Y/N)?:"))
1245
    else:
1246 5
        writebool = False
1247 5
    return gpgpass, writebool
1248
1249
1250 5
def bulk_hash(dirs, compressed=True, deleted=True, radios=True, hashdict=None):
1251
    """
1252
    Hash files in several folders based on flags.
1253
1254
    :param dirs: Folders: [OS_bars, radio_bars, OS_exes, radio_exes, OS_zips, radio_zips]
1255
    :type dirs: list(str)
1256
1257
    :param compressed: Whether to hash compressed files. True by default.
1258
    :type compressed: bool
1259
1260
    :param deleted: Whether to delete uncompressed files. True by default.
1261
    :type deleted: bool
1262
1263
    :param radios: Whether to hash radio autoloaders. True by default.
1264
    :type radios: bool
1265
1266
    :param hashdict: Dictionary of hash rules, in ~\bbarchivist.ini.
1267
    :type hashdict: dict({str: bool})
1268
    """
1269 5
    print("HASHING LOADERS...")
1270 5
    utilities.cond_check(hashutils.verifier, utilities.def_args(dirs), [hashdict], radios, compressed, deleted)
1271
1272
1273 5
def bulk_verify(dirs, compressed=True, deleted=True, radios=True):
1274
    """
1275
    Verify files in several folders based on flags.
1276
1277
    :param dirs: Folders: [OS_bars, radio_bars, OS_exes, radio_exes, OS_zips, radio_zips]
1278
    :type dirs: list(str)
1279
1280
    :param compressed: Whether to hash compressed files. True by default.
1281
    :type compressed: bool
1282
1283
    :param deleted: Whether to delete uncompressed files. True by default.
1284
    :type deleted: bool
1285
1286
    :param radios: Whether to hash radio autoloaders. True by default.
1287
    :type radios: bool
1288
    """
1289 5
    gpgkey, gpgpass = verify_gpg_credentials()
1290 5
    if gpgpass is not None and gpgkey is not None:
1291 5
        print("VERIFYING LOADERS...")
1292 5
        print("KEY: {0}".format(gpgkey))
1293 5
        restargs = [gpgkey, gpgpass, True]
1294 5
        utilities.cond_check(gpgutils.gpgrunner, utilities.def_args(dirs), restargs, radios, compressed, deleted)
1295
1296
1297 5
def enn_ayy(quant):
1298
    """
1299
    Cheeky way to put a N/A placeholder for a string.
1300
1301
    :param quant: What to check if it's None.
1302
    :type quant: str
1303
    """
1304 5
    return "N/A" if quant is None else quant
1305
1306
1307 5
def generate_workfolder(folder=None):
1308
    """
1309
    Check if a folder exists, make it if it doesn't, set it to home if None.
1310
1311
    :param folder: Folder to check.
1312
    :type folder: str
1313
    """
1314 5
    folder = utilities.dirhandler(folder, os.getcwd())
1315 5
    if folder is not None and not os.path.exists(folder):
1316 5
        os.makedirs(folder)
1317 5
    return folder
1318
1319
1320 5
def info_header(afile, osver, radio=None, software=None, device=None):
1321
    """
1322
    Write header for info file.
1323
1324
    :param afile: Open file to write to.
1325
    :type afile: File object
1326
1327
    :param osver: OS version, required for both types.
1328
    :type osver: str
1329
1330
    :param radio: Radio version, required for QNX.
1331
    :type radio: str
1332
1333
    :param software: Software release, required for QNX.
1334
    :type software: str
1335
1336
    :param device: Device type, required for Android.
1337
    :type device: str
1338
    """
1339 5
    afile.write("OS: {0}\n".format(osver))
1340 5
    if device:
1341 5
        afile.write("Device: {0}\n".format(enn_ayy(device)))
1342
    else:
1343 5
        afile.write("Radio: {0}\n".format(enn_ayy(radio)))
1344 5
        afile.write("Software: {0}\n".format(enn_ayy(software)))
1345 5
    afile.write("{0}\n".format("~"*40))
1346
1347
1348 5
def prep_info(filepath, osver, device=None):
1349
    """
1350
    Prepare file list for new-style info file.
1351
1352
    :param filepath: Path to folder to analyze.
1353
    :type filepath: str
1354
1355
    :param osver: OS version, required for both types.
1356
    :type osver: str
1357
1358
    :param device: Device type, required for Android.
1359
    :type device: str
1360
    """
1361 5
    fileext = ".zip" if device else ".7z"
1362 5
    files = os.listdir(filepath)
1363 5
    absfiles = [os.path.join(filepath, x) for x in files if x.endswith((fileext, ".exe"))]
1364 5
    fname = os.path.join(filepath, "!{0}_OSINFO!.txt".format(osver))
1365 5
    return fname, absfiles
1366
1367
1368 5
def make_info(filepath, osver, radio=None, software=None, device=None):
1369
    """
1370
    Create a new-style info (names, sizes and hashes) file.
1371
1372
    :param filepath: Path to folder to analyze.
1373
    :type filepath: str
1374
1375
    :param osver: OS version, required for both types.
1376
    :type osver: str
1377
1378
    :param radio: Radio version, required for QNX.
1379
    :type radio: str
1380
1381
    :param software: Software release, required for QNX.
1382
    :type software: str
1383
1384
    :param device: Device type, required for Android.
1385
    :type device: str
1386
    """
1387 5
    fname, absfiles = prep_info(filepath, osver, device)
1388 5
    with open(fname, "w") as afile:
1389 5
        info_header(afile, osver, radio, software, device)
1390 5
        for indx, file in enumerate(absfiles):
1391 5
            write_info(file, indx, len(absfiles), afile)
1392
1393
1394 5
def write_info(infile, index, filecount, outfile):
1395
    """
1396
    Write a new-style info (names, sizes and hashes) file.
1397
1398
    :param infile: Path to file whose name, size and hash are to be written.
1399
    :type infile: str
1400
1401
    :param index: Which file index out of the list of files we're writing.
1402
    :type index: int
1403
1404
    :param filecount: Total number of files we're to write; for excluding terminal newline.
1405
    :type filecount: int
1406
1407
    :param outfile: Open (!!!) file handle. Output file.
1408
    :type outfile: str
1409
    """
1410 5
    fsize = os.stat(infile).st_size
1411 5
    outfile.write("File: {0}\n".format(os.path.basename(infile)))
1412 5
    outfile.write("\tSize: {0} ({1})\n".format(fsize, utilities.fsizer(fsize)))
1413 5
    outfile.write("\tHashes:\n")
1414 5
    outfile.write("\t\tMD5: {0}\n".format(hashutils.hashlib_hash(infile, hashlib.md5()).upper()))
1415 5
    outfile.write("\t\tSHA1: {0}\n".format(hashutils.hashlib_hash(infile, hashlib.sha1()).upper()))
1416 5
    outfile.write("\t\tSHA256: {0}\n".format(hashutils.hashlib_hash(infile, hashlib.sha256()).upper()))
1417 5
    outfile.write("\t\tSHA512: {0}\n".format(hashutils.hashlib_hash(infile, hashlib.sha512()).upper()))
1418 5
    if index != filecount - 1:
1419 5
        outfile.write("\n")
1420
1421
1422 5
def bulk_info(dirs, osv, compressed=True, deleted=True, radios=True, rad=None, swv=None, dev=None):
1423
    """
1424
    Generate info files in several folders based on flags.
1425
1426
    :param dirs: Folders: [OS_bars, radio_bars, OS_exes, radio_exes, OS_zips, radio_zips]
1427
    :type dirs: list(str)
1428
1429
    :param osver: OS version, required for both types.
1430
    :type osver: str
1431
1432
    :param compressed: Whether to hash compressed files. True by default.
1433
    :type compressed: bool
1434
1435
    :param deleted: Whether to delete uncompressed files. True by default.
1436
    :type deleted: bool
1437
1438
    :param radios: Whether to hash radio autoloaders. True by default.
1439
    :type radios: bool
1440
1441
    :param rad: Radio version, required for QNX.
1442
    :type rad: str
1443
1444
    :param swv: Software release, required for QNX.
1445
    :type swv: str
1446
1447
    :param dev: Device type, required for Android.
1448
    :type dev: str
1449
    """
1450 5
    print("GENERATING INFO FILES...")
1451 5
    restargs = [osv, rad, swv, dev]
1452
    utilities.cond_check(make_info, utilities.def_args(dirs), restargs, radios, compressed, deleted)
1453