Completed
Push — master ( 2df547...733f1c )
by John
01:24
created

bulk_droid_skeletons()   B

Complexity

Conditions 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
dl 0
loc 23
rs 8.7972
c 0
b 0
f 0
1
#!/usr/bin/env python3
2
"""This module is used for network connections; APIs, downloading, etc."""
3
4
import os  # filesystem read
5
import xml.etree.ElementTree  # XML parsing
6
import re  # regexes
7
import hashlib  # base url creation
8
import concurrent.futures  # multiprocessing/threading
9
import glob  # pem file lookup
10
import requests  # downloading
11
from bs4 import BeautifulSoup  # scraping
12
from bbarchivist import utilities  # parse filesize
13
from bbarchivist.bbconstants import SERVERS  # lookup servers
14
15
__author__ = "Thurask"
16
__license__ = "WTFPL v2"
17
__copyright__ = "Copyright 2015-2016 Thurask"
18
19
20
def grab_pem():
21
    """
22
    Work with either local cacerts or system cacerts. Since cx_freeze is dumb.
23
    """
24
    try:
25
        pemfile = glob.glob(os.path.join(os.getcwd(), "cacert.pem"))[0]
26
    except IndexError:
27
        return requests.certs.where()  # no local cacerts
28
    else:
29
        return os.path.abspath(pemfile)  # local cacerts
30
31
32
def pem_wrapper(method):
33
    """
34
    Decorator to set REQUESTS_CA_BUNDLE.
35
36
    :param method: Method to use.
37
    :type method: function
38
    """
39
    def wrapper(*args, **kwargs):
40
        """
41
        Set REQUESTS_CA_BUNDLE before doing function.
42
        """
43
        os.environ["REQUESTS_CA_BUNDLE"] = grab_pem()
44
        return method(*args, **kwargs)
45
    return wrapper
46
47
48
@pem_wrapper
49
def get_length(url):
50
    """
51
    Get content-length header from some URL.
52
53
    :param url: The URL to check.
54
    :type url: str
55
    """
56
    if url is None:
57
        return 0
58
    try:
59
        heads = requests.head(url)
60
        fsize = heads.headers['content-length']
61
        return int(fsize)
62
    except requests.ConnectionError:
63
        return 0
64
65
66
@pem_wrapper
67
def download(url, output_directory=None):
68
    """
69
    Download file from given URL.
70
71
    :param url: URL to download from.
72
    :type url: str
73
74
    :param output_directory: Download folder. Default is local.
75
    :type output_directory: str
76
    """
77
    if output_directory is None:
78
        output_directory = os.getcwd()
79
    lfname = url.split('/')[-1]
80
    sname = utilities.stripper(lfname)
81
    fname = os.path.join(output_directory, lfname)
82
    with open(fname, "wb") as file:
83
        req = requests.get(url, stream=True)
84
        clength = req.headers['content-length']
85
        fsize = utilities.fsizer(clength)
86
        if req.status_code == 200:  # 200 OK
87
            print("DOWNLOADING {0} [{1}]".format(sname, fsize))
88
            for chunk in req.iter_content(chunk_size=1024):
89
                file.write(chunk)
90
        else:
91
            print("ERROR: HTTP {0} IN {1}".format(req.status_code, lfname))
92
    if os.stat(fname).st_size == 0:
93
        os.remove(fname)
94
95
def download_bootstrap(urls, outdir=None, workers=5):
96
    """
97
    Run downloaders for each file in given URL iterable.
98
99
    :param urls: URLs to download.
100
    :type urls: list
101
102
    :param outdir: Download folder. Default is handled in :func:`download`.
103
    :type outdir: str
104
105
    :param workers: Number of worker processes. Default is 5.
106
    :type workers: int
107
    """
108
    workers = len(urls) if len(urls) < workers else workers
109
    spinman = utilities.SpinManager()
110
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as xec:
111
        try:
112
            spinman.start()
113
            for url in urls:
114
                xec.submit(download, url, outdir)
115
        except (KeyboardInterrupt, SystemExit):
116
            xec.shutdown()
117
            spinman.stop()
118
    spinman.stop()
119
    utilities.spinner_clear()
120
    utilities.line_begin()
121
122
123
def create_base_url(softwareversion):
124
    """
125
    Make the root URL for production server files.
126
127
    :param softwareversion: Software version to hash.
128
    :type softwareversion: str
129
    """
130
    # Hash software version
131
    swhash = hashlib.sha1(softwareversion.encode('utf-8'))
132
    hashedsoftwareversion = swhash.hexdigest()
133
    # Root of all urls
134
    baseurl = "http://cdn.fs.sl.blackberry.com/fs/qnx/production/" + hashedsoftwareversion
135
    return baseurl
136
137
138
@pem_wrapper
139
def availability(url):
140
    """
141
    Check HTTP status code of given URL.
142
    200 or 301-308 is OK, else is not.
143
144
    :param url: URL to check.
145
    :type url: str
146
    """
147
    try:
148
        avlty = requests.head(url)
149
        status = int(avlty.status_code)
150
        return status == 200 or 300 < status <= 308
151
    except requests.ConnectionError:
152
        return False
153
154
155
def clean_availability(results, server):
156
    """
157
    Clean availability for autolookup script.
158
159
    :param results: Result dict.
160
    :type results: dict(str: str)
161
162
    :param server: Server, key for result dict.
163
    :type server: str
164
    """
165
    marker = "PD" if server == "p" else server.upper()
166
    rel = results[server.lower()]
167
    avail = marker if rel != "SR not in system" and rel is not None else "  "
168
    return rel, avail
169
170
171
@pem_wrapper
172
def carrier_checker(mcc, mnc):
173
    """
174
    Query BlackBerry World to map a MCC and a MNC to a country and carrier.
175
176
    :param mcc: Country code.
177
    :type mcc: int
178
179
    :param mnc: Network code.
180
    :type mnc: int
181
    """
182
    url = "http://appworld.blackberry.com/ClientAPI/checkcarrier?homemcc={0}&homemnc={1}&devicevendorid=-1&pin=0".format(
1 ignored issue
show
Coding Style introduced by
This line is too long as per the coding-style (121/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
183
        mcc, mnc)
184
    user_agent = {'User-agent': 'AppWorld/5.1.0.60'}
185
    req = requests.get(url, headers=user_agent)
186
    root = xml.etree.ElementTree.fromstring(req.text)
187
    for child in root:
188
        if child.tag == "country":
189
            country = child.get("name")
190
        if child.tag == "carrier":
191
            carrier = child.get("name")
192
    return country, carrier
193
194
195
def return_npc(mcc, mnc):
196
    """
197
    Format MCC and MNC into a NPC.
198
199
    :param mcc: Country code.
200
    :type mcc: int
201
202
    :param mnc: Network code.
203
    :type mnc: int
204
    """
205
    return "{0}{1}30".format(str(mcc).zfill(3), str(mnc).zfill(3))
206
207
208
@pem_wrapper
209
def carrier_query(npc, device, upgrade=False, blitz=False, forced=None):
210
    """
211
    Query BlackBerry servers, check which update is out for a carrier.
212
213
    :param npc: MCC + MNC (see `func:return_npc`)
214
    :type npc: int
215
216
    :param device: Hexadecimal hardware ID.
217
    :type device: str
218
219
    :param upgrade: Whether to use upgrade files. False by default.
220
    :type upgrade: bool
221
222
    :param blitz: Whether or not to create a blitz package. False by default.
223
    :type blitz: bool
224
225
    :param forced: Force a software release.
226
    :type forced: str
227
    """
228
    upg = "upgrade" if upgrade else "repair"
229
    forced = "latest" if forced is None else forced
230
    url = "https://cs.sl.blackberry.com/cse/updateDetails/2.2/"
231
    query = '<?xml version="1.0" encoding="UTF-8"?>'
232
    query += '<updateDetailRequest version="2.2.1" authEchoTS="1366644680359">'
233
    query += "<clientProperties>"
234
    query += "<hardware>"
235
    query += "<pin>0x2FFFFFB3</pin><bsn>1128121361</bsn>"
236
    query += "<imei>004401139269240</imei>"
237
    query += "<id>0x{0}</id>".format(device)
238
    query += "</hardware>"
239
    query += "<network>"
240
    query += "<homeNPC>0x{0}</homeNPC>".format(npc)
241
    query += "<iccid>89014104255505565333</iccid>"
242
    query += "</network>"
243
    query += "<software>"
244
    query += "<currentLocale>en_US</currentLocale>"
245
    query += "<legalLocale>en_US</legalLocale>"
246
    query += "</software>"
247
    query += "</clientProperties>"
248
    query += "<updateDirectives>"
249
    query += '<allowPatching type="REDBEND">true</allowPatching>'
250
    query += "<upgradeMode>{0}</upgradeMode>".format(upg)
251
    query += "<provideDescriptions>false</provideDescriptions>"
252
    query += "<provideFiles>true</provideFiles>"
253
    query += "<queryType>NOTIFICATION_CHECK</queryType>"
254
    query += "</updateDirectives>"
255
    query += "<pollType>manual</pollType>"
256
    query += "<resultPackageSetCriteria>"
257
    query += '<softwareRelease softwareReleaseVersion="{0}" />'.format(forced)
258
    query += "<releaseIndependent>"
259
    query += '<packageType operation="include">application</packageType>'
260
    query += "</releaseIndependent>"
261
    query += "</resultPackageSetCriteria>"
262
    query += "</updateDetailRequest>"
263
    header = {"Content-Type": "text/xml;charset=UTF-8"}
264
    req = requests.post(url, headers=header, data=query)
265
    return parse_carrier_xml(req.text, blitz)
266
267
268
def parse_carrier_xml(data, blitz=False):
269
    """
270
    Parse the response to a carrier update request and return the juicy bits.
271
272
    :param data: The data to parse.
273
    :type data: xml
274
275
    :param blitz: Whether or not to create a blitz package. False by default.
276
    :type blitz: bool
277
    """
278
    root = xml.etree.ElementTree.fromstring(data)
279
    sw_exists = root.find('./data/content/softwareReleaseMetadata')
280
    swver = "N/A" if sw_exists is None else ""
281
    if sw_exists is not None:
282
        for child in root.iter("softwareReleaseMetadata"):
283
            swver = child.get("softwareReleaseVersion")
284
    files = []
285
    osver = ""
286
    radver = ""
287
    package_exists = root.find('./data/content/fileSets/fileSet')
288
    if package_exists is not None:
289
        baseurl = "{0}/".format(package_exists.get("url"))
290
        for child in root.iter("package"):
291
            if not blitz:
292
                files.append(baseurl + child.get("path"))
293
            else:
294
                if child.get("type") not in ["system:radio", "system:desktop", "system:os"]:
295
                    files.append(baseurl + child.get("path"))
296
            if child.get("type") == "system:radio":
297
                radver = child.get("version")
298
            if child.get("type") == "system:desktop":
299
                osver = child.get("version")
300
            if child.get("type") == "system:os":
301
                osver = child.get("version")
302
            else:
303
                pass
304
    return(swver, osver, radver, files)
305
306
307
@pem_wrapper
308
def sr_lookup(osver, server):
309
    """
310
    Software release lookup, with choice of server.
311
    :data:`bbarchivist.bbconstants.SERVERLIST` for server list.
312
313
    :param osver: OS version to lookup, 10.x.y.zzzz.
314
    :type osver: str
315
316
    :param server: Server to use.
317
    :type server: str
318
    """
319
    reg = re.compile(r"(\d{1,4}\.)(\d{1,4}\.)(\d{1,4}\.)(\d{1,4})")
320
    query = '<?xml version="1.0" encoding="UTF-8"?>'
321
    query += '<srVersionLookupRequest version="2.0.0"'
322
    query += ' authEchoTS="1366644680359">'
323
    query += '<clientProperties><hardware>'
324
    query += '<pin>0x2FFFFFB3</pin><bsn>1140011878</bsn>'
325
    query += '<imei>004402242176786</imei><id>0x8D00240A</id>'
326
    query += '<isBootROMSecure>true</isBootROMSecure>'
327
    query += '</hardware>'
328
    query += '<network>'
329
    query += '<vendorId>0x0</vendorId><homeNPC>0x60</homeNPC>'
330
    query += '<currentNPC>0x60</currentNPC><ecid>0x1</ecid>'
331
    query += '</network>'
332
    query += '<software><currentLocale>en_US</currentLocale>'
333
    query += '<legalLocale>en_US</legalLocale>'
334
    query += '<osVersion>{0}</osVersion>'.format(osver)
335
    query += '<omadmEnabled>false</omadmEnabled>'
336
    query += '</software></clientProperties>'
337
    query += '</srVersionLookupRequest>'
338
    header = {"Content-Type": "text/xml;charset=UTF-8"}
339
    try:
340
        req = requests.post(server, headers=header, data=query, timeout=1)
341
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
342
        return "SR not in system"
343
    try:
344
        root = xml.etree.ElementTree.fromstring(req.text)
345
    except xml.etree.ElementTree.ParseError:
346
        return "SR not in system"
347
    else:
348
        packages = root.findall('./data/content/')
349
        for package in packages:
350
            if package.text is not None:
351
                match = reg.match(package.text)
352
                if match:
353
                    return package.text
354
                else:
355
                    return "SR not in system"
356
357
358
def sr_lookup_bootstrap(osv):
359
    """
360
    Run lookups for each server for given OS.
361
362
    :param osv: OS to check.
363
    :type osv: str
364
    """
365
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as xec:
366
        try:
367
            results = {
368
                "p": None,
369
                "a1": None,
370
                "a2": None,
371
                "b1": None,
372
                "b2": None
373
            }
374
            for key in results:
375
                results[key] = xec.submit(sr_lookup, osv, SERVERS[key]).result()
376
            return results
377
        except KeyboardInterrupt:
378
            xec.shutdown(wait=False)
379
380
381
@pem_wrapper
382
def available_bundle_lookup(mcc, mnc, device):
383
    """
384
    Check which software releases were ever released for a carrier.
385
386
    :param mcc: Country code.
387
    :type mcc: int
388
389
    :param mnc: Network code.
390
    :type mnc: int
391
392
    :param device: Hexadecimal hardware ID.
393
    :type device: str
394
    """
395
    server = "https://cs.sl.blackberry.com/cse/availableBundles/1.0.0/"
396
    npc = return_npc(mcc, mnc)
397
    query = '<?xml version="1.0" encoding="UTF-8"?>'
398
    query += '<availableBundlesRequest version="1.0.0" '
399
    query += 'authEchoTS="1366644680359">'
400
    query += '<deviceId><pin>0x2FFFFFB3</pin></deviceId>'
401
    query += '<clientProperties><hardware><id>0x{0}</id>'.format(device)
402
    query += '<isBootROMSecure>true</isBootROMSecure></hardware>'
403
    query += '<network><vendorId>0x0</vendorId><homeNPC>0x{0}</homeNPC>'.format(npc)
404
    query += '<currentNPC>0x{0}</currentNPC></network><software>'.format(npc)
405
    query += '<currentLocale>en_US</currentLocale>'
406
    query += '<legalLocale>en_US</legalLocale>'
407
    query += '<osVersion>10.0.0.0</osVersion>'
408
    query += '<radioVersion>10.0.0.0</radioVersion></software>'
409
    query += '</clientProperties><updateDirectives><bundleVersionFilter>'
410
    query += '</bundleVersionFilter></updateDirectives>'
411
    query += '</availableBundlesRequest>'
412
    header = {"Content-Type": "text/xml;charset=UTF-8"}
413
    req = requests.post(server, headers=header, data=query)
414
    root = xml.etree.ElementTree.fromstring(req.text)
415
    package = root.find('./data/content')
416
    bundlelist = [child.attrib["version"] for child in package]
417
    return bundlelist
418
419
420
@pem_wrapper
421
def ptcrb_scraper(ptcrbid):
422
    """
423
    Get the PTCRB results for a given device.
424
425
    :param ptcrbid: Numerical ID from PTCRB (end of URL).
426
    :type ptcrbid: str
427
    """
428
    baseurl = "https://ptcrb.com/vendor/complete/view_complete_request_guest.cfm?modelid={0}".format(
1 ignored issue
show
Coding Style introduced by
This line is too long as per the coding-style (101/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
429
        ptcrbid)
430
    req = requests.get(baseurl)
431
    soup = BeautifulSoup(req.content, 'html.parser')
432
    text = soup.get_text()
433
    text = text.replace("\r\n", " ")
434
    prelimlist = re.findall("OS .+[^\\n]", text, re.IGNORECASE)
435
    if not prelimlist:  # Priv
436
        prelimlist = re.findall(r"[A-Z]{3}[0-9]{3}[\s]", text)
437
    cleanlist = []
438
    for item in prelimlist:
439
        if not item.endswith("\r\n"):  # they should hire QC people...
440
            cleanlist.append(ptcrb_item_cleaner(item))
441
    return cleanlist
442
443
444
def ptcrb_item_cleaner(item):
445
    """
446
    Cleanup poorly formatted PTCRB entries written by an intern.
447
448
    :param item: The item to clean.
449
    :type item: str
450
    """
451
    item = item.replace("<td>", "")
452
    item = item.replace("</td>", "")
453
    item = item.replace("\n", "")
454
    item = item.replace(" (SR", ", SR")
455
    item = re.sub(r"\s?\((.*)$", "", item)
456
    item = re.sub(r"\sSV.*$", "", item)
457
    item = item.replace(")", "")
458
    item = item.replace(". ", ".")
459
    item = item.replace(";", "")
460
    item = item.replace("version", "Version")
461
    item = item.replace("Verison", "Version")
462
    if item.count("OS") > 1:
463
        templist = item.split("OS")
464
        templist[0] = "OS"
465
        item = "".join([templist[0], templist[1]])
466
    item = item.replace("SR", "SW Release")
467
    item = item.replace(" Version:", ":")
468
    item = item.replace("Version ", " ")
469
    item = item.replace(":1", ": 1")
470
    item = item.replace(", ", " ")
471
    item = item.replace("Software", "SW")
472
    item = item.replace("  ", " ")
473
    item = item.replace("OS ", "OS: ")
474
    item = item.replace("Radio ", "Radio: ")
475
    item = item.replace("Release ", "Release: ")
476
    spaclist = item.split(" ")
477
    if len(spaclist) > 1:
478
        while len(spaclist[1]) < 11:
479
            spaclist[1] += " "
480
        while len(spaclist[3]) < 11:
481
            spaclist[3] += " "
482
    else:
483
        spaclist.insert(0, "OS:")
484
    item = " ".join(spaclist)
485
    item = item.strip()
486
    return item
487
488
489
@pem_wrapper
490
def kernel_scraper(utils=False):
491
    """
492
    Scrape BlackBerry's GitHub kernel repo for available branches.
493
494
    :param utils: Check android-utils repo instead of android-linux-kernel. Default is False.
495
    :type utils: bool
496
    """
497
    repo = "android-utils" if utils else "android-linux-kernel"
498
    kernlist = []
499
    for page in range(1, 10):
500
        url = "https://github.com/blackberry/{0}/branches/all?page={1}".format(repo, page)
501
        req = requests.get(url)
502
        soup = BeautifulSoup(req.content, 'html.parser')
503
        if soup.find("div", {"class": "no-results-message"}):
504
            break
505
        else:
506
            text = soup.get_text()
507
            kernlist.extend(re.findall(r"msm[0-9]{4}\/[A-Z0-9]{6}", text, re.IGNORECASE))
508
    return kernlist
509
510
511
def root_generator(folder, build, variant="common"):
512
    """
513
    Generate roots for the SHAxxx hash lookup URLs.
514
515
    :param folder: Dictionary of variant: loader name pairs.
516
    :type folder: dict(str: str)
517
518
    :param build: Build to check, 3 letters + 3 numbers.
519
    :type build: str
520
521
    :param variant: Autoloader variant. Default is "common".
522
    :type variant: str
523
    """
524
    #Priv specific
525
    privx = "bbfoundation/hashfiles_priv/{0}".format(folder[variant])
526
    #DTEK50 specific
527
    dtek50x = "bbSupport/DTEK50" if build[:3] == "AAF" else "bbfoundation/hashfiles_priv/dtek50"
528
    #Pack it up
529
    roots = {"Priv": privx, "DTEK50": dtek50x}
530
    return roots
531
532
533
def make_droid_skeleton(method, build, device, variant="common"):
534
    """
535
    Make an Android autoloader/hash URL.
536
537
    :param method: None for regular OS links, "sha256/512" for SHA256 or 512 hash.
538
    :type method: str
539
540
    :param build: Build to check, 3 letters + 3 numbers.
541
    :type build: str
542
543
    :param device: Device to check.
544
    :type device: str
545
546
    :param variant: Autoloader variant. Default is "common".
547
    :type variant: str
548
    """
549
    folder = {"vzw-vzw": "verizon", "na-att": "att", "na-tmo": "tmo", "common": "default"}
550
    devices = {"Priv": "qc8992", "DTEK50": "qc8952_64_sfi"}
551
    roots = root_generator(folder, build, variant)
552
    base = "bbry_{2}_autoloader_user-{0}-{1}".format(variant, build.upper(), devices[device])
553
    if method is None:
554
        skel = "https://bbapps.download.blackberry.com/Priv/{0}.zip".format(base)
555
    else:
556
        skel = "http://ca.blackberry.com/content/dam/{1}/{0}.{2}sum".format(base, roots[device], method.lower())
1 ignored issue
show
Coding Style introduced by
This line is too long as per the coding-style (112/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
557
    return skel
558
559
560
def bulk_droid_skeletons(devs, build, method=None):
561
    """
562
    Prepare list of Android autoloader/hash URLs.
563
564
    :param devs: List of devices.
565
    :type devs: list(str)
566
567
    :param build: Build to check, 3 letters + 3 numbers.
568
    :type build: str
569
570
    :param method: None for regular OS links, "sha256/512" for SHA256 or 512 hash.
571
    :type method: str
572
    """
573
    carrier_variants = ("common", "vzw-vzw", "na-tmo", "na-att")  # device variants
574
    common_variants = ("common", )  # no Americans
575
    carrier_devices = ("Priv", )  # may this list never expand in the future
576
    skels = []
577
    for dev in devs:
578
        varlist = carrier_variants if dev in carrier_devices else common_variants
579
        for var in varlist:
580
            skel = make_droid_skeleton(method, build, dev, var)
581
            skels.append(skel)
582
    return skels
583
584
585
def prepare_droid_list(device):
586
    """
587
    Convert single devices to a list, if necessary.
588
589
    :param device: Device to check.
590
    :type device: str
591
    """
592
    if isinstance(device, list):
593
        devs = device
594
    else:
595
        devs = []
596
        devs.append(device)
597
    return devs
598
599
600
def droid_scanner(build, device, method=None):
601
    """
602
    Check for Android autoloaders on BlackBerry's site.
603
604
    :param build: Build to check, 3 letters + 3 numbers.
605
    :type build: str
606
607
    :param device: Device to check.
608
    :type device: str
609
610
    :param method: None for regular OS links, "sha256/512" for SHA256 or 512 hash.
611
    :type method: str
612
    """
613
    devs = prepare_droid_list(device)
614
    skels = bulk_droid_skeletons(devs, build, method)
615
    with concurrent.futures.ThreadPoolExecutor(max_workers=len(skels)) as xec:
616
        results = []
617
        for skel in skels:
618
            avail = xec.submit(availability, skel)
619
            if avail.result():
620
                results.append(skel)
621
    return results if results else None
622
623
624
def base_metadata(url):
625
    """
626
    Get BBNDK metadata, base function.
627
    """
628
    req = requests.get(url)
629
    data = req.content
630
    entries = data.split(b"\n")
631
    metadata = [entry.split(b",")[1].decode("utf-8") for entry in entries if entry]
632
    return metadata
633
634
635
def ndk_metadata():
636
    """
637
    Get BBNDK target metadata.
638
    """
639
    data = base_metadata("http://downloads.blackberry.com/upr/developers/update/bbndk/metadata")
640
    metadata = [entry for entry in data if entry.startswith(("10.0", "10.1", "10.2"))]
641
    return metadata
642
643
644
def sim_metadata():
645
    """
646
    Get BBNDK simulator metadata.
647
    """
648
    metadata = base_metadata("http://downloads.blackberry.com/upr/developers/update/bbndk/simulator/simulator_metadata")
1 ignored issue
show
Coding Style introduced by
This line is too long as per the coding-style (120/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
649
    return metadata
650
651
652
def runtime_metadata():
653
    """
654
    Get BBNDK runtime metadata.
655
    """
656
    metadata = base_metadata("http://downloads.blackberry.com/upr/developers/update/bbndk/runtime/runtime_metadata")
1 ignored issue
show
Coding Style introduced by
This line is too long as per the coding-style (116/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
657
    return metadata
658
659
660
def series_generator(osversion):
661
    """
662
    Generate series/branch name from OS version.
663
664
    :param osversion: OS version.
665
    :type osversion: str
666
    """
667
    splits = osversion.split(".")
668
    return "BB{0}_{1}_{2}".format(*splits[0:3])
669
670
671
def devalpha_urls(osversion, skel):
672
    """
673
    Check individual Dev Alpha autoloader URLs.
674
675
    :param osversion: OS version.
676
    :type osversion: str
677
678
    :param skel: Individual skeleton format to try.
679
    :type skel: str
680
    """
681
    url = "http://downloads.blackberry.com/upr/developers/downloads/{0}{1}.exe".format(skel, osversion)
1 ignored issue
show
Coding Style introduced by
This line is too long as per the coding-style (103/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
682
    req = requests.head(url)
683
    if req.status_code == 200:
684
        finals = (url, req.headers["content-length"])
685
    else:
686
        finals = ()
687
    return finals
688
689
690
def devalpha_urls_bootstrap(osversion, skeletons):
691
    """
692
    Get list of valid Dev Alpha autoloader URLs.
693
694
    :param osversion: OS version.
695
    :type osversion: str
696
697
    :param skeletons: List of skeleton formats to try.
698
    :type skeletons: list
699
    """
700
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as xec:
701
        try:
702
            finals = {}
703
            skels = skeletons
704
            for idx, skel in enumerate(skeletons):
705
                if "<SERIES>" in skel:
706
                    skels[idx] = skel.replace("<SERIES>", series_generator(osversion))
707
            for skel in skels:
708
                final = xec.submit(devalpha_urls, osversion, skel).result()
709
                if final:
710
                    finals[final[0]] = final[1]
711
            return finals
712
        except KeyboardInterrupt:
713
            xec.shutdown(wait=False)
714
715
716
def dev_dupe_cleaner(finals):
717
    """
718
    Clean duplicate autoloader entries.
719
720
    :param finals: Dict of URL:content-length pairs.
721
    :type finals: dict(str: str)
722
    """
723
    revo = {}
724
    for key, val in finals.items():
725
        revo.setdefault(val, set()).add(key)
726
    dupelist = [val for key, val in revo.items() if len(val) > 1]
727
    for dupe in dupelist:
728
        for entry in dupe:
729
            if "DevAlpha" in entry:
730
                del finals[entry]
731
    return finals
732