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