def get_hr_style_from_css(css): available_css_attrs = ('width', 'border-width', 'color', 'margin-top', 'margin-bottom', 'float', 'border-style') float_mapping = {'left': 'LEFT', 'right': 'RIGTH', 'none': 'CENTER'} attrs = {} for key, value in css.iteritems(): if key in available_css_attrs: if key == 'width': attrs['width'] = format_size(value) elif key == 'border-width': attrs['thickness'] = format_size(value) elif key == 'color': attrs['color'] = get_color(value) elif key == 'margin-top': attr_value = format_size(value) if attr_value is not None: attrs['spaceBefore'] = attr_value elif key == 'margin-bottom': attr_value = format_size(value) if attr_value is not None: attrs['spaceAfter'] = attr_value elif key == 'float': attrs['hAlign'] = float_mapping.get(value, 'CENTER') elif key == 'border-style': dash = None if value == 'solid': dash = None elif value == 'dashed': dash = [5, 5] elif value == 'dotted': dash = [2, 2] attrs['dash'] = dash return attrs
def p_border_style(key, value): style_attrs = {} if key == 'border': tab = value.split() for element in tab: size = format_size(element, None) if size is not None: style_attrs['borderWidth'] = size continue color = get_color_as_hexa(element, None) if color is not None: style_attrs['borderColor'] = color continue elif key == 'border-bottom': tab = value.split() for element in tab: size = format_size(element, None) if size is not None: style_attrs['borderWidth'] = size continue color = get_color_as_hexa(element, None) if color is not None: style_attrs['borderColor'] = color continue elif key == 'border-color': color = get_color_as_hexa(value, None) if color is not None: style_attrs['borderColor'] = color elif key == 'border-width': size = format_size(value, None) if size is not None: style_attrs['borderWidth'] = size return style_attrs
def __render_details (self, column, cell, model, iter, data): # get the item we are dealing with item = model[iter][0] downloads = self.client.downloads.value text = "" # link is active if downloads.has_key (item.id): download = downloads[item.id] # link is downloading if item.status == Link.Status.DOWNLOADING: speed = utils.format_size (download.speed) eta = utils.format_time (download.eta) size = utils.format_size (download.size) downloaded = utils.format_size (download.bytes_transferred) cell.set_property ("markup", "<small><b>{0}</b> of <b>{1}</b> downloaded @ <b>{2}/s</b> with {3} remaining</small>".format (downloaded, size, speed, eta)) # link is pending some action elif item.status == Link.Status.WAITING: # get the current wait time remaining = download.time_left if download.time_left > 0 else 0 wait_time = utils.format_time (remaining) cell.set_property ("markup", "<small>{0} left</small>".format (wait_time)) elif item.status == Link.Status.FINISHED: size = utils.format_size (item.size) cell.set_property ("markup", "<small>{0} downloaded</small>".format (size)) else: text = "<b>{0}</b>".format (item.error) if item.error else "" cell.set_property ("markup", "<small>{0}</small>".format (text))
def init_files(path): new_path = format_path(path) headers_with_token = {'Authorization': 'Bearer ' + cache['access_token']} url = f'https://graph.microsoft.com/v1.0/me/drive/root{new_path}children' r = requests.get(url, headers=headers_with_token) file_data = eval(r.text) if "error" in file_data: print(file_data['error']['message']) else: values = {} for value in file_data['value']: if value['name'].lower().strip() == 'readme.md': readme = requests.get(value['@microsoft.graph.downloadUrl']).text values['readme.md'] = render_markdown(readme) elif value['name'].lower().strip() == 'head.md': readme = requests.get(value['@microsoft.graph.downloadUrl']).text values['head.md'] = render_markdown(readme) else: if 'folder' in value: folder = { 'time': format_time(value['lastModifiedDateTime']), 'size': format_size(value['size']) } values[value['name']] = folder init_files(path.rstrip('/') + '/' + value['name']) elif 'file' in value: file = { 'time': format_time(value['lastModifiedDateTime']), 'size': format_size(value['size']), 'url': value['@microsoft.graph.downloadUrl'] } values[value['name']] = file cache_tmp['files'][path] = values
def do_quota(self, _): '''disk usage''' ret = self._c.quota() if ret['errno'] == 0: print format_size(ret['used']), "/", format_size(ret['total']) print "%3.2f%%" % (float(ret['used']) / ret['total'] * 100) else: print 'error', ret
def table_get_margin(style_css): """Calculate and return top and bottom margin""" margin_top = margin_bottom = None, None for key, value in style_css.iteritems(): if key == 'margin-top': margin_top = format_size(value, None) elif key == 'margin-bottom': margin_bottom = format_size(value, None) return margin_top, margin_bottom
def format_data(data): data["completed_bytes"] = utils.format_size(data["raw_completed_bytes"]) data["total_bytes"] = utils.format_size(data["raw_total_bytes"]) data["percentage"] = "%.2f" % (data["raw_completed_bytes"] / float(data["raw_total_bytes"]) * 100) data["state"] = get_state(data) data["ratio"] = "%.2f" % (float(data["raw_ratio"]) / 1000) data["down_rate"] = utils.format_speed(data["raw_down_rate"]) data["time_remaining"] = utils.time_remaining(data["raw_down_rate"], data["raw_left_bytes"]) return data
def execute (self): # Channels lst = ChannelList (self.config, self.keys, self.id) channels = lst.execute() # Files lst = FileList (self.config, self.keys, self.id, ','.join(channels)) remote_files = lst.execute() # Check local files new_files = [] for remote_file in remote_files: fp = os.path.join (self.download_dir, remote_file['path']) # No local version if not os.path.exists (fp): new_files.append (remote_file) continue # Outdated local version size = os.path.getsize(fp) attr_md5 = xattr.getxattr (fp, 'md5') attr_time = utils.getxattr (fp, 'md5_time', 0) if remote_file['size'] != size: new_files.append (remote_file) continue if remote_file['md5'] != attr_md5: new_files.append (remote_file) continue logging.info ("%s is up to date" %(remote_file['path'])) if not new_files: return # Report for f in new_files: channel, filename = f['path'].split('/', 1) print (' #%s - %s (%s)' %(channel, filename, utils.format_size(f['size']))) total_size = reduce (lambda x,y: x+y, [f['size'] for f in new_files]) print ("%d files: %s"%(len(new_files), utils.format_size(total_size))) # New files to fetch for f in new_files: channel, filename = f['path'].split('/', 1) download = Download (self.config, self.download_dir, self.keys, self.id, channel, filename, remote_filesize = f['size'], callback_step = self.download_step, callback_finished = self.download_finished) download.execute()
def step_cb (self, filename, download_t, download_d): if self.time_start is None: self.time_start = time.time() lapse = (time.time() - self.time_start) + 0.000001 speed = utils.format_size(download_d/lapse) string = "%s - %s (%s/s)" %(filename, utils.format_size(download_d), speed) string += ' ' * 8 string += '\b' * len(string) sys.stdout.write (string) sys.stdout.flush()
def _display(self, dict): if dict.has_key("downTotal"): self._downTotal = dict["downTotal"] if dict.has_key("fractionDone"): self.progress = int(dict["fractionDone"] * 100.0) d = {"progress": str(self.progress), "size": utils.format_size(self.total_size)} if dict.has_key("timeEst"): d["time"] = utils.hours(dict["timeEst"]) self.message = _("Downloaded %(progress)s%% of %(size)s, %(time)s remaining.") % d else: self.message = _("Downloaded %(progress)s%% of %(size)s") % d if self._progress_callback() == 1: self._done.set() else: self.progress = 0 self.message = "" if self._progress_callback() == 1: self._done.set() if dict.has_key("upTotal"): # check to see if we should stop if self._done_downloading: if dict["upTotal"] >= self._downTotal: # if ratio is one, quit self._done.set() if time.time() - 60 * 60 >= self._start_time: # if it's been an hour, quit self._done.set()
def compute_table_border(key, value): """Key is one of these values border border-XXX-width border-XXX-style border-XXX-color width XXX equals to top, right, bottom, left with border equals to border-top + border-right + border-bottom + border-left """ if key == 'border': # explode the key in sub key # border-top # border-right # border-bottom # border-left return _compute_table_border_full(value) elif key in ('border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width'): return {key: format_size(value, 1)} elif key in ('border-top-style', 'border-right-style', 'border-bottom-style', 'border-left-style'): return {key: compute_border_style(value)} elif key in ('border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color'): return {key: get_color_as_hexa(value)} return None
def render_template(template_name, variables): env = Environment(loader=FileSystemLoader(['themes']), extensions=[]) env.filters['format_size_mb'] = lambda value: format_size_mb(value) env.filters['format_size'] = lambda value: format_size(value) env.filters['typo'] = lambda value: typo(value) tpl = env.get_template(template_name) return tpl.render(variables)
def _display(self, dict): if dict.has_key('downTotal'): self._downTotal = dict['downTotal'] if dict.has_key('fractionDone'): self.progress = int(dict['fractionDone'] * 100.0) d = { 'progress': str(self.progress), 'size': utils.format_size(self.total_size) } if dict.has_key('timeEst'): d['time'] = utils.hours(dict['timeEst']) self.message = _( "Downloaded %(progress)s%% of %(size)s, %(time)s remaining." ) % d else: self.message = _("Downloaded %(progress)s%% of %(size)s") % d if self._progress_callback() == 1: self._done.set() else: self.progress = 0 self.message = "" if self._progress_callback() == 1: self._done.set() if dict.has_key('upTotal'): #check to see if we should stop if self._done_downloading: if dict['upTotal'] >= self._downTotal: #if ratio is one, quit self._done.set() if time.time( ) - 60 * 60 >= self._start_time: #if it's been an hour, quit self._done.set()
def update(self): self.name.set_markup("<small>{0}</small>".format(self.link.name)) self.progress.set_fraction(self.status.percent / 100.0) self.speed.set_markup( "<small>{0}/s - {1}</small>".format( utils.format_size(self.status.speed), utils.format_time(self.status.eta) ) )
def __render_downloaded (self, column, cell, model, iter, data): # get the item we are dealing with item = model[iter][0] if item.size_done > 0: total = utils.format_size (item.size_done) cell.set_property ("text", total) else: cell.set_property ("text", "")
def table_padding_style(key, value, start, stop): """Calculate the Reportlab padding from the html one Note that only the padding-X attributes are allowed""" style = [] size = format_size(value, None) if size is not None: if key in TABLE_PADDINGS.keys(): style.append((TABLE_PADDINGS[key], start, stop, size)) return style
def body_margin_style(key, value): style_attr = {} size = format_size(value, None) if size is not None: if key == 'margin': for margin in BODY_MARGINS.values(): style_attr[margin] = size elif key in BODY_MARGINS.keys(): style_attr[BODY_MARGINS[key]] = size return style_attr
def frame_padding_style(key, value): style_attr = {} size = format_size(value, None) if size is not None: if key == 'padding': for padding in FRAME_PADDINGS.values(): style_attr[padding] = size elif key in FRAME_PADDINGS.keys(): style_attr[FRAME_PADDINGS[key]] = size return style_attr
def __on_connected (self): # display the server details self.space_status.set_text ("{0}".format(utils.format_size(self.client.free_space))) self.server_status.set_text (self.client.host) self.server_status_image.set_from_stock (Gtk.STOCK_YES, Gtk.IconSize.MENU) self.start_button.set_sensitive (self.client.paused) self.stop_button.set_sensitive (not self.client.paused) # periodically poll the client for any property changes GLib.timeout_add (500, self.client.poll)
def _download_finished_cb(self, app, d): if (d.status == FINISHED or d.status == FINISHED_AND_PLAY) and \ self._show_notifications: entry = self._app.db.get_entry(d.media['entry_id']) entry_title = utils.my_quote(entry['title']) feed_title = self._app.db.get_feed_title(entry['feed_id']) feed_title = utils.my_quote(feed_title) icon = self._icon_manager.get_icon(entry['feed_id']) title = _("Download Complete") d2 = {'feed_title':feed_title, 'entry_title':entry_title, 'size': utils.format_size(d.total_size)} message = _("<b>%(feed_title)s:</b> %(entry_title)s" % d2) self._tray_icon.display_notification(title, message, icon, (NOTIFY_DOWNLOAD, d.media['media_id']))
def _get_table_style(style_css, start, stop): table_style = [] for key, value in style_css.iteritems(): if key.startswith('padding'): table_style.extend(table_padding_style(key, value, start, stop)) elif key.startswith('background'): table_style.extend(table_bg_style(key, value, start, stop)) elif key.endswith('align'): table_style.extend(table_align_style(key, value, start, stop)) elif key == 'font-family': rl_value = get_font_name(value) table_style.extend([('FONT', start, stop, rl_value)]) elif key == 'line-height': rl_value = format_size(value) table_style.extend([('LEADING', start, stop, rl_value)]) return table_style
def __render_speed (self, column, cell, model, iter, data): # get the item we are dealing with item = model[iter][0] if item.links_downloading: speed = 0 downloads = self.client.downloads.value for link in item.links.itervalues(): if downloads.has_key (link.id): speed += downloads[link.id].speed speed = utils.format_size (speed) cell.set_property ("text", "{0}/s".format (speed)) else: cell.set_property ("text", "")
def _calculate_table_border(value): """INPUT border: 1px solid red Calculate the 3 attributes width, style, color""" css_value = value.strip() if css_value.endswith(';'): css_value = css_value[:-1] values = value.split() if len(values) == 3: # 1px solid red width, style, color = values width = format_size(width, 1) style = compute_border_style(style) color = get_color_as_hexa(color) else: # Not well formed return None return (width, style, color)
def __render_name (self, column, cell, model, iter, data): # get the item we are dealing with item = model[iter][0] # render as a package if item.is_package: cell.set_property ("markup", "<b>{0}</b>".format(item.name)) # render as a link elif item.is_link: # get the link size size = utils.format_size (item.size) details = "[{0}]".format (size) if item.status in [Link.Status.OFFLINE, Link.Status.TEMP_OFFLINE]: details = item.error # render link details as markup and make it visible text = "<small>{0} - {1} - {2}</small>".format (item.name, details, item.plugin) cell.set_property ("markup", text) cell.set_property ("visible", True)
def do_ls(self, arg): """ls: list dir content ls [dir_name] """ try: path, = shlex.split(arg) path = os.path.normpath(os.path.join(self._cp, path)) except: path = self._cp files = self._c.list(path) if files: print "total", len(files), path for f in files: if f['isdir'] == 1: print 'd', else: print '-', print '\t', format_size(f.get('size', 0)), print '\t', time.strftime("%Y-%m-%d %H:%M", time.localtime(f['server_mtime'])), print '\t', f['server_filename'] else: print "no such dir"
def _wrap_progress_callback(self, dl_total, dl_now, ul_total, ul_now): now = time.time() if now - self._last_progress < 2.0: return self._last_progress = now if self._resume: #adjust sizes so that the percentages are correct dl_total += self._resume_from dl_now += self._resume_from try: if dl_total < 2: # Ignore spurious 0 byte and byte updates self.progress = 0 else: self.progress = int((dl_now*100.0)/dl_total) except: self.progress = 0 if not self.media.has_key('size'): self.media['size_adjustment']=True elif self.media['size']!=round(dl_total) and not self._resume: if round(dl_total) < 2: # Ignore spurious 0 and 1 byte updates logging.debug("Ignoring small size update") self.media['size_adjustment']=False else: self.media['size']=round(dl_total) self.media['size_adjustment']=True else: self.media['size_adjustment']=False d = { 'progress': str(self.progress), 'size': utils.format_size(self.media['size'])} self.total_size = self.media['size'] if self.total_size == 0: d['dl_now'] = dl_now self.message = _("Downloaded %(dl_now)s...") % d else: self.message = _("Downloaded %(progress)s%% of %(size)s") % d return self._progress_callback()
def step_callback(downloaded): lapse = time.time() - time_start print "%s: %s (%s/s)%s\r" % (ns.file, utils.format_size( downloaded), utils.format_size(downloaded / lapse), ' ' * 10),
def __on_speed_changed (self, prop, speed): self.speed_status.set_text ("{0}/s".format(utils.format_size(speed)))
def step_callback(downloaded): lapse = time.time() - time_start print "%s: %s (%s/s)%s\r" %(ns.file, utils.format_size(downloaded), utils.format_size(downloaded/lapse), ' '*10),
def update_downloads(self): """gets called a lot (once for every progress callback) so be quick""" self._downloads = self._mm.get_download_list() current_list = [item.media['media_id'] for item in self._downloads] viewing_list = [item[D_MEDIA_ID] for item in self._downloads_liststore] oldset = set(viewing_list) newset = set(current_list) removed = list(oldset.difference(newset)) added = list(newset.difference(oldset)) unchanged = list(oldset.intersection(newset)) #slower but works better, because the list is changing all over the place for item in removed: i = -1 for row in self._downloads_liststore: i += 1 if row[0] == item: self._downloads_liststore.remove( self._downloads_liststore.get_iter((i, ))) break tree, selected = self._downloads_listview.get_selection( ).get_selected_rows() selected = [i[0] for i in selected] i = -1 for item in self._downloads_liststore: i += 1 if item[D_MEDIA_ID] in unchanged: index = current_list.index(item[D_MEDIA_ID]) medium = self._downloads[index] iter = self._downloads_liststore[i] iter[D_PROGRESS] = medium.progress iter[D_SIZE] = utils.format_size(medium.total_size) #iter[D_STATUS] refers to the old status if medium.status == PAUSED or medium.status == QUEUED: if iter[D_STATUS] != medium.status: if i in selected: iter[ D_DESCRIPTION_MARKUP] = '<i>' + utils.my_quote( iter[D_DESCRIPTION]) + '</i>' iter[D_SIZE_MARKUP] = '<i>' + iter[D_SIZE] + '</i>' if medium.status == PAUSED: iter[D_STATUS_MARKUP] = '<i>' + _( "Paused") + '</i>' elif medium.status == QUEUED: iter[D_STATUS_MARKUP] = '<i>' + _( "Queued") + '</i>' else: iter[ D_DESCRIPTION_MARKUP] = '<span color="#777"><i>' + utils.my_quote( iter[D_DESCRIPTION]) + '</i></span>' iter[ D_SIZE_MARKUP] = '<span color="#777"><i>' + iter[ D_SIZE] + '</i></span>' if medium.status == PAUSED: iter[ D_STATUS_MARKUP] = '<span color="#777"><i>' + _( "Paused") + '</i></span>' elif medium.status == QUEUED: iter[ D_STATUS_MARKUP] = '<span color="#777"><i>' + _( "Queued") + '</i></span>' iter[D_STATUS] = medium.status else: #if iter[D_STATUS] == PAUSED or i in selected: iter[D_DESCRIPTION_MARKUP] = utils.my_quote( iter[D_DESCRIPTION]) iter[D_SIZE_MARKUP] = iter[D_SIZE] iter[D_STATUS] = medium.status iter[D_STATUS_MARKUP] = "" #check resume button sensitivity resume_sens = False i = -1 for item in self._downloads_liststore: i += 1 if item[D_STATUS] == PAUSED or item[D_STATUS] == QUEUED: if i in selected: resume_sens = True break self._resume_button.set_sensitive(resume_sens) for media_id in added: item = self._downloads[current_list.index(media_id)] try: entry = self._app.db.get_entry(item.media['entry_id']) description = self._app.db.get_feed_title( entry['feed_id']) + " " + utils.get_hyphen( ) + " " + entry['title'] size = utils.format_size(item.total_size) except: logging.warning( "trouble getting entry updating downloads: %s" % str(item)) continue if item.status == PAUSED: description_markup = '<span color="#777"><i>' + utils.my_quote( description) + '</i></span>' size_markup = '<span color="#777"><i>' + size + '</i></span>' status_markup = '<i>' + _("Paused") + '</i>' elif item.status == QUEUED: description_markup = '<span color="#777"><i>' + utils.my_quote( description) + '</i></span>' size_markup = '<span color="#777"><i>' + size + '</i></span>' status_markup = '<i>' + _("Queued") + '</i>' else: description_markup = utils.my_quote(description) size_markup = size status_markup = "" pixbuf = self._icon_manager.get_icon_pixbuf( entry['feed_id'], MAX_WIDTH, MAX_HEIGHT, MIN_SIZE, MIN_SIZE) self._downloads_liststore.append([ media_id, description, description_markup, item.progress, size, size_markup, pixbuf, item.status, status_markup ]) #make sure both lists are sorted the same way id_list = [row[D_MEDIA_ID] for row in self._downloads_liststore] self._downloads.sort(lambda x, y: id_list.index(x.media['media_id']) - id_list.index(y.media['media_id']))
def htmlify_media(self, medium): ret = [] ret.append('<div class="media">') if medium['download_status']==D_NOT_DOWNLOADED: ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''') if medium['file'] is None: filename = medium['url'][medium['url'].rfind("/")+1:] else: filename = medium['file'][medium['file'].rfind("/")+1:] ret.append(self._html_command('download://',medium['media_id']) + "</td><td>") ret.append(self._html_command('downloadqueue://',medium['media_id']) + "</td><td>") ret.append('</tr><tr><td colspan="3">(%s: %s)</td></tr></table>' % (filename, utils.format_size(medium['size']))) elif medium['download_status'] == D_DOWNLOADING: if self._basic_progress: if self._ajax_url is None: ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>') else: ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>') ret.append('<i>'+_('Downloading %s...') % utils.format_size(medium['size'])+'</i> '+self._html_command('pause://',medium['media_id'])+' '+self._html_command('stop://',medium['media_id'])) elif medium.has_key('progress_message'): #downloading and we have a custom message if self._ajax_url is None: ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>') else: ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>') ret.append('<p><i>'+medium['progress_message']+'</i></p>') ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''') ret.append(self._html_command('pause://',medium['media_id']) + "</td><td>") ret.append(self._html_command('stop://',medium['media_id'])+"</td></tr></table>") elif self._mm.has_downloader(medium['media_id']): #we have a downloader object downloader = self._mm.get_downloader(medium['media_id']) if downloader.status == Downloader.DOWNLOADING: d = {'progress':downloader.progress, 'size':utils.format_size(medium['size'])} #ret.append('<p><i>'+_("Downloaded %(progress)d%% of %(size)s") % d +'</i> '+ ret.append('''<table border="0" cellpadding="0" cellspacing="12pt">''') ret.append('''<tr><td rowspan="2">''') if self._ajax_url is None: ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>') else: ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>') ret.append("</td><td>") ret.append(self._html_progress_bar(d['progress'], d['size']) + "</td><td>") ret.append(self._html_command('pause://',medium['media_id']) + "</td><td>") ret.append(self._html_command('stop://',medium['media_id'])+"</td></tr></table>") elif downloader.status == Downloader.QUEUED: ret.append('<p><i>'+_("Download queued") +'</i></p>') ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''') ret.append(self._html_command('pause://',medium['media_id']) + "</td><td>") ret.append(self._html_command('stop://',medium['media_id'])+"</td></tr></table>") elif medium.has_key('progress'): #no custom message, but we have a progress value d = {'progress':medium['progress'], 'size':utils.format_size(medium['size'])} #ret.append('<p><i>'+_("Downloaded %(progress)d%% of %(size)s") % d +'</i> '+ ret.append('''<table border="0" cellpadding="0" cellspacing="12pt">''') ret.append('''<tr><td rowspan="2">''') if self._ajax_url is None: ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>') else: ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>') ret.append("</td><td>") ret.append(self._html_progress_bar(d['progress'], d['size']) + "</td><td>") ret.append(self._html_command('pause://',medium['media_id']) + "</td><td>") ret.append(self._html_command('stop://',medium['media_id'])+"</td></tr></table>") else: # we have nothing to go on ret.append('<p><i>'+_('Downloading %s...') % utils.format_size(medium['size'])+'</i></p>') ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''') ret.append(self._html_command('pause://',medium['media_id']) + "</td><td>") ret.append(self._html_command('stop://',medium['media_id'])+"</td></tr></table>") elif medium['download_status'] == D_DOWNLOADED: if self._mm.has_downloader(medium['media_id']): downloader = self._mm.get_downloader(medium['media_id']) ret.append('<p>'+ str(downloader.message)+'</p>') filename = medium['file'][medium['file'].rfind("/")+1:] if utils.is_known_media(medium['file']): #we have a handler if os.path.isdir(medium['file']) and medium['file'][-1]!='/': medium['file']=medium['file']+'/' ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''') ret.append(self._html_command('play://',medium['media_id']) + "</td><td>") ret.append(self._html_command('redownload',medium['media_id']) + "</td><td>") ret.append(self._html_command('delete://',medium['media_id'])+"</td></tr>") ret.append('<tr><td colspan="3">(<a href="reveal://%s">%s</a>: %s)</td></tr></table>' % (medium['file'], filename, utils.format_size(medium['size']))) elif os.path.isdir(medium['file']): #it's a folder ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''') ret.append(self._html_command('file://',medium['file']) + "</td><td>") ret.append(self._html_command('redownload',medium['media_id']) + "</td><td>") ret.append(self._html_command('delete://',medium['media_id'])+"</td></tr></table>") else: #we have no idea what this is ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''') ret.append(self._html_command('file://',medium['file']) + "</td><td>") ret.append(self._html_command('redownload',medium['media_id']) + "</td><td>") ret.append(self._html_command('delete://',medium['media_id'])+"</td></tr>") ret.append('<tr><td colspan="3">(<a href="reveal://%s">%s</a>: %s)</td></tr></table>' % (medium['file'], filename, utils.format_size(medium['size']))) elif medium['download_status'] == D_RESUMABLE: ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''') ret.append(self._html_command('resume://',medium['media_id']) + "</td><td>") ret.append(self._html_command('redownload',medium['media_id']) + "</td><td>") ret.append(self._html_command('delete://',medium['media_id'])+"</td></tr><tr><td>") ret.append('(%s)</td></tr></table>' % (utils.format_size(medium['size']),)) elif medium['download_status'] == D_ERROR: if len(medium['errormsg']) > 0: error_msg = medium['errormsg'] else: error_msg = _("There was an error downloading the file.") ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''') ret.append(medium['url'][medium['url'].rfind('/')+1:]+': '+str(error_msg) + "</td><td>") ret.append(self._html_command('retry',medium['media_id']) + "</td><td>") ret.append(self._html_command('tryresume://',medium['media_id']) + "</td><td>") ret.append(self._html_command('cancel://',medium['media_id'])+"</td></tr><tr><td>") ret.append('(%s)</td></tr></table>' % (utils.format_size(medium['size']),)) ret.append('</div>') return ret
def __render_size (self, column, cell, model, iter, data): # get the item we are dealing with item = model[iter][0] total = utils.format_size (item.size_total) cell.set_property ("text", total)
def __str__(self): size_formatted = utils.format_size(self.get_size()) filepath = utils.colored(self.original_filepath, 'green') size_formatted = utils.colored(f'{size_formatted}', 'blue') return f'{filepath} {size_formatted}'
def build_paragraph_style(context, element, style_css): style_attr = {} # The default style is Normal parent_style_name = 'Normal' bulletText = None style_attr['autoLeading'] = 'max' style_attr['borderPadding'] = 0.1 * cm # TODO Check if it's correct style_attr['leading'] = 0.3 * cm #FIXME must be moved in default css style_attr['spaceBefore'] = 0.3 * cm style_attr['spaceAfter'] = 0.3 * cm # Leading leading_forced = False font_size = None for key, value in style_css.iteritems(): if key == 'color': style_attr['textColor'] = get_color_as_hexa(value) elif key in ('background-color'): style_attr['backColor'] = get_color_as_hexa(value) elif key == 'text-indent': style_attr['firstLineIndent'] = format_size(value) elif key == 'text-align': if value in P_ALIGNMENTS.keys(): style_attr['alignment'] = P_ALIGNMENTS.get(value) elif key == 'text-decoration': if value == 'underline': context.style_tag_stack.append(('u')) elif element[0] not in ('td', 'th') and key.startswith('border'): style_attr.update(p_border_style(key, value)) elif key.startswith('font'): font_style = p_font_style(key, value, context) if 'fontSize' in font_style: font_size = font_style['fontSize'] style_attr.update(font_style) elif key.startswith('padding'): style_attr.update(p_padding_style(key, value)) elif key.startswith('line-height'): leading_forced = True style_attr['leading'] = format_size(value) elif key == 'width': style_attr['width'] = value elif key == 'float': style_attr['float'] = value elif key == 'text-transform': if value in ('uppercase', 'lowercase'): style_attr['textTransform'] = value # Overload the attributes values for key, attr_value in element[1].iteritems(): key = key[1] # (None, key) if key == 'class': # Set the parent style for inheritance parent_style_name = attr_value elif key == 'bulletText': bulletText = attr_value elif key == 'style': # TODO parse inline style attribute continue if element[0] in HEADING + ('toctitle', ): parent_style_name = element[0] style_name = parent_style_name parent_style = context.get_style(parent_style_name) # Calulate the leading if leading_forced is False and font_size: # Reportlab UserGuide # a good rule of thumb is to make this 20% larger than the point size # But we choose to use a ratio of 33% style_attr['leading'] = font_size * 1.33 return (ParagraphStyle(style_name, parent=parent_style, **style_attr), bulletText)
def update_downloads(self): """gets called a lot (once for every progress callback) so be quick""" self._downloads = self._mm.get_download_list() current_list = [item.media['media_id'] for item in self._downloads] viewing_list = [item[D_MEDIA_ID] for item in self._downloads_liststore] oldset = set(viewing_list) newset = set(current_list) removed = list(oldset.difference(newset)) added = list(newset.difference(oldset)) unchanged = list(oldset.intersection(newset)) #slower but works better, because the list is changing all over the place for item in removed: i=-1 for row in self._downloads_liststore: i+=1 if row[0] == item: self._downloads_liststore.remove(self._downloads_liststore.get_iter((i,))) break tree,selected = self._downloads_listview.get_selection().get_selected_rows() selected = [i[0] for i in selected] i=-1 for item in self._downloads_liststore: i+=1 if item[D_MEDIA_ID] in unchanged: index = current_list.index(item[D_MEDIA_ID]) medium = self._downloads[index] iter = self._downloads_liststore[i] iter[D_PROGRESS] = medium.progress iter[D_SIZE] = utils.format_size(medium.total_size) #iter[D_STATUS] refers to the old status if medium.status == PAUSED or medium.status == QUEUED: if iter[D_STATUS] != medium.status: if i in selected: iter[D_DESCRIPTION_MARKUP] = '<i>'+utils.my_quote(iter[D_DESCRIPTION])+'</i>' iter[D_SIZE_MARKUP]= '<i>'+iter[D_SIZE]+'</i>' if medium.status == PAUSED: iter[D_STATUS_MARKUP] = '<i>'+_("Paused")+'</i>' elif medium.status == QUEUED: iter[D_STATUS_MARKUP] = '<i>'+_("Queued")+'</i>' else: iter[D_DESCRIPTION_MARKUP] = '<span color="#777"><i>'+utils.my_quote(iter[D_DESCRIPTION])+'</i></span>' iter[D_SIZE_MARKUP] = '<span color="#777"><i>'+iter[D_SIZE]+'</i></span>' if medium.status == PAUSED: iter[D_STATUS_MARKUP] = '<span color="#777"><i>'+_("Paused")+'</i></span>' elif medium.status == QUEUED: iter[D_STATUS_MARKUP] = '<span color="#777"><i>'+_("Queued")+'</i></span>' iter[D_STATUS] = medium.status else: #if iter[D_STATUS] == PAUSED or i in selected: iter[D_DESCRIPTION_MARKUP] = utils.my_quote(iter[D_DESCRIPTION]) iter[D_SIZE_MARKUP]= iter[D_SIZE] iter[D_STATUS] = medium.status iter[D_STATUS_MARKUP] = "" #check resume button sensitivity resume_sens = False i=-1 for item in self._downloads_liststore: i+=1 if item[D_STATUS] == PAUSED or item[D_STATUS] == QUEUED: if i in selected: resume_sens = True break self._resume_button.set_sensitive(resume_sens) for media_id in added: item = self._downloads[current_list.index(media_id)] try: entry = self._app.db.get_entry(item.media['entry_id']) description = self._app.db.get_feed_title(entry['feed_id']) + " " + utils.get_hyphen() + " " + entry['title'] size = utils.format_size(item.total_size) except: logging.warning("trouble getting entry updating downloads: %s" % str(item)) continue if item.status == PAUSED: description_markup = '<span color="#777"><i>'+utils.my_quote(description)+'</i></span>' size_markup = '<span color="#777"><i>'+size+'</i></span>' status_markup = '<i>'+_("Paused")+'</i>' elif item.status == QUEUED: description_markup = '<span color="#777"><i>'+utils.my_quote(description)+'</i></span>' size_markup = '<span color="#777"><i>'+size+'</i></span>' status_markup = '<i>'+_("Queued")+'</i>' else: description_markup = utils.my_quote(description) size_markup = size status_markup = "" pixbuf = self._icon_manager.get_icon_pixbuf(entry['feed_id'], MAX_WIDTH, MAX_HEIGHT, MIN_SIZE, MIN_SIZE) self._downloads_liststore.append([media_id, description, description_markup, item.progress, size, size_markup, pixbuf, item.status, status_markup]) #make sure both lists are sorted the same way id_list = [row[D_MEDIA_ID] for row in self._downloads_liststore] self._downloads.sort(lambda x,y: id_list.index(x.media['media_id']) - id_list.index(y.media['media_id']))
def htmlify_media(self, medium): ret = [] ret.append('<div class="media">') if medium['download_status'] == D_NOT_DOWNLOADED: ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''' ) if medium['file'] is None: filename = medium['url'][medium['url'].rfind("/") + 1:] else: filename = medium['file'][medium['file'].rfind("/") + 1:] ret.append( self._html_command('download://', medium['media_id']) + "</td><td>") ret.append( self._html_command('downloadqueue://', medium['media_id']) + "</td><td>") ret.append('</tr><tr><td colspan="3">(%s: %s)</td></tr></table>' % (filename, utils.format_size(medium['size']))) elif medium['download_status'] == D_DOWNLOADING: if self._basic_progress: if self._ajax_url is None: ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>') else: ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>') ret.append('<i>' + _('Downloading %s...') % utils.format_size(medium['size']) + '</i> ' + self._html_command('pause://', medium['media_id']) + ' ' + self._html_command('stop://', medium['media_id'])) elif medium.has_key('progress_message' ): #downloading and we have a custom message if self._ajax_url is None: ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>') else: ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>') ret.append('<p><i>' + medium['progress_message'] + '</i></p>') ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''' ) ret.append( self._html_command('pause://', medium['media_id']) + "</td><td>") ret.append( self._html_command('stop://', medium['media_id']) + "</td></tr></table>") elif self._mm.has_downloader( medium['media_id']): #we have a downloader object downloader = self._mm.get_downloader(medium['media_id']) if downloader.status == Downloader.DOWNLOADING: d = { 'progress': downloader.progress, 'size': utils.format_size(medium['size']) } #ret.append('<p><i>'+_("Downloaded %(progress)d%% of %(size)s") % d +'</i> '+ ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt">''' ) ret.append('''<tr><td rowspan="2">''') if self._ajax_url is None: ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>') else: ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>') ret.append("</td><td>") ret.append( self._html_progress_bar(d['progress'], d['size']) + "</td><td>") ret.append( self._html_command('pause://', medium['media_id']) + "</td><td>") ret.append( self._html_command('stop://', medium['media_id']) + "</td></tr></table>") elif downloader.status == Downloader.QUEUED: ret.append('<p><i>' + _("Download queued") + '</i></p>') ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''' ) ret.append( self._html_command('pause://', medium['media_id']) + "</td><td>") ret.append( self._html_command('stop://', medium['media_id']) + "</td></tr></table>") elif medium.has_key( 'progress' ): #no custom message, but we have a progress value d = { 'progress': medium['progress'], 'size': utils.format_size(medium['size']) } #ret.append('<p><i>'+_("Downloaded %(progress)d%% of %(size)s") % d +'</i> '+ ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt">''' ) ret.append('''<tr><td rowspan="2">''') if self._ajax_url is None: ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>') else: ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>') ret.append("</td><td>") ret.append( self._html_progress_bar(d['progress'], d['size']) + "</td><td>") ret.append( self._html_command('pause://', medium['media_id']) + "</td><td>") ret.append( self._html_command('stop://', medium['media_id']) + "</td></tr></table>") else: # we have nothing to go on ret.append('<p><i>' + _('Downloading %s...') % utils.format_size(medium['size']) + '</i></p>') ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''' ) ret.append( self._html_command('pause://', medium['media_id']) + "</td><td>") ret.append( self._html_command('stop://', medium['media_id']) + "</td></tr></table>") elif medium['download_status'] == D_DOWNLOADED: if self._mm.has_downloader(medium['media_id']): downloader = self._mm.get_downloader(medium['media_id']) ret.append('<p>' + str(downloader.message) + '</p>') filename = medium['file'][medium['file'].rfind("/") + 1:] if utils.is_known_media(medium['file']): #we have a handler if os.path.isdir(medium['file']) and medium['file'][-1] != '/': medium['file'] = medium['file'] + '/' ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''' ) ret.append( self._html_command('play://', medium['media_id']) + "</td><td>") ret.append( self._html_command('redownload', medium['media_id']) + "</td><td>") ret.append( self._html_command('delete://', medium['media_id']) + "</td></tr>") ret.append( '<tr><td colspan="3">(<a href="reveal://%s">%s</a>: %s)</td></tr></table>' % (medium['file'], filename, utils.format_size(medium['size']))) elif os.path.isdir(medium['file']): #it's a folder ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''' ) ret.append( self._html_command('file://', medium['file']) + "</td><td>") ret.append( self._html_command('redownload', medium['media_id']) + "</td><td>") ret.append( self._html_command('delete://', medium['media_id']) + "</td></tr></table>") else: #we have no idea what this is ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''' ) ret.append( self._html_command('file://', medium['file']) + "</td><td>") ret.append( self._html_command('redownload', medium['media_id']) + "</td><td>") ret.append( self._html_command('delete://', medium['media_id']) + "</td></tr>") ret.append( '<tr><td colspan="3">(<a href="reveal://%s">%s</a>: %s)</td></tr></table>' % (medium['file'], filename, utils.format_size(medium['size']))) elif medium['download_status'] == D_RESUMABLE: ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''' ) ret.append( self._html_command('resume://', medium['media_id']) + "</td><td>") ret.append( self._html_command('redownload', medium['media_id']) + "</td><td>") ret.append( self._html_command('delete://', medium['media_id']) + "</td></tr><tr><td>") ret.append('(%s)</td></tr></table>' % (utils.format_size(medium['size']), )) elif medium['download_status'] == D_ERROR: if len(medium['errormsg']) > 0: error_msg = medium['errormsg'] else: error_msg = _("There was an error downloading the file.") ret.append( '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''' ) ret.append(medium['url'][medium['url'].rfind('/') + 1:] + ': ' + str(error_msg) + "</td><td>") ret.append( self._html_command('retry', medium['media_id']) + "</td><td>") ret.append( self._html_command('tryresume://', medium['media_id']) + "</td><td>") ret.append( self._html_command('cancel://', medium['media_id']) + "</td></tr><tr><td>") ret.append('(%s)</td></tr></table>' % (utils.format_size(medium['size']), )) ret.append('</div>') return ret
def __str__(self): return '{0} ({1}) {2}/{3}'.format(self.name, self.health, utils.format_size(self.used_size), utils.format_size(self.total_size))