code
stringlengths
1
1.72M
language
stringclasses
1 value
#-*- coding: utf-8 -*- ''' Created on Sep 23, 2010 @author: ivan ''' import gtk from foobnix.util import LOG, const from foobnix.helpers.my_widgets import tab_close_button, tab_close_label from foobnix.online.online_model import OnlineListModel from foobnix.util.fc import FC from foobnix.regui.treeview.playlist import PlaylistControl from foobnix.regui.model.signal import FControl from foobnix.regui.state import LoadSave from foobnix.regui.model import FModel from foobnix.regui.treeview.scanner import DirectoryScanner from foobnix.regui.treeview.musictree import MusicTreeControl import thread class NoteTabControl(gtk.Notebook, FControl, LoadSave): def __init__(self, controls): gtk.Notebook.__init__(self) FControl.__init__(self, controls) self.default_angel = 0 self.tab_labes = [] self.tab_vboxes = [] self.tab_hboxes = [] self.last_notebook_page = "" self.last_notebook_beans = [] self.active_tree = None self.append_tab("Foobnix", []) def append_tab(self, name, beans=None): self.last_notebook_page = name LOG.info("append new tab") if name and len(name) > FC().len_of_tab: name = name[:FC().len_of_tab] tab_content = self.create_notebook_tab(beans) def label(): """label""" label = gtk.Label(name + " ") label.show() label.set_angle(self.default_angel) self.tab_labes.append(label) return label def button(): print "ELEMENT", FC().tab_close_element if FC().tab_close_element == "button": return tab_close_button(func=self.on_delete_tab, arg=tab_content) else: return tab_close_label(func=self.on_delete_tab, arg=tab_content, angel=self.default_angel) """container Vertical Tab""" vbox = gtk.VBox(False, 0) if self.default_angel == 90: vbox.show() vbox.pack_start(button(), False, False, 0) vbox.pack_start(label(), False, False, 0) self.tab_vboxes.append(vbox) """container Horizontal Tab""" hbox = gtk.HBox(False, 0) if self.default_angel == 0: hbox.show() hbox.pack_start(label(), False, False, 0) hbox.pack_start(button(), False, False, 0) self.tab_hboxes.append(hbox) """container BOTH""" both = gtk.HBox(False, 0) both.show() both.pack_start(vbox, False, False, 0) both.pack_start(hbox, False, False, 0) """append tab""" self.prepend_page(tab_content, both) self.set_current_page(0) if self.get_n_pages() > FC().count_of_tabs: self.remove_page(self.get_n_pages() - 1) """autostart play""" if beans: self.controls.next() def next(self): return self.active_tree.next(rnd=self.isRandom, lopping=self.lopping) def prev(self): return self.active_tree.prev(rnd=self.isRandom, lopping=self.lopping) def create_notebook_tab(self, beans): treeview = PlaylistControl(self.controls) self.switch_tree(treeview) #treeview.populate_from_scanner(beans) if beans: treeview.populate(beans) #for bean in beans: #bean.level = None # treeview.append(bean) window = gtk.ScrolledWindow() window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) #window.add_with_viewport(treeview) window.add(treeview) window.show_all() return window def append(self, beans): for bean in beans: self.active_tree.append(bean) def on_delete_tab(self, widget, event, child): if event.type == gtk.gdk.BUTTON_PRESS: #@UndefinedVariable n = self.page_num(child) self.delete_tab(n) def delete_tab(self, page=None): if not page: LOG.info("Remove current page") page = self.get_current_page() self.remove_page(page) def set_random(self, flag): self.isRandom = flag def set_lopping_all(self): self.lopping = const.LOPPING_LOOP_ALL print self.lopping def set_lopping_single(self): self.lopping = const.LOPPING_SINGLE print self.lopping def set_lopping_disable(self): self.lopping = const.LOPPING_DONT_LOOP print self.lopping def on_load(self): self.isRandom = FC().is_order_random self.lopping = FC().lopping def on_save(self): FC().is_order_random = self.isRandom FC().lopping = self.lopping def switch_tree(self, tree): self.active_tree = tree def set_playlist_tree(self): self.active_tree.set_playlist_tree() def set_playlist_plain(self): self.active_tree.set_playlist_plain()
Python
import gtk from foobnix.helpers.toggled import OneActiveToggledButton from foobnix.regui.model.signal import FControl from foobnix.util import LOG class SearchControls(FControl, gtk.Frame): def __init__(self, controls): gtk.Frame.__init__(self) FControl.__init__(self, controls) self.controls = controls label = gtk.Label() label.set_markup("<b>Search music online:</b>") self.set_label_widget(label) self.set_border_width(0) """default search function""" self.search_function = self.controls.search_top_tracks self.buttons = [] vbox = gtk.VBox(False, 0) vbox.pack_start(self.search_line(), False, False, 0) vbox.pack_start(self.search_buttons(), False, False, 0) vbox.pack_start(controls.search_progress, False, False, 0) self.add(vbox) self.show_all() """search on enter""" for button in self.buttons: button.connect("key-press-event", self.on_search_key_press) """only one button active""" OneActiveToggledButton(self.buttons) def set_search_function(self, w, search_function): LOG.info("Set search fucntion", search_function) self.search_function = search_function def on_search(self, *w): if self.get_query(): self.search_function(self.get_query()) def get_query(self): return self.entry.get_text() def search_line(self): hbox = gtk.HBox(False, 0) self.entry = gtk.Entry() self.entry.connect("key-press-event", self.on_search_key_press) self.entry.set_text("Madonna") button = gtk.Button("Search") button.connect("clicked", self.on_search) hbox = gtk.HBox(False, 0) hbox.pack_start(self.entry, True, True, 0) hbox.pack_start(button, False, False, 0) hbox.show_all() return hbox def on_search_key_press(self, w, e): if gtk.gdk.keyval_name(e.keyval) == 'Return': self.on_search(); def search_buttons(self): h_line_box = gtk.HBox(False, 0) """Top searches""" top_frame = gtk.Frame() label = gtk.Label() label.set_markup("<b>Top by artist</b>") top_frame.set_label_widget(label) top_frame.set_shadow_type(gtk.SHADOW_NONE) hbox = gtk.HBox(False, 0) songs = gtk.ToggleButton("Songs") songs.set_active(True) songs.connect("toggled", self.set_search_function, self.controls.search_top_tracks) albums = gtk.ToggleButton("Albums") albums.connect("toggled", self.set_search_function, self.controls.search_top_albums) similars = gtk.ToggleButton("Similar") similars.connect("toggled", self.set_search_function, self.controls.search_top_similar) hbox.pack_start(songs, True, True, 0) hbox.pack_start(albums, True, True, 0) hbox.pack_start(similars, True, True, 0) top_frame.add(hbox) """Other searches""" other_frame = gtk.Frame() label = gtk.Label() label.set_markup("<b>Other</b>") other_frame.set_label_widget(label) other_frame.set_shadow_type(gtk.SHADOW_NONE) hbox = gtk.HBox(False, 0) tags = gtk.ToggleButton("Tag") tags.connect("toggled", self.set_search_function, self.controls.search_top_tags) all = gtk.ToggleButton("All") all.connect("toggled", self.set_search_function , self.controls.search_all_tracks) hbox.pack_start(tags, True, True, 0) hbox.pack_start(all, True, True, 0) other_frame.add(hbox) h_line_box.pack_start(top_frame, True, True, 0) h_line_box.pack_start(other_frame, True, True, 0) h_line_box.show_all() self.buttons = [songs, albums, similars, tags, all] return h_line_box
Python
''' Created on Sep 29, 2010 @author: ivan ''' from foobnix.regui.state import LoadSave from foobnix.regui.treeview import TreeViewControl from foobnix.util.mouse_utils import is_double_left_click, is_rigth_click import gtk from foobnix.helpers.menu import Popup from foobnix.helpers.dialog_entry import one_line_dialog from foobnix.regui.model import FModel class VirtualTreeControl(TreeViewControl, LoadSave): def __init__(self, controls): TreeViewControl.__init__(self, controls) """column config""" column = gtk.TreeViewColumn("Virtual Lybrary", gtk.CellRendererText(), text=self.text[0], font=self.font[0]) column.set_resizable(True) self.append_column(column) def on_button_press(self, w, e): if is_double_left_click(e): bean = self.get_selected_bean() self.controls.append_to_notebook(bean.text, [bean]) print "double left" if is_rigth_click(e): menu = Popup() menu.add_item(_("Add playlist"), gtk.STOCK_ADD, self.create_playlist, None) menu.add_item(_("Rename playlist"), gtk.STOCK_EDIT, self.rename_playlist, None) menu.add_item(_("Delete playlist"), gtk.STOCK_DELETE, self.delete_playlist, None) menu.show(e) def create_playlist(self): text = one_line_dialog("Create new playlist") bean = FModel(text).add_font("bold") self.append(bean) def delete_playlist(self): self.delete_selected() def rename_playlist(self): bean = self.get_selected_bean() text = one_line_dialog("Rename playlist", bean.text) if not text: return selection = self.get_selection() fm, paths = selection.get_selected_rows() path = paths[0] path = self.filter_model.convert_path_to_child_path(path) iter = self.model.get_iter(path) self.model.set_value(iter, self.text[0], text) def on_load(self): self.scroll.hide() pass def on_save(self): pass
Python
#-*- coding: utf-8 -*- ''' Created on 25 сент. 2010 @author: ivan ''' import os from foobnix.util.fc import FC from foobnix.util.file_utils import file_extenstion from foobnix.util import LOG from foobnix.regui.model import FModel """Music directory scanner""" class DirectoryScanner(): def __init__(self, path): self.path = path self.results = [] def get_music_results(self): self._scanner(self.path, None) return self.results def get_music_file_results(self): self._scanner(self.path, None) all = [] for file in self.results: if file.is_file: all.append(file) return all def _scanner(self, path, level): if not os.path.exists(path): return None dir = os.path.abspath(path) list = os.listdir(dir) list = self.sort_by_name(path, list) for file in list: full_path = os.path.join(path, file) if os.path.isfile(full_path) and file_extenstion(file) not in FC().support_formats: continue; if self.is_dir_with_music(full_path): self.results.append(FModel(file, full_path).add_level(level).add_is_file(False)) self._scanner(full_path, full_path) elif os.path.isfile(full_path): self.results.append(FModel(file, full_path).add_level(level).add_is_file(True)) def sort_by_name(self, path, list): files = [] directories = [] for file in list: full_path = os.path.join(path, file) if os.path.isdir(full_path): directories.append(file) else: files.append(file) return sorted(directories) + sorted(files) def is_dir_with_music(self, path): if os.path.isdir(path): list = None try: list = os.listdir(path) except OSError, e: LOG.info("Can'r get list of dir", e) if not list: return False for file in list: full_path = os.path.join(path, file) if os.path.isdir(full_path): if self.is_dir_with_music(full_path): return True else: if file_extenstion(file) in FC().support_formats: return True return False
Python
#-*- coding: utf-8 -*- import gtk import gobject from foobnix.regui.treeview.scanner import DirectoryScanner from foobnix.regui.model import FTreeModel, FModel from foobnix.util import LOG import uuid from foobnix.regui.model.signal import FControl import copy class TreeViewControl(gtk.TreeView, FTreeModel, FControl): def __init__(self, controls): gtk.TreeView.__init__(self) FTreeModel.__init__(self) FControl.__init__(self, controls) self.get_selection().set_mode(gtk.SELECTION_MULTIPLE) self.set_enable_tree_lines(True) """model config""" print "types", FTreeModel().types() self.model = gtk.TreeStore(*FTreeModel().types()) """filter config""" self.filter_model = self.model.filter_new() print "visible", self.visible[0] self.filter_model.set_visible_column(self.visible[0]) self.set_model(self.filter_model) """connectors""" self.connect("button-press-event", self.on_button_press) self.connect("key-release-event", self.on_key_release) self.connect("drag-drop", self.on_drag_drop) self.enable_model_drag_source(gtk.gdk.BUTTON1_MASK, [("example1", 0, 0)], gtk.gdk.ACTION_COPY) self.enable_model_drag_dest([("example1", 0, 0)], gtk.gdk.ACTION_COPY) self.count_index = 0 self.set_reorderable(False) self.set_headers_visible(False) self.prev_iter_play_icon = None self.init_data_tree() def init_data_tree(self): self.get_model().get_model().clear() """ Madonna """ list = [] list.append(FModel("Madonna").add_is_file(False)) list.append(FModel("Madonna - Song1").add_parent("Madonna").add_is_file(True)) list.append(FModel("Madonna - Song2").add_parent("Madonna").add_is_file(True)) for line in list: self.append(line) bean = FModel('TEXT').add_font("bold") parent = self.append(bean) self.append(FModel('TEXT1').add_font("normal").add_level(parent)) self.append(FModel('TEXT2').add_font("normal").add_level(parent)) self.append(FModel('TEXT2').add_font("normal").add_level(parent)) self.append(FModel('TEXT').add_font("bold")) self.append(FModel('TEXT').add_font("bold")) def iter_copy(self, from_model, from_iter, to_model, to_iter, pos): #row = [from_model.get_value(from_iter, 0), from_model.get_value(from_iter, 1), True] row = self.get_row_from_model_iter(from_model, from_iter) if (pos == gtk.TREE_VIEW_DROP_INTO_OR_BEFORE) or (pos == gtk.TREE_VIEW_DROP_INTO_OR_AFTER): new_iter = to_model.prepend(to_iter, row) elif pos == gtk.TREE_VIEW_DROP_BEFORE: new_iter = to_model.insert_before(None, to_iter, row) elif pos == gtk.TREE_VIEW_DROP_AFTER: new_iter = to_model.insert_after(None, to_iter, row) else: new_iter = to_model.append(None, row) if from_model.iter_has_child(from_iter): for i in range(0, from_model.iter_n_children(from_iter)): next_iter_to_copy = from_model.iter_nth_child(from_iter, i) self.iter_copy(from_model, next_iter_to_copy, to_model, new_iter, gtk.TREE_VIEW_DROP_INTO_OR_BEFORE) def on_drag_drop(self, to_tree, drag_context, x, y, selection): to_filter_model = to_tree.get_model() to_model = to_filter_model.get_model() if to_tree.get_dest_row_at_pos(x, y): to_path, to_pos = to_tree.get_dest_row_at_pos(x, y) to_path = to_filter_model.convert_path_to_child_path(to_path) to_iter = to_model.get_iter(to_path) else: to_path = None to_pos = None to_iter = None from_tree = drag_context.get_source_widget() from_filter_model, from_paths = from_tree.get_selection().get_selected_rows() from_model = from_filter_model.get_model() from_path = from_filter_model.convert_path_to_child_path(from_paths[0]) from_iter = from_model.get_iter(from_path) self.iter_copy(from_model, from_iter, to_model, to_iter, to_pos) if to_tree == from_tree: """move element in the save tree""" drag_context.finish(True, True) if to_path: to_tree.expand_to_path(to_path) def set_scrolled(self, policy_horizontal, policy_vertical): self.scroll = gtk.ScrolledWindow() self.scroll.set_policy(policy_horizontal, policy_vertical) self.scroll.add_with_viewport(self) self.scroll.show_all() return self def populate(self, beans): self.clear() for bean in beans: bean.level = None self.append(bean) def append(self, bean): bean.visible = True if bean.is_file == True: bean.font = "normal" else: bean.font = "bold" #bean.text = bean.text + " !" + str(bean.start_sec) + "=" + str(bean.duration_sec) bean.index = self.count_index self.count_index += 1 row = self.get_row_from_bean(bean) if isinstance(bean.level, gtk.TreeIter): value = self.model.append(bean.level, row) else: value = self.model.append(None, row) return value def get_bean_from_row(self, row): bean = FModel() id_dict = FTreeModel().cut().__dict__ for key in id_dict.keys(): num = id_dict[key] setattr(bean, key, row[num]) return bean def get_row_from_bean(self, bean): attributes = [] m_dict = FTreeModel().cut().__dict__ new_dict = dict (zip(m_dict.values(), m_dict.keys())) for key in new_dict.values(): value = getattr(bean, key) attributes.append(value) return attributes def get_row_from_model_iter(self, model, iter): attributes = [] size = len(FTreeModel().__dict__) for i in xrange(size): value = model.get_value(iter, i) attributes.append(value) return attributes def append_from_scanner(self, all): """copy beans""" beans = copy.deepcopy(all) hash = {None:None} for bean in beans: if bean is None: continue bean.visible = True if hash.has_key(bean.level): level = hash[bean.level] else: level = None if bean.is_file: child_level = self.append(bean.add_font("normal").add_level(level)) else: child_level = self.append(bean.add_font("bold").add_level(level)) hash[bean.path] = child_level def populate_from_scanner(self, beans): self.clear() self.append_from_scanner(beans) def clear(self): self.count_index = 0 self.model.clear() def on_button_press(self, w, e): pass def on_key_release(self, w, e): pass def delete_selected(self): selection = self.get_selection() fm, paths = selection.get_selected_rows() path = paths[0] path = self.filter_model.convert_path_to_child_path(path) iter = self.model.get_iter(path) self.model.remove(iter) def get_selected_bean(self): selection = self.get_selection() model, paths = selection.get_selected_rows() if not paths: return None return self._get_bean_by_path(paths[0]) def set_play_icon_to_selected_bean(self): selection = self.get_selection() filter_model, paths = selection.get_selected_rows() if not paths: return None path = filter_model.convert_path_to_child_path(paths[0]) model = filter_model.get_model() iter = model.get_iter(path) model.set_value(iter, self.play_icon[0], gtk.STOCK_MEDIA_PLAY) if self.prev_iter_play_icon: model.set_value(self.prev_iter_play_icon, self.play_icon[0], None) self.prev_iter_play_icon = iter def get_children_beans_by_selected(self): selection = self.get_selection() model, paths = selection.get_selected_rows() selected = model.get_iter(paths[0]) n = model.iter_n_children(selected) iterch = model.iter_children(selected) results = [] for i in xrange(n): path = model.get_path(iterch) bean = self._get_bean_by_path(path) results.append(bean) iterch = model.iter_next(iterch) return results def _get_bean_by_path(self, path): model = self.model LOG.info("Selecte bean path", path) path = self.filter_model.convert_path_to_child_path(path) LOG.info("Selecte bean path", path) iter = model.get_iter(path) if iter: bean = FModel() dt = FTreeModel().__dict__ for key in dt.keys(): setattr(bean, key, model.get_value(iter, dt[key][0])) return bean return None def get_bean_by_position(self, position): bean = FModel() dt = FTreeModel().__dict__ for key in dt.keys(): setattr(bean, key, self.model[position][dt[key][0]]) return bean def get_all_beans(self): beans = [] for i in xrange(len(self.model)): beans.append(self.get_bean_by_position(i)) return beans def get_all_selected_beans(self): selection = self.get_selection() model, paths = selection.get_selected_rows() if not paths: return None beans = [] for path in paths: selection.select_path(path) bean = self._get_bean_by_path(path) beans.append(bean) return beans def filter(self, query): if len(query.strip()) > 0: query = query.strip().decode("utf-8").lower() for line in self.model: name = line[self.text[0]].lower() if name.find(query) >= 0: #LOG.info("FIND PARENT:", name, query) line[self.visible[0]] = True else: find = False child_count = 0; for child in line.iterchildren(): name = str(child[self.text[0]]).decode("utf-8").lower() #name = child[self.text[0]] if name.find(query) >= 0: child_count += 1 #LOG.info("FIND CHILD :", name, query) child[self.visible[0]] = True line[self.visible[0]] = True #line[self.POS_FILTER_CHILD_COUNT] = child_count find = True else: child[self.visible[0]] = False if not find: line[self.visible[0]] = False else: self.expand_all() else: self.collapse_all() for line in self.model: line[self.visible[0]] = True for child in line.iterchildren(): child[self.visible[0]] = True
Python
''' Created on Sep 28, 2010 @author: ivan ''' from foobnix.regui.state import LoadSave from foobnix.regui.treeview import TreeViewControl from foobnix.regui.model.signal import FControl import gtk class SimpleTreeControl(TreeViewControl, LoadSave): def __init__(self, title_name, controls): TreeViewControl.__init__(self, controls) self.set_reorderable(False) """column config""" column = gtk.TreeViewColumn(title_name, gtk.CellRendererText(), text=self.text[0], font=self.font[0]) column.set_resizable(True) self.append_column(column) self.set_headers_visible(True) def on_load(self): pass def on_save(self): pass
Python
#-*- coding: utf-8 -*- ''' Created on 25 сент. 2010 @author: ivan ''' from foobnix.regui.treeview import TreeViewControl import gtk from random import randint from foobnix.util import const from foobnix.util.mouse_utils import is_double_left_click from foobnix.cue.cue_reader import CueReader from foobnix.regui.model import FModel class PlaylistControl(TreeViewControl): def __init__(self, controls): TreeViewControl.__init__(self, controls) """Column icon""" icon = gtk.TreeViewColumn(None, gtk.CellRendererPixbuf(), stock_id=self.play_icon[0]) icon.set_fixed_width(5) icon.set_min_width(5) """track number""" tracknumber = gtk.TreeViewColumn(None, gtk.CellRendererText(), text=self.tracknumber[0]) #tracknumber.set_sort_indicator(True) #tracknumber.set_sort_order(gtk.SORT_DESCENDING) #tracknumber.set_sort_column_id(2) """conlumt artist title""" description = gtk.TreeViewColumn('Artist - Title', gtk.CellRendererText(), text=self.text[0], font=self.font[0]) description.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE) #description.set_resizable(True) description.set_expand(True) """time text""" time = gtk.TreeViewColumn('Time', gtk.CellRendererText(), text=self.time[0]) time.set_fixed_width(5) time.set_min_width(5) self.append_column(icon) self.append_column(tracknumber) self.append_column(description) self.append_column(time) self.index = -1 def set_playlist_tree(self): self.init_data_tree() def recursion(self, row, plain): for child in row.iterchildren(): plain.append(child) self.recursion(child, plain) def set_playlist_plain(self): filter_model = self.get_model() model = filter_model.get_model() plain = [] for row in filter_model: plain.append(row) self.recursion(row, plain) copy_plain = [] for row in plain: copy_plain.append(self.get_bean_from_row(row)) model.clear() print "================" for bean in copy_plain: #self.print_row(bean) bean.visible = True if bean.is_file: model.append(None,self.get_row_from_bean(bean)) def on_key_release(self, w, e): if gtk.gdk.keyval_name(e.keyval) == 'Return': self.active_current_song() def next(self, rnd=False, lopping=const.LOPPING_LOOP_ALL): if lopping == const.LOPPING_LOOP_ALL: if not rnd: self.index += 1 if self.index == self.count_index: self.index = 0 else: self.index = randint(0, self.count_index) elif lopping == const.LOPPING_DONT_LOOP: return None #self.repopulate(self.index) self.set_play_icon_to_selected_bean() return self.get_bean_by_position(self.index) def prev(self, rnd=False, lopping=const.LOPPING_LOOP_ALL): if lopping == const.LOPPING_LOOP_ALL: if not rnd: self.index -= 1 if self.index < 0: self.index = self.count_index - 1 else: self.index = randint(0, self.count_index) elif lopping == const.LOPPING_DONT_LOOP: return None self.set_play_icon_to_selected_bean() return self.get_bean_by_position(self.index) def append(self, bean): value = None if bean.path and bean.path.endswith(".cue"): reader = CueReader(bean.path) beans = reader.get_common_beans() for bean in beans: value = super(PlaylistControl, self).append(bean) else: value = super(PlaylistControl, self).append(bean) return value def active_current_song(self): current = self.get_selected_bean() print current self.index = current.index if current.is_file: self.set_play_icon_to_selected_bean() """play song""" self.controls.play(current) """update song info""" self.controls.update_info_panel(current) """set active tree""" self.controls.notetabs.switch_tree(self) def on_button_press(self, w, e): if is_double_left_click(e): self.active_current_song()
Python
''' Created on Sep 29, 2010 @author: ivan ''' from foobnix.regui.state import LoadSave from foobnix.regui.treeview import TreeViewControl from foobnix.util.mouse_utils import is_double_left_click import gtk class RadioTreeControl(TreeViewControl, LoadSave): def __init__(self, controls): TreeViewControl.__init__(self, controls) self.set_reorderable(False) """column config""" column = gtk.TreeViewColumn("Radio Lybrary", gtk.CellRendererText(), text=self.text[0], font=self.font[0]) column.set_resizable(True) self.append_column(column) def on_button_press(self, w, e): if is_double_left_click(e): current = self.get_selected_bean() if current.is_file: self.controls.notetabs.append_tab(current.text, [current]) else: beans = self.get_children_beans_by_selected() self.controls.notetabs.append_tab(current.text, beans) def on_load(self): self.scroll.hide() pass def on_save(self): pass
Python
#-*- coding: utf-8 -*- ''' Created on 25 сент. 2010 @author: ivan ''' from foobnix.regui.treeview import TreeViewControl import gtk from foobnix.util.mouse_utils import is_double_left_click, is_rigth_click from foobnix.regui.state import LoadSave from foobnix.helpers.menu import Popup from foobnix.util.fc import FC from foobnix.util import LOG class MusicTreeControl(TreeViewControl, LoadSave): def __init__(self, controls): TreeViewControl.__init__(self, controls) """column config""" column = gtk.TreeViewColumn("Music Lybrary", gtk.CellRendererText(), text=self.text[0], font=self.font[0]) column.set_resizable(True) self.append_column(column) #self.enable_model_drag_source(gtk.gdk.BUTTON1_MASK, [("example1", 0, 0)], gtk.gdk.ACTION_COPY) #self.enable_model_drag_dest([("example1", 0, 0)], gtk.gdk.ACTION_COPY) def on_button_press(self, w, e): if is_double_left_click(e): bean = self.get_selected_bean() self.controls.append_to_new_notebook(bean.text, [bean]) if is_rigth_click(e): menu = Popup() menu.add_item(_("Update Music Tree"), gtk.STOCK_REFRESH, self.controls.update_music_tree, None) #menu.add_item(_("Play"), gtk.STOCK_MEDIA_PLAY, self.populate_playlist, None) menu.add_item(_("Add folder"), gtk.STOCK_OPEN, self.add_folder, None) menu.show(e) def add_folder(self): chooser = gtk.FileChooserDialog(title=_("Choose directory with music"), action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, buttons=(gtk.STOCK_OPEN, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) chooser.set_select_multiple(True) if FC().last_music_path: chooser.set_current_folder(FC().last_music_path) response = chooser.run() if response == gtk.RESPONSE_OK: paths = chooser.get_filenames() path = paths[0] FC().last_music_path = path[:path.rfind("/")] for path in paths: if path in FC().music_paths: pass else: FC().music_paths.append(path) self.controls.preferences.on_load() LOG.info("News music paths", FC().music_paths) self.controls.update_music_tree() elif response == gtk.RESPONSE_CANCEL: LOG.info('Closed, no files selected') chooser.destroy() def on_load(self): self.controls.load_music_tree() pass def on_save(self): pass
Python
#-*- coding: utf-8 -*- ''' Created on 3 окт. 2010 @author: ivan ''' import os.path def get_foobnix_resourse_path_by_name(filename): paths = ("/usr/local/share/pixmaps",\ "/usr/share/pixmaps",\ "pixmaps",\ "./../../..",\ "./../../",\ "./") for path in paths: full_path = os.path.join(path, filename) if os.path.exists (full_path): return full_path raise TypeError, "******* WARNING: File "+filename+" not found *******"
Python
#-*- coding: utf-8 -*- ''' Created on 27 сент. 2010 @author: ivan ''' from foobnix.model.entity import CommonBean from foobnix.thirdparty import pylast from foobnix.thirdparty.pylast import WSError, Tag from foobnix.util import LOG from foobnix.online.google.translate import translate from foobnix.util.fc import FC from foobnix.helpers.dialog_entry import show_login_password_error_dialog from foobnix.regui.model import FModel API_KEY = FC().API_KEY API_SECRET = FC().API_SECRET class Cache(): def __init__(self, network): self.network = network self.cache_tracks = {} self.cache_albums = {} self.cache_images = {} def get_key(self,artist, title): return artist+"-"+title def get_track(self, artist, title): if not artist or not title: return None if self.cache_tracks.has_key(self.get_key(artist, title)): track = self.cache_tracks[self.get_key(artist, title)] LOG.debug("Get track from cache", track) return track else: track = self.network.get_track(artist, title) self.cache_tracks[self.get_key(artist, title)] = track return track def get_album(self, artist, title): if not artist or not title: return None track = self.get_track(artist, title) if track: if self.cache_albums.has_key(self.get_key(artist, title)): LOG.debug("Get album from cache", track) return self.cache_albums[self.get_key(artist, title)] else: album = track.get_album() if album: self.cache_albums[self.get_key(artist, title)] = album return album return None def get_album_image_url(self, artist, title, size=pylast.COVER_LARGE): if not artist or not title: return None if self.cache_images.has_key(self.get_key(artist, title)): LOG.info("Get image from cache") return self.cache_images[self.get_key(artist, title)] else: album = self.get_album(artist, title) image = album.get_cover_image(size) self.cache_images[self.get_key(artist, title)] = image return image class LastFmService(): def __init__(self): self.network = None self.scrobler = None self.preferences_window = None #thread.start_new_thread(self.init_thread, ()) def connect(self): if self.network and self.scrobler: return True return self.init_thread() def init_thread(self): username = FC().lfm_login password_hash = pylast.md5(FC().lfm_password) try: self.network = pylast.get_lastfm_network(api_key=API_KEY, api_secret=API_SECRET, username=username, password_hash=password_hash) self.cache = Cache(self.network) if FC().proxy_enable and FC().proxy_url: proxy_rul = FC().proxy_url index = proxy_rul.find(":") proxy = proxy_rul[:index] port = proxy_rul[index + 1:] self.network.enable_proxy(proxy, port) LOG.info("Enable proxy for last fm", proxy, port) """scrobler""" scrobler_network = pylast.get_lastfm_network(username=username, password_hash=password_hash) self.scrobler = scrobler_network.get_scrobbler("fbx", "1.0") except: LOG.error("Invalid last fm login or password or network problems", username, FC().lfm_password) val = show_login_password_error_dialog(_("Last.fm connection error"), _("Verify user and password"), username, FC().lfm_password) if val: FC().lfm_login = val[0] FC().lfm_password = val[1] return False return True def get_network(self): return self.network def get_scrobler(self): return self.scrobler def connected(self): return self.network is not None def search_top_albums(self, aritst_name): self.connect() artist = self.network.get_artist(aritst_name) if not artist: return None try: albums = artist.get_top_albums() except WSError: LOG.info("No artist with that name") return None beans = [] for album in albums: try: album_txt = album.item except AttributeError: album_txt = album['item'] name = album_txt.get_name() #year = album_txt.get_release_year() year = None if year: bean = FModel(name + "("+year+")").add_album(name).add_artist(aritst_name).add_year(year) else: bean = FModel(name).add_album(name).add_artist(aritst_name).add_year(year) beans.append(bean) return beans def search_album_tracks(self, artist_name, album_name): if not artist_name or not album_name: LOG.warn("search_album_tracks artist and album is empty") return [] self.connect() album = self.network.get_album(artist_name, album_name) tracks = album.get_tracks() results = [] for track in tracks: artist = track.get_artist().get_name() title = track.get_title() print artist, title bean = FModel(artist + " - "+ title).add_artist(artist).add_title(title) results.append(bean) return results def search_top_tags(self, tag): self.connect() if not tag: LOG.warn("search_top_tags TAG is empty") return [] tag = translate(tag, src="ru", to="en") print tag beans = [] tags = self.network.search_for_tag(tag) print tags for tag in tags.get_next_page(): tag_name = tag.get_name() bean = FModel(tag_name).add_genre(tag_name) beans.append(bean) return beans def search_top_tag_tracks(self, tag_name): self.connect() if not tag_name: LOG.warn("search_top_tags TAG is empty") return [] tag = Tag(tag_name,self.network) tracks = tag.get_top_tracks() beans = [] for track in tracks: try: track_item = track.item except AttributeError: track_item = track['item'] #LOG.info(track_item.get_duration()) #bean = CommonBean(name=str(track_item), path="", type=CommonBean.TYPE_MUSIC_URL, parent=query); artist = track_item.get_artist().get_name() title = track_item.get_title() text = artist + " - " + title bean = FModel(text).add_artist(artist).add_title(title) #norm_duration = track_item.get_duration() / 1000 #LOG.info(track_item.get_duration(), norm_duration #bean.time = normilize_time(norm_duration) beans.append(bean) return beans def search_top_tracks(self, artist_name): self.connect() artist = self.network.get_artist(artist_name) if not artist: return [] try: tracks = artist.get_top_tracks() except WSError: LOG.info("No artist with that name") return [] beans = [] for track in tracks: try: track_item = track.item except AttributeError: track_item = track['item'] #LOG.info(track_item.get_duration()) #bean = CommonBean(name=str(track_item), path="", type=CommonBean.TYPE_MUSIC_URL, parent=query); artist = track_item.get_artist().get_name() title = track_item.get_title() text = artist + " - " + title bean = FModel(text).add_artist(artist).add_title(title) #norm_duration = track_item.get_duration() / 1000 #LOG.info(track_item.get_duration(), norm_duration #bean.time = normilize_time(norm_duration) beans.append(bean) return beans def search_top_similar_artist(self, artist_name, count=45): self.connect() if not artist_name: LOG.warn("search_top_similar_artist, Artist name is empty") return [] artist = self.network.get_artist(artist_name) if not artist: return [] artists = artist.get_similar(count) beans = [] for artist in artists: try: artist_txt = artist.item except AttributeError: artist_txt = artist['item'] artist_name = artist_txt.get_name() bean = FModel(artist_name).add_artist(artist_name) beans.append(bean) return beans def search_top_similar_tracks(self, artist, title): self.connect() if not artist or not title: LOG.warn("search_top_similar_tags artist or title is empty") return [] track = self.cache.get_track(artist, title) if not track: LOG.warn("search_top_similar_tracks track not found") return [] similars = track.get_similar() beans = [] for tsong in similars: try: tsong_item = tsong.item except AttributeError: tsong_item = tsong['item'] artist = tsong_item.get_artist().get_name() title = tsong_item.get_title() model = FModel(artist + " - " + title).add_artist(artist).add_title(title) beans.append(model) return beans def search_top_similar_tags(self, artist, title): self.connect() if not artist or not title: LOG.warn("search_top_similar_tags artist or title is empty") return [] track = self.cache.get_track(artist, title) if not track: LOG.warn("search_top_similar_tags track not found") return [] tags = track.get_top_tags() beans = [] for tag in tags: try: tag_item = tag.item except AttributeError: tag_item = tag['item'] tag_name = tag_item.get_name() model = FModel(tag_name).add_genre(tag_name) beans.append(model) return beans def get_album_name(self, artist, title): self.connect() album = self.cache.get_album(artist, title); if album: return album.get_name() def get_album_year(self, artist, title): self.connect() album = self.cache.get_album(artist, title); if album: return album.get_release_year() def get_album_image_url(self, artist, title, size=pylast.COVER_LARGE): return self.cache.get_album_image_url(artist, title);
Python
''' Created on Sep 29, 2010 @author: ivan ''' import time from foobnix.util.fc import FC import urllib2 from foobnix.util import LOG import urllib import re from foobnix.helpers.dialog_entry import show_login_password_error_dialog from setuptools.package_index import htmldecode from setuptools.command.sdist import unescape from string import replace from foobnix.regui.model import FModel def _(*a): print a class VKService: def __init__(self, email=None, password=None): self.vk_cookie = None self.execute_time = time.time() def isLive(self): return self.get_s_value() def get_s_value(self): host = 'http://login.vk.com/?act=login' #host = 'http://vkontakte.ru/login.php' post = urllib.urlencode({'email' : FC().vk_login, 'expire' : '', 'pass' : FC().vk_password, 'vk' : ''}) headers = {'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; uk; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 GTB7.0', 'Host' : 'login.vk.com', 'Referer' : 'http://vkontakte.ru/index.php', 'Connection' : 'close', 'Pragma' : 'no-cache', 'Cache-Control' : 'no-cache', } conn = urllib2.Request(host, post, headers) try: data = urllib2.urlopen(conn) except: LOG.error("Error VK connection") return None result = data.read() value = re.findall(r"name='s' value='(.*?)'", result) """old response format""" if not value: value = re.findall(r"name='s' id='s' value='(.*?)'", result) if value: return value[0] return None def get_cookie(self): if FC().vk_cookie: LOG.info("Get VK cookie from cache") return FC().vk_cookie s_value = self.get_s_value() if not s_value: FC().vk_cookie = None val = show_login_password_error_dialog(_("VKontakte connection error"), _("Verify user and password"), FC().vk_login, FC().vk_password) if val: FC().vk_login = val[0] FC().vk_password = val[1] return None if self.vk_cookie: return self.vk_cookie host = 'http://vkontakte.ru/login.php?op=slogin' post = urllib.urlencode({'s' : s_value}) headers = {'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; uk; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 GTB7.0', 'Host' : 'vkontakte.ru', 'Referer' : 'http://login.vk.com/?act=login', 'Connection' : 'close', 'Cookie' : 'remixchk=5; remixsid=nonenone', 'Pragma' : 'no-cache', 'Cache-Control' : 'no-cache' } conn = urllib2.Request(host, post, headers) data = urllib2.urlopen(conn) cookie_src = data.info().get('Set-Cookie') self.cookie = re.sub(r'(expires=.*?;\s|path=\/;\s|domain=\.vkontakte\.ru(?:,\s)?)', '', cookie_src) FC().vk_cookie = self.vk_cookie return self.cookie def get_page(self, query): if not query: return None #GET /gsearch.php?section=audio&q=madonna&name=1 host = 'http://vkontakte.ru/gsearch.php?section=audio&q=vasya#c[q]=some%20id&c[section]=audio&name=1' post = urllib.urlencode({ "c[q]" : query, "c[section]":"audio" }) headers = {'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; uk; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 GTB7.0', 'Host' : 'vkontakte.ru', 'Referer' : 'http://vkontakte.ru/index.php', 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With' : 'XMLHttpRequest', 'Connection' : 'close', 'Cookie' : 'remixlang=0; remixchk=5; audio_vol=100; %s' % self.get_cookie(), 'Pragma' : 'no-cache', 'Cache-Control' : ' no-cache' } conn = urllib2.Request(host, post, headers) #Do not run to offten cur_time = time.time() if cur_time - self.execute_time < 0.5: LOG.info("Sleep because to many requests...") time.sleep(0.8) self.execute_time = time.time() data = urllib2.urlopen(conn); result = data.read() return result def get_page_by_url(self, host_url): if not host_url: return host_url host_url.replace("#", "&") post = host_url[host_url.find("?") + 1:] LOG.debug("post", post) headers = {'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; uk; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 GTB7.0', 'Host' : 'vkontakte.ru', 'Referer' : 'http://vkontakte.ru/index.php', 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With' : 'XMLHttpRequest', 'Connection' : 'close', 'Cookie' : 'remixlang=0; remixchk=5; audio_vol=100; %s' % self.get_cookie(), 'Pragma' : 'no-cache', 'Cache-Control' : ' no-cache' } conn = urllib2.Request(host_url, post, headers) #Do not run to offten cur_time = time.time() if cur_time - self.execute_time < 0.5: LOG.info("Sleep because to many requests...") time.sleep(0.8) self.execute_time = time.time() data = urllib2.urlopen(conn); result = data.read() return result def get_name_by(self, id, result_album): for album in result_album: id_album = album[0] name = album[1] if id_album == id: return name return None def to_good_chars(self, line): try: return htmldecode(line) except: return unescape(line) def get_content_len(self, path): open = urllib.urlopen(path) return open.info().getheaders("Content-Length")[0] def find_time_value(self, times_count, r_count): for i in times_count: if times_count[i] == r_count: return i return None def find_tracks_by_query(self, query): LOG.info("start search songs", query) page = self.get_page(query) #page = page.decode('cp1251') #page = page.decode("cp1251") #unicode(page, "cp1251") reg_all = "([^<>]*)" resultall = re.findall("return operate\(([\w() ,']*)\);", page, re.IGNORECASE) result_album = re.findall(u"<b id=\\\\\"performer([0-9]*)\\\\\">" + reg_all + "<", page, re.IGNORECASE | re.UNICODE) result_track = re.findall(u"<span id=\\\\\"title([0-9]*)\\\\\">" + reg_all + "<", page, re.IGNORECASE | re.UNICODE) result_time = re.findall("<div class=\\\\\"duration\\\\\">" + reg_all + "<", page, re.IGNORECASE) urls = [] ids = [] vkSongs = [] for result in resultall: result = replace(result, "'", " ") result = replace(result, ",", " ") result = result.split() if len(result) > 4: id_id = result[0] id_server = result[1] id_folder = result[2] id_file = result[3] url = "http://cs" + id_server + ".vkontakte.ru/u" + id_folder + "/audio/" + id_file + ".mp3" urls.append(url) ids.append(id_id) for i in xrange(len(result_time)): id = ids[i] path = urls[i] album = self.get_name_by(id, result_album) track = self.get_name_by(id, result_track) time = result_time[i] text = album + " - " + track vkSong = FModel(text, path).add_artist(album).add_title(track).add_time(time) vkSongs.append(vkSong) return vkSongs def find_tracks_by_url(self, url): LOG.debug("Search By URL") result = self.get_page_by_url(url) try: result = unicode(result) except: result = result reg_all = "([^{<}]*)" result_url = re.findall(ur"http:([\\/.0-9_A-Z]*)", result, re.IGNORECASE) result_artist = re.findall(u"q]=" + reg_all + "'", result, re.IGNORECASE | re.UNICODE) result_title = re.findall(u"\"title([0-9_]*)\\\\\">" + reg_all + "", result, re.IGNORECASE | re.UNICODE) result_time = re.findall("duration\\\\\">" + reg_all, result, re.IGNORECASE | re.UNICODE) result_lyr = re.findall(ur"showLyrics" + reg_all, result, re.IGNORECASE | re.UNICODE) LOG.info("lyr:::", result_lyr) songs = [] j = 0 for i, artist in enumerate(result_artist): path = "http:" + result_url[i].replace("\\/", "/") title = self.to_good_chars(result_title[i][1]) if not title: if len(result_lyr) > j: title = result_lyr[j] title = title[title.find(";'>") + 3:] j += 1 artist = self.to_good_chars(artist) #song = VKSong(path, artist, title, result_time[i]); text = artist +" - " + title song = FModel(text, path).add_artist(artist).add_title(title).add_time(result_time) songs.append(song) LOG.info(len(songs)) return self.convert_vk_songs_to_beans(songs) def find_one_track(self, query): vkSongs = self.find_tracks_by_query(query) if not vkSongs: return None times_count = {} for song in vkSongs: time = song.time if time in times_count: times_count[time] = times_count[time] + 1 else: times_count[time] = 1 #get most relatives times time r_count = max(times_count.values()) r_time = self.find_time_value(times_count, r_count) LOG.info("LOG.info(Song time", r_time) LOG.info("LOG.info(Count of congs", r_count) for song in vkSongs: if song.time == r_time: return song return vkSongs[0] #vk = VKService() #list = vk.find_one_track("Madonna - Sorry") #list = vk.find_tracks_by_query("Madonna - Sorry") #print "RES", list
Python
#-*- coding: utf-8 -*- ''' Created on 28 сент. 2010 @author: anton.komolov ''' import dbus.service from dbus.mainloop.glib import DBusGMainLoop from foobnix.util.configuration import get_version from foobnix.regui.model.signal import FControl DBusGMainLoop(set_as_default=True) DBUS_NAME = "org.mpris.foobnix" MPRIS_ROOT_PATH = "/" MPRIS_PLAYER_PATH = "/Player" MPRIS_TRACKLIST_PATH = "/TrackList" DBUS_MEDIAPLAYER_INTERFACE = 'org.freedesktop.MediaPlayer' class MprisPlayer(dbus.service.Object, FControl): def __init__(self, controls, object_path=MPRIS_PLAYER_PATH): dbus.service.Object.__init__(self, dbus.SessionBus(), object_path) FControl.__init__(self, controls) #Next ( ) @dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='') def Next(self): self.controls.next() #Prev ( ) @dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='') def Prev(self): self.controls.prev() #Pause ( ) @dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='') def Pause(self): self.controls.state_pause() #Stop ( ) @dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='') def Stop(self): self.controls.state_stop() #Play ( ) @dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='') def Play(self): self.controls.state_play() #PlayPause for test @dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='') def PlayPause(self): self.controls.state_play_pause() #TODO #Repeat ( b: State ) """State − b TRUE to repeat the current track, FALSE to stop repeating.""" #GetStatus ( ) → (iiii) """Return the status of media player as a struct of 4 ints. Returns Status − (iiii) (Status_Struct) Status_Struct − ( i: Playback_State, i: Shuffle_State, i: Repeat_Current_State, i: Endless_State ) Playback_State − i 0 = Playing, 1 = Paused, 2 = Stopped. Shuffle_State − i 0 = Playing linearly, 1 = Playing randomly. Repeat_Current_State − i 0 = Go to the next element once the current has finished playing, 1 = Repeat the current element. Endless_State − i 0 = Stop playing once the last element has been played, 1 = Never give up playing""" #GetMetadata ( ) → a{sv} """Gives all meta data available for the currently played element. Guidelines for field names are at http://wiki.xmms2.xmms.se/wiki/MPRIS_Metadata . Returns Metadata − a{sv} (String_Variant_Map)""" #GetCaps ( ) → i """Return the "media player"'s current capabilities. Returns Capabilities − i (Caps_Flags)""" #VolumeSet ( i: Volume ) #VolumeGet ( ) → i #PositionSet ( i: Position ) """Track position between [0;<track_length>] in ms.""" #PositionGet ( ) → i """Track position between [0;<track_length>] in ms.""" #Signals: #TrackChange ( a{sv}: Metadata ) #StatusChange ( (iiii): Status ) #CapsChange ( i: Capabilities ) class DBusManager(dbus.service.Object, FControl): def __init__(self, controls, object_path=MPRIS_ROOT_PATH): self.bus = dbus.SessionBus() bus_name = dbus.service.BusName(DBUS_NAME, bus=self.bus) dbus.service.Object.__init__(self, bus_name, object_path) FControl.__init__(self, controls) self._player = MprisPlayer(controls) try: dbus_interface = 'org.gnome.SettingsDaemon.MediaKeys' mm_object = bus.get_object('org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon/MediaKeys') mm_object.GrabMediaPlayerKeys("MyMultimediaThingy", 0, dbus_interface=dbus_interface) mm_object.connect_to_signal('MediaPlayerKeyPressed', self.on_mediakey) except Exception, e: print "your OS is not GNOME", e def on_mediakey(self, comes_from, what): """ gets called when multimedia keys are pressed down. """ if what in ['Stop', 'Play', 'Next', 'Previous']: if what == 'Stop': self.controls.state_stop() elif what == 'Play': self.controls.state_play_pause() elif what == 'Next': self.controls.next() elif what == 'Previous': self.controls.prev() else: print('Got a multimedia key:', what) @dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='s') def Identity(self): return "foobnix %s" % get_version() @dbus.service.method (DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='(qq)') def MprisVersion (self): return (1, 0) @dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='') def Quit(self): self.controls.quit() def foobnixDBusInterface(): bus = dbus.SessionBus() dbus_objects = dbus.Interface(bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus'), 'org.freedesktop.DBus').ListNames() if not DBUS_NAME in dbus_objects: return None else: return dbus.Interface(bus.get_object(DBUS_NAME, MPRIS_ROOT_PATH), DBUS_MEDIAPLAYER_INTERFACE)
Python
#-*- coding: utf-8 -*- ''' Created on 27 сент. 2010 @author: ivan ''' import gtk from foobnix.regui.model.signal import FControl import time import thread class SearchProgressBar(FControl, gtk.ProgressBar): def __init__(self, controls): FControl.__init__(self, controls) gtk.ProgressBar.__init__(self) self.hide() self.flag = True def start(self, text): self.set_text(text) self.show() self.flag = True def pulse_thread(): while self.flag: self.pulse() time.sleep(0.1) thread.start_new_thread(pulse_thread, ()) def stop(self): self.flag = False self.hide()
Python
''' Created on Sep 27, 2010 @author: ivan ''' from foobnix.regui.state import LoadSave from foobnix.helpers.toolbar import MyToolbar from foobnix.regui.model.signal import FControl import gtk class PlaybackControls(FControl,MyToolbar,LoadSave): def __init__(self, controls): FControl.__init__(self, controls) MyToolbar.__init__(self) self.add_separator() self.add_button("Stop", gtk.STOCK_MEDIA_STOP, controls.state_stop, None) self.add_button("Play", gtk.STOCK_MEDIA_PLAY, controls.state_play, None) self.add_button("Pause", gtk.STOCK_MEDIA_PAUSE, controls.state_pause, None) self.add_button("Previous", gtk.STOCK_MEDIA_PREVIOUS, controls.prev, None) self.add_button("Next", gtk.STOCK_MEDIA_NEXT, controls.next, None) self.add_separator() def on_load(self): pass def on_save(self): pass
Python
#-*- coding: utf-8 -*- ''' Created on 28 сент. 2010 @author: ivan ''' from foobnix.regui.model.signal import FControl import gtk class StatusbarControls(gtk.Statusbar, FControl): def __init__(self, controls): gtk.Statusbar.__init__(self) FControl.__init__(self, controls) self.show() def set_text(self, text): print "set TEXT" if text: self.push(0, text)
Python
#-*- coding: utf-8 -*- ''' Created on 28 сент. 2010 @author: ivan ''' from foobnix.regui.model.signal import FControl import gtk from foobnix.util.time_utils import convert_seconds_to_text class SeekProgressBarControls(FControl, gtk.Alignment): def __init__(self, controls): FControl.__init__(self, controls) gtk.Alignment.__init__(self, xalign=0.5, yalign=0.5, xscale=1.0, yscale=1.0) self.set_padding(padding_top=7, padding_bottom=7, padding_left=0, padding_right=7) self.progresbar = gtk.ProgressBar() self.progresbar.set_text("00:00 / 00:00") event = gtk.EventBox() event.connect("button-press-event", self.on_seek) event.add(self.progresbar) self.add(event) self.show_all() def on_seek(self, widget, event): width = widget.allocation.width x = event.x seek_percent = (x + 0.0) / width * 100 self.controls.player_seek(seek_percent); def set_text(self, text): if text: self.progresbar.set_text(text[:200]) def clear(self): self.progresbar.set_text("00:00 / 00:00") def update_seek_status(self, position_sec, duration_sec): duration_str = convert_seconds_to_text(duration_sec) position_str = convert_seconds_to_text(position_sec) seek_text = position_str + " / " + duration_str seek_persent = (position_sec + 0.0) / (duration_sec) self.progresbar.set_text(seek_text) if 0 <= seek_persent <= 1: self.progresbar.set_fraction(seek_persent)
Python
#-*- coding: utf-8 -*- ''' Created on 28 сент. 2010 @author: ivan ''' import gtk from foobnix.regui.state import LoadSave from foobnix.util.fc import FC from foobnix.regui.model.signal import FControl class VolumeControls(LoadSave, gtk.HBox, FControl): MAX_VALUE = 120 def __init__(self, controls): gtk.HBox.__init__(self, False, 0) FControl.__init__(self, controls) label_m = gtk.Label("-") adjustment = gtk.Adjustment(value=1, lower=0, upper=self.MAX_VALUE, step_incr=10, page_incr=50, page_size=0) self.volume_scale = gtk.HScale(adjustment) self.volume_scale.connect("value-changed", self.on_value_changed) self.volume_scale.connect("scroll-event", self.on_scroll_event) self.volume_scale.set_size_request(150, -1) self.volume_scale.set_update_policy(gtk.UPDATE_CONTINUOUS) self.volume_scale.set_digits(1) self.volume_scale.set_draw_value(False) self.volume_scale.set_value(30) label_p = gtk.Label("+") self.pack_start(label_m, False, False) self.pack_start(self.volume_scale, False, False) self.pack_start(label_p, False, False) self.show_all() def get_value(self): self.volume_scale.get_value() def set_value(self,value): self.volume_scale.set_value(value) def on_scroll_event(self, button, event): value = self.volume_scale.get_value() if event.direction == gtk.gdk.SCROLL_UP: #@UndefinedVariable self.volume_scale.set_value(value + 3) else: self.volume_scale.set_value(value - 3) self.controls.player_volue(value) return True def on_value_changed(self, widget): percent = widget.get_value() self.controls.player_volue(percent) FC().volume = percent def on_save(self): FC().volume = self.volume_scale.get_value() def on_load(self): self.volume_scale.set_value(FC().volume)
Python
#-*- coding: utf-8 -*- ''' Created on 25 сент. 2010 @author: ivan ''' from foobnix.regui.model.signal import FControl import gtk from foobnix.regui.state import LoadSave class FilterControl(gtk.Entry, FControl, LoadSave): def __init__(self, controls): gtk.Entry.__init__(self) FControl.__init__(self, controls) self.connect("key-release-event", self.on_filter) def on_filter(self, w, e): value = w.get_text() self.controls.filter_tree(value) def on_load(self): pass def on_save(self): pass
Python
#-*- coding: utf-8 -*- ''' Created on 29 сент. 2010 @author: ivan ''' from foobnix.regui.model.signal import FControl import gtk import os from foobnix.util.fc import FC from foobnix.helpers.toolbar import MyToolbar from foobnix.util.mouse_utils import is_mouse_click from foobnix.regui.service.path_service import get_foobnix_resourse_path_by_name class PopupWindowMenu(gtk.Window, FControl): def __init__(self, controls): FControl.__init__(self, controls) gtk.Window. __init__(self, gtk.WINDOW_POPUP) self.set_position(gtk.WIN_POS_MOUSE) self.connect("leave-notify-event", self.on_leave_window) vbox = gtk.VBox(False, 0) toolbar = MyToolbar() toolbar.add_button("Exit", gtk.STOCK_QUIT, self.controls.quit, None) toolbar.add_separator() toolbar.add_button("Stop", gtk.STOCK_MEDIA_STOP, self.controls.state_stop, None) toolbar.add_button("Play", gtk.STOCK_MEDIA_PLAY, self.controls.state_play, None) toolbar.add_button("Pause", gtk.STOCK_MEDIA_PAUSE, self.controls.state_pause, None) toolbar.add_button("Previous", gtk.STOCK_MEDIA_PREVIOUS, self.controls.prev, None) toolbar.add_button("Next", gtk.STOCK_MEDIA_NEXT, self.controls.next, None) toolbar.add_separator() toolbar.add_button("Close Popup", gtk.STOCK_OK, lambda * a:self.hide(), None) self.poopup_text = gtk.Label("Foobnix") self.poopup_text.set_line_wrap(True) vbox.pack_start(toolbar, False, False) vbox.pack_start(self.poopup_text, False, False) self.add(vbox) self.show_all() self.hide() def set_text(self, text): self.poopup_text.set_text(text) def on_leave_window(self, w, event): print w, event max_x, max_y = w.size_request() x, y = event.x, event.y if 0 < x < max_x and 0 < y < max_y: return True print "hide" self.hide() class TrayIconControls(FControl): def __init__(self, controls): FControl.__init__(self, controls) self.icon = gtk.StatusIcon() self.icon.set_tooltip("Foobnix music player") self.popup_menu = PopupWindowMenu(self.controls) path = get_foobnix_resourse_path_by_name("foobnix.png") if path: self.icon.set_from_file(path) else: self.icon.set_from_stock("gtk-media-play") self.icon.connect("activate", self.on_activate) self.icon.connect("popup-menu", self.on_popup_menu) self.icon.connect("button-press-event", self.on_button_press) self.icon.connect("scroll-event", self.controls.volume.on_scroll_event) if FC().show_tray_icon: self.show() else: self.hide() self.paused = False def on_activate(self, *a): self.controls.windows_visibility() def on_button_press(self, w, e): if is_mouse_click(e): self.paused = not self.paused if self.paused: self.controls.state_play() else: self.controls.state_pause() def hide(self): self.icon.set_visible(False) def show(self): self.icon.set_visible(True) def show_window(self, *a): self.popup_menu.reshow_with_initial_size() self.popup_menu.show() print "show" def hide_window(self, *a): self.popup_menu.hide() print "hide" def on_popup_menu(self, *a): self.show_window() def set_text(self, text): self.popup_menu.set_text(text) self.icon.set_tooltip(text) def get_pixbuf(self): return self.icon.get_pixbuf()
Python
#-*- coding: utf-8 -*- ''' Created on 23 сент. 2010 @author: ivan ''' class LoadSave(object): def __init__(self): pass def on_load(self): raise Exception("Method not defined on_load", self.__class__.__name__) def on_save(self): raise Exception("Method not defined on_save", self.__class__.__name__)
Python
#-*- coding: utf-8 -*- ''' Created on 25 сент. 2010 @author: ivan ''' """base class to comunicate beatween all controls""" class FControl(): def __init__(self, controls): self.controls = controls
Python
import gobject class FTreeModel(): def __init__(self): self.text = 0, str self.visible = 1, gobject.TYPE_BOOLEAN self.font = 2, str self.play_icon = 3, str self.time = 4, str self.path = 5, str self.level = 6, str self.tracknumber = 7, str self.index = 8, int self.is_file = 9, gobject.TYPE_BOOLEAN self.artist = 10, str self.title = 11, str self.image = 12, str self.album = 13, str self.genre = 14, str self.year = 15, str self.info = 16, str self.start_sec = 17, str self.duration_sec = 18, str def cut(self): for i in self.__dict__: self.__dict__[i] = self.__dict__[i][0] return self def types(self): types = [] for i in xrange(0, len(self.__dict__)): for j in self.__dict__: id = self.__dict__[j][0] type = self.__dict__[j][1] if i == id: types.append(type) break; return types class FModel(FTreeModel): TYPE_SONG = "SONG" TYPE_FOLDER = "FOLDER" def __init__(self, text=None, path=None): FTreeModel.__init__(self) for i in self.__dict__: self.__dict__[i] = None self.text = text self.path = path def add_artist(self, artist): self.artist = artist return self def add_title(self, title): self.title = title return self def add_level(self, level): self.level = level return self def add_parent(self, level): self.level = level return self def add_font(self, font): self.font = font return self def add_is_file(self, is_file): self.is_file = is_file return self def add_album(self, album): self.album = album return self def add_year(self, year): self.year = year return self def add_play_icon(self, play_icon): self.play_icon = play_icon return self def add_genre(self, genre): self.genre = genre return self def add_time(self, time): self.time = time return self def __str__(self): return "FModel: " + str(self.__dict__)
Python
#-*- coding: utf-8 -*- ''' Created on 28 сент. 2010 @author: ivan ''' import gst import urllib import os from foobnix.regui.engine import MediaPlayerEngine from foobnix.util import LOG import time import gtk import thread from foobnix.util.fc import FC class GStreamerEngine(MediaPlayerEngine): NANO_SECONDS = 1000000000 def __init__(self, controls): MediaPlayerEngine.__init__(self, controls) self.player = self.init_local() self.position_sec = 0 self.duration_sec = 0 self.prev_path = None self.bean = None def init_local(self): playbin = gst.element_factory_make("playbin2", "player") bus = playbin.get_bus() bus.add_signal_watch() bus.connect("message", self.on_message) LOG.debug("LOCAL gstreamer") return playbin def init_http(self): playbin = gst.element_factory_make("playbin", "player") bus = playbin.get_bus() bus.add_signal_watch() bus.connect("message", self.on_message) LOG.debug("HTTP gstreamer") return playbin def notify_init(self, duraction_int): LOG.debug("Pre init thread", duraction_int) def notify_playing(self, position_int, duration_int): #LOG.debug("Notify playing", position_int) self.position_sec = position_int / self.NANO_SECONDS self.duration_sec = duration_int / self.NANO_SECONDS self.controls.notify_playing(self.position_sec, self.duration_sec) def notify_eos(self): LOG.debug("Notify eos") self.controls.notify_eos() def notify_title(self, text): self.controls.notify_title(text) def notify_error(self): LOG.debug("Notify error") def play(self, bean): self.bean = bean if not bean: return None path = bean.path if not path: LOG.error("Can't play empty path!!!") return None self.state_stop() if self.prev_path != path: if path.startswith("http://"): self.player = self.init_http() uri = path else: self.player = self.init_local() uri = 'file://' + urllib.pathname2url(path) if os.name == 'nt': uri = 'file:' + urllib.pathname2url(path) self.player.set_property("uri", uri) LOG.info("Gstreamer try to play", uri) self.prev_path = path self.state_pause() time.sleep(0.2) self.seek_seconds(bean.start_sec) self.state_play() self.volume(FC().volume) self.play_thread_id = thread.start_new_thread(self.playing_thread, ()) def playing_thread(self): thread_id = self.play_thread_id error_count = 0 while thread_id == self.play_thread_id: try: time.sleep(0.2) duraction_int = self.player.query_duration(gst.Format(gst.FORMAT_TIME), None)[0] if duraction_int == -1: continue gtk.gdk.threads_enter() #@UndefinedVariable self.notify_init(duraction_int) gtk.gdk.threads_leave() #@UndefinedVariable break except Exception, e: LOG.info("Init playing thread", e) time.sleep(1) if error_count > 3: LOG.warn("shit happens") self.state_stop() time.sleep(1) self.state_play() error_count += 1 time.sleep(0.2) if self.bean.duration_sec > 0: duraction_int = float(self.bean.duration_sec) * self.NANO_SECONDS while thread_id == self.play_thread_id: try: position_int = self.player.query_position(gst.Format(gst.FORMAT_TIME), None)[0] if self.bean.start_sec > 0: position_int = position_int - float(self.bean.start_sec) * self.NANO_SECONDS if position_int + self.NANO_SECONDS > duraction_int: gtk.gdk.threads_enter() #@UndefinedVariable self.notify_eos() gtk.gdk.threads_leave() #@UndefinedVariable gtk.gdk.threads_enter() #@UndefinedVariable self.notify_playing(position_int, duraction_int) gtk.gdk.threads_leave() #@UndefinedVariable except Exception, e: LOG.info("Playing thread error..." , e) time.sleep(1) def seek(self, percent): seek_ns = self.duration_sec * percent / 100 * self.NANO_SECONDS; if self.bean.start_sec > 0: seek_ns = seek_ns + float(self.bean.start_sec) * self.NANO_SECONDS self.player.seek_simple(gst.Format(gst.FORMAT_TIME), gst.SEEK_FLAG_FLUSH, seek_ns) def seek_seconds(self, seconds): if not seconds: return LOG.info("Start with seconds", seconds) seek_ns = (float(seconds) + 0.0) * self.NANO_SECONDS LOG.info("SEC SEEK SEC", seek_ns) self.player.seek_simple(gst.Format(gst.FORMAT_TIME), gst.SEEK_FLAG_FLUSH, seek_ns) def volume(self, percent): value = percent / 100.0 self.player.set_property('volume', value) def state_play(self): if self.status.isPause: self.status.setPlay() self.player.set_state(gst.STATE_PLAYING) else: self.state_stop() self.play(self.bean) def state_stop(self): self.status.setStop() self.play_thread_id = None self.player.set_state(gst.STATE_NULL) def state_pause(self): if self.status.isPause: self.state_play() else: self.status.setPause() #self.player.set_state(gst.STATE_VOID_PENDING) self.player.set_state(gst.STATE_PAUSED) def state_play_pause(self): if self.status.isPlay: self.state_pause() else: self.state_play() def on_message(self, bus, message): #print bus, message type = message.type if type == gst.MESSAGE_TAG and message.parse_tag(): if message.structure.has_field("title"): title = message.structure['title'] self.notify_title(title) elif type == gst.MESSAGE_EOS: LOG.info("MESSAGE_EOS") self.notify_eos() elif type == gst.MESSAGE_ERROR: err, debug = message.parse_error() LOG.warn("Error: %s" % err, debug, err.domain, err.code) if err.code != 1: self.notify_title(str(err)) self.notify_error()
Python
from foobnix.regui.model.signal import FControl class MediaPlayerStatus(): def __init__(self): self.setStop() def setPlay(self): self.isPlay = True self.isPause = False self.isStop = False def setPause(self): self.isPlay = False self.isPause = True self.isStop = False def setStop(self): self.isPlay = False self.isPause = False self.isStop = True class MediaPlayerEngine(FControl): def __init__(self, controls): FControl.__init__(self, controls) self.status = MediaPlayerStatus() def state_play(self): pass def state_pause(self): pass def state_stop(self): pass def play(self, path): pass def state_play_pause(self): pass #0-100 def volume_up(self, value): pass #0-100 def volume_down(self, value): pass
Python
#-*- coding: utf-8 -*- ''' Created on 25 сент. 2010 @author: ivan ''' import gtk from foobnix.regui.top import TopWidgets from foobnix.regui.left import LeftWidgets from foobnix.regui.state import LoadSave from foobnix.util.fc import FC from foobnix.regui.model.signal import FControl from foobnix.util import LOG class BaseFoobnixLayout(LoadSave, FControl): def __init__(self, controls): FControl.__init__(self, controls) vbox = gtk.VBox(False, 0) vbox.pack_start(controls.top_panel, False, False) center_box = gtk.VBox(False, 0) self.hpaned_right = gtk.HPaned() self.hpaned_right.pack1(child=controls.notetabs, resize=True, shrink=True) self.hpaned_right.pack2(child=controls.info_panel, resize=True, shrink=True) center_box.pack_start(controls.searchPanel, False, False) center_box.pack_start(self.hpaned_right, True, True) self.left = LeftWidgets(controls) self.hpaned_left = gtk.HPaned() self.hpaned_left.pack1(child=self.left, resize=True, shrink=True) self.hpaned_left.pack2(child=center_box, resize=True, shrink=True) self.hpaned_left.show_all() vbox.pack_start(self.hpaned_left, True, True) vbox.pack_start(controls.statusbar, False, True) vbox.show_all() controls.main_window.add(vbox) def set_visible_search_panel(self, flag=True): LOG.info("set_visible_search_panel", flag) if flag: self.controls.searchPanel.show_all() self.controls.search_progress.hide() else: self.controls.searchPanel.hide() def set_visible_musictree_panel(self, flag): LOG.info("set_visible_musictree_panel", flag) if flag: self.hpaned_left.set_position(FC().hpaned_left) else: self.hpaned_left.set_position(0) def set_visible_info_panel(self, flag): LOG.info("set_visible_info_panel", flag) if flag: self.hpaned_right.set_position(FC().hpaned_right) else: self.hpaned_right.set_position(9999) def on_save(self, *a): if FC().is_view_music_tree_panel: FC().hpaned_left = self.hpaned_left.get_position() if FC().is_view_info_panel: FC().hpaned_right = self.hpaned_right.get_position() def on_load(self): self.controls.search_progress.hide() self.hpaned_left.set_position(FC().hpaned_left) self.hpaned_right.set_position(FC().hpaned_right) self.set_visible_musictree_panel(FC().is_view_music_tree_panel) self.set_visible_info_panel(FC().is_view_info_panel) self.set_visible_search_panel(FC().is_view_search_panel)
Python
# ~*~ coding:utf-8 ~*~ # from mutagen.mp3 import MP3 from mutagen.easyid3 import EasyID3 import os from foobnix.util.time_utils import normilize_time from foobnix.util import LOG def decode_cp866(text): try: decode_text = text.decode("cp866") if decode_text.find(u"├") >= 0 : #LOG.warn("File tags encoding is very old cp866") text = decode_text.replace( u"\u252c", u'ё').replace( u"├", "").replace( u"░", u"р").replace( u"▒", u"с").replace( u"▓", u"т").replace( u"│", u"у").replace( u"┤", u"ф").replace( u"╡", u"х").replace( u"╢", u"ц").replace( u"╖", u"ч").replace( u"╕", u"ш").replace( u"╣", u"щ").replace( u"║", u"ъ").replace( u"╗", u"ы").replace( u"╝", u"ь").replace( u"╜", u"э").replace( u"╛", u"ю").replace( u"┐", u"я") #fix ёш to ё text = text.replace(u'\u0451\u0448', u'\u0451') except: pass return text def udpate_id3(bean): if bean and bean.path and os.path.isfile(bean.path): path_lower = bean.path.lower() audio = None if path_lower.endswith(".mp3"): try: audio = MP3(bean.path, ID3=EasyID3) except Exception, e: LOG.error("ID3 NOT MP3", e, bean.path) return bean if audio and audio.has_key('artist'): bean.artist = decode_cp866(audio["artist"][0]) if audio and audio.has_key('title'): bean.title = decode_cp866(audio["title"][0]) if audio and audio.has_key('tracknumber'): bean.tracknumber = audio["tracknumber"][0] if audio.info and audio.info.length: bean.length = int(audio.info.length) if audio.info: bean.info = audio.info.pprint() if bean.artist and bean.title: bean.text = bean.artist + " - " + bean.title if bean.tracknumber and bean.tracknumber.find("/") >= 0: bean.tracknumber = bean.tracknumber[:bean.tracknumber.find("/")] if bean.tracknumber and bean.tracknumber.startswith("0"): bean.tracknumber = bean.tracknumber[1:] if bean.tracknumber: try: bean.tracknumber = int(bean.tracknumber) except: bean.tracknumber = "" bean.time = normilize_time(bean.length) return bean def update_all_id3(beans): result = [] for bean in beans: result.append(udpate_id3(bean)) return result
Python
#-*- coding: utf-8 -*- from foobnix.regui.notetab import NoteTabControl from foobnix.regui.base_layout import BaseFoobnixLayout from foobnix.regui.base_controls import BaseFoobnixControls from foobnix.regui.treeview.musictree import MusicTreeControl from foobnix.regui.window import MainWindow from foobnix.regui.controls.filter import FilterControl from foobnix.regui.controls.playback import PlaybackControls from foobnix.regui.search import SearchControls from foobnix.regui.controls.seach_progress import SearchProgressBar from foobnix.regui.infopanel import InfoPanelWidget from foobnix.regui.engine.gstreamer import GStreamerEngine from foobnix.regui.controls.seekbar import SeekProgressBarControls from foobnix.regui.controls.volume import VolumeControls from foobnix.regui.controls.status_bar import StatusbarControls from foobnix.regui.treeview.radiotree import RadioTreeControl from foobnix.regui.treeview.virtualtree import VirtualTreeControl from foobnix.regui.controls.tray_icon import TrayIconControls from foobnix.preferences.preferences_window import PreferencesWindow from foobnix.regui.top import TopWidgets from foobnix.eq.eq_gui import EQContols from foobnix.regui.controls.dbus_manager import DBusManager from foobnix.dm.dm_gui import DownloadManager class FoobnixCore(BaseFoobnixControls): def __init__(self): BaseFoobnixControls.__init__(self) self.media_engine = GStreamerEngine(self) """elements""" self.preferences = PreferencesWindow(self) self.statusbar = StatusbarControls(self) self.volume = VolumeControls(self) self.seek_bar = SeekProgressBarControls(self) self.search_progress = SearchProgressBar(self) self.info_panel = InfoPanelWidget(self) self.trayicon = TrayIconControls(self) self.trayicon.show() self.searchPanel = SearchControls(self) self.playback = PlaybackControls(self) self.main_window = MainWindow(self) self.notetabs = NoteTabControl(self) self.filter = FilterControl(self) self.tree = MusicTreeControl(self) self.radio = RadioTreeControl(self) self.virtual = VirtualTreeControl(self) self.eq = EQContols(self) self.dm = DownloadManager(self) """layout panels""" self.top_panel = TopWidgets(self) """layout""" self.layout = BaseFoobnixLayout(self) """D-Bus""" self.dbus = DBusManager(self) self.on_load()
Python
#-*- coding: utf-8 -*- ''' Created on 22 сент. 2010 @author: ivan ''' import gtk from foobnix.regui.menu import MenuWidget from foobnix.helpers.toolbar import ToolbarSeparator from foobnix.regui.model.signal import FControl from foobnix.regui.state import LoadSave class TopWidgets(FControl, LoadSave,gtk.HBox): def __init__(self, controls): FControl.__init__(self, controls) gtk.HBox.__init__(self,False, 0) self.menu = MenuWidget(controls) sep = ToolbarSeparator() self.pack_start(self.menu.widget, False, False) self.pack_start(controls.playback, False, False) self.pack_start(controls.volume, False, False) self.pack_start(sep, False, False) self.pack_start(controls.seek_bar, True, True) self.show_all() def on_save(self): self.controls.volume.on_save() self.menu.on_save() def on_load(self): self.controls.volume.on_load() self.menu.on_load()
Python
''' Created on Sep 23, 2010 @author: ivan ''' import gtk from foobnix.regui.state import LoadSave from foobnix.util.fc import FC from foobnix.regui.model.signal import FControl from foobnix.regui.treeview.simple import SimpleTreeControl from foobnix.helpers.image import CoverImage class InfoPanelWidget(gtk.Frame, LoadSave, FControl): def __init__(self, controls): gtk.Frame.__init__(self) FControl.__init__(self, controls) self.almum_label = gtk.Label() self.almum_label.set_line_wrap(True) self.almum_label.set_markup("<b></b>") self.set_label_widget(self.almum_label) self.set_shadow_type(gtk.SHADOW_NONE) self.vpaned_small = gtk.VPaned() """image and similar artists""" ibox = gtk.HBox(False, 0) self.image = CoverImage() self.artists = SimpleTreeControl("Similar Artist", controls).set_scrolled(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) ibox.pack_start(self.image, False, False) ibox.pack_start(self.artists.scroll, True, True) """image and similar artists""" sbox = gtk.HBox(False, 0) self.tracks = SimpleTreeControl("Similar Songs", controls).set_scrolled(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.tags = SimpleTreeControl("Similar Tags", controls).set_scrolled(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) sbox.pack_start(self.tracks.scroll, True, True) sbox.pack_start(self.tags.scroll, True, True) self.vpaned_small.pack1(ibox, False, False) self.vpaned_small.pack2(sbox, True, True) self.add(self.vpaned_small) self.show_all() def update(self, bean): return print "update info panel", bean """update info""" album_name = self.controls.lastfm.get_album_name(bean.artist, bean.title) album_year = self.controls.lastfm.get_album_year(bean.artist, bean.title) if album_year: self.almum_label.set_markup("<b>%s - %s (%s) - %s</b>" % (bean.artist, album_name, album_year, bean.title)) else: self.almum_label.set_markup("<b>%s - %s - %s</b>" % (bean.artist, album_name, bean.title)) """update image""" if bean.image: self.image.set_image_from_path(bean.image) else: url = self.controls.lastfm.get_album_image_url(bean.artist, bean.title) if url: self.image.set_image_from_url(url) else: self.image.set_no_image() """similar artists""" similar_artists = self.controls.lastfm.search_top_similar_artist(bean.artist) self.artists.populate(similar_artists) """similar songs""" similar_tracks = self.controls.lastfm.search_top_similar_tracks(bean.artist, bean.title) self.tracks.populate(similar_tracks) """similar tags""" similar_tags = self.controls.lastfm.search_top_similar_tags(bean.artist, bean.title) self.tags.populate(similar_tags) def on_load(self): self.vpaned_small.set_position(FC().vpaned_small) def on_save(self): FC().vpaned_small = self.vpaned_small.get_position()
Python
#-*- coding: utf-8 -*- ''' Created on 25 сент. 2010 @author: ivan ''' import gtk from foobnix.regui.model.signal import FControl from foobnix.regui.state import LoadSave from foobnix.util.fc import FC from foobnix.util import const class MainWindow(gtk.Window, FControl, LoadSave): def __init__(self, controls): FControl.__init__(self, controls) gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) self.set_title("Foobnix Music Player by assistent") self.set_position(gtk.WIN_POS_CENTER) self.set_resizable(True) self.connect("delete-event", self.hide_window) self.connect("configure-event", self.on_configure_event) self.set_icon(self.controls.trayicon.get_pixbuf()) def on_configure_event(self, w, e): FC().main_window_size = [e.x, e.y, e.width, e.height] def on_save(self, *a): pass def on_load(self): cfg = FC().main_window_size if cfg: self.set_default_size(cfg[2], cfg[3]) self.move(cfg[0], cfg[1]) def hide_window(self, *args): gtk.main_quit() if FC().on_close_window == const.ON_CLOSE_CLOSE: self.destroy() elif FC().on_close_window == const.ON_CLOSE_HIDE: self.hide() elif FC().on_close_window == const.ON_CLOSE_MINIMIZE: self.iconify() return True
Python
#-*- coding: utf-8 -*- ''' Created on 25 сент. 2010 @author: ivan ''' import gtk from foobnix.util.fc import FC from foobnix.util import LOG from foobnix.regui.state import LoadSave from foobnix.regui.treeview.scanner import DirectoryScanner from foobnix.regui.id3 import update_all_id3 import os from foobnix.regui.model import FModel from foobnix.regui.service.lastfm_service import LastFmService from foobnix.util.singe_thread import SingreThread from foobnix.regui.service.vk_service import VKService from foobnix.util.plsparser import get_radio_source from foobnix.radio.radios import RadioFolder class BaseFoobnixControls(LoadSave): def __init__(self): self.lastfm = LastFmService() self.vk = VKService() self.count_errors = 0 self.is_radio_populated = False pass def set_playlist_tree(self): self.notetabs.set_playlist_tree() def set_playlist_plain(self): self.notetabs.set_playlist_plain() def load_music_tree(self): if FC().cache_music_tree_beans: self.tree.populate_from_scanner(FC().cache_music_tree_beans) LOG.info("Tree loaded from cache") else: self.update_music_tree() LOG.info("Tree updated") def update_music_tree(self): LOG.info("Update music tree", FC().music_paths) self.tree.clear() FC().cache_music_tree_beans = [] for path in FC().music_paths: scan = DirectoryScanner(path) all = scan.get_music_results() for bean in all: FC().cache_music_tree_beans.append(bean) self.tree.append_from_scanner(all) def update_radio_tree(self): if self.is_radio_populated: return True LOG.info("Update radio tree") self.radio_folder = RadioFolder() files = self.radio_folder.get_radio_FPLs() for fpl in files: parent = FModel(fpl.name).add_font("bold").add_is_file(False) parentIter = self.radio.append(parent) for radio, urls in fpl.urls_dict.iteritems(): child = FModel(radio, urls[0]).add_font("").add_level(parentIter).add_is_file(True) self.radio.append(child) self.is_radio_populated = True def set_visible_search_panel(self, flag): self.layout.set_visible_search_panel(flag) def set_visible_musictree_panel(self, flag): self.layout.set_visible_musictree_panel(flag) def set_visible_info_panel(self, flag): self.layout.set_visible_info_panel(flag) def volume_up(self): pass def volume_down(self): pass def windows_visibility(self): visible = self.main_window.get_property('visible') if visible: self.main_window.hide() else: self.main_window.show() def state_play(self): self.media_engine.state_play() def show_preferences(self): self.preferences.show() def state_pause(self): self.media_engine.state_pause() def state_stop(self): self.media_engine.state_stop() def state_play_pause(self): self.media_engine.state_play_pause() def play(self, bean): if not bean: return None if not bean.path: if not bean.artist or not bean.title: vk = self.vk.find_one_track(bean.artist + " - " + bean.title) else: vk = self.vk.find_one_track(bean.text) if vk: bean.path = vk.path bean.time = vk.time else: if self.count_errors < 4: self.next() self.count_errors += 1 else: bean.path = get_radio_source(bean.path) self.media_engine.play(bean) print "!!!!!!", bean.info self.count_errors = 0 self.statusbar.set_text(bean.info) self.trayicon.set_text(bean.text) def notify_playing(self, pos_sec, dur_sec): self.seek_bar.update_seek_status(pos_sec, dur_sec) def notify_title(self, text): self.seek_bar.set_text(text) def notify_eos(self): self.next() def player_seek(self, percent): self.media_engine.seek(percent) def player_volue(self, percent): self.media_engine.volume(percent) def search_all_tracks(self, query): def inline(query): results = self.vk.find_tracks_by_query(query) all = [] all.append(FModel(query).add_font("bold")) for i, bean in enumerate(results): bean.tracknumber = i + 1 all.append(bean) self.notetabs.append_tab(query, all) self.singre_thread.run_with_text(inline, query, "Searching: " + query) def search_top_tracks(self, query): def inline(query): results = self.lastfm.search_top_tracks(query) all = [] all.append(FModel(query).add_font("bold")) for i, bean in enumerate(results): bean.tracknumber = i + 1 all.append(bean) self.notetabs.append_tab(query, all) self.singre_thread.run_with_text(inline, query, "Searching: " + query) def search_top_albums(self, query): def inline(query): results = self.lastfm.search_top_albums(query) self.notetabs.append_tab(query, None) for album in results[:5]: all = [] album.add_font("bold") all.append(album) tracks = self.lastfm.search_album_tracks(album.artist, album.album) for i, track in enumerate(tracks): track.tracknumber = i + 1 all.append(track) self.notetabs.append(all) #inline(query) #self.singre_thread.run(inline, query) self.singre_thread.run_with_text(inline, query, "Searching: " + query) def search_top_similar(self, query): def inline(query): results = self.lastfm.search_top_similar_artist(query) self.notetabs.append_tab(query, None) for artist in results[:5]: all = [] artist.add_font("bold") all.append(artist) tracks = self.lastfm.search_top_tracks(artist.artist) for i, track in enumerate(tracks): track.tracknumber = i + 1 all.append(track) self.notetabs.append(all) #inline(query) self.singre_thread.run_with_text(inline, query, "Searching: " + query) def search_top_tags(self, query): def inline(query): results = self.lastfm.search_top_tags(query) self.notetabs.append_tab(query, None) for tag in results[:5]: all = [] tag.add_font("bold") all.append(tag) tracks = self.lastfm.search_top_tag_tracks(tag.text) for i, track in enumerate(tracks): track.tracknumber = i + 1 all.append(track) self.notetabs.append(all) #inline(query) self.singre_thread.run_with_text(inline, query, "Searching: " + query) def update_info_panel(self, bean): #self.info_panel.update(bean) self.singre_thread.run_with_text(self.info_panel.update, bean, "Updating info panel") def append_to_new_notebook(self, text, beans): path = beans[0].path if os.path.isdir(path): scanner = DirectoryScanner(beans[0].path) results = scanner.get_music_file_results() results = update_all_id3(results) self.notetabs.append_tab(text, results) else: self.notetabs.append_tab(text, [beans[0]]) def append_to_current_notebook(self, beans): bean = beans[0] if bean.is_file: self.notetabs.append([beans[0]]) else: scanner = DirectoryScanner(beans[0].path) results = scanner.get_music_file_results() results = update_all_id3(results) self.notetabs.append(results) def next(self): bean = self.notetabs.next() self.play(bean) def prev(self): bean = self.notetabs.prev() self.play(bean) def filter_tree(self, value): self.tree.filter(value) self.radio.filter(value) def quit(self, *a): LOG.info("Controls - Quit") self.on_save() FC().save() gtk.main_quit() def set_playback_random(self, flag): self.notetabs.set_random(flag) def set_lopping_all(self): self.notetabs.set_lopping_all() def set_lopping_single(self): self.notetabs.set_lopping_single() def set_lopping_disable(self): self.notetabs.set_lopping_disable() def on_load(self): for element in self.__dict__: if isinstance(self.__dict__[element], LoadSave): self.__dict__[element].on_load() else: LOG.debug("NOT LOAD", self.__dict__[element]) self.singre_thread = SingreThread(self.search_progress) self.main_window.show() def on_save(self): for element in self.__dict__: if isinstance(self.__dict__[element], LoadSave): self.__dict__[element].on_save() else: LOG.debug("NOT SAVE", self.__dict__[element])
Python
#-*- coding: utf-8 -*- ''' Created on 22 сент. 2010 @author: ivan ''' import gtk from foobnix.helpers.toggled import OneActiveToggledButton from foobnix.regui.model.signal import FControl from foobnix.regui.state import LoadSave class LeftWidgets(FControl, LoadSave, gtk.VBox): def __init__(self, controls): FControl.__init__(self, controls) gtk.VBox.__init__(self, False, 0) controls.tree.set_scrolled(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) controls.radio.set_scrolled(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) controls.virtual.set_scrolled(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) buttons = PerspectiveButtonControlls(controls) buttons.show_all() self.pack_start(controls.tree.scroll, True, True) self.pack_start(controls.radio.scroll, True, True) self.pack_start(controls.virtual.scroll, True, True) self.pack_start(controls.filter, False, False) self.pack_start(buttons, False, False) self.show_all() def on_load(self): pass def on_save(self): pass class PerspectiveButtonControlls(FControl, gtk.HBox): def __init__(self, controls): FControl.__init__(self, controls) gtk.HBox.__init__(self, False, 0) musics = self.custom_button("Music", gtk.STOCK_HARDDISK) musics.connect("clicked", self.on_change_perspective, controls.tree) musics.set_active(True) radios = self.custom_button("Radio", gtk.STOCK_NETWORK) radios.connect("clicked", self.on_change_perspective, controls.radio) radios.connect("clicked", lambda * a: controls.update_radio_tree()) virtuals = self.custom_button("Lists", gtk.STOCK_INDEX) virtuals.connect("clicked", self.on_change_perspective, controls.virtual) self.button_list = [musics, radios, virtuals] OneActiveToggledButton(self.button_list) self.pack_start(musics, False, False, 0) self.pack_start(radios, False, False, 0) self.pack_start(virtuals, False, False, 0) def on_change_perspective(self, w, perspective): self.controls.tree.scroll.hide() self.controls.radio.scroll.hide() self.controls.virtual.scroll.hide() perspective.scroll.show() def custom_button(self, title, gtk_stock, func=None, param=None): button = gtk.ToggleButton(title) if param and func: button.connect("toggled", lambda * a: func(param)) elif func: button.connect("toggled", lambda * a: func()) button.set_relief(gtk.RELIEF_NONE) label = button.get_child() button.remove(label) vbox = gtk.VBox(False, 0) img = gtk.image_new_from_stock(gtk_stock, gtk.ICON_SIZE_MENU) vbox.add(img) vbox.add(gtk.Label(title)) vbox.show_all() button.add(vbox) return button
Python
''' Created on Mar 14, 2010 @author: ivan ''' import gtk from foobnix.window.window_controller import WindowController from foobnix.player.player_controller import PlayerController from foobnix.player.player_widgets_cntr import PlayerWidgetsCntl from foobnix.directory.directory_controller import DirectoryCntr from foobnix.trayicon import TrayIcon from foobnix.application.app_configuration_controller import AppConfigurationCntrl from foobnix.online.online_controller import OnlineListCntr from foobnix.directory.virtuallist_controller import VirturalLIstCntr from foobnix.base import BaseController from foobnix.util.configuration import FConfiguration, VERSION from foobnix.online.search_panel import SearchPanel from foobnix.preferences.preferences_window import PreferencesWindow import sys from foobnix.online.integration.lastfm import LastFmConnector from socket import gethostname import urllib2 from foobnix.helpers.dialog_entry import info_dialog_with_link from foobnix.util import LOG from foobnix.model.entity import CommonBean class AppController(BaseController): def __init__(self, v): BaseController.__init__(self) last_fm_connector = LastFmConnector() self.player_controller = PlayerController(last_fm_connector) #self.playlistCntr = PlaylistCntr(v.playlist, self.player_controller) self.onlineCntr = OnlineListCntr(v.gxMain, self.player_controller, last_fm_connector) self.playlistCntr = self.onlineCntr self.virtualListCntr = VirturalLIstCntr() #self.radioListCntr = RadioListCntr(v.gxMain, self.player_controller) self.playerWidgets = PlayerWidgetsCntl(v.gxMain, self.player_controller) self.player_controller.registerWidgets(self.playerWidgets) self.player_controller.registerPlaylistCntr(self.playlistCntr) self.directoryCntr = DirectoryCntr(v.gxMain, self.playlistCntr, self.virtualListCntr) #self.playlistCntr.registerDirectoryCntr(self.directoryCntr) self.appConfCntr = AppConfigurationCntrl(v.gxMain, self.directoryCntr) self.onlineCntr.register_directory_cntr(self.directoryCntr) self.player_controller.registerOnlineCntr(self.onlineCntr) self.main_window_controller = WindowController(v.gxMain, v.gxAbout) """show pref window""" menu_preferences = v.gxMain.get_widget("menu_preferences") menu_preferences.connect("activate", lambda * a:self.pref.show()) self.tray_icon = TrayIcon(v.gxTrayIcon) self.main_window_controller.tray_icon = self.tray_icon self.tray_icon.connect('toggle_window_visibility', self.main_window_controller.toggle_visibility) self.tray_icon.connect('exit', self.exit) self.tray_icon.connect('play', self.player_controller.play) self.tray_icon.connect('pause', self.player_controller.pause) self.tray_icon.connect('prev', self.player_controller.prev) self.tray_icon.connect('next', self.player_controller.next) self.tray_icon.connect('volume_up', self.player_controller.volume_up) self.tray_icon.connect('volume_down', self.player_controller.volume_down) self.player_controller.connect('song_playback_started', self.tray_icon.on_song_started) self.player_controller.connect('song_playback_started', self.main_window_controller.on_song_started) self.main_window_controller.connect('exit', self.exit) self.search_panel = SearchPanel(v.gxMain, last_fm_connector) self.search_panel.connect('show_search_results', self.onlineCntr.show_results) self.search_panel.connect('show_searching_line', self.onlineCntr.show_searching) self.pref = PreferencesWindow(self.directoryCntr, self.onlineCntr, self.tray_icon) last_fm_connector.preferences_window = self.pref self.restore_state() """paly music via arguments""" self.play_arguments(sys.argv) self.main_window_controller.show() """enable proxy""" self.check_version() def check_version(self): uuid = FConfiguration().uuid current_version = VERSION try: f = urllib2.urlopen("http://www.foobnix.com/version?uuid=" + uuid + "&host=" + gethostname()) except: return None new_version = f.read() LOG.info("versions", current_version , "|", new_version, "|") f.close() if FConfiguration().check_new_version and current_version < new_version: info_dialog_with_link(_("New version is available"), "foobnix " + new_version, "http://www.foobnix.com/?page=download") #self.setStatusText(_("New version ")+new_version+_(" avaliable at www.foobnix.com")); def action_command(self, args): if args: if len(args) == 1: command = args[0] elif len(args) == 2: command = args[1] else: return None if "--next" == command: self.player_controller.next() elif "--prev" == command: self.player_controller.prev() elif "--stop" == command: self.player_controller.stopState() elif "--pause" == command: self.player_controller.pauseState() elif "--play" == command: self.player_controller.playState() elif "--volume-up" == command: self.player_controller.volume_up() elif "--volume-down" == command: self.player_controller.volume_down() elif "--show-hide" == command: self.main_window_controller.toggle_visibility() elif "--play-pause" == command: if self.player_controller.is_state_playing(): self.player_controller.pauseState() else: self.player_controller.playState() return True return False def play_arguments(self, args): #gtk.gdk.threads_leave() gtk.gdk.threads_enter() #@UndefinedVariable if not self.action_command(args): self.main_window_controller.show() self.onlineCntr.on_play_argumens(args) gtk.gdk.threads_leave() def exit(self, *a): self.main_window_controller.hide() self.save_state() gtk.main_quit() def restore_state(self): if FConfiguration().playlistState: self.playlistCntr.setState(FConfiguration().playlistState) if FConfiguration().virtualListState: self.directoryCntr.setState(FConfiguration().virtualListState) if FConfiguration().volumeValue: self.playerWidgets.volume.set_value(FConfiguration().volumeValue) self.player_controller.setVolume(FConfiguration().volumeValue / 100) if FConfiguration().radiolistState: self.radioListCntr.setState(FConfiguration().radiolistState) if FConfiguration().save_tabs: self.onlineCntr.append_notebook_page(FConfiguration().last_notebook_page) bean = CommonBean(type=CommonBean.TYPE_MUSIC_FILE) if FConfiguration().last_notebook_beans and FConfiguration().last_play_bean: try: bean = FConfiguration().last_notebook_beans[FConfiguration().last_play_bean] except IndexError: bean = FConfiguration().last_notebook_beans[0] FConfiguration().last_play_bean = 0 """auto play last song on start, but do not play radio, it's buggy""" if FConfiguration().play_on_start and bean.type != CommonBean.TYPE_RADIO_URL: self.onlineCntr.append_and_play(FConfiguration().last_notebook_beans, FConfiguration().last_play_bean) else: self.onlineCntr.append(FConfiguration().last_notebook_beans) self.main_window_controller.on_load() def save_state(self): FConfiguration().last_notebook_page = self.onlineCntr.last_notebook_page FConfiguration().last_notebook_beans = self.onlineCntr.last_notebook_beans FConfiguration().last_play_bean = self.onlineCntr.index FConfiguration().playlistState = self.playlistCntr.getState() FConfiguration().virtualListState = self.directoryCntr.getState() #FConfiguration().radiolistState = self.radioListCntr.getState() FConfiguration().volumeValue = self.playerWidgets.volume.get_value() if self.playerWidgets.vpanel.get_position() > 0: FConfiguration().vpanelPostition = self.playerWidgets.vpanel.get_position() if self.playerWidgets.hpanel.get_position() > 0: FConfiguration().hpanelPostition = self.playerWidgets.hpanel.get_position() if self.playerWidgets.hpanel2.get_position() > 0 and not self.playerWidgets.hpanel2.max_pos: FConfiguration().hpanel2Postition = self.playerWidgets.hpanel2.get_position() self.main_window_controller.on_save() FConfiguration().save()
Python
''' Created on Mar 14, 2010 @author: ivan ''' import gtk.glade import sys from foobnix.util import LOG from foobnix.util.configuration import get_version import os class AppView(): gladeMain = "foobnix/glade/foobnix.glade" def __init__(self): self.gxMain = self.glade_XML(self.gladeMain, "foobnixWindow") self.gxTrayIcon = self.glade_XML(self.gladeMain, "popUpWindow") self.gxAbout = self.glade_XML(self.gladeMain, "aboutdialog") self.about_widget = self.gxAbout.get_widget("aboutdialog") self.about_widget.set_version(get_version()) self.about_widget.connect("response", lambda * a: self.about_widget.hide()) self.playlist = self.gxMain.get_widget("playlist_treeview") def close_dialog(self): pass def glade_XML(self, main, widget): if os.path.isfile(main): LOG.info("Find glade in current folder", main) return gtk.glade.XML(main, widget, "foobnix") for path in sys.path: full_path = os.path.join(path, main) if os.path.isfile(full_path): LOG.info("Find glade in the folder", full_path) return gtk.glade.XML(os.path.join(path, main), widget, "foobnix") LOG.error("Can't find glade file!!!");
Python
''' Created on Mar 14, 2010 @author: ivan ''' from foobnix.util.configuration import FConfiguration from foobnix.util import LOG class AppConfigurationCntrl(): def __init__(self, gxMain, directoryCntr): self.directoryCntr = directoryCntr ''''' """Random button""" self.randomCheckButton = gxMain.get_widget("random_checkbutton") self.randomCheckButton.set_active(FConfiguration().isRandom) self.randomCheckButton.connect("clicked", self.onRandomClicked) """Repeat button""" self.repeatCheckButton = gxMain.get_widget("repeat_checkbutton") self.repeatCheckButton.set_active(FConfiguration().isRepeat) self.repeatCheckButton.connect("clicked", self.onRepeatClicked) """Play on Start""" self.playOnStartCheckButton = gxMain.get_widget("playonstart_checkbutton") self.playOnStartCheckButton.set_active(FConfiguration().isPlayOnStart) self.playOnStartCheckButton.connect("clicked", self.onPlayOnStartClicked) ''''' def onPlayOnStartClicked(self, *args): FConfiguration().isPlayOnStart = self.playOnStartCheckButton.get_active() def onRepeatClicked(self, *args): FConfiguration().isRepeat = self.repeatCheckButton.get_active() def onRandomClicked(self, *args): FConfiguration().isRandom = self.randomCheckButton.get_active()
Python
''' Created on Mar 13, 2010 @author: ivan ''' import gtk import os.path from foobnix.base import BaseController from foobnix.base import SIGNAL_RUN_FIRST, TYPE_NONE from foobnix.util.mouse_utils import is_mouse_click from foobnix.util.configuration import FConfiguration class TrayIcon(BaseController): """ A class that represents tray icon and a widget that pops up when the icon is right-clicked. """ _BASIC_SIGNAL = (SIGNAL_RUN_FIRST, TYPE_NONE, ()) __gsignals__ = { 'exit' : _BASIC_SIGNAL, 'toggle_window_visibility' : _BASIC_SIGNAL, 'play' : _BASIC_SIGNAL, 'pause' : _BASIC_SIGNAL, 'next' : _BASIC_SIGNAL, 'prev' : _BASIC_SIGNAL, 'volume_up' : _BASIC_SIGNAL, 'volume_down' : _BASIC_SIGNAL } def __init__(self, gx_tray_icon): BaseController.__init__(self) self.popup = gx_tray_icon.get_widget("popUpWindow") toolbar = gx_tray_icon.get_widget("vbox1") #toolbar.connect("leave-notify-event", self.on_leave_window) text = gx_tray_icon.get_widget("text1") #text.connect("leave-notify-event", self.on_leave_window) self.popup.connect("leave-notify-event", self.on_leave_window) self.text1 = gx_tray_icon.get_widget("text1") self.text2 = gx_tray_icon.get_widget("text2") self.icon = gtk.StatusIcon() self.icon.set_tooltip("Foobnix music player") # TODO: move the path to config icon_path = "/usr/local/share/pixmaps/foobnix.png" icon_path2 = "/usr/share/pixmaps/foobnix.png" if os.path.exists(icon_path): self.icon.set_from_file(icon_path) elif os.path.exists(icon_path2): self.icon.set_from_file(icon_path2) else: self.icon.set_from_stock("gtk-media-play") self.icon.connect("activate", lambda * a: self.emit('toggle_window_visibility')) self.icon.connect("popup-menu", lambda * a: self.popup.show()) try: self.icon.connect("button-press-event", self.on_button_press) self.icon.connect("scroll-event", self.on_mouse_wheel_scrolled) except: pass popup_signals = { "on_close_clicked" : lambda * a: self.emit('exit'), "on_play_clicked" : lambda * a: self.emit('play'), "on_pause_clicked" : lambda * a: self.emit('pause'), "on_next_clicked" : lambda * a: self.emit('next'), "on_prev_clicked" : lambda * s: self.emit('prev'), "on_cancel_clicked": lambda * a: self.popup.hide() } gx_tray_icon.signal_autoconnect(popup_signals) self.paused = False if FConfiguration().show_tray_icon: self.show() else: self.hide() def on_leave_window(self, w, event): max_x, max_y = w.size_request() x, y = event.x, event.y if 0 < x < max_x and 0 < y < max_y: return True if not FConfiguration().tray_icon_auto_hide: return True self.popup.hide() def show(self): self.icon.set_visible(True) def hide(self): self.icon.set_visible(False) def on_button_press(self, w, e): if is_mouse_click(e): self.paused = not self.paused if self.paused: self.emit('pause') else: self.emit('play') def setText1(self, text): self.text1.set_text(text) def setText2(self, text): self.text2.set_text(text) def on_song_started(self, sender, song): self.setText1(song.name[:50]) self.icon.set_tooltip(song.name) def on_mouse_wheel_scrolled(self, w, event): if event.direction == gtk.gdk.SCROLL_UP: #@UndefinedVariable self.emit('volume_up') else: self.emit('volume_down') # TODO: move next line to player_controller # self.playerWidgets.volume.set_value(volume * 100)
Python
''' Created on Mar 13, 2010 @author: ivan ''' import gtk from foobnix.util.configuration import VERSION, FConfiguration from foobnix.base import BaseController from foobnix.base import SIGNAL_RUN_FIRST, TYPE_NONE from foobnix.util import const class WindowController(BaseController): __gsignals__ = { 'exit' : (SIGNAL_RUN_FIRST, TYPE_NONE, ()), 'show_preferences' : (SIGNAL_RUN_FIRST, TYPE_NONE, ()), } def __init__(self, gx_main_window, gx_about): BaseController.__init__(self) self.decorate(gx_main_window) popup_signals = { "on_gtk-preferences_activate": lambda * a: self.emit('show_preferences'), "on_file_quit_activate": lambda * a: self.emit('exit'), "on_menu_about_activate": self.show_about_window } gx_main_window.signal_autoconnect(popup_signals) self.main_window = gx_main_window.get_widget("foobnixWindow") self.main_window.connect("delete-event", self.hide) self.main_window.set_title("Foobnix " + VERSION) self.main_window.connect("window-state-event", self.window_state_event_cb) self.main_window.connect("configure-event", self.on_configure_event) #self.main_window.maximize() self.about_window = gx_about.get_widget("aboutdialog") self.about_window.connect("delete-event", self.hide_about_window) self.tray_icon = None self.configure_state = None def on_load(self): cfg = FConfiguration().configure_state if cfg: print cfg self.main_window.move(cfg[0], cfg[1]) self.main_window.set_default_size(cfg[2], cfg[3]) def on_save(self): FConfiguration().configure_state = self.configure_state def on_configure_event(self, w, e): self.configure_state = [e.x, e.y, e.width, e.height] def on_song_started(self, sender, song): self.main_window.set_title(song.getTitleDescription()) def show_about_window(self, *args): self.about_window.show() def hide_about_window(self, *args): self.about_window.hide() return True def destroy(self): self.main_window.hide() FConfiguration().save() gtk.main_quit() def maximize(self): self.main_window.maximize() def show(self): self.main_window.show() def window_state_event_cb(self, w, event): print event print event.new_window_state print event.changed_mask def hide(self, *args): if FConfiguration().on_close_window == const.ON_CLOSE_CLOSE: self.destroy() elif FConfiguration().on_close_window == const.ON_CLOSE_HIDE: self.main_window.hide() elif FConfiguration().on_close_window == const.ON_CLOSE_MINIMIZE: self.main_window.iconify() return True def toggle_visibility(self, *a): visible = self.main_window.get_property('visible') if visible: self.main_window.hide() else: self.main_window.show() def decorate(self, gx): rc_st = ''' style "menubar-style" { GtkMenuBar::shadow_type = none GtkMenuBar::internal-padding = 0 } class "GtkMenuBar" style "menubar-style" ''' gtk.rc_parse_string(rc_st) style = gx.get_widget("label6").get_style() background_color = style.bg[gtk.STATE_NORMAL] text_color = style.fg[gtk.STATE_NORMAL] menu_bar = gx.get_widget("menubar3") menu_bar.modify_bg(gtk.STATE_NORMAL, background_color) # making main menu look a bit better for item in menu_bar.get_children(): current = item.get_children()[0] current.modify_fg(gtk.STATE_NORMAL, text_color)
Python
#!/usr/bin/env python import sys, os, glob, shutil from distutils.core import setup from foobnix.util.configuration import VERSION, FOOBNIX_TMP, FOOBNIX_TMP_RADIO root_dir = '' for a in sys.argv[1:]: if a.find('--root') == 0: root_dir = a[7:] print "RADIO", FOOBNIX_TMP, FOOBNIX_TMP_RADIO if not os.path.exists(os.path.dirname(root_dir) + FOOBNIX_TMP): os.mkdir(os.path.dirname(root_dir) + FOOBNIX_TMP) if not os.path.exists(os.path.dirname(root_dir) + FOOBNIX_TMP_RADIO): os.mkdir(os.path.dirname(root_dir) + FOOBNIX_TMP_RADIO) def capture(cmd): return os.popen(cmd).read().strip() def removeall(path): if not os.path.isdir(path): return files = os.listdir(path) for x in files: fullpath = os.path.join(path, x) if os.path.isfile(fullpath): f = os.remove rmgeneric(fullpath, f) elif os.path.isdir(fullpath): removeall(fullpath) f = os.rmdir rmgeneric(fullpath, f) def rmgeneric(path, __func__): try: __func__(path) except OSError, (errno, strerror): pass # Create mo files: if not os.path.exists("mo/"): os.mkdir("mo/") for lang in ('ru', 'uk', 'he'): pofile = "po/" + lang + ".po" mofile = "mo/" + lang + "/foobnix.mo" if not os.path.exists("mo/" + lang + "/"): os.mkdir("mo/" + lang + "/") print "generating", mofile os.system("msgfmt %s -o %s" % (pofile, mofile)) # Copy script "foobnix" file to foobnix dir: shutil.copyfile("foobnix.py", "foobnix/foobnix") versionfile = file("foobnix/version.py", "wt") versionfile.write(""" # generated by setup.py VERSION = %r """ % VERSION) versionfile.close() setup(name='foobnix', version=VERSION, description='GTK+ client for the Music Player Daemon (MPD).', author='Ivan Ivanenko', author_email='ivan.ivanenko@gmail.com', url='www.foobnix.com', classifiers=[ 'Development Status :: Beta', 'Environment :: X11 Applications', 'Intended Audience :: End Users/Desktop', 'License :: GNU General Public License (GPL)', 'Operating System :: Linux', 'Programming Language :: Python', 'Topic :: Multimedia :: Sound :: Players', ], packages=[ "foobnix", "foobnix.application", "foobnix.base", "foobnix.cue", "foobnix.directory", "foobnix.eq", "foobnix.glade", "foobnix.helpers", "foobnix.lyric", "foobnix.model", "foobnix.online", "foobnix.online.google", "foobnix.online.integration", "foobnix.player", "foobnix.playlist", "foobnix.preferences", "foobnix.preferences.configs", "foobnix.radio", "foobnix.regui", "foobnix.regui.model", "foobnix.thirdparty", "foobnix.trayicon", "foobnix.util", "foobnix.window" ], package_data={'foobnix': ['glade/*.glade', 'glade/*.png']}, #package_dir={"src/foobnix": "foobnix/"}, scripts=['foobnix/foobnix'], data_files=[('share/foobnix', ['README']), (FOOBNIX_TMP, ['version']), ('/usr/share/applications', ['foobnix.desktop']), ('/usr/share/pixmaps', glob.glob('foobnix/pixmaps/*')), (FOOBNIX_TMP_RADIO, glob.glob('radio/*')), ('share/man/man1', ['foobnix.1']), ('/usr/share/locale/uk/LC_MESSAGES', ['mo/uk/foobnix.mo']), ('/usr/share/locale/he/LC_MESSAGES', ['mo/he/foobnix.mo']), ('/usr/share/locale/ru/LC_MESSAGES', ['mo/ru/foobnix.mo']) ] ) # Cleanup (remove /build, /mo, and *.pyc files: print "Cleaning up..." try: removeall("build/") os.rmdir("build/") pass except: pass try: removeall("mo/") os.rmdir("mo/") except: pass try: for f in os.listdir("."): if os.path.isfile(f): if os.path.splitext(os.path.basename(f))[1] == ".pyc": os.remove(f) except: pass try: os.remove("foobnix/foobnix") except: pass try: os.remove("foobnix/version.py") except: pass
Python
''' Created on Sep 30, 2010 @author: ivan ''' import time from foobnix.regui.controls.dbus_manager import foobnixDBusInterface init_time = time.time() iface = foobnixDBusInterface() if not iface: print "start server" import gobject from foobnix.regui.foobnix_core import FoobnixCore import gtk gobject.threads_init() #@UndefinedVariable #gtk.gdk.threads_enter() eq = FoobnixCore() print "******Foobnix run in", time.time() - init_time, " seconds******" gtk.main() else: print "start client"
Python
#!/usr/bin/env python ''' Created on Mar 10, 2010 @author: ivan ''' import gobject import gtk from foobnix.util.dbus_utils import DBusManager, getFoobnixDBusInterface import sys import time import os import thread class Foobnix(): def __init__(self): from foobnix.application.app_view import AppView from foobnix.application.app_controller import AppController import foobnix.util.localization self.dbus = DBusManager(self) self.app = AppController(AppView()) def start(self): gobject.threads_init() gtk.gdk.threads_enter() gtk.main() def play_args(self, args): arg_list = eval(args) print "fobonix play", for i in arg_list: print i self.app.play_arguments(arg_list) init_time = time.time() iface = getFoobnixDBusInterface() if not iface: print "start server" foobnix = Foobnix() print "******Foobnix run in", time.time() - init_time, " seconds******" foobnix.start() else: print "start client" if sys.argv: iface.interactive_play_args(str(sys.argv))
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s' % (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s' % (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
''' Created on Oct 4, 2010 @author: ivan ''' #!/usr/bin/env python import gobject try: import pygtk; pygtk.require("2.0") except: pass import gtk data = [[0, "zero"], [1, "one"], [2, "two"], [3, "three"], [4, "four"], [5, "five"], [6, "six"]] data1 = [[10, "1zero"], [11, "1one"], [12, "1two"], [13, "1three"], [14, "1four"], [15, "1five"], [16, "1six"]] class CoreTree(gtk.ScrolledWindow): def __init__(self): gtk.ScrolledWindow.__init__(self) self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.model = gtk.TreeStore(int, str, gobject.TYPE_BOOLEAN) self.treeview = gtk.TreeView(self.model) self.treeview.connect("drag-drop", self.on_drag_drop) #self.treeview.connect("drag-data-received", self.on_drag_data_received) self.treeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE) self.add(self.treeview) self.treeview.enable_model_drag_source(gtk.gdk.BUTTON1_MASK, [("example", 0, 0)], gtk.gdk.ACTION_COPY) self.treeview.enable_model_drag_dest([("example", 0, 0)], gtk.gdk.ACTION_COPY) renderer = gtk.CellRendererText() column = gtk.TreeViewColumn("Integer", renderer, text=0, visible=2) self.treeview.append_column(column) column = gtk.TreeViewColumn("String", renderer, text=1, visible=2) self.treeview.append_column(column) self.filter_model = self.model.filter_new() self.filter_model.set_visible_column(2) self.treeview.set_model(self.filter_model) def iter_copy(self, to_pos, to_model, to_iter, from_model, from_iter): print "has child3", from_model.iter_has_child(from_iter) data_column_0 = from_model.get_value(from_iter, 0) data_column_1 = from_model.get_value(from_iter, 1) data_column_2 = from_model.get_value(from_iter, 2) row = [data_column_0,data_column_1, data_column_2] print "has child4", from_model.iter_has_child(from_iter) if (to_pos == gtk.TREE_VIEW_DROP_INTO_OR_BEFORE) or (to_pos == gtk.TREE_VIEW_DROP_INTO_OR_AFTER): new_iter = to_model.prepend(to_iter, row) elif to_pos == gtk.TREE_VIEW_DROP_BEFORE: new_iter = to_model.insert_before(to_iter,None,row) elif to_pos == gtk.TREE_VIEW_DROP_AFTER: new_iter = to_model.insert_after(to_iter,None, row) elif to_pos == "append": print "has child5", from_model.iter_has_child(from_iter) #new_iter = to_model.insert_before(iter,None, row) print "has child6", from_model.iter_has_child(from_iter) print "has child100", from_model.iter_has_child(from_iter) if from_model.iter_has_child(from_iter): for i in xrange(0, from_model.iter_n_children(from_iter)): next_from_iter = from_model.iter_nth_child(from_iter, i) self.iter_copy(gtk.TREE_VIEW_DROP_INTO_OR_BEFORE, to_model, new_iter, from_model, next_from_iter) def on_drag_drop(self, to_tree, drag_context, x, y, selection): """from widget selected""" from_tree = drag_context.get_source_widget() from_model, from_paths = from_tree.get_selection().get_selected_rows() from_path = from_model.convert_path_to_child_path(from_paths[0]) from_iter = from_model.get_iter(from_path) print "has child1", from_model.iter_has_child(from_iter) """to model""" to_filter_model = to_tree.get_model() to_real_model = to_filter_model.get_model() if not to_tree.get_dest_row_at_pos(x, y): to_iter = None to_pos = "append" print "has child2", from_model.iter_has_child(from_iter) self.iter_copy(to_pos, to_real_model, to_iter, from_model, from_iter) return None to_path, to_pos = to_tree.get_dest_row_at_pos(x, y) #to_model = to_tree.get_model() to_path = to_filter_model.convert_path_to_child_path(to_path) to_iter = to_real_model.get_iter(to_path) """iter copy""" self.iter_copy(to_pos, to_real_model, to_iter, from_model, from_iter) to_tree.expand_to_path(to_path) class TreeOne(CoreTree): def __init__(self): CoreTree.__init__(self) for item in data: self.model.append(None, [item[0], item[1], True]) #self.model.set(iter, 0, item[0], 1, item[1], 2, 1) class TreeTwo(CoreTree): def __init__(self): CoreTree.__init__(self) for item in data1: self.model.append(None, [item[0], item[1], True]) #iter = self.model.append(None) #self.model.set(iter, 0, item[0], 1, item[1]) class TreeDNDExample: def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("delete_event", gtk.main_quit) window.set_default_size(250, 350) hbox = gtk.HBox(False, 0) one = TreeOne() two = TreeTwo() hbox.pack_start(one) hbox.pack_start(two) window.add(hbox) window.show_all() def main(): gtk.main() return 0 if __name__ == "__main__": TreeDNDExample() main()
Python
''' Created on Sep 2, 2010 @author: ivan ''' import gst import gtk class Player(): def __init__1(self): self.player = gst.element_factory_make("playbin", "player") #mad = gst.element_factory_make("mad", "mad") #source = gst.element_factory_make("souphttpsrc", "source") #self.player.add(source,mad) #gst.element_link_many(source,mad) bus = self.player.get_bus() bus.connect("message", self.on_message) def __init__(self): self.player = gst.Pipeline("player") source = gst.element_factory_make("souphttpsrc", "source") volume = gst.element_factory_make("volume", "volume") mad = gst.element_factory_make("mad", "mad") audioconvert = gst.element_factory_make("audioconvert", "audioconvert") audioresample = gst.element_factory_make("audioresample", "audioresample") alsasink = gst.element_factory_make("alsasink", "alsasink") #alsasink = gst.element_factory_make("audiotestsrc", "audiotestsrc") self.player.add(source, mad,volume, audioconvert, audioresample, alsasink) gst.element_link_many(source, mad, volume,audioconvert, audioresample, alsasink) bus = self.player.get_bus() bus.add_signal_watch() bus.connect("message", self.on_message) def on_message(self, bus, message): print message def play(self,filepath): source = self.player.get_by_name("source") if source: print "PLAY PROXY" source.set_property("user-agent", "Fooobnix music player") source.set_property("automatic-redirect", "false") #self.player.get_by_name("source").set_property("proxy", "195.114.128.12:3128") source.set_property("proxy", "127.0.0.1:3128") source.set_property("location", filepath) else: print "PLAY LOCAL" self.player.set_property("uri", filepath) self.player.get_by_name("volume").set_property('volume', 0.4) self.player.set_state(gst.STATE_PLAYING) player = Player() player.play("http://cs4755.vkontakte.ru/u51615163/audio/576abb0f1562.mp3") #player.play("http://92.243.94.52:8000/intv_russian_hits-128.mp3") #player.play("http://217.20.164.163:8014") print "running" gtk.main()
Python
# -*- coding: utf-8 -*- # lyricwiki.py # # Copyright 2009 Amr Hassan <amr.hassan@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. import simplejson, urllib, os, hashlib, time def _download(args): """ Downloads the json response and returns it """ base = "http://lyrics.wikia.com/api.php?" str_args = {} for key in args: str_args[key] = args[key].encode("utf-8") args = urllib.urlencode(str_args) return urllib.urlopen(base + args).read() def _get_page_titles(artist, title): """ Returns a list of available page titles """ args = {"action": "query", "list": "search", "srsearch": artist + " " + title, "format": "json", } titles = ["%s:%s" % (artist, title), "%s:%s" % (artist.title(), title.title())] content = simplejson.loads(_download(args)) for t in content["query"]["search"]: titles.append(t["title"]) return titles def _get_lyrics(artist, title): for page_title in _get_page_titles(artist, title): args = {"action": "query", "prop": "revisions", "rvprop": "content", "titles": page_title, "format": "json", } revisions = simplejson.loads(_download(args))["query"]["pages"].popitem()[1] if not "revisions" in revisions: continue content = revisions["revisions"][0]["*"] if content.startswith("#Redirect"): n_title = content[content.find("[[") + 2:content.rfind("]]")] return _get_lyrics(*n_title.split(":")) if "<lyrics>" in content: return content[content.find("<lyrics>") + len("<lyrics>") : content.find("</lyrics>")].strip() elif "<lyric>" in content: return content[content.find("<lyric>") + len("<lyric>") : content.find("</lyric>")].strip() def get_lyrics(artist, title, cache_dir=None): """ Get lyrics by artist and title set cache_dir to a valid (existing) directory to enable caching. """ path = None if cache_dir and os.path.exists(cache_dir): digest = hashlib.sha1(artist.lower().encode("utf-8") + title.lower().encode("utf-8")).hexdigest() path = os.path.join(cache_dir, digest) if os.path.exists(path): fp = open(path) return simplejson.load(fp)["lyrics"].strip() lyrics = _get_lyrics(artist, title) if path and lyrics: fp = open(path, "w") simplejson.dump({"time": time.time(), "artist": artist, "title": title, "source": "lyricwiki", "lyrics": lyrics }, fp, indent=4) fp.close() return lyrics
Python
import gtk import gobject import copy POS_index = 0 POS_text = 1 POS_visible = 2 POS_font = 3 POS_level = 4 POS_parent = 5 class Bean(): def __init__(self, row=None): self.index = None self.text = None self.visible = None self.font = None self.level = None self.parent = None self.path = None if row: self.index = row[0] self.text = row[1] self.visible = row[2] self.font = row[3] self.level = row[4] self.parent = row[5] def get_row(self): return [self.index, self.text, self.visible, self.font, self.level, self.parent] class BaseTree(gtk.TreeView): def __init__(self): gtk.TreeView.__init__(self) column = gtk.TreeViewColumn("value", gtk.CellRendererText(), text=1, font=3) self.append_column(column) self.model_types = int, str, gobject.TYPE_BOOLEAN, str, str, str model = gtk.TreeStore(*self.model_types) filter_model = model.filter_new() filter_model.set_visible_column(2) self.set_model(filter_model) self.enable_model_drag_source(gtk.gdk.BUTTON1_MASK, [("example", 0, 0)], gtk.gdk.ACTION_COPY) self.enable_model_drag_dest([("example", 0, 0)], gtk.gdk.ACTION_COPY) self.connect("drag_drop", self.on_drag_drop) self.get_selection().set_mode(gtk.SELECTION_MULTIPLE) self.init_populate() def check_sanity(self, model_to, model_from, iter_from, iter_to): if model_to == model_from and iter_from== iter_from: return False else: return True def init_populate(self): model = self.get_model().get_model() model.clear() def id(row): return row.__hash__() for i, item in enumerate(["zero", "one"]): iter_parent = model.append(None, [i, "P_" + item, True, "bold", None, None]) model.set_value(iter_parent, POS_level, id(iter_parent)) for j , item in enumerate(["zero", "one", "two"]): #child_iter1 = model.append(iter_parent, [j, "99ch1_" + item, True, "normal", None, None]) #model.set_value(child_iter1, POS_level, id(child_iter1)) #model.set_value(child_iter1, POS_parent, id(iter_parent)) child_iter = model.append(iter_parent, [j, "ch1_" + item, True, "bold", None, None]) model.set_value(child_iter, POS_level, id(child_iter)) model.set_value(child_iter, POS_parent, id(iter_parent)) for n , item in enumerate(["++zero", "++one", "++two"]): ch1 = model.append(child_iter, [n * i * j, "ch2_" + item, True, "normal", None, None]) model.set_value(ch1, POS_level, id(ch1)) model.set_value(ch1, POS_parent, id(child_iter)) self.expand_all() def iter_copy(self, from_model, from_iter, to_model, to_iter, pos): row = [] for i, type in enumerate(self.model_types): row.append(from_model.get_value(from_iter, i)) if (pos == gtk.TREE_VIEW_DROP_INTO_OR_BEFORE) or (pos == gtk.TREE_VIEW_DROP_INTO_OR_AFTER): font = to_model.get_value(to_iter, POS_font) if font == "normal": return False new_iter = to_model.prepend(to_iter, row) elif pos == gtk.TREE_VIEW_DROP_BEFORE: new_iter = to_model.insert_before(None, to_iter, row) elif pos == gtk.TREE_VIEW_DROP_AFTER: new_iter = to_model.insert_after(None, to_iter, row) else: new_iter = to_model.append(None, row) if from_model.iter_has_child(from_iter): for i in range(0, from_model.iter_n_children(from_iter)): next_iter_to_copy = from_model.iter_nth_child(from_iter, i) self.iter_copy(from_model, next_iter_to_copy, to_model, new_iter, gtk.TREE_VIEW_DROP_INTO_OR_BEFORE) return True def on_drag_drop(self, to_tree, drag_context, x, y, selection): to_filter_model = to_tree.get_model() to_model = to_filter_model.get_model() if to_tree.get_dest_row_at_pos(x, y): to_path, to_pos = to_tree.get_dest_row_at_pos(x, y) to_path = to_filter_model.convert_path_to_child_path(to_path) to_iter = to_model.get_iter(to_path) else: to_path = None to_pos = None to_iter = None from_tree = drag_context.get_source_widget() from_filter_model, from_paths = from_tree.get_selection().get_selected_rows() from_model = from_filter_model.get_model() from_path = from_filter_model.convert_path_to_child_path(from_paths[0]) from_iter = from_model.get_iter(from_path) """do not copy to himself""" if to_tree == from_tree and from_path == to_path: drag_context.finish(False, False) return None """do not copy to child""" result = self.iter_copy(from_model, from_iter, to_model, to_iter, to_pos) if result and to_tree == from_tree: """move element in the save tree""" drag_context.finish(True, True) if to_path: to_tree.expand_to_path(to_path) def print_row(self, row): print row, row[0], row[1], row[2], row[3], row[POS_level], row[POS_parent] def recursion(self, row, plain): for child in row.iterchildren(): self.print_row(child) plain.append(child) self.recursion(child, plain) def plaine_view(self): model = self.get_model().get_model() plain = [] """PLAIN VIEW""" for row in model: plain.append(row) self.print_row(row) self.recursion(row, plain) copy_plain = [] for row in plain: copy_plain.append(Bean(row)) model.clear() print "================" for bean in copy_plain: bean.visible = True if bean.font == "bold": bean.visible = True else: bean.visible = True model.append(None, bean.get_row()) def tree_view(self): print """TREE VIEW""" model = self.get_model().get_model() print "init size", len(model) plain = [] for row in model: self.print_row(row) plain.append(row) self.recursion(row, plain) print "plain size", len(plain) print len(plain) copy_plain = [] for row in plain: bean = Bean(row) copy_plain.append(bean) model.clear() print "copy_plain size", len(copy_plain) print """POPULATE""" for bean in copy_plain: print bean.text, bean.level, bean.parent, bean.font self.append_like_tree(bean) self.expand_all() """parent id, parent iter""" hash = {None:None} def append_like_tree(self, bean): """copy beans""" bean = copy.copy(bean) model = self.get_model().get_model() if self.hash.has_key(bean.parent): parent_iter_exists = self.hash[bean.parent] else: parent_iter_exists = None bean.visible= True parent_iter = model.append(parent_iter_exists, bean.get_row()) self.hash[bean.level] = parent_iter class TreeOne(BaseTree): def __init__(self): BaseTree.__init__(self) class TreeTwo(BaseTree): def __init__(self): BaseTree.__init__(self) class TwoTreeExample: def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("delete_event", gtk.main_quit) window.set_default_size(250, 350) scroll_one = gtk.ScrolledWindow() one = TreeOne() scroll_one.add(one) two = TreeTwo() def on_plain(*a): #two.plaine_view() one.plaine_view() def on_tree(*a): one.tree_view() #two.tree_view() vbox = gtk.VBox(False, 0) hbox = gtk.HBox(False, 0) hbox.pack_start(scroll_one) hbox.pack_start(two) hbox1 = gtk.HBox(False, 0) to_plain = gtk.Button("Plain") to_plain.connect("clicked", on_plain) to_tree = gtk.Button("Tree") to_tree.connect("clicked", on_tree) hbox1.pack_start(to_plain) hbox1.pack_start(to_tree) vbox.pack_start(hbox) vbox.pack_start(hbox1, False, False) window.add(vbox) window.show_all() if __name__ == "__main__": TwoTreeExample() gtk.main()
Python
""" Copyright (C) 2009, Eduardo Silva P <edsiper@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ import gtk import gobject import random import threading class TV(gtk.ScrolledWindow): def __init__(self, model): gtk.ScrolledWindow.__init__(self) self._last_col_index = 0 self.model = model self.treeview = gtk.TreeView() # create filter self.filter = model.filter_new() self.filter.set_visible_func(self._cb_visible, [0]) # sorter self.sorter = gtk.TreeModelSort(self.filter) self.treeview.set_model(self.sorter) self.add(self.treeview) def add_column(self, column_name): cell = gtk.CellRendererText() # Configurable wrap col_tv = gtk.TreeViewColumn(column_name, cell, text=self._last_col_index) self.treeview.append_column(col_tv) def _cb_visible(self, model, iter, idx): return True class _IdleObject(gobject.GObject): """ Override gobject.GObject to always emit signals in the main thread by emmitting on an idle handler """ def __init__(self): gobject.GObject.__init__(self) def emit(self, *args): gobject.idle_add(gobject.GObject.emit,self,*args) class Data(_IdleObject): __gsignals__ = { "data": ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)) } def __init__(self): _IdleObject.__init__(self) def run(self): d = list() for i in range(0,20): n = random.random() d.append(n) self.emit('data', d) class Thread(threading.Thread): def __init__(self, data): threading.Thread.__init__(self) self._data = data def run(self): self._data.run() class Main(gtk.Window): def __init__(self): gtk.Window.__init__(self) self.ts = gtk.ListStore(str) tv = TV(self.ts) tv.add_column('Data') button = gtk.Button('Populate') button.connect('clicked', self.launch_thread) self.data = Data() self.data.connect('data', self._populate) vbox = gtk.VBox() vbox.pack_start(tv) vbox.pack_start(button, False) self.set_size_request(500, 400) self.add(vbox) self.show_all() def _populate(self, object, values): self.ts.clear() for val in values: self.ts.append([str(val)]) def launch_thread(self, widget): thread = Thread(self.data) thread.start() gobject.threads_init() main = Main() gtk.main()
Python
import urllib2 class ProxyPasswordMgr: def __init__(self): self.user = self.passwd = None def add_password(self, realm, uri, user, passwd): self.user = user self.passwd = passwd def find_user_password(self, realm, authuri): return self.user, self.passwd #http://spys.ru/proxylist/ proxy = "85.175.153.30:80" user = None password = None proxy = urllib2.ProxyHandler({"http" : proxy}) proxy_auth_handler = urllib2.ProxyBasicAuthHandler(ProxyPasswordMgr()) proxy_auth_handler.add_password(None, None, user, password) opener = urllib2.build_opener(proxy, proxy_auth_handler) urllib2.install_opener(opener) f = urllib2.urlopen("http://www.ukr.net") data = f.read() f.close() print data
Python
import base64 import cgi try: from Crypto.Cipher import AES except: raise Exception ("You need the pycrpyto library: http://cheeseshop.python.org/pypi/pycrypto/") MAIL_HIDE_BASE="http://mailhide.recaptcha.net" def asurl (email, public_key, private_key): """Wraps an email address with reCAPTCHA mailhide and returns the url. public_key is the public key from reCAPTCHA (in the base 64 encoded format). Private key is the AES key, and should be 32 hex chars.""" cryptmail = _encrypt_string (email, base64.b16decode (private_key, casefold=True), '\0' * 16) base64crypt = base64.urlsafe_b64encode (cryptmail) return "%s/d?k=%s&c=%s" % (MAIL_HIDE_BASE, public_key, base64crypt) def ashtml (email, public_key, private_key): """Wraps an email address with reCAPTCHA Mailhide and returns html that displays the email""" url = asurl (email, public_key, private_key) (userpart, domainpart) = _doterizeemail (email) return """%(user)s<a href='%(url)s' onclick="window.open('%(url)s', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;" title="Reveal this e-mail address">...</a>@%(domain)s""" % { 'user' : cgi.escape (userpart), 'domain' : cgi.escape (domainpart), 'url' : cgi.escape (url), } def _pad_string (str, block_size): numpad = block_size - (len (str) % block_size) return str + numpad * chr (numpad) def _encrypt_string (str, aes_key, aes_iv): if len (aes_key) != 16: raise Exception ("expecting key of length 16") if len (aes_iv) != 16: raise Exception ("expecting iv of length 16") return AES.new (aes_key, AES.MODE_CBC, aes_iv).encrypt (_pad_string (str, 16)) def _doterizeemail (email): """replaces part of the username with dots""" try: [user, domain] = email.split ('@') except: # handle invalid emails... sorta user = email domain = "" if len(user) <= 4: user_prefix = user[:1] elif len(user) <= 6: user_prefix = user[:3] else: user_prefix = user[:4] return (user_prefix, domain)
Python
import urllib2, urllib API_SSL_SERVER="https://api-secure.recaptcha.net" API_SERVER="http://api.recaptcha.net" VERIFY_SERVER="api-verify.recaptcha.net" class RecaptchaResponse(object): def __init__(self, is_valid, error_code=None): self.is_valid = is_valid self.error_code = error_code def displayhtml (public_key, use_ssl = False, error = None): """Gets the HTML to display for reCAPTCHA public_key -- The public api key use_ssl -- Should the request be sent over ssl? error -- An error message to display (from RecaptchaResponse.error_code)""" error_param = '' if error: error_param = '&error=%s' % error if use_ssl: server = API_SSL_SERVER else: server = API_SERVER return """<script type="text/javascript" src="%(ApiServer)s/challenge?k=%(PublicKey)s%(ErrorParam)s"></script> <noscript> <iframe src="%(ApiServer)s/noscript?k=%(PublicKey)s%(ErrorParam)s" height="300" width="500" frameborder="0"></iframe><br /> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type='hidden' name='recaptcha_response_field' value='manual_challenge' /> </noscript> """ % { 'ApiServer' : server, 'PublicKey' : public_key, 'ErrorParam' : error_param, } def submit (recaptcha_challenge_field, recaptcha_response_field, private_key, remoteip): """ Submits a reCAPTCHA request for verification. Returns RecaptchaResponse for the request recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form recaptcha_response_field -- The value of recaptcha_response_field from the form private_key -- your reCAPTCHA private key remoteip -- the user's ip address """ if not (recaptcha_response_field and recaptcha_challenge_field and len (recaptcha_response_field) and len (recaptcha_challenge_field)): return RecaptchaResponse (is_valid = False, error_code = 'incorrect-captcha-sol') def encode_if_necessary(s): if isinstance(s, unicode): return s.encode('utf-8') return s params = urllib.urlencode ({ 'privatekey': encode_if_necessary(private_key), 'remoteip' : encode_if_necessary(remoteip), 'challenge': encode_if_necessary(recaptcha_challenge_field), 'response' : encode_if_necessary(recaptcha_response_field), }) request = urllib2.Request ( url = "http://%s/verify" % VERIFY_SERVER, data = params, headers = { "Content-type": "application/x-www-form-urlencoded", "User-agent": "reCAPTCHA Python" } ) httpresp = urllib2.urlopen (request) return_values = httpresp.read ().splitlines (); httpresp.close(); return_code = return_values [0] if (return_code == "true"): return RecaptchaResponse (is_valid=True) else: return RecaptchaResponse (is_valid=False, error_code = return_values [1])
Python
r"""Command-line tool to validate and pretty-print JSON Usage:: $ echo '{"json":"obj"}' | python -m simplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -m simplejson.tool Expecting property name: line 1 column 2 (char 2) """ import sys import simplejson as json def main(): if len(sys.argv) == 1: infile = sys.stdin outfile = sys.stdout elif len(sys.argv) == 2: infile = open(sys.argv[1], 'rb') outfile = sys.stdout elif len(sys.argv) == 3: infile = open(sys.argv[1], 'rb') outfile = open(sys.argv[2], 'wb') else: raise SystemExit(sys.argv[0] + " [infile [outfile]]") try: obj = json.load(infile, object_pairs_hook=json.OrderedDict, use_decimal=True) except ValueError, e: raise SystemExit(e) json.dump(obj, outfile, sort_keys=True, indent=' ', use_decimal=True) outfile.write('\n') if __name__ == '__main__': main()
Python
"""JSON token scanner """ import re def _import_c_make_scanner(): try: from simplejson._speedups import make_scanner return make_scanner except ImportError: return None c_make_scanner = _import_c_make_scanner() __all__ = ['make_scanner'] NUMBER_RE = re.compile( r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?', (re.VERBOSE | re.MULTILINE | re.DOTALL)) def py_make_scanner(context): parse_object = context.parse_object parse_array = context.parse_array parse_string = context.parse_string match_number = NUMBER_RE.match encoding = context.encoding strict = context.strict parse_float = context.parse_float parse_int = context.parse_int parse_constant = context.parse_constant object_hook = context.object_hook object_pairs_hook = context.object_pairs_hook memo = context.memo def _scan_once(string, idx): try: nextchar = string[idx] except IndexError: raise StopIteration if nextchar == '"': return parse_string(string, idx + 1, encoding, strict) elif nextchar == '{': return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook, object_pairs_hook, memo) elif nextchar == '[': return parse_array((string, idx + 1), _scan_once) elif nextchar == 'n' and string[idx:idx + 4] == 'null': return None, idx + 4 elif nextchar == 't' and string[idx:idx + 4] == 'true': return True, idx + 4 elif nextchar == 'f' and string[idx:idx + 5] == 'false': return False, idx + 5 m = match_number(string, idx) if m is not None: integer, frac, exp = m.groups() if frac or exp: res = parse_float(integer + (frac or '') + (exp or '')) else: res = parse_int(integer) return res, m.end() elif nextchar == 'N' and string[idx:idx + 3] == 'NaN': return parse_constant('NaN'), idx + 3 elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity': return parse_constant('Infinity'), idx + 8 elif nextchar == '-' and string[idx:idx + 9] == '-Infinity': return parse_constant('-Infinity'), idx + 9 else: raise StopIteration def scan_once(string, idx): try: return _scan_once(string, idx) finally: memo.clear() return scan_once make_scanner = c_make_scanner or py_make_scanner
Python
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`simplejson` exposes an API familiar to users of the standard library :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained version of the :mod:`json` library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups. Encoding basic Python object hierarchies:: >>> import simplejson as json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print json.dumps("\"foo\bar") "\"foo\bar" >>> print json.dumps(u'\u1234') "\u1234" >>> print json.dumps('\\') "\\" >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson as json >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson as json >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=' ') >>> print '\n'.join([l.rstrip() for l in s.splitlines()]) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson as json >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj True >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' True >>> from StringIO import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io)[0] == 'streaming API' True Specializing JSON object decoding:: >>> import simplejson as json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) >>> from decimal import Decimal >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1') True Specializing JSON object encoding:: >>> import simplejson as json >>> def encode_complex(obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... raise TypeError(repr(o) + " is not JSON serializable") ... >>> json.dumps(2 + 1j, default=encode_complex) '[2.0, 1.0]' >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) '[2.0, 1.0]' >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) '[2.0, 1.0]' Using simplejson.tool from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -m simplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -m simplejson.tool Expecting property name: line 1 column 2 (char 2) """ __version__ = '2.1.1' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder', 'OrderedDict', ] __author__ = 'Bob Ippolito <bob@redivi.com>' from decimal import Decimal from decoder import JSONDecoder, JSONDecodeError from encoder import JSONEncoder def _import_OrderedDict(): import collections try: return collections.OrderedDict except AttributeError: import ordered_dict return ordered_dict.OrderedDict OrderedDict = _import_OrderedDict() def _import_c_make_encoder(): try: from simplejson._speedups import make_encoder return make_encoder except ImportError: return None _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=False, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=False, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If *indent* is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *use_decimal* is true (default: ``False``) then decimal.Decimal will be natively serialized to JSON with full precision. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=False, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is false then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *use_decimal* is true (default: ``False``) then decimal.Decimal will be natively serialized to JSON with full precision. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and not use_decimal and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, **kw).encode(obj) _default_decoder = JSONDecoder(encoding=None, object_hook=None, object_pairs_hook=None) def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. If *use_decimal* is true (default: ``False``) then it implies parse_float=decimal.Decimal for parity with ``dump``. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, use_decimal=use_decimal, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. If *use_decimal* is true (default: ``False``) then it implies parse_float=decimal.Decimal for parity with ``dump``. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and object_pairs_hook is None and not use_decimal and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if object_pairs_hook is not None: kw['object_pairs_hook'] = object_pairs_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant if use_decimal: if parse_float is not None: raise TypeError("use_decimal=True implies parse_float=Decimal") kw['parse_float'] = Decimal return cls(encoding=encoding, **kw).decode(s) def _toggle_speedups(enabled): import simplejson.decoder as dec import simplejson.encoder as enc import simplejson.scanner as scan c_make_encoder = _import_c_make_encoder() if enabled: dec.scanstring = dec.c_scanstring or dec.py_scanstring enc.c_make_encoder = c_make_encoder enc.encode_basestring_ascii = (enc.c_encode_basestring_ascii or enc.py_encode_basestring_ascii) scan.make_scanner = scan.c_make_scanner or scan.py_make_scanner else: dec.scanstring = dec.py_scanstring enc.c_make_encoder = None enc.encode_basestring_ascii = enc.py_encode_basestring_ascii scan.make_scanner = scan.py_make_scanner dec.make_scanner = scan.make_scanner global _default_decoder _default_decoder = JSONDecoder( encoding=None, object_hook=None, object_pairs_hook=None, ) global _default_encoder _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, )
Python
import unittest import doctest class OptionalExtensionTestSuite(unittest.TestSuite): def run(self, result): import simplejson run = unittest.TestSuite.run run(self, result) simplejson._toggle_speedups(False) run(self, result) simplejson._toggle_speedups(True) return result def additional_tests(suite=None): import simplejson import simplejson.encoder import simplejson.decoder if suite is None: suite = unittest.TestSuite() for mod in (simplejson, simplejson.encoder, simplejson.decoder): suite.addTest(doctest.DocTestSuite(mod)) suite.addTest(doctest.DocFileSuite('../../index.rst')) return suite def all_tests_suite(): suite = unittest.TestLoader().loadTestsFromNames([ 'simplejson.tests.test_check_circular', 'simplejson.tests.test_decode', 'simplejson.tests.test_default', 'simplejson.tests.test_dump', 'simplejson.tests.test_encode_basestring_ascii', 'simplejson.tests.test_encode_for_html', 'simplejson.tests.test_fail', 'simplejson.tests.test_float', 'simplejson.tests.test_indent', 'simplejson.tests.test_pass1', 'simplejson.tests.test_pass2', 'simplejson.tests.test_pass3', 'simplejson.tests.test_recursion', 'simplejson.tests.test_scanstring', 'simplejson.tests.test_separators', 'simplejson.tests.test_speedups', 'simplejson.tests.test_unicode', 'simplejson.tests.test_decimal', ]) suite = additional_tests(suite) return OptionalExtensionTestSuite([suite]) def main(): runner = unittest.TextTestRunner() suite = all_tests_suite() runner.run(suite) if __name__ == '__main__': import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) main()
Python
"""Implementation of JSONDecoder """ import re import sys import struct from simplejson.scanner import make_scanner def _import_c_scanstring(): try: from simplejson._speedups import scanstring return scanstring except ImportError: return None c_scanstring = _import_c_scanstring() __all__ = ['JSONDecoder'] FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') # The struct module in Python 2.4 would get frexp() out of range here # when an endian is specified in the format string. Fixed in Python 2.5+ if sys.byteorder != 'big': _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() class JSONDecodeError(ValueError): """Subclass of ValueError with the following additional properties: msg: The unformatted error message doc: The JSON document being parsed pos: The start index of doc where parsing failed end: The end index of doc where parsing failed (may be None) lineno: The line corresponding to pos colno: The column corresponding to pos endlineno: The line corresponding to end (may be None) endcolno: The column corresponding to end (may be None) """ def __init__(self, msg, doc, pos, end=None): ValueError.__init__(self, errmsg(msg, doc, pos, end=end)) self.msg = msg self.doc = doc self.pos = pos self.end = end self.lineno, self.colno = linecol(doc, pos) if end is not None: self.endlineno, self.endcolno = linecol(doc, pos) else: self.endlineno, self.endcolno = None, None def linecol(doc, pos): lineno = doc.count('\n', 0, pos) + 1 if lineno == 1: colno = pos else: colno = pos - doc.rindex('\n', 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): # Note that this function is called from _speedups lineno, colno = linecol(doc, pos) if end is None: #fmt = '{0}: line {1} column {2} (char {3})' #return fmt.format(msg, lineno, colno, pos) fmt = '%s: line %d column %d (char %d)' return fmt % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) #fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})' #return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end) fmt = '%s: line %d column %d - line %d column %d (char %d - %d)' return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, } STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) BACKSLASH = { '"': u'"', '\\': u'\\', '/': u'/', 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', } DEFAULT_ENCODING = "utf-8" def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters are allowed in the string. Returns a tuple of the decoded string and the index of the character in s after the end quote.""" if encoding is None: encoding = DEFAULT_ENCODING chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise JSONDecodeError( "Unterminated string starting at", s, begin) end = chunk.end() content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters if content: if not isinstance(content, unicode): content = unicode(content, encoding) _append(content) # Terminator is the end of string, a literal control character, # or a backslash denoting that an escape sequence follows if terminator == '"': break elif terminator != '\\': if strict: msg = "Invalid control character %r at" % (terminator,) #msg = "Invalid control character {0!r} at".format(terminator) raise JSONDecodeError(msg, s, end) else: _append(terminator) continue try: esc = s[end] except IndexError: raise JSONDecodeError( "Unterminated string starting at", s, begin) # If not a unicode escape sequence, must be in the lookup table if esc != 'u': try: char = _b[esc] except KeyError: msg = "Invalid \\escape: " + repr(esc) raise JSONDecodeError(msg, s, end) end += 1 else: # Unicode escape sequence esc = s[end + 1:end + 5] next_end = end + 5 if len(esc) != 4: msg = "Invalid \\uXXXX escape" raise JSONDecodeError(msg, s, end) uni = int(esc, 16) # Check for surrogate pair on UCS-4 systems if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: msg = "Invalid \\uXXXX\\uXXXX surrogate pair" if not s[end + 5:end + 7] == '\\u': raise JSONDecodeError(msg, s, end) esc2 = s[end + 7:end + 11] if len(esc2) != 4: raise JSONDecodeError(msg, s, end) uni2 = int(esc2, 16) uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) next_end += 6 char = unichr(uni) end = next_end # Append the unescaped character _append(char) return u''.join(chunks), end # Use speedup if available scanstring = c_scanstring or py_scanstring WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS) WHITESPACE_STR = ' \t\n\r' def JSONObject((s, end), encoding, strict, scan_once, object_hook, object_pairs_hook, memo=None, _w=WHITESPACE.match, _ws=WHITESPACE_STR): # Backwards compatibility if memo is None: memo = {} memo_get = memo.setdefault pairs = [] # Use a slice to prevent IndexError from being raised, the following # check will raise a more specific ValueError if the string is empty nextchar = s[end:end + 1] # Normally we expect nextchar == '"' if nextchar != '"': if nextchar in _ws: end = _w(s, end).end() nextchar = s[end:end + 1] # Trivial empty object if nextchar == '}': if object_pairs_hook is not None: result = object_pairs_hook(pairs) return result, end pairs = {} if object_hook is not None: pairs = object_hook(pairs) return pairs, end + 1 elif nextchar != '"': raise JSONDecodeError("Expecting property name", s, end) end += 1 while True: key, end = scanstring(s, end, encoding, strict) key = memo_get(key, key) # To skip some function call overhead we optimize the fast paths where # the JSON key separator is ": " or just ":". if s[end:end + 1] != ':': end = _w(s, end).end() if s[end:end + 1] != ':': raise JSONDecodeError("Expecting : delimiter", s, end) end += 1 try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass try: value, end = scan_once(s, end) except StopIteration: raise JSONDecodeError("Expecting object", s, end) pairs.append((key, value)) try: nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar == '}': break elif nextchar != ',': raise JSONDecodeError("Expecting , delimiter", s, end - 1) try: nextchar = s[end] if nextchar in _ws: end += 1 nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar != '"': raise JSONDecodeError("Expecting property name", s, end - 1) if object_pairs_hook is not None: result = object_pairs_hook(pairs) return result, end pairs = dict(pairs) if object_hook is not None: pairs = object_hook(pairs) return pairs, end def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR): values = [] nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] # Look-ahead for trivial empty array if nextchar == ']': return values, end + 1 _append = values.append while True: try: value, end = scan_once(s, end) except StopIteration: raise JSONDecodeError("Expecting object", s, end) _append(value) nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break elif nextchar != ',': raise JSONDecodeError("Expecting , delimiter", s, end) try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass return values, end class JSONDecoder(object): """Simple JSON <http://json.org> decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | unicode | +---------------+-------------------+ | number (int) | int, long | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """ def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None): """ *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. *strict* controls the parser's behavior when it encounters an invalid control character in a string. The default setting of ``True`` means that unescaped control characters are parse errors, if ``False`` then control characters will be allowed in strings. """ self.encoding = encoding self.object_hook = object_hook self.object_pairs_hook = object_pairs_hook self.parse_float = parse_float or float self.parse_int = parse_int or int self.parse_constant = parse_constant or _CONSTANTS.__getitem__ self.strict = strict self.parse_object = JSONObject self.parse_array = JSONArray self.parse_string = scanstring self.memo = {} self.scan_once = make_scanner(self) def decode(self, s, _w=WHITESPACE.match): """Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise JSONDecodeError("Extra data", s, end, len(s)) return obj def raw_decode(self, s, idx=0): """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ try: obj, end = self.scan_once(s, idx) except StopIteration: raise JSONDecodeError("No JSON object could be decoded", s, idx) return obj, end
Python
"""Implementation of JSONEncoder """ import re from decimal import Decimal def _import_speedups(): try: from simplejson import _speedups return _speedups.encode_basestring_ascii, _speedups.make_encoder except ImportError: return None, None c_encode_basestring_ascii, c_make_encoder = _import_speedups() from simplejson.decoder import PosInf ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') HAS_UTF8 = re.compile(r'[\x80-\xff]') ESCAPE_DCT = { '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', } for i in range(0x20): #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i)) ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) FLOAT_REPR = repr def encode_basestring(s): """Return a JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): return ESCAPE_DCT[match.group(0)] return u'"' + ESCAPE.sub(replace, s) + u'"' def py_encode_basestring_ascii(s): """Return an ASCII-only JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: n = ord(s) if n < 0x10000: #return '\\u{0:04x}'.format(n) return '\\u%04x' % (n,) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) s2 = 0xdc00 | (n & 0x3ff) #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2) return '\\u%04x\\u%04x' % (s1, s2) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' encode_basestring_ascii = ( c_encode_basestring_ascii or py_encode_basestring_ascii) class JSONEncoder(object): """Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """ item_separator = ', ' key_separator = ': ' def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=False): """Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is true, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If specified, separators should be a (item_separator, key_separator) tuple. The default is (', ', ': '). To get the most compact JSON representation you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8. If use_decimal is true (not the default), ``decimal.Decimal`` will be supported directly by the encoder. For the inverse, decode JSON with ``parse_float=decimal.Decimal``. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.use_decimal = use_decimal if isinstance(indent, (int, long)): indent = ' ' * indent self.indent = indent if separators is not None: self.item_separator, self.key_separator = separators if default is not None: self.default = default self.encoding = encoding def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError(repr(o) + " is not JSON serializable") def encode(self, o): """Return a JSON string representation of a Python data structure. >>> from simplejson import JSONEncoder >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks. if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if (_encoding is not None and not (_encoding == 'utf-8')): o = o.decode(_encoding) if self.ensure_ascii: return encode_basestring_ascii(o) else: return encode_basestring(o) # This doesn't pass the iterator directly to ''.join() because the # exceptions aren't as detailed. The list call should be roughly # equivalent to the PySequence_Fast that ''.join() would do. chunks = self.iterencode(o, _one_shot=True) if not isinstance(chunks, (list, tuple)): chunks = list(chunks) if self.ensure_ascii: return ''.join(chunks) else: return u''.join(chunks) def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=PosInf, _neginf=-PosInf): # Check for specials. Note that this type of test is processor # and/or platform-specific, so do tests which don't depend on # the internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError( "Out of range float values are not JSON compliant: " + repr(o)) return text key_memo = {} if (_one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys): _iterencode = c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan, key_memo, self.use_decimal) else: _iterencode = _make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot, self.use_decimal) try: return _iterencode(o, 0) finally: key_memo.clear() class JSONEncoderForHTML(JSONEncoder): """An encoder that produces JSON safe to embed in HTML. To embed JSON content in, say, a script tag on a web page, the characters &, < and > should be escaped. They cannot be escaped with the usual entities (e.g. &amp;) because they are not expanded within <script> tags. """ def encode(self, o): # Override JSONEncoder.encode because it has hacks for # performance that make things more complicated. chunks = self.iterencode(o, True) if self.ensure_ascii: return ''.join(chunks) else: return u''.join(chunks) def iterencode(self, o, _one_shot=False): chunks = super(JSONEncoderForHTML, self).iterencode(o, _one_shot) for chunk in chunks: chunk = chunk.replace('&', '\\u0026') chunk = chunk.replace('<', '\\u003c') chunk = chunk.replace('>', '\\u003e') yield chunk def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, _use_decimal, ## HACK: hand-optimized bytecode; turn globals into locals False=False, True=True, ValueError=ValueError, basestring=basestring, Decimal=Decimal, dict=dict, float=float, id=id, int=int, isinstance=isinstance, list=list, long=long, str=str, tuple=tuple, ): def _iterencode_list(lst, _current_indent_level): if not lst: yield '[]' return if markers is not None: markerid = id(lst) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = lst buf = '[' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (_indent * _current_indent_level) separator = _item_separator + newline_indent buf += newline_indent else: newline_indent = None separator = _item_separator first = True for value in lst: if first: first = False else: buf = separator if isinstance(value, basestring): yield buf + _encoder(value) elif value is None: yield buf + 'null' elif value is True: yield buf + 'true' elif value is False: yield buf + 'false' elif isinstance(value, (int, long)): yield buf + str(value) elif isinstance(value, float): yield buf + _floatstr(value) elif _use_decimal and isinstance(value, Decimal): yield buf + str(value) else: yield buf if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (_indent * _current_indent_level) yield ']' if markers is not None: del markers[markerid] def _iterencode_dict(dct, _current_indent_level): if not dct: yield '{}' return if markers is not None: markerid = id(dct) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = dct yield '{' if _indent is not None: _current_indent_level += 1 newline_indent = '\n' + (_indent * _current_indent_level) item_separator = _item_separator + newline_indent yield newline_indent else: newline_indent = None item_separator = _item_separator first = True if _sort_keys: items = dct.items() items.sort(key=lambda kv: kv[0]) else: items = dct.iteritems() for key, value in items: if isinstance(key, basestring): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = _floatstr(key) elif key is True: key = 'true' elif key is False: key = 'false' elif key is None: key = 'null' elif isinstance(key, (int, long)): key = str(key) elif _skipkeys: continue else: raise TypeError("key " + repr(key) + " is not a string") if first: first = False else: yield item_separator yield _encoder(key) yield _key_separator if isinstance(value, basestring): yield _encoder(value) elif value is None: yield 'null' elif value is True: yield 'true' elif value is False: yield 'false' elif isinstance(value, (int, long)): yield str(value) elif isinstance(value, float): yield _floatstr(value) elif _use_decimal and isinstance(value, Decimal): yield str(value) else: if isinstance(value, (list, tuple)): chunks = _iterencode_list(value, _current_indent_level) elif isinstance(value, dict): chunks = _iterencode_dict(value, _current_indent_level) else: chunks = _iterencode(value, _current_indent_level) for chunk in chunks: yield chunk if newline_indent is not None: _current_indent_level -= 1 yield '\n' + (_indent * _current_indent_level) yield '}' if markers is not None: del markers[markerid] def _iterencode(o, _current_indent_level): if isinstance(o, basestring): yield _encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield str(o) elif isinstance(o, float): yield _floatstr(o) elif isinstance(o, (list, tuple)): for chunk in _iterencode_list(o, _current_indent_level): yield chunk elif isinstance(o, dict): for chunk in _iterencode_dict(o, _current_indent_level): yield chunk elif _use_decimal and isinstance(o, Decimal): yield str(o) else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o o = _default(o) for chunk in _iterencode(o, _current_indent_level): yield chunk if markers is not None: del markers[markerid] return _iterencode
Python
"""Drop-in replacement for collections.OrderedDict by Raymond Hettinger http://code.activestate.com/recipes/576693/ """ from UserDict import DictMixin # Modified from original to support Python 2.4, see # http://code.google.com/p/simplejson/issues/detail?id=53 try: all except NameError: def all(seq): for elem in seq: if not elem: return False return True class OrderedDict(dict, DictMixin): def __init__(self, *args, **kwds): if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__end except AttributeError: self.clear() self.update(*args, **kwds) def clear(self): self.__end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.__map = {} # key --> [key, prev, next] dict.clear(self) def __setitem__(self, key, value): if key not in self: end = self.__end curr = end[1] curr[2] = end[1] = self.__map[key] = [key, curr, end] dict.__setitem__(self, key, value) def __delitem__(self, key): dict.__delitem__(self, key) key, prev, next = self.__map.pop(key) prev[2] = next next[1] = prev def __iter__(self): end = self.__end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): end = self.__end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] def popitem(self, last=True): if not self: raise KeyError('dictionary is empty') # Modified from original to support Python 2.4, see # http://code.google.com/p/simplejson/issues/detail?id=53 if last: key = reversed(self).next() else: key = iter(self).next() value = self.pop(key) return key, value def __reduce__(self): items = [[k, self[k]] for k in self] tmp = self.__map, self.__end del self.__map, self.__end inst_dict = vars(self).copy() self.__map, self.__end = tmp if inst_dict: return (self.__class__, (items,), inst_dict) return self.__class__, (items,) def keys(self): return list(self) setdefault = DictMixin.setdefault update = DictMixin.update pop = DictMixin.pop values = DictMixin.values items = DictMixin.items iterkeys = DictMixin.iterkeys itervalues = DictMixin.itervalues iteritems = DictMixin.iteritems def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) def copy(self): return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d def __eq__(self, other): if isinstance(other, OrderedDict): return len(self)==len(other) and \ all(p==q for p, q in zip(self.items(), other.items())) return dict.__eq__(self, other) def __ne__(self, other): return not self == other
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import __main__ class Event(object): """ Event is a simple publish/subscribe based event dispatcher. It's a way to add, or take advantage of, hooks in your application. If you want to tie actions in with lower level classes you're developing within your application, you can set events to fire, and then subscribe to them with callback methods in other methods in your application. It sets itself to the __main__ function. In order to use it, you must import it with your __main__ method, and make sure you import __main__ and it's accessible for the methods where you want to use it. For example, from sessions.py # if the event class has been loaded, fire off the sessionDeleted event if u"AEU_Events" in __main__.__dict__: __main__.AEU_Events.fire_event(u"sessionDelete") You can the subscribe to session delete events, adding a callback if u"AEU_Events" in __main__.__dict__: __main__.AEU_Events.subscribe(u"sessionDelete", clear_user_session) """ def __init__(self): self.events = [] def subscribe(self, event, callback, args = None): """ This method will subscribe a callback function to an event name. Args: event: The event to subscribe to. callback: The callback method to run. args: Optional arguments to pass with the callback. Returns True """ if not {"event": event, "callback": callback, "args": args, } \ in self.events: self.events.append({"event": event, "callback": callback, \ "args": args, }) return True def unsubscribe(self, event, callback, args = None): """ This method will unsubscribe a callback from an event. Args: event: The event to subscribe to. callback: The callback method to run. args: Optional arguments to pass with the callback. Returns True """ if {"event": event, "callback": callback, "args": args, }\ in self.events: self.events.remove({"event": event, "callback": callback,\ "args": args, }) return True def fire_event(self, event = None): """ This method is what a method uses to fire an event, initiating all registered callbacks Args: event: The name of the event to fire. Returns True """ for e in self.events: if e["event"] == event: if type(e["args"]) == type([]): e["callback"](*e["args"]) elif type(e["args"]) == type({}): e["callback"](**e["args"]) elif e["args"] == None: e["callback"]() else: e["callback"](e["args"]) return True """ Assign to the event class to __main__ """ __main__.AEU_Events = Event()
Python
''' Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import os, cgi, __main__ from google.appengine.ext.webapp import template import wsgiref.handlers from google.appengine.ext import webapp from google.appengine.api import memcache from google.appengine.ext import db from appengine_utilities import cron class MainPage(webapp.RequestHandler): def get(self): c = cron.Cron() query = cron._AppEngineUtilities_Cron.all() results = query.fetch(1000) template_values = {"cron_entries" : results} path = os.path.join(os.path.dirname(__file__), 'templates/scheduler_form.html') self.response.out.write(template.render(path, template_values)) def post(self): if str(self.request.get('action')) == 'Add': cron.Cron().add_cron(str(self.request.get('cron_entry'))) elif str(self.request.get('action')) == 'Delete': entry = db.get(db.Key(str(self.request.get('key')))) entry.delete() query = cron._AppEngineUtilities_Cron.all() results = query.fetch(1000) template_values = {"cron_entries" : results} path = os.path.join(os.path.dirname(__file__), 'templates/scheduler_form.html') self.response.out.write(template.render(path, template_values)) def main(): application = webapp.WSGIApplication( [('/gaeutilities/', MainPage)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == "__main__": main()
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ __author__="jbowman" __date__ ="$Sep 11, 2009 4:20:11 PM$" # Configuration settings for the session class. session = { "COOKIE_NAME": "gaeutilities_session", "DEFAULT_COOKIE_PATH": "/", "SESSION_EXPIRE_TIME": 7200, # sessions are valid for 7200 seconds # (2 hours) "INTEGRATE_FLASH": True, # integrate functionality from flash module? "SET_COOKIE_EXPIRES": True, # Set to True to add expiration field to # cookie "WRITER":"datastore", # Use the datastore writer by default. # cookie is the other option. "CLEAN_CHECK_PERCENT": 50, # By default, 50% of all requests will clean # the datastore of expired sessions "CHECK_IP": True, # validate sessions by IP "CHECK_USER_AGENT": True, # validate sessions by user agent "SESSION_TOKEN_TTL": 5, # Number of seconds a session token is valid # for. "UPDATE_LAST_ACTIVITY": 60, # Number of seconds that may pass before # last_activity is updated } # Configuration settings for the cache class cache = { "DEFAULT_TIMEOUT": 3600, # cache expires after one hour (3600 sec) "CLEAN_CHECK_PERCENT": 50, # 50% of all requests will clean the database "MAX_HITS_TO_CLEAN": 20, # the maximum number of cache hits to clean } # Configuration settings for the flash class flash = { "COOKIE_NAME": "appengine-utilities-flash", } # Configuration settings for the paginator class paginator = { "DEFAULT_COUNT": 10, "CACHE": 10, "DEFAULT_SORT_ORDER": "ASC", } rotmodel = { "RETRY_ATTEMPTS": 3, "RETRY_INTERVAL": .2, } if __name__ == "__main__": print "Hello World";
Python
# -*- coding: utf-8 -*- """ Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # main python imports import os import time import datetime import random import hashlib import Cookie import pickle import __main__ from time import strftime # google appengine imports from google.appengine.ext import db from google.appengine.api import memcache from django.utils import simplejson # appengine_utilities import from rotmodel import ROTModel # settings try: import settings except: import settings_default as settings class _AppEngineUtilities_Session(ROTModel): """ Model for the sessions in the datastore. This contains the identifier and validation information for the session. Uses ROTModel rather than db.Model in order to make more attempts to retrieve information on get(). """ sid = db.StringListProperty() session_key = db.FloatProperty() ip = db.StringProperty() ua = db.StringProperty() last_activity = db.DateTimeProperty() dirty = db.BooleanProperty(default=False) working = db.BooleanProperty(default=False) deleted = db.BooleanProperty(default=False) def put(self): """ Extends put so that it writes vaules to memcache as well as the datastore, and keeps them in sync, even when datastore writes fails. It also uses a db.put(), rather than the ROTModel put, to avoid retries on puts. With the memcache layer this optimizes performance, stopping on db.Timeout rather than retrying. Returns the session object. """ if self.session_key: memcache.set(u"_AppEngineUtilities_Session_%s" % \ (unicode(self.session_key)), self) else: # new session, generate a new key, which will handle the # put and set the memcache self.create_key() self.last_activity = datetime.datetime.now() try: self.dirty = False db.put(self) memcache.set(u"_AppEngineUtilities_Session_%s" % \ (unicode(self.session_key)), self) except: self.dirty = True memcache.set(u"_AppEngineUtilities_Session_%s" % \ (unicode(self.session_key)), self) return self @classmethod def get_session(cls, session_obj=None): """ Uses the passed objects sid to get a session object from memcache, or datastore if a valid one exists. Args: session_obj: a session object Returns a validated session object. """ if session_obj.sid == None: return None session_key = session_obj.sid.split(u'_')[0] session = memcache.get(u"_AppEngineUtilities_Session_%s" % \ (unicode(session_key))) if session: if session.deleted == True: session.delete() return None if session.dirty == True and session.working != False: # the working bit is used to make sure multiple requests, # which can happen with ajax oriented sites, don't try to put # at the same time session.working = True memcache.set(u"_AppEngineUtilities_Session_%s" % \ (unicode(session_key)), session) session.put() if session_obj.sid in session.sid: sessionAge = datetime.datetime.now() - session.last_activity if sessionAge.seconds > session_obj.session_expire_time: session.delete() return None return session else: return None # Not in memcache, check datastore query = _AppEngineUtilities_Session.all() query.filter(u"sid = ", session_obj.sid) results = query.fetch(1) if len(results) > 0: sessionAge = datetime.datetime.now() - results[0].last_activity if sessionAge.seconds > session_obj.session_expire_time: results[0].delete() return None memcache.set(u"_AppEngineUtilities_Session_%s" % \ (unicode(session_key)), results[0]) memcache.set(u"_AppEngineUtilities_SessionData_%s" % \ (unicode(session_key)), results[0].get_items_ds()) return results[0] else: return None def get_items(self): """ Returns all the items stored in a session. Queries memcache first and will try the datastore next. """ items = memcache.get(u"_AppEngineUtilities_SessionData_%s" % \ (unicode(self.session_key))) if items: for item in items: if item.deleted == True: item.delete() items.remove(item) return items query = _AppEngineUtilities_SessionData.all() query.filter(u"session_key", self.session_key) results = query.fetch(1000) return results def get_item(self, keyname = None): """ Returns a single session data item from the memcache or datastore Args: keyname: keyname of the session data object Returns the session data object if it exists, otherwise returns None """ mc = memcache.get(u"_AppEngineUtilities_SessionData_%s" % \ (unicode(self.session_key))) if mc: for item in mc: if item.keyname == keyname: if item.deleted == True: item.delete() return None return item query = _AppEngineUtilities_SessionData.all() query.filter(u"session_key = ", self.session_key) query.filter(u"keyname = ", keyname) results = query.fetch(1) if len(results) > 0: memcache.set(u"_AppEngineUtilities_SessionData_%s" % \ (unicode(self.session_key)), self.get_items_ds()) return results[0] return None def get_items_ds(self): """ This gets all session data objects from the datastore, bypassing memcache. Returns a list of session data entities. """ query = _AppEngineUtilities_SessionData.all() query.filter(u"session_key", self.session_key) results = query.fetch(1000) return results def delete(self): """ Deletes a session and all it's associated data from the datastore and memcache. Returns True """ try: query = _AppEngineUtilities_SessionData.all() query.filter(u"session_key = ", self.session_key) results = query.fetch(1000) db.delete(results) db.delete(self) memcache.delete_multi([u"_AppEngineUtilities_Session_%s" % \ (unicode(self.session_key)), \ u"_AppEngineUtilities_SessionData_%s" % \ (unicode(self.session_key))]) except: mc = memcache.get(u"_AppEngineUtilities_Session_%s" %+ \ (unicode(self.session_key))) if mc: mc.deleted = True else: # not in the memcache, check to see if it should be query = _AppEngineUtilities_Session.all() query.filter(u"sid = ", self.sid) results = query.fetch(1) if len(results) > 0: results[0].deleted = True memcache.set(u"_AppEngineUtilities_Session_%s" % \ (unicode(self.session_key)), results[0]) return True def create_key(self): """ Creates a unique key for the session. Returns the key value as a unicode string. """ self.session_key = time.time() valid = False while valid == False: # verify session_key is unique if memcache.get(u"_AppEngineUtilities_Session_%s" % \ (unicode(self.session_key))): self.session_key = self.session_key + 0.001 else: query = _AppEngineUtilities_Session.all() query.filter(u"session_key = ", self.session_key) results = query.fetch(1) if len(results) > 0: self.session_key = self.session_key + 0.001 else: try: self.put() memcache.set(u"_AppEngineUtilities_Session_%s" %+ \ (unicode(self.session_key)), self) except: self.dirty = True memcache.set(u"_AppEngineUtilities_Session_%s" % \ (unicode(self.session_key)), self) valid = True return unicode(self.session_key) class _AppEngineUtilities_SessionData(ROTModel): """ Model for the session data in the datastore. """ session_key = db.FloatProperty() keyname = db.StringProperty() content = db.BlobProperty() model = db.ReferenceProperty() dirty = db.BooleanProperty(default=False) deleted = db.BooleanProperty(default=False) def put(self): """ Adds a keyname/value for session to the datastore and memcache Returns the key from the datastore put or u"dirty" """ # update or insert in datastore try: return_val = db.put(self) self.dirty = False except: return_val = u"dirty" self.dirty = True # update or insert in memcache mc_items = memcache.get(u"_AppEngineUtilities_SessionData_%s" % \ (unicode(self.session_key))) if mc_items: value_updated = False for item in mc_items: if value_updated == True: break if item.keyname == self.keyname: item.content = self.content item.model = self.model memcache.set(u"_AppEngineUtilities_SessionData_%s" % \ (unicode(self.session_key)), mc_items) value_updated = True break if value_updated == False: mc_items.append(self) memcache.set(u"_AppEngineUtilities_SessionData_%s" % \ (unicode(self.session_key)), mc_items) return return_val def delete(self): """ Deletes an entity from the session in memcache and the datastore Returns True """ try: db.delete(self) except: self.deleted = True mc_items = memcache.get(u"_AppEngineUtilities_SessionData_%s" % \ (unicode(self.session_key))) value_handled = False for item in mc_items: if value_handled == True: break if item.keyname == self.keyname: if self.deleted == True: item.deleted = True else: mc_items.remove(item) memcache.set(u"_AppEngineUtilities_SessionData_%s" % \ (unicode(self.session_key)), mc_items) return True class _DatastoreWriter(object): def put(self, keyname, value, session): """ Insert a keyname/value pair into the datastore for the session. Args: keyname: The keyname of the mapping. value: The value of the mapping. Returns the model entity key """ keyname = session._validate_key(keyname) if value is None: raise ValueError(u"You must pass a value to put.") # datestore write trumps cookie. If there is a cookie value # with this keyname, delete it so we don't have conflicting # entries. if session.cookie_vals.has_key(keyname): del(session.cookie_vals[keyname]) session.output_cookie["%s_data" % (session.cookie_name)] = \ simplejson.dumps(session.cookie_vals) print session.output_cookie.output() sessdata = session._get(keyname=keyname) if sessdata is None: sessdata = _AppEngineUtilities_SessionData() sessdata.session_key = session.session.session_key sessdata.keyname = keyname try: db.model_to_protobuf(value) if not value.is_saved(): value.put() sessdata.model = value except: sessdata.content = pickle.dumps(value) sessdata.model = None session.cache[keyname] = value return sessdata.put() class _CookieWriter(object): def put(self, keyname, value, session): """ Insert a keyname/value pair into the datastore for the session. Args: keyname: The keyname of the mapping. value: The value of the mapping. Returns True """ keyname = session._validate_key(keyname) if value is None: raise ValueError(u"You must pass a value to put.") # Use simplejson for cookies instead of pickle. session.cookie_vals[keyname] = value # update the requests session cache as well. session.cache[keyname] = value # simplejson will raise any error I'd raise about an invalid value # so let it raise exceptions session.output_cookie["%s_data" % (session.cookie_name)] = \ simplejson.dumps(session.cookie_vals) print session.output_cookie.output() return True class Session(object): """ Sessions are used to maintain user presence between requests. Sessions can either be stored server side in the datastore/memcache, or be kept entirely as cookies. This is set either with the settings file or on initialization, using the writer argument/setting field. Valid values are "datastore" or "cookie". Session can be used as a standard dictionary object. session = appengine_utilities.sessions.Session() session["keyname"] = "value" # sets keyname to value print session["keyname"] # will print value Datastore Writer: The datastore writer was written with the focus being on security, reliability, and performance. In that order. It is based off of a session token system. All data is stored server side in the datastore and memcache. A token is given to the browser, and stored server side. Optionally (and on by default), user agent and ip checking is enabled. Tokens have a configurable time to live (TTL), which defaults to 5 seconds. The current token, plus the previous 2, are valid for any request. This is done in order to manage ajax enabled sites which may have more than on request happening at a time. This means any token is valid for 15 seconds. A request with a token who's TTL has passed will have a new token generated. In order to take advantage of the token system for an authentication system, you will want to tie sessions to accounts, and make sure only one session is valid for an account. You can do this by setting a db.ReferenceProperty(_Appengine_Utilities_Session) attribute on your user Model, and use the get_ds_session() method on a valid session to populate it on login. Note that even with this complex system, sessions can still be hijacked and it will take the user logging in to retrieve the account. In the future an ssl only cookie option may be implemented for the datastore writer, which would further protect the session token from being sniffed, however it would be restricted to using cookies on the .appspot.com domain, and ssl requests are a finite resource. This is why such a thing is not currently implemented. Session data objects are stored in the datastore pickled, so any python object is valid for storage. Cookie Writer: Sessions using the cookie writer are stored entirely in the browser and no interaction with the datastore is required. This creates a drastic improvement in performance, but provides no security for session hijack. This is useful for requests where identity is not important, but you wish to keep state between requests. Information is stored in a json format, as pickled data from the server is unreliable. Note: There is no checksum validation of session data on this method, it's streamlined for pure performance. If you need to make sure data is not tampered with, use the datastore writer which stores the data server side. django-middleware: Included with the GAEUtilties project is a django-middleware.middleware.SessionMiddleware which can be included in your settings file. This uses the cookie writer for anonymous requests, and you can switch to the datastore writer on user login. This will require an extra set in your login process of calling request.session.save() once you validated the user information. This will convert the cookie writer based session to a datastore writer. """ # cookie name declaration for class methods COOKIE_NAME = settings.session["COOKIE_NAME"] def __init__(self, cookie_path=settings.session["DEFAULT_COOKIE_PATH"], cookie_name=settings.session["COOKIE_NAME"], session_expire_time=settings.session["SESSION_EXPIRE_TIME"], clean_check_percent=settings.session["CLEAN_CHECK_PERCENT"], integrate_flash=settings.session["INTEGRATE_FLASH"], check_ip=settings.session["CHECK_IP"], check_user_agent=settings.session["CHECK_USER_AGENT"], set_cookie_expires=settings.session["SET_COOKIE_EXPIRES"], session_token_ttl=settings.session["SESSION_TOKEN_TTL"], last_activity_update=settings.session["UPDATE_LAST_ACTIVITY"], writer=settings.session["WRITER"]): """ Initializer Args: cookie_name: The name for the session cookie stored in the browser. session_expire_time: The amount of time between requests before the session expires. clean_check_percent: The percentage of requests the will fire off a cleaning routine that deletes stale session data. integrate_flash: If appengine-utilities flash utility should be integrated into the session object. check_ip: If browser IP should be used for session validation check_user_agent: If the browser user agent should be used for sessoin validation. set_cookie_expires: True adds an expires field to the cookie so it saves even if the browser is closed. session_token_ttl: Number of sessions a session token is valid for before it should be regenerated. """ self.cookie_path = cookie_path self.cookie_name = cookie_name self.session_expire_time = session_expire_time self.integrate_flash = integrate_flash self.check_user_agent = check_user_agent self.check_ip = check_ip self.set_cookie_expires = set_cookie_expires self.session_token_ttl = session_token_ttl self.last_activity_update = last_activity_update self.writer = writer # make sure the page is not cached in the browser print self.no_cache_headers() # Check the cookie and, if necessary, create a new one. self.cache = {} string_cookie = os.environ.get(u"HTTP_COOKIE", u"") self.cookie = Cookie.SimpleCookie() self.output_cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) try: self.cookie_vals = \ simplejson.loads(self.cookie["%s_data" % (self.cookie_name)].value) # sync self.cache and self.cookie_vals which will make those # values available for all gets immediately. for k in self.cookie_vals: self.cache[k] = self.cookie_vals[k] # sync the input cookie with the output cookie self.output_cookie["%s_data" % (self.cookie_name)] = \ self.cookie["%s_data" % (self.cookie_name)] except: self.cookie_vals = {} if writer == "cookie": pass else: self.sid = None new_session = True # do_put is used to determine if a datastore write should # happen on this request. do_put = False # check for existing cookie if self.cookie.get(cookie_name): self.sid = self.cookie[cookie_name].value # The following will return None if the sid has expired. self.session = _AppEngineUtilities_Session.get_session(self) if self.session: new_session = False if new_session: # start a new session self.session = _AppEngineUtilities_Session() self.session.put() self.sid = self.new_sid() if u"HTTP_USER_AGENT" in os.environ: self.session.ua = os.environ[u"HTTP_USER_AGENT"] else: self.session.ua = None if u"REMOTE_ADDR" in os.environ: self.session.ip = os.environ["REMOTE_ADDR"] else: self.session.ip = None self.session.sid = [self.sid] # do put() here to get the session key self.session.put() else: # check the age of the token to determine if a new one # is required duration = datetime.timedelta(seconds=self.session_token_ttl) session_age_limit = datetime.datetime.now() - duration if self.session.last_activity < session_age_limit: self.sid = self.new_sid() if len(self.session.sid) > 2: self.session.sid.remove(self.session.sid[0]) self.session.sid.append(self.sid) do_put = True else: self.sid = self.session.sid[-1] # check if last_activity needs updated ula = datetime.timedelta(seconds=self.last_activity_update) if datetime.datetime.now() > self.session.last_activity + \ ula: do_put = True self.output_cookie[cookie_name] = self.sid self.output_cookie[cookie_name]["path"] = cookie_path if self.set_cookie_expires: self.output_cookie[cookie_name]["expires"] = \ self.session_expire_time self.cache[u"sid"] = self.sid if do_put: if self.sid != None or self.sid != u"": self.session.put() if self.set_cookie_expires: if not self.output_cookie.has_key("%s_data" % (cookie_name)): self.output_cookie["%s_data" % (cookie_name)] = u"" self.output_cookie["%s_data" % (cookie_name)]["expires"] = \ self.session_expire_time print self.output_cookie.output() # fire up a Flash object if integration is enabled if self.integrate_flash: import flash self.flash = flash.Flash(cookie=self.cookie) # randomly delete old stale sessions in the datastore (see # CLEAN_CHECK_PERCENT variable) if random.randint(1, 100) < clean_check_percent: self._clean_old_sessions() def new_sid(self): """ Create a new session id. Returns session id as a unicode string. """ sid = u"%s_%s" % (self.session.session_key, hashlib.md5(repr(time.time()) + \ unicode(random.random())).hexdigest() ) #sid = unicode(self.session.session_key) + "_" + \ # hashlib.md5(repr(time.time()) + \ # unicode(random.random())).hexdigest() return sid def _get(self, keyname=None): """ private method Return all of the SessionData object data from the datastore only, unless keyname is specified, in which case only that instance of SessionData is returned. Important: This does not interact with memcache and pulls directly from the datastore. This also does not get items from the cookie store. Args: keyname: The keyname of the value you are trying to retrieve. Returns a list of datastore entities. """ if keyname != None: return self.session.get_item(keyname) return self.session.get_items() def _validate_key(self, keyname): """ private method Validate the keyname, making sure it is set and not a reserved name. Returns the validated keyname. """ if keyname is None: raise ValueError( u"You must pass a keyname for the session data content." ) elif keyname in (u"sid", u"flash"): raise ValueError(u"%s is a reserved keyname." % keyname) if type(keyname) != type([str, unicode]): return unicode(keyname) return keyname def _put(self, keyname, value): """ Insert a keyname/value pair into the datastore for the session. Args: keyname: The keyname of the mapping. value: The value of the mapping. Returns the value from the writer put operation, varies based on writer. """ if self.writer == "datastore": writer = _DatastoreWriter() else: writer = _CookieWriter() return writer.put(keyname, value, self) def _delete_session(self): """ private method Delete the session and all session data. Returns True. """ # if the event class has been loaded, fire off the preSessionDelete event if u"AEU_Events" in __main__.__dict__: __main__.AEU_Events.fire_event(u"preSessionDelete") if hasattr(self, u"session"): self.session.delete() self.cookie_vals = {} self.cache = {} self.output_cookie["%s_data" % (self.cookie_name)] = \ simplejson.dumps(self.cookie_vals) print self.output_cookie.output() # if the event class has been loaded, fire off the sessionDelete event if u"AEU_Events" in __main__.__dict__: __main__.AEU_Events.fire_event(u"sessionDelete") return True def delete(self): """ Delete the current session and start a new one. This is useful for when you need to get rid of all data tied to a current session, such as when you are logging out a user. Returns True """ self._delete_session() @classmethod def delete_all_sessions(cls): """ Deletes all sessions and session data from the data store. This does not delete the entities from memcache (yet). Depending on the amount of sessions active in your datastore, this request could timeout before completion and may have to be called multiple times. NOTE: This can not delete cookie only sessions as it has no way to access them. It will only delete datastore writer sessions. Returns True on completion. """ all_sessions_deleted = False while not all_sessions_deleted: query = _AppEngineUtilities_Session.all() results = query.fetch(75) if len(results) is 0: all_sessions_deleted = True else: for result in results: result.delete() return True def _clean_old_sessions(self): """ Delete 50 expired sessions from the datastore. This is only called for CLEAN_CHECK_PERCENT percent of requests because it could be rather intensive. Returns True on completion """ duration = datetime.timedelta(seconds=self.session_expire_time) session_age = datetime.datetime.now() - duration query = _AppEngineUtilities_Session.all() query.filter(u"last_activity <", session_age) results = query.fetch(50) for result in results: result.delete() return True def cycle_key(self): """ Changes the session id/token. Returns new token. """ self.sid = self.new_sid() if len(self.session.sid) > 2: self.session.sid.remove(self.session.sid[0]) self.session.sid.append(self.sid) return self.sid def flush(self): """ Delete's the current session, creating a new one. Returns True """ self._delete_session() self.__init__() return True def no_cache_headers(self): """ Generates headers to avoid any page caching in the browser. Useful for highly dynamic sites. Returns a unicode string of headers. """ return u"".join([u"Expires: Tue, 03 Jul 2001 06:00:00 GMT", strftime("Last-Modified: %a, %d %b %y %H:%M:%S %Z").decode("utf-8"), u"Cache-Control: no-store, no-cache, must-revalidate, max-age=0", u"Cache-Control: post-check=0, pre-check=0", u"Pragma: no-cache", ]) def clear(self): """ Removes session data items, doesn't delete the session. It does work with cookie sessions, and must be called before any output is sent to the browser, as it set cookies. Returns True """ sessiondata = self._get() # delete from datastore if sessiondata is not None: for sd in sessiondata: sd.delete() # delete from memcache self.cache = {} self.cookie_vals = {} self.output_cookie["%s_data" %s (self.cookie_name)] = \ simplejson.dumps(self.cookie_vals) print self.output_cookie.output() return True def has_key(self, keyname): """ Equivalent to k in a, use that form in new code Args: keyname: keyname to check Returns True/False """ return self.__contains__(keyname) def items(self): """ Creates a copy of just the data items. Returns dictionary of session data objects. """ op = {} for k in self: op[k] = self[k] return op def keys(self): """ Returns a list of keys. """ l = [] for k in self: l.append(k) return l def update(self, *dicts): """ Updates with key/value pairs from b, overwriting existing keys Returns None """ for dict in dicts: for k in dict: self._put(k, dict[k]) return None def values(self): """ Returns a list object of just values in the session. """ v = [] for k in self: v.append(self[k]) return v def get(self, keyname, default = None): """ Returns either the value for the keyname or a default value passed. Args: keyname: keyname to look up default: (optional) value to return on keyname miss Returns value of keyname, or default, or None """ try: return self.__getitem__(keyname) except KeyError: if default is not None: return default return None def setdefault(self, keyname, default = None): """ Returns either the value for the keyname or a default value passed. If keyname lookup is a miss, the keyname is set with a value of default. Args: keyname: keyname to look up default: (optional) value to return on keyname miss Returns value of keyname, or default, or None """ try: return self.__getitem__(keyname) except KeyError: if default is not None: self.__setitem__(keyname, default) return default return None @classmethod def check_token(cls, cookie_name=COOKIE_NAME, delete_invalid=True): """ Retrieves the token from a cookie and validates that it is a valid token for an existing cookie. Cookie validation is based on the token existing on a session that has not expired. This is useful for determining if datastore or cookie writer should be used in hybrid implementations. Args: cookie_name: Name of the cookie to check for a token. delete_invalid: If the token is not valid, delete the session cookie, to avoid datastore queries on future requests. Returns True/False """ string_cookie = os.environ.get(u"HTTP_COOKIE", u"") cookie = Cookie.SimpleCookie() cookie.load(string_cookie) if cookie.has_key(cookie_name): query = _AppEngineUtilities_Session.all() query.filter(u"sid", cookie[cookie_name].value) results = query.fetch(1) if len(results) > 0: return True else: if delete_invalid: output_cookie = Cookie.SimpleCookie() output_cookie[cookie_name] = cookie[cookie_name] output_cookie[cookie_name][u"expires"] = 0 print output_cookie.output() return False def get_ds_entity(self): """ Will return the session entity from the datastore if one exists, otherwise will return None (as in the case of cookie writer session. """ if hasattr(self, u"session"): return self.session return None # Implement Python container methods def __getitem__(self, keyname): """ Get item from session data. keyname: The keyname of the mapping. """ # flash messages don't go in the datastore if self.integrate_flash and (keyname == u"flash"): return self.flash.msg if keyname in self.cache: return self.cache[keyname] if keyname in self.cookie_vals: return self.cookie_vals[keyname] if hasattr(self, u"session"): data = self._get(keyname) if data: # TODO: It's broke here, but I'm not sure why, it's # returning a model object, but I can't seem to modify # it. try: if data.model != None: self.cache[keyname] = data.model return self.cache[keyname] else: self.cache[keyname] = pickle.loads(data.content) return self.cache[keyname] except: self.delete_item(keyname) else: raise KeyError(unicode(keyname)) raise KeyError(unicode(keyname)) def __setitem__(self, keyname, value): """ Set item in session data. Args: keyname: They keyname of the mapping. value: The value of mapping. """ if self.integrate_flash and (keyname == u"flash"): self.flash.msg = value else: keyname = self._validate_key(keyname) self.cache[keyname] = value return self._put(keyname, value) def delete_item(self, keyname, throw_exception=False): """ Delete item from session data, ignoring exceptions if necessary. Args: keyname: The keyname of the object to delete. throw_exception: false if exceptions are to be ignored. Returns: Nothing. """ if throw_exception: self.__delitem__(keyname) return None else: try: self.__delitem__(keyname) except KeyError: return None def __delitem__(self, keyname): """ Delete item from session data. Args: keyname: The keyname of the object to delete. """ bad_key = False sessdata = self._get(keyname = keyname) if sessdata is None: bad_key = True else: sessdata.delete() if keyname in self.cookie_vals: del self.cookie_vals[keyname] bad_key = False self.output_cookie["%s_data" % (self.cookie_name)] = \ simplejson.dumps(self.cookie_vals) print self.output_cookie.output() if bad_key: raise KeyError(unicode(keyname)) if keyname in self.cache: del self.cache[keyname] def __len__(self): """ Return size of session. """ # check memcache first if hasattr(self, u"session"): results = self._get() if results is not None: return len(results) + len(self.cookie_vals) else: return 0 return len(self.cookie_vals) def __contains__(self, keyname): """ Check if an item is in the session data. Args: keyname: The keyname being searched. """ try: self.__getitem__(keyname) except KeyError: return False return True def __iter__(self): """ Iterate over the keys in the session data. """ # try memcache first if hasattr(self, u"session"): vals = self._get() if vals is not None: for k in vals: yield k.keyname for k in self.cookie_vals: yield k def __str__(self): """ Return string representation. """ return u"{%s}" % ', '.join(['"%s" = "%s"' % (k, self[k]) for k in self])
Python
# -*- coding: utf-8 -*- """ Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # main python imports import datetime import pickle import random import __main__ # google appengine import from google.appengine.ext import db from google.appengine.api import memcache # settings try: import settings except: import settings_default as settings class _AppEngineUtilities_Cache(db.Model): cachekey = db.StringProperty() createTime = db.DateTimeProperty(auto_now_add=True) timeout = db.DateTimeProperty() value = db.BlobProperty() class Cache(object): """ Cache is used for storing pregenerated output and/or objects in the Big Table datastore to minimize the amount of queries needed for page displays. The idea is that complex queries that generate the same results really should only be run once. Cache can be used to store pregenerated value made from queries (or other calls such as urlFetch()), or the query objects themselves. Cache is a standard dictionary object and can be used as such. It attesmpts to store data in both memcache, and the datastore. However, should a datastore write fail, it will not try again. This is for performance reasons. """ def __init__(self, clean_check_percent = settings.cache["CLEAN_CHECK_PERCENT"], max_hits_to_clean = settings.cache["MAX_HITS_TO_CLEAN"], default_timeout = settings.cache["DEFAULT_TIMEOUT"]): """ Initializer Args: clean_check_percent: how often cache initialization should run the cache cleanup max_hits_to_clean: maximum number of stale hits to clean default_timeout: default length a cache item is good for """ self.clean_check_percent = clean_check_percent self.max_hits_to_clean = max_hits_to_clean self.default_timeout = default_timeout if random.randint(1, 100) < self.clean_check_percent: self._clean_cache() if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheInitialized') def _clean_cache(self): """ _clean_cache is a routine that is run to find and delete cache items that are old. This helps keep the size of your over all datastore down. It only deletes the max_hits_to_clean per attempt, in order to maximize performance. Default settings are 20 hits, 50% of requests. Generally less hits cleaned on more requests will give you better performance. Returns True on completion """ query = _AppEngineUtilities_Cache.all() query.filter('timeout < ', datetime.datetime.now()) results = query.fetch(self.max_hits_to_clean) db.delete(results) return True def _validate_key(self, key): """ Internal method for key validation. This can be used by a superclass to introduce more checks on key names. Args: key: Key name to check Returns True is key is valid, otherwise raises KeyError. """ if key == None: raise KeyError return True def _validate_value(self, value): """ Internal method for value validation. This can be used by a superclass to introduce more checks on key names. Args: value: value to check Returns True is value is valid, otherwise raises ValueError. """ if value == None: raise ValueError return True def _validate_timeout(self, timeout): """ Internal method to validate timeouts. If no timeout is passed, then the default_timeout is used. Args: timeout: datetime.datetime format Returns the timeout """ if timeout == None: timeout = datetime.datetime.now() +\ datetime.timedelta(seconds=self.default_timeout) if type(timeout) == type(1): timeout = datetime.datetime.now() + \ datetime.timedelta(seconds = timeout) if type(timeout) != datetime.datetime: raise TypeError if timeout < datetime.datetime.now(): raise ValueError return timeout def add(self, key = None, value = None, timeout = None): """ Adds an entry to the cache, if one does not already exist. If they key already exists, KeyError will be raised. Args: key: Key name of the cache object value: Value of the cache object timeout: timeout value for the cache object. Returns the cache object. """ self._validate_key(key) self._validate_value(value) timeout = self._validate_timeout(timeout) if key in self: raise KeyError cacheEntry = _AppEngineUtilities_Cache() cacheEntry.cachekey = key cacheEntry.value = pickle.dumps(value) cacheEntry.timeout = timeout # try to put the entry, if it fails silently pass # failures may happen due to timeouts, the datastore being read # only for maintenance or other applications. However, cache # not being able to write to the datastore should not # break the application try: cacheEntry.put() except: pass memcache_timeout = timeout - datetime.datetime.now() memcache.set('cache-%s' % (key), value, int(memcache_timeout.seconds)) if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheAdded') return self.get(key) def set(self, key = None, value = None, timeout = None): """ Sets an entry to the cache, overwriting an existing value if one already exists. Args: key: Key name of the cache object value: Value of the cache object timeout: timeout value for the cache object. Returns the cache object. """ self._validate_key(key) self._validate_value(value) timeout = self._validate_timeout(timeout) cacheEntry = self._read(key) if not cacheEntry: cacheEntry = _AppEngineUtilities_Cache() cacheEntry.cachekey = key cacheEntry.value = pickle.dumps(value) cacheEntry.timeout = timeout try: cacheEntry.put() except: pass memcache_timeout = timeout - datetime.datetime.now() memcache.set('cache-%s' % (key), value, int(memcache_timeout.seconds)) if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheSet') return self.get(key) def _read(self, key = None): """ _read is an internal method that will get the cache entry directly from the datastore, and return the entity. This is used for datastore maintenance within the class. Args: key: The key to retrieve Returns the cache entity """ query = _AppEngineUtilities_Cache.all() query.filter('cachekey', key) query.filter('timeout > ', datetime.datetime.now()) results = query.fetch(1) if len(results) is 0: return None if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheReadFromDatastore') if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheRead') return results[0] def delete(self, key = None): """ Deletes a cache object. Args: key: The key of the cache object to delete. Returns True. """ memcache.delete('cache-%s' % (key)) result = self._read(key) if result: if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheDeleted') result.delete() return True def get(self, key): """ Used to return the cache value associated with the key passed. Args: key: The key of the value to retrieve. Returns the value of the cache item. """ mc = memcache.get('cache-%s' % (key)) if mc: if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheReadFromMemcache') if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheRead') return mc result = self._read(key) if result: timeout = result.timeout - datetime.datetime.now() memcache.set('cache-%s' % (key), pickle.loads(result.value), int(timeout.seconds)) if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheRead') return pickle.loads(result.value) else: raise KeyError def get_many(self, keys): """ Returns a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict. Args: keys: A list of keys to retrieve. Returns a dictionary of key/value pairs. """ dict = {} for key in keys: value = self.get(key) if value is not None: dict[key] = val return dict def __getitem__(self, key): """ __getitem__ is necessary for this object to emulate a container. """ return self.get(key) def __setitem__(self, key, value): """ __setitem__ is necessary for this object to emulate a container. """ return self.set(key, value) def __delitem__(self, key): """ Implement the 'del' keyword """ return self.delete(key) def __contains__(self, key): """ Implements "in" operator """ try: self.__getitem__(key) except KeyError: return False return True def has_key(self, keyname): """ Equivalent to k in a, use that form in new code """ return self.__contains__(keyname)
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import time from google.appengine.api import datastore from google.appengine.ext import db # settings try: import settings except: import settings_default as settings class ROTModel(db.Model): """ ROTModel overrides the db.Model functions, retrying each method each time a timeout exception is raised. Methods superclassed from db.Model are: get(cls, keys) get_by_id(cls, ids, parent) get_by_key_name(cls, key_names, parent) get_or_insert(cls, key_name, kwargs) put(self) """ @classmethod def get(cls, keys): count = 0 while count < settings.rotmodel["RETRY_ATTEMPTS"]: try: return db.Model.get(keys) except db.Timeout(): count += 1 time.sleep(count * settings.rotmodel["RETRY_INTERVAL"]) else: raise db.Timeout() @classmethod def get_by_id(cls, ids, parent=None): count = 0 while count < settings.rotmodel["RETRY_ATTEMPTS"]: try: return db.Model.get_by_id(ids, parent) except db.Timeout(): count += 1 time.sleep(count * settings.rotmodel["RETRY_INTERVAL"]) else: raise db.Timeout() @classmethod def get_by_key_name(cls, key_names, parent=None): if isinstance(parent, db.Model): parent = parent.key() key_names, multiple = datastore.NormalizeAndTypeCheck(key_names, basestring) keys = [datastore.Key.from_path(cls.kind(), name, parent=parent) for name in key_names] count = 0 if multiple: while count < settings.rotmodel["RETRY_ATTEMPTS"]: try: return db.get(keys) except db.Timeout(): count += 1 time.sleep(count * settings.rotmodel["RETRY_INTERVAL"]) else: while count < settings.rotmodel["RETRY_ATTEMPTS"]: try: return db.get(*keys) except db.Timeout(): count += 1 time.sleep(count * settings.rotmodel["RETRY_INTERVAL"]) @classmethod def get_or_insert(cls, key_name, **kwargs): def txn(): entity = cls.get_by_key_name(key_name, parent=kwargs.get('parent')) if entity is None: entity = cls(key_name=key_name, **kwargs) entity.put() return entity return db.run_in_transaction(txn) def put(self): count = 0 while count < settings.rotmodel["RETRY_ATTEMPTS"]: try: return db.Model.put(self) except db.Timeout(): count += 1 time.sleep(count * settings.rotmodel["RETRY_INTERVAL"]) else: raise db.Timeout() def delete(self): count = 0 while count < settings.rotmodel["RETRY_ATTEMPTS"]: try: return db.Model.delete(self) except db.Timeout(): count += 1 time.sleep(count * settings.rotmodel["RETRY_INTERVAL"]) else: raise db.Timeout()
Python
import Cookie import os from common.appengine_utilities import sessions class SessionMiddleware(object): TEST_COOKIE_NAME = 'testcookie' TEST_COOKIE_VALUE = 'worked' def process_request(self, request): """ Check to see if a valid session token exists, if not, then use a cookie only session. It's up to the application to convert the session to a datastore session. Once this has been done, the session will continue to use the datastore unless the writer is set to "cookie". Setting the session to use the datastore is as easy as resetting request.session anywhere if your application. Example: from common.appengine_utilities import sessions request.session = sessions.Session() """ self.request = request if sessions.Session.check_token(): request.session = sessions.Session() else: request.session = sessions.Session(writer="cookie") request.session.set_test_cookie = self.set_test_cookie request.session.test_cookie_worked = self.test_cookie_worked request.session.delete_test_cookie = self.delete_test_cookie request.session.save = self.save def set_test_cookie(self): string_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) self.cookie[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE print self.cookie def test_cookie_worked(self): string_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) return self.cookie.get(self.TEST_COOKIE_NAME) def delete_test_cookie(self): string_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) self.cookie[self.TEST_COOKIE_NAME] = '' self.cookie[self.TEST_COOKIE_NAME]['path'] = '/' self.cookie[self.TEST_COOKIE_NAME]['expires'] = 0 def save(self): self.request.session = sessions.Session()
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import os import Cookie from time import strftime from django.utils import simplejson # settings try: import settings except: import settings_default as settings COOKIE_NAME = settings.flash["COOKIE_NAME"] class Flash(object): """ Send messages to the user between pages. When you instantiate the class, the attribute 'msg' will be set from the cookie, and the cookie will be deleted. If there is no flash cookie, 'msg' will default to None. To set a flash message for the next page, simply set the 'msg' attribute. Example psuedocode: if new_entity.put(): flash = Flash() flash.msg = 'Your new entity has been created!' return redirect_to_entity_list() Then in the template on the next page: {% if flash.msg %} <div class="flash-msg">{{ flash.msg }}</div> {% endif %} """ def __init__(self, cookie=None): """ Load the flash message and clear the cookie. """ print self.no_cache_headers() # load cookie if cookie is None: browser_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(browser_cookie) else: self.cookie = cookie # check for flash data if self.cookie.get(COOKIE_NAME): # set 'msg' attribute cookie_val = self.cookie[COOKIE_NAME].value # we don't want to trigger __setattr__(), which creates a cookie try: self.__dict__['msg'] = simplejson.loads(cookie_val) except: # not able to load the json, so do not set message. This should # catch for when the browser doesn't delete the cookie in time for # the next request, and only blanks out the content. pass # clear the cookie self.cookie[COOKIE_NAME] = '' self.cookie[COOKIE_NAME]['path'] = '/' self.cookie[COOKIE_NAME]['expires'] = 0 print self.cookie[COOKIE_NAME] else: # default 'msg' attribute to None self.__dict__['msg'] = None def __setattr__(self, name, value): """ Create a cookie when setting the 'msg' attribute. """ if name == 'cookie': self.__dict__['cookie'] = value elif name == 'msg': self.__dict__['msg'] = value self.__dict__['cookie'][COOKIE_NAME] = simplejson.dumps(value) self.__dict__['cookie'][COOKIE_NAME]['path'] = '/' print self.cookie else: raise ValueError('You can only set the "msg" attribute.') def no_cache_headers(self): """ Generates headers to avoid any page caching in the browser. Useful for highly dynamic sites. Returns a unicode string of headers. """ return u"".join([u"Expires: Tue, 03 Jul 2001 06:00:00 GMT", strftime("Last-Modified: %a, %d %b %y %H:%M:%S %Z").decode("utf-8"), u"Cache-Control: no-store, no-cache, must-revalidate, max-age=0", u"Cache-Control: post-check=0, pre-check=0", u"Pragma: no-cache", ])
Python
# -*- coding: utf-8 -*- from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from web.article import ViewArticle, TemplatePage, CreateUpdateArticle from web.comment import AddComment, DeleteComment from web.rss import RssFeed from web.stats import SubmitVersion, ShowStats, SetVersion, RobotsTXT from web.constants import get_admin_user from google.appengine.api import users import os from google.appengine.ext.webapp import template from recaptcha.client import captcha class LoginPage(webapp.RequestHandler): def get(self): user = get_admin_user() if user: self.response.out.write('Hello, ' + user.nickname()) else: self.redirect(users.create_login_url(self.request.uri)) class HomePage(webapp.RequestHandler): def get(self): self.redirect("/") application = webapp.WSGIApplication([ ('/login', LoginPage), ('/edit', CreateUpdateArticle), ('/rss', RssFeed), ('/version', SubmitVersion), ('/set_version', SetVersion), ('/add_commnet', AddComment), ('/delete_comment', DeleteComment), ('/stats', ShowStats), (r'/article/(.*)/(.*)', ViewArticle), (r'/article/(.*)', ViewArticle), (r'/(.*)/(.*)/(.*)', TemplatePage), (r'/(.*)/(.*)', TemplatePage), ('/page_404', HomePage), ('/robots.txt', RobotsTXT), (r'/(.*)', TemplatePage), ], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
from google.appengine.ext import webapp from web.constants import get_admin_user, title, slogan, menu, ARTICLES_ON_PAGE, \ cleaner from appengine_utilities import sessions from web.models import ArticleModel, CommentModel, StatisticModel, \ CommonStatisticModel, VersoinModel from google.appengine.ext.webapp import template import uuid import os from web.translate import translate from datetime import datetime, timedelta from sets import Set from google.appengine.api import memcache def get_stat_string(): return "disabled" stat_string = memcache.get("stats_string") if stat_string: return stat_string stats = CommonStatisticModel().all() stats.order("-date") stats.fetch(1) if stats.count() > 1: value = stats[0].count else: value = 0 memcache.add(key="stats_string", value=value, time=3600) return value class SetVersion(webapp.RequestHandler): def get(self): if not get_admin_user(): self.redirect("/version") return version = self.request.get('version') if version: v = VersoinModel() v.version = version v.put() self.redirect("/version") class SubmitVersion(webapp.RequestHandler): def get(self): uuid = self.request.get('uuid') host = self.request.get('host') current_version = self.request.get('v') if uuid and host: find = StatisticModel().all() find.filter("userUUID", uuid) find.filter("host", host) find.filter("date", datetime.now().date()) find.fetch(1) """if not hound uniq pc""" if find.count() == 0: nfind = CommonStatisticModel().all() nfind.filter("date", datetime.now().date()) nfind.fetch(1) if nfind.count() >= 1: add = nfind[0] add.count += 1 add.put() else: add = CommonStatisticModel() add.put() model = StatisticModel() model.userUUID = uuid[:100] model.host = host[:100] model.v = current_version model.put() versions = VersoinModel.all() versions.order('-date') versions.fetch(1) version = versions[0].version self.response.out.write(version) class RobotsTXT(webapp.RequestHandler): def post(self): self.get() def get(self): path = os.path.join(os.path.dirname(__file__), 'robots.txt') self.response.out.write(template.render(path, None)) class ShowStats(webapp.RequestHandler): def get(self): if not get_admin_user(): self.response.out.write("Not admin no statistsic") return None stats = CommonStatisticModel().all() stats.order("-date") for stat in stats: self.response.out.write(str(stat.date) + " <b>" + str(stat.count) + "</b><br/>"); self.response.out.write("=================================<br/>"); current = datetime.today() today = datetime(current.year, current.month, current.day, 0, 0, 0, 0) for i in xrange(3): models = StatisticModel.all() host = self.request.get('host') if host: models.filter("host", host); models.order('-date') yesterday = today + timedelta(days= -i + 1) be_yesterday = today + timedelta(days= -i) models.filter('date >', be_yesterday) models.filter('date <', yesterday) models.fetch(1000) set_uuid = Set() set_host = Set() for model in models: set_uuid.add(model.userUUID) set_host.add(model.host) if host: line = str(model.userUUID) + " : " + str(model.host) + " : <b>" + model.date.strftime("%d/%m/%Y") + "</b> </br>" self.response.out.write(line) aver = (len(set_uuid) + len(set_host)) / 2 self.response.out.write("<br/><b>" + be_yesterday.strftime("%d/%m/%Y") + " </b>uuid: " + str(len(set_uuid)) + " hosts: " + str(len(set_host)) + " <b> " + str(aver) + "</b><br/>") for host in set_host: self.response.out.write("<a href='stats?host=" + str(host) + "'>" + str(host) + "</a>, ")
Python
from google.appengine.ext import webapp from web.constants import get_admin_user, title, slogan, menu, ARTICLES_ON_PAGE, \ cleaner from appengine_utilities import sessions from web.models import ArticleModel, CommentModel from google.appengine.ext.webapp import template import uuid import os from web.translate import translate from google.appengine.api import mail from recaptcha.client import captcha def send_email_to_admin(text): mail.send_mail(sender="ivan.ivanenko@gmail.com", to="ivan.ivanenko@gmail.com", subject="New comment", body=text) class DeleteComment(webapp.RequestHandler): def get(self): cuuid = self.request.get('cuuid') u_id = self.request.get('uuid') lang = self.request.get('lang') if cuuid: cm = CommentModel().get(cuuid) cm.delete() self.redirect("/article/" + u_id + "/" + lang) class AddComment(webapp.RequestHandler): def post(self): self.get() def get(self): #self.response.out.write("Comments templorary disabled!") #return "Comments" """"comments""" name = self.request.get('name') site = self.request.get('site') comment = self.request.get('comment') u_id = self.request.get('uuid') lang = self.request.get('lang') if not lang: lang = "rus" try: article = ArticleModel.get_by_id(int(u_id)) except: self.redirect("/page_404") return None if not article: self.redirect("/page_404") return None """verify captcha""" remote_ip = self.request.remote_addr challenge = self.request.get('recaptcha_challenge_field') response = self.request.get('recaptcha_response_field') recaptcha_response = captcha.submit(challenge, response, "6Ld9tL0SAAAAAA8RPX--P6dgmyJ2HUeUdBUfLLAM", remote_ip) link = "/article/" + u_id + "/" + lang if not recaptcha_response.is_valid: #self.response.out.write("Not valid == "+str(recaptcha_response.error_code) + " == ip:" + remote_ip+" == chall: "+challenge+" == resp: "+response) self.redirect(link + "?name=%s&site=%s&comment=%s" % (name, site, comment)) return if name and comment: session = sessions.Session() if not session.has_key('user_id'): session['user_id'] = uuid.uuid4().hex cm = CommentModel() cm.article = article cm.name = cleaner.strip(name[:100]) if not site: site = "http://foobnix.com" if site and not site.startswith("http://"): site = "http://" + site cm.site = cleaner.strip(site[:100]) comment = cleaner.strip(comment[:500]) cm.comment = comment cm.comment_eng = translate(comment, src="ru", to="en") cm.user_id = session['user_id'] cm.put() send_email_to_admin("@" + name + " " + comment + " http://www.foobnix.com" + link) self.redirect(link)
Python
#-*- coding: utf-8 -*- ''' Created on 20 сент. 2010 @author: ivan ''' from google.appengine.api import users from web import xss menu = [ {"id" : "news", "rus" : "Главная", "eng" : "Main"}, {"id" : "screenshots", "rus" : "Внешний вид", "eng" : "Screenshots"}, {"id" : "about", "rus" : "Описание", "eng" : "About/Description"}, {"id" : "download", "rus" : "Скачать", "eng" : "Download"}, {"id" : "donate", "rus" : "Поддержать (Donate)", "eng" : "Donate"}, #{"id" : "radio", "rus" : "Радиостанции", "eng" : "Radio"}, {"id" : "feedback", "rus" : "Отзывы", "eng" : "Feedback"}, {"id" : "statistics", "rus" : "Статистика", "eng" : "Statistics"}, #{"id" : "other", "rus" : "Другое", "eng" : "Other"}, ] title = { "rus" : "Foobnix простой и мощный плеер музыки для Linux", "eng" : "Foobnix Simple and Powerful music player for Linux" } slogan = { "rus" : "Все лучшее в одном плеере", "eng" : "All best features in one player" } search = { "rus" : "Хороший Муз. Поиск", "eng" : "Free Music Search" } donate = { "rus":"""Foobnix бесплатный плеер(спасибо за Донейты). Я надеюсь вы буде довольны им. <a href="mailto:ivan.ivanenko@gmail.com" style="background:none">ivan.ivanenko@gmail.com</a>""", "eng":"""Foobnix is free of charge(thanks to your donations). I hope you'll enjoy it. <a href="mailto:ivan.ivanenko@gmail.com" style="background:none">ivan.ivanenko@gmail.com</a>""" } admins = ["ivan.ivanenko"] ARTICLES_ON_PAGE = 5 def get_admin_user(): user = users.get_current_user() if user and user.nickname() in admins: return user return None cleaner = xss.XssCleaner()
Python
# -*- coding: utf-8 -*- dict = { u'а':'a', u'б':'b', u'в':'v', u'г':'g', u'д':'d', u'е':'e', u'ё':'e', u'з':'z', u'и':'i', u'й':'j', u'к':'k', u'л':'l', u'м':'m', u'н':'n', u'о':'o', u'п':'p', u'р':'r', u'с':'s', u'т':'t', u'у':'u', u'ф':'f', u'х':'h', u'ъ':"'", u'ы':'y', u'ь':"'", u'э':'e', u'А':'A', u'Б':'B', u'В':'V', u'Г':'G', u'Д':'D', u'Е':'E', u'Ё':'E', u'З':'Z', u'И':'I', u'Й':'J', u'К':'K', u'Л':'L', u'М':'M', u'Н':'N', u'О':'O', u'П':'P', u'Р':'R', u'С':'S', u'Т':'T', u'У':'U', u'Ф':'F', u'Х':'H', u'Ъ':"'", u'Ы':'Y', u'Ь':"'", u'Э':'E', u'ж':'zh', u'ц':'ts', u'ч':'ch', u'ш':'sh', u'щ':'sch', u'ю':'ju', u'я':'ja', u'Ж':'Zh', u'Ц':'Ts', u'Ч':'Ch', u' ':'_'} def tilte_translate(s): if s: s = s.strip() for k in dict.keys(): s = s.replace(k, dict[k]) return s
Python
from google.appengine.ext import webapp from web.constants import get_admin_user, title, slogan, search, menu, ARTICLES_ON_PAGE, \ donate from appengine_utilities import sessions from web.models import ArticleModel, CommentModel, CommonStatisticModel from google.appengine.ext.webapp import template import uuid import os from web.translate import translate from web.utils import tilte_translate from web.stats import get_stat_string class ViewArticle(webapp.RequestHandler): def get(self, u_id, lang="rus"): user = get_admin_user() # u_id = self.request.get('uuid') #lang = self.request.get('lang') session = sessions.Session() if not session.has_key('user_id'): session['user_id'] = uuid.uuid4().hex try: article = ArticleModel.get_by_id(int(u_id)) except: self.redirect("/page_404") return None if not article: self.redirect("/page_404") return None comments = article.commentmodel_set comments.fetch(100) all = self.request.get('all') if all: comments = CommentModel.all() comments.order('-date') template_values = { 'statistics': get_stat_string(), 'session':session, 'comments':comments, 'title':title, 'slogan':slogan, 'donate':donate, 'search':search, 'lang':lang, 'id':u_id, 'article': article, 'user': user, 'menu':menu, "name" : self.request.get('name'), "site" : self.request.get('site'), "comment" : self.request.get('comment') } path = os.path.join(os.path.dirname(__file__), 'view_article.html') self.response.out.write(template.render(path, template_values)) class TemplatePage(webapp.RequestHandler): def get_render_page(self, category="news", lang="rus", index=0, stat_string=None): stats = None if category == "statistics": stats = CommonStatisticModel().all() stats.order("-date") stats.fetch(30) template_values = { 'stats': stats, 'stat_string':stat_string } if int(index) <= 0: index = 0 find = False for menu_item in menu: if category == menu_item['id']: find = True break; if not find: self.redirect("/page_404") query = ArticleModel.all() if category != "other": query.filter("category", category) query.order('-date') articles = query.fetch(ARTICLES_ON_PAGE, ARTICLES_ON_PAGE * int(index)) user = get_admin_user() template_values = { 'stats': stats, 'stat_string':stat_string, 'lang': lang, 'index': int(index) + 1, 'index1': int(index) - 1, 'user': user, 'category':category, 'articles': articles, } path = os.path.join(os.path.dirname(__file__), 'article_list.html') return template.render(path, template_values) def get(self, category="news", lang="rus", index=0): user = get_admin_user() if user: username = "Hello " + user.nickname() else: username = "Hello anonimous" #category = self.request.get("page") if not category: category = "news" #lang = self.request.get('lang') stat_string = get_stat_string() content = self.get_render_page(category, lang, index, stat_string) template_values = { 'statistics': stat_string, 'title': title, 'slogan': slogan, 'donate':donate, 'search': search, 'lang': lang, 'user': user, 'page':category, 'menu' : menu, 'content': content, 'username':username } path = os.path.join(os.path.dirname(__file__), 'template.html') self.response.out.write(template.render(path, template_values)) class CreateUpdateArticle(webapp.RequestHandler): def get(self): delete = self.request.get('delete') if delete: uuid = self.request.get('uuid') model = ArticleModel.get_by_id(int(uuid)) if model: model.delete() self.redirect("/") return True self.post() def post(self): uuid = self.request.get('uuid') category = self.request.get('category') if uuid: model = ArticleModel.get_by_id(int(uuid)) else: model = ArticleModel() user = get_admin_user() if user: model.author = user if self.request.get('create'): model.title = self.request.get('title') model.title_eng = translate(model.title, src="ru", to="en") model.content = self.request.get('content') model.content_eng = translate(model.content, src="ru", to="en") model.category = self.request.get('category') model.keywords = self.request.get('keywords') model.visible = self.request.get('visible') model.title_translit = tilte_translate(model.title) model.put() uuid = model.key().id() template_values = { 'user': user, 'menu':menu, 'category': category, 'uuid': uuid, 'model': model, } path = os.path.join(os.path.dirname(__file__), 'edit_article.html') self.response.out.write(template.render(path, template_values))
Python
from google.appengine.ext import webapp from web.models import ArticleModel from web.constants import title import datetime import os from google.appengine.ext.webapp import template class RssFeed(webapp.RequestHandler): def get(self): models = ArticleModel.all() models.order('-date') models.fetch(10) lang = self.request.get('lang') template_values = { 'title':title, 'lang':lang, 'date': datetime, 'uuid': "234213041234021340234", 'models': models, } path = os.path.join(os.path.dirname(__file__), 'rss.xml') self.response.out.write(template.render(path, template_values))
Python
#-*- coding: utf-8 -*- ''' Created on 20 сент. 2010 @author: ivan ''' from google.appengine.ext import db class ArticleModel(db.Model): author = db.UserProperty() title = db.StringProperty(multiline=False) title_eng = db.StringProperty(multiline=False) title_translit = db.StringProperty(multiline=False) content = db.TextProperty() content_eng = db.TextProperty() keywords = db.StringProperty(multiline=False) date = db.DateTimeProperty(auto_now_add=True) category = db.StringProperty(required=False) visible = db.StringProperty(required=False) class VersoinModel(db.Model): version = db.StringProperty(multiline=False) date = db.DateTimeProperty(auto_now_add=True) class StatisticModel(db.Model): userUUID = db.StringProperty(multiline=False) host = db.StringProperty(multiline=False) date = db.DateProperty(auto_now_add=True) v = db.StringProperty(multiline=False) class CommonStatisticModel(db.Model): date = db.DateProperty(auto_now_add=True) count = db.IntegerProperty(default=1) class CommentModel(db.Model): date = db.DateTimeProperty(auto_now_add=True) name = db.StringProperty(multiline=False) site = db.StringProperty(multiline=False) comment = db.TextProperty() comment_eng = db.TextProperty() article = db.ReferenceProperty(ArticleModel) user_id = db.StringProperty(multiline=False)
Python
#-*- coding: utf-8 -*- ''' Created on 20 сент. 2010 @author: ivan ''' ## {{{ http://code.activestate.com/recipes/496942/ (r1) from htmllib import HTMLParser from cgi import escape from urlparse import urlparse from formatter import AbstractFormatter from htmlentitydefs import entitydefs from xml.sax.saxutils import quoteattr def xssescape(text): """Gets rid of < and > and & and, for good measure, :""" return escape(text, quote=True).replace(':', '&#58;') class XssCleaner(HTMLParser): def __init__(self, fmt=AbstractFormatter): HTMLParser.__init__(self, fmt) self.result = "" self.open_tags = [] # A list of the only tags allowed. Be careful adding to this. Adding # "script," for example, would not be smart. 'img' is out by default # because of the danger of IMG embedded commands, and/or web bugs. self.permitted_tags = ['a', 'b', 'blockquote', 'br', 'i', 'li', 'ol', 'ul', 'p', 'cite'] # A list of tags that require no closing tag. self.requires_no_close = ['img', 'br'] # A dictionary showing the only attributes allowed for particular tags. # If a tag is not listed here, it is allowed no attributes. Adding # "on" tags, like "onhover," would not be smart. Also be very careful # of "background" and "style." self.allowed_attributes = \ {'a':['href', 'title'], 'img':['src', 'alt'], 'blockquote':['type']} # The only schemes allowed in URLs (for href and src attributes). # Adding "javascript" or "vbscript" to this list would not be smart. self.allowed_schemes = ['http', 'https', 'ftp'] def handle_data(self, data): if data: self.result += xssescape(data) def handle_charref(self, ref): if len(ref) < 7 and ref.isdigit(): self.result += '&#%s;' % ref else: self.result += xssescape('&#%s' % ref) def handle_entityref(self, ref): if ref in entitydefs: self.result += '&%s;' % ref else: self.result += xssescape('&%s' % ref) def handle_comment(self, comment): if comment: self.result += xssescape("<!--%s-->" % comment) def handle_starttag(self, tag, method, attrs): if tag not in self.permitted_tags: self.result += xssescape("<%s>" % tag) else: bt = "<" + tag if tag in self.allowed_attributes: attrs = dict(attrs) self.allowed_attributes_here = \ [x for x in self.allowed_attributes[tag] if x in attrs \ and len(attrs[x]) > 0] for attribute in self.allowed_attributes_here: if attribute in ['href', 'src', 'background']: if self.url_is_acceptable(attrs[attribute]): bt += ' %s="%s"' % (attribute, attrs[attribute]) else: bt += ' %s=%s' % \ (xssescape(attribute), quoteattr(attrs[attribute])) if bt == "<a" or bt == "<img": return if tag in self.requires_no_close: bt += "/" bt += ">" self.result += bt self.open_tags.insert(0, tag) def handle_endtag(self, tag, attrs): bracketed = "</%s>" % tag if tag not in self.permitted_tags: self.result += xssescape(bracketed) elif tag in self.open_tags: self.result += bracketed self.open_tags.remove(tag) def unknown_starttag(self, tag, attributes): self.handle_starttag(tag, None, attributes) def unknown_endtag(self, tag): self.handle_endtag(tag, None) def url_is_acceptable(self, url): ### Requires all URLs to be "absolute." parsed = urlparse(url) return parsed[0] in self.allowed_schemes and '.' in parsed[1] def strip(self, rawstring): """Returns the argument stripped of potentially harmful HTML or Javascript code""" self.result = "" self.feed(rawstring) for endtag in self.open_tags: if endtag not in self.requires_no_close: self.result += "</%s>" % endtag return self.result def xtags(self): """Returns a printable string informing the user which tags are allowed""" self.permitted_tags.sort() tg = "" for x in self.permitted_tags: tg += "<" + x if x in self.allowed_attributes: for y in self.allowed_attributes[x]: tg += ' %s=""' % y tg += "> " return xssescape(tg.strip()) ## end of http://code.activestate.com/recipes/496942/ }}}
Python
import urllib import simplejson baseUrl = "http://ajax.googleapis.com/ajax/services/language/translate" def getSplits(text, splitLength=4500): ''' Translate Api has a limit on length of text(4500 characters) that can be translated at once, ''' return (text[index:index + splitLength] for index in xrange(0, len(text), splitLength)) def translate(text, src='en', to='ru'): text = (u"" + text).encode('utf-8') ''' A Python Wrapper for Google AJAX Language API: * Uses Google Language Detection, in cases source language is not provided with the source text * Splits up text if it's longer then 4500 characters, as a limit put up by the API ''' params = ({'langpair': '%s|%s' % (src, to), 'v': '1.0' }) retText = '' for text in getSplits(text): params['q'] = text resp = simplejson.load(urllib.urlopen('%s' % (baseUrl), data=urllib.urlencode(params))) try: retText += resp['responseData']['translatedText'] except: raise return retText
Python
#! /usr/bin/env python # encoding: utf-8 # waf 1.6.10 VERSION='0.3.3' import sys APPNAME='p2t' top = '.' out = 'build' CPP_SOURCES = ['poly2tri/common/shapes.cc', 'poly2tri/sweep/cdt.cc', 'poly2tri/sweep/advancing_front.cc', 'poly2tri/sweep/sweep_context.cc', 'poly2tri/sweep/sweep.cc', 'testbed/main.cc'] from waflib.Tools.compiler_cxx import cxx_compiler cxx_compiler['win32'] = ['g++'] #Platform specific libs if sys.platform == 'win32': # MS Windows sys_libs = ['glfw', 'opengl32'] elif sys.platform == 'darwin': # Apple OSX sys_libs = ['glfw', 'OpenGL'] else: # GNU/Linux, BSD, etc sys_libs = ['glfw', 'GL'] def options(opt): print(' set_options') opt.load('compiler_cxx') def configure(conf): print(' calling the configuration') conf.load('compiler_cxx') conf.env.CXXFLAGS = ['-O3', '-ffast-math'] conf.env.DEFINES_P2T = ['P2T'] conf.env.LIB_P2T = sys_libs def build(bld): print(' building') bld.program(features = 'cxx cxxprogram', source=CPP_SOURCES, target = 'p2t', uselib = 'P2T')
Python
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import webapp2 class MainHandler(webapp2.RequestHandler): def get(self): self.response.write('Hello world!') app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True)
Python
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import webapp2 class MainHandler(webapp2.RequestHandler): def get(self): self.response.write('Hello world!') app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True)
Python
from google.appengine.ext import db class Food(db.Model): """Models a food source entry with an author, date, name, kJ, kcal, carbs, fat, protein""" author = db.UserProperty(required=True) date = db.DateTimeProperty(auto_now_add=True) name = db.StringProperty(required=True) kj = db.IntegerProperty(required=True) kcal = db.IntegerProperty(required=True) protein = db.IntegerProperty(required=True) carbs = db.IntegerProperty(required=True) fat = db.IntegerProperty(required=True) class RegisteredUser(db.Model): """Models a user that has access here, and her attributes""" user = db.UserProperty(required=True) accesslevel = db.StringProperty(required=True,choices=set(["admin", "super", "normal"])) class Profile(db.Model): """Models a user profile with personal data used to calculate caloric needs aso""" user = db.UserProperty(required=True) name = db.StringProperty() gender = db.StringProperty(required=True,choices=set(["male","female"]),default="male") birthyear = db.IntegerProperty(required=True,default=1969) height = db.IntegerProperty(required=True,default=175) lossprofile = db.StringProperty(required=True,choices=set(["1kg pr week","0.5kg pr week","1kg pr month","maintain"]),default="maintain") activitylevel = db.StringProperty(required=True,choices=set(["seditary","light","moderate","rigorous"]),default="light") caloricneed = db.IntegerProperty(required=False) # for djangoforms, it is force-set anyway by the ProfileHandler calculateneed = db.BooleanProperty(required=True,default=True)
Python
import logging import locale import os import re import cgi import datetime import urllib import wsgiref.handlers from django.utils import simplejson from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.db import djangoforms from food import datamodel class MainPage(webapp.RequestHandler): def get(self): user = users.get_current_user() user_accesslevel = "normal" user_loggedin = "" path = os.path.join(os.path.dirname(__file__), 'templates/loggedout.html') if user: url = users.create_logout_url(self.request.uri) url_linktext = '' user_loggedin = "<a id='usernick' href='#'>"+user.nickname() + "</a>" path = os.path.join(os.path.dirname(__file__), 'templates/loggedin.html') else: url = users.create_login_url(self.request.uri) url_linktext = 'Login' template_values = { 'url': url, 'url_linktext': url_linktext, 'user_loggedin': user_loggedin, 'user_accesslevel': user_accesslevel, } self.response.out.write(template.render(path, template_values)) class RPCHandler(webapp.RequestHandler): """ Allows the functions defined in the RPCMethods class to be RPCed.""" def __init__(self): webapp.RequestHandler.__init__(self) self.methods = RPCMethods() def get(self): func = None action = self.request.get('action') if action: if action[0] == '_': self.error(403) # access denied return else: func = getattr(self.methods, action, None) logging.debug('func: %s' % func) if not func: self.error(404) # file not found return result = func(self.request) self.response.out.write(simplejson.dumps(result)) else: self.error(403) class RPCMethods: """ Defines the methods that can be RPCed. NOTE: Do not allow remote callers access to private/protected "_*" methods. """ def GetProfile(self, request): user = users.get_current_user() if user: profile = db.GqlQuery("SELECT * " "FROM Profile " "WHERE user = :1 ", user).get() if profile: logging.debug("Profile found for %s" % user.nickname() ) return {'name': profile.name, 'height' : profile.height, 'birthyear' : profile.birthyear, 'activitylevel' : profile.activitylevel, 'lossprofile' : profile.lossprofile, 'gender' : profile.gender, 'calculateneed' : profile.calculateneed, 'caloricneed' : profile.caloricneed } else: logging.debug("NO Profile found for %s" % user.nickname() ) return {'error': 'no profile found'} else: return {'error': 'no user'} def StoreProfile(self, request): user = users.get_current_user() if user: logging.debug('storing user: %s' % user.nickname()) profile = db.GqlQuery("SELECT * " "FROM Profile " "WHERE user = :1 ", user).get() if not profile: # update the current profile with the passed data. profile = datamodel.Profile(user=user) errors = {} name = cgi.escape(request.get("name")) birthyear = cgi.escape(request.get("birthyear")) height = cgi.escape(request.get("height")) calculateneed = cgi.escape(request.get("calculateneed")) caloricneed = cgi.escape(request.get("caloricneed")) gender = cgi.escape(request.get("gender")) lossprofile = cgi.escape(request.get("lossprofile")) activitylevel = cgi.escape(request.get("activitylevel")) if not re.match("[a-zA-Z0-9 ]+$",name): errors["name"] = "name contains bogus letters" if not re.match("[0-9]{3}$",request.get("height")): errors["height"] = "height must be all digits and between 100-999" if not re.match("[0-9]{4}$",request.get("birthyear")): errors["birthyear"] = "birthyear must be all digits and between 1000-9999" if calculateneed != "true" and not re.match("[0-9]{3,4}$",caloricneed): errors["caloricneed"] = "caloricneed must be all digits and between 100-9999" if len(errors) != 0: return {'error': 'validation error','errors' : errors } else: # we can store the profile, and return OK profile.name = name profile.birthyear = int(birthyear) profile.height = int(height) profile.calculateneed = bool(calculateneed) profile.lossprofile = lossprofile profile.activitylevel = activitylevel profile.gender = gender if calculateneed == "true": profile.caloricneed = calculateCaloricNeed(profile) else: profile.caloricneed = caloricneed profile.put() return {'result': 'OK'} else: return {'error': 'no user'} def calculateCaloricNeed(profile): age = datetime.date.today() - datetime.date(profile.birthyear,6,1) age = age.days / 365 weight = getMetric( profile.user, "weight" ) bmr = 0 if profile.gender=="male": bmr = 66.5 + (13.75 * weight) + (5.003 * profile.height) - (6.775 * age); """ Men """ else: bmr = 655.1 + (9.563 * weight) + (1.850 * profile.height) - (4.676 * age); """ Women """ act_multiplier = 1.2 if profile.activitylevel=="light": act_multiplier = 1.3 elif profile.activitylevel=="moderate": act_multiplier = 1.4 elif profile.activitylevel=="rigorous": act_multiplier = 1.5 result = act_multiplier*bmr; if profile.lossprofile=="0.5kg pr week": result = result - 500 elif profile.lossprofile=="1kg pr week": result = result - 1000 elif profile.lossprofile=="1kg pr month": result = result - 250 return int(result) """ Fetches a metric from the Metric database, so far just a stub until metric storing is implemented """ def getMetric(user, metric): return 90 application = webapp.WSGIApplication([ ('/', MainPage), ('/jsonrpc', RPCHandler), ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
Python
import Image #Image-processing libiary. Python Imaging Library (PIL) import sys #Standard System library import math #Standard Math library def main(): picture = "ufoBlue" #name of the picture without file extension img = Image.open(picture + ".png") #open requested image with file extension. Change ".png" for other file type norm = Image.new("RGBA", img.size) #Creates a new image that will be loaded with RGBA from normals pix = img.load() #Loads the requested image into an list for faster access to pixels Zmatrix = [[0 for y in xrange(img.size[1])] for x in xrange(img.size[0])] #Creates an matrix by the same dimensions as the requseted image. Will be loaded with the Z-coordinates XYmatrix = fillXYwithCoords(img) #fillXYwithCoords does the same as the row above, but instead of integer it fills it with tuples (0,0) findEdges(Zmatrix, pix, img) #determine which pixels are transparent and not. Transparent pixels will get Z-value = 0 and non-transparent will get Z-value = maxInteger. generateZ(Zmatrix, img) #Generate the Z-values by looking att the lowest neighbour and set value to lowest neighbour+1. getXandY(Zmatrix, XYmatrix, img) #Generate the X- and Y-values by calculate the direction to each lowest neighbour and sum it up and normalize it. d = 255/getBiggest(Zmatrix, img) for x in xrange(img.size[0]): #Uncomment these two rows to print the matrix containing the Z-values. print(Zmatrix[x]) #for x in xrange(img.size[0]): #Uncomment these two rows to print the matrix containing the XY-values. #print(XYmatrix[x]) for y in xrange(img.size[1]): #Loop through the picture. for x in xrange(img.size[0]): (q,w) = XYmatrix[x][y] #get the X- and Y-coords for specific pixel r = (255 - (q*0.5+0.5)*255) g = (w*0.5+0.5)*255 b = 255 - (Zmatrix[x][y]) norm.putpixel((x,y), (int(r), int(g), int(b), 255)) #put each pixel in the new image we created in the beginning norm.save("normals/" + picture + "Normal.png") #save the normalmap as .png in folder normals def getBiggest(Zmatrix, img): biggest = 0 for y in xrange(img.size[1]): for x in xrange(img.size[0]): if Zmatrix[x][y] > biggest: biggest = Zmatrix[x][y] return biggest def fillXYwithCoords(img): #returns an matrix by the same dimensions as the requseted image and fills it with tuples (0,0) matrix = [[0 for y in xrange(img.size[1])] for x in xrange(img.size[0])] for y in range(0,img.size[1]): for x in range(0,img.size[0]): matrix[x][y] = (0,0) return matrix def findEdges(Zmatrix, pix ,img): #determine which pixels are transparent and not. Transparent pixels will get Z-value = 0 and non-transparent will get Z-value = maxInteger. for y in xrange(img.size[1]): #Looping through image for x in xrange(img.size[0]): pixel = pix[x, y][3] #Request the alpha value for specific pixel if pixel == 0: Zmatrix[x][y] = 0 #If transparent set Z-value to 0 else: Zmatrix[x][y] = sys.maxint #If transparent set Z-value to max integer if (x == 0 or x == img.size[0]-1 or y == 0 or y == img.size[1]-1) and not pixel == 0: Zmatrix[x][y] = 1 #To avoid out of range later on, set all the non-transparent pixels by the edge of the image with 1. def generateZ(Zmatrix, img): #Generate the Z-values by looking att the lowest neighbour and set value to lowest neighbour+1. for y in range(1, img.size[1]-1): #Looping through image for x in range(1, img.size[0]-1): u = img.size[0]-1 - x #Starts from the right-down-corner v = img.size[1]-1 - y lowest = getSmallestNeighbour(Zmatrix, u, v) #Gets the smallest neightbour if lowest < Zmatrix[u][v]: #Check if the smallest neightbour is smaller than current Z-value Zmatrix[u][v] = (lowest + 1)*1.5 #if it is then set current z-value to smallest neighbour+1 else: continue #Else just continue for y in range(1, img.size[1]-1): for x in range(1, img.size[0]-1): #Do the same all over again, but start from top-left-corner lowest = getSmallestNeighbour(Zmatrix, x, y) if lowest < Zmatrix[x][y]: Zmatrix[x][y] = (lowest + 1)*1.5 else: continue def getSmallestNeighbour(Zmatrix, x, y): #Return the smallest neightbour lowest = sys.maxint #Set lowest to max integer. for u in range(-1,2): for v in range(-1,2): #Loop through the neighbours if (Zmatrix[x+v][y+u] < lowest): #If the found value is lower than the previous, replace it. lowest = Zmatrix[x+v][y+u] #Return ether max integer or a lower neightbour return lowest def getXandY(Zmatrix, XYmatrix, img): #Generate the X- and Y-values by calculate the direction to each lowest neighbour and sum it up and normalize it. for y in range(1,img.size[1]-1): #Loop through image, but skipping the edges to avoid out of range later on. for x in range(1,img.size[0]-1): a = getCoord(Zmatrix, x, y) #Get the normalized X- and Y-coordinate XYmatrix[x][y] = a #Set XY-value in the matrix def getCoord(Zmatrix, x, y): #Returns the normalized X- and Y-coordinate coord = (0,0) for u in range(-1,2): #Loop through the neighbours for v in range(-1,2): if (Zmatrix[x+v][y+u] < Zmatrix[x][y]): #If neightbour is smaller, calculate its direction, normalize it and add it to the allready found coords. direction = normalize(-v,-u) coord = (coord[0] + direction[0], coord[1] + direction[1]) return normalize(coord[0],coord[1]) #Normalize the end result and return it. def normalize(x,y): #Returns an normalized vector. length = math.sqrt(x*x + y*y) #Calculates the lenght by add the x- and y-values that is powered in two. Then squareroot the result. return (float(x) / max(length, 0.1), float(y) / max(length, 0.1)) #Normalize by dividing the vector by the lenght. max() is to avoid devision by zero. main() #Starts the main program
Python
import Image #Image-processing libiary. Python Imaging Library (PIL) import sys #Standard System library import math #Standard Math library def main(): picture = "enemyBlue1" #name of the picture without file extension img = Image.open(picture + ".png") #open requested image with file extension. Change ".png" for other file type norm = Image.new("RGBA", img.size) #Creates a new image that will be loaded with RGBA from normals pix = img.load() #Loads the requested image into an list for faster access to pixels Zmatrix = [[0.0 for y in xrange(img.size[1])] for x in xrange(img.size[0])] #Creates an matrix by the same dimensions as the requseted image. Will be loaded with the Z-coordinates findEdges(Zmatrix, pix, img) #determine which pixels are transparent and not. Transparent pixels will get Z-value = 0 and non-transparent will get Z-value = maxInteger. generateZ(Zmatrix, img) #Generate the Z-values by looking att the lowest neighbour and set value to lowest neighbour+1. d = getBiggest(Zmatrix, img) #for y in xrange(img.size[1]): #for x in xrange(img.size[0]): #Zmatrix[x][y] = Zmatrix[x][y] / d #for x in xrange(img.size[0]): #Uncomment these 1wo rows to print the matrix containing the Z-values. #print(Zmatrix[x]) for y in range(1, img.size[1]-1): #Loop through the picture. for x in range(1,img.size[0]-1): (r,g,b) = generateNormal(Zmatrix, x, y) r = (r*0.5+0.5)*255 g = 255 - (g*0.5+0.5)*255 b = (b*0.5+0.5)*255 r = r + 0.5 g = g + 0.5 b = b + 0.5 norm.putpixel((x,y), (int(r), int(g), int(b), 255)) #put each pixel in the new image we created in the beginning norm.save("normals/" + picture + "Normal.png") #save the normalmap as .png in folder normals def generateNormal(Zmatrix, x, y): #[A][B][C] #[D][E][F] #[G][H][I] B = (x,y-1,Zmatrix[x][y-1]) D = (x-1,y,Zmatrix[x-1][y]) F = (x+1,y,Zmatrix[x+1][y]) H = (x,y+1,Zmatrix[x][y+1]) HB = normalize(subVector(H,B)) DF = normalize(subVector(D,F)) N1 = normalize(cross(HB,DF)) return normalize(N1) def addVector(p1,p2): return (float(p1[0])+float(p2[0]), float(p1[1])+float(p2[1]), float(p1[2])+float(p2[2])) def subVector(p1, p2): return (float(p1[0])-float(p2[0]), float(p1[1])-float(p2[1]), float(p1[2])-float(p2[2])) def getBiggest(Zmatrix, img): biggest = 0.0 for y in xrange(img.size[1]): for x in xrange(img.size[0]): if Zmatrix[x][y] > biggest: biggest = Zmatrix[x][y] return biggest def normalize(vector): #Returns an normalized vector. x,y,z = vector[0],vector[1],vector[2] length = math.sqrt(x*x + y*y + z*z) #Calculates the lenght by add the x- and y-values that is powered in two. Then squareroot the result. return (float(x) / max(length, 0.0001), float(y) / max(length, 0.0001), float(z) / max(length, 0.0001)) #Normalize by dividing the vector by the lenght. max() is to avoid devision by zero. def cross(a, b): c = [a[1] *b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return c def findEdges(Zmatrix, pix ,img): #determine which pixels are transparent and not. Transparent pixels will get Z-value = 0 and non-transparent will get Z-value = maxInteger. for y in xrange(img.size[1]): #Looping through image for x in xrange(img.size[0]): pixel = pix[x, y][3] #Request the alpha value for specific pixel if pixel == 0: Zmatrix[x][y] = 0.0 #If transparent set Z-value to 0 else: Zmatrix[x][y] = 99999.0 #If transparent set Z-value to max integer if (x == 0 or x == img.size[0]-1 or y == 0 or y == img.size[1]-1) and not pixel == 0: Zmatrix[x][y] = 1.0 #To avoid out of range later on, set all the non-transparent pixels by the edge of the image with 1. def generateZ(Zmatrix, img): #Generate the Z-values by looking att the lowest neighbour and set value to lowest neighbour+1. for y in range(1, img.size[1]-1): #Looping through image for x in range(1, img.size[0]-1): u = img.size[0]-1 - x #Starts from the right-down-corner v = img.size[1]-1 - y lowest = getSmallestNeighbour(Zmatrix, u, v) #Gets the smallest neightbour if lowest < Zmatrix[u][v]: #Check if the smallest neightbour is smaller than current Z-value Zmatrix[u][v] = lowest + 1.0 #if it is then set current z-value to smallest neighbour+1 else: continue #Else just continue for y in range(1, img.size[1]-1): for x in range(1, img.size[0]-1): #Do the same all over again, but start from top-left-corner lowest = getSmallestNeighbour(Zmatrix, x, y) if lowest < Zmatrix[x][y]: Zmatrix[x][y] = lowest + 1.0 else: continue def getSmallestNeighbour(Zmatrix, x, y): #Return the smallest neightbour lowest = 99999.0 #Set lowest to max integer. for u in range(-1,2): for v in range(-1,2): #Loop through the neighbours if (Zmatrix[x+v][y+u] < lowest): #If the found value is lower than the previous, replace it. lowest = Zmatrix[x+v][y+u] #Return ether max integer or a lower neightbour return lowest main() #Starts the main program
Python
import Image import sys import math def main(): picture = "enemyBlue4" #name of the picture without file extension img = Image.open(picture + ".png") #open requested image with file extension. Change ".png" for other file type norm = Image.new("RGBA", img.size) #Creates a new image that will be loaded with RGBA from normals pix = img.load() #Loads the requested image into an list for faster access to pixels Zmatrix = [[0 for y in xrange(img.size[1])] for x in xrange(img.size[0])] #Creates an matrix by the same dimensions as the requseted image. Will be loaded with the Z-coordinates XYmatrix = fillXYwithCoords(img) #fillXYwithCoords does the same as the row above, but instead of integer it fills it with tuples (0,0) findEdges(Zmatrix, pix, img) #determine which pixels are transparent and not. Transparent pixels will get Z-value = 0 and non-transparent will get Z-value = maxInteger. generateZ(Zmatrix, img) #Generate the Z-values by looking att the lowest neighbour and set value to lowest neighbour+1. getXandY(Zmatrix, XYmatrix, img) for y in range(1,img.size[1]-1): for x in range(1,img.size[0]-1): a = smoothXY(XYmatrix, pix, x, y) d = 255/getBiggest(Zmatrix, img) #for x in xrange(img.size[0]): #print(Zmatrix[x]) for y in xrange(img.size[1]): for x in xrange(img.size[0]): (q,w) = XYmatrix[x][y] a = ((q*0.5+0.5)*255) b = (255 - ((w*0.5+0.5)*255)) c = 255 - (Zmatrix[x][y]) #c = 255 - Zmatrix[x][y] norm.putpixel((x,y), (int(a), int(b), int(c), 255)) norm.save("normals/" + picture + "Normal.png") def smoothXY(XYmatrix, pix, x, y): coord = (0,0) for u in range(-1,2): for v in range(-1,2): if(not pix[x, y][3] == 0): direction = XYmatrix[x+v][y+u] direction = normalize(direction[0], direction[1]) coord = (coord[0] + direction[0], coord[1] + direction[1]) XYmatrix[x][y] = normalize(coord[0],coord[1]) def fillXYwithCoords(img): matrix = [[0 for y in xrange(img.size[1])] for x in xrange(img.size[0])] for y in range(0,img.size[1]): for x in range(0,img.size[0]): matrix[x][y] = (0,0) return matrix def getXandY(Zmatrix, XYmatrix, img): for y in range(3,img.size[1]-3): for x in range(3,img.size[0]-3): a = getCoord(Zmatrix, x, y) XYmatrix[x][y] = a def getCoord(Zmatrix, x, y): coord = (0,0) for u in range(-3,4): for v in range(-3,4): if (Zmatrix[x+v][y+u] < Zmatrix[x][y]): direction = normalize(v,u) coord = (coord[0] + direction[0], coord[1] + direction[1]) return normalize(coord[0],coord[1]) def normalize(x,y): length = math.sqrt(x*x + y*y) #return (x / length, y / length) return (float(x) / max(length, 0.1), float(y) / max(length, 0.1)) def getBiggest(Zmatrix, img): biggest = 0 for y in xrange(img.size[1]): for x in xrange(img.size[0]): if Zmatrix[x][y] > biggest: biggest = Zmatrix[x][y] return biggest def findEdges(matrix, pix ,img): for y in xrange(img.size[1]): for x in xrange(img.size[0]): pixel = pix[x, y][3] if pixel == 0: matrix[x][y] = 0 else: matrix[x][y] = sys.maxint if (x == 0 or x == img.size[0]-1 or y == 0 or y == img.size[1]-1) and not pixel == 0: matrix[x][y] = 1 def generateZ(Zmatrix, img): for y in range(1, img.size[1]-1): for x in range(1, img.size[0]-1): u = img.size[0]-1 - x v = img.size[1]-1 - y lowest = getSmallestNeighbour(Zmatrix, u, v) if lowest < Zmatrix[u][v]: Zmatrix[u][v] = lowest + 1 else: continue for y in range(1, img.size[1]-1): for x in range(1, img.size[0]-1): lowest = getSmallestNeighbour(Zmatrix, x, y) if lowest < Zmatrix[x][y]: Zmatrix[x][y] = lowest + 1 else: continue def getSmallestNeighbour(Zmatrix, x, y): lowest = sys.maxint for u in range(-1,2): for v in range(-1,2): if (Zmatrix[x+v][y+u] < lowest): lowest = Zmatrix[x+v][y+u] return lowest main()
Python
import Image img = Image.new( 'RGB', (255,255), "black") # create a new black image pixels = img.load() # create the pixel map for i in range(img.size[0]): # for every pixel: for j in range(img.size[1]): pixels[i,j] = (i, j, 100) # set the colour accordingly img.show()
Python
import Image import sys im = Image.open("ufoBlue.png") pix = im.load() visited = [] #print im.size #print pix[0,0] res = [[0 for x in xrange(im.size[0])] for x in xrange(im.size[1])] for i in range(im.size[0]): for j in range(im.size[1]): if pix[i, j][3] == 0: res[i][j] = 0 else: res[i][j] = 1 sys.stdout.write(str(res[i][j])) print '' def adjacent_passages(mat, pos): possible = [] if pos[0] > 0 and pos[0] <= len(mat) and pos[1] >= 0: if searchvisited(mat, pos[0]-1, pos[1]) == False: possible += [(pos[0]-1, pos[1])] if pos[0] >= 0 and pos[0] < len(mat)-1 and pos[1] >= 0: if searchvisited(mat, pos[0]+1, pos[1]) == False: possible += [(pos[0]+1, pos[1])] if pos[1] > 0 and pos[1] <= len(mat[0]) and pos[0] >= 0: if searchvisited(mat, pos[0], pos[1]-1) == False: possible += [(pos[0], pos[1]-1)] if pos[1] >= 0 and pos[1] < len(mat[0])-1 and pos[0] >= 0: if searchvisited(mat, pos[0], pos[1]+1) == False: possible += [(pos[0], pos[1]+1)] return possible def bfs(mat, nod): #print(nod) visited.append(nod[0]) if mat[nod[0][0]][nod[0][1]] == 0: return nod adjacent = adjacent_passages(mat, nod[0]) if adjacent == []: return False #print(adjacent) for i in range(0, len(adjacent), 1): nod.insert(0, adjacent[i]) solution = bfs(mat, nod) if(solution != False): return solution nod.pop(0) return bfs(mat, nod) def searchvisited(mat, x, y): pos = (x,y) for i in range(0, len(visited), 1): if pos == visited[i]: return True return False for i in range(im.size[0]): for j in range(im.size[1]): if res[i][j] != 0: res[i][j] = len(bfs(res, (res[i][j]))) sys.stdout.write(str(res[i][j])) print '' #start = [(30, 30)] #pathToAlpha = bfs(res, start) #print pathToAlpha
Python
import Image import sys import math def main(): picture = "enemyBlue1" #name of the picture without file extension img = Image.open(picture + ".png") #open requested image with file extension. Change ".png" for other file type norm = Image.new("RGBA", img.size) #Creates a new image that will be loaded with RGBA from normals pix = img.load() #Loads the requested image into an list for faster access to pixels print ("image loaded") Zmatrix = [[0 for y in xrange(img.size[1])] for x in xrange(img.size[0])] #Creates an matrix by the same dimensions as the requseted image. Will be loaded with the Z-coordinates findEdges(img, pix, Zmatrix) print ("edges found") generateZ(Zmatrix, img) print ("Z generated") XYmatrix = fillXYwithCoords(img) getXandY(Zmatrix, XYmatrix, img) d = 255/getBiggest(Zmatrix, img) #for x in xrange(img.size[0]): #print(XYmatrix[x]) for y in xrange(img.size[1]): for x in xrange(img.size[0]): (q,w) = XYmatrix[x][y] a = (255 - (q*0.5+0.5)*255) b = (w*0.5+0.5)*255 c = 255 - (Zmatrix[x][y]) norm.putpixel((x,y), (int(a), int(b), int(c), 255)) norm.save("normals/" + picture + "Normal.png") def getBiggest(Zmatrix, img): biggest = 0 for y in xrange(img.size[1]): for x in xrange(img.size[0]): if Zmatrix[x][y] > biggest: biggest = Zmatrix[x][y] return biggest def getXandY(Zmatrix, XYmatrix, img): for y in range(0,img.size[1]): for x in range(0,img.size[0]): if Zmatrix[x][y] == 0: XYmatrix[x][y] = (0,0) else: distanceCalc(XYmatrix, Zmatrix, img, x, y) def distanceCalc(XYmatrix, Zmatrix, img, x, y): coords = getCoordsBiggest(Zmatrix, img, x, y) coords = (coords[0]-x, coords[1]-y) XYmatrix[x][y] = normalize(coords[0], coords[1]) def getCoordsBiggest(Zmatrix, img, x, y): biggest = 0 for y in xrange(img.size[1]): for x in xrange(img.size[0]): if Zmatrix[x][y] > biggest: biggest = Zmatrix[x][y] coords = (x,y) return coords def normalize(x,y): length = math.sqrt(x*x + y*y) return (float(x) / max(length, 0.1), float(y) / max(length, 0.1)) def fillXYwithCoords(img): XYmatrix = [[0 for y in xrange(img.size[1])] for x in xrange(img.size[0])] for y in range(0,img.size[1]): for x in range(0,img.size[0]): XYmatrix[x][y] = (x,y) return XYmatrix def findEdges(img, pix, Zmatrix): for y in xrange(img.size[1]): for x in xrange(img.size[0]): pixel = pix[x, y][3] if pixel == 0: Zmatrix[x][y] = 0 else: Zmatrix[x][y] = sys.maxint if (x == 0 or x == img.size[0]-1 or y == 0 or y == img.size[1]-1) and not pixel == 0: Zmatrix[x][y] = 1 def generateZ(Zmatrix, img): for y in range(1, img.size[1]-1): for x in range(1, img.size[0]-1): u = img.size[0]-1 - x v = img.size[1]-1 - y lowest = getSmallestNeighbour(Zmatrix, u, v) if lowest < Zmatrix[u][v]: Zmatrix[u][v] = lowest + 1 else: continue for y in range(1, img.size[1]-1): for x in range(1, img.size[0]-1): lowest = getSmallestNeighbour(Zmatrix, x, y) if lowest < Zmatrix[x][y]: Zmatrix[x][y] = lowest + 1 else: continue def getSmallestNeighbour(Zmatrix, x, y): lowest = sys.maxint for u in range(-1,2): for v in range(-1,2): if (Zmatrix[x+v][y+u] < lowest): lowest = Zmatrix[x+v][y+u] return lowest main()
Python
import urllib import urllib2 import re import os from urlparse import urlparse, parse_qs import StorageServer from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup import xbmcplugin import xbmcgui import xbmcaddon base_url = 'http://www.foodnetwork.com' addon = xbmcaddon.Addon() addon_version = addon.getAddonInfo('version') addon_id = addon.getAddonInfo('id') cache = StorageServer.StorageServer("foodnetwork", 6) home = xbmc.translatePath(addon.getAddonInfo('path')) icon = addon.getAddonInfo('icon') language = addon.getLocalizedString debug = addon.getSetting('debug') def addon_log(string): try: log_message = string.encode('utf-8', 'ignore') except: log_message = 'addonException: addon_log' xbmc.log("[%s-%s]: %s" %(addon_id, addon_version, log_message),level=xbmc.LOGDEBUG) def make_request(url): addon_log('Request URL: ' + url) try: headers = {'User-agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0', 'Referer' : base_url} req = urllib2.Request(url,None,headers) response = urllib2.urlopen(req) data = response.read() addon_log('ResponseInfo: %s' %response.info()) response.close() return data except urllib2.URLError, e: addon_log('We failed to open "%s".' %url) if hasattr(e, 'reason'): addon_log('We failed to reach a server.') addon_log('Reason: %s' %e.reason) if hasattr(e, 'code'): addon_log('We failed with error code - %s.' %e.code) def cache_shows(): cat = { 'videos': {'url': base_url+'/food-network-top-food-videos/videos/index.html'}, 'episodes': {'url': base_url+'/food-network-full-episodes/videos/index.html'} } for i in cat.keys(): soup = BeautifulSoup(make_request(cat[i]['url']), convertEntities=BeautifulSoup.HTML_ENTITIES) play_lists = [] playlists = soup.find('ul', attrs={'class': 'playlists'})('li') for p in playlists: play_lists.append((p.a.string, p['data-channel'], p.a['href'])) cat[i]['playlists'] = play_lists if not cat.has_key('most_popular'): most_popular = soup.find('h4', text='Videos').findNext('ul', attrs={'class': 'media'})('a') video_list = [] for m in most_popular: video_list.append((m.string, m['href'])) cat['most_popular'] = video_list return cat def get_categories(): add_dir(language(30000), 'episodes', 1, icon) add_dir(language(30001), 'videos', 1, icon) add_dir(language(30002), 'most_popular', 1, icon) add_dir(language(30003), 'all_shows', 5, icon) def get_cat(url): if url == 'most_popular': items = cache.cacheFunction(cache_shows)[url] for i in items: add_dir(i[0], i[1], 3, icon, {}, False) else: items = cache.cacheFunction(cache_shows)[url]['playlists'] for i in items: title = i[0] if title.endswith('Full Episodes'): title = title.replace('Full Episodes','').replace(' - ','') add_dir(title, i[2], 2, icon) def get_all_shows(): show_file = os.path.join(home, 'resources', 'show_list') show_list = eval(open(show_file, 'r').read()) for i in show_list: if i.has_key('video_href'): if i.has_key('thumb'): thumb = i['thumb'] else: thumb = icon add_dir(i['name'], i['video_href'], 6, thumb) def get_video_xml(url, show=False): video_id = None try: if int(eval(url)): video_id = eval(url) except: pass if not video_id: if url.startswith('/'): url = base_url+url data = make_request(url) if show: playlists = None soup = BeautifulSoup(data, convertEntities=BeautifulStoneSoup.HTML_ENTITIES) try: playlists = soup.find('ul', attrs={'class': "playlists"})('li') except: pass if playlists: for i in playlists: add_dir(i.a.string, i.a['href'], 2, icon) xbmcplugin.endOfDirectory(int(sys.argv[1])) return try: video_id = re.findall('var snap = new SNI.Food.Player.VideoAsset\(.+?, (.+?)\);', data)[0] except: try: video_id = re.findall('var snap = new SNI.Food.Player.FullSize\(.+?, (.+?)\);', data)[0] except: try: video_id = re.findall('var snap = new SNI.Food.Player.FullSizeNoPlaylist\(.+?, (.+?)\);', data)[0] except: addon_log('Unable to find video_id') if video_id: xml_url = 'http://www.foodnetwork.com/food/channel/xml/0,,%s,00.xml' %video_id soup = BeautifulStoneSoup(make_request(xml_url), convertEntities=BeautifulStoneSoup.XML_ENTITIES) if show: for i in soup('video'): add_dir(i.clipname.string, i.videourl.string, 4, i.thumbnailurl.string, {'Plot': i.abstract.string, 'Duration': get_length_in_minutes(i.length.string)}, False) xbmcplugin.endOfDirectory(int(sys.argv[1])) else: resolve_url(soup.video.videourl.string) def get_playlist(url, name): if not name == language(30005): playlist_url = url.rsplit(',', 1)[0].rsplit('/', 1)[1] else: playlist_url = url json_url = '%s/food/feeds/channel-video/%s_RA,00.json' %(base_url, playlist_url) items = eval(make_request(json_url).split('var snapTravelingLib = ')[1])[0] for i in items['videos']: add_dir(i['label'], i['videoURL'], 4, i['thumbnailURL'], {'Plot': i['description'], 'Duration': get_length_in_minutes(i['length'])}, False) if items['last'] < items['total']: page_items = playlist_url.rsplit('_', 2) page_url = '%s_%s_%s' %(page_items[0], (int(page_items[1])+1), page_items[2]) add_dir(language(30005), page_url, 2, icon) def resolve_url(url): playpath = url.replace('http://wms.scrippsnetworks.com','').replace('.wmv','') final_url = ( 'rtmp://flash.scrippsnetworks.com:1935/ondemand?ovpfv=1.1 ' 'swfUrl=http://common.scrippsnetworks.com/common/snap/snap-3.2.17.swf ' 'playpath=' + playpath ) item = xbmcgui.ListItem(path=final_url) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item) def cache_all_shows(): url = 'http://www.foodnetwork.com/shows/index.html' soup = BeautifulSoup(make_request(url), convertEntities=BeautifulSoup.HTML_ENTITIES) items = soup.find('div', attrs={'class': "list-wrap"})('li') show_list = [] for i in items: show = {} show['name'] = i.a.string show['page_href'] = i.a['href'] show_list.append(show) dialog = xbmcgui.Dialog() ok = dialog.yesno( language(30011), language(30009), language(30010) ) if ok: xbmc.executebuiltin("ActivateWindow(busydialog)") for i in show_list: data = make_request(base_url+i['page_href']) if data: s_soup = BeautifulSoup(data, convertEntities=BeautifulSoup.HTML_ENTITIES) item = s_soup.find('span', attrs={'class': "lgbtn-text"}, text='videos') if not item: item = s_soup.find('span', attrs={'class': "lgbtn-text"}, text='VIDEOS') if item: i['video_href'] = item.findPrevious('a')['href'] else: try: item = re.findall('var snap = new SNI.Food.Player.VideoAsset\(.+?, (.+?)\);', data)[0] except: try: item = re.findall('var snap = new SNI.Food.Player.FullSize\(.+?, (.+?)\);', data)[0] except: try: item = re.findall('var snap = new SNI.Food.Player.FullSizeNoPlaylist\(.+?, (.+?)\);', data)[0] except: addon_log('Unable to find video_id') item = None if item: i['video_href'] = item try: ok = i['video_href'] addon_log('Videos: True: %s' %i['name']) except: addon_log('Videos: False: %s' %i['name']) addon_log('Removing %s From Show List' %i['name']) for index in range(len(show_list)): if show_list[index]['name'] == i['name']: del show_list[index] break continue thumb = None try: thumb = re.findall('background: url\((.+?)\)', data)[0] except: try: thumb = s_soup.find('div', attrs={'id': "main-bd"}).img['src'] except: pass if thumb: i['thumb'] = thumb else: addon_log('No Data') xbmc.sleep(500) show_file = os.path.join(home, 'resources', 'show_list') w = open(show_file, 'w') w.write(repr(show_list)) w.close() addon_log('%s Shows with videos in Show List' %len(show_list)) xbmc.executebuiltin("Dialog.Close(busydialog)") def get_length_in_minutes(length): if not isinstance(length, str): if ':' in str(length): length = str(length) elif isinstance(length, int): return length if ':' in length: l_split = length.split(':') minutes = int(l_split[-2]) if int(l_split[-1]) >= 30: minutes += 1 if len(l_split) == 3: minutes += (int(l_split[0]) * 60) if minutes < 1: minutes = 1 return minutes def get_params(): p = parse_qs(sys.argv[2][1:]) for i in p.keys(): p[i] = p[i][0] return p def add_dir(name, url, mode, iconimage, infolabels={}, isfolder=True): params = {'name': name, 'url': url, 'mode': mode} infolabels['Title'] = name url = '%s?%s' %(sys.argv[0], urllib.urlencode(params)) listitem = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) if not isfolder: listitem.setProperty('IsPlayable', 'true') listitem.setInfo(type="Video", infoLabels=infolabels) xbmcplugin.addDirectoryItem(int(sys.argv[1]), url, listitem, isfolder) params = get_params() try: mode = int(params['mode']) except: mode = None addon_log(repr(params)) if mode == None: get_categories() xbmcplugin.endOfDirectory(int(sys.argv[1])) elif mode == 1: get_cat(params['url']) xbmcplugin.endOfDirectory(int(sys.argv[1])) elif mode == 2: get_playlist(params['url'], params['name']) xbmcplugin.endOfDirectory(int(sys.argv[1])) elif mode == 3: get_video_xml(params['url']) elif mode == 4: resolve_url(params['url']) elif mode == 5: get_all_shows() xbmcplugin.endOfDirectory(int(sys.argv[1])) elif mode == 6: get_video_xml(params['url'], True) elif mode == 7: cache_all_shows()
Python
from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class MainPage(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hello, webapp World!') application = webapp.WSGIApplication([('/', MainPage)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
#Football Schedule GUI program import re import gdata.calendar.service import atom import sys from PyQt4 import QtGui, QtCore import icalendar from datetime import datetime from icalendar import UTC # Level abbreviations and game fees levels = {"Freshman":"Fr", "JV":"JV", "Varsity":"V", "8th Grade":"8", "Invalid":"Invalid"} fees = {"Fr" : 42, "JV" : 42, "V" : 56, "8": 42, "Invalid": 0} # Game object stores info about a single game class Game: #set default values def __init__(self): self.calid = "N/A" self.date = "2000-01-01" self.time = "16:00" self.level = "Invalid" self.visitor = "???" self.home = "???" self.worked = False self.pay = "" self.tithing = False self.where = "" self.idgroup = "UNKNOWN" self.assignor = "???" self.gameid = "" self.officials = {"REF" : "", "UMP" : "", "HL" : "", "LJ" : "", "BJ" : ""} self.mismatch = "" # read a google event object into this object def fromEvent(self, event): # this RE matches yyyy-mm-ddThh:mm format in the start time; date is group 1, time is group 2 m = re.match("(\d{4,4}-\d{2,2}-\d{2,2})T(\d{2,2}:\d{2,2})", event.when[0].start_time) self.event = event idstart = event.id.text.rindex("/") + 1 self.calid = event.id.text[idstart:] self.date = m.group(1) self.time = m.group(2) # vvshatp is Visitor vs Home at Place. Matches game level (1), then a dash, then finds visitor (2) vs home (3) # vath is Visitor at Home. Matches game level (1), then a dash, then visitor (2) @ home (3) vvshatp = ".*?\((Fr|V|JV|8)\)\s*-\s*(.+?)\s*vs\s*(.+?)\s+@" vath = ".*?\((Fr|V|JV|8)\)\s*-\s*(.+)\s*@\s*(.+)" # first try to match on Visitor vs Home at Place m = re.match(vvshatp, event.title.text) if (m): self.level = m.group(1).strip() self.visitor = m.group(2).strip() self.home = m.group(3).strip() else: # try Visitor at Home m = re.match(vath, event.title.text) if (m): self.level = m.group(1).strip(); self.visitor = m.group(2).strip() self.home = m.group(3).strip() for lev in levels: # get the full/long name of the level if levels[lev] == self.level: self.level = lev break # derive pay from level, get where value and the event content for game details self.desc = event.content.text self.pay = fees[levels[self.level.__str__()]] self.where = event.where[0].value_string if self.where is not None: self.where = self.where.strip() #d_vvsh is a line for visitor (1) vs home (2) #d_level is a line for the game level #d_assign is a line for the Assignor name (1) #d_gameid is a line for the ID Group (1), and the actual ID# (2) #d_official is a line for matching a position, with the official (1) separating them (ie, REF - Person Name) d_vvsh = "(.+?)\s*vs\s*(.+)" d_level = "(Freshman|JV|Varsity|8th Grade)" d_assign = "\(Assignor - (.+?)\)" d_gameid = "(.+?) ID - (.*)" d_official = "(REF|UMP|HL|LJ|BJ)\s*-\s*(.*)" desclines = self.desc.splitlines(0) #pares each line of the content for descline in desclines: # for simplicity, do matches here for each line type m1 = re.match(d_vvsh, descline) m2 = re.match(d_level, descline) m3 = re.match(d_assign, descline) m4 = re.match(d_gameid, descline) m5 = re.match(d_official, descline) if (m1): # Visitor vs Home line d_vis = m1.group(1).strip() d_home = m1.group(2).strip() if (d_vis != self.visitor): self.mismatch = self.mismatch + "Visitor mismatch: " + self.visitor + " ... " + d_vis + "\n" if (d_home != self.home): self.mismatch = self.mismatch + "Home mismatch: " + self.home + " ... " + d_home + "\n" elif (m2): # Level line if self.level != m2.group(1): self.mismatch = self.mismatch + "Level mismatch: " + self.level + " ... " + m2.group(1) + "\n" elif (m3): # Assignor line self.assignor = m3.group(1).strip() elif (m4): # Game ID line (and group for which the ID applies) self.idgroup = m4.group(1).strip() self.gameid = m4.group(2).strip() elif (m5): # Official/Position line position = m5.group(1).strip() officialname = m5.group(2).strip() self.officials[position] = officialname # get a short summary string of the game def str_short(self): return '%s %s (%2s) %s vs %s' % (self.date, self.time, levels[self.level.__str__()], self.visitor, self.home) # get a longer string form of the entire game details def str(self): basicinfo = self.str_short() assignor = 'Assignor: %s' % (self.assignor) idinfo = '%s ID: %s' % (self.idgroup, self.gameid) officials = 'REF: %s\nUMP: %s\n HL: %s\n' % (self.officials['REF'], self.officials['UMP'], self.officials['HL']) # only add LJ and BJ if it's a Varsity game if levels[self.level.__str__()] == 'V': officials += ' LJ: %s\n BJ: %s\n' % (self.officials['LJ'], self.officials['BJ']) return '%s\n%s\n%s\n%s' % (basicinfo, assignor, idinfo, officials) # Get the string to use for the title of the game in the calendar def getTitle(self): title = '(%s) - %s ' % (levels[self.level.__str__()], self.visitor) # Do visitor @ home if the location is the same as the home, otherwise do visitor vs home @ location if (self.home == self.where): title += '@ %s' % (self.home) else: title += 'vs %s @ %s' % (self.home, self.where) return title # Get the string to use for the event content field in the calendar def getContent(self): maincontent = '%s vs %s\n%s\n(Assignor - %s)\n%s ID - %s\n\n' % (self.visitor, self.home, self.level, self.assignor, self.idgroup, self.gameid) offic = 'REF - %s\nUMP - %s\nHL - %s' % (self.officials['REF'], self.officials['UMP'], self.officials['HL']) # only add the LJ and BJ to the content if it's a Varsity game if levels[self.level.__str__()] == 'V': offic += '\nLJ - %s\nBJ - %s' % (self.officials['LJ'], self.officials['BJ']) return '%s%s' % (maincontent, offic) # A dialog box for loggin in class LoginDialog(QtGui.QDialog): def __init__(self): QtGui.QDialog.__init__(self) self.setWindowTitle('Login To Your Calendar') # Build the fields and buttons self.username = QtGui.QLineEdit() self.username.setMinimumWidth(150) self.password = QtGui.QLineEdit() self.password.setEchoMode(QtGui.QLineEdit.Password) self.password.setMinimumWidth(150) okButton = QtGui.QPushButton('OK') cancelButton = QtGui.QPushButton('Cancel') # Add them to the dialog box main = QtGui.QGridLayout() main.addWidget(QtGui.QLabel('Username'), 0, 0) main.addWidget(self.username, 0, 1) main.addWidget(QtGui.QLabel('Password') , 1, 0) main.addWidget(self.password, 1, 1) main.addWidget(okButton, 2, 0) main.addWidget(cancelButton, 2, 1) # Set the layout and connect the buttons to the dialogs built-in methods self.setLayout(main) self.connect(okButton, QtCore.SIGNAL("clicked()"), self.accept) self.connect(cancelButton, QtCore.SIGNAL("clicked()"), self.reject) # A dialog for comfirming an export of the games list class ExportDialog(QtGui.QDialog): def __init__(self): QtGui.QDialog.__init__(self) self.setWindowTitle('Export Schedule to iCalendar Format') # Build the fields and buttons self.filename = QtGui.QLineEdit() self.filename.setMinimumWidth(300) filebutton = QtGui.QPushButton("Browse...") self.onlyworkhours = QtGui.QCheckBox("Only export times during normal work hours") okButton = QtGui.QPushButton('OK') cancelButton = QtGui.QPushButton('Cancel') # Add them to the main = QtGui.QGridLayout() main.addWidget(QtGui.QLabel('iCal File :'), 0, 0) main.addWidget(self.filename, 0, 1) main.addWidget(filebutton, 0, 2) main.addWidget(self.onlyworkhours, 1, 0, 1, 2) buttonLayout = QtGui.QHBoxLayout() buttonLayout.addStretch() buttonLayout.addWidget(okButton) buttonLayout.addSpacing(5) buttonLayout.addWidget(cancelButton) buttonLayout.addStretch() main.addLayout(buttonLayout, 2, 0, 1, 3) # Set the layout and connect the buttons to the dialogs methods self.setLayout(main) self.connect(okButton, QtCore.SIGNAL("clicked()"), self.accept) self.connect(cancelButton, QtCore.SIGNAL("clicked()"), self.reject) self.connect(filebutton, QtCore.SIGNAL("clicked()"), self.chooseFile) # open the filepicker and set the result in the dialog def chooseFile(self): filename = QtGui.QFileDialog.getSaveFileName(self, "Choose iCalendar File", "", "iCal Files (*.ics)") if filename != "": self.filename.setText(filename) # A custom List Item for the game selection list, used to attach the actual game info to the item for retrieval class GameListItem(QtGui.QListWidgetItem): def __init__(self,game): QtGui.QListWidgetItem.__init__(self, game.str_short()) self.game = game # A custom Date field, set to use the calendar popup and specified format. Also supports the needed get and set fields # so all info fields can be uniformly retrieved class GameInfoDateEdit(QtGui.QDateEdit): def __init__(self,parent=None): QtGui.QDateEdit.__init__(self, parent) self.setCalendarPopup(True) self.setDisplayFormat("yyyy-MM-dd") self.setDate(QtCore.QDate.currentDate()) def reset(self): self.setDate(QtCore.QDate.currentDate()) def setValue(self,newValue): self.setDate(QtCore.QDate.fromString(newValue, "yyyy-MM-dd")) def getValue(self): return self.date().toString("yyyy-MM-dd") # A custom Time field, set to use the specified format, and a default time (4PM). # Also supports the needed get and set fields so all info fields can be uniformly retrieved class GameInfoTimeEdit(QtGui.QTimeEdit): def __init__(self,parent=None): QtGui.QDateEdit.__init__(self, parent) self.setDisplayFormat("hh:mm") self.setTime(QtCore.QTime(16,00)) def reset(self): self.setTime(QtCore.QTime(16,00)) def setValue(self, newValue): self.setTime(QtCore.QTime.fromString(newValue, "hh:mm")) def getValue(self): return self.time().toString("hh:mm") # A custom single-line entry for most data, setting a disabled background and size constraints. # Also contains custom get and set methods to be uniformly retrievable. class GameInfoLineEdit(QtGui.QLineEdit): def __init__(self,parent=None): QtGui.QLineEdit.__init__(self, parent) self.palette().setColor(QtGui.QPalette.Disabled, QtGui.QPalette.Background, QtGui.QColor(175,175,175)) self.setMaximumHeight(30) self.setMinimumWidth(200) def reset(self): self.setText("") def setValue(self,newValue): self.setText(newValue) def getValue(self): return self.text() # A custom combo box item, adding custom get and set methods to uniformly access values. class GameInfoComboBox(QtGui.QComboBox): def __init__(self, valList, parent=None): QtGui.QComboBox.__init__(self,parent) self.addItems(valList) def reset(self): self.setCurrentIndex(0) def setValue(self, newValue): i = self.findText(newValue) if i >= 0: self.setCurrentIndex(i) def getValue(self): return self.currentText() # The Game Info widget is the right half of the dialog containing all the fields for a single game. class GameInfoWidget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.rowNum = 0 self.resize(400,500) self.grid = QtGui.QGridLayout() # Add each input field; note that the field names match the field names in the Game object for easier conversion self.addInput('date', 'Date', GameInfoDateEdit()) self.addInput('time', 'Time', GameInfoTimeEdit()) self.addInput('level', 'Level', GameInfoComboBox(["Freshman", "JV", "Varsity", "8th Grade"])) self.addInput('visitor', 'Visitor', GameInfoLineEdit()) self.addInput('home', 'Home', GameInfoLineEdit()) self.addInput('where', 'Location', GameInfoLineEdit()) self.addInput('assignor', "Assignor", GameInfoLineEdit()) self.addInput('idgroup', 'ID Group', GameInfoLineEdit()) self.addInput('gameid', 'Game ID', GameInfoLineEdit()) self.addInput( 'REF', 'Referee', GameInfoLineEdit()) self.addInput('UMP', 'Umpire', GameInfoLineEdit()) self.addInput('HL', 'Head Linesman', GameInfoLineEdit()) self.addInput('LJ', 'Line Judge', GameInfoLineEdit()) self.addInput('BJ', 'Back Judge', GameInfoLineEdit()) workpay = QtGui.QHBoxLayout() workpay.addWidget(QtGui.QCheckBox("Worked")) workpay.addWidget(QtGui.QLabel("Payment:")) workpay.addWidget(QtGui.QLineEdit()) workpay.addWidget(QtGui.QCheckBox("Recorded")) self.grid.addLayout(workpay, self.rowNum, 0, 1, 4) # Connect the Level combo box to enable/disable the LJ/BJ fields depending on level chosen self.level.connect(self.level, QtCore.SIGNAL("currentIndexChanged(QString)"), self.updateLjBj) # Set the layout and enable/diable LJ/BJ based on current level value self.setLayout(self.grid) self.updateLjBj(self.level.getValue()) # Add one input field to the widget, with it's label; add to the specified row of the grid. def addInput(self, varName, labelText, input): self.__dict__[varName] = input self.grid.addWidget(QtGui.QLabel(labelText + ":"),self.rowNum,0) self.grid.addWidget(input,self.rowNum,1) self.rowNum += 1 # Enable the LJ/BJ fields for Varsity games, disable otherwise. def updateLjBj(self, newlevel): disable = True if newlevel == 'Varsity': disable = False self.LJ.setDisabled(disable) self.BJ.setDisabled(disable) if disable: self.LJ.setValue("N/A") self.BJ.setValue("N/A") else: if (self.LJ.getValue() == "N/A"): self.LJ.reset() if (self.BJ.getValue() == "N/A"): self.BJ.reset() # The Main application window class MainWindow(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Football Editor') # Add the list of games to the left, the game info widget on the right, with new game and save buttons leftvbox = QtGui.QVBoxLayout() self.gamelist = QtGui.QListWidget(self) self.gamelist.setMinimumWidth(400) self.gamelist.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) leftvbox.addWidget(self.gamelist) totalpayrow = QtGui.QHBoxLayout() totalpayrow.addWidget(QtGui.QLabel("Total Expected Pay :")) self.paylabel = QtGui.QLabel("$0") totalpayrow.addWidget(self.paylabel) leftvbox.addLayout(totalpayrow) newgamebutton = QtGui.QPushButton("New Game") leftvbox.addWidget(newgamebutton) exportbutton = QtGui.QPushButton("Export To iCal") leftvbox.addWidget(exportbutton) rightvbox = QtGui.QVBoxLayout() self.gameinfo = GameInfoWidget(self) rightvbox.addWidget(self.gameinfo) self.savebutton = QtGui.QPushButton("Save Game") rightvbox.addWidget(self.savebutton) hbox = QtGui.QHBoxLayout() hbox.addStretch(1) hbox.addLayout(leftvbox) hbox.addStretch(5) hbox.addLayout(rightvbox) hbox.addStretch(1) # Connect the game list to update the game info widget, and the new and save buttons to their methods self.gamelist.connect(self.gamelist, QtCore.SIGNAL('itemClicked(QListWidgetItem *)'), self.updateGame) newgamebutton.connect(newgamebutton, QtCore.SIGNAL('clicked()'), self.newGame) self.savebutton.connect(self.savebutton, QtCore.SIGNAL('clicked()'), self.saveGame) exportbutton.connect(exportbutton, QtCore.SIGNAL('clicked()'), self.exportIcal) self.setLayout(hbox) # Set the client so that the window can refresh itself def setClient(self, client): self.client = client # clear the game list and refresh it from the google calendar def refreshlist(self): self.gamelist.clear() # set up the query query = gdata.calendar.service.CalendarEventQuery('default', 'private', 'full') query.start_min = '2010-06-01' query.orderby = 'starttime' query.sortorder = 'a' query.max_results = 100 # run the query into feed games = [] feed = self.client.CalendarQuery(query) # initialize total pay totalpay = 0 # Go through each event and add the game for i, event in enumerate(feed.entry): # This expression just checks to make sure it's a football game and not some other event in the calendar # Checks to see if it has (Fr), (JV) or (V) in the title m = re.match(".*?\((Fr|JV|V|8)\)", event.title.text) if (m): # If it matches, parse the game and add it to the list g = Game() g.fromEvent(event) games.append(g) # get the abbreviation of the level, and then get the fee for that level totalpay += fees[levels[g.level]] # update the pay label text to be the total estimated pay self.paylabel.setText("$%d" % totalpay) # Go through each game and add it to the form list for game in games: self.gamelist.addItem(GameListItem(game)) # clear the game info widget self.updateGame(None) # Update the game info widget based on the current game def updateGame(self, curr): if curr is not None: # If a game is selected, go through each of the games fields for field in curr.game.__dict__: # If the fields is officials, go through each official and set the appropriate field value if field == 'officials': for official in curr.game.officials: if hasattr(self.gameinfo, official) and hasattr(getattr(self.gameinfo, official), "setValue"): getattr(self.gameinfo, official).setValue(curr.game.officials[official]) else: # If it's not an official, set the appropriate field value if needed if hasattr(self.gameinfo, field) and hasattr(getattr(self.gameinfo, field), "setValue"): getattr(self.gameinfo, field).setValue(getattr(curr.game, field)) else: # If no game selected, just clear the widget self.clearInfo() # Enable/Disable LJ/BJ field as needed self.gameinfo.updateLjBj(self.gameinfo.level.getValue()) # newgame just clears the info widget and deselects any selected game in the list def newGame(self): for item in self.gamelist.selectedItems(): item.setSelected(False) self.clearInfo() # Clear the game info widget def clearInfo(self): for field in self.gameinfo.__dict__: if hasattr(getattr(self.gameinfo, field), "reset"): getattr(self.gameinfo, field).reset() # save the current game to the calendar def saveGame(self): items = self.gamelist.selectedItems() game = Game() # disable the save button while running self.savebutton.setDisabled(True) # go through each field in the info widget for field in self.gameinfo.__dict__: # If a matching attribute in a game object is found, set the value, checking officials if needed if hasattr(game, field): setattr(game, field, getattr(self.gameinfo, field).getValue().__str__()) elif field in game.officials: game.officials[field] = getattr(self.gameinfo, field).getValue().__str__() # If no location specified, just use the home team. if game.where == "": game.where = game.home event = None # If no game is selected, create a new entry, otherwise, use the existing entry in the game's object if len(items) == 0: event = gdata.calendar.CalendarEventEntry() else: event = items[0].game.event # clear the when and where fields del event.when[0:len(event.when)] del event.where[0:len(event.where)] # set the event title, content, and where event.title = atom.Title(text=game.getTitle()) event.content = atom.Content(text=game.getContent()) event.where.append(gdata.calendar.Where(value_string=game.where)) # build the start time info in UTC format start_time = '%sT%s:00.000' % (game.date, game.time) # If subvarsity, 2 hours for the game; Varsity is 4 hours gamelen = 2 if (game.level == 'V'): gamelen = 4 # set the stop time in UTC format based on the game length stop = QtCore.QTime(QtCore.QTime.fromString(game.time,"hh:mm")).addSecs(gamelen*60*60) stop_time = '%sT%s:00.000' % (game.date, stop.toString("hh:mm")) event.when.append(gdata.calendar.When(start_time=start_time, end_time=stop_time)) try: boxtext = "" if len(items) == 0: # if a new game, use the insert event method self.client.InsertEvent(event, '/calendar/feeds/default/private/full') boxtext = "The game has been added to your calendar." else: # if updating a previous game, use the update event method # note that you must get the edit link from the object in order to do the update self.client.UpdateEvent(event.GetEditLink().href, event) boxtext = "The game has been modified." # refresh the list and display the message self.refreshlist() msgBox = QtGui.QMessageBox() msgBox.setText(boxtext) msgBox.exec_() except gdata.service.RequestError as err: # if there was a problem with the save, display the error message msgBox = QtGui.QMessageBox() msgBox.setText("ERROR: " + str(err)) msgBox.exec_() # re-enable the save button self.savebutton.setDisabled(False) # export the current game list to an iCalendar file def exportIcal(self): # open the confirm dialog confirmDialog = ExportDialog() if confirmDialog.exec_() == QtGui.QDialog.Rejected: return # get the values from the dialog filename = confirmDialog.filename.text() onlywork = confirmDialog.onlyworkhours.isChecked() # create and initialize the Calendar object cal = icalendar.Calendar() cal.add('prodid', '-//Football Calendar//gmail.com//') cal.add('version', '2.0') # go through each game in the list numgames = self.gamelist.count() for i in range(0, numgames): # get the Game object and date/time info game = self.gamelist.item(i).game (year, month, day) = game.date.split("-") year = int(year) month = int(month) day = int(day) (hour, minute) = game.time.split(":") hour = int(hour) minute = int(minute) # Give an hour and a half "travel time" if minute < 30: hour -= 2 minute += 30 else: hour -= 1 minute -= 30 # create the datetime objects start = datetime(year, month, day, hour, minute, 0) stop = datetime(year, month, day, hour+4, minute, 0) # if a weekend game or past 5:00PM, and only games during work # time are wanted, skip this game if onlywork and (start.weekday() >= 5 or hour >= 17): continue # create the generic game event (details aren't needed) and add it to the calendar event = icalendar.Event() event.add('summary', 'Football Game') event.add('dtstart', start) event.add('dtend', stop) event.add('dtstamp', datetime.now()) event.add('priority', 3) event['uid'] = "%4d%02d%02dT%02d%02d00/sigmazero13@gmail.com" % (year, month, day, hour, minute) cal.add_component(event) # write the calendar file f = open(filename, 'wb') f.write(cal.as_string()) f.close # MAIN PROGRAM START # create the application and main window objects app = QtGui.QApplication(sys.argv) main = MainWindow() # display the login dialog. If canceled, just quit. loginDialog = LoginDialog() if loginDialog.exec_() == QtGui.QDialog.Rejected: sys.exit() client = gdata.calendar.service.CalendarService() try: # Try to log into the service client.ClientLogin(loginDialog.username.text(), loginDialog.password.text()) except gdata.service.Error as err: # if there's an error, display a message and quit msgBox = QtGui.QMessageBox() msgBox.setText("ERROR: " + str(err)) msgBox.exec_() sys.exit() # set the client, refresh the list, show the main window and run the application's event loop main.setClient(client) main.refreshlist() main.show() sys.exit(app.exec_())
Python
"""wrapper for libmpq""" # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. import ctypes import ctypes.util import os libmpq = ctypes.CDLL(ctypes.util.find_library("mpq")) class Error(Exception): pass errors = { -1: (IOError, "open"), -2: (IOError, "close"), -3: (IOError, "seek"), -4: (IOError, "read"), -5: (IOError, "write"), -6: (MemoryError,), -7: (Error, "file is not an mpq or is corrupted"), -8: (AssertionError, "not initialized"), -9: (AssertionError, "buffer size too small"), -10: (IndexError, "file not in archive"), -11: (AssertionError, "decrypt"), -12: (AssertionError, "unpack"), } def check_error(result, func, arguments, errors=errors): try: error = errors[result] except KeyError: return result else: raise error[0](*error[1:]) libmpq.libmpq__version.restype = ctypes.c_char_p libmpq.libmpq__archive_open.errcheck = check_error libmpq.libmpq__archive_close.errcheck = check_error libmpq.libmpq__archive_packed_size.errcheck = check_error libmpq.libmpq__archive_unpacked_size.errcheck = check_error libmpq.libmpq__archive_offset.errcheck = check_error libmpq.libmpq__archive_version.errcheck = check_error libmpq.libmpq__archive_files.errcheck = check_error libmpq.libmpq__file_packed_size.errcheck = check_error libmpq.libmpq__file_unpacked_size.errcheck = check_error libmpq.libmpq__file_offset.errcheck = check_error libmpq.libmpq__file_blocks.errcheck = check_error libmpq.libmpq__file_encrypted.errcheck = check_error libmpq.libmpq__file_compressed.errcheck = check_error libmpq.libmpq__file_imploded.errcheck = check_error libmpq.libmpq__file_number.errcheck = check_error libmpq.libmpq__file_read.errcheck = check_error libmpq.libmpq__block_open_offset.errcheck = check_error libmpq.libmpq__block_close_offset.errcheck = check_error libmpq.libmpq__block_unpacked_size.errcheck = check_error libmpq.libmpq__block_read.errcheck = check_error __version__ = libmpq.libmpq__version() class Reader(object): def __init__(self, file, libmpq=libmpq): self._file = file self._pos = 0 self._buf = [] self._cur_block = 0 libmpq.libmpq__block_open_offset(self._file._archive._mpq, self._file.number) def __iter__(self): return self def __repr__(self): return "iter(%r)" % self._file def seek(self, offset, whence=os.SEEK_SET, os=os): if whence == os.SEEK_SET: pass elif whence == os.SEEK_CUR: offset += self._pos elif whence == os.SEEK_END: offset += self._file.unpacked_size else: raise ValueError, "invalid whence" if offset >= self._pos: self.read(offset - self._pos) else: self._pos = 0 self._buf = [] self._cur_block = 0 self.read(offset) def tell(self): return self._pos def _read_block(self, ctypes=ctypes, libmpq=libmpq): block_size = ctypes.c_uint64() libmpq.libmpq__block_unpacked_size(self._file._archive._mpq, self._file.number, self._cur_block, ctypes.byref(block_size)) block_data = ctypes.create_string_buffer(block_size.value) libmpq.libmpq__block_read(self._file._archive._mpq, self._file.number, self._cur_block, block_data, ctypes.c_uint64(len(block_data)), None) self._buf.append(block_data.raw) self._cur_block += 1 def read(self, size=-1): while size < 0 or sum(map(len, self._buf)) < size: if self._cur_block == self._file.blocks: break self._read_block() buf = "".join(self._buf) if size < 0: ret = buf self._buf = [] else: ret = buf[:size] self._buf = [buf[size:]] self._pos += len(ret) return ret def readline(self, os=os): line = [] while True: char = self.read(1) if char == "": break if char not in '\r\n' and line and line[-1] in '\r\n': self.seek(-1, os.SEEK_CUR) break line.append(char) return ''.join(line) def next(self): line = self.readline() if not line: raise StopIteration return line def readlines(self, sizehint=-1): res = [] while sizehint < 0 or sum(map(len, res)) < sizehint: line = self.readline() if not line: break res.append(line) return res xreadlines = __iter__ def __del__(self, libmpq=libmpq): libmpq.libmpq__block_close_offset(self._file._archive._mpq, self._file.number) class File(object): def __init__(self, archive, number, ctypes=ctypes, libmpq=libmpq): self._archive = archive self.number = number for name, atype in [ ("packed_size", ctypes.c_uint64), ("unpacked_size", ctypes.c_uint64), ("offset", ctypes.c_uint64), ("blocks", ctypes.c_uint32), ("encrypted", ctypes.c_uint32), ("compressed", ctypes.c_uint32), ("imploded", ctypes.c_uint32), ]: data = atype() func = getattr(libmpq, "libmpq__file_"+name) func(self._archive._mpq, self.number, ctypes.byref(data)) setattr(self, name, data.value) def __str__(self, ctypes=ctypes, libmpq=libmpq): data = ctypes.create_string_buffer(self.unpacked_size) libmpq.libmpq__file_read(self._archive._mpq, self.number, data, ctypes.c_uint64(len(data)), None) return data.raw def __repr__(self): return "%r[%i]" % (self._archive, self.number) def __iter__(self, Reader=Reader): return Reader(self) class Archive(object): def __init__(self, source, ctypes=ctypes, File=File, libmpq=libmpq): self._source = source if isinstance(source, File): assert not source.encrypted assert not source.compressed assert not source.imploded self.filename = source._archive.filename offset = source._archive.offset + source.offset else: self.filename = source offset = -1 self._mpq = ctypes.c_void_p() libmpq.libmpq__archive_open(ctypes.byref(self._mpq), self.filename, ctypes.c_uint64(offset)) self._opened = True for field_name, field_type in [ ("packed_size", ctypes.c_uint64), ("unpacked_size", ctypes.c_uint64), ("offset", ctypes.c_uint64), ("version", ctypes.c_uint32), ("files", ctypes.c_uint32), ]: func = getattr(libmpq, "libmpq__archive_" + field_name) data = field_type() func(self._mpq, ctypes.byref(data)) setattr(self, field_name, data.value) def __del__(self, libmpq=libmpq): if getattr(self, "_opened", False): libmpq.libmpq__archive_close(self._mpq) def __len__(self): return self.files def __contains__(self, item, ctypes=ctypes, libmpq=libmpq): if isinstance(item, str): data = ctypes.c_uint32() try: libmpq.libmpq__file_number(self._mpq, ctypes.c_char_p(item), ctypes.byref(data)) except IndexError: return False return True return 0 <= item < self.files def __getitem__(self, item, ctypes=ctypes, File=File, libmpq=libmpq): if isinstance(item, str): data = ctypes.c_int() libmpq.libmpq__file_number(self._mpq, ctypes.c_char_p(item), ctypes.byref(data)) item = data.value else: if not 0 <= item < self.files: raise IndexError, "file not in archive" return File(self, item) def __repr__(self): return "mpq.Archive(%r)" % self._source # Remove clutter - everything except Error and Archive. del os, check_error, ctypes, errors, File, libmpq, Reader if __name__ == "__main__": import sys, random archive = Archive(sys.argv[1]) print repr(archive) for k, v in archive.__dict__.iteritems(): #if k[0] == '_': continue print " " * (4 - 1), k, v assert '(listfile)' in archive assert 0 in archive assert len(archive) == archive.files files = [x.strip() for x in archive['(listfile)']] files.extend(xrange(archive.files)) for key in files: #sys.argv[2:] if sys.argv[2:] else xrange(archive.files): file = archive[key] print print " " * (4 - 1), repr(file) for k, v in file.__dict__.iteritems(): #if k[0] == '_': continue print " " * (8 - 1), k, v a = str(file) b = iter(file).read() reader = iter(file) c = [] while True: l = random.randrange(1, 10) d = reader.read(l) if not d: break assert len(d) <= l c.append(d) c = "".join(c) d = [] reader.seek(0) for line in reader: d.append(line) d = "".join(d) assert a == b == c == d, map(hash, [a,b,c,d]) assert len(a) == file.unpacked_size repr(iter(file)) reader.seek(0) a = reader.readlines() reader.seek(0) b = list(reader) assert a == b
Python
#!/usr/bin/env python from __future__ import division import sys import mpq archive = mpq.Archive(sys.argv[1]) print "Name: %s" % sys.argv[1] print "Version: %s" % archive.filename print "Offset: %s" % archive.offset print "Packed size: %s" % archive.packed_size print "Unpacked size: %s" % archive.unpacked_size print "Compression ratio: %s" % (archive.packed_size/archive.unpacked_size)
Python
#!/usr/bin/python import datetime #import subprocess import commands import time import sys def main(argv): if len(argv) < 2: sys.stderr.write("Usage: %s <action>" % (argv[0],)) return 1 output = commands.getoutput("ps -e") while argv[1] in output: output = commands.getoutput("ps -e") print argv[1], " running", datetime.datetime.now() #print output time.sleep(30) sys.stderr.write("Process finished at %s\n" % datetime.datetime.now()) if __name__ == "__main__": sys.exit(main(sys.argv))
Python
#!/usr/bin/python #@author Aditya Kumar #This python script is used in copying the directory structure #from one directory-path to the other. import os import shutil import sys if __name__ == '__main__': os.system('rm -rf dm_dir') origPath = "/home/hiraditya/Downloads/hiphop/hiphop-aug17/hiphop-php" pathname = "/home/hiraditya/Downloads/hiphop/hiphop-aug17/hiphop-php/dm_dir/" for dirname, dirnames, filenames in os.walk(origPath): print "old dirname", dirname, "\n\t" newDir = dirname.replace(origPath,pathname) print "new dir name", newDir os.mkdir(newDir)
Python
#!/usr/bin/python import datetime #import subprocess import commands import time import sys def main(argv): if len(argv) < 2: sys.stderr.write("Usage: %s <action>" % (argv[0],)) return 1 output = commands.getoutput("ps -e") while argv[1] in output: output = commands.getoutput("ps -e") print argv[1], " running", datetime.datetime.now() #print output time.sleep(30) sys.stderr.write("Process finished at %s\n" % datetime.datetime.now()) if __name__ == "__main__": sys.exit(main(sys.argv))
Python
#!/usr/bin/python #@author Aditya Kumar #This python script is used in copying the directory structure #from one directory-path to the other. import os import shutil import sys if __name__ == '__main__': os.system('rm -rf dm_dir') origPath = "/home/hiraditya/Downloads/hiphop/hiphop-aug17/hiphop-php" pathname = "/home/hiraditya/Downloads/hiphop/hiphop-aug17/hiphop-php/dm_dir/" for dirname, dirnames, filenames in os.walk(origPath): print "old dirname", dirname, "\n\t" newDir = dirname.replace(origPath,pathname) print "new dir name", newDir os.mkdir(newDir)
Python
#!/usr/bin/python import pygst pygst.require("0.10") import gst class StreamManager: "Classe do gerenciador de media.\nFornece funcoes de abrir, tocar e pausa." def __init__(self, metadata_callback=None, eos_callback=None): '''Construtor do StreamManager. Pode receber uma funcao de atualizacao a ser chamada quando houver mudanca nos metadados.''' self.title = None self.artist = None self.position = gst.CLOCK_TIME_NONE self.duration = gst.CLOCK_TIME_NONE self.metadata_callback = metadata_callback self.eos_callback = eos_callback self.player = gst.element_factory_make("playbin", "playaPlaybin") bus = self.player.get_bus() bus.add_signal_watch() bus.connect('message', self.__on_message) def __on_message(self, bus, message): "Recebe mensagens da Bus." if message.type == gst.MESSAGE_TAG: tags = message.parse_tag() try: self.title = tags['title'] self.artist = tags['artist'] except: pass if self.metadata_callback: self.metadata_callback() elif message.type == gst.MESSAGE_EOS: if self.eos_callback: self.eos_callback() elif message.type == gst.MESSAGE_ERROR: print 'ERROR' print message def is_playing(self): print 'is_playing:' print self.player.get_state()[1] print self.player.get_state()[1] == gst.STATE_PLAYING playing = self.player.get_state()[1] == gst.STATE_PLAYING return playing def open(self, filepath): "Abre arquivo de audio (na verdade de midia, mas vamos ficar no audio)." self.player.set_property('uri', 'file://' + filepath) self.player.set_state(gst.STATE_READY) self.title = filepath self.artist = None self.duration = 0 def play(self): "Toca o stream de audio carregado." return \ self.player.set_state(gst.STATE_PLAYING) == gst.STATE_CHANGE_SUCCESS def pause(self): "Pausa o stream de audio carregado." return \ self.player.set_state(gst.STATE_PAUSED) == gst.STATE_CHANGE_SUCCESS def seek(self, location): "Move para localizacao temporal dentro do stream." event = gst.event_new_seek(1.0, gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_ACCURATE, gst.SEEK_TYPE_SET, location, gst.SEEK_TYPE_NONE, 0) success = self.player.send_event(event) if not success: gst.error("seek to %r failed" % location) '''Codigo deprecated, esta aqui por um tempo pra servir de referencia if res: gst.info("setting new stream time to 0") self.player.set_new_stream_time(0L) else: gst.error("seek to %r failed" % location) ''' def get_position(self): "Retorna uma tupla (position, duration)" try: self.position, format = self.player.query_position(gst.FORMAT_TIME) except: self.position = gst.CLOCK_TIME_NONE try: self.duration, format = self.player.query_duration(gst.FORMAT_TIME) except: self.duration = gst.CLOCK_TIME_NONE return (self.position, self.duration) def format_time(self, time): time_seconds = time / gst.SECOND time_f = '%02d:%02d' % (time_seconds / 60, time_seconds % 60) return time_f
Python
#!/usr/bin/python import pygst pygst.require("0.10") import gst class StreamManager: "Classe do gerenciador de media.\nFornece funcoes de abrir, tocar e pausa." def __init__(self, metadata_callback=None, eos_callback=None): '''Construtor do StreamManager. Pode receber uma funcao de atualizacao a ser chamada quando houver mudanca nos metadados.''' self.title = None self.artist = None self.position = gst.CLOCK_TIME_NONE self.duration = gst.CLOCK_TIME_NONE self.metadata_callback = metadata_callback self.eos_callback = eos_callback self.player = gst.element_factory_make("playbin", "playaPlaybin") bus = self.player.get_bus() bus.add_signal_watch() bus.connect('message', self.__on_message) def __on_message(self, bus, message): "Recebe mensagens da Bus." if message.type == gst.MESSAGE_TAG: tags = message.parse_tag() try: self.title = tags['title'] self.artist = tags['artist'] except: pass if self.metadata_callback: self.metadata_callback() elif message.type == gst.MESSAGE_EOS: if self.eos_callback: self.eos_callback() elif message.type == gst.MESSAGE_ERROR: print 'ERROR' print message def is_playing(self): print 'is_playing:' print self.player.get_state()[1] print self.player.get_state()[1] == gst.STATE_PLAYING playing = self.player.get_state()[1] == gst.STATE_PLAYING return playing def open(self, filepath): "Abre arquivo de audio (na verdade de midia, mas vamos ficar no audio)." self.player.set_property('uri', 'file://' + filepath) self.player.set_state(gst.STATE_READY) self.title = filepath self.artist = None self.duration = 0 def play(self): "Toca o stream de audio carregado." return \ self.player.set_state(gst.STATE_PLAYING) == gst.STATE_CHANGE_SUCCESS def pause(self): "Pausa o stream de audio carregado." return \ self.player.set_state(gst.STATE_PAUSED) == gst.STATE_CHANGE_SUCCESS def seek(self, location): "Move para localizacao temporal dentro do stream." event = gst.event_new_seek(1.0, gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_ACCURATE, gst.SEEK_TYPE_SET, location, gst.SEEK_TYPE_NONE, 0) success = self.player.send_event(event) if not success: gst.error("seek to %r failed" % location) '''Codigo deprecated, esta aqui por um tempo pra servir de referencia if res: gst.info("setting new stream time to 0") self.player.set_new_stream_time(0L) else: gst.error("seek to %r failed" % location) ''' def get_position(self): "Retorna uma tupla (position, duration)" try: self.position, format = self.player.query_position(gst.FORMAT_TIME) except: self.position = gst.CLOCK_TIME_NONE try: self.duration, format = self.player.query_duration(gst.FORMAT_TIME) except: self.duration = gst.CLOCK_TIME_NONE return (self.position, self.duration) def format_time(self, time): time_seconds = time / gst.SECOND time_f = '%02d:%02d' % (time_seconds / 60, time_seconds % 60) return time_f
Python
#!/usr/bin/python from StreamManager import StreamManager import pygtk pygtk.require("2.0") import gtk import gtk.glade import gobject class PyPlaya: def __init__(self): self.timeout_id = -1 self.was_playing = False self.streamManager = StreamManager(self.metadata_callback, self.eos_callback) self.widgetTree = gtk.glade.XML('playa.glade') #Widgets self.window = self.widgetTree.get_widget('playaWindow') self.playPauseBtn = self.widgetTree.get_widget('playPauseBtn') self.playPauseImg = self.widgetTree.get_widget('playPauseImg') self.playingLabel = self.widgetTree.get_widget('playingLabel') self.timeLabel = self.widgetTree.get_widget('timeLabel') self.timeBar = self.widgetTree.get_widget('timeBar') self.time_adjustment = self.timeBar.get_adjustment() self.window.set_title('PyPlaya') self.widgetTree.signal_autoconnect(self) self.window.show_all() # Callbacks ----------------------------------------------------- def on_timeBar_press(self, widget, event): self.was_playing = self.streamManager.is_playing() if self.was_playing: gobject.source_remove(self.timeout_id) def on_timeBar_release(self, widget, event): pos = long(self.timeBar.get_value() * self.streamManager.duration / 100) self.streamManager.seek(pos) self.update_gui() if self.was_playing: self.play() def on_playPause_clicked(self, widget): if self.streamManager.is_playing(): self.pause() else: self.play() def on_open_clicked(self, widget): fileDlg = gtk.FileChooserDialog(title='Abrir arquivo...', parent=self.window, action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK)) if fileDlg.run() == gtk.RESPONSE_OK: self.open_media(fileDlg.get_filename()) fileDlg.hide() def metadata_callback(self): self.playingLabel.set_markup('<big><b>%s - %s</b></big>' % (self.streamManager.artist, self.streamManager.title)) def eos_callback(self): self.pause() self.streamManager.seek(long(0)) self.update_gui(init=True) # Metodos auxiliares -------------------------------------------- def play(self): if self.streamManager.play(): self.playPauseImg.set_from_stock( gtk.STOCK_MEDIA_PAUSE, gtk.ICON_SIZE_BUTTON) self.timeout_id = gobject.timeout_add(500, self.update_gui) def pause(self): if self.streamManager.pause(): self.playPauseImg.set_from_stock( gtk.STOCK_MEDIA_PLAY, gtk.ICON_SIZE_BUTTON) gobject.source_remove(self.timeout_id) def open_media(self, filepath): self.playPauseBtn.set_sensitive(True) self.timeBar.set_sensitive(True) self.streamManager.open(filepath) self.pause() def update_gui(self, init=False): position, duration = self.streamManager.get_position() if init: position = 0 self.timeLabel.set_text('%s/%s' % (self.streamManager.format_time(position), self.streamManager.format_time(duration))) self.time_adjustment.set_value(position * 100.0 / duration) return True def exit_playa(self, widget): self.streamManager.pause() gtk.main_quit() # Main ======================================================================== if __name__ == "__main__": PyPlaya() gtk.main()
Python
#!/usr/bin/python from StreamManager import StreamManager import pygtk pygtk.require("2.0") import gtk import gtk.glade import gobject class PyPlaya: def __init__(self): self.timeout_id = -1 self.was_playing = False self.streamManager = StreamManager(self.metadata_callback, self.eos_callback) self.widgetTree = gtk.glade.XML('playa.glade') #Widgets self.window = self.widgetTree.get_widget('playaWindow') self.playPauseBtn = self.widgetTree.get_widget('playPauseBtn') self.playPauseImg = self.widgetTree.get_widget('playPauseImg') self.playingLabel = self.widgetTree.get_widget('playingLabel') self.timeLabel = self.widgetTree.get_widget('timeLabel') self.timeBar = self.widgetTree.get_widget('timeBar') self.time_adjustment = self.timeBar.get_adjustment() self.window.set_title('PyPlaya') self.widgetTree.signal_autoconnect(self) self.window.show_all() # Callbacks ----------------------------------------------------- def on_timeBar_press(self, widget, event): self.was_playing = self.streamManager.is_playing() if self.was_playing: gobject.source_remove(self.timeout_id) def on_timeBar_release(self, widget, event): pos = long(self.timeBar.get_value() * self.streamManager.duration / 100) self.streamManager.seek(pos) self.update_gui() if self.was_playing: self.play() def on_playPause_clicked(self, widget): if self.streamManager.is_playing(): self.pause() else: self.play() def on_open_clicked(self, widget): fileDlg = gtk.FileChooserDialog(title='Abrir arquivo...', parent=self.window, action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK)) if fileDlg.run() == gtk.RESPONSE_OK: self.open_media(fileDlg.get_filename()) fileDlg.hide() def metadata_callback(self): self.playingLabel.set_markup('<big><b>%s - %s</b></big>' % (self.streamManager.artist, self.streamManager.title)) def eos_callback(self): self.pause() self.streamManager.seek(long(0)) self.update_gui(init=True) # Metodos auxiliares -------------------------------------------- def play(self): if self.streamManager.play(): self.playPauseImg.set_from_stock( gtk.STOCK_MEDIA_PAUSE, gtk.ICON_SIZE_BUTTON) self.timeout_id = gobject.timeout_add(500, self.update_gui) def pause(self): if self.streamManager.pause(): self.playPauseImg.set_from_stock( gtk.STOCK_MEDIA_PLAY, gtk.ICON_SIZE_BUTTON) gobject.source_remove(self.timeout_id) def open_media(self, filepath): self.playPauseBtn.set_sensitive(True) self.timeBar.set_sensitive(True) self.streamManager.open(filepath) self.pause() def update_gui(self, init=False): position, duration = self.streamManager.get_position() if init: position = 0 self.timeLabel.set_text('%s/%s' % (self.streamManager.format_time(position), self.streamManager.format_time(duration))) self.time_adjustment.set_value(position * 100.0 / duration) return True def exit_playa(self, widget): self.streamManager.pause() gtk.main_quit() # Main ======================================================================== if __name__ == "__main__": PyPlaya() gtk.main()
Python