~ubuntu-branches/ubuntu/utopic/mugshot/utopic

« back to all changes in this revision

Viewing changes to mugshot/MugshotWindow.py

  • Committer: Package Import Robot
  • Author(s): Sean Davis
  • Date: 2014-09-01 20:23:33 UTC
  • mfrom: (1.1.5)
  • Revision ID: package-import@ubuntu.com-20140901202333-izr5f0h9y8o1u170
Tags: 0.2.5-0ubuntu1
* New upstream release.
  - Fix: mugshot fails to start for some users (LP: #1353530)

Show diffs side-by-side

added added

removed removed

Lines of Context:
5
5
#
6
6
#   This program is free software: you can redistribute it and/or modify it
7
7
#   under the terms of the GNU General Public License as published by
8
 
#   the Free Software Foundation, either version 3 of the License, or 
 
8
#   the Free Software Foundation, either version 3 of the License, or
9
9
#   (at your option) any later version.
10
10
#
11
11
#   This program is distributed in the hope that it will be useful, but
192
192
        self.fax_entry = builder.get_object('fax')
193
193
 
194
194
        # Users without sudo rights cannot change their name.
195
 
        if not SudoDialog.check_sudo():
196
 
            self.first_name_entry.set_sensitive(False)
197
 
            self.last_name_entry.set_sensitive(False)
 
195
        self.set_name_editable(SudoDialog.check_dependencies(['chfn']))
198
196
 
199
197
        # Stock photo browser
200
198
        self.stock_browser = builder.get_object('stock_browser')
217
215
        # Populate all of the widgets.
218
216
        self.init_user_details()
219
217
 
 
218
    def set_name_editable(self, editable):
 
219
        """Set name fields editable."""
 
220
        self.first_name_entry.set_sensitive(editable)
 
221
        self.last_name_entry.set_sensitive(editable)
 
222
        self.initials_entry.set_sensitive(editable)
 
223
 
220
224
    def init_user_details(self):
221
225
        """Initialize the user details entries and variables."""
222
226
        # Check for .face and set profile image.
248
252
                self.updated_image = None
249
253
                self.set_user_image(None)
250
254
 
251
 
        # Search /etc/passwd for the current user's details.
252
 
        logger.debug('Getting user details from /etc/passwd')
253
 
        for line in open('/etc/passwd', 'r'):
254
 
            if line.startswith(username + ':'):
255
 
                logger.debug('Found details: %s' % line.strip())
256
 
                details = line.split(':')[4].split(',', 3)
257
 
 
258
 
                while len(details) < 4:
259
 
                    details.append("")
260
 
 
261
 
                # Extract the user details
262
 
                name, office, office_phone, home_phone = details
263
 
                break
264
 
 
265
 
        # Expand the user's fullname into first and last.
266
 
        try:
267
 
            first_name, last_name = name.split(' ', 1)
268
 
        except:
269
 
            first_name = name
270
 
            last_name = ''
271
 
 
272
 
        # If the variables are defined as 'none', use blank for cleanliness.
273
 
        if home_phone == 'none':
274
 
            home_phone = ''
275
 
        if office_phone == 'none':
276
 
            office_phone = ''
277
 
 
278
 
        # Get dconf settings
279
 
        logger.debug('Getting initials, email, and fax from dconf')
280
 
        initials = self.settings['initials']
281
 
        email = self.settings['email']
282
 
        fax = self.settings['fax']
 
255
        user_details = self.get_user_details()
283
256
 
284
257
        # Set the class variables
285
 
        self.first_name = first_name
286
 
        self.last_name = last_name
287
 
        self.initials = initials
288
 
        self.home_phone = home_phone
289
 
        self.office_phone = office_phone
 
258
        self.first_name = user_details['first_name']
 
259
        self.last_name = user_details['last_name']
 
260
        self.initials = user_details['initials']
 
261
        self.home_phone = user_details['home_phone']
 
262
        self.office_phone = user_details['office_phone']
 
263
        email = user_details['email']
 
264
        fax = user_details['fax']
290
265
 
291
266
        # Populate the GtkEntries.
292
267
        logger.debug('Populating entries')
336
311
        changes."""
337
312
        logger.debug('Applying changes...')
338
313
        if self.get_chfn_details_updated():
339
 
            if not self.save_chfn_details():
 
314
            success, response = self.save_chfn_details()
 
315
            if not success:
340
316
                # Password was incorrect, complain.
341
 
                primary = _("Authentication Failed")
 
317
                if response in [Gtk.ResponseType.NONE,
 
318
                                Gtk.ResponseType.CANCEL,
 
319
                                Gtk.ResponseType.DELETE_EVENT]:
 
320
                    msg_type = Gtk.MessageType.WARNING
 
321
                    primary = _("Authentication cancelled.")
 
322
                elif response == Gtk.ResponseType.REJECT:
 
323
                    msg_type = Gtk.MessageType.WARNING
 
324
                    primary = _("Authentication failed.")
 
325
                else:
 
326
                    msg_type = Gtk.MessageType.ERROR
 
327
                    primary = _("An error occurred when saving changes.")
 
328
 
342
329
                secondary = _("User details were not updated.")
343
330
                dialog = Gtk.MessageDialog(transient_for=self, flags=0,
344
 
                                           message_type=
345
 
                                           Gtk.MessageType.WARNING,
 
331
                                           message_type=msg_type,
346
332
                                           buttons=Gtk.ButtonsType.OK,
347
333
                                           text=primary)
348
334
                dialog.format_secondary_text(secondary)
458
444
            (path,) = result.unpack()
459
445
 
460
446
            variant = GLib.Variant('(s)',
461
 
                      ('org.freedesktop.Accounts.User',)
462
 
                      )
 
447
                                   ('org.freedesktop.Accounts.User',))
463
448
            result = bus.call_sync('org.freedesktop.Accounts',
464
449
                                   path,
465
450
                                   'org.freedesktop.DBus.Properties',
580
565
        """Handle password prompts from the interactive chfn commands."""
581
566
        # Force the C language for guaranteed english strings in the script.
582
567
        logger.debug('Executing: %s' % command)
583
 
        child = pexpect.spawn(command, env={"LANG": "C"})
584
 
        child.timeout = 5
 
568
        child = SudoDialog.env_spawn(command, 5)
585
569
        child.write_to_stdout = True
586
570
        try:
587
571
            child.expect([".*ssword.*", pexpect.EOF])
607
591
        sudo_dialog.format_secondary_text(_("This is a security measure to "
608
592
                                            "prevent unwanted updates\n"
609
593
                                            "to your personal information."))
610
 
        sudo_dialog.run()
 
594
        response = sudo_dialog.run()
611
595
        sudo_dialog.hide()
612
596
        password = sudo_dialog.get_password()
613
597
        sudo_dialog.destroy()
614
598
 
615
599
        if not password:
616
 
            return False
 
600
            return (False, response)
617
601
 
618
602
        sudo = which('sudo')
619
603
        chfn = which('chfn')
631
615
            home_phone = 'none'
632
616
 
633
617
        # Full name can only be modified by root.  Try using sudo to modify.
634
 
        if SudoDialog.check_sudo():
 
618
        if SudoDialog.check_dependencies(['chfn']):
635
619
            logger.debug('Updating Full Name...')
636
620
            command = "%s %s -f \"%s\" %s" % (sudo, chfn, full_name, username)
637
621
            if self.process_terminal_password(command, password):
654
638
        else:
655
639
            success = False
656
640
 
657
 
        return success
 
641
        return (success, response)
658
642
 
659
643
    # = LibreOffice ========================================================= #
660
644
    def get_libreoffice_details_updated(self):
683
667
        logger.debug('LibreOffice details do not need to be updated.')
684
668
        return False
685
669
 
 
670
    def get_user_details(self):
 
671
        """Use the various methods to get the most up-to-date version of the
 
672
        user details."""
 
673
        # Start with LibreOffice, as users may have configured that first.
 
674
        data = self.get_libreoffice_data()
 
675
 
 
676
        # Next is passwd, where we override name values with system values.
 
677
        pwd_data = self.get_passwd_data()
 
678
        data['first_name'] = pwd_data['first_name']
 
679
        data['last_name'] = pwd_data['last_name']
 
680
        data['initials'] = pwd_data['initials']
 
681
        if len(data['home_phone']) == 0:
 
682
            data['home_phone'] = pwd_data['home_phone']
 
683
        if len(data['office_phone']) == 0:
 
684
            data['office_phone'] = pwd_data['office_phone']
 
685
 
 
686
        # Then get data from dconf
 
687
        initials = self.settings['initials']
 
688
        if len(initials) > 0:
 
689
            data['initials'] = initials
 
690
        email = self.settings['email']
 
691
        if len(data['email']) == 0:
 
692
            data['email'] = email
 
693
        if len(data['fax']) == 0:
 
694
            data['fax'] = self.settings['fax']
 
695
 
 
696
        # Return all of the finalized information.
 
697
        return data
 
698
 
 
699
    def get_passwd_data(self):
 
700
        """Get user details from passwd"""
 
701
        # Use getent for current user's details.
 
702
        try:
 
703
            line = subprocess.check_output(['getent', 'passwd', username])
 
704
            if isinstance(line, bytes):
 
705
                line = line.decode('utf-8')
 
706
            line = line.strip()
 
707
            logger.debug('Found details: %s' % line.strip())
 
708
            details = line.split(':')[4].split(',', 3)
 
709
 
 
710
            while len(details) < 4:
 
711
                details.append("")
 
712
 
 
713
            # Extract the user details
 
714
            name, office, office_phone, home_phone = details
 
715
        except subprocess.CalledProcessError:
 
716
            logger.warning("User %s not found in /etc/passwd. "
 
717
                           "Mugshot may not function correctly." % username)
 
718
            office = ""
 
719
            office_phone = ""
 
720
            home_phone = ""
 
721
 
 
722
        # Use GLib to get the actual name.
 
723
        name = GLib.get_real_name()
 
724
 
 
725
        # Expand the user's fullname into first, last, and initials.
 
726
        initials = name[0]
 
727
        try:
 
728
            first_name, last_name = name.split(' ', 1)
 
729
            initials += last_name[0]
 
730
        except:
 
731
            first_name = name
 
732
            last_name = ''
 
733
 
 
734
        # If the variables are defined as 'none', use blank for cleanliness.
 
735
        if home_phone == 'none':
 
736
            home_phone = ''
 
737
        if office_phone == 'none':
 
738
            office_phone = ''
 
739
 
 
740
        # Pack the data
 
741
        data = {'first_name': first_name, 'last_name': last_name,
 
742
                'home_phone': home_phone, 'office_phone': office_phone,
 
743
                'initials': initials, 'email': '', 'fax': ''}
 
744
 
 
745
        return data
 
746
 
686
747
    def get_libreoffice_data(self):
687
748
        """Get each of the preferences from the LibreOffice
688
749
        registymodifications preferences file.