Skip to content
This repository has been archived by the owner on Feb 9, 2021. It is now read-only.

Commit

Permalink
Backport to Python 2. Fix logging stuff.
Browse files Browse the repository at this point in the history
  • Loading branch information
10se1ucgo committed Apr 25, 2016
1 parent 6766735 commit ada20b4
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 46 deletions.
66 changes: 41 additions & 25 deletions dwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ def __init__(self):
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):
Expand Down Expand Up @@ -160,38 +161,39 @@ def __init__(self, parent):
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)
middle_app_sizer = wx.BoxSizer(wx.VERTICAL)
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:
Expand Down Expand Up @@ -232,6 +234,7 @@ def __init__(self, parent):
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)

Expand All @@ -243,6 +246,19 @@ def select_all_apps(self, event):
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)
Expand Down
8 changes: 5 additions & 3 deletions dwt_about.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -166,8 +167,9 @@ def __init__(self, parent):


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']
Expand Down
72 changes: 54 additions & 18 deletions dwt_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,41 @@
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):
Expand All @@ -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'))

Expand All @@ -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
Expand All @@ -67,29 +99,29 @@ 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'))


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):
Expand Down Expand Up @@ -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):
Expand All @@ -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
Expand Down

0 comments on commit ada20b4

Please sign in to comment.