Completed
Push — master ( ee956e...fc3a5e )
by John
02:41
created

questionnaire_3digit()   B

Complexity

Conditions 5

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
dl 0
loc 12
rs 8.5454
c 0
b 0
f 0
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__ = "Copyright 2015-2016 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
            if args.folder is None:
109
                args.folder = os.getcwd()
110
            if args.blitz:
111
                args.download = True
112
                args.upgrade = True  # blitz takes precedence
113
            if args.bundles:
114
                args.download = False
115
                args.upgrade = False
116
                args.export = False
117
                args.blitz = False
118
            if args.forcedos is not None and args.forcedsw is None:
119
                avail = networkutils.sr_lookup(args.forcedos,
120
                                               bbconstants.SERVERS['p'])
121
                forced = avail if avail != "SR not in system" else None
122
            elif args.forcedos is None and args.forcedsw is not None:
123
                forced = args.forcedsw
124
            else:
125
                forced = None
126
            carrierchecker_main(
127
                args.mcc,
128
                args.mnc,
129
                args.device,
130
                args.download,
131
                args.upgrade,
132
                args.folder,
133
                args.export,
134
                args.blitz,
135
                args.bundles,
136
                forced,
137
                args.selective)
138
    else:
139
        questionnaire()
140
    decorators.enter_to_exit(True)
141
142
143
def questionnaire_3digit(message):
144
    """
145
    Get MCC/MNC from questionnaire.
146
    """
147
    while True:
148
        try:
149
            trip = int(input("{0}: ".format(message)))
150
        except ValueError:
151
            continue
152
        else:
153
            if trip == utilities.valid_carrier(trip):
154
                return trip
155
156
157
def questionnaire():
158
    """
159
    Questions to ask if no arguments given.
160
    """
161
    mcc = questionnaire_3digit("MCC")
162
    mnc = questionnaire_3digit("MNC")
163
    device = scriptutils.questionnaire_device()
164
    bundles = utilities.s2b(input("CHECK BUNDLES?: "))
165
    if bundles:
166
        download = False
167
        upgrade = False
168
        export = False
169
        blitz = False
170
    else:
171
        export = utilities.s2b(input("EXPORT TO FILE?: "))
172
        download = utilities.s2b(input("DOWNLOAD?: "))
173
        upgrade = False if not download else utilities.s2b(input("Y=UPGRADE BARS, N=DEBRICK BARS?: "))
174
        blitz = False if not download else (utilities.s2b(input("CREATE BLITZ?: ")) if upgrade else False)
175
    directory = os.getcwd()
176
    print(" ")
177
    carrierchecker_main(
178
        mcc,
179
        mnc,
180
        device,
181
        download,
182
        upgrade,
183
        directory,
184
        export,
185
        blitz,
186
        bundles,
187
        None,
188
        False)
189
190
191
def carrierchecker_argfilter(mcc, mnc, device, directory):
192
    """
193
    Filter arguments.
194
195
    :param mcc: Country code.
196
    :type mcc: int
197
198
    :param mnc: Network code.
199
    :type mnc: int
200
201
    :param device: Device ID (SXX100-#)
202
    :type device: str
203
204
    :param directory: Where to store files. Default is local directory.
205
    :type directory: str
206
    """
207
    if mcc is None:
208
        print("INVALID MCC!")
209
        raise SystemExit
210
    elif mnc is None:
211
        print("INVALID MNC!")
212
        raise SystemExit
213
    elif device is None:
214
        print("INVALID DEVICE!")
215
        raise SystemExit
216
    device = device.upper()
217
    directory = os.getcwd() if directory is None else directory
218
    return device, directory
219
220
221
def carrierchecker_jsonprepare(mcc, mnc, device):
222
    """
223
    Prepare JSON data.
224
225
    :param mcc: Country code.
226
    :type mcc: int
227
228
    :param mnc: Network code.
229
    :type mnc: int
230
231
    :param device: Device ID (SXX100-#).
232
    :type device: str
233
    """
234
    data = jsonutils.load_json("devices")
235
    model, family, hwid = jsonutils.certchecker_prep(data, device)
236
    country, carrier = networkutils.carrier_checker(mcc, mnc)
237
    return model, family, hwid, country, carrier
238
239
240
def carrierchecker_bundles(mcc, mnc, hwid):
241
    """
242
    :param mcc: Country code.
243
    :type mcc: int
244
245
    :param mnc: Network code.
246
    :type mnc: int
247
248
    :param hwid: Device hardware ID.
249
    :type hwid: str
250
    """
251
    releases = networkutils.available_bundle_lookup(mcc, mnc, hwid)
252
    print("\nAVAILABLE BUNDLES:")
253
    utilities.lprint(releases)
254
255
256
def carrierchecker_selective(files, selective=False):
257
    """
258
    Filter useless bar files.
259
260
    :param files: List of files.
261
    :type files: list(str)
262
263
    :param selective: Whether or not to exclude Nuance/other dross. Default is false.
264
    :type selective: bool
265
    """
266
    if selective:
267
        craplist = jsonutils.load_json("apps_to_remove")
268
        files = scriptutils.clean_barlist(files, craplist)
269
    return files
270
271
272
def carrierchecker_export(mcc, mnc, files, hwid, osv, radv, swv, export=False, upgrade=False, forced=None):
273
    """
274
    Export files to file.
275
276
    :param mcc: Country code.
277
    :type mcc: int
278
279
    :param mnc: Network code.
280
    :type mnc: int
281
282
    :param files: List of files.
283
    :type files: list(str)
284
285
    :param hwid: Device hardware ID.
286
    :type hwid: str
287
288
    :param osv: OS version, 10.x.y.zzzz.
289
    :type osv: str
290
291
    :param radv: Radio version, 10.x.y.zzzz.
292
    :type radv: str
293
294
    :param swv: Software release, 10.x.y.zzzz.
295
    :type swv: str
296
297
    :param export: Whether or not to write URLs to a file. Default is false.
298
    :type export: bool
299
300
    :param upgrade: Whether or not to use upgrade files. Default is false.
301
    :type upgrade: bool
302
303
    :param forced: Force a software release. None to go for latest.
304
    :type forced: str
305
    """
306
    if export:
307
        print("\nEXPORTING...")
308
        npc = networkutils.return_npc(mcc, mnc)
309
        scriptutils.export_cchecker(files, npc, hwid, osv, radv, swv, upgrade, forced)
310
311
312
def carrierchecker_download(files, directory, osv, radv, swv, family, download=False, blitz=False, session=None):
313
    """
314
    Download files, create blitz if specified.
315
316
    :param files: List of files.
317
    :type files: list(str)
318
319
    :param directory: Where to store files. Default is local directory.
320
    :type directory: str
321
322
    :param osv: OS version, 10.x.y.zzzz.
323
    :type osv: str
324
325
    :param radv: Radio version, 10.x.y.zzzz.
326
    :type radv: str
327
328
    :param swv: Software release, 10.x.y.zzzz.
329
    :type swv: str
330
331
    :param family: Device family.
332
    :type family: str
333
334
    :param download: Whether or not to download. Default is false.
335
    :type download: bool
336
337
    :param blitz: Whether or not to create a blitz package. Default is false.
338
    :type blitz: bool
339
340
    :param session: Requests session object, default is created on the fly.
341
    :type session: requests.Session()
342
    """
343
    if download:
344
        suffix = "-BLITZ" if blitz else "-{0}".format(family)
345
        bardir = os.path.join(directory, "{0}{1}".format(swv, suffix))
346
        if not os.path.exists(bardir):
347
            os.makedirs(bardir)
348
        if blitz:
349
            files = scriptutils.generate_blitz_links(files, osv, radv, swv)
350
        print("\nDOWNLOADING...")
351
        networkutils.download_bootstrap(files, outdir=bardir, session=session)
352
        scriptutils.test_bar_files(bardir, files)
353
        if blitz:
354
            scriptutils.package_blitz(bardir, swv)
355
        print("\nFINISHED!!!")
356
357
358
def carrierchecker_main(mcc, mnc, device,
359
                        download=False, upgrade=True,
360
                        directory=None,
361
                        export=False,
362
                        blitz=False,
363
                        bundles=False,
364
                        forced=None,
365
                        selective=False):
366
    """
367
    Wrap around :mod:`bbarchivist.networkutils` carrier checking.
368
369
    :param mcc: Country code.
370
    :type mcc: int
371
372
    :param mnc: Network code.
373
    :type mnc: int
374
375
    :param device: Device ID (SXX100-#).
376
    :type device: str
377
378
    :param download: Whether or not to download. Default is false.
379
    :type download: bool
380
381
    :param upgrade: Whether or not to use upgrade files. Default is false.
382
    :type upgrade: bool
383
384
    :param directory: Where to store files. Default is local directory.
385
    :type directory: str
386
387
    :param export: Whether or not to write URLs to a file. Default is false.
388
    :type export: bool
389
390
    :param blitz: Whether or not to create a blitz package. Default is false.
391
    :type blitz: bool
392
393
    :param bundles: Whether or not to check software bundles. Default is false.
394
    :type bundles: bool
395
396
    :param forced: Force a software release. None to go for latest.
397
    :type forced: str
398
399
    :param selective: Whether or not to exclude Nuance/other dross. Default is false.
400
    :type selective: bool
401
    """
402
    device, directory = carrierchecker_argfilter(mcc, mnc, device, directory)
403
    model, family, hwid, country, carrier = carrierchecker_jsonprepare(mcc, mnc, device)
404
    scriptutils.slim_preamble("CARRIERCHECKER")
405
    print("COUNTRY: {0}".format(country.upper()))
406
    print("CARRIER: {0}".format(carrier.upper()))
407
    print("DEVICE: {0}".format(model.upper()))
408
    print("VARIANT: {0}".format(device.upper()))
409
    print("HARDWARE ID: {0}".format(hwid.upper()))
410
    print("\nCHECKING CARRIER...")
411
    if bundles:
412
        carrierchecker_bundles(mcc, mnc, hwid)
413
    else:
414
        npc = networkutils.return_npc(mcc, mnc)
415
        swv, osv, radv, files = networkutils.carrier_query(npc, hwid, upgrade, blitz, forced)
416
        print("SOFTWARE RELEASE: {0}".format(swv))
417
        print("OS VERSION: {0}".format(osv))
418
        print("RADIO VERSION: {0}".format(radv))
419
        files = carrierchecker_selective(files, selective)
420
        carrierchecker_export(mcc, mnc, files, hwid, osv, radv, swv, export, upgrade, forced)
421
        sess = requests.Session()
422
        carrierchecker_download(files, directory, osv, radv, swv, family, download, blitz, sess)
423
424
425
if __name__ == "__main__":
426
    grab_args()
427