Completed
Push — master ( 974cdd...c16db8 )
by John
01:26
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
    if len(sys.argv) > 1:
25
        parser = scriptutils.default_parser("bb-cchecker", "Carrier info checking")
26
        parser.add_argument("mcc",
27
                            help="1-3 digit country code",
28
                            type=utilities.valid_carrier,
29
                            nargs="?",
30
                            default=None)
31
        parser.add_argument("mnc",
32
                            help="1-3 digit carrier code",
33
                            type=utilities.valid_carrier,
34
                            nargs="?",
35
                            default=None)
36
        parser.add_argument("device",
37
                            help="'STL100-1', 'SQW100-3', etc.",
38
                            nargs="?",
39
                            default=None)
40
        parser.add_argument(
41
            "-c", "--codes",
42
            dest="codes",
43
            help="Open browser for MCC/MNC list",
44
            action="store_true",
45
            default=False)
46
        parser.add_argument(
47
            "-a", "--available-bundles",
48
            dest="bundles",
49
            help="Check available bundles",
50
            action="store_true",
51
            default=False)
52
        parser.add_argument(
53
            "-d", "--download",
54
            dest="download",
55
            help="Download files after checking",
56
            action="store_true",
57
            default=False)
58
        parser.add_argument(
59
            "-e", "--export",
60
            dest="export",
61
            help="Export links to files",
62
            action="store_true",
63
            default=False)
64
        parser.add_argument(
65
            "-r", "--repair",
66
            dest="upgrade",
67
            help="Debrick instead of upgrade bars",
68
            action="store_false",
69
            default=True)
70
        parser.add_argument(
71
            "-f", "--folder",
72
            dest="folder",
73
            help="Working folder",
74
            default=None,
75
            metavar="DIR")
76
        parser.add_argument(
77
            "-b", "--blitz",
78
            dest="blitz",
79
            help="Create blitz package",
80
            action="store_true",
81
            default=False)
82
        parser.add_argument(
83
            "--selective",
84
            dest="selective",
85
            help="Skip Nuance/retaildemo",
86
            action="store_true",
87
            default=False)
88
        fgroup = parser.add_mutually_exclusive_group()
89
        fgroup.add_argument(
90
            "-s", "--software-release",
91
            dest="forcedsw",
92
            help="Force SW release (check bundles first!)",
93
            default=None,
94
            metavar="SWRELEASE")
95
        fgroup.add_argument(
96
            "-o", "--os",
97
            dest="forcedos",
98
            help="Force OS (check bundles first!)",
99
            default=None,
100
            metavar="OS")
101
        parser.set_defaults()
102
        args = parser.parse_args(sys.argv[1:])
103
        if args.codes:
104
            webbrowser.open("https://en.wikipedia.org/wiki/Mobile_country_code")
105
        else:
106
            if args.folder is None:
107
                args.folder = os.getcwd()
108
            if args.blitz:
109
                args.download = True
110
                args.upgrade = True  # blitz takes precedence
111
            if args.bundles:
112
                args.download = False
113
                args.upgrade = False
114
                args.export = False
115
                args.blitz = False
116
            if args.forcedos is not None and args.forcedsw is None:
117
                avail = networkutils.sr_lookup(args.forcedos,
118
                                               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():
142
    """
143
    Questions to ask if no arguments given.
144
    """
145
    while True:
146
        try:
147
            mcc = int(input("MCC: "))
148
        except ValueError:
149
            continue
150
        else:
151
            if mcc == utilities.valid_carrier(mcc):
152
                break
153
    while True:
154
        try:
155
            mnc = int(input("MNC: "))
156
        except ValueError:
157
            continue
158
        else:
159
            if mnc == utilities.valid_carrier(mnc):
160
                break
161
    device = input("DEVICE (SXX100-#): ")
162
    if not device:
163
        print("NO DEVICE SPECIFIED!")
164
        decorators.enter_to_exit(True)
165
        if not getattr(sys, 'frozen', False):
166
            raise SystemExit
167
    bundles = utilities.s2b(input("CHECK BUNDLES?: "))
168
    if bundles:
169
        download = False
170
        upgrade = False
171
        export = False
172
        blitz = False
173
    else:
174
        export = utilities.s2b(input("EXPORT TO FILE?: "))
175
        download = utilities.s2b(input("DOWNLOAD?: "))
176
        if download:
177
            upgrade = utilities.s2b(input("Y=UPGRADE BARS, N=DEBRICK BARS?: "))
178
            blitz = utilities.s2b(input("CREATE BLITZ?: ")) if upgrade else False
179
        else:
180
            upgrade = False
181
            blitz = False
182
    directory = os.getcwd()
183
    print(" ")
184
    carrierchecker_main(
185
        mcc,
186
        mnc,
187
        device,
188
        download,
189
        upgrade,
190
        directory,
191
        export,
192
        blitz,
193
        bundles,
194
        None,
195
        False)
196
197
198
def carrierchecker_main(mcc, mnc, device,
199
                        download=False, upgrade=True,
200
                        directory=None,
201
                        export=False,
202
                        blitz=False,
203
                        bundles=False,
204
                        forced=None,
205
                        selective=False):
206
    """
207
    Wrap around :mod:`bbarchivist.networkutils` carrier checking.
208
209
    :param mcc: Country code.
210
    :type mcc: int
211
212
    :param mnc: Network code.
213
    :type mnc: int
214
215
    :param device: Device ID (SXX100-#)
216
    :type device: str
217
218
    :param download: Whether or not to download. Default is false.
219
    :type download: bool
220
221
    :param upgrade: Whether or not to use upgrade files. Default is false.
222
    :type upgrade: bool
223
224
    :param directory: Where to store files. Default is local directory.
225
    :type directory: str
226
227
    :param export: Whether or not to write URLs to a file. Default is false.
228
    :type export: bool
229
230
    :param blitz: Whether or not to create a blitz package. Default is false.
231
    :type blitz: bool
232
233
    :param bundles: Whether or not to check software bundles. Default is false.
234
    :type bundles: bool
235
236
    :param forced: Force a software release. None to go for latest.
237
    :type forced: str
238
239
    :param selective: Whether or not to exclude Nuance/other dross. Default is false.
240
    :type selective: bool
241
    """
242
    if mcc is None:
243
        print("INVALID MCC!")
244
        raise SystemExit
245
    elif mnc is None:
246
        print("INVALID MNC!")
247
        raise SystemExit
248
    elif device is None:
249
        print("INVALID DEVICE!")
250
        raise SystemExit
251
    device = device.upper()
252
    if directory is None:
253
        directory = os.getcwd()
254
    data = jsonutils.load_json("devices")
255
    model, family, hwid = jsonutils.certchecker_prep(data, device)
256
    scriptutils.slim_preamble("CARRIERCHECKER")
257
    country, carrier = networkutils.carrier_checker(mcc, mnc)
258
    print("COUNTRY: {0}".format(country.upper()))
259
    print("CARRIER: {0}".format(carrier.upper()))
260
    print("DEVICE: {0}".format(model.upper()))
261
    print("VARIANT: {0}".format(device.upper()))
262
    print("HARDWARE ID: {0}".format(hwid.upper()))
263
    print("\nCHECKING CARRIER...")
264
    if bundles:
265
        releases = networkutils.available_bundle_lookup(mcc, mnc, hwid)
266
        print("\nAVAILABLE BUNDLES:")
267
        utilities.lprint(releases)
268
    else:
269
        npc = networkutils.return_npc(mcc, mnc)
270
        swv, osv, radv, files = networkutils.carrier_query(npc, hwid, upgrade, blitz, forced)
271
        print("SOFTWARE RELEASE: {0}".format(swv))
272
        print("OS VERSION: {0}".format(osv))
273
        print("RADIO VERSION: {0}".format(radv))
274
        if selective:
275
            craplist = jsonutils.load_json("apps_to_remove")
276
            files = scriptutils.purge_dross(files, craplist)
277
        if export:
278
            print("\nEXPORTING...")
279
            npc = networkutils.return_npc(mcc, mnc)
280
            scriptutils.export_cchecker(files, npc, hwid, osv, radv, swv, upgrade, forced)
281
        if download:
282
            suffix = "-BLITZ" if blitz else "-{0}".format(family)
283
            bardir = os.path.join(directory, "{0}{1}".format(swv, suffix))
284
            if not os.path.exists(bardir):
285
                os.makedirs(bardir)
286
            if blitz:
287
                files = scriptutils.generate_blitz_links(files, osv, radv, swv)
288
            print("\nDOWNLOADING...")
289
            networkutils.download_bootstrap(files, outdir=bardir)
290
            scriptutils.test_bar_files(bardir, files)
291
            if blitz:
292
                scriptutils.package_blitz(bardir, swv)
293
            print("\nFINISHED!!!")
294
295
296
if __name__ == "__main__":
297
    grab_args()
298