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