Completed
Push — master ( 1f2fd3...fc852d )
by John
01:20
created

questionnaire()   B

Complexity

Conditions 5

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 4
Metric Value
cc 5
dl 0
loc 32
rs 8.0894
c 5
b 0
f 4
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_main(mcc, mnc, device,
218
                        download=False, upgrade=True,
219
                        directory=None,
220
                        export=False,
221
                        blitz=False,
222
                        bundles=False,
223
                        forced=None,
224
                        selective=False):
225
    """
226
    Wrap around :mod:`bbarchivist.networkutils` carrier checking.
227
228
    :param mcc: Country code.
229
    :type mcc: int
230
231
    :param mnc: Network code.
232
    :type mnc: int
233
234
    :param device: Device ID (SXX100-#)
235
    :type device: str
236
237
    :param download: Whether or not to download. Default is false.
238
    :type download: bool
239
240
    :param upgrade: Whether or not to use upgrade files. Default is false.
241
    :type upgrade: bool
242
243
    :param directory: Where to store files. Default is local directory.
244
    :type directory: str
245
246
    :param export: Whether or not to write URLs to a file. Default is false.
247
    :type export: bool
248
249
    :param blitz: Whether or not to create a blitz package. Default is false.
250
    :type blitz: bool
251
252
    :param bundles: Whether or not to check software bundles. Default is false.
253
    :type bundles: bool
254
255
    :param forced: Force a software release. None to go for latest.
256
    :type forced: str
257
258
    :param selective: Whether or not to exclude Nuance/other dross. Default is false.
259
    :type selective: bool
260
    """
261
    if mcc is None:
262
        print("INVALID MCC!")
263
        raise SystemExit
264
    elif mnc is None:
265
        print("INVALID MNC!")
266
        raise SystemExit
267
    elif device is None:
268
        print("INVALID DEVICE!")
269
        raise SystemExit
270
    device = device.upper()
271
    if directory is None:
272
        directory = os.getcwd()
273
    data = jsonutils.load_json("devices")
274
    model, family, hwid = jsonutils.certchecker_prep(data, device)
275
    scriptutils.slim_preamble("CARRIERCHECKER")
276
    country, carrier = networkutils.carrier_checker(mcc, mnc)
277
    print("COUNTRY: {0}".format(country.upper()))
278
    print("CARRIER: {0}".format(carrier.upper()))
279
    print("DEVICE: {0}".format(model.upper()))
280
    print("VARIANT: {0}".format(device.upper()))
281
    print("HARDWARE ID: {0}".format(hwid.upper()))
282
    print("\nCHECKING CARRIER...")
283
    if bundles:
284
        releases = networkutils.available_bundle_lookup(mcc, mnc, hwid)
285
        print("\nAVAILABLE BUNDLES:")
286
        utilities.lprint(releases)
287
    else:
288
        npc = networkutils.return_npc(mcc, mnc)
289
        swv, osv, radv, files = networkutils.carrier_query(npc, hwid, upgrade, blitz, forced)
290
        print("SOFTWARE RELEASE: {0}".format(swv))
291
        print("OS VERSION: {0}".format(osv))
292
        print("RADIO VERSION: {0}".format(radv))
293
        if selective:
294
            craplist = jsonutils.load_json("apps_to_remove")
295
            files = scriptutils.purge_dross(files, craplist)
296
        if export:
297
            print("\nEXPORTING...")
298
            npc = networkutils.return_npc(mcc, mnc)
299
            scriptutils.export_cchecker(files, npc, hwid, osv, radv, swv, upgrade, forced)
300
        if download:
301
            suffix = "-BLITZ" if blitz else "-{0}".format(family)
302
            bardir = os.path.join(directory, "{0}{1}".format(swv, suffix))
303
            if not os.path.exists(bardir):
304
                os.makedirs(bardir)
305
            if blitz:
306
                files = scriptutils.generate_blitz_links(files, osv, radv, swv)
307
            print("\nDOWNLOADING...")
308
            networkutils.download_bootstrap(files, outdir=bardir)
309
            scriptutils.test_bar_files(bardir, files)
310
            if blitz:
311
                scriptutils.package_blitz(bardir, swv)
312
            print("\nFINISHED!!!")
313
314
315
if __name__ == "__main__":
316
    grab_args()
317