Test Failed
Branch master (c56792)
by John
02:11
created

bbarchivist.scripts.carrierchecker   B

Complexity

Total Complexity 39

Size/Duplication

Total Lines 457
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 219
dl 0
loc 457
rs 8.2857
c 0
b 0
f 0
wmc 39

14 Functions

Rating   Name   Duplication   Size   Complexity  
A carrierchecker_selective() 0 14 2
A forced_args() 0 14 3
A carrierchecker_main() 0 58 2
A carrierchecker_jsonprepare() 0 17 1
B carrierchecker_argfilter() 0 24 3
B carrierchecker_export() 0 38 2
B questionnaire_3digit() 0 12 5
A forced_avail() 0 10 2
A execute_args() 0 18 3
A carrierchecker_bundles() 0 14 1
B questionnaire() 0 21 5
B carrierchecker_download_prep() 0 32 4
B carrierchecker_download() 0 39 3
B grab_args() 0 95 3
1
#!/usr/bin/env python3
2
"""Checks a carrier for an OS version, can download."""
3
4
import os  # file/path operations
5
import sys  # load arguments
6
import webbrowser  # code list
7
8
import requests  # session
9
from bbarchivist import bbconstants  # versions/constants
10
from bbarchivist import decorators  # enter to exit
11
from bbarchivist import jsonutils  # json
12
from bbarchivist import networkutils  # check function
13
from bbarchivist import scriptutils  # default parser
14
from bbarchivist import utilities  # input validation
15
16
__author__ = "Thurask"
17
__license__ = "WTFPL v2"
18
__copyright__ = "2015-2018 Thurask"
19
20
21
def grab_args():
22
    """
23
    Parse arguments from argparse/questionnaire.
24
25
    Invoke :func:`carrierchecker.carrierchecker_main` with those arguments.
26
    """
27
    if len(sys.argv) > 1:
28
        parser = scriptutils.default_parser("bb-cchecker", "Carrier info checking")
29
        parser.add_argument(
30
            "mcc",
31
            help="1-3 digit country code",
32
            type=utilities.valid_carrier,
33
            nargs="?",
34
            default=None)
35
        parser.add_argument(
36
            "mnc",
37
            help="1-3 digit carrier code",
38
            type=utilities.valid_carrier,
39
            nargs="?",
40
            default=None)
41
        parser.add_argument(
42
            "device",
43
            help="'STL100-1', 'SQW100-3', etc.",
44
            nargs="?",
45
            default=None)
46
        parser.add_argument(
47
            "-c", "--codes",
48
            dest="codes",
49
            help="Open browser for MCC/MNC list",
50
            action="store_true",
51
            default=False)
52
        parser.add_argument(
53
            "-a", "--available-bundles",
54
            dest="bundles",
55
            help="Check available bundles",
56
            action="store_true",
57
            default=False)
58
        parser.add_argument(
59
            "-d", "--download",
60
            dest="download",
61
            help="Download files after checking",
62
            action="store_true",
63
            default=False)
64
        parser.add_argument(
65
            "-e", "--export",
66
            dest="export",
67
            help="Export links to files",
68
            action="store_true",
69
            default=False)
70
        parser.add_argument(
71
            "-r", "--repair",
72
            dest="upgrade",
73
            help="Debrick instead of upgrade bars",
74
            action="store_false",
75
            default=True)
76
        parser.add_argument(
77
            "-f", "--folder",
78
            dest="folder",
79
            help="Working folder",
80
            default=None,
81
            metavar="DIR")
82
        parser.add_argument(
83
            "-b", "--blitz",
84
            dest="blitz",
85
            help="Create blitz package",
86
            action="store_true",
87
            default=False)
88
        parser.add_argument(
89
            "--selective",
90
            dest="selective",
91
            help="Skip Nuance/retaildemo",
92
            action="store_true",
93
            default=False)
94
        fgroup = parser.add_mutually_exclusive_group()
95
        fgroup.add_argument(
96
            "-s", "--software-release",
97
            dest="forcedsw",
98
            help="Force SW release (check bundles first!)",
99
            default=None,
100
            metavar="SWRELEASE")
101
        fgroup.add_argument(
102
            "-o", "--os",
103
            dest="forcedos",
104
            help="Force OS (check bundles first!)",
105
            default=None,
106
            metavar="OS")
107
        parser.set_defaults()
108
        args = parser.parse_args(sys.argv[1:])
109
        if args.codes:
110
            webbrowser.open("https://en.wikipedia.org/wiki/Mobile_country_code")
111
        else:
112
            execute_args(args)
113
    else:
114
        questionnaire()
115
    decorators.enter_to_exit(True)
116
117
118
def forced_avail(args):
119
    """
120
    Determine the forced argument after availability checking.
121
122
    :param args: Arguments.
123
    :type args: argparse.Namespace
124
    """
125
    avail = networkutils.sr_lookup(args.forcedos, bbconstants.SERVERS['p'])
126
    forced = avail if avail != "SR not in system" else None
127
    return forced
128
129
130
def forced_args(args):
131
    """
132
    Determine the forced argument.
133
134
    :param args: Arguments.
135
    :type args: argparse.Namespace
136
    """
137
    if utilities.one_and_none(args.forcedsw, args.forcedos):
138
        forced = forced_avail(args)
139
    elif utilities.one_and_none(args.forcedos, args.forcedsw):
140
        forced = args.forcedsw
141
    else:
142
        forced = None
143
    return forced
144
145
146
def execute_args(args):
147
    """
148
    Get args and decide what to do with them.
149
150
    :param args: Arguments.
151
    :type args: argparse.Namespace
152
    """
153
    args.folder = utilities.dirhandler(args.folder, os.getcwd())
154
    if args.blitz:
155
        args.download = True
156
        args.upgrade = True  # blitz takes precedence
157
    if args.bundles:
158
        args.download = False
159
        args.upgrade = False
160
        args.export = False
161
        args.blitz = False
162
    forced = forced_args(args)
163
    carrierchecker_main(args.mcc, args.mnc, args.device, args.download, args.upgrade, args.folder, args.export, args.blitz, args.bundles, forced, args.selective)
164
165
166
def questionnaire_3digit(message):
167
    """
168
    Get MCC/MNC from questionnaire.
169
    """
170
    while True:
171
        try:
172
            trip = int(input("{0}: ".format(message)))
173
        except ValueError:
174
            continue
175
        else:
176
            if trip == utilities.valid_carrier(trip):
177
                return trip
178
179
180
def questionnaire():
181
    """
182
    Questions to ask if no arguments given.
183
    """
184
    mcc = questionnaire_3digit("MCC")
185
    mnc = questionnaire_3digit("MNC")
186
    device = scriptutils.questionnaire_device()
187
    bundles = utilities.i2b("CHECK BUNDLES?: ")
188
    if bundles:
189
        download = False
190
        upgrade = False
191
        export = False
192
        blitz = False
193
    else:
194
        export = utilities.i2b("EXPORT TO FILE?: ")
195
        download = utilities.i2b("DOWNLOAD?: ")
196
        upgrade = False if not download else utilities.i2b("Y=UPGRADE BARS, N=DEBRICK BARS?: ")
197
        blitz = False if not download else (utilities.i2b("CREATE BLITZ?: ") if upgrade else False)
198
    directory = os.getcwd()
199
    print(" ")
200
    carrierchecker_main(mcc, mnc, device, download, upgrade, directory, export, blitz, bundles, None, False)
201
202
203
def carrierchecker_argfilter(mcc, mnc, device, directory):
204
    """
205
    Filter arguments.
206
207
    :param mcc: Country code.
208
    :type mcc: int
209
210
    :param mnc: Network code.
211
    :type mnc: int
212
213
    :param device: Device ID (XXX100-#)
214
    :type device: str
215
216
    :param directory: Where to store files. Default is local directory.
217
    :type directory: str
218
    """
219
    targdir = {"MCC": mcc, "MNC": mnc, "DEVICE": device}
220
    for key, value in targdir.items():
221
        if value is None:
222
            print("INVALID {0}!".format(key))
223
            raise SystemExit
224
    device = device.upper()
225
    directory = utilities.dirhandler(directory, os.getcwd())
226
    return device, directory
227
228
229
def carrierchecker_jsonprepare(mcc, mnc, device):
230
    """
231
    Prepare JSON data.
232
233
    :param mcc: Country code.
234
    :type mcc: int
235
236
    :param mnc: Network code.
237
    :type mnc: int
238
239
    :param device: Device ID (XXX100-#).
240
    :type device: str
241
    """
242
    data = jsonutils.load_json("devices")
243
    model, family, hwid = jsonutils.certchecker_prep(data, device)
244
    country, carrier = networkutils.carrier_checker(mcc, mnc)
245
    return model, family, hwid, country, carrier
246
247
248
def carrierchecker_bundles(mcc, mnc, hwid):
249
    """
250
    :param mcc: Country code.
251
    :type mcc: int
252
253
    :param mnc: Network code.
254
    :type mnc: int
255
256
    :param hwid: Device hardware ID.
257
    :type hwid: str
258
    """
259
    releases = networkutils.available_bundle_lookup(mcc, mnc, hwid)
260
    print("\nAVAILABLE BUNDLES:")
261
    utilities.lprint(releases)
262
263
264
def carrierchecker_selective(files, selective=False):
265
    """
266
    Filter useless bar files.
267
268
    :param files: List of files.
269
    :type files: list(str)
270
271
    :param selective: Whether or not to exclude Nuance/other dross. Default is false.
272
    :type selective: bool
273
    """
274
    if selective:
275
        craplist = jsonutils.load_json("apps_to_remove")
276
        files = scriptutils.clean_barlist(files, craplist)
277
    return files
278
279
280
def carrierchecker_export(mcc, mnc, files, hwid, osv, radv, swv, export=False, upgrade=False, forced=None):
1 ignored issue
show
best-practice introduced by
Too many arguments (10/5)
Loading history...
281
    """
282
    Export files to file.
283
284
    :param mcc: Country code.
285
    :type mcc: int
286
287
    :param mnc: Network code.
288
    :type mnc: int
289
290
    :param files: List of files.
291
    :type files: list(str)
292
293
    :param hwid: Device hardware ID.
294
    :type hwid: str
295
296
    :param osv: OS version, 10.x.y.zzzz.
297
    :type osv: str
298
299
    :param radv: Radio version, 10.x.y.zzzz.
300
    :type radv: str
301
302
    :param swv: Software release, 10.x.y.zzzz.
303
    :type swv: str
304
305
    :param export: Whether or not to write URLs to a file. Default is false.
306
    :type export: bool
307
308
    :param upgrade: Whether or not to use upgrade files. Default is false.
309
    :type upgrade: bool
310
311
    :param forced: Force a software release. None to go for latest.
312
    :type forced: str
313
    """
314
    if export:
315
        print("\nEXPORTING...")
316
        npc = networkutils.return_npc(mcc, mnc)
317
        scriptutils.export_cchecker(files, npc, hwid, osv, radv, swv, upgrade, forced)
318
319
320
def carrierchecker_download_prep(files, directory, osv, radv, swv, family, blitz=False):
1 ignored issue
show
best-practice introduced by
Too many arguments (7/5)
Loading history...
321
    """
322
    Prepare for downloading files.
323
324
    :param files: List of files.
325
    :type files: list(str)
326
327
    :param directory: Where to store files. Default is local directory.
328
    :type directory: str
329
330
    :param osv: OS version, 10.x.y.zzzz.
331
    :type osv: str
332
333
    :param radv: Radio version, 10.x.y.zzzz.
334
    :type radv: str
335
336
    :param swv: Software release, 10.x.y.zzzz.
337
    :type swv: str
338
339
    :param family: Device family.
340
    :type family: str
341
342
    :param blitz: Whether or not to create a blitz package. Default is false.
343
    :type blitz: bool
344
    """
345
    suffix = "-BLITZ" if blitz else "-{0}".format(family)
346
    bardir = os.path.join(directory, "{0}{1}".format(swv, suffix))
347
    if not os.path.exists(bardir):
348
        os.makedirs(bardir)
349
    if blitz:
350
        files = scriptutils.generate_blitz_links(files, osv, radv, swv)
351
    return bardir, files
352
353
354
def carrierchecker_download(files, directory, osv, radv, swv, family, download=False, blitz=False, session=None):
1 ignored issue
show
best-practice introduced by
Too many arguments (9/5)
Loading history...
355
    """
356
    Download files, create blitz if specified.
357
358
    :param files: List of files.
359
    :type files: list(str)
360
361
    :param directory: Where to store files. Default is local directory.
362
    :type directory: str
363
364
    :param osv: OS version, 10.x.y.zzzz.
365
    :type osv: str
366
367
    :param radv: Radio version, 10.x.y.zzzz.
368
    :type radv: str
369
370
    :param swv: Software release, 10.x.y.zzzz.
371
    :type swv: str
372
373
    :param family: Device family.
374
    :type family: str
375
376
    :param download: Whether or not to download. Default is false.
377
    :type download: bool
378
379
    :param blitz: Whether or not to create a blitz package. Default is false.
380
    :type blitz: bool
381
382
    :param session: Requests session object, default is created on the fly.
383
    :type session: requests.Session()
384
    """
385
    if download:
386
        bardir, files = carrierchecker_download_prep(files, directory, osv, radv, swv, family, blitz)
387
        print("\nDOWNLOADING...")
388
        networkutils.download_bootstrap(files, outdir=bardir, session=session)
389
        scriptutils.test_bar_files(bardir, files)
390
        if blitz:
391
            scriptutils.package_blitz(bardir, swv)
392
        print("\nFINISHED!!!")
393
394
395
def carrierchecker_main(mcc, mnc, device, download=False, upgrade=True, directory=None, export=False, blitz=False, bundles=False, forced=None, selective=False):
2 ignored issues
show
best-practice introduced by
Too many arguments (11/5)
Loading history...
Comprehensibility introduced by
This function exceeds the maximum number of variables (22/15).
Loading history...
396
    """
397
    Wrap around :mod:`bbarchivist.networkutils` carrier checking.
398
399
    :param mcc: Country code.
400
    :type mcc: int
401
402
    :param mnc: Network code.
403
    :type mnc: int
404
405
    :param device: Device ID (XXX100-#).
406
    :type device: str
407
408
    :param download: Whether or not to download. Default is false.
409
    :type download: bool
410
411
    :param upgrade: Whether or not to use upgrade files. Default is false.
412
    :type upgrade: bool
413
414
    :param directory: Where to store files. Default is local directory.
415
    :type directory: str
416
417
    :param export: Whether or not to write URLs to a file. Default is false.
418
    :type export: bool
419
420
    :param blitz: Whether or not to create a blitz package. Default is false.
421
    :type blitz: bool
422
423
    :param bundles: Whether or not to check software bundles. Default is false.
424
    :type bundles: bool
425
426
    :param forced: Force a software release. None to go for latest.
427
    :type forced: str
428
429
    :param selective: Whether or not to exclude Nuance/other dross. Default is false.
430
    :type selective: bool
431
    """
432
    device, directory = carrierchecker_argfilter(mcc, mnc, device, directory)
433
    model, family, hwid, country, carrier = carrierchecker_jsonprepare(mcc, mnc, device)
434
    scriptutils.slim_preamble("CARRIERCHECKER")
435
    print("COUNTRY: {0}".format(country.upper()))
436
    print("CARRIER: {0}".format(carrier.upper()))
437
    print("DEVICE: {0}".format(model.upper()))
438
    print("VARIANT: {0}".format(device.upper()))
439
    print("HARDWARE ID: {0}".format(hwid.upper()))
440
    print("\nCHECKING CARRIER...")
441
    if bundles:
442
        carrierchecker_bundles(mcc, mnc, hwid)
443
    else:
444
        npc = networkutils.return_npc(mcc, mnc)
445
        swv, osv, radv, files = networkutils.carrier_query(npc, hwid, upgrade, blitz, forced)
446
        print("SOFTWARE RELEASE: {0}".format(swv))
447
        print("OS VERSION: {0}".format(osv))
448
        print("RADIO VERSION: {0}".format(radv))
449
        files = carrierchecker_selective(files, selective)
450
        carrierchecker_export(mcc, mnc, files, hwid, osv, radv, swv, export, upgrade, forced)
451
        sess = requests.Session()
452
        carrierchecker_download(files, directory, osv, radv, swv, family, download, blitz, sess)
453
454
455
if __name__ == "__main__":
456
    grab_args()
457