Completed
Push — master ( 152b55...0bdad9 )
by John
01:22
created

carrierchecker_main()   F

Complexity

Conditions 13

Size

Total Lines 96

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 13
c 1
b 0
f 1
dl 0
loc 96
rs 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like carrierchecker_main() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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():
143
    """
144
    Questions to ask if no arguments given.
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
                break
154
    while True:
155
        try:
156
            mnc = int(input("MNC: "))
157
        except ValueError:
158
            continue
159
        else:
160
            if mnc == utilities.valid_carrier(mnc):
161
                break
162
    device = input("DEVICE (SXX100-#): ")
163
    if not device:
164
        print("NO DEVICE SPECIFIED!")
165
        decorators.enter_to_exit(True)
166
        if not getattr(sys, 'frozen', False):
167
            raise SystemExit
168
    bundles = utilities.s2b(input("CHECK BUNDLES?: "))
169
    if bundles:
170
        download = False
171
        upgrade = False
172
        export = False
173
        blitz = False
174
    else:
175
        export = utilities.s2b(input("EXPORT TO FILE?: "))
176
        download = utilities.s2b(input("DOWNLOAD?: "))
177
        if download:
178
            upgrade = utilities.s2b(input("Y=UPGRADE BARS, N=DEBRICK BARS?: "))
179
            blitz = utilities.s2b(input("CREATE BLITZ?: ")) if upgrade else False
180
        else:
181
            upgrade = False
182
            blitz = False
183
    directory = os.getcwd()
184
    print(" ")
185
    carrierchecker_main(
186
        mcc,
187
        mnc,
188
        device,
189
        download,
190
        upgrade,
191
        directory,
192
        export,
193
        blitz,
194
        bundles,
195
        None,
196
        False)
197
198
199
def carrierchecker_main(mcc, mnc, device,
200
                        download=False, upgrade=True,
201
                        directory=None,
202
                        export=False,
203
                        blitz=False,
204
                        bundles=False,
205
                        forced=None,
206
                        selective=False):
207
    """
208
    Wrap around :mod:`bbarchivist.networkutils` carrier checking.
209
210
    :param mcc: Country code.
211
    :type mcc: int
212
213
    :param mnc: Network code.
214
    :type mnc: int
215
216
    :param device: Device ID (SXX100-#)
217
    :type device: str
218
219
    :param download: Whether or not to download. Default is false.
220
    :type download: bool
221
222
    :param upgrade: Whether or not to use upgrade files. Default is false.
223
    :type upgrade: bool
224
225
    :param directory: Where to store files. Default is local directory.
226
    :type directory: str
227
228
    :param export: Whether or not to write URLs to a file. Default is false.
229
    :type export: bool
230
231
    :param blitz: Whether or not to create a blitz package. Default is false.
232
    :type blitz: bool
233
234
    :param bundles: Whether or not to check software bundles. Default is false.
235
    :type bundles: bool
236
237
    :param forced: Force a software release. None to go for latest.
238
    :type forced: str
239
240
    :param selective: Whether or not to exclude Nuance/other dross. Default is false.
241
    :type selective: bool
242
    """
243
    if mcc is None:
244
        print("INVALID MCC!")
245
        raise SystemExit
246
    elif mnc is None:
247
        print("INVALID MNC!")
248
        raise SystemExit
249
    elif device is None:
250
        print("INVALID DEVICE!")
251
        raise SystemExit
252
    device = device.upper()
253
    if directory is None:
254
        directory = os.getcwd()
255
    data = jsonutils.load_json("devices")
256
    model, family, hwid = jsonutils.certchecker_prep(data, device)
257
    scriptutils.slim_preamble("CARRIERCHECKER")
258
    country, carrier = networkutils.carrier_checker(mcc, mnc)
259
    print("COUNTRY: {0}".format(country.upper()))
260
    print("CARRIER: {0}".format(carrier.upper()))
261
    print("DEVICE: {0}".format(model.upper()))
262
    print("VARIANT: {0}".format(device.upper()))
263
    print("HARDWARE ID: {0}".format(hwid.upper()))
264
    print("\nCHECKING CARRIER...")
265
    if bundles:
266
        releases = networkutils.available_bundle_lookup(mcc, mnc, hwid)
267
        print("\nAVAILABLE BUNDLES:")
268
        utilities.lprint(releases)
269
    else:
270
        npc = networkutils.return_npc(mcc, mnc)
271
        swv, osv, radv, files = networkutils.carrier_query(npc, hwid, upgrade, blitz, forced)
272
        print("SOFTWARE RELEASE: {0}".format(swv))
273
        print("OS VERSION: {0}".format(osv))
274
        print("RADIO VERSION: {0}".format(radv))
275
        if selective:
276
            craplist = jsonutils.load_json("apps_to_remove")
277
            files = scriptutils.purge_dross(files, craplist)
278
        if export:
279
            print("\nEXPORTING...")
280
            npc = networkutils.return_npc(mcc, mnc)
281
            scriptutils.export_cchecker(files, npc, hwid, osv, radv, swv, upgrade, forced)
282
        if download:
283
            suffix = "-BLITZ" if blitz else "-{0}".format(family)
284
            bardir = os.path.join(directory, "{0}{1}".format(swv, suffix))
285
            if not os.path.exists(bardir):
286
                os.makedirs(bardir)
287
            if blitz:
288
                files = scriptutils.generate_blitz_links(files, osv, radv, swv)
289
            print("\nDOWNLOADING...")
290
            networkutils.download_bootstrap(files, outdir=bardir)
291
            scriptutils.test_bar_files(bardir, files)
292
            if blitz:
293
                scriptutils.package_blitz(bardir, swv)
294
            print("\nFINISHED!!!")
295
296
297
if __name__ == "__main__":
298
    grab_args()
299