def refresh_transfer_rate(self): incoming_transfer_rate = 0 outgoing_transfer_rate = 0 for item in self.listView.subviews().copy(): if item.transfer and item.transfer.transfer_rate is not None: if isinstance(item.transfer, IncomingFileTransferHandler): incoming_transfer_rate += item.transfer.transfer_rate elif isinstance(item.transfer, OutgoingPushFileTransferHandler): outgoing_transfer_rate += item.transfer.transfer_rate elif isinstance(item.transfer, OutgoingPullFileTransferHandler): incoming_transfer_rate += item.transfer.transfer_rate if incoming_transfer_rate or outgoing_transfer_rate: if incoming_transfer_rate and outgoing_transfer_rate: f1 = format_size(incoming_transfer_rate, bits=True) f2 = format_size(outgoing_transfer_rate, bits=True) text = NSLocalizedString( "Incoming %s/s", "Label") % f1 + ", " + NSLocalizedString( "Outgoing %s/s", "Label") % f2 elif incoming_transfer_rate: f = format_size(incoming_transfer_rate, bits=True) text = NSLocalizedString("Incoming %s/s", "Label") % f elif outgoing_transfer_rate: f = format_size(outgoing_transfer_rate, bits=True) text = NSLocalizedString("Outgoing %s/s", "Label") % f self.transferSpeed.setStringValue_(text) else: self.transferSpeed.setStringValue_('')
def refresh_transfer_rate(self): incoming_transfer_rate = 0 outgoing_transfer_rate = 0 for item in self.listView.subviews().copy(): if item.transfer and item.transfer.transfer_rate is not None: if isinstance(item.transfer, IncomingFileTransferHandler): incoming_transfer_rate += item.transfer.transfer_rate elif isinstance(item.transfer, OutgoingPushFileTransferHandler): outgoing_transfer_rate += item.transfer.transfer_rate elif isinstance(item.transfer, OutgoingPullFileTransferHandler): incoming_transfer_rate += item.transfer.transfer_rate if incoming_transfer_rate or outgoing_transfer_rate: if incoming_transfer_rate and outgoing_transfer_rate: f1 = format_size(incoming_transfer_rate, bits=True) f2 = format_size(outgoing_transfer_rate, bits=True) text = NSLocalizedString("Incoming %s/s", "Label") % f1 + ", " + NSLocalizedString("Outgoing %s/s", "Label") % f2 elif incoming_transfer_rate: f = format_size(incoming_transfer_rate, bits=True) text = NSLocalizedString("Incoming %s/s", "Label") % f elif outgoing_transfer_rate: f = format_size(outgoing_transfer_rate, bits=True) text = NSLocalizedString("Outgoing %s/s", "Label") % f self.transferSpeed.setStringValue_(text) else: self.transferSpeed.setStringValue_('')
def refresh_transfer_rate(self): incoming_transfer_rate = 0 outgoing_transfer_rate = 0 for item in self.listView.subviews().copy(): if item.transfer and item.transfer.transfer_rate is not None: if isinstance(item.transfer, IncomingFileTransferHandler): incoming_transfer_rate += item.transfer.transfer_rate elif isinstance(item.transfer, OutgoingPushFileTransferHandler): outgoing_transfer_rate += item.transfer.transfer_rate elif isinstance(item.transfer, OutgoingPullFileTransferHandler): incoming_transfer_rate += item.transfer.transfer_rate if incoming_transfer_rate or outgoing_transfer_rate: if incoming_transfer_rate and outgoing_transfer_rate: text = "Incoming %s/s, Outgoing %s/s" % ( format_size(incoming_transfer_rate, bits=True), format_size(outgoing_transfer_rate, bits=True), ) elif incoming_transfer_rate: text = "Incoming %s/s" % format_size(incoming_transfer_rate, bits=True) elif outgoing_transfer_rate: text = "Outgoing %s/s" % format_size(outgoing_transfer_rate, bits=True) self.transferSpeed.setStringValue_(text) else: self.transferSpeed.setStringValue_("")
def do_action(cmd,p): bc=cmd.client if bc.container: ls=bc.list_blobs(p.prefix.value) else: ls=bc.list_containers(p.prefix.value) cs=0 #coutainer count bs=0 #blob count ts=0 #total_size(blob) formatter='%s \t%s \t%s' path_idx=len(string.join(bc.paths,bc.path_separator)) if path_idx: path_idx+=1 for l in ls: if isinstance(l,Container): cs+=1 size='<DIR>' name=l.name else: bs+=1 size=l.properties.content_length ts+=size size=util.format_size(size) name=l.name[path_idx:] time=l.properties.last_modified time=util.format_time(time) cmd.info(formatter,time,size,name) cmd.hightlight('\tcontainer(s):%s\tblob(s):%s\tblob size:%s',cs,bs,util.format_size(ts))
def initWithFrame_oldTransfer_(self, frame, transferInfo): self = NSView.initWithFrame_(self, frame) if self: self.oldTransferInfo = transferInfo NSBundle.loadNibNamed_owner_("FileTransferItemView", self) filename = transferInfo.file_path if filename.endswith(".download"): filename = filename[:-len(".download")] self.updateIcon(NSWorkspace.sharedWorkspace().iconForFile_(filename)) self.nameText.setStringValue_(os.path.basename(filename)) self.fromText.setStringValue_('To %s' % transferInfo.remote_uri if transferInfo.direction=='outgoing' else 'From %s' % transferInfo.remote_uri) if transferInfo.status == "completed": status = "%s %s Completed"%(format_size(transferInfo.file_size, 1024), unichr(0x2014)) else: error = transferInfo.status if transferInfo.direction == "outgoing": status = error else: status = "%s of %s"%(format_size(transferInfo.bytes_transfered, 1024), format_size(transferInfo.file_size, 1024)) status = "%s %s %s"%(status, unichr(0x2014), error) self.sizeText.setStringValue_(status) frame.size = self.view.frame().size self.setFrame_(frame) self.addSubview_(self.view) self.relayoutForDone() self.done = True return self
def do_action(cmd, p): bc = cmd.client if bc.container: ls = bc.list_blobs(p.prefix.value) else: ls = bc.list_containers(p.prefix.value) cs = 0 #coutainer count bs = 0 #blob count ts = 0 #total_size(blob) formatter = '%s \t%s \t%s' path_idx = len(string.join(bc.paths, bc.path_separator)) if path_idx: path_idx += 1 for l in ls: if isinstance(l, Container): cs += 1 size = '<DIR>' name = l.name else: bs += 1 size = l.properties.content_length ts += size size = util.format_size(size) name = l.name[path_idx:] time = l.properties.last_modified time = util.format_time(time) cmd.info(formatter, time, size, name) cmd.hightlight('\tcontainer(s):%s\tblob(s):%s\tblob size:%s', cs, bs, util.format_size(ts))
def _NH_MediaStreamDidStart(self, sender, data): self.log_info("Outgoing Push File Transfer started") self.status = "%s of %s" % (format_size(self.file_pos, 1024), format_size(self.file_size, 1024)) self.ft_info.status = "transferring" self.started = True self.start_time = datetime.datetime.now() notification_center = NotificationCenter() notification_center.post_notification("BlinkFileTransferDidStart", sender=self)
def download(self, logger=None): if logger is None: logger = logging.getLogger("pakfire") downloads = self.get_downloads() # If there are no downloads, we can just stop here. if not downloads: return # Get free space of the download location. path = os.path.realpath(REPO_CACHE_DIR) while not os.path.ismount(path): path = os.path.dirname(path) path_stat = os.statvfs(path) if self.download_size >= path_stat.f_bavail * path_stat.f_bsize: raise DownloadError, _("Not enough space to download %s of packages.") \ % util.format_size(self.download_size) logger.info(_("Downloading packages:")) time_start = time.time() counter = 0 counter_downloads = len(downloads) for step in downloads: counter += 1 # Download the package file. step.binary_pkg = step.pkg.download( text="(%d/%d): " % (counter, counter_downloads), logger=logger) # Write an empty line to the console when there have been any downloads. width, height = util.terminal_size() # Print a nice line. logger.info("-" * width) # Format and calculate download information. time_stop = time.time() download_time = time_stop - time_start download_speed = self.download_size / download_time download_speed = util.format_speed(download_speed) download_size = util.format_size(self.download_size) download_time = util.format_time(download_time) line = "%s | %5sB %s " % \ (download_speed, self.download_size, download_time) line = " " * (width - len(line)) + line logger.info(line) logger.info("")
def download(self, logger=None): if logger is None: logger = logging.getLogger("pakfire") downloads = self.get_downloads() # If there are no downloads, we can just stop here. if not downloads: return # Get free space of the download location. path = os.path.realpath(REPO_CACHE_DIR) while not os.path.ismount(path): path = os.path.dirname(path) path_stat = os.statvfs(path) if self.download_size >= path_stat.f_bavail * path_stat.f_bsize: raise DownloadError, _("Not enough space to download %s of packages.") \ % util.format_size(self.download_size) logger.info(_("Downloading packages:")) time_start = time.time() counter = 0 counter_downloads = len(downloads) for step in downloads: counter += 1 # Download the package file. step.binary_pkg = step.pkg.download(text="(%d/%d): " % (counter, counter_downloads), logger=logger) # Write an empty line to the console when there have been any downloads. width, height = util.terminal_size() # Print a nice line. logger.info("-" * width) # Format and calculate download information. time_stop = time.time() download_time = time_stop - time_start download_speed = self.download_size / download_time download_speed = util.format_speed(download_speed) download_size = util.format_size(self.download_size) download_time = util.format_time(download_time) line = "%s | %5sB %s " % \ (download_speed, self.download_size, download_time) line = " " * (width - len(line)) + line logger.info(line) logger.info("")
def print_errors(self, logger=None): if logger is None: logger = logging.getLogger("pakfire") for file in self.error_files: pkgs = self.provides_file(file) if len(pkgs) == 2: logger.critical( _("file %(name)s from %(pkg1)s conflicts with file from package %(pkg2)s") % \ { "name" : file, "pkg1" : pkgs[0], "pkg2" : pkgs[1] } ) elif len(pkgs) >= 3: logger.critical( _("file %(name)s from %(pkg)s conflicts with files from %(pkgs)s") % \ { "name" : file, "pkg" : pkgs[0], "pkgs" : i18n.list(pkgs[1:])} ) else: logger.critical( _("file %(name)s causes the transaction test to fail for an unknown reason") % \ { "name" : file } ) for mp in self.mountpoints: if mp.space_left >= 0: continue logger.critical(_("There is not enough space left on %(name)s. Need at least %(size)s to perform transaction.") \ % { "name" : mp.path, "size" : util.format_size(mp.space_needed) })
def add_to_history(self): FileTransferHistory().add_transfer( transfer_id=self.ft_info.transfer_id, direction=self.ft_info.direction, local_uri=self.ft_info.local_uri, remote_uri=self.ft_info.remote_uri, file_path=self.ft_info.file_path, bytes_transfered=self.ft_info.bytes_transfered, file_size=self.ft_info.file_size or 0, status=self.ft_info.status) message = "<h3>%s File Transfer</h3>" % self.ft_info.direction.capitalize( ) message += "<p>%s (%s)" % (self.ft_info.file_path, format_size(self.ft_info.file_size or 0)) media_type = 'file-transfer' local_uri = self.ft_info.local_uri remote_uri = self.ft_info.remote_uri direction = self.ft_info.direction status = 'delivered' if self.ft_info.status == 'completed' else 'failed' cpim_from = self.ft_info.remote_uri cpim_to = self.ft_info.remote_uri timestamp = str(ISOTimestamp.now()) ChatHistory().add_message(self.ft_info.transfer_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, "html", "0", status)
def initWithFrame_oldTransfer_(self, frame, transferInfo): self = NSView.initWithFrame_(self, frame) if self: self.oldTransferInfo = transferInfo NSBundle.loadNibNamed_owner_("FileTransferItemView", self) filename = transferInfo.file_path if filename.endswith(".download"): filename = filename[:-len(".download")] self.updateIcon(NSWorkspace.sharedWorkspace().iconForFile_(filename)) self.nameText.setStringValue_(os.path.basename(filename)) self.fromText.setStringValue_('To %s from account %s' % (transferInfo.remote_uri, transferInfo.local_uri) if transferInfo.direction=='outgoing' else 'From %s to account %s' % (transferInfo.remote_uri, transferInfo.local_uri)) time_print = format_date(transferInfo.time) if transferInfo.status == "completed": t = NSLocalizedString("Completed transfer of ", "Label") status = t + "%s %s" % (format_size(transferInfo.file_size, 1024), time_print) else: if transferInfo.direction == "outgoing": status = '%s %s' % (transferInfo.status.title(), time_print) self.retryButton.setHidden_(False) else: #status = "%s of %s"%(format_size(transferInfo.bytes_transfered, 1024), format_size(transferInfo.file_size, 1024)) status = "%s %s" % (transferInfo.status.title(), time_print) self.sizeText.setStringValue_(status) frame.size = self.view.frame().size self.setFrame_(frame) self.addSubview_(self.view) self.relayoutForDone() self.done = True return self
def handle_info(self): ret = [] ret.append("") ret.append(" PAKFIRE %s" % PAKFIRE_VERSION) ret.append("") ret.append(" %-20s: %s" % (_("Hostname"), system.hostname)) ret.append(" %-20s: %s" % (_("Pakfire hub"), self.config.get("client", "server"))) if self.config.get("client", "username") and self.config.get("client", "password"): ret.append(" %-20s: %s" % \ (_("Username"), self.config.get("client", "username"))) ret.append("") # Hardware information ret.append(" %s:" % _("Hardware information")) ret.append(" %-16s: %s" % (_("CPU model"), system.cpu_model)) ret.append(" %-16s: %s" % (_("Memory"), util.format_size(system.memory))) ret.append(" %-16s: %s" % (_("Parallelism"), system.parallelism)) ret.append("") ret.append(" %-16s: %s" % (_("Native arch"), system.native_arch)) if not system.arch == system.native_arch: ret.append(" %-16s: %s" % (_("Default arch"), system.arch)) header = _("Supported arches") for arch in system.supported_arches: ret.append(" %-16s: %s" % (header, arch)) header = "" ret.append("") for line in ret: print line
def _terminate(self, failure_reason=None, failure_status=None): notification_center = NotificationCenter() if failure_reason is None: self.log_info("File Transfer ended (%i of %i bytes transferred)" % (self.bytes, self.total_bytes)) self.end_time = datetime.datetime.now() t = NSLocalizedString("Completed transfer of ", "Label") self.status = t + format_size(self.file_size) + NSLocalizedString( " in ", "Label") + format_duration( self.end_time - self.start_time) + " " + format_date( self.end_time) self.ft_info.status = "completed" self.ft_info.bytes_transfered = self.file_selector.size else: if failure_status is None: if self.total_bytes: self.log_info("File Transfer was interrupted") self.status = NSLocalizedString( "Transferred %s of ", "Label") % format_size( self.bytes, 1024) + format_size( self.total_bytes) + " - " + failure_reason else: self.log_info("File Transfer was cancelled") self.status = failure_reason else: self.log_info("File Transfer failed: %s" % failure_reason) self.status = failure_status self.ft_info.status = "failed" self.ft_info.bytes_transfered = self.file_pos if self.session is not None and self.stream is not None and self.handler is not None: notification_center.remove_observer(self, sender=self.stream) notification_center.remove_observer(self, sender=self.handler) self.session = None self.stream = None self.handler = None self.transfer_rate = None notification_center.post_notification( "BlinkFileTransferDidEnd", sender=self, data=NotificationData(file_path=self.ft_info.file_path, error=failure_reason is not None)) self.add_to_history()
def _NH_MediaStreamDidStart(self, sender, data): self.log_info("Receiving File...") self.status = format_size(self.file_pos, 1024) self.ft_info.status = "transferring" self.started = True self.start_time = datetime.datetime.now() notification_center = NotificationCenter() notification_center.post_notification("BlinkFileTransferDidStart", sender=self)
def initWithFrame_oldTransfer_(self, frame, transferInfo): self = NSView.initWithFrame_(self, frame) if self: self.oldTransferInfo = transferInfo NSBundle.loadNibNamed_owner_("FileTransferItemView", self) filename = transferInfo.file_path if filename.endswith(".download"): filename = filename[:-len(".download")] self.updateIcon( NSWorkspace.sharedWorkspace().iconForFile_(filename)) self.nameText.setStringValue_(os.path.basename(filename)) self.fromText.setStringValue_( 'To %s' % transferInfo.remote_uri if transferInfo.direction == 'outgoing' else 'From %s' % transferInfo.remote_uri) if transferInfo.status == "completed": status = "%s %s Completed" % (format_size( transferInfo.file_size, 1024), unichr(0x2014)) else: error = transferInfo.status if transferInfo.direction == "outgoing": status = error else: status = "%s of %s" % (format_size( transferInfo.bytes_transfered, 1024), format_size(transferInfo.file_size, 1024)) status = "%s %s %s" % (status, unichr(0x2014), error) self.sizeText.setStringValue_(status) frame.size = self.view.frame().size self.setFrame_(frame) self.addSubview_(self.view) self.relayoutForDone() self.done = True return self
def renderPJSIP(self, text): if self.pjsipCheckBox.state() == NSOnState: iserror = 'error' in text.lower() self.pjsipCount += 1 self.pjsipBytes += len(text) if iserror: self.append_error_line(self.pjsipTextView, text) else: self.append_line(self.pjsipTextView, text) self.pjsipInfoLabel.setStringValue_( "%d lines, %sytes" % (self.pjsipCount, format_size(self.pjsipBytes)))
def renderNotifications(self): text = unicode( self.filterNotificationsSearchBox.stringValue().strip().lower()) self.notifications = [ notification for notification in self.notifications_unfiltered if text in notification[0].lower() ] if text else self.notifications_unfiltered self.notificationsTextView.noteNumberOfRowsChanged() self.notificationsTextView.scrollRowToVisible_( len(self.notifications) - 1) self.notificationsInfoLabel.setStringValue_( '%d notifications, %sytes' % (len(self.notifications), format_size(self.notificationsBytes)) if not text else '%d notifications matched' % len(self.notifications))
def format_progress(self): t = NSLocalizedString("Transferred %s of ", "Label") % format_size( self.bytes, 1024) + format_size(self.total_bytes, 1024) if self.transfer_rate is not None: if self.transfer_rate == 0: status = t + " (" + NSLocalizedString("stalled", "Label") + ")" else: eta = (self.total_bytes - self.bytes) / self.transfer_rate if eta < 60: time_left = NSLocalizedString("Less than 1 minute", "Label") elif eta < 60 * 60: e = eta / 60 time_left = NSLocalizedString("About %i minutes", "Label") % e else: time_left = "%s left" % format_duration( datetime.timedelta(seconds=eta)) status = t + " - %s/s - %s" % (format_size( self.transfer_rate, bits=True), time_left) else: status = t return status
def add_to_history(self): FileTransferHistory().add_transfer(transfer_id=self.ft_info.transfer_id, direction=self.ft_info.direction, local_uri=self.ft_info.local_uri, remote_uri=self.ft_info.remote_uri, file_path=self.ft_info.file_path, bytes_transfered=self.ft_info.bytes_transfered, file_size=self.ft_info.file_size or 0, status=self.ft_info.status) message = "<h3>%s File Transfer</h3>" % self.ft_info.direction.capitalize() message += "<p>%s (%s)" % (self.ft_info.file_path, format_size(self.ft_info.file_size or 0)) media_type = 'file-transfer' local_uri = self.ft_info.local_uri remote_uri = self.ft_info.remote_uri direction = self.ft_info.direction status = 'delivered' if self.ft_info.status == 'completed' else 'failed' cpim_from = self.ft_info.remote_uri cpim_to = self.ft_info.remote_uri timestamp = str(ISOTimestamp.now()) ChatHistory().add_message(self.ft_info.transfer_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, "html", "0", status)
def print_section(self, caption, steps, format_string): section = [caption,] pkgs = [s.pkg for s in steps] for pkg in sorted(pkgs): line = format_string % { "arch" : pkg.arch, "name" : pkg.name, "repo" : pkg.repo.name, "size" : util.format_size(pkg.size), "version" : pkg.friendly_version, } section.append(line) section.append("") return section
def print_section(self, caption, steps, format_string): section = [ caption, ] pkgs = [s.pkg for s in steps] for pkg in sorted(pkgs): line = format_string % { "arch": pkg.arch, "name": pkg.name, "repo": pkg.repo.name, "size": util.format_size(pkg.size), "version": pkg.friendly_version, } section.append(line) section.append("") return section
def getparts(msg, parent): for child in msg.get_payload(): if child.is_multipart(): getparts( child, partmodel.append_named( parent, MESSAGE=None, LABEL=child.get_content_subtype())) else: label = '\n'.join( filter( bool, (child.get_content_type(), child.get_filename(), util.format_size(len(child.get_payload()))))) partmodel.append_named(parent, MESSAGE=child, LABEL=label)
def add_row(parentrow, m): id, parent, subject, text, date, received, size, filename, folder, fromaddr, fromname = m dispsubject = subject or ('(No subject)' if filename else '(Missing message)') if not text: disptext = dispsubject elif not subject or re.match('(?i)re:', subject): disptext = text else: disptext = subject + ' / ' + text return msgmodel.append_named(parentrow, SELECTED=False, ID=id, FILENAME=filename, CONTENT=disptext, SUBJECT=dispsubject, FROM=fromname + ' <' + fromaddr + '>' if fromname else fromaddr, DATE=date or received, FOLDER=folder, LAST=None, SIZE=size or 0, SIZESTR=util.format_size(size) if size else None )
def initWithFrame_oldTransfer_(self, frame, transferInfo): self = NSView.initWithFrame_(self, frame) if self: self.oldTransferInfo = transferInfo self.file_path = transferInfo.file_path self.remote_uri = transferInfo.remote_uri self.local_uri = transferInfo.local_uri NSBundle.loadNibNamed_owner_("FileTransferItemView", self) self.updateIcon(NSWorkspace.sharedWorkspace().iconForFile_( self.file_path)) self.nameText.setStringValue_(os.path.basename(self.file_path)) self.fromText.setStringValue_( 'To %s from account %s' % (transferInfo.remote_uri, transferInfo.local_uri) if transferInfo.direction == 'outgoing' else 'From %s to account %s' % (transferInfo.remote_uri, transferInfo.local_uri)) self.revealButton.setHidden_(not os.path.exists(self.file_path)) time_print = format_date(transferInfo.time) if transferInfo.status == "completed": self.sizeText.setTextColor_(NSColor.blueColor()) t = NSLocalizedString("Completed transfer of ", "Label") status = t + "%s %s" % (format_size(transferInfo.file_size, 1024), time_print) else: self.sizeText.setTextColor_(NSColor.redColor()) status = "%s %s" % (transferInfo.status.title(), time_print) self.sizeText.setStringValue_(status) frame.size = self.view.frame().size self.setFrame_(frame) self.addSubview_(self.view) self.relayoutForDone() if transferInfo.direction == "outgoing" and transferInfo.status != "completed" and os.path.exists( self.file_path): self.retryButton.setHidden_(False) self.done = True return self
def _NH_SIPSessionDidEnd(self, sender, data): self.log_info(u"Session ended by %s" % data.originator) notification_center = NotificationCenter() self.end_time = datetime.datetime.now() if not self.finished_transfer: self.fail_reason = "Interrupted" self.ft_info.status = "failed" self.ft_info.bytes_transfered = self.file_pos self.status = "%s %s %s" % (str(format_size(self.file_pos, 1024)), unichr(0x2014), self.fail_reason) notification_center.post_notification("BlinkFileTransferDidFail", sender=self) else: self.ft_info.status = "completed" self.ft_info.bytes_transfered=self.file_size self.status = "Completed in %s %s %s" % (format_duration(self.end_time-self.start_time), unichr(0x2014), format_size(self.file_size)) notification_center.post_notification("BlinkFileTransferDidEnd", sender=self, data=NotificationData(file_path=self.file_path)) self.file_selector.fd.close() self.file_selector = None
def add_row(parentrow, m): id, parent, subject, text, date, received, size, filename, folder, fromaddr, fromname = m dispsubject = subject or ('(No subject)' if filename else '(Missing message)') if not text: disptext = dispsubject elif not subject or re.match('(?i)re:', subject): disptext = text else: disptext = subject + ' / ' + text return msgmodel.append_named( parentrow, SELECTED=False, ID=id, FILENAME=filename, CONTENT=disptext, SUBJECT=dispsubject, FROM=fromname + ' <' + fromaddr + '>' if fromname else fromaddr, DATE=date or received, FOLDER=folder, LAST=None, SIZE=size or 0, SIZESTR=util.format_size(size) if size else None)
def format_progress(self): if not self.file_size: return '' if self.transfer_rate is not None: if self.transfer_rate == 0: status = "%s of %s (stalled)" % (format_size(self.file_pos, 1024), format_size(self.file_size, 1024)) else: eta = (self.file_size - self.file_pos) / self.transfer_rate if eta < 60: time_left = "Less than 1 minute" elif eta < 60*60: time_left = "About %i minutes" % (eta/60) else: time_left = "%s left" % format_duration(datetime.timedelta(seconds=eta)) status = "%s of %s - %s/s - %s" % (format_size(self.file_pos, 1024), format_size(self.file_size, 1024), format_size(self.transfer_rate, bits=True), time_left) else: status = "%s of %s" % (format_size(self.file_pos, 1024), format_size(self.file_size, 1024)) return status
def renderPJSIP(self, text): if self.pjsipCheckBox.state() == NSOnState: iserror = 'error' in text.lower() self.pjsipCount += 1 self.pjsipBytes += len(text) if iserror: self.append_error_line(self.pjsipTextView, text) else: self.append_line(self.pjsipTextView, text) self.pjsipInfoLabel.setStringValue_("%d lines, %sytes" % (self.pjsipCount, format_size(self.pjsipBytes)))
def renderSIP(self, notification): settings = SIPSimpleSettings() if settings.logs.trace_sip_in_gui == Disabled: return event_data = notification.data self.sipBytes += len(event_data.data) if self._siptrace_start_time is None: self._siptrace_start_time = notification.datetime self._siptrace_packet_count += 1 text = NSMutableAttributedString.alloc().init() if self.lastSIPMessageWasDNS: text.appendAttributedString_(self.newline) self.lastSIPMessageWasDNS = False if event_data.received: self.sipInCount += 1 text.appendAttributedString_(self.receivedText) else: self.sipOutCount += 1 text.appendAttributedString_(self.sendingText) line = " Packet %d, +%s\n" % (self._siptrace_packet_count, (notification.datetime - self._siptrace_start_time)) text.appendAttributedString_(NSAttributedString.alloc().initWithString_(line)) line = "%s: %s:%d -(SIP over %s)-> %s:%d\n" % (notification.datetime, event_data.source_ip, event_data.source_port, event_data.transport, event_data.destination_ip, event_data.destination_port) text.appendAttributedString_(NSAttributedString.alloc().initWithString_(line)) data = event_data.data.strip() first, rest = data.split("\n", 1) applications = None method = None msg_type = None event = None code = None if data.startswith("SIP/2.0"): try: code = first.split()[1] attribs = self.boldRedTextAttribs if code[0] in ["4", "5", "6"] else self.boldTextAttribs for line in data.split("\n"): line = line.strip() if line.startswith("Event:"): try: event = line.split(" ", 1)[1] except IndexError: pass continue if line.startswith("CSeq"): cseq, _number, _method = line.split(" ", 2) try: applications = self.filter_sip_methods[_method.strip()] method = _method msg_type = 'response' except KeyError: pass continue if settings.logs.trace_sip_in_gui == Full: text.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(first+"\n", attribs)) text.appendAttributedString_(NSAttributedString.alloc().initWithString_(rest+"\n")) else: text.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(first+"\n", attribs)) except: text.appendAttributedString_(NSAttributedString.alloc().initWithString_(data+"\n")) else: _method = first.split()[0] try: applications = self.filter_sip_methods[_method] method = _method msg_type = 'offer' except KeyError: pass for line in data.split("\n"): line = line.strip() if line.startswith("Event:"): try: event = line.split(" ", 1)[1] except IndexError: pass continue if settings.logs.trace_sip_in_gui == Full: text.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(first+"\n", self.boldTextAttribs)) text.appendAttributedString_(NSAttributedString.alloc().initWithString_(rest+"\n")) else: text.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(first+"\n", self.boldTextAttribs)) self.sipInfoLabel.setStringValue_("%d SIP messages sent, %d SIP messages received, %sytes" % (self.sipOutCount, self.sipInCount, format_size(self.sipBytes))) if self.filter_sip_application is not None and applications is not None: if self.filter_sip_application not in applications: return self.sipTextView.textStorage().appendAttributedString_(text) self.sipTextView.textStorage().appendAttributedString_(self.newline) self.sipTextView.scrollRangeToVisible_(NSMakeRange(self.sipTextView.textStorage().length()-1, 1))
def renderNotifications(self): text = unicode(self.filterNotificationsSearchBox.stringValue().strip().lower()) self.notifications = [notification for notification in self.notifications_unfiltered if text in notification[0].lower()] if text else self.notifications_unfiltered self.notificationsTextView.noteNumberOfRowsChanged() self.notificationsTextView.scrollRowToVisible_(len(self.notifications)-1) self.notificationsInfoLabel.setStringValue_('%d notifications, %sytes' % (len(self.notifications), format_size(self.notificationsBytes)) if not text else '%d notifications matched' % len(self.notifications))
def dump(self, logger=None): if logger is None: logger = logging.getLogger("pakfire") if not self.steps: logger.info(_("Nothing to do")) return # Prepare some string formatting stuff. # XXX this needs to adapt to the terminal size format_string = " %(name)-21s %(arch)-8s %(version)-21s %(repo)-18s %(size)6s " # Prepare the headline. headline = format_string % { "arch": _("Arch"), "name": _("Package"), "repo": _("Repository"), "size": _("Size"), "version": _("Version"), } # As long, as we can't use the actual terminal width, we use the # length of the headline. terminal_width = len(headline) # Create a separator line. sep_line = "=" * terminal_width # Create the header. s = [ sep_line, headline, sep_line, ] steps = ( (_("Installing:"), self.installs), (_("Reinstalling:"), self.reinstalls), (_("Updating:"), self.updates), (_("Downgrading:"), self.downgrades), (_("Removing:"), self.removes), ) for caption, _steps in steps: if not _steps: continue s += self.print_section(caption, _steps, format_string) # Append the transaction summary s.append(_("Transaction Summary")) s.append(sep_line) for caption, _steps in steps: if not _steps: continue s.append( "%-20s %-4d %s" % (caption, len(_steps), _("package", "packages", len(_steps)))) # Calculate the size of all files that need to be downloaded this this # transaction. if self.download_size: s.append( _("Total download size: %s") % util.format_size(self.download_size)) # Show the size that is consumed by the new packages. if self.installsizechange > 0: s.append( _("Installed size: %s") % util.format_size(self.installsizechange)) elif self.installsizechange < 0: s.append( _("Freed size: %s") % util.format_size(-self.installsizechange)) s.append("") for line in s: logger.info(line)
def dump(self, logger=None): if logger is None: logger = logging.getLogger("pakfire") if not self.steps: logger.info(_("Nothing to do")) return # Prepare some string formatting stuff. # XXX this needs to adapt to the terminal size format_string = " %(name)-21s %(arch)-8s %(version)-21s %(repo)-18s %(size)6s " # Prepare the headline. headline = format_string % { "arch" : _("Arch"), "name" : _("Package"), "repo" : _("Repository"), "size" : _("Size"), "version" : _("Version"), } # As long, as we can't use the actual terminal width, we use the # length of the headline. terminal_width = len(headline) # Create a separator line. sep_line = "=" * terminal_width # Create the header. s = [sep_line, headline, sep_line,] steps = ( (_("Installing:"), self.installs), (_("Reinstalling:"), self.reinstalls), (_("Updating:"), self.updates), (_("Downgrading:"), self.downgrades), (_("Removing:"), self.removes), ) for caption, _steps in steps: if not _steps: continue s += self.print_section(caption, _steps, format_string) # Append the transaction summary s.append(_("Transaction Summary")) s.append(sep_line) for caption, _steps in steps: if not _steps: continue s.append("%-20s %-4d %s" % (caption, len(_steps), _("package", "packages", len(_steps)))) # Calculate the size of all files that need to be downloaded this this # transaction. if self.download_size: s.append(_("Total download size: %s") % util.format_size(self.download_size)) # Show the size that is consumed by the new packages. if self.installsizechange > 0: s.append(_("Installed size: %s") % util.format_size(self.installsizechange)) elif self.installsizechange < 0: s.append(_("Freed size: %s") % util.format_size(-self.installsizechange)) s.append("") for line in s: logger.info(line)
def renderSIP(self, event_data): self.sipBytes += len(event_data.data) if self.sipTraceType is None: return if self._siptrace_start_time is None: self._siptrace_start_time = event_data.timestamp self._siptrace_packet_count += 1 text = NSMutableAttributedString.alloc().init() if self.lastSIPMessageWasDNS: text.appendAttributedString_(self.newline) self.lastSIPMessageWasDNS = False if event_data.received: self.sipInCount += 1 text.appendAttributedString_(self.receivedText) else: self.sipOutCount += 1 text.appendAttributedString_(self.sendingText) line = " Packet %d, +%s\n" % (self._siptrace_packet_count, (event_data.timestamp - self._siptrace_start_time)) text.appendAttributedString_(NSAttributedString.alloc().initWithString_(line)) line = "%(timestamp)s: %(source_ip)s:%(source_port)d -(SIP over %(transport)s)-> %(destination_ip)s:%(destination_port)d\n" % event_data.__dict__ text.appendAttributedString_(NSAttributedString.alloc().initWithString_(line)) data = event_data.data.strip() first, rest = data.split("\n", 1) if data.startswith("SIP/2.0"): try: code = first.split()[1] attribs = self.boldRedTextAttribs if code[0] in ["4", "5", "6"] else self.boldTextAttribs if self.sipTraceType == "full": text.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(first+"\n", attribs)) text.appendAttributedString_(NSAttributedString.alloc().initWithString_(rest+"\n")) else: text.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(first+"\n", attribs)) except: text.appendAttributedString_(NSAttributedString.alloc().initWithString_(data+"\n")) else: if self.sipTraceType == "full": text.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(first+"\n", self.boldTextAttribs)) text.appendAttributedString_(NSAttributedString.alloc().initWithString_(rest+"\n")) else: text.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(first+"\n", self.boldTextAttribs)) self.sipTextView.textStorage().appendAttributedString_(text) self.sipTextView.textStorage().appendAttributedString_(self.newline) self.sipTextView.scrollRangeToVisible_(NSMakeRange(self.sipTextView.textStorage().length()-1, 1)) self.sipInfoLabel.setStringValue_("%d SIP messages sent, %d SIP messages received, %sytes" % (self.sipOutCount, self.sipInCount, format_size(self.sipBytes)))
def _NH_OutgoingPullFileTransferHandlerDidEnd(self, sender, data): notification_center = NotificationCenter() if not self.finished_transfer: self.log_info(u"Removing incomplete file %s" % self.file_path) os.remove(self.file_path) self.fail_reason = "Interrupted" else: local_hash = 'sha1:' + ':'.join(re.findall(r'..', self.hash.hexdigest())) remote_hash = self.file_selector.hash.lower() if local_hash == remote_hash: oname = self.file_path self.file_path = self.file_path[:-len(".download")] self.ft_info.file_path = self.file_path self.log_info(u"Renaming transferred file to %s" % self.file_path) os.rename(oname, self.file_path) else: self.error = True self.fail_reason = "File hash mismatch" self.log_info(u"Removing corrupted file %s" % self.file_path) os.remove(self.file_path) self.log_info("Incoming File Transfer ended (%i of %i bytes transferred)" % (self.file_pos, self.file_size)) self.end_time = datetime.datetime.now() if self.finished_transfer and not self.error: self.status = "Completed in %s %s %s" % (format_duration(self.end_time-self.start_time), unichr(0x2014), format_size(self.file_size)) self.ft_info.status = "completed" self.ft_info.bytes_transfered = self.file_size notification_center.post_notification("BlinkFileTransferDidEnd", sender=self, data=NotificationData(file_path=self.file_path)) else: self.status = self.fail_reason self.ft_info.status = "failed" self.ft_info.bytes_transfered = self.file_pos notification_center.post_notification("BlinkFileTransferDidFail", sender=self)
def _NH_MSRPTransportTrace(self, notification): if self.msrpTraceType is None: return arrow = { 'incoming': '<--', 'outgoing': '-->' }[notification.data.direction] try: local_address = notification.sender.transport.getHost() local_address = '%s:%d' % (local_address.host, local_address.port) except AttributeError: # this may happen because we process this notification after transport has been disconnected local_address = 'local' remote_address = notification.sender.getPeer() remote_address = '%s:%d' % (remote_address.host, remote_address.port) message = '\n%s: %s %s %s' % (notification.data.timestamp, local_address, arrow, remote_address) header = [] if self.msrpTraceType == "full": header = notification.data.data.split("\n") else: if notification.data.data.startswith("MSRP "): lines = notification.data.data.split("\n") for line in lines: if not line.strip() or line[0] == "-": break header.append(line) if notification.data.direction == "outgoing": self.msrpOutCount += 1 self.append_line(self.msrpTextView, self.sendingText) else: self.msrpInCount += 1 self.append_line(self.msrpTextView, self.receivedText) self.msrpBytes += len(message) self.append_line(self.msrpTextView, message) if header: try: dummy, ident, code, msg = header[0].split(None, 3) attribs = self.boldRedTextAttribs if int( code) >= 400 else self.boldTextAttribs self.append_line( self.msrpTextView, NSAttributedString.alloc().initWithString_attributes_( header[0], attribs)) except: self.append_line( self.msrpTextView, NSAttributedString.alloc().initWithString_attributes_( header[0], self.boldTextAttribs)) self.append_line(self.msrpTextView, "\n".join(header[1:])) if not self.msrpTraceType == "full": self.append_line(self.msrpTextView, self.newline) self.msrpInfoLabel.setStringValue_( "%d MSRP messages sent, %d MRSP messages received, %sytes" % (self.msrpOutCount, self.msrpInCount, format_size(self.msrpBytes)))
def format_subject_for_incoming_reinvite(self, session, streams): alt_action = None alt_object = ONLY_CHAT if len(streams) != 1: type_names = [s.type.replace('-', ' ').capitalize() for s in streams] if "Screen sharing" in type_names: ds = [s for s in streams if s.type == "screen-sharing"] if ds: type_names.remove("Screen sharing") if ds[0].handler.type == "active": type_names.append(NSLocalizedString("Remote Screen offered by", "Label")) else: type_names.append(NSLocalizedString("My Screen requested by", "Label")) subject = NSLocalizedString("Addition of %s", "Label") % ", ".join(type_names) elif 'Video' in type_names: subject = NSLocalizedString("Video call requested by", "Label") else: subject = NSLocalizedString("Addition of %s requested by", "Label") % ", ".join(type_names) type_names = [s.type.replace('-', ' ').capitalize() for s in streams] if "Chat" in type_names: alt_action = NSLocalizedString("Chat Only", "Button title") alt_object = ONLY_CHAT elif "Audio" in type_names: alt_action = NSLocalizedString("Audio Only", "Button title") alt_object = ONLY_AUDIO elif type(streams[0]) is VideoStream: subject = NSLocalizedString("Addition of Video requested by", "Label") elif type(streams[0]) is AudioStream: subject = NSLocalizedString("Addition of Audio requested by", "Label") elif type(streams[0]) is ChatStream: subject = NSLocalizedString("Addition of Chat requested by", "Label") elif type(streams[0]) is FileTransferStream: subject = NSLocalizedString("Transfer of File", "Label") + " '%s' (%s) " % (streams[0].file_selector.name, format_size(streams[0].file_selector.size, 1024)) + NSLocalizedString("offered by", "Label") elif type(streams[0]) is ScreenSharingStream: if streams[0].handler.type == "active": subject = NSLocalizedString("Remote Screen offered by", "Label") else: subject = NSLocalizedString("My Screen requested by", "Label") else: subject = NSLocalizedString("Addition of unknown stream to existing session requested by", "Label") return subject, alt_action, alt_object
def _NH_MSRPTransportTrace(self, notification): settings = SIPSimpleSettings() if settings.logs.trace_msrp_in_gui == Disabled: return arrow = {'incoming': '<--', 'outgoing': '-->'}[notification.data.direction] try: local_address = notification.sender.transport.getHost() local_address = '%s:%d' % (local_address.host, local_address.port) except AttributeError: # this may happen because we process this notification after transport has been disconnected local_address = 'local' remote_address = notification.sender.getPeer() remote_address = '%s:%d' % (remote_address.host, remote_address.port) message = '\n%s: %s %s %s' % (notification.datetime, local_address, arrow, remote_address) header = [] if settings.logs.trace_msrp_in_gui == Full: header = notification.data.data.split("\n") else: if notification.data.data.startswith("MSRP "): lines = notification.data.data.split("\n") for line in lines: if not line.strip() or line[0] == "-": break header.append(line) if notification.data.direction == "outgoing": self.msrpOutCount += 1 self.append_line(self.msrpTextView, self.sendingText) else: self.msrpInCount += 1 self.append_line(self.msrpTextView, self.receivedText) self.msrpBytes += len(message) self.append_line(self.msrpTextView, message) if header: try: dummy, ident, code, msg = header[0].split(None, 3) attribs = self.boldRedTextAttribs if int(code) >= 400 else self.boldTextAttribs self.append_line(self.msrpTextView, NSAttributedString.alloc().initWithString_attributes_(header[0], attribs)) except: self.append_line(self.msrpTextView, NSAttributedString.alloc().initWithString_attributes_(header[0], self.boldTextAttribs)) self.append_line(self.msrpTextView, "\n".join(header[1:])) if settings.logs.trace_msrp_in_gui != Full: self.append_line(self.msrpTextView, self.newline) self.msrpInfoLabel.setStringValue_("%d MSRP messages sent, %d MRSP messages received, %sytes" % (self.msrpOutCount, self.msrpInCount, format_size(self.msrpBytes)))
def display(result): return "Transfer Today: {0}".format(format_size(result))
def display(result): largest_items = nlargest(15, result.iteritems(), itemgetter(1)) return ("Most Transferred Files ({0}):\n ".format(len(result)) + "\n ".join(["{0} - {1}".format(name, format_size(num)) for name, num in largest_items]))
def format_subject_for_incoming_invite(self, session, streams): default_action = u"Accept" alt_action = None if len(streams) != 1: type_names = [s.type.replace('-', ' ').capitalize() for s in streams] if "Chat" in type_names: alt_action = u"Chat Only" elif "Audio" in type_names and len(type_names) > 1: alt_action = u"Audio Only" if session.subject: subject = session.subject else: if len(streams) != 1: if "Screen sharing" in type_names: ds = [s for s in streams if s.type == "screen-sharing"] if ds: type_names.remove("Screen sharing") if ds[0].handler.type == "active": type_names.append("Remote Screen offered by") else: type_names.append("My Screen requested by") subject = u"%s" % " and ".join(type_names) else: subject = u"%s session requested by" % " and ".join(type_names) elif type(streams[0]) is AudioStream: subject = u"Audio Session requested by" elif type(streams[0]) is ChatStream: subject = u"Chat Session requested by" elif type(streams[0]) is ScreenSharingStream: subject = u"Remote Screen offered by" if streams[0].handler.type == "active" else u"My Screen requested by" elif type(streams[0]) is FileTransferStream: subject = u"Transfer of File '%s' (%s) offered by" % (streams[0].file_selector.name.decode("utf8"), format_size(streams[0].file_selector.size, 1024)) else: subject = u"Incoming Session request from" BlinkLogger().log_info(u"Unknown Session content %s" % streams) return subject, default_action, alt_action
def format_subject_for_incoming_reinvite(self, session, streams): default_action = u"Accept" if len(streams) != 1: type_names = [s.type.replace('-', ' ').capitalize() for s in streams] if "Screen sharing" in type_names: ds = [s for s in streams if s.type == "screen-sharing"] if ds: type_names.remove("Screen sharing") if ds[0].handler.type == "active": type_names.append("Remote Screen offered by") else: type_names.append("My Screen requested by") subject = u"Addition of %s" % " and ".join(type_names) else: subject = u"Addition of %s to existing session requested by" % " and ".join(type_names) alt_action = u"Chat Only" elif type(streams[0]) is AudioStream: subject = u"Addition of Audio to existing session requested by" alt_action = None elif type(streams[0]) is ChatStream: subject = u"Addition of Chat to existing session requested by" alt_action = None elif type(streams[0]) is FileTransferStream: subject = u"Transfer of File '%s' (%s) offered by" % (streams[0].file_selector.name, format_size(streams[0].file_selector.size, 1024)) alt_action = None elif type(streams[0]) is ScreenSharingStream: if streams[0].handler.type == "active": subject = u"Remote Screen offered by" else: subject = u"My Screen requested by" alt_action = None else: subject = u"Addition of unknown Stream to existing Session requested by" alt_action = None return subject, default_action, alt_action
def renderSIP(self, event_data): self.sipBytes += len(event_data.data) if self.sipTraceType is None: return if self._siptrace_start_time is None: self._siptrace_start_time = event_data.timestamp self._siptrace_packet_count += 1 text = NSMutableAttributedString.alloc().init() if self.lastSIPMessageWasDNS: text.appendAttributedString_(self.newline) self.lastSIPMessageWasDNS = False if event_data.received: self.sipInCount += 1 text.appendAttributedString_(self.receivedText) else: self.sipOutCount += 1 text.appendAttributedString_(self.sendingText) line = " Packet %d, +%s\n" % (self._siptrace_packet_count, (event_data.timestamp - self._siptrace_start_time)) text.appendAttributedString_( NSAttributedString.alloc().initWithString_(line)) line = "%(timestamp)s: %(source_ip)s:%(source_port)d -(SIP over %(transport)s)-> %(destination_ip)s:%(destination_port)d\n" % event_data.__dict__ text.appendAttributedString_( NSAttributedString.alloc().initWithString_(line)) data = event_data.data.strip() first, rest = data.split("\n", 1) if data.startswith("SIP/2.0"): try: code = first.split()[1] attribs = self.boldRedTextAttribs if code[0] in [ "4", "5", "6" ] else self.boldTextAttribs if self.sipTraceType == "full": text.appendAttributedString_( NSAttributedString.alloc().initWithString_attributes_( first + "\n", attribs)) text.appendAttributedString_( NSAttributedString.alloc().initWithString_(rest + "\n")) else: text.appendAttributedString_( NSAttributedString.alloc().initWithString_attributes_( first + "\n", attribs)) except: text.appendAttributedString_( NSAttributedString.alloc().initWithString_(data + "\n")) else: if self.sipTraceType == "full": text.appendAttributedString_( NSAttributedString.alloc().initWithString_attributes_( first + "\n", self.boldTextAttribs)) text.appendAttributedString_( NSAttributedString.alloc().initWithString_(rest + "\n")) else: text.appendAttributedString_( NSAttributedString.alloc().initWithString_attributes_( first + "\n", self.boldTextAttribs)) self.sipTextView.textStorage().appendAttributedString_(text) self.sipTextView.textStorage().appendAttributedString_(self.newline) self.sipTextView.scrollRangeToVisible_( NSMakeRange(self.sipTextView.textStorage().length() - 1, 1)) self.sipInfoLabel.setStringValue_( "%d SIP messages sent, %d SIP messages received, %sytes" % (self.sipOutCount, self.sipInCount, format_size(self.sipBytes)))
def updateVideo(self): if self.video_status.stringValue() and ( self.sessionController is None or self.video_stream is None or self.video_stream.stream is None): self.resetVideo() elif (self.sessionController is not None and self.video_stream is not None and self.video_stream.stream is not None): self.updateVideoStatus() self.video_rx_speed_graph.setDataQueue_needsDisplay_( self.video_stream.rx_speed_history, True if self.window.isVisible() else False) self.video_tx_speed_graph.setDataQueue_needsDisplay_( self.video_stream.tx_speed_history, True if self.window.isVisible() else False) rtt = self.video_stream.statistics['rtt'] if rtt > 1000: text = '%.1f s' % (float(rtt) / 1000.0) elif rtt > 100: text = '%d ms' % rtt elif rtt: text = '%d ms' % rtt else: text = '' self.video_rx_speed.setStringValue_('Rx %s/s' % format_size( self.video_stream.statistics['rx_bytes'], bits=True)) self.video_tx_speed.setStringValue_('Tx %s/s' % format_size( self.video_stream.statistics['tx_bytes'], bits=True)) if self.video_stream.stream.codec and self.video_stream.stream.sample_rate: codec = beautify_video_codec(self.video_stream.stream.codec) try: settings = SIPSimpleSettings() sample_rate = self.video_stream.stream.sample_rate / 1000 codec = codec + " @%d fps" % self.video_stream.statistics[ 'fps'] except TypeError: pass self.video_codec.setStringValue_(codec) self.video_srtp_lock.setHidden_( False if self.video_stream.encryption_active else True) if self.video_stream.encryption_active: if self.video_stream.zrtp_active: self.video_srtp_lock.setImage_( NSImage.imageNamed_("locked-green") if self. video_stream.zrtp_verified else NSImage. imageNamed_("locked-red")) else: self.video_srtp_lock.setImage_( NSImage.imageNamed_("srtp")) else: self.video_codec.setStringValue_('') self.video_srtp_lock.setHidden_(True) self.video_remote_endpoint.setStringValue_( '%s:%s' % (self.video_stream.stream.remote_rtp_address, self.video_stream.stream.remote_rtp_port) if self. video_stream.stream.remote_rtp_address else '') if self.video_stream.stream.ice_active: ice_status = self.video_stream.ice_negotiation_status if self.video_stream.ice_negotiation_status is not None else '' if self.video_stream.stream.ice_active: if self.video_stream.stream.local_rtp_candidate and self.video_stream.stream.remote_rtp_candidate: if self.video_stream.stream.local_rtp_candidate.type.lower( ) != 'relay' and self.video_stream.stream.remote_rtp_candidate.type.lower( ) != 'relay': if self.video_stream.stream.local_rtp_candidate.type.lower( ) == 'host' and self.video_stream.stream.remote_rtp_candidate.type.lower( ) == 'host': ice_status = NSLocalizedString( "Host to Host", "Label") else: ice_status = NSLocalizedString( "Peer to Peer", "Label") else: ice_status = NSLocalizedString( "Server Relayed", "Label") else: ice_status = self.video_stream.ice_negotiation_status if self.video_stream.ice_negotiation_status is not None else '' if ice_status == "All ICE checklists failed (PJNATH_EICEFAILED)": ice_status = NSLocalizedString("Probing Failed", "Label") elif ice_status == "Remote answer doesn't support ICE": ice_status = NSLocalizedString("Not Supported", "Label") self.video_ice_negotiation.setStringValue_(ice_status)
def progress_text(self): if self.fail_reason: return u"%s of %s %s %s" % (format_size(self.file_pos), format_size(self.file_size), unichr(0x2014), self.fail_reason) else: return self.status
def format_subject_for_incoming_invite(self, session, streams): alt_action = None alt_object = ONLY_CHAT if len(streams) != 1: type_names = [s.type.replace('-', ' ').capitalize() for s in streams] if "Chat" in type_names: alt_action = NSLocalizedString("Chat Only", "Button title") alt_object = ONLY_CHAT elif "Audio" in type_names and len(type_names) > 1: alt_action = NSLocalizedString("Audio Only", "Button title") alt_object = ONLY_AUDIO if session.subject: subject = session.subject else: if len(streams) != 1: if "Screen sharing" in type_names: ds = [s for s in streams if s.type == "screen-sharing"] if ds: type_names.remove("Screen sharing") if ds[0].handler.type == "active": type_names.append(NSLocalizedString("Remote Screen offered by", "Label")) else: type_names.append(NSLocalizedString("My Screen requested by", "Label")) subject = ", ".join(type_names) elif 'Video' in type_names: subject = NSLocalizedString("Video call requested by", "Label") else: subject = NSLocalizedString("%s Session requested by", "Label") % ", ".join(type_names) elif type(streams[0]) is VideoStream: subject = NSLocalizedString("Video call requested by", "Label") elif type(streams[0]) is AudioStream: subject = NSLocalizedString("Audio call requested by", "Label") elif type(streams[0]) is ChatStream: subject = NSLocalizedString("Chat Session requested by", "Label") elif type(streams[0]) is ScreenSharingStream: subject = NSLocalizedString("Remote Screen offered by", "Label") if streams[0].handler.type == "active" else NSLocalizedString("My Screen requested by", "Label") elif type(streams[0]) is FileTransferStream: subject = NSLocalizedString("Transfer of File", "Label") + " '%s' (%s) " % (streams[0].file_selector.name.decode("utf8"), format_size(streams[0].file_selector.size, 1024)) + NSLocalizedString("offered by", "Label") else: subject = NSLocalizedString("Incoming Session request from", "Label") BlinkLogger().log_info(u"Unknown media type %s" % streams) return subject, alt_action, alt_object
def display(result): return "Total Transfer: {0}".format(format_size(result))