def store_file(self, id, file): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') if filename == os.path.normpath(file): return self.iconmap.get(id, None) makedirs(directory) pixmap = QPixmap() if file is not None and pixmap.load(file): if pixmap.size().width() > self.max_size or pixmap.size().height( ) > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def _NH_XCAPManagerDidReloadData(self, notification): account = notification.sender.account settings = SIPSimpleSettings() offline_status = notification.data.offline_status status_icon = notification.data.status_icon try: offline_note = next(note for service in offline_status.pidf.services for note in service.notes) except (AttributeError, StopIteration): offline_note = None settings.presence_state.offline_note = offline_note settings.save() if status_icon: icon_hash = hashlib.sha512(status_icon.data).hexdigest() user_icon = UserIcon(status_icon.url, icon_hash) if not settings.presence_state.icon or settings.presence_state.icon.etag != icon_hash: # TODO: convert icon to PNG before saving it self.owner.saveUserIcon(status_icon.data, icon_hash) else: user_icon = None if settings.presence_state.icon: unlink(settings.presence_state.icon.path) settings.presence_state.icon = None settings.save() account.xcap.icon = user_icon account.save() # Cleanup old base64 encoded icons from payload if account.id not in self._cleanedup_accounts: self._cleanup_icons(account)
def initialize(self, stream, session): super(IncomingFileTransferHandler, self).initialize(stream, session) try: directory = self.save_directory or SIPSimpleSettings().file_transfer.directory.normalized makedirs(directory) with self.metadata as metadata: try: prev_file = metadata.pop(stream.file_selector.hash.lower()) mtime = os.path.getmtime(prev_file.filename) if mtime != prev_file.mtime: raise ValueError('file was modified') filename = os.path.join(directory, os.path.basename(stream.file_selector.name)) try: os.link(prev_file.filename, filename) except (AttributeError, OSError): stream.file_selector.name = prev_file.filename else: stream.file_selector.name = filename unlink(prev_file.filename) stream.file_selector.fd = openfile(stream.file_selector.name, 'ab') # open doesn't seek to END in append mode on win32 until first write, but openfile does self.offset = stream.file_selector.fd.tell() self.hash = prev_file.partial_hash except (KeyError, EnvironmentError, ValueError): for name in UniqueFilenameGenerator.generate(os.path.join(directory, os.path.basename(stream.file_selector.name))): try: stream.file_selector.fd = openfile(name, 'xb') except FileExistsError: continue else: stream.file_selector.name = name break except Exception as e: NotificationCenter().post_notification('FileTransferHandlerDidNotInitialize', sender=self, data=NotificationData(reason=str(e))) else: NotificationCenter().post_notification('FileTransferHandlerDidInitialize', sender=self)
def start(self): notification_center = NotificationCenter() notification_center.post_notification('FileTransferHandlerDidStart', sender=self) file_selector = self.stream.file_selector fd = file_selector.fd while True: chunk = self.queue.get() if chunk is EndTransfer: break data = chunk.data try: fd.write(data) except EnvironmentError as e: fd.close() notification_center.post_notification( 'FileTransferHandlerError', sender=self, data=NotificationData(error=str(e))) notification_center.post_notification( 'FileTransferHandlerDidEnd', sender=self, data=NotificationData(error=True, reason=str(e))) return self.hash.update(data) self.offset += chunk.size transferred_bytes = chunk.byte_range.start + chunk.size - 1 total_bytes = file_selector.size = chunk.byte_range.total notification_center.post_notification( 'FileTransferHandlerProgress', sender=self, data=NotificationData(transferred_bytes=transferred_bytes, total_bytes=total_bytes)) if transferred_bytes == total_bytes: break fd.close() # Transfer is finished if self.offset != self.stream.file_selector.size: notification_center.post_notification( 'FileTransferHandlerDidEnd', sender=self, data=NotificationData(error=True, reason='Incomplete file')) return if self.hash != self.stream.file_selector.hash: unlink(self.filename ) # something got corrupted, better delete the file notification_center.post_notification( 'FileTransferHandlerDidEnd', sender=self, data=NotificationData(error=True, reason='File hash mismatch')) return notification_center.post_notification('FileTransferHandlerDidEnd', sender=self, data=NotificationData( error=False, reason=None))
def store_data(self, id, data): id = id.replace('/', '_') directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') makedirs(directory) pixmap = QPixmap() if data is not None and pixmap.loadFromData(data): image_size = pixmap.size() if image_size.width() > self.max_size or image_size.height() > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) if imghdr.what(None, data) != 'png' or pixmap.size() != image_size: buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data icon.content_type = 'image/png' else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def _NH_MediaStreamDidNotInitialize(self, notification): if self.stream.file_selector.fd is not None: position = self.stream.file_selector.fd.tell() self.stream.file_selector.fd.close() if position == 0: unlink(self.stream.file_selector.name) super(IncomingFileTransferHandler, self)._NH_MediaStreamDidNotInitialize(notification)
def store_image(self, data): if data is None: return None data_hash = sha512(data).hexdigest() try: return self.filemap[data_hash].destination except KeyError: pass try: destination_name = os.path.join('images', self.available_names.popleft()) except IndexError: # No more available file names. return None pixmap = QPixmap() if pixmap.loadFromData(data): pixmap = pixmap.scaled(32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation) makedirs(ApplicationData.get('images')) if pixmap.save(ApplicationData.get(destination_name)): file_mapping = FileMapping(data_hash, destination_name) self.filemap[data_hash] = file_mapping map_filename = ApplicationData.get(os.path.join('images', '.cached_icons.map')) map_tempname = map_filename + '.tmp' try: file = open(map_tempname, 'wb') pickle.dump(self.filemap, file) file.close() if sys.platform == 'win32': unlink(map_filename) os.rename(map_tempname, map_filename) except Exception, e: log.error("could not save icon cache file mappings: %s" % e) return destination_name
def initialize(self, stream, session): super(IncomingFileTransferHandler, self).initialize(stream, session) try: directory = self.save_directory or SIPSimpleSettings().file_transfer.directory.normalized makedirs(directory) with self.metadata as metadata: try: prev_file = metadata.pop(stream.file_selector.hash.lower()) mtime = os.path.getmtime(prev_file.filename) if mtime != prev_file.mtime: raise ValueError('file was modified') filename = os.path.join(directory, os.path.basename(stream.file_selector.name)) try: os.link(prev_file.filename, filename) except (AttributeError, OSError): stream.file_selector.name = prev_file.filename else: stream.file_selector.name = filename unlink(prev_file.filename) stream.file_selector.fd = openfile(stream.file_selector.name, 'ab') # open doesn't seek to END in append mode on win32 until first write, but openfile does self.offset = stream.file_selector.fd.tell() self.hash = prev_file.partial_hash except (KeyError, EnvironmentError, ValueError): for name in UniqueFilenameGenerator.generate(os.path.join(directory, os.path.basename(stream.file_selector.name))): try: stream.file_selector.fd = openfile(name, 'xb') except FileExistsError: continue else: stream.file_selector.name = name break except Exception, e: NotificationCenter().post_notification('FileTransferHandlerDidNotInitialize', sender=self, data=NotificationData(reason=str(e)))
def __init__(self): self.accounting = [ __import__('mediaproxy.interfaces.accounting.%s' % mod.lower(), globals(), locals(), ['']).Accounting() for mod in set(DispatcherConfig.accounting) ] self.cred = X509Credentials(cert_name='dispatcher') self.tls_context = TLSContext(self.cred) self.relay_factory = RelayFactory(self) dispatcher_addr, dispatcher_port = DispatcherConfig.listen self.relay_listener = reactor.listenTLS(dispatcher_port, self.relay_factory, self.tls_context, interface=dispatcher_addr) self.opensips_factory = OpenSIPSControlFactory(self) socket_path = process.runtime.file(DispatcherConfig.socket_path) unlink(socket_path) self.opensips_listener = reactor.listenUNIX(socket_path, self.opensips_factory) self.opensips_management = opensips.ManagementInterface() self.management_factory = ManagementControlFactory(self) management_addr, management_port = DispatcherConfig.listen_management if DispatcherConfig.management_use_tls: self.management_listener = reactor.listenTLS( management_port, self.management_factory, self.tls_context, interface=management_addr) else: self.management_listener = reactor.listenTCP( management_port, self.management_factory, interface=management_addr)
def store_file(self, id, file): id = id.replace('/', '_') directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') if filename == os.path.normpath(file): return self.iconmap.get(id, None) makedirs(directory) pixmap = QPixmap() if file is not None and pixmap.load(file): if pixmap.size().width() > self.max_size or pixmap.size().height() > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data icon.content_type = 'image/png' else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def close(self): for request in self.transport.requests.values(): if not request.deferred.called: request.deferred.errback(Error('shutting down')) self.transport.requests.clear() self.transport.stopListening() unlink(self.path)
def removeSelectedAccount(self): account_info = self.selectedAccount() if account_info: account = account_info.account text = "Permanently remove account %s?" % account_info.name text = re.sub("%", "%%", text) # http://stackoverflow.com/questions/4498709/problem-in-displaying-in-nsrunalertpanel if NSRunAlertPanel("Remove Account", text, "Remove", "Cancel", None) != NSAlertDefaultReturn: return if account.tls.certificate and os.path.basename( account.tls.certificate.normalized) != 'default.crt': unlink(account.tls.certificate.normalized) account_manager = AccountManager() if account_manager.default_account is account: try: account_manager.default_account = ( acc for acc in account_manager.iter_accounts() if acc is not account and acc.enabled).next() except StopIteration: account_manager.default_account = None account.delete()
def _save_calls(self, result): if self.calls: log.info('Saving calls') calls_file = process.runtime.file(backup_calls_file) try: f = open(calls_file, 'wb') except: pass else: for call in list(self.calls.values()): call.application = None # we will mark timers with 'running' or 'idle', depending on their current state, # to be able to correctly restore them later (Timer objects cannot be pickled) if call.timer is not None: if call.inprogress: call.timer.cancel() call.timer = 'running' # temporary mark that this timer was running else: call.timer = 'idle' # temporary mark that this timer was not running failed_dump = False try: try: pickle.dump(self.calls, f) except Exception as e: log.warning('Failed to dump call list: %s', e) failed_dump = True finally: f.close() if failed_dump: unlink(calls_file) else: log.info("Saved calls: %s" % str(list(self.calls.keys()))) self.calls = {}
def save(self, data): """ Given a dictionary conforming to the IConfigurationBackend specification, write the data to the file configured with this backend in a format suitable to be read back using load(). """ lines = self._build_group(data, 0) config_directory = os.path.dirname(self.filename) tmp_filename = '%s.%d.%08X' % (self.filename, os.getpid(), random.getrandbits(32)) try: if config_directory: makedirs(config_directory) file = openfile(tmp_filename, 'wb', permissions=0o600) file.write( (os.linesep.join(lines) + os.linesep).encode(self.encoding)) file.close() if platform.system() == 'Windows': # os.rename does not work on Windows if the destination file already exists. # It seems there is no atomic way to do this on Windows. unlink(self.filename) os.rename(tmp_filename, self.filename) except (IOError, OSError) as e: raise ConfigurationBackendError( "failed to write configuration file: %s" % str(e))
def store_data(self, id, data): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') makedirs(directory) pixmap = QPixmap() if data is not None and pixmap.loadFromData(data): image_size = pixmap.size() if image_size.width() > self.max_size or image_size.height( ) > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) if imghdr.what(None, data) != 'png' or pixmap.size() != image_size: buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def __init__(self): socket_path = process.runtime.file('opensips.sock') unlink(socket_path) self.path = socket_path self.transport = reactor.listenUNIXDatagram(self.path, UNIXSocketProtocol()) self.transport.requests = {} reactor.addSystemEventTrigger('during', 'shutdown', self.close)
def __init__(self): unlink(CallControlConfig.socket) self.path = CallControlConfig.socket self.group = CallControlConfig.group self.listening = None self.engines = None self.monitor = None self.calls = {} self.users = {} self._restore_calls()
def _NH_FileTransferHandlerDidEnd(self, notification): if notification.data.error and self.stream.file_selector.hash is not None: if os.path.getsize(self.stream.file_selector.name) == 0: unlink(self.stream.file_selector.name) else: with self.metadata as metadata: entry = FileMetadataEntry.from_selector(self.stream.file_selector) entry.partial_hash = self.hash metadata[entry.hash] = entry super(IncomingFileTransferHandler, self)._NH_FileTransferHandlerDidEnd(notification)
def _create_connections_as_needed(self): while self.workers < self.max and len(self.waiters) > len(self.connections): socket_name = "opensips_%s%02d.sock" % (self.id, self.workers+1) socket_path = process.runtime_file(socket_name) unlink(socket_path) try: conn = UNIXSocketConnection(socket_path) except CannotListenError, why: log.error("cannot create an OpenSIPS UNIX socket connection: %s" % str(why)) break self.connections.append(conn) self.workers += 1
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
def __init__(self, dispatcher): self.dispatcher = dispatcher self.relays = {} self.shutting_down = False state_file = process.runtime_file("dispatcher_state") try: self.sessions = pickle.load(open(state_file)) except: self.sessions = {} self.cleanup_timers = {} else: self.cleanup_timers = dict((ip, reactor.callLater(DispatcherConfig.cleanup_dead_relays_after, self._do_cleanup, ip)) for ip in set(session.relay_ip for session in self.sessions.itervalues())) unlink(state_file) self.expired_cleaner = RecurrentCall(600, self._remove_expired_sessions)
def _create_connections_as_needed(self): while self.workers < self.max and len(self.waiters) > len( self.connections): socket_name = "opensips_%s%02d.sock" % (self.id, self.workers + 1) socket_path = process.runtime_file(socket_name) unlink(socket_path) try: conn = UNIXSocketConnection(socket_path) except CannotListenError, why: log.error( "cannot create an OpenSIPS UNIX socket connection: %s" % str(why)) break self.connections.append(conn) self.workers += 1
def save(self, name, data): """Write the data in a file identified by name.""" filename = os.path.join(self.directory, self.account_id, name) tmp_filename = '%s.%d.%08X' % (filename, os.getpid(), random.getrandbits(32)) try: makedirs(os.path.join(self.directory, self.account_id)) file = os.fdopen(os.open(tmp_filename, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0600), 'wb') file.write(data) file.close() if platform.system() == 'Windows': # os.rename does not work on Windows if the destination file already exists. # It seems there is no atomic way to do this on Windows. unlink(filename) os.rename(tmp_filename, filename) except (IOError, OSError), e: raise XCAPStorageError("failed to save XCAP data for %s/%s: %s" % (self.account_id, name, str(e)))
def save(self, name, data): """Write the data in a file identified by name.""" filename = os.path.join(self.directory, self.account_id, name) tmp_filename = '%s.%d.%08X' % (filename, os.getpid(), random.getrandbits(32)) try: makedirs(os.path.join(self.directory, self.account_id)) file = openfile(tmp_filename, 'wb', permissions=0600) file.write(data) file.close() if platform.system() == 'Windows': # os.rename does not work on Windows if the destination file already exists. # It seems there is no atomic way to do this on Windows. unlink(filename) os.rename(tmp_filename, filename) except (IOError, OSError), e: raise XCAPStorageError("failed to save XCAP data for %s/%s: %s" % (self.account_id, name, str(e)))
def __init__(self): self.accounting = [__import__("mediaproxy.interfaces.accounting.%s" % mod.lower(), globals(), locals(), [""]).Accounting() for mod in set(DispatcherConfig.accounting)] self.cred = X509Credentials(cert_name='dispatcher') self.relay_factory = RelayFactory(self) dispatcher_addr, dispatcher_port = DispatcherConfig.listen self.relay_listener = reactor.listenTLS(dispatcher_port, self.relay_factory, self.cred, interface=dispatcher_addr) self.opensips_factory = OpenSIPSControlFactory(self) socket_path = process.runtime_file(DispatcherConfig.socket_path) unlink(socket_path) self.opensips_listener = reactor.listenUNIX(socket_path, self.opensips_factory) self.opensips_management = opensips.ManagementInterface() self.management_factory = ManagementControlFactory(self) management_addr, management_port = DispatcherConfig.listen_management if DispatcherConfig.management_use_tls: self.management_listener = reactor.listenTLS(management_port, self.management_factory, self.cred, interface=management_addr) else: self.management_listener = reactor.listenTCP(management_port, self.management_factory, interface=management_addr)
def initialize(self, stream, session): super(IncomingFileTransferHandler, self).initialize(stream, session) try: directory = self.save_directory or SIPSimpleSettings().file_transfer.directory.normalized makedirs(directory) with self.metadata as metadata: try: prev_file = metadata.pop(stream.file_selector.hash.lower()) mtime = os.path.getmtime(prev_file.filename) if mtime != prev_file.mtime: raise ValueError('file was modified') filename = os.path.join(directory, os.path.basename(stream.file_selector.name)) try: os.link(prev_file.filename, filename) except (AttributeError, OSError): stream.file_selector.name = prev_file.filename else: stream.file_selector.name = filename unlink(prev_file.filename) stream.file_selector.fd = open(stream.file_selector.name.encode(sys.getfilesystemencoding()), 'ab') if sys.platform == 'win32': stream.file_selector.fd.seek(0, os.SEEK_END) self.offset = stream.file_selector.fd.tell() self.hash = prev_file.partial_hash except (KeyError, EnvironmentError, ValueError): filename = None fd = None flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL if sys.platform == 'win32': flags |= os.O_BINARY for name in UniqueFilenameGenerator.generate(os.path.join(directory, os.path.basename(stream.file_selector.name))): try: fd = os.open(name, flags, 0644) except OSError, e: if e.args[0] == errno.EEXIST: continue raise filename = name break stream.file_selector.name = filename stream.file_selector.fd = os.fdopen(fd, 'wb') except Exception, e: NotificationCenter().post_notification('FileTransferHandlerDidNotInitialize', sender=self, data=NotificationData(reason=str(e)))
def store(self, filename, pixmap=None): if filename is None: return None if not os.path.isabs(filename): return filename if filename.startswith(ApplicationData.directory + os.path.sep): return filename[len(ApplicationData.directory + os.path.sep):] try: file_mapping = self.filemap[filename] except KeyError: pass else: source_info = FileInfo(filename) destination_info = FileInfo(file_mapping.destination.name) if (source_info, destination_info) == (file_mapping.source, file_mapping.destination): return destination_info.name try: destination_name = os.path.join('images', self.available_names.popleft()) except IndexError: # No more available file names. Return original file for now return filename if pixmap is None: pixmap = QPixmap() if pixmap.load(filename): pixmap = pixmap.scaled(32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation) makedirs(ApplicationData.get('images')) if pixmap.save(ApplicationData.get(destination_name)): source_info = FileInfo(filename) destination_info = FileInfo(destination_name) file_mapping = FileMapping(source_info, destination_info) self.filemap[filename] = file_mapping map_filename = ApplicationData.get(os.path.join('images', '.cached_icons.map')) map_tempname = map_filename + '.tmp' try: file = open(map_tempname, 'wb') pickle.dump(self.filemap, file) file.close() if sys.platform == 'win32': unlink(map_filename) os.rename(map_tempname, map_filename) except Exception, e: log.error("could not save icon cache file mappings: %s" % e) return destination_name
def __init__(self, dispatcher): self.dispatcher = dispatcher self.relays = {} self.shutting_down = False state_file = process.runtime.file('dispatcher_state') try: self.sessions = pickle.load(open(state_file)) except Exception: self.sessions = {} self.cleanup_timers = {} else: self.cleanup_timers = dict( (ip, reactor.callLater(DispatcherConfig.cleanup_dead_relays_after, self._do_cleanup, ip)) for ip in set(session.relay_ip for session in self.sessions.itervalues())) unlink(state_file) self.expired_cleaner = RecurrentCall(600, self._remove_expired_sessions)
def removeSelectedAccount(self): account_info = self.selectedAccount() if account_info: account = account_info.account text = "Permanently remove account %s?" % account_info.name text = re.sub("%", "%%", text) # http://stackoverflow.com/questions/4498709/problem-in-displaying-in-nsrunalertpanel if NSRunAlertPanel("Remove Account", text, "Remove", "Cancel", None) != NSAlertDefaultReturn: return if account.tls.certificate and os.path.basename(account.tls.certificate.normalized) != 'default.crt': unlink(account.tls.certificate.normalized) account_manager = AccountManager() if account_manager.default_account is account: try: account_manager.default_account = (acc for acc in account_manager.iter_accounts() if acc is not account and acc.enabled).next() except StopIteration: account_manager.default_account = None account.delete()
def save(self, data): """ Given a dictionary conforming to the IConfigurationBackend specification, write the data to the file configured with this backend in a format suitable to be read back using load(). """ lines = self._build_group(data, 0) config_directory = os.path.dirname(self.filename) tmp_filename = '%s.%d.%08X' % (self.filename, os.getpid(), random.getrandbits(32)) try: if config_directory: makedirs(config_directory) file = os.fdopen(os.open(tmp_filename, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0600), 'wb') file.write((os.linesep.join(lines)+os.linesep).encode(self.encoding)) file.close() if platform.system() == 'Windows': # os.rename does not work on Windows if the destination file already exists. # It seems there is no atomic way to do this on Windows. unlink(self.filename) os.rename(tmp_filename, self.filename) except (IOError, OSError), e: raise FileBuilderError("failed to write configuration data: %s" % str(e))
def fetch_account(self): """Fetch the SIP account from ~/.blink_account and create/update it as needed""" filename = os.path.expanduser('~/.blink_account') if not os.path.exists(filename): return try: data = open(filename).read() data = cjson.decode(data.replace('\\/', '/')) except (OSError, IOError), e: BlinkLogger().log_error(u"Failed to read json data from ~/.blink_account: %s" % e) return except cjson.DecodeError, e: BlinkLogger().log_error(u"Failed to decode json data from ~/.blink_account: %s" % e) return finally: unlink(filename) data = defaultdict(lambda: None, data) account_id = data['sip_address'] if account_id is None: return account_manager = AccountManager() try: account = account_manager.get_account(account_id) except KeyError: account = Account(account_id) account.display_name = data['display_name'] default_account = account else:
def close(self): if self._initialized: self.transport.stopListening() unlink(self.path)
total_bytes=total_bytes)) if transferred_bytes == total_bytes: break fd.close() # Transfer is finished if self.offset != self.stream.file_selector.size: notification_center.post_notification( 'FileTransferHandlerDidEnd', sender=self, data=NotificationData(error=True, reason='Incomplete file')) return if self.hash != self.stream.file_selector.hash: unlink(self.filename ) # something got corrupted, better delete the file notification_center.post_notification( 'FileTransferHandlerDidEnd', sender=self, data=NotificationData(error=True, reason='File hash mismatch')) return notification_center.post_notification('FileTransferHandlerDidEnd', sender=self, data=NotificationData( error=False, reason=None)) def _NH_MediaStreamDidNotInitialize(self, notification): if self.stream.file_selector.fd is not None: position = self.stream.file_selector.fd.tell() self.stream.file_selector.fd.close()
def _restore_calls(self): calls_file = process.runtime.file(backup_calls_file) try: f = open(calls_file, 'r') except: pass else: try: self.calls = pickle.load(f) except Exception as e: log.warning( 'Failed to load calls saved in the previous session: %s', e) f.close() unlink(calls_file) if self.calls: log.info("Restoring calls saved previously: %s" % str(list(self.calls.keys()))) # the calls in the 2 sets below are never overlapping because closed and terminated # calls have different database fingerprints. so the dictionary update below is safe try: db = RadiusDatabase() try: terminated = db.query( RadiusDatabase.RadiusTask(None, 'terminated', calls=self.calls) ) # calls terminated by caller/called didtimeout = db.query( RadiusDatabase.RadiusTask(None, 'timedout', calls=self.calls) ) # calls closed by mediaproxy after a media timeout finally: db.close() except RadiusDatabaseError as e: log.error("Could not query database: %s" % e) else: for callid, call in list(self.calls.items()): callinfo = terminated.get(callid) or didtimeout.get( callid) if callinfo: # call already terminated or did timeout in mediaproxy del self.calls[callid] callinfo['call'] = call call.timer = None continue # close all calls that were already terminated or did timeout count = 0 for callinfo in list(terminated.values()): call = callinfo.get('call') if call is not None: call.end(calltime=callinfo['duration']) count += 1 for callinfo in list(didtimeout.values()): call = callinfo.get('call') if call is not None: call.end(sendbye=True) count += 1 if count > 0: log.info("Removed %d already terminated call%s" % (count, 's' * (count != 1))) for callid, call in list(self.calls.items()): call.application = self if call.timer == 'running': now = time.time() remain = call.starttime + call.timelimit - now if remain < 0: call.timelimit = int(round(now - call.starttime)) remain = 0 call._setup_timer(remain) call.timer.start() elif call.timer == 'idle': call._setup_timer() # also restore users table self.users.setdefault(call.billingParty, []).append(callid)
def fetch_account(self): """Fetch the SIP account from ~/.blink_account and create/update it as needed""" filename = os.path.expanduser('~/.blink_account') if not os.path.exists(filename): return try: data = open(filename).read() data = json.loads(data.decode().replace('\\/', '/')) except (OSError, IOError) as e: BlinkLogger().log_error("Failed to read json data from ~/.blink_account: %s" % e) return except ValueError as e: BlinkLogger().log_error("Failed to decode json data from ~/.blink_account: %s" % e) return finally: unlink(filename) data = defaultdict(lambda: None, data) account_id = data['sip_address'] if account_id is None: return account_manager = AccountManager() try: account = account_manager.get_account(account_id) except KeyError: account = Account(account_id) account.display_name = data['display_name'] default_account = account else: default_account = account_manager.default_account account.auth.username = data['auth_username'] account.auth.password = data['password'] or '' account.sip.outbound_proxy = data['outbound_proxy'] account.xcap.xcap_root = data['xcap_root'] account.nat_traversal.msrp_relay = data['msrp_relay'] account.server.settings_url = data['settings_url'] account.web_alert.alert_url = data['web_alert_url'] account.server.web_password = data['web_password'] account.conference.server_address = data['conference_server'] if data['ldap_hostname']: account.ldap.enabled = True account.ldap.hostname = data['ldap_hostname'] account.ldap.dn = data['ldap_dn'] account.ldap.username = data['ldap_username'] if data['ldap_password']: account.ldap.password = data['ldap_password'] if data['ldap_transport']: account.ldap.transport = data['ldap_transport'] if data['ldap_port']: account.ldap.port = data['ldap_port'] if data['passport'] is not None: cert_path = self.save_certificates(data) if cert_path: account.tls.certificate = cert_path account.enabled = True account.save() account_manager.default_account = default_account settings = SIPSimpleSettings() settings.service_provider.name = data['service_provider_name'] settings.service_provider.help_url = data['service_provider_help_url'] settings.service_provider.about_url = data['service_provider_about_url'] settings.save()
def remove(self, id): self.iconmap.pop(id, None) unlink(ApplicationData.get(os.path.join('images', id + '.png')))
def remove(self, id): id = id.replace('/', '_') self.iconmap.pop(id, None) unlink(ApplicationData.get(os.path.join('images', id + '.png')))
self.offset += chunk.size transferred_bytes = chunk.byte_range[0] + chunk.size - 1 total_bytes = file_selector.size = chunk.byte_range[2] notification_center.post_notification('FileTransferHandlerProgress', sender=self, data=NotificationData(transferred_bytes=transferred_bytes, total_bytes=total_bytes)) if transferred_bytes == total_bytes: break fd.close() # Transfer is finished if self.offset != self.stream.file_selector.size: notification_center.post_notification('FileTransferHandlerDidEnd', sender=self, data=NotificationData(error=True, reason='Incomplete file')) return if self.hash != self.stream.file_selector.hash: unlink(self.filename) # something got corrupted, better delete the file notification_center.post_notification('FileTransferHandlerDidEnd', sender=self, data=NotificationData(error=True, reason='File hash mismatch')) return notification_center.post_notification('FileTransferHandlerDidEnd', sender=self, data=NotificationData(error=False, reason=None)) def _NH_MediaStreamDidNotInitialize(self, notification): if self.stream.file_selector.fd is not None: position = self.stream.file_selector.fd.tell() self.stream.file_selector.fd.close() if position == 0: unlink(self.stream.file_selector.name) super(IncomingFileTransferHandler, self)._NH_MediaStreamDidNotInitialize(notification) def _NH_FileTransferHandlerDidEnd(self, notification): if notification.data.error and self.stream.file_selector.hash is not None:
def fetch_account(self): filename = os.path.expanduser('~/.blink_account') if not os.path.exists(filename): return try: data = open(filename).read() data = cjson.decode(data.replace(r'\/', '/')) except (OSError, IOError), e: print "Failed to read json data from ~/.blink_account: %s" % e return except cjson.DecodeError, e: print "Failed to decode json data from ~/.blink_account: %s" % e return finally: unlink(filename) data = defaultdict(lambda: None, data) account_id = data['sip_address'] if account_id is None: return account_manager = AccountManager() try: account = account_manager.get_account(account_id) except KeyError: account = Account(account_id) account.display_name = data['display_name'] or None default_account = account else: default_account = account_manager.default_account account.auth.username = data['auth_username'] account.auth.password = data['password'] or ''