a5f04c19530847a82c3979dce4f5db48eb4b0301
[moonshot-ui.git] / src / moonshot-identity-manager-app.vala
1 using Gee;
2 using Gtk;
3
4 #if IPC_DBUS
5 [DBus (name = "org.janet.Moonshot")]
6 interface IIdentityManager : GLib.Object {
7 #if IPC_DBUS_GLIB
8     public abstract bool show_ui() throws DBus.Error;
9 #else
10     public abstract bool show_ui() throws IOError;
11 #endif
12 }
13 #endif
14
15 public class IdentityManagerApp {
16     public IdentityManagerModel model;
17     public IdCard default_id_card;
18     public bool explicitly_launched;
19     public IdentityManagerView view;
20     private MoonshotServer ipc_server;
21
22 #if OS_MACOS
23         public OSXApplication osxApp;
24   
25     // the signal handler function.
26     // the current instance of our app class is passed in the 
27     // id_manager_app_instanceparameter 
28         public static bool on_osx_open_files (OSXApplication osx_app_instance, 
29                                         string file_name, 
30                                         IdentityManagerApp id_manager_app_instance ) {
31     int added_cards = id_manager_app_instance.ipc_server.install_from_file(file_name);
32     return true;
33         }
34 #endif
35
36     private const int WINDOW_WIDTH = 400;
37     private const int WINDOW_HEIGHT = 500;
38     public void show() {
39         if (view != null) view.show();    
40     }
41         
42     public IdentityManagerApp (bool headless, bool use_flat_file_store) {
43 #if GNOME_KEYRING
44         bool keyring_available = GnomeKeyring.is_available();
45 #else
46         bool keyring_available = false;
47 #endif
48         IIdentityCardStore.StoreType store_type;
49         if (headless || use_flat_file_store || !keyring_available)
50             store_type = IIdentityCardStore.StoreType.FLAT_FILE;
51         else
52             store_type = IIdentityCardStore.StoreType.KEYRING;
53
54         model = new IdentityManagerModel(this, store_type);
55         /* if headless, but we have nothing in the flat file store
56          * and keyring is available, switch to keyring */
57         if (headless && keyring_available && !use_flat_file_store && !model.HasNonTrivialIdentities())
58             model.set_store_type(IIdentityCardStore.StoreType.KEYRING);
59
60         if (!headless)
61             view = new IdentityManagerView(this);
62         LinkedList<IdCard> card_list = model.get_card_list() ;
63         if (card_list.size > 0)
64             this.default_id_card = card_list.first();
65
66         init_ipc_server ();
67
68 #if OS_MACOS
69
70         osxApp = OSXApplication.get_instance();
71         // The 'correct' way of connrcting wont work in Mac OS with Vala 0.12   e.g.    
72         //              osxApp.ns_application_open_file.connect(install_from_file);
73         // so we have to use this old way
74         Signal.connect(osxApp, "NSApplicationOpenFile", (GLib.Callback)(on_osx_open_files), this);
75
76 #endif
77     }
78
79     public bool add_identity (IdCard id, bool force_flat_file_store) {
80         if (view != null) return view.add_identity(id, force_flat_file_store);
81         model.add_card(id, force_flat_file_store);
82         return true;
83     }
84
85     public void select_identity (IdentityRequest request) {
86         IdCard identity = null;
87
88         if (request.select_default)
89         {
90             identity = default_id_card;
91         }
92
93         if (identity == null)
94         {
95             bool has_nai = request.nai != null && request.nai != "";
96             bool has_srv = request.service != null && request.service != "";
97             bool confirm = false;
98             IdCard nai_provided = null;
99
100             foreach (IdCard id in model.get_card_list())
101             {
102                 /* If NAI matches we add id card to the candidate list */
103                 if (has_nai && request.nai == id.nai)
104                 {
105                     nai_provided = id;
106                     request.candidates.append (id);
107                     continue;
108                 }
109
110                 /* If any service matches we add id card to the candidate list */
111                 if (has_srv)
112                 {
113                     foreach (string srv in id.services)
114                     {
115                         if (request.service == srv)
116                         {
117                             request.candidates.append (id);
118                             continue;
119                         }
120                     }
121                 }
122             }
123
124             /* If more than one candidate we dissasociate service from all ids */
125             if (has_srv && request.candidates.length() > 1)
126             {
127                 foreach (IdCard id in request.candidates)
128                 {
129                     int i = 0;
130                     SList<string> services_list = null;
131                     bool has_service = false;
132
133                     foreach (string srv in id.services)
134                     {
135                         if (srv == request.service)
136                         {
137                             has_service = true;
138                             continue;
139                         }
140                         services_list.append (srv);
141                     }
142                     
143                     if (!has_service)
144                         continue;
145
146                     if (services_list.length () == 0)
147                     {
148                         id.services = {};
149                         continue;
150                     }
151
152                     string[] services = new string[services_list.length ()];
153                     foreach (string srv in services_list)
154                     {
155                         services[i] = srv;
156                         i++;
157                     }
158
159                     id.services = services;
160                 }
161             }
162
163 //            model.store_id_cards ();
164
165             /* If there are no candidates we use the service matching rules */
166             if (request.candidates.length () == 0)
167             {
168                 foreach (IdCard id in model.get_card_list())
169                 {
170                     foreach (Rule rule in id.rules)
171                     {
172                         if (!match_service_pattern (request.service, rule.pattern))
173                             continue;
174
175                         request.candidates.append (id);
176
177                         if (rule.always_confirm == "true")
178                             confirm = true;
179                     }
180                 }
181             }
182             
183             if (request.candidates.length () > 1)
184             {
185                 if (has_nai && nai_provided != null)
186                 {
187                     identity = nai_provided;
188                     confirm = false;
189                 }
190                 else
191                     confirm = true;
192             }
193             if (identity == null)
194                 identity = request.candidates.nth_data (0);
195             if ((identity != null) && 
196                 ((identity.password == null) || (identity.password == "")))
197                 identity.password = request.password;
198             if (identity == null) {
199                 if (has_nai) {
200                     // create a temp identity
201                     string[] components = request.nai.split("@", 2);
202                     identity = new IdCard();
203                     identity.display_name = request.nai;
204                     identity.username = components[0];
205                     if (components.length > 1)
206                         identity.issuer = components[1];
207                     identity.password = request.password;
208                 } else {
209                     confirm = true;
210                 }
211             }
212
213             /* TODO: If candidate list empty return fail */
214             
215             if (confirm && (view != null))
216             {
217                 if (!explicitly_launched)
218                     show();
219                 view.queue_identity_request(request);
220                 return;
221             }
222         }
223         // Send back the identity (we can't directly run the
224         // callback because we may be being called from a 'yield')
225         Idle.add(
226             () => {
227                 if (view != null) {
228                     identity = view.check_add_password(identity, request, model);
229                 }
230                 request.return_identity (identity);
231 // The following occasionally causes the app to exit without sending the dbus
232 // reply, so for now we just don't exit
233 //                if (!explicitly_launched)
234 //                    Idle.add( () => { Gtk.main_quit(); return false; } );
235                 return false;
236             }
237         );
238         return;
239     }
240
241     private bool match_service_pattern (string service, string pattern)
242     {
243         var pspec = new PatternSpec (pattern);
244         return pspec.match_string (service);
245     }   
246     
247 #if IPC_MSRPC
248     private void init_ipc_server ()
249     {
250         // Errors will currently be sent via g_log - ie. to an
251         // obtrusive message box, on Windows
252         //
253         this.ipc_server = MoonshotServer.get_instance ();
254         MoonshotServer.start (this);
255     }
256 #elif IPC_DBUS_GLIB
257     private void init_ipc_server ()
258     {
259         try {
260             var conn = DBus.Bus.get (DBus.BusType.SESSION);
261             dynamic DBus.Object bus = conn.get_object ("org.freedesktop.DBus",
262                                                        "/org/freedesktop/DBus",
263                                                        "org.freedesktop.DBus");
264
265             // try to register service in session bus
266             uint reply = bus.request_name ("org.janet.Moonshot", (uint) 0);
267             if (reply == DBus.RequestNameReply.PRIMARY_OWNER)
268             {
269                 this.ipc_server = new MoonshotServer (this);
270                 conn.register_object ("/org/janet/moonshot", ipc_server);
271             } else {
272                 bool shown=false;
273                 GLib.Error e;
274                 DBus.Object manager_proxy = conn.get_object ("org.janet.Moonshot",
275                                                              "/org/janet/moonshot",
276                                                              "org.janet.Moonshot");
277                 if (manager_proxy != null)
278                     manager_proxy.call("ShowUi", out e, GLib.Type.INVALID, typeof(bool), out shown, GLib.Type.INVALID);
279
280                 if (!shown) {
281                     GLib.error ("Couldn't own name org.janet.Moonshot on dbus or show previously launched identity manager.");
282                 } else {
283                     stdout.printf("Showed previously launched identity manager.\n");
284                     GLib.Process.exit(0);
285                 }
286             }
287         }
288         catch (DBus.Error e)
289         {
290             stderr.printf ("%s\n", e.message);
291         }
292     }
293 #else
294     private void bus_acquired_cb (DBusConnection conn)
295     {
296         try {
297             conn.register_object ("/org/janet/moonshot", ipc_server);
298         }
299         catch (Error e)
300         {
301             stderr.printf ("%s\n", e.message);
302         }
303     }
304
305     private void init_ipc_server ()
306     {
307         this.ipc_server = new MoonshotServer (this);
308         GLib.Bus.own_name (GLib.BusType.SESSION,
309                            "org.janet.Moonshot",
310                            GLib.BusNameOwnerFlags.NONE,
311                            bus_acquired_cb,
312                            (conn, name) => {},
313                            (conn, name) => {
314                                bool shown=false;
315                                try {
316                                    IIdentityManager manager = Bus.get_proxy_sync (BusType.SESSION, name, "/org/janet/moonshot");
317                                    shown = manager.show_ui();
318                                } catch (IOError e) {
319                                }
320                                if (!shown) {
321                                    GLib.error ("Couldn't own name %s on dbus or show previously launched identity manager.", name);
322                                } else {
323                                    stdout.printf("Showed previously launched identity manager.\n");
324                                    GLib.Process.exit(0);
325                                }
326                            });
327     }
328 #endif
329 }
330
331 static bool explicitly_launched = true;
332 static bool use_flat_file_store = false;
333 const GLib.OptionEntry[] options = {
334     {"dbus-launched",0,GLib.OptionFlags.REVERSE,GLib.OptionArg.NONE,
335      ref explicitly_launched,"launch for dbus rpc use",null},
336     {"flat-file-store",0,0,GLib.OptionArg.NONE,
337      ref use_flat_file_store,"force use of flat file identity store (used by default only for headless operation)",null},
338     {null}
339 };
340
341
342 public static int main(string[] args){
343 #if IPC_MSRPC
344         bool headless = false;
345 #else
346         bool headless = GLib.Environment.get_variable("DISPLAY") == null;
347 #endif
348
349         if (headless) {
350             try {
351                 var opt_context = new OptionContext(null);
352                 opt_context.set_help_enabled (true);
353                 opt_context.add_main_entries (options, null);
354                 opt_context.parse(ref args);
355             } catch (OptionError e) {
356                 stdout.printf(_("error: %s\n"),e.message);
357                 stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
358                 return -1;
359             }
360             explicitly_launched = false;
361         } else {
362             try {
363                 if (!Gtk.init_with_args(ref args, _(""), options, null)) {
364                     stdout.printf(_("unable to initialize window\n"));
365                     return -1;
366                 }
367             } catch (GLib.Error e) {
368                 stdout.printf(_("error: %s\n"),e.message);
369                 stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
370                 return -1;
371             }
372             gtk_available = true;
373         }
374
375 #if OS_WIN32
376         // Force specific theme settings on Windows without requiring a gtkrc file
377         Gtk.Settings settings = Gtk.Settings.get_default ();
378         settings.set_string_property ("gtk-theme-name", "ms-windows", "moonshot");
379         settings.set_long_property ("gtk-menu-images", 0, "moonshot");
380 #endif
381
382         Intl.bindtextdomain (Config.GETTEXT_PACKAGE, Config.LOCALEDIR);
383         Intl.bind_textdomain_codeset (Config.GETTEXT_PACKAGE, "UTF-8");
384         Intl.textdomain (Config.GETTEXT_PACKAGE);
385        
386            
387         var app = new IdentityManagerApp(headless, use_flat_file_store);
388         app.explicitly_launched = explicitly_launched;
389         
390         if (app.explicitly_launched) {
391             app.show();
392         }
393
394         if (headless) {
395 #if !IPC_MSRPC
396             MainLoop loop = new MainLoop();
397             loop.run();
398 #endif
399         } else {
400             Gtk.main();
401         }
402
403         return 0;
404     }
405