Completed
Push — master ( de6c4c...cc1262 )
by John
03:54
created

carrierchecker_download_prep()   B

Complexity

Conditions 4

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

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