f3d190d254f9693bd92a1defbea125257f75af63
[lxde/lxadmin.git] / src / lxproxy / lxproxy.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 ### BEGIN LICENSE
4 # Copyright (C) YYYY Leszek Lesner leszek@zevenos.com
5 #This program is free software: you can redistribute it and/or modify it
6 #under the terms of the GNU General Public License version 3, as published
7 #by the Free Software Foundation.
8 #
9 #This program is distributed in the hope that it will be useful, but
10 #WITHOUT ANY WARRANTY; without even the implied warranties of
11 #MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
12 #PURPOSE. See the GNU General Public License for more details.
13 #
14 #You should have received a copy of the GNU General Public License along
15 #with this program. If not, see <http://www.gnu.org/licenses/>.
16 ### END LICENSE
17
18 import sys
19 import os
20 import gtk
21 from user import home
22
23 import lxadmin.defs as defs
24
25 # Check if we are working in the source tree or from the installed
26 # package and mangle the python path accordingly
27 if os.path.dirname(sys.argv[0]) != ".":
28 if sys.argv[0][0] == "/":
29 fullPath = os.path.dirname(sys.argv[0])
30 sys.path.insert(0, os.path.join(defs.SHARED_DATA_DIR,"lxproxy"))
31 else:
32 fullPath = os.getcwd() + "/" + os.path.dirname(sys.argv[0])
33 else:
34 fullPath = os.getcwd()
35 sys.path.insert(0, os.path.dirname(fullPath))
36 DEFAULTDICT = {"export http_proxy": "http://user:password@hostname:8080",
37 "export https_proxy": "http://user:password@hostname:8080",
38 "export ftp_proxy": "http://user:password@hostname:8080"}
39
40 import AboutLxproxyDialog
41 from lxproxyconfig import getdatapath
42
43 class LxproxyWindow(gtk.Window):
44 __gtype_name__ = "LxproxyWindow"
45
46 def __init__(self):
47 """__init__ - This function is typically not called directly.
48 Creation a LxproxyWindow requires redeading the associated ui
49 file and parsing the ui definition extrenally,
50 and then calling LxproxyWindow.finish_initializing().
51
52 Use the convenience function NewLxproxyWindow to create
53 LxproxyWindow object.
54
55 """
56 pass
57
58 def finish_initializing(self, builder):
59 """finish_initalizing should be called after parsing the ui definition
60 and creating a LxproxyWindow object with it in order to finish
61 initializing the start of the new LxproxyWindow instance.
62
63 """
64 #get a reference to the builder and set up the signals
65 self.builder = builder
66 self.builder.connect_signals(self)
67 global httptxt, httpstxt, ftptxt, sockstxt, httpspin, httpsspin, ftpspin, socksspin,directradio,manualradio
68 directradio = self.builder.get_object("directradio")
69 manualradio = self.builder.get_object("manualradio")
70 httptxt = self.builder.get_object("httptxt")
71 httpstxt = self.builder.get_object("httpstxt")
72 ftptxt = self.builder.get_object("ftptxt")
73 sockstxt = self.builder.get_object("sockstxt")
74 httpspin = self.builder.get_object("httpspin")
75 httpsspin = self.builder.get_object("httpsspin")
76 ftpspin = self.builder.get_object("ftpspin")
77 socksspin = self.builder.get_object("socksspin")
78 socksbox = self.builder.get_object("hbox4")
79 socksbox.hide()
80 if manualradio.get_active():
81 httptxt.set_sensitive(True)
82 httpstxt.set_sensitive(True)
83 ftptxt.set_sensitive(True)
84 sockstxt.set_sensitive(True)
85 httpspin.set_sensitive(True)
86 httpsspin.set_sensitive(True)
87 ftpspin.set_sensitive(True)
88 socksspin.set_sensitive(True)
89 else:
90 httptxt.set_sensitive(False)
91 httpstxt.set_sensitive(False)
92 ftptxt.set_sensitive(False)
93 sockstxt.set_sensitive(False)
94 httpspin.set_sensitive(False)
95 httpsspin.set_sensitive(False)
96 ftpspin.set_sensitive(False)
97 socksspin.set_sensitive(False)
98 httpspin.set_value(8080)
99 httpsspin.set_value(8080)
100 ftpspin.set_value(8080)
101 socksspin.set_value(8080)
102
103 self.readfile()
104
105 #uncomment the following code to read in preferences at start up
106 #dlg = PreferencesLxproxyDialog.NewPreferencesLxproxyDialog()
107 #self.preferences = dlg.get_preferences()
108
109 #code for other initialization actions should be added here
110
111 def readfile(self):
112 profile_location = os.path.expanduser('~/.profile')
113 if not os.path.exists(profile_location):
114 tmpfile = open(profile_location, 'w')
115 tmpfile.write('')
116 tmpfile.close()
117 try:
118 data = profile_location.read()
119 profile_location.close()
120 config = self.parse(data)
121 except:
122 print "Could not open proxyconfig"
123
124 def parse(self, s):
125 #Fetch a *copy* of the default dictionary.
126 ret = DEFAULTDICT.copy()
127 # Split lines
128 lines = s.split("\n")
129 for line in lines:
130 line = line.strip()
131 #if line and line[0] != "#":
132 if line.startswith('export'):
133 manualradio.set_active(True)
134 values = line.split("=")
135 ret[values[0]] = values[1]
136
137 try:
138 #print ret # Debugging
139 port=ret["export http_proxy"].split(":")
140 httptxt.set_text(port[0]+":"+port[1]+":"+port[2])
141 httpspin.set_value(float(port[3]))
142 port=ret["export https_proxy"].split(":")
143 httpstxt.set_text(port[0]+":"+port[1]+":"+port[2])
144 httpsspin.set_value(float(port[3]))
145 port=ret["export ftp_proxy"].split(":")
146 ftptxt.set_text(port[0]+":"+port[1]+":"+port[2])
147 ftpspin.set_value(float(port[3]))
148 except:
149 try:
150 port=ret["export http_proxy"].split(":")
151 httptxt.set_text(port[0]+":"+port[1])
152 httpspin.set_value(float(port[2]))
153 port=ret["export https_proxy"].split(":")
154 httpstxt.set_text(port[0]+":"+port[1])
155 httpsspin.set_value(float(port[2]))
156 port=ret["export ftp_proxy"].split(":")
157 ftptxt.set_text(port[0]+":"+port[1])
158 ftpspin.set_value(float(port[2]))
159 except:
160 httptxt.set_text(ret["export http_proxy"])
161 httpstxt.set_text(ret["export https_proxy"])
162 ftptxt.set_text(ret["export ftp_proxy"])
163
164
165 def on_closebtn_clicked(self,widget):
166 if directradio.get_active():
167 file(home+'/.profile2', 'w').writelines([l for l in file(home+'/.profile').readlines() if 'export http_proxy' not in l])
168 os.system("mv "+ home+"/.profile2 " + home + "/.profile")
169 file(home+'/.profile2', 'w').writelines([l for l in file(home+'/.profile').readlines() if 'export https_proxy' not in l])
170 os.system("mv "+ home+"/.profile2 " + home + "/.profile")
171 file(home+'/.profile2', 'w').writelines([l for l in file(home+'/.profile').readlines() if 'export ftp_proxy' not in l])
172 os.system("mv "+ home+"/.profile2 " + home + "/.profile")
173 file(home+'/.profile2', 'w').writelines([l for l in file(home+'/.profile').readlines() if 'export HTTP_PROXY' not in l])
174 os.system("mv "+ home+"/.profile2 " + home + "/.profile")
175 file(home+'/.profile2', 'w').writelines([l for l in file(home+'/.profile').readlines() if 'export HTTPS_PROXY' not in l])
176 os.system("mv "+ home+"/.profile2 " + home + "/.profile")
177 file(home+'/.profile2', 'w').writelines([l for l in file(home+'/.profile').readlines() if 'export FTP_PROXY' not in l])
178 os.system("mv "+ home+"/.profile2 " + home + "/.profile")
179 else:
180 os.system("echo 'export http_proxy="+httptxt.get_text()+":"+str(httpspin.get_value())[:-2]+"' >> "+ home+ "/.profile")
181 os.system("echo 'export https_proxy="+httpstxt.get_text()+":"+str(httpsspin.get_value())[:-2]+"' >> "+ home+ "/.profile")
182 os.system("echo 'export ftp_proxy="+ftptxt.get_text()+":"+str(ftpspin.get_value())[:-2]+"' >> "+ home+ "/.profile")
183 os.system("echo 'export HTTP_PROXY=$http_proxy' >> "+ home+ "/.profile")
184 os.system("echo 'export HTTPS_PROXY=$https_proxy' >> "+ home+ "/.profile")
185 os.system("echo 'export FTP_PROXY=$ftp_proxy' >> "+ home+ "/.profile")
186 self.quit(self,widget)
187
188 def on_manualradio_toggled(self,widget):
189 httptxt.set_sensitive(True)
190 httpstxt.set_sensitive(True)
191 ftptxt.set_sensitive(True)
192 sockstxt.set_sensitive(True)
193 httpspin.set_sensitive(True)
194 httpsspin.set_sensitive(True)
195 ftpspin.set_sensitive(True)
196 socksspin.set_sensitive(True)
197
198 def on_directradio_toggled(self,widget):
199 httptxt.set_sensitive(False)
200 httpstxt.set_sensitive(False)
201 ftptxt.set_sensitive(False)
202 sockstxt.set_sensitive(False)
203 httpspin.set_sensitive(False)
204 httpsspin.set_sensitive(False)
205 ftpspin.set_sensitive(False)
206 socksspin.set_sensitive(False)
207
208
209 def about(self, widget, data=None):
210 """about - display the about box for lxproxy """
211 about = AboutLxproxyDialog.NewAboutLxproxyDialog()
212 response = about.run()
213 about.destroy()
214
215 def preferences(self, widget, data=None):
216 """preferences - display the preferences window for lxproxy """
217 prefs = PreferencesLxproxyDialog.NewPreferencesLxproxyDialog()
218 response = prefs.run()
219 if response == gtk.RESPONSE_OK:
220 #make any updates based on changed preferences here
221 pass
222 prefs.destroy()
223
224 def quit(self, widget, data=None):
225 """quit - signal handler for closing the LxproxyWindow"""
226 self.destroy()
227
228 def on_destroy(self, widget, data=None):
229 """on_destroy - called when the LxproxyWindow is close. """
230 #clean up code for saving application state should be added here
231
232 gtk.main_quit()
233
234 def NewLxproxyWindow():
235 """NewLxproxyWindow - returns a fully instantiated
236 LxproxyWindow object. Use this function rather than
237 creating a LxproxyWindow directly.
238 """
239
240 #look for the ui file that describes the ui
241 #ui_filename = os.path.join(getdatapath(), 'ui', 'lxproxy', 'LxproxyWindow.ui')
242 #if not os.path.exists(ui_filename):
243 # ui_filename = None
244 #
245 builder = gtk.Builder()
246 builder.add_from_file(getdatapath('LxproxyWindow.ui'))
247 window = builder.get_object("lxproxy_window")
248 window.finish_initializing(builder)
249 return window
250
251 if __name__ == "__main__":
252 #support for command line options
253 import logging, optparse
254 parser = optparse.OptionParser(version="%prog %ver")
255 parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Show debug messages")
256 (options, args) = parser.parse_args()
257
258 #set the logging level to show debug messages
259 if options.verbose:
260 logging.basicConfig(level=logging.DEBUG)
261 logging.debug('logging enabled')
262
263 #run the application
264 window = NewLxproxyWindow()
265 window.show()
266 gtk.main()
267