Completed
Push — master ( 4fb5d7...82edc4 )
by John
01:11
created

carrierchecker_bundles()   A

Complexity

Conditions 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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