Exemplo n.º 1
0
    def __init__(self, peer_options={}):
        self.peer_options = DEFAULT_OTR_FLAGS.copy()
        self.peer_options.update(peer_options)
        path = ApplicationData.get('chat')
        makedirs(path)

        super(BlinkOtrAccount, self).__init__('blink', 'sip', '1024', privkey=None)
        self.defaultQuery = b'?OTRv{versions}?\n{accountname} has requested ' \
                            b'end-to-end encryption but this ' \
                            b'software does not support this feature. ';

        self.keyFilePath = ApplicationData.get('chat/private_key.dsa')
        self.trustedPeersPath = ApplicationData.get('chat/trusted_peers')
Exemplo n.º 2
0
    def cropAndAddImage(self, path):
        try:
            image = NSImage.alloc().initWithContentsOfFile_(path)
        except:
            NSRunAlertPanel("Invalid Image", u"%s is not a valid image."%path, "OK", None, None)
            return

        rect = NSZeroRect.copy()
        rect.size = image.size()
        curSize = self.cropWindow.frame().size
        if rect.size.width > curSize.width or rect.size.height > curSize.height:
            self.cropWindowImage.setFrame_(rect)
        self.cropOriginalImage = image.copy()
        self.cropWindowImage.setImage_(image)

        if NSApp.runModalForWindow_(self.cropWindow) == NSOKButton:
            path = ApplicationData.get('photos')
            dt = datetime.datetime.now().strftime("%Y%m%d%H%M%S")

            image = self.cropWindowImage.getCropped()
            path = path+"/photo%s.tiff"%dt
            image.TIFFRepresentation().writeToFile_atomically_(path, False)

            self.cropWindow.orderOut_(None)

            self.refreshLibrary()
        else:
            self.cropWindow.orderOut_(None)
Exemplo n.º 3
0
    def addImageFile(self, path):
        photodir = ApplicationData.get('photos')
        path = os.path.normpath(path)

        if os.path.dirname(path) != photodir:
            # scale and copy the image to our photo dir
            try:
                image = NSImage.alloc().initWithContentsOfFile_(path)
            except:
                NSRunAlertPanel("Invalid Image", u"%s is not a valid image."%path, "OK", None, None)
                return

            size = image.size()
            if size.width > 128 or size.height > 128:
                image.setScalesWhenResized_(True)
                image.setSize_(NSMakeSize(128, 128 * size.height/size.width))

            finalpath = photodir+"/"+os.path.basename(path)
            prefix, ext = os.path.splitext(finalpath)
            i= 0
            while os.path.exists(finalpath):
                finalpath = prefix+str(i)+ext

            image.TIFFRepresentation().writeToFile_atomically_(finalpath, False)
            self.refreshLibrary()
Exemplo n.º 4
0
    def save_certificates(self, response):
        passport = response["passport"]
        address = response["sip_address"]

        tls_folder = ApplicationData.get('tls')
        if not os.path.exists(tls_folder):
            os.mkdir(tls_folder, 0o700)

        ca = passport["ca"].strip() + os.linesep
        self.add_certificate_authority(ca)

        crt = passport["crt"].strip() + os.linesep
        try:
            X509Certificate(crt)
        except GNUTLSError as e:
            BlinkLogger().log_error("Invalid TLS certificate: %s" % e)
            return None

        key = passport["key"].strip() + os.linesep
        try:
            X509PrivateKey(key)
        except GNUTLSError as e:
            BlinkLogger().log_error("Invalid Private Key: %s" % e)
            return None

        crt_path = os.path.join(tls_folder, address + ".crt")
        f = open(crt_path, "w")
        os.chmod(crt_path, 0o600)
        f.write(crt)
        f.write(key)
        f.close()
        BlinkLogger().log_info("Saved new TLS Certificate and Private Key to %s" % crt_path)

        return crt_path
Exemplo n.º 5
0
 def purge_screenshots():
     screenshots_folder = ApplicationData.get('.tmp_screenshots')
     if os.path.exists(screenshots_folder):
         try:
             shutil.rmtree(screenshots_folder)
         except EnvironmentError:
             pass
Exemplo n.º 6
0
 def purge_temporary_files(self):
     for dir in ('.tmp_screenshots', '.tmp_snapshots', '.tmp_file_transfers'):
         folder = ApplicationData.get(dir)
         if os.path.exists(folder):
             try:
                 shutil.rmtree(folder)
             except EnvironmentError:
                 pass
Exemplo n.º 7
0
 def loadConfigurations(self):
     self.storage_path = ApplicationData.get(
         'conference_configurations.pickle')
     try:
         self.conference_configurations = cPickle.load(
             open(self.storage_path))
     except:
         self.conference_configurations = {}
Exemplo n.º 8
0
 def purge_temporary_files(self):
     for dir in ('.tmp_screenshots', '.tmp_snapshots', '.tmp_file_transfers'):
         folder = ApplicationData.get(dir)
         if os.path.exists(folder):
             try:
                 shutil.rmtree(folder)
             except EnvironmentError:
                 pass
Exemplo n.º 9
0
    def offlineWindowConfirm_(self, sender):
        note = unicode(self.offlineNote.stringValue())
        activity = unicode(self.offlineActivity.titleOfSelectedItem())

        self.offlineWindow.performClose_(None)

        storage_path = ApplicationData.get('presence_offline_')
        cPickle.dump({"note":note, "activity":activity}, open(storage_path, "w+"))
Exemplo n.º 10
0
    def loadConfigurations(self):
        path = ApplicationData.get('conference')
        makedirs(path)

        try:
            with open(self.storage_path, 'rb') as f:
                self.conference_configurations = pickle.load(f)
        except Exception as e:
            self.conference_configurations = {}
Exemplo n.º 11
0
    def __init__(self,
                 target=None,
                 participants=[],
                 media_type=["chat"],
                 default_domain=None,
                 autostart=False):
        NSBundle.loadNibNamed_owner_("JoinConferenceWindow", self)

        self.autostart = autostart
        self.notification_center = NotificationCenter()
        self.notification_center.add_observer(
            self, name='BonjourConferenceServicesDidRemoveServer')
        self.notification_center.add_observer(
            self, name='BonjourConferenceServicesDidUpdateServer')
        self.notification_center.add_observer(
            self, name='BonjourConferenceServicesDidAddServer')
        self.notification_center.add_observer(
            self, name='SIPAccountManagerDidChangeDefaultAccount')
        self.startWhenParticipantsAvailable.setEnabled_(False)

        self.storage_path = ApplicationData.get('conference/rooms.pickle')

        self.selected_configuration = None

        self.default_domain = default_domain

        self.nickname = None

        if target is not None and "@" not in target and self.default_domain:
            target = '%s@%s' % (target, self.default_domain)

        if target is not None and validateParticipant(target):
            self.room.setStringValue_(target)

        account = AccountManager().default_account
        if account is not None:
            self.nickname_textfield.setStringValue_(account.conference.nickname
                                                    or account.display_name)

        if participants:
            self._participants = participants
        else:
            self._participants = []

        self.participantsTable.reloadData()
        self.removeAllParticipants.setHidden_(
            False if len(self._participants) > 1 else True)

        if media_type:
            self.audio.setState_(NSOnState if "audio" in
                                 media_type else NSOffState)
            self.chat.setState_(NSOnState if "chat" in
                                media_type else NSOffState)

        self.updatePopupButtons()
Exemplo n.º 12
0
    def offlineWindowConfirm_(self, sender):
        note = unicode(self.offlineNote.stringValue())
        activity = unicode(self.offlineActivity.titleOfSelectedItem())

        self.offlineWindow.performClose_(None)

        storage_path = ApplicationData.get('presence_offline_')
        cPickle.dump({
            "note": note,
            "activity": activity
        }, open(storage_path, "w+"))
Exemplo n.º 13
0
    def loadConfigurations(self):
        path = ApplicationData.get('conference')
        makedirs(path)

        try:
            with open(ApplicationData.get('conference_configurations.pickle')): pass
        except IOError:
            pass
        else:
            src = ApplicationData.get('conference_configurations.pickle')
            dst = ApplicationData.get('conference/conference_configurations.pickle')
            try:
                shutil.move(src, dst)
            except shutil.Error:
                pass

        self.storage_path = ApplicationData.get('conference/conference_configurations.pickle')
        try:
            self.conference_configurations = cPickle.load(open(self.storage_path))
        except:
            self.conference_configurations = {}
    def loadConfigurations(self):
        path = ApplicationData.get('conference')
        makedirs(path)

        try:
            with open(ApplicationData.get('conference_configurations.pickle'), 'rb'): pass
        except IOError:
            pass
        else:
            src = ApplicationData.get('conference_configurations.pickle')
            dst = ApplicationData.get('conference/conference_configurations.pickle')
            try:
                shutil.move(src, dst)
            except shutil.Error:
                pass

        try:
            with open(ApplicationData.get('conference/conference_configurations.pickle'), 'rb') as f:
                self.conference_configurations = pickle.load(f)
        except:
            self.conference_configurations = {}
Exemplo n.º 15
0
    def initWithFrame_transfer_(self, frame, transfer):
        self = NSView.initWithFrame_(self, frame)
        if self:
            self.transfer = transfer
            NotificationCenter().add_observer(self, sender=transfer)

            NSBundle.loadNibNamed_owner_("FileTransferItemView", self)

            self.file_path = os.path.basename(self.transfer.ft_info.file_path)
            self.nameText.setStringValue_(self.file_path)
            self.remote_uri = self.transfer.ft_info.remote_uri
            self.local_uri = self.transfer.ft_info.local_uri

            if type(self.transfer) == OutgoingPushFileTransferHandler:
                self.fromText.setStringValue_("To:  %s" %
                                              self.transfer.account.id)
            else:
                self.fromText.setStringValue_("From:  %s" %
                                              self.transfer.account.id)
            self.revealButton.setHidden_(True)

            # XXX: there should be a better way to do this!
            tmp_folder = ApplicationData.get('.tmp_file_transfers')
            makedirs(tmp_folder, 0o700)
            tmpf = tmp_folder + "/tmpf-" + self.file_path.decode(
            ) if isinstance(self.file_path, bytes) else self.file_path
            with open(tmpf, "wb+"):
                self.updateIcon(
                    NSWorkspace.sharedWorkspace().iconForFile_(tmpf))
            unlink(tmpf)

            self.updateProgressInfo()
            self.progressBar.setIndeterminate_(True)
            self.progressBar.startAnimation_(None)

            self.checksumProgressBar.setIndeterminate_(False)
            self.checksumProgressBar.startAnimation_(None)

            if transfer.direction == 'outgoing':
                self.progressBar.setHidden_(True)
                self.checksumProgressBar.setHidden_(False)
            else:
                self.progressBar.setHidden_(False)
                self.checksumProgressBar.setHidden_(True)

            frame.size = self.view.frame().size
            self.setFrame_(frame)
            self.addSubview_(self.view)
            self.originalHeight = NSHeight(frame)
        return self
Exemplo n.º 16
0
    def storeCaptured(self):
        path = ApplicationData.get('photos')
        makedirs(path)

        dt = datetime.datetime.now().strftime("%Y%m%d%H%M%S")

        if not self.photoView.image():
            self.captureImage()

        image = self.photoView.getCropped()
        path = path+"/photo%s.tiff"%dt
        image.TIFFRepresentation().writeToFile_atomically_(path, False)
        self.refreshLibrary()
        return path, image
Exemplo n.º 17
0
    def refreshLibrary(self):
        settings = SIPSimpleSettings()
        own_icon_path = settings.presence_state.icon
        selected_icon = None
        def md5sum(filename):
            md5 = hashlib.md5()
            with open(filename,'rb') as f:
                for chunk in iter(lambda: f.read(128*md5.block_size), b''):
                    md5.update(chunk)
            return md5.hexdigest()

        path = ApplicationData.get('photos')

        if os.path.exists(path):
          files = os.listdir(path)
        else:
          files = []
        array = NSMutableArray.array()
        knownFiles = set()
        for item in self.contentArrayController.arrangedObjects():
            knownFiles.add(unicode(item.objectForKey_("path")))

        seen_md5sum = {}
        i = 0
        for f in files:
            if not f.startswith('user_icon') and not f.startswith('photo') and f != 'default_user_icon.tiff':
                continue
            p = os.path.normpath(path+"/"+f)
            if p not in knownFiles:
                photos_folder = unicodedata.normalize('NFC', path)
                filename = os.path.join(photos_folder, f)
                checksum = md5sum(filename)
                try:
                    seen_md5sum[filename]
                except KeyError:
                    seen_md5sum[filename] = checksum
                    image = NSImage.alloc().initWithContentsOfFile_(p)
                    if not image:
                        continue
                    item = NSDictionary.dictionaryWithObjectsAndKeys_(image, "picture", p, "path")
                    array.addObject_(item)
                    if own_icon_path is not None and filename == unicode(own_icon_path):
                        selected_icon = i
                    i += 1

        if array.count() > 0:
            self.contentArrayController.addObjects_(array)
            if selected_icon is not None:
                self.libraryCollectionView.setSelectionIndexes_(NSIndexSet.indexSetWithIndex_(selected_icon))
Exemplo n.º 18
0
    def showPresenceOfflineStatus_(self, sender):
        if not self.offlineWindowShown:
            NSBundle.loadNibNamed_owner_("PresenceOfflineWindow", self)
            fillPresenceMenu(self.offlineActivity.menu(), None, None)
            self.offlineWindowShown = True
        
        try:
            storage_path = ApplicationData.get('presence_offline_')
            info = cPickle.load(open(storage_path, "r"))
            self.offlineNote.setStringValue_(info["note"])
            self.offlineActivity.selectItemWithTitle_(info["activity"])
        except (cPickle.UnpicklingError, IOError):
            pass

        self.offlineWindow.makeKeyAndOrderFront_(None)
Exemplo n.º 19
0
    def showPresenceOfflineStatus_(self, sender):
        if not self.offlineWindowShown:
            NSBundle.loadNibNamed_owner_("PresenceOfflineWindow", self)
            fillPresenceMenu(self.offlineActivity.menu(), None, None)
            self.offlineWindowShown = True

        try:
            storage_path = ApplicationData.get('presence_offline_')
            info = cPickle.load(open(storage_path, "r"))
            self.offlineNote.setStringValue_(info["note"])
            self.offlineActivity.selectItemWithTitle_(info["activity"])
        except (cPickle.UnpicklingError, IOError):
            pass

        self.offlineWindow.makeKeyAndOrderFront_(None)
Exemplo n.º 20
0
    def initWithFrame_transfer_(self, frame, transfer):
        self = NSView.initWithFrame_(self, frame)
        if self:
            self.transfer = transfer
            NotificationCenter().add_observer(self, sender=transfer)

            NSBundle.loadNibNamed_owner_("FileTransferItemView", self)

            filename = self.transfer.file_path

            if type(self.transfer) == OutgoingPushFileTransferHandler:
                self.fromText.setStringValue_(u"To:  %s" %
                                              self.transfer.account.id)
            else:
                if filename.endswith(".download"):
                    filename = filename[:-len(".download")]
                self.fromText.setStringValue_(u"From:  %s" %
                                              self.transfer.account.id)
            self.nameText.setStringValue_(os.path.basename(filename))

            if os.path.exists(filename):
                self.updateIcon(
                    NSWorkspace.sharedWorkspace().iconForFile_(filename))
            else:
                tmp_folder = ApplicationData.get('.tmp_file_transfers')
                if not os.path.exists(tmp_folder):
                    os.mkdir(tmp_folder, 0700)

                tmpf = tmp_folder + "/tmpf" + os.path.splitext(filename)[1]
                open(tmpf, "w+").close()
                self.updateIcon(
                    NSWorkspace.sharedWorkspace().iconForFile_(tmpf))
                os.remove(tmpf)

            self.updateProgressInfo()
            self.progressBar.setIndeterminate_(True)
            self.progressBar.startAnimation_(None)
            self.progressBar.setHidden_(True)

            self.checksumProgressBar.setIndeterminate_(False)
            self.checksumProgressBar.startAnimation_(None)
            self.checksumProgressBar.setHidden_(False)

            frame.size = self.view.frame().size
            self.setFrame_(frame)
            self.addSubview_(self.view)
            self.originalHeight = NSHeight(frame)
        return self
Exemplo n.º 21
0
    def save_certificates(self, response):
        passport = response["passport"]
        address = response["sip_address"]

        tls_folder = ApplicationData.get('tls')
        if not os.path.exists(tls_folder):
            os.mkdir(tls_folder, 0700)

        ca = passport["ca"].strip() + os.linesep
        self.add_certificate_authority(ca)

        crt = passport["crt"].strip() + os.linesep
        try:
            X509Certificate(crt)
        except GNUTLSError, e:
            BlinkLogger().log_error(u"Invalid TLS certificate: %s" % e)
            return None
Exemplo n.º 22
0
    def save_certificates(self, response):
        passport = response["passport"]
        address = response["sip_address"]

        tls_folder = ApplicationData.get('tls')
        if not os.path.exists(tls_folder):
            os.mkdir(tls_folder, 0700)

        ca = passport["ca"].strip() + os.linesep
        self.add_certificate_authority(ca)

        crt = passport["crt"].strip() + os.linesep
        try:
            X509Certificate(crt)
        except GNUTLSError, e:
            BlinkLogger().log_error(u"Invalid TLS certificate: %s" % e)
            return None
Exemplo n.º 23
0
    def __init__(self, storage_folder=ApplicationData.get('photos'), high_res=False, history=True):
        self.history = history
        NSBundle.loadNibNamed_owner_("PhotoPicker", self)
        self.lock = NSLock.alloc().init()
        self.captureButton.setHidden_(True)
        self.previewButton.setHidden_(False)
        self.countdownCheckbox.setHidden_(True)
        self.storage_folder = storage_folder
        self.high_res = high_res
        if self.high_res:
            self.photoView.setCropSize_()

        if not self.history:
            self.tabView.selectTabViewItem_(self.cameraTabView)
            self.previewButton.setHidden_(True)
            self.countdownCheckbox.setHidden_(False)
            self.captureButton.setHidden_(False)
Exemplo n.º 24
0
    def initWithFrame_transfer_(self, frame, transfer):
        self = NSView.initWithFrame_(self, frame)
        if self:
            self.transfer = transfer
            NotificationCenter().add_observer(self, sender=transfer)

            NSBundle.loadNibNamed_owner_("FileTransferItemView", self)

            filename = self.transfer.file_path

            if type(self.transfer) == OutgoingPushFileTransferHandler:
                self.fromText.setStringValue_(u"To:  %s" % self.transfer.account.id)
            else:
                if filename.endswith(".download"):
                    filename = filename[:-len(".download")]
                self.fromText.setStringValue_(u"From:  %s" % self.transfer.account.id)
            self.nameText.setStringValue_(os.path.basename(filename))

            if os.path.exists(filename):
                self.updateIcon(NSWorkspace.sharedWorkspace().iconForFile_(filename))
            else:
                tmp_folder = ApplicationData.get('.tmp_file_transfers')
                if not os.path.exists(tmp_folder):
                    os.mkdir(tmp_folder, 0700)

                tmpf = tmp_folder + "/tmpf" + os.path.splitext(filename)[1]
                open(tmpf, "w+").close()
                self.updateIcon(NSWorkspace.sharedWorkspace().iconForFile_(tmpf))
                os.remove(tmpf)

            self.updateProgressInfo()
            self.progressBar.setIndeterminate_(True)
            self.progressBar.startAnimation_(None)
            self.progressBar.setHidden_(True)

            self.checksumProgressBar.setIndeterminate_(False)
            self.checksumProgressBar.startAnimation_(None)
            self.checksumProgressBar.setHidden_(False)

            frame.size = self.view.frame().size
            self.setFrame_(frame)
            self.addSubview_(self.view)
            self.originalHeight = NSHeight(frame)
        return self
Exemplo n.º 25
0
    def refreshLibrary(self):
        path = ApplicationData.get('photos')

        if os.path.exists(path):
          files = os.listdir(path)
        else:
          files = []
        array = NSMutableArray.array()
        knownFiles = set()
        for item in self.contentArrayController.arrangedObjects():
            knownFiles.add(unicode(item.objectForKey_("path")))

        for f in files:
            p = os.path.normpath(path+"/"+f)
            if p not in knownFiles:
                image = NSImage.alloc().initWithContentsOfFile_(p)
                item = NSDictionary.dictionaryWithObjectsAndKeys_(image, "picture", p, "path")
                array.addObject_(item)

        if array.count() > 0:
            self.contentArrayController.addObjects_(array)
Exemplo n.º 26
0
    def add_certificate_authority(self, ca):
        # not used anymore, let users add CAs in keychain instead
        try:
            X509Certificate(ca)
        except GNUTLSError as e:
            BlinkLogger().log_error("Invalid Certificate Authority: %s" % e)
            return False

        settings = SIPSimpleSettings()
        must_save_ca = False
        if settings.tls.ca_list is not None:
            ca_path = settings.tls.ca_list.normalized
        else:
            tls_folder = ApplicationData.get('tls')
            if not os.path.exists(tls_folder):
                os.mkdir(tls_folder, 0o700)
            ca_path = os.path.join(tls_folder, 'ca.crt')
            must_save_ca = True

        try:
            existing_cas = open(ca_path, "r").read().strip() + os.linesep
        except:
            existing_cas = None
            ca_list = ca
        else:
            ca_list = existing_cas if ca in existing_cas else existing_cas + ca

        if ca_list != existing_cas:
            f = open(ca_path, "w")
            os.chmod(ca_path, 0o600)
            f.write(ca_list)
            f.close()
            BlinkLogger().log_debug("Added new Certificate Authority to %s" % ca_path)
            must_save_ca = True

        if must_save_ca:
            settings.tls.ca_list = ca_path
            settings.save()

        return True
Exemplo n.º 27
0
    def applicationDidFinishLaunching_(self, sender):
        self.blinkMenu.setTitle_(self.applicationNamePrint)

        config_file = ApplicationData.get('config')
        self.icloud_manager = iCloudManager()
        self.backend = SIPManager()

        self.contactsWindowController.setup(self.backend)

        while True:
            try:
                first_run = not os.path.exists(config_file)
                self.contactsWindowController.first_run = first_run

                self.backend.init()
                self.backend.fetch_account()
                accounts = AccountManager().get_accounts()
                if not accounts or (first_run and accounts == [BonjourAccount()]):
                    self.wait_for_enrollment = True
                    self.enroll()
                break

            except FileParserError, exc:
                BlinkLogger().log_warning(u"Error parsing configuration file: %s" % exc)
                if NSRunAlertPanel(NSLocalizedString("Error", "Window title"),
                    NSLocalizedString("The configuration file is corrupted. You will need to replace it and re-enter your account information. \n\nYour current configuration file will be backed up to %s.corrupted. ", "Label") % config_file,
                    NSLocalizedString("Replace", "Button title"), NSLocalizedString("Quit", "Button title"), None) != NSAlertDefaultReturn:
                    NSApp.terminate_(None)
                    return
                os.rename(config_file, config_file+".corrupted")
                BlinkLogger().log_info(u"Renamed configuration file to %s" % config_file+".corrupted")
            except BaseException, exc:
                import traceback
                print traceback.print_exc()
                NSRunAlertPanel(NSLocalizedString("Error", "Window title"), NSLocalizedString("There was an error during startup of core functionality:\n%s", "Label") % exc,
                        NSLocalizedString("Quit", "Button title"), None, None)
                NSApp.terminate_(None)
                return
Exemplo n.º 28
0
    def init_configurations(self):
        account_manager = AccountManager()
        settings = SIPSimpleSettings()

        # fixup default account
        self._selected_account = account_manager.default_account
        if self._selected_account is None:
            self._selected_account = account_manager.get_accounts()[0]

        # save default ca if needed
        ca = open(Resources.get('ca.crt'), "r").read().strip()
        try:
            X509Certificate(ca)
        except GNUTLSError as e:
            BlinkLogger().log_error("Invalid Certificate Authority: %s" % e)
            return

        tls_folder = ApplicationData.get('tls')
        if not os.path.exists(tls_folder):
            os.mkdir(tls_folder, 0o700)
        ca_path = os.path.join(tls_folder, 'ca.crt')

        try:
            existing_cas = open(ca_path, "r").read().strip()
        except Exception:
            existing_cas = None

        if ca == existing_cas:
            return

        with open(ca_path, "wb") as f:
            os.chmod(ca_path, 0o600)
            f.write(ca.encode())

        BlinkLogger().log_debug("Added default Certificate Authority to %s" % ca_path)
        settings.tls.ca_list = ca_path
        settings.save()
Exemplo n.º 29
0
    def __init__(self,
                 storage_folder=ApplicationData.get('photos'),
                 high_res=False,
                 history=True):
        self.history = history
        NSBundle.loadNibNamed_owner_("PhotoPicker", self)
        self.captureButton.setHidden_(True)
        self.previewButton.setHidden_(False)
        self.countdownCheckbox.setHidden_(True)
        self.mirrorButton.setHidden_(True)
        self.storage_folder = storage_folder
        self.high_res = high_res

        settings = SIPSimpleSettings()
        try:
            self.previous_auto_rotate_cameras = settings.video.auto_rotate_cameras
            settings.video.auto_rotate_cameras = False
            settings.save()
        except AttributeError:
            pass

        if self.high_res:
            self.photoView.setCropSize_()

        if not self.history:
            self.tabView.selectTabViewItem_(self.cameraTabView)
            self.previewButton.setHidden_(True)
            #self.countdownCheckbox.setHidden_(False)
            self.mirrorButton.setHidden_(False)
            self.captureButton.setHidden_(False)

        self.notification_center = NotificationCenter()
        self.notification_center.add_observer(
            self, name="VideoDeviceDidChangeCamera")
        self.notification_center.add_observer(self,
                                              name="CameraSnapshotDidSucceed")
Exemplo n.º 30
0
 def get_audio_recordings_directory(self):
     return ApplicationData.get('history')
Exemplo n.º 31
0
 def get_contacts_backup_directory(self):
     path = ApplicationData.get('contacts_backup')
     makedirs(path)
     return path
Exemplo n.º 32
0
        settings.save()

    def add_certificate_authority(self, ca):
        # not used anymore, let users add CAs in keychain instead
        try:
            X509Certificate(ca)
        except GNUTLSError, e:
            BlinkLogger().log_error(u"Invalid Certificate Authority: %s" % e)
            return False

        settings = SIPSimpleSettings()
        must_save_ca = False
        if settings.tls.ca_list is not None:
            ca_path = settings.tls.ca_list.normalized
        else:
            tls_folder = ApplicationData.get('tls')
            if not os.path.exists(tls_folder):
                os.mkdir(tls_folder, 0700)
            ca_path = os.path.join(tls_folder, 'ca.crt')
            must_save_ca = True

        try:
            existing_cas = open(ca_path, "r").read().strip() + os.linesep
        except:
            existing_cas = None
            ca_list = ca
        else:
            ca_list = existing_cas if ca in existing_cas else existing_cas + ca

        if ca_list != existing_cas:
            f = open(ca_path, "w")
Exemplo n.º 33
0
 def _get_path(self):
     if isinstance(self.__dict__['path'], self.DefaultTLSCertificate):
         return Resources.get(self.__dict__['path'])
     else:
         return ApplicationData.get(self.__dict__['path'])
Exemplo n.º 34
0
 def _get_path(self):
     return ApplicationData.get(self.__dict__['path'])
Exemplo n.º 35
0
 def normalized(self):
     return ApplicationData.get(self)
Exemplo n.º 36
0
    def applicationDidFinishLaunching_(self, sender):
        BlinkLogger().log_debug("Application launched")

        branding_file = NSBundle.mainBundle().infoDictionary().objectForKey_("BrandingFile")
        try:
            branding = __import__(branding_file)
        except ImportError:
            try:
                import branding
            except ImportError:
                branding = Null

        branding.setup(self)

        if self.updater and self.sp_update_url is not None:
            self.updater.sp.setFeedURL_(NSURL.URLWithString_(self.sp_update_url))

        self.blinkMenu.setTitle_(self.applicationNamePrint)

        config_file = ApplicationData.get('config')
        self.icloud_manager = iCloudManager()
        self.backend = SIPManager()

        self.contactsWindowController.setup(self.backend)

        while True:
            try:
                first_run = not os.path.exists(config_file)
                self.contactsWindowController.first_run = first_run

                self.backend.init()
                self.backend.fetch_account()
                accounts = AccountManager().get_accounts()
                if not accounts or (first_run and accounts == [BonjourAccount()]):
                    self.wait_for_enrollment = True
                    self.enroll()
                break

            except FileParserError as exc:
                BlinkLogger().log_warning("Error parsing configuration file: %s" % exc)
                if NSRunAlertPanel(NSLocalizedString("Error", "Window title"),
                    NSLocalizedString("The configuration file is corrupted. You will need to replace it and re-enter your account information. \n\nYour current configuration file will be backed up to %s.corrupted. ", "Label") % config_file,
                    NSLocalizedString("Replace", "Button title"), NSLocalizedString("Quit", "Button title"), None) != NSAlertDefaultReturn:
                    NSApp.terminate_(None)
                    return
                os.rename(config_file, config_file+".corrupted")
                BlinkLogger().log_info("Renamed configuration file to %s" % config_file+".corrupted")
            except BaseException as exc:
                import traceback
                print(traceback.print_exc())
                NSRunAlertPanel(NSLocalizedString("Error", "Window title"), NSLocalizedString("There was an error during startup of core functionality:\n%s", "Label") % exc,
                        NSLocalizedString("Quit", "Button title"), None, None)
                NSApp.terminate_(None)
                return

        # window should be shown only after enrollment check
        if self.wait_for_enrollment:
            BlinkLogger().log_info('Starting User Interface')
            self.contactsWindowController.model.moveBonjourGroupFirst()
            self.contactsWindowController.showWindow_(None)
            self.wait_for_enrollment = False

        self.contactsWindowController.setupFinished()
        SMSWindowManager.SMSWindowManager().setOwner_(self.contactsWindowController)
        self.debugWindow = DebugWindow.alloc().init()
        self.chatWindowController = ChatWindowController.ChatWindowController.alloc().init()
Exemplo n.º 37
0
 def _get_path(self):
     if isinstance(self.__dict__['path'], self.DefaultTLSCertificate):
         return Resources.get(self.__dict__['path'])
     else:
         return ApplicationData.get(self.__dict__['path'])
Exemplo n.º 38
0
 def get_contacts_backup_directory(self):
     storage_path = ApplicationData.get('contacts_backup/dummy')
     makedirs(os.path.dirname(storage_path))
     return ApplicationData.get('contacts_backup')
Exemplo n.º 39
0
 def get_contacts_backup_directory(self):
     path = ApplicationData.get('contacts_backup')
     makedirs(path)
     return path
Exemplo n.º 40
0
 def loadConfigurations(self):
     self.storage_path = ApplicationData.get('conference_configurations.pickle')
     try:
         self.conference_configurations = cPickle.load(open(self.storage_path))
     except:
         self.conference_configurations = {}
Exemplo n.º 41
0
class SIPManager(object):
    __metaclass__ = Singleton

    implements(IObserver)

    def __init__(self):

        self._app = SIPApplication()
        self._delegate = None
        self._selected_account = None
        self._version = None
        self.ip_address_monitor = IPAddressMonitor()
        self.bonjour_disabled_on_sleep = False
        self.bonjour_conference_services = BonjourConferenceServices()
        self.notification_center = NotificationCenter()
        self.notification_center.add_observer(self, sender=self._app)
        self.notification_center.add_observer(self, sender=self._app.engine)
        self.notification_center.add_observer(
            self, name='CFGSettingsObjectDidChange')
        self.notification_center.add_observer(self,
                                              name='SIPAccountDidActivate')
        self.notification_center.add_observer(self,
                                              name='SIPAccountDidDeactivate')
        self.notification_center.add_observer(
            self, name='SIPAccountRegistrationDidSucceed')
        self.notification_center.add_observer(
            self, name='SIPAccountRegistrationDidEnd')
        self.notification_center.add_observer(
            self, name='SIPAccountRegistrationDidFail')
        self.notification_center.add_observer(
            self, name='SIPAccountRegistrationGotAnswer')
        self.notification_center.add_observer(
            self, name='SIPAccountMWIDidGetSummary')
        self.notification_center.add_observer(
            self, name='XCAPManagerDidDiscoverServerCapabilities')
        self.notification_center.add_observer(self, name='SystemWillSleep')
        self.notification_center.add_observer(self,
                                              name='SystemDidWakeUpFromSleep')

    def set_delegate(self, delegate):
        self._delegate = delegate

    def migratePasswordsToKeychain(self):
        account_manager = AccountManager()
        configuration_manager = ConfigurationManager()
        bonjour_account = BonjourAccount()
        for account in (account for account in account_manager.iter_accounts()
                        if account is not bonjour_account):
            try:
                stored_auth_password = configuration_manager.get(
                    account.__key__ + ['auth', 'password'])
            except ObjectNotFoundError:
                stored_auth_password = None
            try:
                stored_ldap_password = configuration_manager.get(
                    account.__key__ + ['ldap', 'password'])
            except ObjectNotFoundError:
                stored_ldap_password = None
            try:
                stored_web_password = configuration_manager.get(
                    account.__key__ + ['server', 'web_password'])
            except ObjectNotFoundError:
                stored_web_password = None
            if (stored_auth_password, stored_ldap_password,
                    stored_web_password) != ('keychain', 'keychain',
                                             'keychain'):
                Account.auth.password.dirty[account.auth] = True
                Account.ldap.password.dirty[account.ldap] = True
                Account.server.web_password.dirty[account.server] = True
                account.save()

    def init(self):
        self._version = str(
            NSBundle.mainBundle().infoDictionary().objectForKey_(
                "CFBundleShortVersionString"))

        #first_start = not os.path.exists(ApplicationData.get('config'))

        Account.register_extension(AccountExtension)
        BonjourAccount.register_extension(BonjourAccountExtension)
        Contact.register_extension(BlinkContactExtension)
        ContactGroup.register_extension(BlinkContactGroupExtension)
        SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)

        self._app.start(FileStorage(ApplicationData.directory))
        self.init_configurations()

        # start session mgr
        SessionManager()

    def init_configurations(self):
        account_manager = AccountManager()
        settings = SIPSimpleSettings()

        self.notification_center.add_observer(self, sender=settings)

        # fixup default account
        self._selected_account = account_manager.default_account
        if self._selected_account is None:
            self._selected_account = account_manager.get_accounts()[0]

        default_ca = open(Resources.get('ca.crt'), "r").read().strip()
        self.set_default_certificate_authority(default_ca)

    def set_default_certificate_authority(self, ca):
        try:
            X509Certificate(ca)
        except GNUTLSError, e:
            BlinkLogger().log_error(u"Invalid Certificate Authority: %s" % e)
            return False

        settings = SIPSimpleSettings()
        must_save_ca = False
        tls_folder = ApplicationData.get('tls')
        if not os.path.exists(tls_folder):
            os.mkdir(tls_folder, 0700)
        ca_path = os.path.join(tls_folder, 'ca.crt')

        try:
            existing_cas = open(ca_path, "r").read().strip()
        except:
            existing_cas = None

        if ca != existing_cas:
            f = open(ca_path, "w")
            os.chmod(ca_path, 0600)
            f.write(ca)
            f.close()
            BlinkLogger().log_info(
                u"Added default Certificate Authority to %s" % ca_path)
            must_save_ca = True

        if must_save_ca:
            settings.tls.ca_list = ca_path
            settings.save()

        return True
Exemplo n.º 42
0
 def get_contacts_backup_directory(self):
     storage_path = ApplicationData.get('contacts_backup/dummy')
     makedirs(os.path.dirname(storage_path))
     return ApplicationData.get('contacts_backup')
Exemplo n.º 43
0
 def _get_path(self):
     return ApplicationData.get(self.__dict__['path'])
Exemplo n.º 44
0
 def get_audio_recordings_directory(self):
     return ApplicationData.get('history')
Exemplo n.º 45
0
 def normalized(self):
     return ApplicationData.get(self)
Exemplo n.º 46
0
        return True

    def add_certificate_authority(self, ca):
        # not used anymore, let users add CAs in keychain instead
        try:
            X509Certificate(ca)
        except GNUTLSError, e:
            BlinkLogger().log_error(u"Invalid Certificate Authority: %s" % e)
            return False

        settings = SIPSimpleSettings()
        must_save_ca = False
        if settings.tls.ca_list is not None:
            ca_path = settings.tls.ca_list.normalized
        else:
            tls_folder = ApplicationData.get('tls')
            if not os.path.exists(tls_folder):
                os.mkdir(tls_folder, 0700)
            ca_path = os.path.join(tls_folder, 'ca.crt')
            must_save_ca = True

        try:
            existing_cas = open(ca_path, "r").read().strip() + os.linesep
        except:
            existing_cas = None
            ca_list = ca
        else:
            ca_list = existing_cas if ca in existing_cas else existing_cas + ca

        if ca_list != existing_cas:
            f = open(ca_path, "w")