diff options
author | 10se1ucgo <hammaadu1@gmail.com> | 2016-04-25 22:43:59 +0300 |
---|---|---|
committer | 10se1ucgo <hammaadu1@gmail.com> | 2016-04-25 22:43:59 +0300 |
commit | ada20b44748278e3d5ac1eb841aeecc47c377eee (patch) | |
tree | 011cfd0e1d02c880a14a95f3afcb1452b9331543 | |
parent | 6766735fe250a9999c4f612435eb64ee705aa94f (diff) |
Backport to Python 2. Fix logging stuff.v3.0.1
-rw-r--r-- | dwt.py | 66 | ||||
-rw-r--r-- | dwt_about.py | 8 | ||||
-rw-r--r-- | dwt_util.py | 72 |
3 files changed, 100 insertions, 46 deletions
@@ -102,6 +102,7 @@ class MainFrame(wx.Frame): self.Bind(wx.EVT_MENU, lambda x: dwt_about.about_dialog(self), about) self.Bind(wx.EVT_MENU, panel.settings, settings) self.Bind(wx.EVT_MENU, lambda x: dwt_about.Licenses(self), licenses) + self.Layout() class MainPanel(wx.Panel): @@ -160,7 +161,7 @@ class MainPanel(wx.Panel): go_button = wx.Button(self, label="Go!") self.app_box = wx.StaticBoxSizer(wx.VERTICAL, self, "Built-in Apps") - stat_box = self.app_box.GetStaticBox + stat_box = self.app_box.GetStaticBox() top_app_sizer = wx.BoxSizer(wx.HORIZONTAL) button_app_sizer = wx.BoxSizer(wx.HORIZONTAL) left_app_sizer = wx.BoxSizer(wx.VERTICAL) @@ -168,30 +169,31 @@ class MainPanel(wx.Panel): right_app_sizer = wx.BoxSizer(wx.VERTICAL) # wx.CheckBox(app_box.GetStaticBox(), label="Name", name="search_name") - wx.CheckBox(stat_box(), label="3D Builder", name="3dbuilder") - wx.CheckBox(stat_box(), label="Calender and Mail", name="windowscommunicationsapps") - wx.CheckBox(stat_box(), label="Camera", name="windowscamera") - wx.CheckBox(stat_box(), label="Get Office App", name="officehub") - wx.CheckBox(stat_box(), label="Get Skype App", name="skypeapp") - wx.CheckBox(stat_box(), label="Get Started App", name="getstarted") - wx.CheckBox(stat_box(), label="Groove Music", name="zunemusic") - wx.CheckBox(stat_box(), label="Maps", name="windowsmaps") - wx.CheckBox(stat_box(), label="Solitaire Collection", name="solitairecollection") - wx.CheckBox(stat_box(), label="Money", name="bingfinance") - wx.CheckBox(stat_box(), label="Movies && TV", name="zunevideo") - wx.CheckBox(stat_box(), label="News", name="bingnews") - wx.CheckBox(stat_box(), label="OneNote App", name="onenote") - wx.CheckBox(stat_box(), label="People", name="people") - wx.CheckBox(stat_box(), label="Phone Companion", name="windowsphone") - wx.CheckBox(stat_box(), label="Photos", name="photos") - wx.CheckBox(stat_box(), label="Sports", name="bingsports") - wx.CheckBox(stat_box(), label="Voice Recorder", name="soundrecorder") - wx.CheckBox(stat_box(), label="Weather", name="bingweather") - wx.CheckBox(stat_box(), label="Xbox", name="xboxapp") - remove_app_button = wx.Button(stat_box(), label="Remove selected apps") - select_all_check = wx.CheckBox(stat_box(), label="Select all") - - sorted_list = sorted(stat_box().GetChildren(), key=lambda x: x.GetLabel()) + wx.CheckBox(stat_box, label="3D Builder", name="3dbuilder") + wx.CheckBox(stat_box, label="Calender and Mail", name="windowscommunicationsapps") + wx.CheckBox(stat_box, label="Camera", name="windowscamera") + wx.CheckBox(stat_box, label="Get Office App", name="officehub") + wx.CheckBox(stat_box, label="Get Skype App", name="skypeapp") + wx.CheckBox(stat_box, label="Get Started App", name="getstarted") + wx.CheckBox(stat_box, label="Groove Music", name="zunemusic") + wx.CheckBox(stat_box, label="Maps", name="windowsmaps") + wx.CheckBox(stat_box, label="Solitaire Collection", name="solitairecollection") + wx.CheckBox(stat_box, label="Sway App", name="sway") + wx.CheckBox(stat_box, label="Money", name="bingfinance") + wx.CheckBox(stat_box, label="Movies && TV", name="zunevideo") + wx.CheckBox(stat_box, label="News", name="bingnews") + wx.CheckBox(stat_box, label="OneNote App", name="onenote") + wx.CheckBox(stat_box, label="People", name="people") + wx.CheckBox(stat_box, label="Phone Companion", name="windowsphone") + wx.CheckBox(stat_box, label="Photos", name="photos") + wx.CheckBox(stat_box, label="Sports", name="bingsports") + wx.CheckBox(stat_box, label="Voice Recorder", name="soundrecorder") + wx.CheckBox(stat_box, label="Weather", name="bingweather") + wx.CheckBox(stat_box, label="Xbox", name="xboxapp") + remove_app_button = wx.Button(stat_box, label="Remove selected apps") + select_all_check = wx.CheckBox(stat_box, label="Select all") + + sorted_list = sorted(stat_box.GetChildren(), key=lambda x: x.GetLabel()) for index, item in enumerate([x for x in sorted_list if isinstance(x, wx.CheckBox) and x != select_all_check]): n = len(sorted_list) // 3 if index <= n: @@ -232,6 +234,7 @@ class MainPanel(wx.Panel): check_sizer.Add(self.onedrive_check, 0, wx.ALL, 1) self.Bind(wx.EVT_CHECKBOX, handler=self.select_all_apps, source=select_all_check) + self.Bind(wx.EVT_CHECKBOX, handler=self.hosts_warn, source=self.extra_host_check) self.Bind(wx.EVT_BUTTON, handler=self.remove_apps, source=remove_app_button) self.Bind(wx.EVT_BUTTON, handler=self.go, source=go_button) @@ -243,6 +246,19 @@ class MainPanel(wx.Panel): if isinstance(child, wx.CheckBox): child.SetValue(event.IsChecked()) + def hosts_warn(self, event): + # Warn users about the potential side effects of the extra hosts mod. + if event.IsChecked(): + warn = wx.MessageDialog(parent=self, + message="This option could potentially disable one or more of the following " + "services:\n\nSkype, Hotmain, Dr. Watson and/or Error Reporting. Continue?", + caption="Attention!", style=wx.YES_NO | wx.ICON_EXCLAMATION) + + if warn.ShowModal() == wx.ID_NO: + event.GetObject().SetValue(False) + + warn.Destroy() + def go(self, event): if not all((self.picked_ips, self.picked_extra, self.picked_normal)): self.settings(event=None) diff --git a/dwt_about.py b/dwt_about.py index 4b9b2ec..0767c41 100644 --- a/dwt_about.py +++ b/dwt_about.py @@ -16,8 +16,9 @@ # along with DisableWinTracking. If not, see <http://www.gnu.org/licenses/>. # dwt.py will become cluttered enough :^) +import cgi import json -import urllib.request +import urllib2 import webbrowser from distutils.version import StrictVersion @@ -166,8 +167,9 @@ class Licenses(wx.Dialog): def update_check(parent): - response = urllib.request.urlopen('https://api.github.com/repos/10se1ucgo/DisableWinTracking/releases/latest') - release = json.loads(response.read().decode()) + r = urllib2.urlopen('https://api.github.com/repos/10se1ucgo/DisableWinTracking/releases/latest') + value, parameters = cgi.parse_header(r.headers.get('Content-Type', '')) + release = json.loads(r.read().decode(parameters.get('charset', 'utf-8'))) if release['prerelease']: return new = release['tag_name'] diff --git a/dwt_util.py b/dwt_util.py index 31cd033..e8bffbb 100644 --- a/dwt_util.py +++ b/dwt_util.py @@ -30,9 +30,41 @@ import winerror logger = logging.getLogger('dwt.util') +class CalledProcessError(Exception): + """This exception is raised by subprocess_handler() returns a non-zero exit status. + It is a direct copy + paste backport from Python 3, as the Python 2 version does not + include the "stderr" property. + + Original docstring: + This exception is raised when a process run by check_call() or + check_output() returns a non-zero exit status. + The exit status will be stored in the returncode attribute; + check_output() will also store the output in the output attribute. + """ + def __init__(self, returncode, cmd, output=None, stderr=None): + self.returncode = returncode + self.cmd = cmd + self.output = output + self.stderr = stderr + + def __str__(self): + return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) + + @property + def stdout(self): + """Alias for output attribute, to match stderr""" + return self.output + + @stdout.setter + def stdout(self, value): + # There's no obvious reason to set this, but allow it anyway so + # .stdout is a transparent alias for .output + self.output = value + + def is_64bit(): # Detect if OS is 64bit - return True if "64" in platform.uname().machine else False + return True if "64" in platform.machine() else False def ip_block(ip_list, undo): @@ -45,7 +77,7 @@ def ip_block(ip_list, undo): try: subprocess_handler(shlex.split(cmd)) logger.info("IP Blocker: The IP {ip} was successfully blocked.".format(ip=ip)) - except subprocess.CalledProcessError as e: + except CalledProcessError as e: logger.exception("IP Blocker: Failed to block IP {ip}".format(ip=ip)) logger.critical("IP Blocker: Error output:\n" + e.stdout.decode('ascii', 'replace')) @@ -58,7 +90,7 @@ def clear_diagtrack(): try: subprocess_handler(shlex.split(own_cmd)) - except subprocess.CalledProcessError as e: + except CalledProcessError as e: logger.exception("DiagTrack: Failed to clear DiagTrack log -- could not take ownership of file") logger.critical("DiagTrack: Error output:\n" + e.output.decode('ascii', 'replace')) return @@ -67,7 +99,7 @@ def clear_diagtrack(): open(file, 'w').close() subprocess_handler(shlex.split(lock_cmd)) logger.info("DiagTrack: Successfully cleared and locked DiagTrack log.") - except subprocess.CalledProcessError as e: + except CalledProcessError as e: logger.exception("DiagTrack: Failed to clear DiagTrack log -- could not clear or lock") logger.critical("DiagTrack: Error output:\n" + e.output.decode('ascii', 'replace')) @@ -75,21 +107,21 @@ def clear_diagtrack(): def delete_service(service): try: win32serviceutil.RemoveService(service) - logging.info("Services: Succesfully removed service '{service}'".format(service=service)) + logger.info("Services: Succesfully removed service '{service}'".format(service=service)) except pywintypes.error as e: errors = (winerror.ERROR_SERVICE_DOES_NOT_EXIST, winerror.ERROR_SERVICE_NOT_ACTIVE) if not any(error == e.winerror for error in errors): - logging.exception("Services: Failed to remove service '{service}'".format(service=service)) + logger.exception("Services: Failed to remove service '{service}'".format(service=service)) def disable_service(service): try: win32serviceutil.StopService(service) - logging.info("Services: Succesfully stopped service '{service}'".format(service=service)) + logger.info("Services: Succesfully stopped service '{service}'".format(service=service)) except pywintypes.error as e: errors = (winerror.ERROR_SERVICE_DOES_NOT_EXIST, winerror.ERROR_SERVICE_NOT_ACTIVE) if not any(error == e.winerror for error in errors): - logging.exception("Services: Failed to stop service '{service}'".format(service=service)) + logger.exception("Services: Failed to stop service '{service}'".format(service=service)) def telemetry(undo): @@ -173,9 +205,9 @@ def set_registry(keys): key = winreg.CreateKeyEx(values[0], values[1], 0, mask) winreg.SetValueEx(key, values[2], 0, values[3], values[4]) winreg.CloseKey(key) - logging.info("Registry: Successfully modified {key} key.".format(key=key_name)) + logger.info("Registry: Successfully modified {key} key.".format(key=key_name)) except OSError: - logging.exception("Registry: Unable to mody {key} key.".format(key=key_name)) + logger.exception("Registry: Unable to mody {key} key.".format(key=key_name)) def host_file(entries, undo): @@ -193,40 +225,44 @@ def host_file(entries, undo): shutil.move(temp.name, hosts_path) return True except OSError: - logging.exception("Hosts: Failed to undo hosts file") + logger.exception("Hosts: Failed to undo hosts file") else: try: with open(hosts_path, 'a') as f: f.write('\n' + '\n'.join(nulled_entires)) return True except (WindowsError, IOError): - logging.exception("Hosts: Failed to modify hosts file") + logger.exception("Hosts: Failed to modify hosts file") return False def app_manager(apps, undo): - running = [] + running = {} for app in apps: cmd = 'powershell "Get-AppxPackage *{app}*|Remove-AppxPackage"'.format(app=app) try: process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) - running.append(process) + running[app] = process except OSError: - logging.exception("App remover: Failed to remove app '{app}'".format(app=app)) + logger.exception("App remover: Failed to remove app '{app}'".format(app=app)) - for process in running: + for app, process in running.items(): process.wait() + if process.returncode: + logger.exception("App remover: Failed to remove app '{app}'".format(app=app)) + else: + logger.info("Successfully removed app '{app}'".format(app=app)) def subprocess_handler(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) output = p.communicate() if p.returncode: - raise subprocess.CalledProcessError(returncode=p.returncode, cmd=cmd, output=output[0], stderr=output[1]) + raise CalledProcessError(returncode=p.returncode, cmd=cmd, output=output[0], stderr=output[1]) -# Old reinstall code: +# Old reinstall code, does not work: # if reinstall: # # We encode in Base64 because the command is complex and I'm too lazy to escape everything. # # It's uncoded format command: "Get-AppxPackage -AllUsers| Foreach {Add-AppxPackage -DisableDevelopmentMode |