# HG changeset patch # User Emmanuel Gil Peyrot # Date 1358528134 -3600 # Node ID 952322b1d490665c070feef0355950b6e73ab660 # Parent 6a718ede8be1bf3651308788fc2ab7745ddaf376 Remove trailing whitespaces. diff -r 6a718ede8be1 -r 952322b1d490 CONTRAT_SOCIAL --- a/CONTRAT_SOCIAL Fri Jan 18 17:55:27 2013 +0100 +++ b/CONTRAT_SOCIAL Fri Jan 18 17:55:34 2013 +0100 @@ -24,5 +24,5 @@ - L'idée de Fraternité est essentielle, aussi: - nous ferons notre possible pour aider les utilisateurs, quel que soit leur niveau - - de même, des efforts seront fait quant à l'accessibilité aux personnes victimes d'un handicap + - de même, des efforts seront fait quant à l'accessibilité aux personnes victimes d'un handicap - « Salut à Toi », XMPP, et les technologies utilisées facilitent les échanges électroniques, mais nous désirons mettre l'accent sur les rencontres réelles et humaines: nous favoriserons toujours le réel sur le virtuel. diff -r 6a718ede8be1 -r 952322b1d490 INSTALL --- a/INSTALL Fri Jan 18 17:55:27 2013 +0100 +++ b/INSTALL Fri Jan 18 17:55:34 2013 +0100 @@ -1,6 +1,6 @@ *** Below are the old manual instructions for installation, you can install SàT automatically using easy_install or pip. The full instructions are available on the wiki: http://wiki.goffi.org/wiki/Salut_%C3%A0_Toi -*** +*** The following instructions are for GNU/Linux operating system. Instruction for other OS will come in the future. diff -r 6a718ede8be1 -r 952322b1d490 README --- a/README Fri Jan 18 17:55:27 2013 +0100 +++ b/README Fri Jan 18 17:55:34 2013 +0100 @@ -63,7 +63,7 @@ ** Misc ** -You can find Primitivus shortcuts on the wiki: +You can find Primitivus shortcuts on the wiki: http://wiki.goffi.org/wiki/Primitivus -- diff -r 6a718ede8be1 -r 952322b1d490 frontends/sortilege_old/boxsizer.py --- a/frontends/sortilege_old/boxsizer.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/sortilege_old/boxsizer.py Fri Jan 18 17:55:34 2013 +0100 @@ -62,7 +62,7 @@ else: current_row.append([win, h+y-oriY, w+x-oriX, oriY, oriX]) oriX=oriX+w - + if oriX!=0: oriY=oriY+h visible_row.append(current_row) diff -r 6a718ede8be1 -r 952322b1d490 frontends/sortilege_old/chat.py --- a/frontends/sortilege_old/chat.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/sortilege_old/chat.py Fri Jan 18 17:55:34 2013 +0100 @@ -40,7 +40,7 @@ class Chat(Window, QuickChat): def __init__(self, to_id, host): - QuickChat.__init__(self, to_id, host) + QuickChat.__init__(self, to_id, host) self.__parent=host.stdscr self.to_id=JID(to_id) self.content=[] @@ -88,7 +88,7 @@ att_header=curses.color_pair(1) else: att_header=curses.color_pair(2) - + while (msg): if part==0: hd=header @@ -105,7 +105,7 @@ next = max + 1 #we skip the LF else: next = max - + content.insert(part,[att,hd, msg[:max]]) msg=msg[next:] #we erase treated part part=part+1 @@ -116,7 +116,7 @@ if self.__scollIdx>0 and len(content) 0: @@ -144,7 +144,7 @@ return self.content.append([timestamp,jid.short,msg]) self.update() - + def handleKey(self, k): if k == C('p'): self.scrollIdxUp() diff -r 6a718ede8be1 -r 952322b1d490 frontends/sortilege_old/editbox.py --- a/frontends/sortilege_old/editbox.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/sortilege_old/editbox.py Fri Jan 18 17:55:34 2013 +0100 @@ -43,7 +43,7 @@ self.__replace_mode=False self.__parent=parent self.__code=code - + Window.__init__(self, self.__parent, 1, self.__parent.getmaxyx()[1], self.__parent.getmaxyx()[0]-1,0, code=code) self.update() @@ -60,7 +60,7 @@ """return the text printed on the edit line""" width = self.rWidth - len(self.__header) -1 if self.__curs_pos=self.rWidth: @@ -94,7 +94,7 @@ """Clear the text of the edit box""" self.__text="" self.__curs_pos=0 - + def replace_cur(self): """must be called earch time the cursor is moved""" self.move_cur(self.__curs_pos) @@ -136,7 +136,7 @@ elif k==curses.KEY_HOME or k==C('a'): self.__curs_pos=0 - + elif k==curses.KEY_END or k==C('e'): self.__curs_pos=len(self.__text) diff -r 6a718ede8be1 -r 952322b1d490 frontends/sortilege_old/sortilege --- a/frontends/sortilege_old/sortilege Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/sortilege_old/sortilege Fri Jan 18 17:55:34 2013 +0100 @@ -39,7 +39,7 @@ import time from curses import ascii import locale -from signal import signal, SIGWINCH +from signal import signal, SIGWINCH import fcntl import struct import termios @@ -68,7 +68,7 @@ class ChatList(QuickChatList): """This class manage the list of chat windows""" - + def __init__(self, host): QuickChatList.__init__(self, host) self.sizer=host.sizer @@ -77,10 +77,10 @@ chat = Chat(name, self.host) self.sizer.appendColum(0,chat) self.sizer.update() - return chat - + return chat + class ContactList(Window, QuickContactList): - + def __init__(self, host, CM): QuickContactList.__init__(self, CM) self.host = host @@ -97,7 +97,7 @@ Must be called when stdscr is resized.""" self.resize(stdscr.getmaxyx()[0]-2,const_CONTACT_WIDTH,0,0) self.update() - + def registerEnterCB(self, CB): self.__enterCB=CB @@ -118,7 +118,7 @@ if self.__index < len(self.jid_list)-1: #we dont want to select a missing contact self.__index = self.__index + 1 self.update() - + def indexDown(self): """decrement select contact index""" if self.__index > 0: @@ -142,7 +142,7 @@ return Window.update(self) self.jid_list.sort() - begin=0 if self.__index 0: continue #the new message is older, we need to insert it upper - + #we discard double messages, to avoid backlog / history conflict if ((idx and self.content[idx-1].message == msg) or (self.content[idx].message == msg) or @@ -262,7 +262,7 @@ break else: self.content.append(new_text) - + if self.text_list.get_focus()[1] == len(self.content)-2: #we don't change focus if user is not at the bottom #as that mean that he is probably watching discussion history @@ -271,9 +271,9 @@ if not self.host.x_notify.hasFocus(): if self.type=="one2one": self.host.x_notify.sendNotification(_("Primitivus: %s is talking to you") % from_jid) - elif self.getUserNick().lower() in msg.lower(): + elif self.getUserNick().lower() in msg.lower(): self.host.x_notify.sendNotification(_("Primitivus: Somebody pinged your name in %s room") % self.target) - + def printInfo(self, msg, type='normal', timestamp=""): """Print general info @param msg: message to print @@ -292,28 +292,28 @@ if not self.host.x_notify.hasFocus(): if self.type=="one2one": self.host.x_notify.sendNotification(_("Primitivus: there is a message about you")) - elif self.getUserNick().lower() in msg.lower(): + elif self.getUserNick().lower() in msg.lower(): self.host.x_notify.sendNotification(_("Primitivus: Somebody is talking about you in %s room") % self.target) - + def startGame(self, game_type, referee, players): """Configure the chat window to start a game""" if game_type=="Tarot": self.tarot_wid = CardGame(self, referee, players, self.nick) self.__appendGamePanel(self.tarot_wid) - + def getGame(self, game_type): """Return class managing the game type""" #TODO: check that the game is launched, and manage errors if game_type=="Tarot": - return self.tarot_wid + return self.tarot_wid #MENU EVENTS# def onTarotRequest(self, menu): if len(self.occupants) != 4: - self.host.showPopUp(sat_widgets.Alert(_("Can't start game"), _("You need to be exactly 4 peoples in the room to start a Tarot game"), ok_cb=self.host.removePopUp)) + self.host.showPopUp(sat_widgets.Alert(_("Can't start game"), _("You need to be exactly 4 peoples in the room to start a Tarot game"), ok_cb=self.host.removePopUp)) else: self.host.bridge.tarotGameCreate(self.id, list(self.occupants), self.host.profile) - + def onSendFileRequest(self, menu): dialog = FileDialog(ok_cb=self.onFileSelected, cancel_cb=self.host.removePopUp) self.host.showPopUp(dialog, 80, 80) @@ -328,4 +328,4 @@ else: full_jid = self.target progress_id = self.host.bridge.sendFile(full_jid, filepath, {}, self.host.profile) - self.host.addProgress(progress_id,filepath) + self.host.addProgress(progress_id,filepath) diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/primitivus/constants.py --- a/frontends/src/primitivus/constants.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/primitivus/constants.py Fri Jan 18 17:55:34 2013 +0100 @@ -68,7 +68,7 @@ ('status', 'yellow', 'default'), ('status_focus', 'yellow, bold', 'default'), ] -__builtin__.__dict__['const_SHOW_ICON'] = {"unavailable": (u'⨯', "show_disconnected"), +__builtin__.__dict__['const_SHOW_ICON'] = {"unavailable": (u'⨯', "show_disconnected"), "": (u'✔', "show_normal"), "chat": (u'✆', "show_chat"), "away": (u'✈', "show_away"), diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/primitivus/contact_list.py --- a/frontends/src/primitivus/contact_list.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/primitivus/contact_list.py Fri Jan 18 17:55:34 2013 +0100 @@ -37,7 +37,7 @@ self.alert_jid=set() self.show_status = False self.show_disconnected = False - + #we now build the widget self.frame = urwid.Frame(self.__buildList()) self.main_widget = sat_widgets.LabelLine(self.frame, sat_widgets.SurroundedText(_("Contacts"))) @@ -65,8 +65,8 @@ elif key == "meta d": #user wants to (un)hide disconnected contacts self.show_disconnected = not self.show_disconnected self.update() - return super(ContactList, self).keypress(size, key) - + return super(ContactList, self).keypress(size, key) + def __contains__(self, jid): for group in self.groups: if jid.short in self.groups[group][1]: @@ -116,9 +116,9 @@ @param content: widget list, e.g. SimpleListWalker @param contacts: list of JID""" contacts = list(param_contacts) - + widgets = [] #list of built widgets - + for contact in contacts: if contact.startswith(const_PRIVATE_PREFIX): contact_disp = ('alert' if contact in self.alert_jid else "show_normal", unescapePrivate(contact)) @@ -148,7 +148,7 @@ widget.data = contact widget.comp = contact_disp[1].lower() #value to use for sorting widgets.append(widget) - + widgets.sort(key=lambda widget: widget.comp) for widget in widgets: @@ -160,7 +160,7 @@ specials = self.specials.keys() specials.sort() for special in specials: - jid=JID(special) + jid=JID(special) name = self.getCache(jid, 'name') nick = self.getCache(jid, 'nick') special_disp = ('alert' if special in self.alert_jid else 'default', nick or name or jid.node or jid.short) @@ -176,7 +176,7 @@ def __buildList(self): """Build the main contact list widget""" content = urwid.SimpleListWalker([]) - + self.__buildSpecials(content) if self.specials: content.append(urwid.Divider('=')) @@ -205,7 +205,7 @@ def getContact(self): """Return contact currently selected""" return self.selected - + def clearContacts(self): """clear all the contact list""" QuickContactList.clearContacts(self) @@ -238,7 +238,7 @@ contacts.sort() self.list_wid.changeValues(contacts) self._emit('change')""" - + def remove(self, jid): """remove a contact from the list""" QuickContactList.remove(self, jid) @@ -252,7 +252,7 @@ for group in groups_to_remove: del self.groups[group] self.update() - + def add(self, jid, param_groups=[None]): """add a contact to the list""" self.replace(jid,param_groups) diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/primitivus/gateways.py --- a/frontends/src/primitivus/gateways.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/primitivus/gateways.py Fri Jan 18 17:55:34 2013 +0100 @@ -44,7 +44,7 @@ list_wid = urwid.ListBox(widget_list) decorated = sat_widgets.LabelLine(list_wid, sat_widgets.SurroundedText(title)) urwid.WidgetWrap.__init__(self, decorated) - + def browseExternalServer(self, button): """Open the gateway manager on given server""" server = self.ext_serv.get_edit_text() @@ -58,15 +58,15 @@ self.host.removeWindow() def addGateway(self, widget_list, gateway, param): - + widget_col = [] widget_col.append(('weight',4,urwid.Text(unicode(param['name'])))) #FIXME: unicode to be remove when DBus bridge will not give dbus.String anymore - + #Then the transport type message widget_col.append(('weight',6,urwid.Text(self.getGatewayDesc(param['type'])))) #The buttons - + reg_button = sat_widgets.CustomButton( _("Register"), self.onRegister) reg_button.gateway_jid = JID(gateway) widget_col.append(('fixed',reg_button.getSize(),reg_button)) @@ -74,7 +74,7 @@ unreg_button.gateway_jid = JID(gateway) widget_col.append(('fixed',unreg_button.getSize(),unreg_button)) widget_list.append(urwid.Columns(widget_col,1)) - + def onRegister(self, button): """Called when register button is clicked""" gateway_jid = button.gateway_jid diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/primitivus/notify.py --- a/frontends/src/primitivus/notify.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/primitivus/notify.py Fri Jan 18 17:55:34 2013 +0100 @@ -23,13 +23,13 @@ class Notify: """Used to send notification and detect if we have focus""" - + def __init__(self): #X11 stuff self.display = None self.X11_id = -1 - + try: from Xlib import display as X_display self.display = X_display.Display() @@ -44,7 +44,7 @@ self.freedesktop_int = dbus.Interface(db_object, dbus_interface='org.freedesktop.Notifications') except: self.freedesktop_int = None - + def getFocus(self): if not self.display: @@ -62,15 +62,15 @@ #TODO: check options before sending notifications if self.freedesktop_int: self.sendFDNotification(summ_mess, body_mess) - + def sendFDNotification(self, summ_mess, body_mess=""): """Send notification with the FreeDesktop D-Bus API""" if self.freedesktop_int: - app_name = "Primitivus" + app_name = "Primitivus" replaces_id = 0 app_icon = "" summary = summ_mess - body = body_mess + body = body_mess actions = dbus.Array(signature='s') hints = dbus.Dictionary(signature='sv') expire_timeout = -1 diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/primitivus/primitivus --- a/frontends/src/primitivus/primitivus Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/primitivus/primitivus Fri Jan 18 17:55:34 2013 +0100 @@ -44,18 +44,18 @@ logging.basicConfig(level=logging.CRITICAL, #TODO: configure it to put messages in a log file format='%(message)s') ### - + class ChatList(QuickChatList): """This class manage the list of chat windows""" - + def createChat(self, target): return Chat(target, self.host) class PrimitivusApp(QuickApp): - + def __init__(self): QuickApp.__init__(self) - + ## main loop setup ## self.main_widget = ProfileManager(self) self.loop = urwid.MainLoop(self.main_widget, const_PALETTE, event_loop=urwid.GLibEventLoop(), input_filter=self.inputFilter, unhandled_input=self.keyHandler) @@ -82,7 +82,7 @@ """Change mode if make sens (i.e.: if there is nothing in the editBar""" if not self.editBar.get_edit_text(): self.mode = value - + def debug(self): """convenient method to reset screen and launch p(u)db""" try: @@ -209,9 +209,9 @@ category,item,type = new_menu assert(type=="NORMAL") #TODO: manage other types menu.addMenu(unicode(category), unicode(item), add_menu_cb) - + menu_roller = sat_widgets.MenuRoller([(_('Main menu'),menu)]) - return menu_roller + return menu_roller def __buildMainWidget(self): self.contact_list = ContactList(self, on_click = self.contactSelected, on_change=lambda w: self.redraw()) @@ -257,14 +257,14 @@ completion_data['last_nick'] = nicks[idx] return text[:space+1] + nicks[idx] + (': ' if space < 0 else '') return text - - + + def plug_profile(self, profile_key='@DEFAULT@'): self.loop.widget = self.__buildMainWidget() self.redraw() QuickApp.plug_profile(self, profile_key) - + def removePopUp(self, widget=None): "Remove current pop-up, and if there is other in queue, show it" self.loop.widget = self.main_widget @@ -305,7 +305,7 @@ self.center_part.widget_list[wid_idx] = urwid.Filler(urwid.Text('')) self.center_part.set_focus(0) self.redraw() - + def addProgress (self, id, message): """Follow a SàT progress bar @param id: SàT id of the progression @@ -342,13 +342,13 @@ def newMessage(self, from_jid, to_jid, msg, _type, extra, profile): QuickApp.newMessage(self, from_jid, to_jid, msg, _type, extra, profile) - + if not from_jid in self.contact_list and from_jid.short != self.profiles[profile]['whoami'].short: #XXX: needed to show entities which haven't sent any # presence information and which are not in roster #TODO: put these entities in a "not in roster" list self.contact_list.replace(from_jid) - + if JID(self.contact_list.selected).short != from_jid.short: self.contact_list.putAlert(from_jid) @@ -363,22 +363,22 @@ answer_cb = data[0] answer_data = [data[1]] if data[1] else [] answer_cb(False, *answer_data) - + def showDialog(self, message, title="", type="info", answer_cb = None, answer_data = None): if type == 'info': - popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore + popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore elif type == 'error': - popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore + popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore elif type == 'yes/no': popup = sat_widgets.ConfirmDialog(unicode(message), yes_cb=self._dialogOkCb, yes_value = (answer_cb, answer_data), no_cb=self._dialogCancelCb, no_value = (answer_cb, answer_data)) else: - popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore + popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore error(_('unmanaged dialog type: %s'), type) self.showPopUp(popup) - + def onNotification(self, notBar): """Called when a new notification has been received""" if not isinstance(self.main_widget, sat_widgets.FocusFrame): @@ -401,26 +401,26 @@ if not self.check_profile(profile): return answer_data={} - + def dir_selected_cb(path): dest_path = join(path, data['filename']) - answer_data["dest_path"] = getNewPath(dest_path) - self.addProgress(confirmation_id, dest_path) + answer_data["dest_path"] = getNewPath(dest_path) + self.addProgress(confirmation_id, dest_path) accept_cb(None) def accept_file_transfer_cb(widget): self.removePopUp() - pop_up_widget = FileDialog(dir_selected_cb, refuse_cb, title=_(u"Where do you want to save the file ?"), style=['dir']) + pop_up_widget = FileDialog(dir_selected_cb, refuse_cb, title=_(u"Where do you want to save the file ?"), style=['dir']) self.showPopUp(pop_up_widget) def accept_cb(widget): self.removePopUp() self.bridge.confirmationAnswer(confirmation_id, True, answer_data, profile) - + def refuse_cb(widget): self.removePopUp() self.bridge.confirmationAnswer(confirmation_id, False, answer_data, profile) - + if confirmation_type == "FILE_TRANSFER": pop_up_widget = sat_widgets.ConfirmDialog(_("The contact %(jid)s wants to send you the file %(filename)s\nDo you accept ?") % {'jid':data["from"], 'filename':data["filename"]}, no_cb=refuse_cb, yes_cb=accept_file_transfer_cb) self.showPopUp(pop_up_widget) @@ -432,7 +432,7 @@ def actionResult(self, type, id, data, profile): if not self.check_profile(profile): return - + if not id in self.current_action_ids: debug (_('unknown id, ignoring')) return @@ -455,7 +455,7 @@ ui.show('window') elif type == "ERROR": self.current_action_ids.remove(id) - self.showPopUp(sat_widgets.Alert(_("Error"), unicode(data["message"]), ok_cb=self.removePopUp)) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore + self.showPopUp(sat_widgets.Alert(_("Error"), unicode(data["message"]), ok_cb=self.removePopUp)) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore elif type == "RESULT": self.current_action_ids.remove(id) if self.current_action_ids_cb.has_key(id): @@ -481,7 +481,7 @@ else: message = _("'%s' is an invalid JID !") % room_jid error (message) - self.showPopUp(sat_widgets.Alert(_("Error"), message, ok_cb=self.removePopUp)) + self.showPopUp(sat_widgets.Alert(_("Error"), message, ok_cb=self.removePopUp)) def onAddContact(self, button, edit): self.removePopUp() @@ -511,7 +511,7 @@ def failure(error): self.showPopUp(sat_widgets.Alert(_("Error"), _("Can't get parameters"), ok_cb=self.removePopUp)) self.bridge.getParamsUI(self.profile, callback=success, errback=failure) - + def onExitRequest(self, menu): QuickApp.onExit(self) @@ -541,8 +541,8 @@ self.showPopUp(pop_up_widget) def onAboutRequest(self, menu): - self.showPopUp(sat_widgets.Alert(_("About"), const_APP_NAME + " v" + self.bridge.getVersion(), ok_cb=self.removePopUp)) - + self.showPopUp(sat_widgets.Alert(_("About"), const_APP_NAME + " v" + self.bridge.getVersion(), ok_cb=self.removePopUp)) + #MISC CALLBACKS# def onGatewaysFound(self, data): diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/primitivus/profile_manager.py --- a/frontends/src/primitivus/profile_manager.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/primitivus/profile_manager.py Fri Jan 18 17:55:34 2013 +0100 @@ -31,11 +31,11 @@ #profiles list profiles = self.host.bridge.getProfilesList() profiles.sort() - + #login & password box must be created before list because of onProfileChange self.login_wid = AdvancedEdit(_('Login:'),align='center') self.pass_wid = Password(_('Password:'),align='center') - + self.list_profile = List(profiles, style=['single'], align='center', on_change=self.onProfileChange) #new & delete buttons @@ -96,7 +96,7 @@ self.host.bridge.deleteProfile(profile_name) self.__refillProfiles() self.host.removePopUp() - + def onNewProfile(self, e): pop_up_widget = InputDialog(_("New profile"), _("Please enter a new profile name"), cancel_cb=self.cancelDialog, ok_cb=self.newProfile) self.host.showPopUp(pop_up_widget) @@ -117,7 +117,7 @@ if profile_name: self.host.bridge.asyncGetParamA("JabberID", "Connection", profile_key=profile_name, callback=setJID, errback=self.getParamError) self.host.bridge.asyncGetParamA("Password", "Connection", profile_key=profile_name, callback=setPassword, errback=self.getParamError) - + def onConnectProfile(self, button): profile_name = self.list_profile.getSelectedValue() if not profile_name: @@ -136,7 +136,7 @@ def __old_jidReceived(self, old_jid, profile): self.host.bridge.asyncGetParamA("Password", "Connection", profile_key=profile, callback=lambda old_pass: self.__old_passReceived(old_jid, old_pass, profile), errback=self.getParamError) - + def __old_passReceived(self, old_jid, old_pass, profile): """Check if we have new jid/pass, save them if it is the case, and plug profile""" new_jid = self.login_wid.get_edit_text() @@ -148,7 +148,7 @@ if old_pass != new_pass: self.host.bridge.setParam("Password", new_pass, "Connection", profile) self.host.plug_profile(profile) - + def getParamError(self, ignore): popup = Alert("Error", _("Can't get profile parameter"), ok_cb=self.host.removePopUp) self.host.showPopUp(popup) diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/primitivus/progress.py --- a/frontends/src/primitivus/progress.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/primitivus/progress.py Fri Jan 18 17:55:34 2013 +0100 @@ -55,7 +55,7 @@ #first answer, we must construct the bar self.progress_dict[(progress_id, profile)]['state'] = 'progress' pbar.done = float(data['size']) - + pbar.set_completion(float(data['position'])) self.updateNotBar() else: @@ -93,4 +93,4 @@ nb_bars+=1 av_progress = progress/float(nb_bars) self.host.setProgress(av_progress) - + diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/primitivus/xmlui.py --- a/frontends/src/primitivus/xmlui.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/primitivus/xmlui.py Fri Jan 18 17:55:34 2013 +0100 @@ -44,12 +44,12 @@ pile.widget_list.append(widget) pile.item_types.append(('weight',getattr(self,'weight_'+str(self.idx)))) self.idx = (self.idx + 1) % 2 - + class InvalidXMLUI(Exception): pass class XMLUI(urwid.WidgetWrap): - + def __init__(self, host, xml_data, title = None, options = None, misc = None): self.host = host self.title = title @@ -72,7 +72,7 @@ type = elem.getAttribute("type") value = elem.getAttribute("value") if elem.hasAttribute('value') else u'' if type=="empty": - ctrl = urwid.Text('') + ctrl = urwid.Text('') elif type=="text": try: value = elem.childNodes[0].wholeText @@ -135,10 +135,10 @@ warning(_("Unknown layout, using default one")) self.__parseElems(node, current) elif node.nodeName == "category": - name = node.getAttribute('name') - label = node.getAttribute('label') + name = node.getAttribute('name') + label = node.getAttribute('label') if not name or not isinstance(data,sat_widgets.TabsContainer): - raise InvalidXMLUI + raise InvalidXMLUI if self.type == 'param': self._current_category = name #XXX: awful hack because params need category and we don't keep parent tab_cont = data @@ -150,9 +150,9 @@ raise NotImplementedError def constructUI(self, xml_data): - + ret_wid = urwid.ListBox(urwid.SimpleListWalker([])) - + cat_dom = minidom.parseString(xml_data.encode('utf-8')) top=cat_dom.documentElement self.type = top.getAttribute("type") @@ -166,11 +166,11 @@ self.__parseChilds(ret_wid.body, cat_dom.documentElement) assert ret_wid.body - + if isinstance(ret_wid.body[0],sat_widgets.TabsContainer): ret_wid = ret_wid.body[0] #xxx: awfull hack cause TabsContainer is a BoxWidget, can't be inside a ListBox - - + + if self.type == 'form': buttons = [] buttons.append(urwid.Button(_('Submit'),self.onFormSubmitted)) @@ -195,7 +195,7 @@ - popup - window""" self.__dest = "popup" - decorated = sat_widgets.LabelLine(self, sat_widgets.SurroundedText(self.title or '')) + decorated = sat_widgets.LabelLine(self, sat_widgets.SurroundedText(self.title or '')) if show_type == 'popup': self.host.showPopUp(decorated) elif show_type == 'window': @@ -244,7 +244,7 @@ else: warning (_("The form data is not sent back, the type is not managed properly")) self.host.removePopUp() - + def onFormCancelled(self, button): if self.__dest == 'window': self.host.removeWindow() diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/quick_frontend/quick_app.py --- a/frontends/src/quick_frontend/quick_app.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/quick_frontend/quick_app.py Fri Jan 18 17:55:34 2013 +0100 @@ -37,7 +37,7 @@ self.profiles = {} self.single_profile = single_profile self.check_options() - + ## bridge ## try: self.bridge=DBusBridgeFrontend() @@ -81,11 +81,11 @@ self.bridge.register("quizGameAnswerResult", self.quizGameAnswerResult, "plugin") self.bridge.register("quizGameTimerExpired", self.quizGameTimerExpired, "plugin") self.bridge.register("quizGameTimerRestarted", self.quizGameTimerRestarted, "plugin") - + self.current_action_ids = set() self.current_action_ids_cb = {} self.media_dir = self.bridge.getConfig('','media_dir') - + def check_profile(self, profile): """Tell if the profile is currently followed by the application""" return profile in self.profiles.keys() @@ -93,7 +93,7 @@ def postInit(self): """Must be called after initialization is done, do all automatic task (auto plug profile)""" if self.options.profile: - if not self.bridge.getProfileName(self.options.profile): + if not self.bridge.getProfileName(self.options.profile): error(_("Trying to plug an unknown profile (%s)" % self.options.profile)) else: self.plug_profile(self.options.profile) @@ -116,7 +116,7 @@ def _getParamError(self, ignore): error(_("Can't get profile parameter")) - + def plug_profile(self, profile_key='@DEFAULT@'): """Tell application which profile must be used""" if self.single_profile and self.profiles: @@ -132,11 +132,11 @@ self.profiles[profile]={} if self.single_profile: self.profile = profile - + ###now we get the essential params### self.bridge.asyncGetParamA("JabberID","Connection", profile_key=profile, callback=lambda _jid: self.plug_profile_2(_jid, profile), errback=self._getParamError) - + def plug_profile_2(self, _jid, profile): self.profiles[profile]['whoami'] = JID(_jid) self.bridge.asyncGetParamA("autoconnect","Connection", profile_key=profile, @@ -152,7 +152,7 @@ self.bridge.asyncConnect(profile, callback=lambda: self.plug_profile_5(watched, autoconnect, profile), errback=lambda ignore: error(_('Error during autoconnection'))) else: self.plug_profile_5(watched, autoconnect, profile) - + def plug_profile_5(self, watched, autoconnect, profile): self.profiles[profile]['watched'] = watched.split() #TODO: put this in a plugin @@ -198,7 +198,7 @@ for confirm_id, confirm_type, data in self.bridge.getWaitingConf(profile): self.askConfirmation(confirm_id, confirm_type, data, profile) - + def unplug_profile(self, profile): """Tell the application to not follow anymore the profile""" @@ -224,7 +224,7 @@ debug(_("Disconnected")) self.contact_list.clearContacts() self.setStatusOnline(False) - + def connectionError(self, error_type, profile): """called when something goest wrong with the connection""" if not self.check_profile(profile): @@ -250,15 +250,15 @@ return from_jid = JID(from_jid_s) to_jid = JID(to_jid_s) - + from_me = from_jid.short == self.profiles[profile]['whoami'].short win = to_jid if from_me else from_jid - + if _type != "groupchat" and self.contact_list.getSpecial(win) == "MUC": #we have a private message in a MUC room #XXX: normaly we use bare jid as key, here we need the full jid # so we cheat by replacing the "/" before the resource by - # a "@", so the jid is invalid, + # a "@", so the jid is invalid, new_jid = escapePrivate(win) if from_me: to_jid = new_jid @@ -268,11 +268,11 @@ self.contact_list.add(new_jid) self.newMessage(from_jid, to_jid, msg, _type, extra, profile) - + def newMessage(self, from_jid, to_jid, msg, _type, extra, profile): from_me = from_jid.short == self.profiles[profile]['whoami'].short win = to_jid if from_me else from_jid - + self.current_action_ids = set() self.current_action_ids_cb = {} @@ -291,7 +291,7 @@ assert alert_type in ['INFO','ERROR'] self.showDialog(unicode(msg),unicode(title),alert_type.lower()) - + def setStatusOnline(self, online=True): pass @@ -309,21 +309,21 @@ self.setStatusOnline(False) return - self.contact_list.updatePresence(from_jid, show, priority, statuses) - + self.contact_list.updatePresence(from_jid, show, priority, statuses) + if show != 'unavailable': - + #FIXME: must be moved in a plugin if from_jid.short in self.profiles[profile]['watched'] and not from_jid.short in self.profiles[profile]['onlineContact']: self.showAlert(_("Watched jid [%s] is connected !") % from_jid.short) self.profiles[profile]['onlineContact'].add(from_jid) #FIXME onlineContact is useless with CM, must be removed - + #TODO: vcard data (avatar) if show=="unavailable" and from_jid in self.profiles[profile]['onlineContact']: self.profiles[profile]['onlineContact'].remove(from_jid) - + def roomJoined(self, room_jid, room_nicks, user_nick, profile): """Called when a MUC room is joined""" if not self.check_profile(profile): @@ -374,7 +374,7 @@ if self.chat_wins.has_key(room_jid): self.chat_wins[room_jid].setSubject(subject) debug (_("new subject for room [%(room_jid)s]: %(subject)s") % {'room_jid':room_jid, "subject":subject}) - + def tarotGameStarted(self, room_jid, referee, players, profile): if not self.check_profile(profile): return @@ -382,7 +382,7 @@ if self.chat_wins.has_key(room_jid): self.chat_wins[room_jid].startGame("Tarot", referee, players) debug (_("new Tarot game started by [%(referee)s] in room [%(room_jid)s] with %(players)s") % {'referee':referee, 'room_jid':room_jid, 'players':[str(player) for player in players]}) - + def tarotGameNew(self, room_jid, hand, profile): if not self.check_profile(profile): return @@ -411,8 +411,8 @@ debug (_("My turn to play")) if self.chat_wins.has_key(room_jid): self.chat_wins[room_jid].getGame("Tarot").myTurn() - - def tarotScore(self, room_jid, xml_data, winners, loosers, profile): + + def tarotScore(self, room_jid, xml_data, winners, loosers, profile): """Called when the game is finished and the score are updated""" if not self.check_profile(profile): return @@ -426,14 +426,14 @@ debug (_("Card(s) played (%(player)s): %(cards)s") % {"player":player, "cards":cards}) if self.chat_wins.has_key(room_jid): self.chat_wins[room_jid].getGame("Tarot").cardsPlayed(player, cards) - + def tarotInvalidCards(self, room_jid, phase, played_cards, invalid_cards, profile): if not self.check_profile(profile): return debug (_("Cards played are not valid: %s") % invalid_cards) if self.chat_wins.has_key(room_jid): self.chat_wins[room_jid].getGame("Tarot").invalidCards(phase, played_cards, invalid_cards) - + def quizGameStarted(self, room_jid, referee, players, profile): if not self.check_profile(profile): return @@ -441,7 +441,7 @@ if self.chat_wins.has_key(room_jid): self.chat_wins[room_jid].startGame("Quiz", referee, players) debug (_("new Quiz game started by [%(referee)s] in room [%(room_jid)s] with %(players)s") % {'referee':referee, 'room_jid':room_jid, 'players':[str(player) for player in players]}) - + def quizGameNew(self, room_jid, data, profile): if not self.check_profile(profile): return @@ -477,7 +477,7 @@ return if self.chat_wins.has_key(room_jid): self.chat_wins[room_jid].getGame("Quiz").quizGameAnswerResult(player, good_answer, score) - + def quizGameTimerExpired(self, room_jid, profile): """Called when nobody answered the question in time""" if not self.check_profile(profile): @@ -516,10 +516,10 @@ def showDialog(self, message, title, type="info", answer_cb = None): raise NotImplementedError - + def showAlert(self, message): pass #FIXME - + def paramUpdate(self, name, value, namespace, profile): if not self.check_profile(profile): return @@ -556,7 +556,7 @@ def askConfirmation(self, confirm_id, confirm_type, data, profile): raise NotImplementedError - + def actionResult(self, type, id, data): raise NotImplementedError diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/quick_frontend/quick_card_game.py --- a/frontends/src/quick_frontend/quick_card_game.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/quick_frontend/quick_card_game.py Fri Jan 18 17:55:34 2013 +0100 @@ -25,7 +25,7 @@ class QuickCardGame(): - + def __init__(self, parent, referee, players, player_nick): self._autoplay = None #XXX: use 0 to activate fake play, None else self.parent = parent @@ -58,7 +58,7 @@ self.state = None for pl in self.played: self.played[pl] = None - + def getPlayerLocation(self, nick): """return player location (top,bottom,left or right)""" for location in ['top','left','bottom','right']: @@ -76,7 +76,7 @@ self.cards["coeur"]={} #heart self.cards["carreau"]={} #diamond self.cards["trefle"]={} #club - + def newGame(self, hand): """Start a new game, with given hand""" assert (len(self.hand) == 0) @@ -84,7 +84,7 @@ self.hand.append(self.cards[suit, value]) self.hand.sort() self.state = "init" - + def contratSelected(self, contrat): """Called when the contrat has been choosed @param data: form result""" @@ -94,7 +94,7 @@ """Called when the player as to select his contrat @param xml_data: SàT xml representation of the form""" raise NotImplementedError - + def showCards(self, game_stage, cards, data): """Display cards in the middle of the game (to show for e.g. chien ou poignée)""" self.to_show = [] @@ -111,7 +111,7 @@ self.to_show = [] self.state = "play" self.__fakePlay() - + def __fakePlay(self): """Convenience method for stupid autoplay /!\ don't forgot to comment any interactive dialog for invalid card""" @@ -131,7 +131,7 @@ @param winners: list of winners' nicks @param loosers: list of loosers' nicks""" raise NotImplementedError - + def cardsPlayed(self, player, cards): """A card has been played by player""" if self.to_show: @@ -143,7 +143,7 @@ for suit, value in cards: pl_cards.append(self.cards[suit, value]) self.played[player] = pl_cards[0] - + def invalidCards(self, phase, played_cards, invalid_cards): """Invalid cards have been played @param phase: phase of the game @@ -156,10 +156,10 @@ self.state = "ecart" else: error ('INTERNAL ERROR: unmanaged game phase') - + for suit, value in played_cards: self.hand.append(self.cards[suit, value]) - + self.hand.sort() self.__fakePlay() diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/quick_frontend/quick_chat.py --- a/frontends/src/quick_frontend/quick_chat.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/quick_frontend/quick_chat.py Fri Jan 18 17:55:34 2013 +0100 @@ -25,7 +25,7 @@ class QuickChat(): - + def __init__(self, target, host, type='one2one'): self.target = target self.host = host @@ -49,7 +49,7 @@ error (_("[INTERNAL] trying to set presents nicks for a non group chat window")) raise Exception("INTERNAL ERROR") #TODO: raise proper Exception here self.occupants.update(nicks) - + def replaceUser(self, nick, show_info=True): """Add user if it is not in the group list""" debug (_("Replacing user %s") % nick) @@ -77,7 +77,7 @@ def getUserNick(self): return unicode(self.nick) - + def changeUserNick(self, old_nick, new_nick): """Change nick of a user in group list""" debug(_("Changing nick of user %(old_nick)s to %(new_nick)s") % {"old_nick": old_nick, "new_nick": new_nick}) @@ -99,13 +99,13 @@ """Print the initial history""" debug (_("now we print history")) def onHistory(history): - for line in history: + for line in history: timestamp, from_jid, to_jid, message, _type = line if ((self.type == 'group' and _type != 'groupchat') or (self.type == 'one2one' and _type == 'groupchat')): continue self.printMessage(JID(from_jid), message, profile, timestamp) - + def onHistoryError(err): error (_("Can't get history")) @@ -123,11 +123,11 @@ if jid.startswith(const_PRIVATE_PREFIX) or unescaped.short == jid.short: return unescaped.resource return jid.resource if self.type == "group" else (self.host.contact_list.getCache(jid,'nick') or self.host.contact_list.getCache(jid,'name') or jid.node) - + def printMessage(self, from_jid, msg, profile, timestamp = ''): """Print message in chat window. Must be implemented by child class""" jid=JID(from_jid) - nick = self._get_nick(jid) + nick = self._get_nick(jid) mymess = (jid.resource == self.nick) if self.type == "group" else (jid.short == self.host.profiles[profile]['whoami'].short) #mymess = True if message comes from local user if msg.startswith('/me '): self.printInfo('* %s %s' % (nick, msg[4:]),type='me', timestamp=timestamp) @@ -143,12 +143,12 @@ """ raise NotImplementedError - + def startGame(self, game_type, referee, players): """Configure the chat window to start a game""" #No need to raise an error as game are not mandatory warning(_('startGame is not implemented in this frontend')) - + def getGame(self, game_type): """Return class managing the game type""" #No need to raise an error as game are not mandatory diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/quick_frontend/quick_chat_list.py --- a/frontends/src/quick_frontend/quick_chat_list.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/quick_frontend/quick_chat_list.py Fri Jan 18 17:55:34 2013 +0100 @@ -25,7 +25,7 @@ class QuickChatList(dict): """This class is used to manage the list of chat windows. It act as a dict, but create a chat window when the name is found for the first time.""" - + def __init__(self, host): dict.__init__(self) self.host = host diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/quick_frontend/quick_contact_list.py --- a/frontends/src/quick_frontend/quick_contact_list.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/quick_frontend/quick_contact_list.py Fri Jan 18 17:55:34 2013 +0100 @@ -49,16 +49,16 @@ def __contains__(self, jid): raise NotImplementedError - + def clearContacts(self): """Clear all the contact list""" self.specials.clear() - + def replace(self, jid, groups=None, attributes=None): """add a contact to the list if doesn't exist, else update it""" if attributes and 'name' in attributes: self.setCache(jid, 'name', attributes['name']) - + def remove(self, jid): """remove a contact from the list""" try: diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/quick_frontend/quick_contact_management.py --- a/frontends/src/quick_frontend/quick_contact_management.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/quick_frontend/quick_contact_management.py Fri Jan 18 17:55:34 2013 +0100 @@ -47,7 +47,7 @@ if entity.resource in self.__contactlist[entity.short]['resources']: self.__contactlist[entity.short]['resources'].remove(entity.resource) self.__contactlist[entity.short]['resources'].append(entity.resource) - + def getContFromGroup(self, group): """Return all contacts which are in given group""" result = [] @@ -71,7 +71,7 @@ else: debug(_('Trying to get attribute for an unknown contact')) return None - + def isConnected(self, entity): """Tell if the contact is online""" return self.__contactlist.has_key(entity.short) @@ -101,4 +101,4 @@ def get_full(self, entity): return entity.short+'/'+self.__contactlist[entity.short]['resources'][-1] - + diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/quick_frontend/quick_gateways.py --- a/frontends/src/quick_frontend/quick_gateways.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/quick_frontend/quick_gateways.py Fri Jan 18 17:55:34 2013 +0100 @@ -24,7 +24,7 @@ class QuickGatewaysManager(): - + def __init__(self, host, gateways, title=_("Gateways manager"), server=None): self.WARNING_MSG = _(u"""Be careful ! Gateways allow you to use an external IM (legacy IM), so you can see your contact as jabber contacts. But when you do this, all your messages go throught the external legacy IM server, it is a huge privacy issue (i.e.: all your messages throught the gateway can be monitored, recorded, analyzed by the external server, most of time a private company).""") diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/card_game.py --- a/frontends/src/wix/card_game.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/card_game.py Fri Jan 18 17:55:34 2013 +0100 @@ -49,7 +49,7 @@ def draw(self, dc, x, y): """Draw the card on the device context @param dc: device context - @param x: abscissa + @param x: abscissa @param y: ordinate""" dc.DrawBitmap(self.bitmap, x, y, True) @@ -152,7 +152,7 @@ def onPaint(self, event): dc = wx.PaintDC(self) - + #We print the names to know who play where TODO: print avatars when available max_x, max_y = self.GetSize() border = 10 #border between nick and end of panel @@ -214,7 +214,7 @@ def onMouseClick(self, event): print "mouse click:",event.GetPosition() pos_x,pos_y = event.GetPosition() - + if self.state == "chien": self.to_show = [] self.state = "wait" diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/chat.py --- a/frontends/src/wix/chat.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/chat.py Fri Jan 18 17:55:34 2013 +0100 @@ -41,11 +41,11 @@ def __init__(self, target, host, type='one2one'): wx.Frame.__init__(self, None, title=target, pos=(0,0), size=(400,200)) - QuickChat.__init__(self, target, host, type) + QuickChat.__init__(self, target, host, type) self.sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.sizer) - + self.splitter = wx.SplitterWindow(self, -1) self.sizer.Add(self.splitter, 1, flag = wx.EXPAND) @@ -60,7 +60,7 @@ self.conv_panel.SetSizer(self.conv_panel.sizer) self.splitter.Initialize(self.conv_panel) self.SetMenuBar(wx.MenuBar()) - + #events self.Bind(wx.EVT_CLOSE, self.onClose, self) self.Bind(wx.EVT_TEXT_ENTER, self.onEnterPressed, self.textBox) @@ -69,14 +69,14 @@ self.font={} self.font["points"] = self.chatWindow.GetFont().GetPointSize() self.font["family"] = self.chatWindow.GetFont().GetFamily() - - + + #misc self.day_change = time.strptime(time.strftime("%a %b %d 00:00:00 %Y")) #struct_time of day changing time self.setType(self.type) self.textBox.SetFocus() self.Hide() #We hide because of the show toggle - + def __createPresents(self): """Create a list of present people in a group chat""" self.present_panel = wx.Panel(self.splitter) @@ -108,7 +108,7 @@ self.__eraseMenus() self.__createMenus_O2O() self.historyPrint(profile=self.host.profile) - + def startGame(self, game_type, referee, players): """Configure the chat window to start a game""" if game_type=="Tarot": @@ -130,9 +130,9 @@ """Return class managing the game type""" #TODO: check that the game is launched, and manage errors if game_type=="Tarot": - return self.tarot_panel + return self.tarot_panel elif game_type=="Quiz": - return self.quiz_panel + return self.quiz_panel def setPresents(self, nicks): """Set the users presents in the contact list for a group chat @@ -141,7 +141,7 @@ QuickChat.setPresents(self, nicks) for nick in nicks: self.present_panel.presents.replace(nick) - + def replaceUser(self, nick, show_info=True): """Add user if it is not in the group list""" debug (_("Replacing user %s") % nick) @@ -166,7 +166,7 @@ menuBar = self.GetMenuBar() for i in range(menuBar.GetMenuCount()): menuBar.Remove(i) - + def __createMenus_O2O(self): """create menu bar for one 2 one chat""" info("Creating menus") @@ -190,7 +190,7 @@ #events wx.EVT_MENU(self, idTAROT, self.onStartTarot) - + def __del__(self): wx.Frame.__del__(self) @@ -202,7 +202,7 @@ def onEnterPressed(self, event): """Behaviour when enter pressed in send line.""" self.host.sendMessage(self.target.short if self.type=='group' else self.target, - event.GetString(), + event.GetString(), mess_type = "groupchat" if self.type=='group' else "chat", profile_key=self.host.profile) self.textBox.Clear() @@ -236,7 +236,7 @@ self.chatWindow.AppendText("%s\n" % msg) if not mymess: self.__blink() - + def printInfo(self, msg, type='normal'): """Print general info @param msg: message to print @@ -265,7 +265,7 @@ else: full_jid = self.target id = self.host.bridge.sendFile(full_jid, filename, {}, self.host.profile) - self.host.waitProgress(id, _("File Transfer"), _("Copying %s") % os.path.basename(filename), self.host.profile) + self.host.waitProgress(id, _("File Transfer"), _("Copying %s") % os.path.basename(filename), self.host.profile) def onStartTarot(self, e): debug (_("Starting Tarot game")) diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/contact_list.py --- a/frontends/src/wix/contact_list.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/contact_list.py Fri Jan 18 17:55:34 2013 +0100 @@ -52,7 +52,7 @@ self.empty_avatar = join(host.media_dir, 'misc/empty_avatar') self.Bind(wx.EVT_LISTBOX, self.onSelected) self.Bind(wx.EVT_LISTBOX_DCLICK, self.onActivated) - + def __contains__(self, jid): return bool(self.__find_idx(jid)) @@ -107,7 +107,7 @@ def __presentItemDefault(self, contact): """Make a basic presentation of string contacts in the list.""" return contact - + def __presentItemJID(self, jid): """Make a nice presentation of the contact in the list for JID contacts.""" name = self.getCache(jid,'name') @@ -116,7 +116,7 @@ if _show == None or _show == 'unavailable': return None show = filter(lambda x : x[0] == _show, const_STATUS)[0] - + #show[0]==shortcut #show[1]==human readable #show[2]==color (or None) @@ -126,7 +126,7 @@ #WxPython segfault, and it doesn't without nothing. I couldn't reproduce the case with a basic test script, so it need further investigation before reporting it #to WxPython dev. Anyway, the program crash with a segfault, not a python exception, so there is definitely something wrong with WxPython. #The case seems to happen when SimpleHtmlListBox parse the HTML with the tag - + html = """
@@ -140,7 +140,7 @@ """ % (avatar, escape(nick or name or jid.node or jid.short), show_html, - escape(status)) + escape(status)) return html @@ -163,7 +163,7 @@ gp_idx = self.Append(self.__presentGroup(group), Group(group)) else: gp_idx = indexes[0] - + _present = self.__presentItem(contact) if _present: self.Insert(_present, gp_idx+1, contact) @@ -199,7 +199,7 @@ event.Skip(False) else: event.Skip() - + def onActivated(self, event): """Called when a contact is clicked or activated with keyboard.""" data = self.getSelection() diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/gateways.py --- a/frontends/src/wix/gateways.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/gateways.py Fri Jan 18 17:55:34 2013 +0100 @@ -36,7 +36,7 @@ if server: self.SetTitle(title+" (%s)" % server) - + #Fonts self.normal_font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.NORMAL) self.bold_font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD) @@ -61,10 +61,10 @@ self.sizer.Add(self.panel, 1, flag=wx.EXPAND) self.SetSizer(self.sizer) self.SetAutoLayout(True) - + #events self.Bind(wx.EVT_CLOSE, self.onClose, self) - + self.MakeModal() self.panel.sizer.Add(wx.Window(self.panel, -1)) title_name = wx.StaticText(self.panel, -1, "Name") @@ -75,7 +75,7 @@ self.panel.sizer.Add(title_type) self.panel.sizer.Add(wx.Window(self.panel, -1)) self.panel.sizer.Add(wx.Window(self.panel, -1)) - + for gateway in gateways: self.addGateway(gateway, gateways[gateway]) @@ -94,20 +94,20 @@ self.ext_server_panel.sizer.Add(ext_server_label) self.ext_server_panel.sizer.Add(self.ext_server_text, 1, flag=wx.EXPAND) self.ext_server_panel.sizer.Add(ext_server_button) - + #self.panel.sizer.Fit(self) self.sizer.Fit(self) - + self.Show() def browseExternalServer(self, event): """Open the gateway manager on given server""" server = self.ext_server_text.GetValue() - debug(_("Opening gateways manager on [%s]") % server) + debug(_("Opening gateways manager on [%s]") % server) id = self.host.bridge.findGateways(server, self.host.profile) self.host.current_action_ids.add(id) self.host.current_action_ids_cb[id] = self.host.onGatewaysFound - self.MakeModal(False) + self.MakeModal(False) self.Destroy() @@ -121,7 +121,7 @@ label=wx.StaticText(self.panel, -1, param['name']) label.SetFont(self.normal_font) - + #Then the transport type message type_label_txt = self.getGatewayDesc(param['type']) @@ -134,7 +134,7 @@ gateway_jid = event.GetEventObject().gateway_jid id = self.host.bridge.in_band_register(gateway_jid, self.host.profile) self.host.current_action_ids.add(id) - self.MakeModal(False) + self.MakeModal(False) self.Destroy() def unregister_cb(event): @@ -142,9 +142,9 @@ gateway_jid = event.GetEventObject().gateway_jid id = self.host.bridge.gatewayRegister("CANCEL",gateway_jid, None, self.host.profile) self.host.current_action_ids.add(id) - self.MakeModal(False) + self.MakeModal(False) self.Destroy() - + reg_button = wx.Button(self.panel, -1, _("Register"), size=wx.Size(-1, 8)) reg_button.SetFont(self.button_font) reg_button.gateway_jid = JID(gateway) @@ -153,7 +153,7 @@ unreg_button.SetFont(self.button_font) unreg_button.gateway_jid = JID(gateway) self.panel.Bind(wx.EVT_BUTTON, unregister_cb, unreg_button) - + self.panel.sizer.Add(im_icon) self.panel.sizer.Add(label) self.panel.sizer.Add(type_label) diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/main_window.py --- a/frontends/src/wix/main_window.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/main_window.py Fri Jan 18 17:55:34 2013 +0100 @@ -48,10 +48,10 @@ class ChatList(QuickChatList): """This class manage the list of chat windows""" - + def createChat(self, target): return Chat(target, self.host) - + class MainWindow(wx.Frame, QuickApp): """main app window""" @@ -62,13 +62,13 @@ #sizer self.sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.sizer) - + #Frame elements self.contact_list = ContactList(self, self) self.contact_list.registerActivatedCB(self.onContactActivated) self.contact_list.Hide() self.sizer.Add(self.contact_list, 1, flag=wx.EXPAND) - + self.chat_wins=ChatList(self) self.CreateStatusBar() @@ -80,12 +80,12 @@ self.tools.AddSeparator() self.statusTxt=wx.TextCtrl(self.tools, -1, style = wx.TE_PROCESS_ENTER) self.tools.AddControl(self.statusTxt) - self.Bind(wx.EVT_COMBOBOX, self.onStatusChange, self.statusBox) + self.Bind(wx.EVT_COMBOBOX, self.onStatusChange, self.statusBox) self.Bind(wx.EVT_TEXT_ENTER, self.onStatusChange, self.statusTxt) self.tools.Disable() - - + + #tray icon ticon = wx.Icon(os.path.join(self.media_dir, 'icons/crystal/tray_icon.xpm'), wx.BITMAP_TYPE_XPM) self.tray_icon = wx.TaskBarIcon() @@ -95,16 +95,16 @@ #events self.Bind(wx.EVT_CLOSE, self.onClose, self) - + #menus self.createMenus() for i in range(self.menuBar.GetMenuCount()): self.menuBar.EnableTop(i, False) - + #profile panel - self.profile_pan = ProfileManager(self) + self.profile_pan = ProfileManager(self) self.sizer.Add(self.profile_pan, 1, flag=wx.EXPAND) - + self.postInit() self.Show() @@ -195,7 +195,7 @@ popup.SetPosition((x,0)) popup.Show() wx.CallLater(5000,popup.Destroy) - + def showDialog(self, message, title="", type="info", answer_cb = None, answer_data = None): if type == 'info': flags = wx.OK | wx.ICON_INFORMATION @@ -212,7 +212,7 @@ if answer_cb: data = [answer_data] if answer_data else [] answer_cb(True if (answer == wx.ID_YES or answer == wx.ID_OK) else False, *data) - + def setStatusOnline(self, online=True): """enable/disable controls, must be called when local user online status change""" if online: @@ -241,12 +241,12 @@ if filename: answer_data["dest_path"] = filename self.bridge.confirmationAnswer(confirmation_id, True, answer_data, profile) - self.waitProgress(confirmation_id, _("File Transfer"), _("Copying %s") % os.path.basename(filename), profile) + self.waitProgress(confirmation_id, _("File Transfer"), _("Copying %s") % os.path.basename(filename), profile) else: answer = wx.ID_NO if answer==wx.ID_NO: self.bridge.confirmationAnswer(confirmation_id, False, answer_data, profile) - + dlg.Destroy() elif confirmation_type == "YES/NO": @@ -323,21 +323,21 @@ if not self.pbar: #first answer, we must construct the bar self.pbar = wx.ProgressDialog(title, message, float(data['size']), None, - wx.PD_SMOOTH | wx.PD_ELAPSED_TIME | wx.PD_ESTIMATED_TIME | wx.PD_REMAINING_TIME) + wx.PD_SMOOTH | wx.PD_ELAPSED_TIME | wx.PD_ESTIMATED_TIME | wx.PD_REMAINING_TIME) self.pbar.finish_value = float(data['size']) - + self.pbar.Update(int(data['position'])) elif self.pbar: self.pbar.Update(self.pbar.finish_value) return wx.CallLater(10, self.progressCB, progress_id, title, message, profile) - + def waitProgress (self, progress_id, title, message, profile): self.pbar = None wx.CallLater(10, self.progressCB, progress_id, title, message, profile) - - + + ### events ### @@ -388,7 +388,7 @@ def onExit(self, e): self.Close() - + def onAddContact(self, e): debug(_("Add contact request")) dlg = wx.TextEntryDialog( @@ -439,15 +439,15 @@ dlg.ShowModal() dlg.Destroy() return - _id = self.bridge.getCard(target.short, profile_key=self.profile) + _id = self.bridge.getCard(target.short, profile_key=self.profile) self.current_action_ids.add(_id) self.current_action_ids_cb[_id] = self.onProfileReceived - + def onProfileReceived(self, data): """Called when a profile is received""" debug (_('Profile received: [%s]') % data) profile=Profile(self, data) - + def onJoinRoom(self, e): warning('FIXME: temporary menu, must be improved') #TODO: a proper MUC room joining dialog with nickname etc @@ -473,7 +473,7 @@ target = data['__private__']['target'] del data['__private__'] gatewayManager = GatewaysManager(self, data, server=target) - + def onClose(self, e): QuickApp.onExit(self) info(_("Exiting...")) @@ -489,4 +489,4 @@ self.Show() self.Raise() e.Skip() - + diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/param.py --- a/frontends/src/wix/param.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/param.py Fri Jan 18 17:55:34 2013 +0100 @@ -42,15 +42,15 @@ self.sizer.Add(self.notebook, 1, flag=wx.EXPAND) self.SetSizer(self.sizer) self.SetAutoLayout(True) - + #events self.Bind(wx.EVT_CLOSE, self.onClose, self) - + self.MakeModal() for category in self.host.bridge.getParamsCategories(): self.addCategory(category) - + self.Show() def addCategory(self, category): @@ -62,7 +62,7 @@ def gotParams(result): cat_dom = minidom.parseString(result.encode('utf-8')) - + for param in cat_dom.documentElement.getElementsByTagName("param"): name = param.getAttribute("name") label = param.getAttribute("label") @@ -109,20 +109,20 @@ def onTextChanged(self, event): """Called when a string paramater is modified""" self.modified[event.GetEventObject().param_id]=event.GetString() - + ### FIXME # Some hacks for better presentation, should be generic # FIXME ### if event.GetEventObject().param_id == ('JabberID', 'Connection'): domain = JID(event.GetString()).domain self.ctl_list[('Server', 'Connection')].SetValue(domain) - self.modified[('Server', 'Connection')] = domain + self.modified[('Server', 'Connection')] = domain event.Skip() - + def onCheckBoxClicked(self, event): """Called when a bool paramater is modified""" self.modified[event.GetEventObject().param_id]="true" if event.GetEventObject().GetValue() else "false" event.Skip() - + def onButtonClicked(self, event): """Called when a button paramater is modified""" self.__save_parameters() diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/profile.py --- a/frontends/src/wix/profile.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/profile.py Fri Jan 18 17:55:34 2013 +0100 @@ -47,24 +47,24 @@ self.sizer.Add(self.notebook, 1, flag=wx.EXPAND) self.SetSizer(self.sizer) self.SetAutoLayout(True) - + #events self.Bind(wx.EVT_CLOSE, self.onClose, self) - + self.MakeModal() self.showData(data) self.Show() def showData(self, data): flags = wx.TE_READONLY - + #General tab generaltab = wx.Panel(self.notebook) sizer = wx.FlexGridSizer(cols=2) sizer.AddGrowableCol(1) generaltab.SetSizer(sizer) generaltab.SetAutoLayout(True) - for field in ['fullname','nick', 'birthday', 'phone', 'website', 'email']: + for field in ['fullname','nick', 'birthday', 'phone', 'website', 'email']: value = data[field] if data.has_key(field) else '' label=wx.StaticText(generaltab, -1, self.name_dict[field]+": ") sizer.Add(label) @@ -80,7 +80,7 @@ sizer.Add(self.ctl_list['avatar'], 0) - + self.notebook.AddPage(generaltab, _("General")) diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/profile_manager.py --- a/frontends/src/wix/profile_manager.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/profile_manager.py Fri Jan 18 17:55:34 2013 +0100 @@ -56,7 +56,7 @@ self.sizer.Add(button_panel, flag=wx.CENTER) self.Bind(wx.EVT_BUTTON, self.onNewProfile, button_new) self.Bind(wx.EVT_BUTTON, self.onDeleteProfile, button_del) - + login_box = wx.StaticBox(self, -1, _("Login")) self.login_sizer = wx.StaticBoxSizer(login_box, wx.VERTICAL) self.sizer.Add(self.login_sizer, 1, wx.EXPAND | wx.ALL) @@ -66,13 +66,13 @@ self.login_pass = wx.TextCtrl(self, -1, style = wx.TE_PASSWORD) self.login_sizer.Add(wx.StaticText(self, -1, _("Password:")), 0, flag=wx.ALIGN_CENTER) self.login_sizer.Add(self.login_pass, flag=wx.EXPAND) - + loggin_button = wx.Button(self, -1, _("Connect")) self.Bind(wx.EVT_BUTTON, self.onConnectButton, loggin_button) self.login_sizer.Add(loggin_button, flag=wx.ALIGN_CENTER) self.sizer.Add(wx.Window(self, -1), 1) - + #Now we can set the default value self.__setDefault() @@ -82,7 +82,7 @@ if profile_default: self.profile_name.SetValue(profile_default) self.onProfileChange(None) - + def __refillProfiles(self): """Update profiles with current names. Must be called after a profile change""" self.profile_name.Clear() @@ -90,8 +90,8 @@ profiles.sort() for profile in profiles: self.profile_name.Append(profile) - - + + def onNewProfile(self, event): dlg = wx.TextEntryDialog(self, _("Please enter the new profile name"), _("New profile"), style = wx.OK | wx.CANCEL) if dlg.ShowModal() == wx.ID_OK: @@ -104,7 +104,7 @@ self.__refillProfiles() self.profile_name.SetValue(name) dlg.Destroy() - + def onDeleteProfile(self, event): name = self.profile_name.GetValue() if not name: @@ -136,12 +136,12 @@ return profile = self.host.bridge.getProfileName(name) assert(profile) - + self.host.bridge.asyncGetParamA("JabberID", "Connection", profile_key=profile, callback=lambda old_jid: self.__old_jidReceived(old_jid, profile), errback=self.getParamError) - + def __old_jidReceived(self, old_jid, profile): self.host.bridge.asyncGetParamA("Password", "Connection", profile_key=profile, callback=lambda old_pass: self.__old_passReceived(old_jid, old_pass, profile), errback=self.getParamError) - + def __old_passReceived(self, old_jid, old_pass, profile): new_jid = self.login_jid.GetValue() new_pass = self.login_pass.GetValue() @@ -153,7 +153,7 @@ debug(_('Saving new password')) self.host.bridge.setParam("Password", new_pass, "Connection", profile) self.host.plug_profile(profile) - - + + def getParamError(self, ignore): wx.MessageDialog(self, _("Can't get profile parameter"), _("Profile error"), wx.ICON_ERROR).ShowModal() diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/quiz_game.py --- a/frontends/src/wix/quiz_game.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/quiz_game.py Fri Jan 18 17:55:34 2013 +0100 @@ -49,17 +49,17 @@ def __cmp__(self, other): return self.zindex.__cmp__(other.zindex) - + def draw(self, dc, x=None, y=None): """Draw the card on the device context @param dc: device context - @param x: abscissa + @param x: abscissa @param y: ordinate""" dc.DrawBitmap(self.bitmap, x or self.x, y or self.y, self.transparent) class BaseWindow(wx.Window): """This is the panel where the game is drawed, under the other widgets""" - + def __init__(self, parent): wx.Window.__init__(self, parent, pos=(0,0), size=(WIDTH, HEIGHT)) self.parent = parent @@ -98,7 +98,7 @@ for i in range(4): answer = self.parent.players_data[i]["answer"] score = self.parent.players_data[i]["score"] - if answer == None: + if answer == None: device_context.DrawText("%d" % score, 100 + i*184, 355) else: device_context.DrawBitmap(self.right_image if answer else self.wrong_image, 39+i*184, 348, True) @@ -118,14 +118,14 @@ if left: #we now draw the timer angle = ((-2*pi)*((total-left)/total) + (pi/2)) - x = center_x + radius * cos(angle) + x = center_x + radius * cos(angle) y = center_y - radius * sin(angle) device_context.DrawArc(center_x, center_y-radius, x, y, center_x, center_y) def onPaint(self, event): dc = wx.PaintDC(self) self.fullPaint(dc) - + class QuizPanel(wx.Panel): @@ -156,7 +156,7 @@ self.answer.Bind(wx.EVT_TEXT_ENTER, self.answered) self.parent.host.bridge.quizGameReady(player_nick, referee, profile_key = self.parent.host.profile) self.state = None - + def answered(self, event): """Called when the player gave an answer in the box""" self.last_answer = self.answer.GetValue() @@ -184,7 +184,7 @@ self.time_limit = self.time_origin + timer self.time_pause = None self.__timer_refresh() - + def __timer_refresh(self): self.Refresh() if self.time_left: @@ -203,14 +203,14 @@ self.startTimer(timer) self.last_answer = None self.answer.Clear() - + def quizGamePlayerBuzzed(self, player, pause): """Called when the player pushed the buzzer @param player: player who pushed the buzzer @param pause: should we stop the timer ?""" if pause: self.time_pause = time() - + def quizGamePlayerSays(self, player, text, delay): """Called when the player says something @param player: who is talking diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/wix --- a/frontends/src/wix/wix Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/wix Fri Jan 18 17:55:34 2013 +0100 @@ -25,7 +25,7 @@ import pdb import logging from logging import debug, info, error -from sat_frontends.wix.main_window import MainWindow +from sat_frontends.wix.main_window import MainWindow ### logging configuration FIXME: put this elsewhere ### logging.basicConfig(level=logging.DEBUG, diff -r 6a718ede8be1 -r 952322b1d490 frontends/src/wix/xmlui.py --- a/frontends/src/wix/xmlui.py Fri Jan 18 17:55:27 2013 +0100 +++ b/frontends/src/wix/xmlui.py Fri Jan 18 17:55:34 2013 +0100 @@ -43,11 +43,11 @@ self.sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.sizer) self.SetAutoLayout(True) - + #events if not 'NO_CANCEL' in self.options: self.Bind(wx.EVT_CLOSE, self.onClose, self) - + self.MakeModal() self.constructUI(xml_data) @@ -83,7 +83,7 @@ elif type=="password": ctrl = wx.TextCtrl(parent, -1, value, style=wx.TE_PASSWORD) self.ctrl_list[name] = ({'type':type, 'control':ctrl}) - _proportion = 1 + _proportion = 1 elif type=="textbox": ctrl = wx.TextCtrl(parent, -1, value, style=wx.TE_MULTILINE) self.ctrl_list[name] = ({'type':type, 'control':ctrl}) @@ -142,12 +142,12 @@ if parent: parent.sizer.Add(current, _proportion, flag=wx.EXPAND) elif node.nodeName == "category": - name = node.getAttribute('name') - label = node.getAttribute('label') + name = node.getAttribute('name') + label = node.getAttribute('label') if not node.nodeName in wanted or not name or not isinstance(parent,wx.Notebook): raise Exception("Invalid XMLUI") #TODO: make a custom exception notebook = parent - tab_panel = wx.Panel(notebook, -1) + tab_panel = wx.Panel(notebook, -1) tab_panel.sizer = wx.BoxSizer(wx.VERTICAL) tab_panel.SetSizer(tab_panel.sizer) notebook.AddPage(tab_panel, label or name) @@ -162,7 +162,7 @@ def constructUI(self, xml_data): panel=wx.Panel(self) panel.sizer = wx.BoxSizer(wx.VERTICAL) - + cat_dom = minidom.parseString(xml_data.encode('utf-8')) top= cat_dom.documentElement self.type = top.getAttribute("type") @@ -230,13 +230,13 @@ warning (_("The form data is not sent back, the type is not managed properly")) self.MakeModal(False) self.Destroy() - + def onFormCancelled(self, event): """Called when cancel button is clicked""" debug(_("Cancelling form")) self.MakeModal(False) self.Close() - + def onClose(self, event): """Close event: we have to send the form.""" debug(_("close")) diff -r 6a718ede8be1 -r 952322b1d490 src/bridge/DBus.py --- a/src/bridge/DBus.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/bridge/DBus.py Fri Jan 18 17:55:34 2013 +0100 @@ -94,7 +94,7 @@ raise DeferredNotAsync return result - ### signals ### + ### signals ### @dbus.service.signal(const_INT_PREFIX+const_PLUGIN_SUFFIX, signature='') @@ -175,8 +175,8 @@ pass - ### methods ### - + ### methods ### + @dbus.service.method(const_INT_PREFIX+const_CORE_SUFFIX, in_signature='ss', out_signature='', async_callbacks=None) @@ -411,11 +411,11 @@ def updateContact(self, entity_jid, name, groups, profile_key="@DEFAULT@"): return self._callback("updateContact", unicode(entity_jid), unicode(name), groups, unicode(profile_key)) - + def __attributes(self, in_sign): """Return arguments to user given a in_sign @param in_sign: in_sign in the short form (using s,a,i,b etc) - @return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")""" + @return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")""" i=0 idx=0 attr=[] @@ -454,19 +454,19 @@ _arguments = inspect_args.args _defaults = list(inspect_args.defaults or []) - + if inspect.ismethod(method): #if we have a method, we don't want the first argument (usually 'self') del(_arguments[0]) #first arguments are for the _callback method arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback','errback=errback']) if async else _arguments)) - + if async: _arguments.extend(['callback','errback']) _defaults.extend([None, None]) - - + + #now we create a second list with default values for i in range(1, len(_defaults)+1): _arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i])) @@ -484,7 +484,7 @@ function = getattr(self, name) func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface] func_table[function.__name__] = function #Needed for introspection - + def addSignal(self, name, int_suffix, signature, doc={}): """Dynamically add a signal to Dbus Bridge""" attributes = ', '.join(self.__attributes(signature)) diff -r 6a718ede8be1 -r 952322b1d490 src/bridge/bridge.py --- a/src/bridge/bridge.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/bridge/bridge.py Fri Jan 18 17:55:34 2013 +0100 @@ -26,7 +26,7 @@ info ("Bridge initialization") ##signals - def newContact(self, contact): + def newContact(self, contact): raise NotImplementedError def newMessage(self, from_jid, msg, type='chat'): @@ -45,7 +45,7 @@ def getContacts(self): raise NotImplementedError - + def getPresenceStatus(self): raise NotImplementedError @@ -57,12 +57,12 @@ def setParam(self, name, value, namespace): raise NotImplementedError - + def getParam(self, name, namespace): raise NotImplementedError def getParams(self, namespace): raise NotImplementedError - + def getHistory(self, from_jid, to_jid, size): raise NotImplementedError diff -r 6a718ede8be1 -r 952322b1d490 src/bridge/bridge_constructor/bridge_contructor.py --- a/src/bridge/bridge_constructor/bridge_contructor.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/bridge/bridge_constructor/bridge_contructor.py Fri Jan 18 17:55:34 2013 +0100 @@ -53,11 +53,11 @@ class ParseError(Exception): - #Used when the signature parsing is going wrong (invalid signature ?) + #Used when the signature parsing is going wrong (invalid signature ?) pass class Constructor: - + def __init__(self, bridge_template, options): self.bridge_template = bridge_template self.options = options @@ -74,14 +74,14 @@ value = None function[option] = value return function - + def getDefault(self, name): """Return default values of a function in a dict @param name: Name of the function to get @return: dict, each key is the integer param number (no key if no default value)""" default_dict={} def_re = re.compile(r"param_(\d+)_default") - + for option in self.bridge_template.options(name): match = def_re.match(option) if match: @@ -90,7 +90,7 @@ except ValueError: raise ParseError("Invalid value [%s] for parameter number" % match.group(1)) default_dict[idx] = self.bridge_template.get(name, option) - + return default_dict def getFlags(self, name): @@ -102,7 +102,7 @@ if option in FLAGS: flags.append(option) return flags - + def getArgumentsDoc(self, name): """Return documentation of arguments @param name: Name of the function to get @@ -175,10 +175,10 @@ @param name: dictionary of arguments name like given by getArguments @param default: dictionary of default values, like given by getDefault @param unicode_protect: activate unicode protection on strings (return strings as unicode(str)) - @return: list of arguments that correspond to a signature (e.g.: "sss" return "arg1, arg2, arg3")""" + @return: list of arguments that correspond to a signature (e.g.: "sss" return "arg1, arg2, arg3")""" idx=0 attr_string=[] - + for arg in self.argumentsParser(signature): attr_string.append(("unicode(%(name)s)%(default)s" if (unicode_protect and arg=='s') else "%(name)s%(default)s") % { 'name':name[idx][0] if (name and name.has_key(idx)) else "arg_%i" % idx, @@ -186,7 +186,7 @@ }) #give arg_1, arg2, etc or name1, name2=default, etc. \ #give unicode(arg_1), unicode(arg_2), etc. if unicode_protect is set and arg is a string idx+=1 - + return ", ".join(attr_string) def generateCoreSide(self): @@ -209,7 +209,7 @@ os.mkdir(DEST_DIR) full_path=os.path.join(DEST_DIR,filename) if os.path.exists(full_path) and not self.options.force: - print ("The destination file [%s] already exists ! Use --force to overwrite it" % full_path) + print ("The destination file [%s] already exists ! Use --force to overwrite it" % full_path) try: with open(full_path,'w') as dest_file: dest_file.write('\n'.join(file_buf)) @@ -223,8 +223,8 @@ def __init__(self, bridge_template, options): Constructor.__init__(self, bridge_template, options) - self.core_template="mediawiki_template.tpl" - self.core_dest="mediawiki.wiki" + self.core_template="mediawiki_template.tpl" + self.core_dest="mediawiki.wiki" def _addTextDecorations(self, text): """Add text decorations like coloration or shortcuts""" @@ -259,7 +259,7 @@ if arg_default.has_key(i): wiki.append(":''DEFAULT: %s''" % arg_default[i]) return "\n".join(wiki) - + def _wikiReturn(self, name): """Format return doc with the wiki syntax @param name: name of the function @@ -317,7 +317,7 @@ %(async)s {| class="wikitable" style="text-align:left; width:80%%;" ! scope=row | category -| %(category)s +| %(category)s |- %(signature)s ! scope=row | parameters @@ -325,7 +325,7 @@ %(parameters)s%(return)s |} """ % completion) - + #at this point, signals_part, and methods_part should be filled, #we just have to place them in the right part of the template core_bridge = [] @@ -342,7 +342,7 @@ core_bridge.append(line.replace('\n','')) except IOError: print ("Can't open template file [%s]" % self.core_template) - sys.exit(1) + sys.exit(1) #now we write to final file self.finalWrite(self.core_dest, core_bridge) @@ -351,9 +351,9 @@ def __init__(self, bridge_template, options): Constructor.__init__(self, bridge_template, options) - self.core_template="dbus_core_template.py" - self.frontend_template="dbus_frontend_template.py" - self.frontend_dest = self.core_dest="DBus.py" + self.core_template="dbus_core_template.py" + self.frontend_template="dbus_frontend_template.py" + self.frontend_dest = self.core_dest="DBus.py" def generateCoreSide(self): signals_part = [] @@ -371,7 +371,7 @@ 'sig_in':function['sig_in'] or '', 'sig_out':function['sig_out'] or '', 'category':'PLUGIN' if function['category'] == 'plugin' else 'CORE', - 'name':section, + 'name':section, 'args':self.getArguments(function['sig_in'], name=arg_doc, default=default ) } @@ -427,7 +427,7 @@ core_bridge.append(line.replace('\n','')) except IOError: print ("Can't open template file [%s]" % self.core_template) - sys.exit(1) + sys.exit(1) #now we write to final file self.finalWrite(self.core_dest, core_bridge) @@ -446,7 +446,7 @@ 'sig_in':function['sig_in'] or '', 'sig_out':function['sig_out'] or '', 'category':'plugin' if function['category'] == 'plugin' else 'core', - 'name':section, + 'name':section, 'args':self.getArguments(function['sig_in'], name=arg_doc, default=default) } @@ -483,7 +483,7 @@ frontend_bridge.append(line.replace('\n','')) except IOError: print ("Can't open template file [%s]" % self.frontend_template) - sys.exit(1) + sys.exit(1) #now we write to final file self.finalWrite(self.frontend_dest, frontend_bridge) @@ -493,8 +493,8 @@ def __init__(self, bridge_template, options): Constructor.__init__(self, bridge_template, options) - - self.template="dbus_xml_template.xml" + + self.template="dbus_xml_template.xml" self.core_dest="org.goffi.sat.xml" self.default_annotation = { 'a{ss}': 'StringDict', 'a(sa{ss}as)': 'QList', @@ -540,7 +540,7 @@ annot_elt.setAttribute('value', self.default_annotation[arg]) new_elt.appendChild(annot_elt) idx+=1 - + if function['sig_out']: arg_elt = doc.createElement('arg') arg_elt.setAttribute('type', function['sig_out']) @@ -575,7 +575,7 @@ class BridgeConstructor: def __init__(self): self.options = None - + def check_options(self): """Check command line options""" _usage=""" @@ -597,7 +597,7 @@ help=("Add debug information printing")) parser.add_option("--no_unicode", action="store_false", dest="unicode", default=True, help=("Remove unicode type protection from string results")) - parser.add_option("--flags", action="store", type="string", + parser.add_option("--flags", action="store", type="string", help=("Constructors' specific flags, comma separated")) diff -r 6a718ede8be1 -r 952322b1d490 src/bridge/bridge_constructor/bridge_template.ini --- a/src/bridge/bridge_constructor/bridge_template.ini Fri Jan 18 17:55:27 2013 +0100 +++ b/src/bridge/bridge_constructor/bridge_template.ini Fri Jan 18 17:55:34 2013 +0100 @@ -35,7 +35,7 @@ doc_param_0=contact_jid: JID from who the message is comming doc_param_1=attributes: Dictionary of attributes where keys are: - name: name of the contact - - to: "True" if the contact give its presence information to us + - to: "True" if the contact give its presence information to us - from: "True" if contact is registred to our presence information - ask: "True" is subscription is pending doc_param_2=groups: Roster's groups where the contact is @@ -135,7 +135,7 @@ sig_in=ssa{sa{ss}}s doc=Requested result of an action (Extended) doc_param_0=answer_type: Same as for [actionResult] but with the following additional one: - - DICT_DICT: As RESULT, but returned as a dictionary of dictionary + - DICT_DICT: As RESULT, but returned as a dictionary of dictionary doc_param_1=id: Id of the action doc_param_2=data: answer_type specific data doc_param_3=%(doc_profile)s @@ -319,7 +319,7 @@ doc=Return presence informations of all contacts doc_param_0=%(doc_profile_key)s doc_return=Dict of presence with bare JID of contact as key, and value as follow: - A dict where key is the resource and the value is a tuple with (show, priority, statuses) as for [presenceUpdate] + A dict where key is the resource and the value is a tuple with (show, priority, statuses) as for [presenceUpdate] [getWaitingSub] type=method @@ -552,7 +552,7 @@ doc_param_1=%(doc_profile)s doc_return=dict with progress information: - position: current position - - size: end position + - size: end position [getMenus] type=method @@ -564,7 +564,7 @@ - category: Category of the menu - name: Name of the menu - menu_type: Type which can be: - * NORMAL: Classical application menu + * NORMAL: Classical application menu [getMenuHelp] type=method diff -r 6a718ede8be1 -r 952322b1d490 src/bridge/bridge_constructor/dbus_core_template.py --- a/src/bridge/bridge_constructor/dbus_core_template.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/bridge/bridge_constructor/dbus_core_template.py Fri Jan 18 17:55:34 2013 +0100 @@ -94,7 +94,7 @@ raise DeferredNotAsync return result - ### signals ### + ### signals ### @dbus.service.signal(const_INT_PREFIX+const_PLUGIN_SUFFIX, signature='') @@ -106,14 +106,14 @@ ##SIGNALS_PART## - ### methods ### - + ### methods ### + ##METHODS_PART## - + def __attributes(self, in_sign): """Return arguments to user given a in_sign @param in_sign: in_sign in the short form (using s,a,i,b etc) - @return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")""" + @return: list of arguments that correspond to a in_sign (e.g.: "sss" return "arg1, arg2, arg3")""" i=0 idx=0 attr=[] @@ -152,19 +152,19 @@ _arguments = inspect_args.args _defaults = list(inspect_args.defaults or []) - + if inspect.ismethod(method): #if we have a method, we don't want the first argument (usually 'self') del(_arguments[0]) #first arguments are for the _callback method arguments_callback = ', '.join([repr(name)] + ((_arguments + ['callback=callback','errback=errback']) if async else _arguments)) - + if async: _arguments.extend(['callback','errback']) _defaults.extend([None, None]) - - + + #now we create a second list with default values for i in range(1, len(_defaults)+1): _arguments[-i] = "%s = %s" % (_arguments[-i], repr(_defaults[-i])) @@ -182,7 +182,7 @@ function = getattr(self, name) func_table = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__][function._dbus_interface] func_table[function.__name__] = function #Needed for introspection - + def addSignal(self, name, int_suffix, signature, doc={}): """Dynamically add a signal to Dbus Bridge""" attributes = ', '.join(self.__attributes(signature)) diff -r 6a718ede8be1 -r 952322b1d490 src/bridge/bridge_constructor/dbus_frontend_template.py --- a/src/bridge/bridge_constructor/dbus_frontend_template.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/bridge/bridge_constructor/dbus_frontend_template.py Fri Jan 18 17:55:34 2013 +0100 @@ -73,7 +73,7 @@ # - or if the last two arguments are callable async = False - + if kwargs: if 'callback' in kwargs and 'errback' in kwargs: async = True @@ -84,26 +84,26 @@ args = list(args) _errback = args.pop() _callback = args.pop() - + method = getattr(self.db_plugin_iface, name) - + if async: kwargs['reply_handler'] = _callback kwargs['error_handler'] = lambda err:_errback(err._dbus_error_name[len(const_ERROR_PREFIX)+1:]) return method(*args, **kwargs) - + return getPluginMethod ##METHODS_PART## #methods from plugins - + def joinMUC(self, room_jid, nick, options, profile_key): if options == None: options = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature return self.db_plugin_iface.joinMUC(room_jid, nick, options, profile_key) - + def gatewayRegister(self, action, target, data, profile_key): if data == None: data = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature diff -r 6a718ede8be1 -r 952322b1d490 src/core/sat_main.py --- a/src/core/sat_main.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/core/sat_main.py Fri Jan 18 17:55:34 2013 +0100 @@ -65,7 +65,7 @@ return "sat_id_"+str(sat_id) class SAT(service.Service): - + def get_next_id(self): return sat_next_id() @@ -87,26 +87,26 @@ """Save a constant""" if CONST.has_key(name): error(_('Trying to redefine a constant')) - raise Exception + raise Exception CONST[name] = value - + def __init__(self): #TODO: standardize callback system - - self.__general_cb_map = {} #callback called for general reasons (key = name) + + self.__general_cb_map = {} #callback called for general reasons (key = name) self.__private_data = {} #used for internal callbacks (key = id) self.profiles = {} self.plugins = {} self.menus = {} #used to know which new menus are wanted by plugins - + self.memory=Memory(self) - + local_dir = self.memory.getConfig('', 'local_dir') if not os.path.exists(local_dir): os.makedirs(local_dir) - self.trigger = TriggerManager() #trigger are used to change SàT behaviour - + self.trigger = TriggerManager() #trigger are used to change SàT behaviour + self.bridge=DBusBridge() self.bridge.register("getVersion", lambda: self.get_const('client_version')) self.bridge.register("getProfileName", self.memory.getProfileName) @@ -147,8 +147,8 @@ self.bridge.register("getMenus", self.getMenus) self.bridge.register("getMenuHelp", self.getMenuHelp) self.bridge.register("callMenu", self.callMenu) - - self.memory.initialized.addCallback(self._postMemoryInit) + + self.memory.initialized.addCallback(self._postMemoryInit) def _postMemoryInit(self, ignore): """Method called after memory initialization is done""" @@ -159,7 +159,7 @@ def _import_plugins(self): """Import all plugins found in plugins directory""" import sat.plugins - plugins_path = os.path.dirname(sat.plugins.__file__) + plugins_path = os.path.dirname(sat.plugins.__file__) plug_lst = [os.path.splitext(plugin)[0] for plugin in map(os.path.basename,glob(os.path.join(plugins_path,"plugin*.py")))] __plugins_to_import = {} #plugins we still have to import for plug in plug_lst: @@ -198,11 +198,11 @@ self.plugins[import_name].is_handler = False #TODO: test xmppclient presence and register handler parent - + def connect(self, profile_key = '@DEFAULT@'): """Connect to jabber server""" self.asyncConnect(profile_key) - + def asyncConnect(self, profile_key = '@DEFAULT@'): """Connect to jabber server with asynchronous reply @param profile_key: %(doc_profile)s @@ -212,7 +212,7 @@ if not profile: error (_('Trying to connect a non-exsitant profile')) raise ProfileUnknownError(profile_key) - + if (self.isConnected(profile)): info(_("already connected !")) return defer.succeed("None") @@ -227,12 +227,12 @@ current = self.profiles[profile] = xmpp.SatXMPPClient(self, profile, jid.JID(self.memory.getParamA("JabberID", "Connection", profile_key = profile), profile), self.memory.getParamA("Password", "Connection", profile_key = profile), - self.memory.getParamA("Server", "Connection", profile_key = profile), + self.memory.getParamA("Server", "Connection", profile_key = profile), port) current.messageProt = xmpp.SatMessageProtocol(self) current.messageProt.setHandlerParent(current) - + current.roster = xmpp.SatRosterProtocol(self) current.roster.setHandlerParent(current) @@ -247,7 +247,7 @@ current.versionHandler.setHandlerParent(current) debug (_("setting plugins parents")) - + for plugin in self.plugins.iteritems(): if plugin[1].is_handler: plugin[1].getHandler(profile).setHandlerParent(current) @@ -307,7 +307,7 @@ info("Salut à toi ô mon frère !") #TODO: manage autoconnect #self.connect() - + def stopService(self): self.memory.save() info("Salut aussi à Rantanplan") @@ -315,13 +315,13 @@ def run(self): debug(_("running app")) reactor.run() - + def stop(self): debug(_("stopping app")) reactor.stop() - + ## Misc methods ## - + def getJidNStream(self, profile_key): """Convenient method to get jid and stream from profile key @return: tuple (jid, xmlstream) from profile, can be None""" @@ -347,8 +347,8 @@ serverRegistrer = xmlstream.XmlStreamFactory(xmpp.RegisteringAuthenticator(self, server, login, password, email, next_id, profile)) connector = reactor.connectTCP(server, port, serverRegistrer) serverRegistrer.clientConnectionLost = lambda conn, reason: connector.disconnect() - - return next_id + + return next_id def registerNewAccountCB(self, id, data, profile): user = jid.parse(self.memory.getParamA("JabberID", "Connection", profile_key=profile))[0] @@ -363,7 +363,7 @@ confirm_id = sat_next_id() self.__private_data[confirm_id]=(id,profile) - + self.askConfirmation(confirm_id, "YES/NO", {"message":_("Are you sure to register new account [%(user)s] to server %(server)s ?") % {'user':user, 'server':server, 'profile':profile}}, self.regisConfirmCB, profile) @@ -393,7 +393,7 @@ profile = self.memory.getProfileName(profile_key) assert(profile) to_jid = jid.JID(target) - + iq = compat.IQ(self.profiles[profile].xmlstream, 'set') iq["to"] = target iq["from"] = self.profiles[profile].jid.full() @@ -456,7 +456,7 @@ ## jabber methods ## - + def getWaitingConf(self, profile_key=None): assert(profile_key) client = self.getClient(profile_key) @@ -467,22 +467,22 @@ conf_type, data = client._waiting_conf[conf_id][:2] ret.append((conf_id, conf_type, data)) return ret - + def sendMessage(self, to, msg, subject=None, mess_type='auto', profile_key='@DEFAULT@'): #FIXME: check validity of recipient profile = self.memory.getProfileName(profile_key) assert(profile) client = self.profiles[profile] current_jid = client.jid - mess_data = { #we put data in a dict, so trigger methods can change them + mess_data = { #we put data in a dict, so trigger methods can change them "to": jid.JID(to), "message": msg, "subject": subject, "type": mess_type } - + if mess_data["type"] == "auto": - # we try to guess the type + # we try to guess the type if mess_data["subject"]: mess_data["type"] = 'normal' elif not mess_data["to"].resource: #if to JID has a resource, the type is not 'groupchat' @@ -492,7 +492,7 @@ #FIXME: should entity_type manage ressources ? except (UnknownEntityError, KeyError): entity_type = "contact" - + if entity_type == "chatroom": mess_data["type"] = 'groupchat' else: @@ -500,10 +500,10 @@ else: mess_data["type"] == 'chat' mess_data["type"] == "chat" if mess_data["subject"] else "normal" - + if not self.trigger.point("sendMessage", mess_data, profile): return - + debug(_("Sending jabber message of type [%(type)s] to %(to)s...") % {"type": mess_data["type"], "to": to}) message = domish.Element((None,'message')) message["to"] = mess_data["to"].full() @@ -531,8 +531,8 @@ del statuses[''] self.bridge.presenceUpdate(self.profiles[profile].jid.full(), show, int(priority), statuses, profile) - - + + def subscription(self, subs_type, raw_jid, profile_key): """Called to manage subscription @param subs_type: subsciption type (cf RFC 3921) @@ -592,31 +592,31 @@ def serverDiscoItems(self, disco_result, disco_client, profile, initialized): """xep-0030 Discovery Protocol. @param disco_result: result of the disco item querry - @param disco_client: SatDiscoProtocol instance - @param profile: profile of the user + @param disco_client: SatDiscoProtocol instance + @param profile: profile of the user @param initialized: deferred which must be chained when everything is done""" - + def _check_entity_cb(result, entity, profile): for category, type in result.identities: debug (_('Identity added: (%(category)s,%(type)s) ==> %(entity)s [%(profile)s]') % { 'category':category, 'type':type, 'entity':entity, 'profile':profile}) - self.memory.addServerIdentity(category, type, entity, profile) + self.memory.addServerIdentity(category, type, entity, profile) def _errback(result, entity, profile): warning(_("Can't get information on identity [%(entity)s] for profile [%(profile)s]") % {'entity':entity, 'profile': profile}) - + defer_list = [] for item in disco_result._items: if item.entity.full().count('.') == 1: #XXX: workaround for a bug on jabberfr, tmp warning(_('Using jabberfr workaround, be sure your domain has at least two levels (e.g. "example.tld", not "example" alone)')) continue - args = [item.entity, profile] + args = [item.entity, profile] defer_list.append(disco_client.requestInfo(item.entity).addCallbacks(_check_entity_cb, _errback, args, None, args)) defer.DeferredList(defer_list).chainDeferred(initialized) - - ## Generic HMI ## - + + ## Generic HMI ## + def actionResult(self, action_id, action_type, data, profile): """Send the result of an action @param action_id: same action_id used with action diff -r 6a718ede8be1 -r 952322b1d490 src/core/xmpp.py --- a/src/core/xmpp.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/core/xmpp.py Fri Jan 18 17:55:34 2013 +0100 @@ -28,7 +28,7 @@ class SatXMPPClient(client.XMPPClient): - + def __init__(self, host_app, profile, user_jid, password, host=None, port=5222): client.XMPPClient.__init__(self, user_jid, password, host, port) self.factory.clientConnectionLost = self.connectionLost @@ -39,7 +39,7 @@ self.conn_deferred = defer.Deferred() self._waiting_conf = {} #callback called when a confirmation is received self._progress_cb_map = {} #callback called when a progress is requested (key = progress id) - + def getConnectionDeferred(self): """Return a deferred which fire when the client is connected""" @@ -53,28 +53,28 @@ info (_("********** [%s] CONNECTED **********") % self.profile) self.streamInitialized() self.host_app.bridge.connected(self.profile) #we send the signal to the clients - + def streamInitialized(self): """Called after _authd""" debug (_("XML stream is initialized")) self.keep_alife = task.LoopingCall(self.xmlstream.send, " ") #Needed to avoid disconnection (specially with openfire) self.keep_alife.start(180) - + self.disco = SatDiscoProtocol(self) self.disco.setHandlerParent(self) self.discoHandler = disco.DiscoHandler() self.discoHandler.setHandlerParent(self) - + if not self.host_app.trigger.point("Disco Handled", self.profile): return self.roster.requestRoster() - + self.presence.available() - + self.disco.requestInfo(jid.JID(self.jid.host)).addCallback(self.host_app.serverDisco, self.profile) #FIXME: use these informations - + self.disco.requestItems(jid.JID(self.jid.host)).addCallback(self.host_app.serverDiscoItems, self.disco, self.profile, self.client_initialized) self.conn_deferred.callback(None) @@ -90,7 +90,7 @@ def isConnected(self): return self.__connected - + def connectionLost(self, connector, unused_reason): self.__connected=False info (_("********** [%s] DISCONNECTED **********") % self.profile) @@ -103,7 +103,7 @@ class SatMessageProtocol(xmppim.MessageProtocol): - + def __init__(self, host): xmppim.MessageProtocol.__init__(self) self.host = host @@ -128,7 +128,7 @@ self.host.memory.addToHistory(jid.JID(message["from"]), jid.JID(message["to"]), mess_body, mess_type, profile=self.parent.profile) self.host.bridge.newMessage(message["from"], mess_body, mess_type, message['to'], extra, profile=self.parent.profile) break - + class SatRosterProtocol(xmppim.RosterClientProtocol): def __init__(self, host): @@ -138,7 +138,7 @@ #XXX: the two following dicts keep a local copy of the roster self._groups = {} #map from groups to bare jids: key=group value=set of bare jids self._jids = {} #map from bare jids to RosterItem: key=jid value=RosterItem - + def rosterCb(self, roster): for raw_jid, item in roster.iteritems(): self.onRosterSet(item) @@ -153,7 +153,7 @@ """Remove a contact from roster list""" xmppim.RosterClientProtocol.removeItem(self, to) #TODO: check IQ result - + #XXX: disabled (cf http://wokkel.ik.nu/ticket/56)) #def addItem(self, to): #"""Add a contact to roster list""" @@ -187,7 +187,7 @@ if item.name: item_attr['name'] = item.name return item_attr - + def onRosterSet(self, item): """Called when a new/update roster item is received""" #TODO: send a signal to frontends @@ -199,13 +199,13 @@ return info (_("new contact in roster list: %s"), item.jid.full()) #self.host.memory.addContact(item.jid, item_attr, item.groups, self.parent.profile) - + bare_jid = item.jid.userhost() self._jids[bare_jid] = item for group in item.groups: self._groups.setdefault(group,set()).add(bare_jid) self.host.bridge.newContact(item.jid.full(), self.getAttributes(item), item.groups, self.parent.profile) - + def onRosterRemove(self, entity): """Called when a roster removal event is received""" print _("removing %s from roster list") % entity.full() @@ -226,7 +226,7 @@ except KeyError: log.warning("there is not cache for the group [%(groups)s] of the removed roster item [%(jid)s]" % {"group": group, "jid": bare_jid}) - + #then we send the bridge signal self.host.bridge.contactDeleted(entity.userhost(), self.parent.profile) @@ -247,7 +247,7 @@ def isJidInRoster(self, entity_jid): """Return True if jid is in roster""" return entity_jid.userhost() in self._jids - + def getItems(self): """Return all items of the roster""" return self._jids.values() @@ -257,20 +257,20 @@ return self._groups[group] except KeyError: return exceptions.UnknownGroupError - + class SatPresenceProtocol(xmppim.PresenceClientProtocol): def __init__(self, host): xmppim.PresenceClientProtocol.__init__(self) self.host = host - + def availableReceived(self, entity, show=None, statuses=None, priority=0): debug (_("presence update for [%(entity)s] (available, show=%(show)s statuses=%(statuses)s priority=%(priority)d)") % {'entity':entity, 'show':show, 'statuses':statuses, 'priority':priority}) - + if not statuses: statuses = {} - + if statuses.has_key(None): #we only want string keys statuses["default"] = statuses[None] del statuses[None] @@ -281,13 +281,13 @@ #now it's time to notify frontends self.host.bridge.presenceUpdate(entity.full(), show or "", int(priority), statuses, self.parent.profile) - + def unavailableReceived(self, entity, statuses=None): debug (_("presence update for [%(entity)s] (unavailable, statuses=%(statuses)s)") % {'entity':entity, 'statuses':statuses}) - + if not statuses: statuses = {} - + if statuses.has_key(None): #we only want string keys statuses["default"] = statuses[None] del statuses[None] @@ -295,13 +295,13 @@ #now it's time to notify frontends self.host.bridge.presenceUpdate(entity.full(), "unavailable", 0, statuses, self.parent.profile) - - + + def available(self, entity=None, show=None, statuses=None, priority=0): if not statuses: statuses = {} # default for us is None for wokkel - # so we must temporarily switch to wokkel's convention... + # so we must temporarily switch to wokkel's convention... if 'default' in statuses: statuses[None] = statuses['default'] @@ -380,10 +380,10 @@ self.answer_id = answer_id self.profile = profile print _("Registration asked for"),user_login, user_pass, jabber_host - + def connectionMade(self): print "connectionMade" - + self.xmlstream.namespace = "jabber:client" self.xmlstream.sendHeader() @@ -405,7 +405,7 @@ answer_data={"message":_("Registration successfull")} self.host.bridge.actionResult(answer_type, self.answer_id, answer_data, self.profile) self.xmlstream.sendFooter() - + def registrationFailure(self, failure): info (_("Registration failure: %s") % str(failure.value)) answer_type = "ERROR" diff -r 6a718ede8be1 -r 952322b1d490 src/memory/memory.py --- a/src/memory/memory.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/memory/memory.py Fri Jan 18 17:55:34 2013 +0100 @@ -40,7 +40,7 @@ class Params(): """This class manage parameters with xml""" ### TODO: add desciption in params - + #TODO: move Watched in a plugin default_xml = u""" @@ -84,7 +84,7 @@ source_set = set(source_map.keys()) dest_set = set(dest_map.keys()) to_add = source_set.difference(dest_set) - + for node_key in to_add: dest_node.appendChild(source_map[node_key].cloneNode(True)) @@ -97,12 +97,12 @@ self.dom = minidom.parse(xml_file) default_dom = minidom.parseString(Params.default_xml.encode('utf-8')) self._mergeParams(default_dom.documentElement, self.dom.documentElement) - + def loadGenParams(self): """Load general parameters data from storage @return: deferred triggered once params are loaded""" return self.storage.loadGenParams(self.params_gen) - + def loadIndParams(self, profile, cache=None): """Load individual parameters set self.params cache or a temporary cache @@ -112,7 +112,7 @@ if cache == None: self.params[profile] = {} return self.storage.loadIndParams(self.params[profile] if cache==None else cache, profile) - + def purgeProfile(self, profile): """Remove cache data of a profile @param profile: %(doc_profile)s""" @@ -279,7 +279,7 @@ @param category: category of the parameter @param attr: name of the attribute (default: "value") @param profile: owner of the param (@ALL@ for everyone) - + @return: attribute""" #FIXME: looks really dirty and buggy, need to be reviewed/refactored node = self.__getParamNode(name, category) @@ -290,19 +290,19 @@ if node[0] == 'general': value = self.__getParam(None, category, name, 'general') return self.__getAttr(node[1], attr, value) - + assert(node[0] == 'individual') profile = self.getProfileName(profile_key) if not profile: error(_('Requesting a param for an non-existant profile')) raise exceptions.ProfileUnknownError - + if profile not in self.params: error(_('Requesting synchronous param for not connected profile')) raise exceptions.NotConnectedProfileError(profile) - if attr == "value": + if attr == "value": value = self.__getParam(profile, category, name) return self.__getAttr(node[1], attr, value) @@ -325,15 +325,15 @@ if node[0] == 'general': value = self.__getParam(None, category, name, 'general') return defer.succeed(self.__getAttr(node[1], attr, value)) - + assert(node[0] == 'individual') profile = self.getProfileName(profile_key) if not profile: error(_('Requesting a param for a non-existant profile')) return defer.fail() - - if attr != "value": + + if attr != "value": return defer.succeed(node[1].getAttribute(attr)) try: value = self.__getParam(profile, category, name) @@ -396,7 +396,7 @@ for param_node in params: name = param_node.getAttribute('name') - + if name not in dest_params: dest_params[name] = param_node.cloneNode(True) dest_cat.appendChild(dest_params[name]) @@ -407,8 +407,8 @@ if new_node: prof_xml.documentElement.appendChild(dest_cat) return prof_xml - - + + if self.params.has_key(profile): d = defer.succeed(None) profile_cache = self.params[profile] @@ -435,13 +435,13 @@ if not profile: error(_("Asking params for inexistant profile")) return "" - + def returnXML(prof_xml): return_xml = prof_xml.toxml() prof_xml.unlink() return return_xml - return self.__constructProfileXml(profile).addCallback(returnXML) + return self.__constructProfileXml(profile).addCallback(returnXML) def getParamsForCategory(self, category, profile_key): """Return node's xml for selected category""" @@ -460,7 +460,7 @@ prof_xml.unlink() return "" - + d = self.__constructProfileXml(profile) return d.addCallback(returnCategoryXml) @@ -475,7 +475,7 @@ @return: a tuple with the node type and the the node, or None if not found""" for type_node in self.dom.documentElement.childNodes: - if ( ((_type == "@ALL@" or _type == "@GENERAL@") and type_node.nodeName == 'general') + if ( ((_type == "@ALL@" or _type == "@GENERAL@") and type_node.nodeName == 'general') or ( (_type == "@ALL@" or _type == "@INDIVIDUAL@") and type_node.nodeName == 'individual') ): for node in type_node.getElementsByTagName('category'): if node.getAttribute("name") == category: @@ -484,7 +484,7 @@ if param.getAttribute("name") == name: return (type_node.nodeName, param) return None - + def getParamsCategories(self): """return the categories availables""" categories=[] @@ -507,7 +507,7 @@ if not node: error(_('Requesting an unknown parameter (%(category)s/%(name)s)') % {'category':category, 'name':name}) return - + if node[0] == 'general': self.params_gen[(category, name)] = value self.storage.setGenParam(category, name, value) @@ -515,10 +515,10 @@ if self.host.isConnected(profile): self.host.bridge.paramUpdate(name, value, category, profile) return - + assert (node[0] == 'individual') assert (profile_key != "@NONE@") - + _type = node[1].getAttribute("type") if _type=="button": print "clique",node.toxml() @@ -533,7 +533,7 @@ def __init__(self, host): info (_("Memory manager init")) - self.initialized = defer.Deferred() + self.initialized = defer.Deferred() self.host = host self.entitiesCache={} #XXX: keep presence/last resource/other data in cache # /!\ an entity is not necessarily in roster @@ -611,7 +611,7 @@ @param profile: %(doc_profile)s""" info(_("[%s] Profile session started" % profile)) self.entitiesCache[profile] = {} - + def purgeProfileSession(self, profile): """Delete cache of data of profile @param profile: %(doc_profile)s""" @@ -628,7 +628,7 @@ #TODO: need to encrypt files (at least passwords !) and set permissions param_file_xml = os.path.expanduser(self.getConfig('','local_dir')+ self.host.get_const('savefile_param_xml')) - + self.params.save_xml(param_file_xml) debug(_("params saved")) @@ -647,13 +647,13 @@ @param name: Profile name """ return self.params.createProfile(name) - + def asyncCreateProfile(self, name): """Create a new profile @param name: Profile name """ return self.params.asyncCreateProfile(name) - + def deleteProfile(self, name): """Delete an existing profile @param name: Name of the profile""" @@ -674,7 +674,7 @@ if not self.server_features.has_key(profile): self.server_features[profile] = [] self.server_features[profile].append(feature) - + def addServerIdentity(self, category, _type, entity, profile): """Add an identity discovered from server @param feature: string of the feature @@ -727,7 +727,7 @@ return self.entitiesCache[profile][entity]["last_resource"] except KeyError: return "" - + def getPresenceStatus(self, profile_key): profile = self.getProfileName(profile_key) if not profile: @@ -782,7 +782,7 @@ if there is no value of a given key, resulting dict will have nothing with that key nether @raise: exceptions.UnknownEntityError if entity is not in cache - exceptions.ProfileNotInCacheError if profile is not in cache + exceptions.ProfileNotInCacheError if profile is not in cache """ profile = self.getProfileName(profile_key) if not profile: @@ -819,14 +819,14 @@ if not self.subscriptions.has_key(profile): self.subscriptions[profile] = {} self.subscriptions[profile][entity_jid] = _type - + def delWaitingSub(self, entity_jid, profile_key): """Called when a subcription request is finished""" profile = self.getProfileName(profile_key) assert(profile) if self.subscriptions.has_key(profile) and self.subscriptions[profile].has_key(entity_jid): del self.subscriptions[profile][entity_jid] - + def getWaitingSub(self, profile_key): """Called to get a list of currently waiting subscription requests""" profile = self.getProfileName(profile_key) @@ -835,38 +835,38 @@ return {} if not self.subscriptions.has_key(profile): return {} - + return self.subscriptions[profile] def getStringParamA(self, name, category, attr="value", profile_key='@DEFAULT@'): return self.params.getStringParamA(name, category, attr, profile_key) - + def getParamA(self, name, category, attr="value", profile_key='@DEFAULT@'): return self.params.getParamA(name, category, attr, profile_key) - + def asyncGetParamA(self, name, category, attr="value", profile_key='@DEFAULT@'): return self.params.asyncGetParamA(name, category, attr, profile_key) - + def asyncGetStringParamA(self, name, category, attr="value", profile_key='@DEFAULT@'): return self.params.asyncGetStringParamA(name, category, attr, profile_key) - + def getParamsUI(self, profile_key): return self.params.getParamsUI(profile_key) - + def getParams(self, profile_key): - return self.params.getParams(profile_key) - + return self.params.getParams(profile_key) + def getParamsForCategory(self, category, profile_key): - return self.params.getParamsForCategory(category, profile_key) - + return self.params.getParamsForCategory(category, profile_key) + def getParamsCategories(self): return self.params.getParamsCategories() - + def setParam(self, name, value, category, profile_key): return self.params.setParam(name, value, category, profile_key) def importParams(self, xml): return self.params.importParams(xml) - + def setDefault(self, name, category, callback, errback=None): return self.params.setDefault(name, category, callback, errback) diff -r 6a718ede8be1 -r 952322b1d490 src/memory/persistent.py --- a/src/memory/persistent.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/memory/persistent.py Fri Jan 18 17:55:34 2013 +0100 @@ -74,7 +74,7 @@ def __cmp__(self, other): return self._cache.__cmp__(other) - + def __hash__(self): return self._cache.__hash__() @@ -117,7 +117,7 @@ class PersistentBinaryDict(PersistentDict): """Persistent dict where value can be any python data (instead of string only)""" - + def load(self): """load persistent data from storage """ diff -r 6a718ede8be1 -r 952322b1d490 src/memory/sqlite.py --- a/src/memory/sqlite.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/memory/sqlite.py Fri Jan 18 17:55:34 2013 +0100 @@ -68,7 +68,7 @@ def fillProfileCache(ignore): d = self.dbpool.runQuery("SELECT name,id FROM profiles").addCallback(self._profilesCache) d.chainDeferred(self.initialized) - + defer.DeferredList(init_defers).addCallback(fillProfileCache) #Profiles @@ -77,8 +77,8 @@ @param profiles_result: result of the sql profiles query""" for profile in profiles_result: name, id = profile - self.profiles[name] = id - + self.profiles[name] = id + def getProfilesList(self): """"Return list of all registered profiles""" return self.profiles.keys() @@ -87,23 +87,23 @@ """return True if profile_name exists @param profile_name: name of the profile to check""" return self.profiles.has_key(profile_name) - + def createProfile(self, name): """Create a new profile @param name: name of the profile @return: deferred triggered once profile is actually created""" def getProfileId(ignore): return self.dbpool.runQuery("SELECT (id) FROM profiles WHERE name = ?", (name,)) - + def profile_created(profile_id): _id = profile_id[0][0] self.profiles[name] = _id #we synchronise the cache - + d = self.dbpool.runQuery("INSERT INTO profiles(name) VALUES (?)", (name,)) d.addCallback(getProfileId) d.addCallback(profile_created) return d - + def deleteProfile(self, name): """Delete profile @param name: name of the profile @@ -126,7 +126,7 @@ for param in result: category,name,value = param params_gen[(category, name)] = value - debug(_("loading general parameters from database")) + debug(_("loading general parameters from database")) return self.dbpool.runQuery("SELECT category,name,value FROM param_gen").addCallback(fillParams) def loadIndParams(self, params_ind, profile): @@ -138,7 +138,7 @@ for param in result: category,name,value = param params_ind[(category, name)] = value - debug(_("loading individual parameters from database")) + debug(_("loading individual parameters from database")) d = self.dbpool.runQuery("SELECT category,name,value FROM param_ind WHERE profile_id=?", (self.profiles[profile],)) d.addCallback(fillParams) return d @@ -218,7 +218,7 @@ values.append(_jid.resource) return '(%s=? AND %s_res=?)' % (_type, _type) return '%s=?' % (_type,) - + if between: query_parts.append("(%s OR %s) AND (%s or %s)" % (test_jid('source', from_jid), test_jid('source', to_jid), @@ -233,7 +233,7 @@ if limit: query_parts.append("LIMIT ?") values.append(limit) - + d = self.dbpool.runQuery(" ".join(query_parts), values) return d.addCallback(sqliteToDict) @@ -247,7 +247,7 @@ for private in result: key,value = private private_gen[key] = value - debug(_("loading general private values [namespace: %s] from database") % (namespace,)) + debug(_("loading general private values [namespace: %s] from database") % (namespace,)) d = self.dbpool.runQuery("SELECT key,value FROM private_gen WHERE namespace=?", (namespace,)).addCallback(fillPrivates) return d.addErrback(lambda x: debug(_("No data present in database for namespace %s") % namespace)) @@ -273,7 +273,7 @@ @param value: value to set @return: deferred""" d = self.dbpool.runQuery("REPLACE INTO private_gen(namespace,key,value) VALUES (?,?,?)", (namespace,key,value)) - d.addErrback(lambda ignore: error(_("Can't set general private value (%(key)s) [namespace:%(namespace)s] in database" % + d.addErrback(lambda ignore: error(_("Can't set general private value (%(key)s) [namespace:%(namespace)s] in database" % {"namespace":namespace, "key":key}))) return d @@ -295,7 +295,7 @@ @param key: key of the private value @return: deferred""" d = self.dbpool.runQuery("DELETE FROM private_gen WHERE namespace=? AND key=?", (namespace,key)) - d.addErrback(lambda ignore: error(_("Can't delete general private value (%(key)s) [namespace:%(namespace)s] in database" % + d.addErrback(lambda ignore: error(_("Can't delete general private value (%(key)s) [namespace:%(namespace)s] in database" % {"namespace":namespace, "key":key}))) return d @@ -320,7 +320,7 @@ for private in result: key,value = private private_gen[key] = pickle.loads(str(value)) - debug(_("loading general private binary values [namespace: %s] from database") % (namespace,)) + debug(_("loading general private binary values [namespace: %s] from database") % (namespace,)) d = self.dbpool.runQuery("SELECT key,value FROM private_gen_bin WHERE namespace=?", (namespace,)).addCallback(fillPrivates) return d.addErrback(lambda x: debug(_("No binary data present in database for namespace %s") % namespace)) @@ -346,7 +346,7 @@ @param value: value to set @return: deferred""" d = self.dbpool.runQuery("REPLACE INTO private_gen_bin(namespace,key,value) VALUES (?,?,?)", (namespace,key,pickle.dumps(value,0))) - d.addErrback(lambda ignore: error(_("Can't set general private binary value (%(key)s) [namespace:%(namespace)s] in database" % + d.addErrback(lambda ignore: error(_("Can't set general private binary value (%(key)s) [namespace:%(namespace)s] in database" % {"namespace":namespace, "key":key}))) return d @@ -368,7 +368,7 @@ @param key: key of the private value @return: deferred""" d = self.dbpool.runQuery("DELETE FROM private_gen_bin WHERE namespace=? AND key=?", (namespace,key)) - d.addErrback(lambda ignore: error(_("Can't delete general private binary value (%(key)s) [namespace:%(namespace)s] in database" % + d.addErrback(lambda ignore: error(_("Can't delete general private binary value (%(key)s) [namespace:%(namespace)s] in database" % {"namespace":namespace, "key":key}))) return d diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/deprecated_misc_cs.py --- a/src/plugins/deprecated_misc_cs.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/deprecated_misc_cs.py Fri Jan 18 17:55:34 2013 +0100 @@ -83,7 +83,7 @@ def dataLoaded(ignore): if not self.data[profile]: self.data[profile] = {'cookies':{}} - + self.data[profile].load().addCallback(dataLoaded) def profileDisconnected(self, profile): @@ -104,10 +104,10 @@ self.host.bridge.actionResult("ERROR", id, message_data) return - post_data = urllib.urlencode({'auth_login[un]':login,'auth_login[pw]':password,'auth_login[action]':'Login...'}) - + post_data = urllib.urlencode({'auth_login[un]':login,'auth_login[pw]':password,'auth_login[action]':'Login...'}) + self.data[profile]['cookies'] = {} - + d = getPage('http://www.couchsurfing.org/login.html', method='POST', postdata=post_data, headers={'Content-Type':'application/x-www-form-urlencoded'} , agent=AGENT, cookies=self.data[profile]['cookies']) d.addCallback(self.__connectionCB, id, profile) d.addErrback(self.erroCB, id) @@ -193,7 +193,7 @@ friend_id = regex_href.search(unicode(a_tag)).groups()[0] debug(_("CS friend found: %(friend_name)s (id: %(friend_id)s, link: %(friend_link)s)") % {'friend_name':friend_name, 'friend_id':friend_id, 'friend_link':friend_link}) - friends[friend_name] = {'link':friend_link,'id':friend_id} + friends[friend_name] = {'link':friend_link,'id':friend_id} a = soup.find('td','barmiddle next').a #is there several pages ? if a: #yes, we parse the next page @@ -255,7 +255,7 @@ message = data['message'] info(_("sending message to %(friends)s with subject [%(subject)s]" % {'friends':friends, 'subject':subject})) self.__sendMessage(None, subject, message, self.data[profile], friends, id, profile) - + def __showUnreadMessages2(self, html, id, profile): """Called when the inbox page has been received""" #FIXME: that's really too fragile, only works if the unread messages are in the first page, and it would be too resources consuming for the website to DL each time all pages. In addition, the show attribute doesn't work as expected. @@ -269,4 +269,4 @@ d = getPage("http://www.couchsurfing.org/messages.html?message_status=inbox&show=10000", agent=AGENT, cookies=self.data[profile]['cookies']) d.addCallback(self.__showUnreadMessages2, id, profile) d.addErrback(self.erroCB, id) - + diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_exp_parrot.py --- a/src/plugins/plugin_exp_parrot.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_exp_parrot.py Fri Jan 18 17:55:34 2013 +0100 @@ -24,7 +24,7 @@ from sat.core.exceptions import UnknownEntityError -from sat.tools.misc import SkipOtherTriggers +from sat.tools.misc import SkipOtherTriggers PLUGIN_INFO = { "name": "Parrot Plugin", @@ -57,28 +57,28 @@ # _links = client.parrot_links # except AttributeError: # return True - # + # # if mess_data['to'].userhostJID() in _links.values(): # debug("Parrot link detected, skipping other triggers") - # raise SkipOtherTriggers + # raise SkipOtherTriggers def MessageReceivedTrigger(self, message, profile): """ Check if source is linked and repeat message, else do nothing """ client = self.host.getClient(profile) from_jid = jid.JID(message["from"]) - + try: _links = client.parrot_links except AttributeError: return True - + if not from_jid.userhostJID() in _links: return True - + for e in message.elements(): if e.name == "body": mess_body = e.children[0] if e.children else "" - + try: entity_type = self.host.memory.getEntityData(from_jid, ['type'], profile)["type"] except (UnknownEntityError, KeyError): @@ -97,7 +97,7 @@ self.host.sendMessage(unicode(linked), msg, None, "auto", profile_key=profile) else: warning("No body element found in message, following normal behaviour") - + return True def addParrot(self, source_jid, dest_jid, profile): diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_exp_pipe.py --- a/src/plugins/plugin_exp_pipe.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_exp_pipe.py Fri Jan 18 17:55:34 2013 +0100 @@ -57,9 +57,9 @@ def profileConnected(self, profile): client = self.host.getClient(profile) - client._pipe_waiting_for_approval = {} #key = id, value = [transfer data, IdelayedCall Reactor timeout, + client._pipe_waiting_for_approval = {} #key = id, value = [transfer data, IdelayedCall Reactor timeout, # current stream method, [failed stream methods], profile] - + def _kill_id(self, approval_id, profile): """Delete a waiting_for_approval id, called after timeout @param approval_id: id of _pipe_waiting_for_approval""" @@ -69,7 +69,7 @@ del client._pipe_waiting_for_approval[approval_id] except KeyError: warning(_("kill id called on a non existant approval id")) - + def transferRequest(self, iq_id, from_jid, si_id, si_mime_type, si_el, profile): """Called when a pipe transfer is requested @param iq_id: id of the iq request @@ -85,12 +85,12 @@ raise ProfileNotInCacheError pipe_elts = filter(lambda elt: elt.name == 'pipe', si_el.elements()) feature_elts = self.host.plugins["XEP-0020"].getFeatureElt(si_el) - + if not pipe_elts: warning(_("No pipe element found")) self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile) return - + if feature_elts: feature_el = feature_elts[0] form = data_form.Form.fromElement(feature_el.firstChildElement()) @@ -202,7 +202,7 @@ if not feature_elts: warning(_("No feature element")) return - + choosed_options = self.host.plugins["XEP-0020"].getChoosedOptions(feature_elts[0]) try: stream_method = choosed_options["stream-method"] @@ -236,9 +236,9 @@ warning(_("Trying to send a file from an unknown profile")) return "" feature_elt = self.host.plugins["XEP-0020"].proposeFeatures({'stream-method': self.managed_stream_m}) - + pipe_transfer_elts = [] - + pipe_elt = domish.Element((PROFILE, 'pipe')) pipe_transfer_elts.append(pipe_elt) diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_misc_account.py --- a/src/plugins/plugin_misc_account.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_misc_account.py Fri Jan 18 17:55:34 2013 +0100 @@ -52,12 +52,12 @@ class ProsodyRegisterProtocol(protocol.ProcessProtocol): """ Try to register an account with prosody """ - + def __init__(self, password, deferred = None): self.password = password self.deferred = deferred self.data = '' - + def connectionMade(self): self.transport.write("%s\n%s" % ((self.password.encode('utf-8'),)*2)) self.transport.closeStdin() @@ -65,10 +65,10 @@ def outReceived(self, data): self.data += data - + def errReceived(self, data): self.data += data - + def processEnded(self, reason): if (reason.value.exitCode == 0): info(_('Prosody registration success')) @@ -97,7 +97,7 @@ info(_('Prosody path found: %s') % (self._prosody_path,)) def _registerAccount(self, email, password, profile): - + """ #Password Generation #_charset = [chr(i) for i in range(0x21,0x7F)] #XXX: this charset seems to have some issues with openfire @@ -117,13 +117,13 @@ return d def _profileRegistered(self, result, email, password, profile): - + #FIXME: values must be in a config file instead of hardcoded - self.host.memory.setParam("JabberID", "%s@%s/%s" % (profile, _NEW_ACCOUNT_DOMAIN, _NEW_ACCOUNT_RESOURCE), "Connection", profile) + self.host.memory.setParam("JabberID", "%s@%s/%s" % (profile, _NEW_ACCOUNT_DOMAIN, _NEW_ACCOUNT_RESOURCE), "Connection", profile) self.host.memory.setParam("Server", _NEW_ACCOUNT_SERVER, "Connection", profile) self.host.memory.setParam("Password", password, "Connection", profile) #and the account - + #XXX: we use "prosodyctl adduser" because "register" doesn't check conflict # and just change the password if the account already exists d = defer.Deferred() @@ -146,7 +146,7 @@ def email_ko(ignore): #TODO: return error code to user error ("Failed to send email to %s" % email) - + body = (u"""Welcome to Libervia, a Salut à Toi project part /!\\ WARNING, THIS IS ONLY A TECHNICAL DEMO, DON'T USE THIS ACCOUNT FOR ANY SERIOUS PURPOSE /!\\ diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_misc_groupblog.py --- a/src/plugins/plugin_misc_groupblog.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_misc_groupblog.py Fri Jan 18 17:55:34 2013 +0100 @@ -82,7 +82,7 @@ host.bridge.addMethod("sendGroupBlog", ".plugin", in_sign='sasss', out_sign='', method=self.sendGroupBlog) - + host.bridge.addMethod("getLastGroupBlogs", ".plugin", in_sign='sis', out_sign='aa{ss}', method=self.getLastGroupBlogs, @@ -92,21 +92,21 @@ in_sign='sasis', out_sign='a{saa{ss}}', method=self.getMassiveLastGroupBlogs, async = True) - + host.bridge.addMethod("subscribeGroupBlog", ".plugin", in_sign='ss', out_sign='', method=self.subscribeGroupBlog, async = True) - + host.bridge.addMethod("massiveSubscribeGroupBlogs", ".plugin", in_sign='sass', out_sign='', method=self.massiveSubscribeGroupBlogs, async = True) - + host.trigger.add("PubSubItemsReceived", self.pubSubItemsReceivedTrigger) - - + + def getHandler(self, profile): return GroupBlog_handler() - + @defer.inlineCallbacks def initialise(self, profile_key): """Check that this data for this profile are initialised, and do it else @@ -115,14 +115,14 @@ profile = self.host.memory.getProfileName(profile_key) if not profile: error(_("Unknown profile")) - raise Exception("Unknown profile") - + raise Exception("Unknown profile") + client = self.host.getClient(profile) if not client: error(_('No client for this profile key: %s') % profile_key) - raise Exception("Unknown profile") + raise Exception("Unknown profile") yield client.client_initialized #we want to be sure that the client is initialized - + #we first check that we have a item-access pubsub server if not hasattr(client,"item_access_pubsub"): debug(_('Looking for item-access power pubsub server')) @@ -136,7 +136,7 @@ info(_("item-access powered pubsub service found: [%s]") % entity.full()) client.item_access_pubsub = entity client._item_access_pubsub_pending.callback(None) - + if hasattr(client,"_item_access_pubsub_pending"): #XXX: we need to wait for item access pubsub service check yield client._item_access_pubsub_pending @@ -174,7 +174,7 @@ form_elts = filter(lambda elt: elt.name == "x", item.children) for form_elt in form_elts: form = data_form.Form.fromElement(form_elt) - + if (form.formNamespace == NS_PUBSUB_ITEM_CONFIG): access_model = form.get(OPT_ACCESS_MODEL, 'open') if access_model == "roster": @@ -183,7 +183,7 @@ except KeyError: warning("No group found for roster access-model") microblog_data["groups"] = '' - + break def item2gbdata(self, item): @@ -258,12 +258,12 @@ raise NotImplementedError else: error(_("Unknown access type")) - raise BadAccessTypeError - + raise BadAccessTypeError + self.initialise(profile_key).addCallback(initialised) - + def getLastGroupBlogs(self, pub_jid, max_items=10, profile_key='@DEFAULT@'): """Get the last published microblogs @param pub_jid: jid of the publisher @@ -271,7 +271,7 @@ @param profile_key: profile key @return: list of microblog data (dict) """ - + def initialised(result): profile, client = result d = self.host.plugins["XEP-0060"].getItems(client.item_access_pubsub, self.getNodeName(jid.JID(pub_jid)), @@ -292,14 +292,14 @@ """ def sendResult(result): """send result of DeferredList (list of microblogs to the calling method""" - + ret = {} for (success, value) in result: if success: source_jid, data = value ret[source_jid] = data - + return ret def initialised(result): @@ -316,9 +316,9 @@ jids = publishers else: raise UnknownType - + mblogs = [] - + for _jid in jids: d = self.host.plugins["XEP-0060"].getItems(client.item_access_pubsub, self.getNodeName(jid.JID(_jid)), max_items=max_items, profile_key=profile_key) @@ -326,7 +326,7 @@ mblogs.append(d) dlist = defer.DeferredList(mblogs) dlist.addCallback(sendResult) - + return dlist @@ -391,7 +391,7 @@ class GroupBlog_handler(XMPPHandler): implements(iwokkel.IDisco) - + def getDiscoInfo(self, requestor, target, nodeIdentifier=''): return [disco.DiscoFeature(NS_GROUPBLOG)] diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_misc_imap.py --- a/src/plugins/plugin_misc_imap.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_misc_imap.py Fri Jan 18 17:55:34 2013 +0100 @@ -51,7 +51,7 @@ class IMAP_server(): #TODO: connect profile on mailbox request, once password is accepted - + params = """ @@ -65,13 +65,13 @@ def __init__(self, host): info(_("Plugin Imap Server initialization")) self.host = host - + #parameters host.memory.importParams(self.params) port = int(self.host.memory.getParamA("IMAP Port", "Mail Server")) info(_("Launching IMAP server on port %d"), port) - + self.server_factory = ImapServerFactory(self.host) reactor.listenTCP(port, self.server_factory) @@ -84,7 +84,7 @@ self.flags=flags self.mess_fp=mess_fp self.message=Parser().parse(mess_fp) - + def getUID(self): """Retrieve the unique identifier associated with this message. """ @@ -221,7 +221,7 @@ """Called before this mailbox is deleted, permanently. """ debug('destroy') - + def requestStatus(self, names): """Return status information about this mailbox. @@ -340,7 +340,7 @@ setF(mess_id, new_flags) ret[mess_id] = tuple(new_flags) return ret - + if uid: messages.last = self.mailbox.getMaxUid() messages.getnext = self.mailbox.getNextExistingUid @@ -348,7 +348,7 @@ for listener in self.listeners: listener.flagsChanged(ret) return ret - + else: messages.last = self.getMessageCount() ret = updateFlags(self.mailbox.getFlags,self.mailbox.setFlags) @@ -412,7 +412,7 @@ credentialInterfaces = (credentials.IUsernamePassword, credentials.IUsernameHashedPassword) - + def __init__(self, host): self.host = host diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_misc_maildir.py --- a/src/plugins/plugin_misc_maildir.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_misc_maildir.py Fri Jan 18 17:55:34 2013 +0100 @@ -57,7 +57,7 @@ pass class MaildirBox(): - + def __init__(self, host): info(_("Plugin Maildir initialization")) self.host = host @@ -184,14 +184,14 @@ if idx>box_data['cur_idx']: return None return idx - + def getMaxUid(self, boxname, profile): """Give the max existing uid @param boxname: name of the box where the message is @return: uid""" box_data = self.__getBoxData(boxname, profile) return box_data['cur_idx'] - + def getIdFromUid(self, boxname, message_uid, profile): """Return the message unique id from it's integer UID @param boxname: name of the box where the message is @@ -251,9 +251,9 @@ """ box_data = self.__getBoxData(boxname, profile) for mess_id in self.getMessageIdsWithFlag(boxname,"\\Deleted", profile): - del(box_data[mess_id]) + del(box_data[mess_id]) self.data[profile].force(boxname) - + def cleanTable(self, boxname, existant_id, profile): """Remove mails which no longuer exist from the table @param boxname: name of the box to clean @@ -265,7 +265,7 @@ to_remove.append(key) for key in to_remove: del box_data[key] - + def addObserver(self, callback, profile, boxname, signal="NEW_MESSAGE"): """Add an observer for maildir box changes @param callback: method to call when the the box is updated @@ -327,7 +327,7 @@ elif e.name == "subject": mail['Subject'] = e.children[0].encode('utf-8') return mail.as_string() - + def __init__(self, _maildir, name, observer=None, profile="@NONE@"): """@param _maildir: the main MaildirBox instance @param name: name of the mailbox @@ -350,7 +350,7 @@ self.mailbox = maildir.MaildirMailbox(mailbox_path) self.observer=observer self.__uid_table_update() - + if observer: debug("adding observer for %s (%s)" % (name,profile)) self.maildir.addObserver(observer, profile, name, "NEW_MESSAGE") @@ -362,7 +362,7 @@ existant_id.append(self.getId(mess_idx)) self.getUid(mess_idx) self.maildir.cleanTable(self.name, existant_id, profile=self.profile) - + def __del__(self): if observer: @@ -417,7 +417,7 @@ if self.getUid(mess_idx) == mess_uid: return mess_idx raise IndexError - + def getIdxFromId(self, mess_id): """Return the message index from the unique index @param mess_id: message unique index as given by MaildirMailbox @@ -426,7 +426,7 @@ if self.mailbox.getUidl(mess_idx) == mess_id: return mess_idx raise IndexError - + def getMessage(self, mess_idx): """Return the full message @param mess_idx: message index""" @@ -443,7 +443,7 @@ @return: list of strings""" id = self.getId(mess_idx) return self.maildir.getFlags(self.name, id, profile=self.profile) - + def getFlagsUid(self, mess_uid): """Return the flags of the message @param mess_uid: message unique identifier @@ -487,4 +487,4 @@ """Delete everything in the .Trash dir""" import shutils pdb.set_trace() - + diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_misc_quiz.py --- a/src/plugins/plugin_misc_quiz.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_misc_quiz.py Fri Jan 18 17:55:34 2013 +0100 @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- """ -SAT plugin for managing Quiz game +SAT plugin for managing Quiz game Copyright (C) 2009, 2010, 2011, 2012, 2013 Jérôme Poisson (goffi@goffi.org) This program is free software: you can redistribute it and/or modify @@ -133,7 +133,7 @@ for data in game_data: data_elt = domish.Element((None,data)) data_elt.addContent(game_data[data]) - game_data_elt.addChild(data_elt) + game_data_elt.addChild(data_elt) return game_data_elt def __xml_to_game_data(self, game_data_elt): @@ -161,17 +161,17 @@ score = {} for player in game_data['players']: score[player] = players_data[player]['score'] - + answer_result_elt = domish.Element((None,'answer_result')) answer_result_elt['player'] = player_answering answer_result_elt['good_answer'] = str(good_answer) - + for player in score: score_elt = domish.Element((None,"score")) score_elt['player'] = player score_elt['score'] = str(score[player]) - answer_result_elt.addChild(score_elt) - + answer_result_elt.addChild(score_elt) + return answer_result_elt def __create_started_elt(self, players): @@ -193,7 +193,7 @@ question_elt['timer'] = str(timer) question_elt.addContent(question) return question_elt - + def __start_play(self, room_jid, game_data, profile): """Start the game (tell to the first player after dealer to play""" game_data['stage'] = "play" @@ -231,14 +231,14 @@ for player in players: self.host.plugins["XEP-0249"].invite(jid.JID(player), room.occupantJID.userhostJID(), {"game":"Quiz"}, profile) self.waiting_inv[_room] = (time(), players) #TODO: remove invitation waiting for too long, using the time data - + def after_init(ignore): room_name = "sat_quiz_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key) print "\n\n===> room_name:", room_name muc_service = None for service in self.host.memory.getServerServiceEntities("conference", "text", profile): if not ".irc." in service.userhost(): - #FIXME: + #FIXME: #This awfull ugly hack is here to avoid an issue with openfire: the irc gateway #use "conference/text" identity (instead of "conference/irc"), there is certainly a better way #to manage this, but this hack fill do it for test purpose @@ -247,7 +247,7 @@ if not muc_service: error(_("Can't find a MUC service")) return - + _jid, xmlstream = self.host.getJidNStream(profile) d = self.host.plugins["XEP-0045"].join(jid.JID("%s@%s" % (room_name, muc_service.userhost())), _jid.user, {}, profile).addCallback(quizRoomJoined) @@ -355,18 +355,18 @@ game_data["timer"] = reactor.callLater(timer, self.timerExpired, room_jid, profile) game_data["time_left"] = None - def checkAnswer(self, room_jid, player, answer, profile): + def checkAnswer(self, room_jid, player, answer, profile): """Check if the answer given is right""" game_data = self.games[room_jid.userhost()] players_data = game_data['players_data'] good_answer = game_data['question_id'] == "1" and answer=="42" players_data[player]['score'] += 1 if good_answer else -1 players_data[player]['score'] = min(9, max(0, players_data[player]['score'])) - + mess = self.createGameElt(room_jid) mess.firstChildElement().addChild(self.__answer_result(player, good_answer, game_data)) self.host.profiles[profile].xmlstream.send(mess) - + if good_answer: reactor.callLater(4, self.askQuestion, room_jid, profile) else: @@ -382,7 +382,7 @@ for player in players: players_data[player]['game_score'] = 0 - + new_game_data = {"instructions": _(u"""Bienvenue dans cette partie rapide de quizz, le premier à atteindre le score de 9 remporte le jeu Attention, tu es prêt ?""")} @@ -393,20 +393,20 @@ reactor.callLater(10, self.askQuestion, room_jid, profile) def quiz_game_cmd(self, mess_elt, profile): - from_jid = jid.JID(mess_elt['from']) + from_jid = jid.JID(mess_elt['from']) room_jid = jid.JID(from_jid.userhost()) game_elt = mess_elt.firstChildElement() game_data = self.games[room_jid.userhost()] players_data = game_data['players_data'] - + for elt in game_elt.elements(): - + if elt.name == 'started': #new game created players = [] for player in elt.elements(): players.append(unicode(player)) self.host.bridge.quizGameStarted(room_jid.userhost(), from_jid.full(), players, profile) - + elif elt.name == 'player_ready': #ready to play player = elt['player'] status = self.games[room_jid.userhost()]['status'] @@ -418,10 +418,10 @@ elif elt.name == 'game_data': self.host.bridge.quizGameNew(room_jid.userhost(), self.__xml_to_game_data(elt), profile) - + elif elt.name == 'question': #A question is asked self.host.bridge.quizGameQuestion(room_jid.userhost(), elt["id"], unicode(elt), int(elt["timer"]), profile ) - + elif elt.name == 'player_answer': player = elt['player'] pause = game_data['stage'] == 'question' #we pause the game only if we are have a question at the moment @@ -429,7 +429,7 @@ mess = self.createGameElt(room_jid) buzzer_elt = mess.firstChildElement().addElement('player_buzzed') buzzer_elt['player'] = player - buzzer_elt['pause'] = str(pause) + buzzer_elt['pause'] = str(pause) self.host.profiles[profile].xmlstream.send(mess) if pause: self.pauseTimer(room_jid) @@ -442,17 +442,17 @@ say_elt['delay'] = "3" reactor.callLater(2, self.host.profiles[profile].xmlstream.send, mess) reactor.callLater(6, self.checkAnswer, room_jid, player, _answer, profile=profile) - + elif elt.name == 'player_buzzed': self.host.bridge.quizGamePlayerBuzzed(room_jid.userhost(), elt["player"], elt['pause'] == str(True), profile) - + elif elt.name == 'player_says': self.host.bridge.quizGamePlayerSays(room_jid.userhost(), elt["player"], unicode(elt), int(elt["delay"]), profile) - + elif elt.name == 'answer_result': player, good_answer, score = self.__answer_result_to_signal_args(elt) self.host.bridge.quizGameAnswerResult(room_jid.userhost(), player, good_answer, score, profile) - + elif elt.name == 'timer_expired': self.host.bridge.quizGameTimerExpired(room_jid.userhost(), profile) @@ -461,13 +461,13 @@ else: error (_('Unmanaged game element: %s') % elt.name) - + def getHandler(self, profile): return QuizGameHandler(self) class QuizGameHandler (XMPPHandler): implements(iwokkel.IDisco) - + def __init__(self, plugin_parent): self.plugin_parent = plugin_parent self.host = plugin_parent.host diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_misc_radiocol.py --- a/src/plugins/plugin_misc_radiocol.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_misc_radiocol.py Fri Jan 18 17:55:34 2013 +0100 @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- """ -SAT plugin for managing Radiocol +SAT plugin for managing Radiocol Copyright (C) 2009, 2010, 2011, 2012, 2013 Jérôme Poisson (goffi@goffi.org) This program is free software: you can redistribute it and/or modify @@ -80,7 +80,7 @@ elt["type"] = type elt.addElement((NC_RADIOCOL, RADIOC_TAG)) return elt - + def __create_started_elt(self): """Create a game_started domish element""" started_elt = domish.Element((None,'started')) @@ -122,14 +122,14 @@ self.radiocolCreate(_room_jid.userhost(), profile_key=profile) for occupant in occupants: self.host.plugins["XEP-0249"].invite(jid.JID(occupant), room.occupantJID.userhostJID(), {"game":"Radiocol"}, profile) - + def after_init(ignore): room_name = "sat_radiocol_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key) print "\n\n===> room_name:", room_name muc_service = None for service in self.host.memory.getServerServiceEntities("conference", "text", profile): if not ".irc." in service.userhost(): - #FIXME: + #FIXME: #This awfull ugly hack is here to avoid an issue with openfire: the irc gateway #use "conference/text" identity (instead of "conference/irc"), there is certainly a better way #to manage this, but this hack fill do it for test purpose @@ -138,7 +138,7 @@ if not muc_service: error(_("Can't find a MUC service")) return - + _jid, xmlstream = self.host.getJidNStream(profile) d = self.host.plugins["XEP-0045"].join(jid.JID("%s@%s" % (room_name, muc_service.userhost())), _jid.user, {}, profile) d.addCallback(radiocolRoomJoined) @@ -184,7 +184,7 @@ client = self.host.getClient(profile) if not client: error(_("Can't access profile's data")) - return + return try: song = OggVorbis(song_path) except OggVorbisHeaderError: @@ -213,7 +213,7 @@ self.host.profiles[profile].xmlstream.send(mess) radio_data = self.radios[jid.JID(referee).userhost()] #FIXME: referee comes from Libervia's client side, it's unsecure - radio_data['to_delete'][filename] = song_path #FIXME: works only because of the same host trick, see the note under the docstring + radio_data['to_delete'][filename] = song_path #FIXME: works only because of the same host trick, see the note under the docstring def playNext(self, room_jid, profile): """"Play next sont in queue if exists, and put a timer @@ -248,22 +248,22 @@ except KeyError: error(_("INTERNAL ERROR: can't find full path of the song to delete")) return - - #we wait more than the song length to delete the file, to manage poorly reactive networks/clients + + #we wait more than the song length to delete the file, to manage poorly reactive networks/clients reactor.callLater(length + 90, unlink, file_to_delete) #FIXME: same host trick (see above) def radiocol_game_cmd(self, mess_elt, profile): #FIXME: we should check sender (is it referee ?) here before accepting commands - from_jid = jid.JID(mess_elt['from']) + from_jid = jid.JID(mess_elt['from']) room_jid = jid.JID(from_jid.userhost()) radio_elt = mess_elt.firstChildElement() radio_data = self.radios[room_jid.userhost()] occupants_data = radio_data['occupants_data'] queue = radio_data['queue'] - + for elt in radio_elt.elements(): - + if elt.name == 'started': #new game created self.host.bridge.radiocolStarted(room_jid.userhost(), from_jid.full(), profile) elif elt.name == 'preload': #a song is in queue and must be preloaded @@ -279,7 +279,7 @@ elif elt.name == 'song_added': #a song has been added #FIXME: we are KISS for the proof of concept: every song is added, to a limit of 3 in queue. # Need to manage some sort of rules to allow peoples to send songs - + if len(queue) >= QUEUE_LIMIT: #there are already too many songs in queue, we reject this one mess = self.createRadiocolElt(room_jid) @@ -289,7 +289,7 @@ #FIXME: add an error code self.host.profiles[profile].xmlstream.send(mess) return - + #The song is accepted and added in queue queue.append((elt['filename'], float(elt['length']))) @@ -317,13 +317,13 @@ self.playNext(room_jid, profile) else: error (_('Unmanaged game element: %s') % elt.name) - + def getHandler(self, profile): return RadiocolHandler(self) class RadiocolHandler (XMPPHandler): implements(iwokkel.IDisco) - + def __init__(self, plugin_parent): self.plugin_parent = plugin_parent self.host = plugin_parent.host diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_misc_smtp.py --- a/src/plugins/plugin_misc_smtp.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_misc_smtp.py Fri Jan 18 17:55:34 2013 +0100 @@ -50,7 +50,7 @@ } class SMTP_server(): - + params = """ @@ -64,13 +64,13 @@ def __init__(self, host): info(_("Plugin SMTP Server initialization")) self.host = host - + #parameters host.memory.importParams(self.params) port = int(self.host.memory.getParamA("SMTP Port", "Mail Server")) info(_("Launching SMTP server on port %d"), port) - + self.server_factory = SmtpServerFactory(self.host) reactor.listenTCP(port, self.server_factory) @@ -81,7 +81,7 @@ self.host=host self.profile=profile self.message=[] - + def lineReceived(self, line): """handle another line""" self.message.append(line) @@ -167,7 +167,7 @@ credentialInterfaces = (credentials.IUsernamePassword, credentials.IUsernameHashedPassword) - + def __init__(self, host): self.host = host @@ -203,7 +203,7 @@ def clientConnectionLost(self, connector, reason): debug (_("SMTP server connection lost (reason: %s)"), reason) smtp.SMTPFactory.clientConnectionLost(self, connector, reason) - + def buildProtocol(self, addr): p = smtp.SMTPFactory.buildProtocol(self, addr) # add the challengers from imap4, more secure and complicated challengers are available diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_misc_tarot.py --- a/src/plugins/plugin_misc_tarot.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_misc_tarot.py Fri Jan 18 17:55:34 2013 +0100 @@ -98,7 +98,7 @@ card_elt = domish.Element((None,'card')) card_elt['suit'] = card.suit card_elt['value'] = card.value - cards_list_elt.addChild(card_elt) + cards_list_elt.addChild(card_elt) return cards_list_elt def __xml_to_list(self, cards_list_elt): @@ -107,7 +107,7 @@ for card in cards_list_elt.elements(): cards_list.append((card['suit'], card['value'])) return cards_list - + def __create_started_elt(self, players): """Create a game_started domish element""" @@ -164,7 +164,7 @@ error_elt.addChild(played_elt) error_elt.addChild(invalid_elt) return error_elt - + def __next_player(self, game_data, next_pl = None): """Increment player number & return player name @param next_pl: if given, then next_player is forced to this one @@ -180,7 +180,7 @@ """give the nick of the player who win this trick""" players_data = game_data['players_data'] first = game_data['first_player'] - first_idx = game_data['players'].index(first) + first_idx = game_data['players'].index(first) suit_asked = None strongest = None winner = None @@ -225,19 +225,19 @@ if not excuse in played: #the Excuse is not on the table, nothing to do return - + excuse_player = None #Who has played the Excuse ? for player in game_data['players']: if players_data[player]['played'] == excuse: excuse_player = player break - + if excuse_player == winner: return #the excuse player win the trick, nothing to do - + #first we remove the excuse from played cards played.remove(excuse) - #then we give it back to the original owner + #then we give it back to the original owner owner_levees = players_data[excuse_player]['levees'] owner_levees.append(excuse) #finally we give a low card to the trick winner @@ -267,10 +267,10 @@ for player in game_data['players']: scores_str+=_("\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i") % {'player':player, 'score_game':0, 'total_score': players_data[player]['score']} debug(scores_str) - + return (scores_str, [], []) - + def __calculate_scores(self, game_data): """The game is finished, time to know who won :) @param game_data: data of the game @@ -285,7 +285,7 @@ nb_bouts +=1 bouts.append(card.value) score += card.points - + #We we do a basic check on score calculation check_score = 0 defenseurs = game_data['players'][:] @@ -297,7 +297,7 @@ for card in game_data['chien']: check_score+=card.points assert (score + check_score == 91) - + point_limit = None if nb_bouts == 3: point_limit = 36 @@ -340,7 +340,7 @@ for player in game_data['players']: scores_str+=_("\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i") % {'player':player, 'score_game':player_score[player], 'total_score': players_data[player]['score']} debug(scores_str) - + return (scores_str, winners, loosers) def __invalid_cards(self, game_data, cards): @@ -437,7 +437,7 @@ for player in players: self.host.plugins["XEP-0249"].invite(jid.JID(player), room.occupantJID.userhostJID(), {"game":"Tarot"}, profile) self.waiting_inv[_room] = (time(), players) #TODO: remove invitation waiting for too long, using the time data - + def after_init(ignore): room_name = "sat_tarot_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key) print "\n\n===> room_name:", room_name @@ -445,7 +445,7 @@ muc_service = None for service in self.host.memory.getServerServiceEntities("conference", "text", profile): if not ".irc." in service.userhost(): - #FIXME: + #FIXME: #This awfull ugly hack is here to avoid an issue with openfire: the irc gateway #use "conference/text" identity (instead of "conference/irc"), there is certainly a better way #to manage this, but this hack fill do it for test purpose @@ -454,7 +454,7 @@ if not muc_service: error(_("Can't find a MUC service")) return - + _jid, xmlstream = self.host.getJidNStream(profile) d = self.host.plugins["XEP-0045"].join(jid.JID("%s@%s" % (room_name, muc_service.userhost())), _jid.user, {}, profile).addCallback(tarotRoomJoined) @@ -580,23 +580,23 @@ mess = self.createGameElt(to_jid) mess.firstChildElement().addChild(self.__ask_contrat()) self.host.profiles[profile].xmlstream.send(mess) - + def card_game_cmd(self, mess_elt, profile): - from_jid = jid.JID(mess_elt['from']) + from_jid = jid.JID(mess_elt['from']) room_jid = jid.JID(from_jid.userhost()) game_elt = mess_elt.firstChildElement() game_data = self.games[room_jid.userhost()] players_data = game_data['players_data'] - + for elt in game_elt.elements(): - + if elt.name == 'started': #new game created players = [] for player in elt.elements(): players.append(unicode(player)) self.host.bridge.tarotGameStarted(room_jid.userhost(), from_jid.full(), players, profile) - + elif elt.name == 'player_ready': #ready to play player = elt['player'] status = self.games[room_jid.userhost()]['status'] @@ -605,7 +605,7 @@ debug (_('Player %(player)s is ready to start [status: %(status)s]') % {'player':player, 'status':status}) if status.values().count('ready') == nb_players: #everybody is ready, we can start the game self.newGame(room_jid, profile) - + elif elt.name == 'hand': #a new hand has been received self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile) @@ -613,7 +613,7 @@ form = data_form.Form.fromElement(elt.firstChildElement()) xml_data = dataForm2xml(form) self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile) - + elif elt.name == 'contrat_choosed': #TODO: check we receive the contrat from the right person #TODO: use proper XEP-0004 way for answering form @@ -648,7 +648,7 @@ return debug (_("%(player)s win the bid with %(contrat)s") % {'player':best_contrat[0],'contrat':best_contrat[1]}) game_data['contrat'] = best_contrat[1] - + if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre": self.__start_play(room_jid, game_data, profile) game_data['attaquant'] = best_contrat[0] @@ -662,7 +662,7 @@ #the attacker (attaquant) get the chien game_data['hand'][best_contrat[0]].extend(game_data['chien']) del game_data['chien'][:] - + if game_data['contrat'] == "Garde Sans": #The chien go into attaquant's (attacker) levees players_data[best_contrat[0]]['levees'].extend(game_data['chien']) @@ -693,13 +693,13 @@ players_data[elt['player']]['levees'].extend(list_cards) #we add the chien to attaquant's levées for card in list_cards: game_data['hand'][elt['player']].remove(card) - + self.__start_play(room_jid, game_data, profile) - + elif game_data['stage'] == "play": current_player = game_data['players'][game_data['current_player']] cards = TarotCard.from_tuples(self.__xml_to_list(elt)) - + if mess_elt['type'] == 'groupchat': self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile) else: @@ -719,7 +719,7 @@ mess = self.createGameElt(room_jid) playcard_elt = mess.firstChildElement().addChild(elt) self.host.profiles[profile].xmlstream.send(mess) - + #Did everybody played ? played = [players_data[player]['played'] for player in game_data['players']] if all(played): @@ -776,13 +776,13 @@ error (_('Unmanaged error type: %s') % elt['type']) else: error (_('Unmanaged card game element: %s') % elt.name) - + def getHandler(self, profile): return CardGameHandler(self) class CardGameHandler (XMPPHandler): implements(iwokkel.IDisco) - + def __init__(self, plugin_parent): self.plugin_parent = plugin_parent self.host = plugin_parent.host diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_misc_text_commands.py --- a/src/plugins/plugin_misc_text_commands.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_misc_text_commands.py Fri Jan 18 17:55:34 2013 +0100 @@ -89,29 +89,29 @@ def cmd_nick(self, mess_data, profile): """change nickname""" debug("Catched nick command") - + if mess_data['type'] != "groupchat": #/nick command does nothing if we are not on a group chat info("Ignoring /nick command on a non groupchat message") - + return True - + nick = mess_data["unparsed"].strip() room = mess_data["to"] self.host.plugins["XEP-0045"].nick(room,nick,profile) return False - + def cmd_join(self, mess_data, profile): """join a new room (on the same service if full jid is not specified)""" debug("Catched join command") - + if mess_data['type'] != "groupchat": #/leave command does nothing if we are not on a group chat info("Ignoring /join command on a non groupchat message") return True - + if mess_data["unparsed"].strip(): room = self._getRoomJID(mess_data["unparsed"].strip(), mess_data["to"].host) nick = (self.host.plugins["XEP-0045"].getRoomNick(mess_data["to"].userhost(), profile) or @@ -123,14 +123,14 @@ def cmd_leave(self, mess_data, profile): """quit a room""" debug("Catched leave command") - + if mess_data['type'] != "groupchat": #/leave command does nothing if we are not on a group chat info("Ignoring /leave command on a non groupchat message") return True - + if mess_data["unparsed"].strip(): - room = self._getRoomJID(mess_data["unparsed"].strip(), mess_data["to"].host) + room = self._getRoomJID(mess_data["unparsed"].strip(), mess_data["to"].host) else: room = mess_data["to"] @@ -145,14 +145,14 @@ def cmd_title(self, mess_data, profile): """change room's subject""" debug("Catched title command") - + if mess_data['type'] != "groupchat": #/leave command does nothing if we are not on a group chat info("Ignoring /title command on a non groupchat message") return True - + subject = mess_data["unparsed"].strip() - + if subject: room = mess_data["to"] self.host.plugins["XEP-0045"].subject(room, subject, profile) @@ -167,9 +167,9 @@ """activate Parrot mode between 2 entities, in both directions.""" #TODO: these commands must not be hardcoded, an interface should be made # to allow plugins to register simple commands like this. - + debug("Catched parrot command") - + try: link_left_jid = jid.JID(mess_data["unparsed"].strip()) if not link_left_jid.user or not link_left_jid.host: @@ -184,13 +184,13 @@ self.host.plugins["EXP-PARROT"].addParrot(link_right_jid, link_left_jid, profile) self._feedBack("Parrot mode activated for %s" % (unicode(link_left_jid),), mess_data, profile) - + return False def cmd_unparrot(self, mess_data, profile): """remove Parrot mode between 2 entities, in both directions.""" debug("Catched unparrot command") - + try: link_left_jid = jid.JID(mess_data["unparsed"].strip()) if not link_left_jid.user or not link_left_jid.host: @@ -205,7 +205,7 @@ self.host.plugins["EXP-PARROT"].removeParrot(link_right_jid, profile) self._feedBack("Parrot mode deactivated for %s and %s" % (unicode(link_left_jid), unicode(link_right_jid)), mess_data, profile) - + return False def cmd_help(self, mess_data, profile): @@ -213,7 +213,7 @@ commands=filter(lambda method: method.startswith('cmd_'), dir(self)) longuest = max([len(command) for command in commands]) help_cmds = [] - + for command in commands: method = getattr(self, command) try: @@ -223,7 +223,7 @@ spaces = (longuest - len(command)) * ' ' help_cmds.append(" /%s: %s %s" % (command[4:], spaces, help_str)) - help_mess = _(u"Text commands available:\n%s") % (u'\n'.join(help_cmds),) + help_mess = _(u"Text commands available:\n%s") % (u'\n'.join(help_cmds),) self._feedBack(help_mess, mess_data, profile) - + diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_misc_xmllog.py --- a/src/plugins/plugin_misc_xmllog.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_misc_xmllog.py Fri Jan 18 17:55:34 2013 +0100 @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- """ -SàT plugin for managing raw XML log +SàT plugin for managing raw XML log Copyright (C) 2011 Jérôme Poisson (goffi@goffi.org) This program is free software: you can redistribute it and/or modify @@ -50,10 +50,10 @@ def dataReceived(self, data): self._host.bridge.xmlLog("IN", data.decode('utf-8'), self._profile) return XmlStream.dataReceived(self, data) - + class XmlLog(): - + params = """ @@ -67,18 +67,18 @@ def __init__(self, host): info(_("Plugin XML Log initialization")) self.host = host - + #parameters host.memory.importParams(self.params) - + #bridge host.bridge.addSignal("xmlLog", ".plugin", signature='sss') #args: direction("IN" or "OUT"), xml_data, profile - + do_log = self.host.memory.getParamA("Xml log", "Debug") if do_log: info(_("XML log activated")) host.trigger.add("XML Initialized", self.logXml) - + def logXml(self, xmlstream, profile): xmlstream.__class__ = LoggingXmlStream xmlstream._profile = profile diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0020.py --- a/src/plugins/plugin_xep_0020.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0020.py Fri Jan 18 17:55:34 2013 +0100 @@ -48,7 +48,7 @@ def __init__(self, host): info(_("Plugin XEP_0020 initialization")) - + def getHandler(self, profile): return XEP_0020_handler() @@ -106,7 +106,7 @@ class XEP_0020_handler(XMPPHandler): implements(iwokkel.IDisco) - + def getDiscoInfo(self, requestor, target, nodeIdentifier=''): return [disco.DiscoFeature(NS_FEATURE_NEG)] diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0045.py --- a/src/plugins/plugin_xep_0045.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0045.py Fri Jan 18 17:55:34 2013 +0100 @@ -106,7 +106,7 @@ # we have a nickname conflict, we try again with "_" suffixed to current nickname nick += '_' return self.clients[profile].join(room_jid, nick, history_options, password).addCallbacks(self.__room_joined, self.__err_joining_room, callbackKeywords={'profile':profile}, errbackArgs=[room_jid, nick, history_options, password, profile]) - + mess = _("Error when joining the room") error (mess) self.host.bridge.newAlert(mess, _("Group chat error"), "ERROR", profile) @@ -131,14 +131,14 @@ if not self.__check_profile(profile) or not self.clients[profile].joined_rooms.has_key(room_jid_s): return '' return self.clients[profile].joined_rooms[room_jid_s].nick - + def isNickInRoom(self, room_jid, nick, profile): """Tell if a nick is currently present in a room""" profile = self.host.memory.getProfileName(profile) if not self.__check_profile(profile): raise exceptions.UnknownProfileError("Unknown or disconnected profile") if not self.clients[profile].joined_rooms.has_key(room_jid.userhost()): - raise UnknownRoom("This room has not been joined") + raise UnknownRoom("This room has not been joined") return self.clients[profile].joined_rooms[room_jid.userhost()].inRoster(nick) def getRoomsSubjects(self, profile_key='@DEFAULT@'): @@ -152,7 +152,7 @@ """Return unique name for room, avoiding collision""" #TODO: we should use #RFC-0045 10.1.4 when available here #TODO: we should be able to select the MUC service here - return uuid.uuid1() + return uuid.uuid1() def join(self, room_jid, nick, options, profile_key='@DEFAULT@'): def _errDeferred(exc_obj = Exception, txt='Error while joining room'): @@ -162,15 +162,15 @@ profile = self.host.memory.getProfileName(profile_key) if not self.__check_profile(profile): - return _errDeferred() + return _errDeferred() if self.clients[profile].joined_rooms.has_key(room_jid.userhost()): warning(_('%(profile)s is already in room %(room_jid)s') % {'profile':profile, 'room_jid':room_jid.userhost()}) - return _errDeferred() + return _errDeferred() info (_("[%(profile)s] is joining room %(room)s with nick %(nick)s") % {'profile':profile,'room':room_jid.userhost(), 'nick':nick}) history_options = options["history"] == "True" if options.has_key("history") else None password = options["password"] if options.has_key("password") else None - + return self.clients[profile].join(room_jid, nick, history_options, password).addCallbacks(self.__room_joined, self.__err_joining_room, callbackKeywords={'profile':profile}, errbackArgs=[room_jid, nick, history_options, password, profile]) def _join(self, room_jid_s, nick, options={}, profile_key='@DEFAULT@'): @@ -193,23 +193,23 @@ if not self.__check_profile(profile): raise exceptions.UnknownProfileError("Unknown or disconnected profile") if not self.clients[profile].joined_rooms.has_key(room_jid.userhost()): - raise UnknownRoom("This room has not been joined") + raise UnknownRoom("This room has not been joined") return self.clients[profile].nick(room_jid, nick) - - def leave(self, room_jid, profile_key): + + def leave(self, room_jid, profile_key): profile = self.host.memory.getProfileName(profile_key) if not self.__check_profile(profile): raise exceptions.UnknownProfileError("Unknown or disconnected profile") if not self.clients[profile].joined_rooms.has_key(room_jid.userhost()): - raise UnknownRoom("This room has not been joined") + raise UnknownRoom("This room has not been joined") return self.clients[profile].leave(room_jid) - def subject(self, room_jid, subject, profile_key): + def subject(self, room_jid, subject, profile_key): profile = self.host.memory.getProfileName(profile_key) if not self.__check_profile(profile): raise exceptions.UnknownProfileError("Unknown or disconnected profile") if not self.clients[profile].joined_rooms.has_key(room_jid.userhost()): - raise UnknownRoom("This room has not been joined") + raise UnknownRoom("This room has not been joined") return self.clients[profile].subject(room_jid, subject) def mucNick(self, room_jid_s, nick, profile_key='@DEFAULT@'): @@ -227,7 +227,7 @@ class SatMUCClient (muc.MUCClient): #implements(iwokkel.IDisco) - + def __init__(self, plugin_parent): self.plugin_parent = plugin_parent self.host = plugin_parent.host @@ -240,7 +240,7 @@ def subject(self, room, subject): return muc.MUCClientProtocol.subject(self, room, subject) - + def unavailableReceived(self, presence): #XXX: we override this method to manage nickname change #TODO: feed this back to Wokkel @@ -274,9 +274,9 @@ debug (_("user %(nick)s has joined room (%(room_id)s)") % {'nick':user.nick, 'room_id':room.occupantJID.userhost()}) if not self.host.trigger.point("MUC user joined", room, user, self.parent.profile): return - user_data={'entity':user.entity.full() if user.entity else '', 'affiliation':user.affiliation, 'role':user.role} + user_data={'entity':user.entity.full() if user.entity else '', 'affiliation':user.affiliation, 'role':user.role} self.host.bridge.roomUserJoined(room.roomJID.userhost(), user.nick, user_data, self.parent.profile) - + def userLeftRoom(self, room, user): if user.nick == room.nick: # we left the room @@ -288,7 +288,7 @@ self.host.bridge.roomLeft(room.roomJID.userhost(), self.parent.profile) else: debug (_("user %(nick)s left room (%(room_id)s)") % {'nick':user.nick, 'room_id':room.occupantJID.userhost()}) - user_data={'entity':user.entity.full() if user.entity else '', 'affiliation':user.affiliation, 'role':user.role} + user_data={'entity':user.entity.full() if user.entity else '', 'affiliation':user.affiliation, 'role':user.role} self.host.bridge.roomUserLeft(room.roomJID.userhost(), user.nick, user_data, self.parent.profile) def userChangedNick(self, room, user, new_nick): @@ -305,10 +305,10 @@ #def connectionInitialized(self): #pass - + #def getDiscoInfo(self, requestor, target, nodeIdentifier=''): #return [disco.DiscoFeature(NS_VCARD)] #def getDiscoItems(self, requestor, target, nodeIdentifier=''): #return [] - + diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0047.py --- a/src/plugins/plugin_xep_0047.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0047.py Fri Jan 18 17:55:34 2013 +0100 @@ -72,13 +72,13 @@ if not client: raise ProfileNotInCacheError client.xep_0047_current_stream = {} #key: stream_id, value: data(dict) - + def _timeOut(self, sid, profile): """Delecte current_stream id, called after timeout @param id: id of client.xep_0047_current_stream""" info(_("In-Band Bytestream: TimeOut reached for id %s [%s]") % (sid, profile)) self._killId(sid, False, "TIMEOUT", profile) - + def _killId(self, sid, success=False, failure_reason="UNKNOWN", profile=None): """Delete an current_stream id, clean up associated observers @param sid: id of client.xep_0047_current_stream""" @@ -96,18 +96,18 @@ client.xep_0047_current_stream[sid]['timer'].cancel() if client.xep_0047_current_stream[sid].has_key("size"): self.host.removeProgressCB(sid, profile) - + file_obj = client.xep_0047_current_stream[sid]['file_obj'] success_cb = client.xep_0047_current_stream[sid]['success_cb'] failure_cb = client.xep_0047_current_stream[sid]['failure_cb'] - + del client.xep_0047_current_stream[sid] if success: success_cb(sid, file_obj, NS_IBB, profile) else: failure_cb(sid, file_obj, NS_IBB, failure_reason, profile) - + def getProgress(self, sid, data, profile): """Fill data with position of current transfer""" client = self.host.getClient(profile) @@ -119,7 +119,7 @@ data["size"] = str(client.xep_0047_current_stream[sid]["size"]) except: pass - + def prepareToReceive(self, from_jid, sid, file_obj, size, success_cb, failure_cb, profile): """Called when a bytestream is imminent @param from_jid: jid of the sender @@ -174,7 +174,7 @@ #we save the xmlstream, events and observer data to allow observer removal client.xep_0047_current_stream[sid]["event_data"] = event_data = (IBB_MESSAGE_DATA if stanza=='message' else IBB_IQ_DATA) % sid - client.xep_0047_current_stream[sid]["observer_cb"] = observer_cb = self.messageData if stanza=='message' else self.iqData + client.xep_0047_current_stream[sid]["observer_cb"] = observer_cb = self.messageData if stanza=='message' else self.iqData event_close = IBB_CLOSE % sid #we now set the stream observer to look after data packet client.xmlstream.addObserver(event_data, observer_cb, profile = profile) @@ -207,16 +207,16 @@ if not client: raise ProfileNotInCacheError data_elt = IQ.firstChildElement() - + if self._manageDataElt(data_elt, 'iq', IQ['id'], jid.JID(IQ['from']), profile): #and send a success answer result = domish.Element((None, 'iq')) result['type'] = 'result' result['id'] = IQ['id'] result['to'] = IQ['from'] - + client.xmlstream.send(result) - + def messageData(self, message_elt, profile): data_elt = message_elt.firstChildElement() sid = message_elt.getAttribute('id','') @@ -272,7 +272,7 @@ result = domish.Element((None, 'iq')) result['type'] = 'result' result['id'] = iq_id - result['to'] = to_jid + result['to'] = to_jid error_el = result.addElement('error') error_el['type'] = 'cancel' error_el.addElement(('urn:ietf:params:xml:ns:xmpp-stanzas','not-acceptable')) @@ -323,10 +323,10 @@ warning(_("Transfer failed")) self.terminateStream(sid, "IQ_ERROR") return - + if data['timer'].active(): data['timer'].cancel() - + buffer = data["file_obj"].read(data["block_size"]) if buffer: next_iq_elt = jabber_client.IQ(client.xmlstream,'set') @@ -366,10 +366,10 @@ class XEP_0047_handler(XMPPHandler): implements(iwokkel.IDisco) - + def __init__(self,parent): self.plugin_parent = parent - + def connectionInitialized(self): self.xmlstream.addObserver(IBB_OPEN, self.plugin_parent.streamOpening, profile = self.parent.profile) diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0054.py --- a/src/plugins/plugin_xep_0054.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0054.py Fri Jan 18 17:55:34 2013 +0100 @@ -90,9 +90,9 @@ x_elt = domish.Element((NS_VCARD_UPDATE, 'x')) x_elt.addElement('photo', content=self.avatars_cache[client.jid.userhost()]) presence_elt.addChild(x_elt) - + return True - + def _fillCachedValues(self, result, client): #FIXME: this is really suboptimal, need to be reworked # the current naive approach keeps a map between all jids of all profiles @@ -101,11 +101,11 @@ for _jid in client.roster.getBareJids() + [client.jid.userhost()]: if _jid in self.avatars_cache: self.host.memory.updateEntityData(jid.JID(_jid), "avatar", self.avatars_cache[_jid], client.profile) - + def profileConnected(self, profile): client = self.host.getClient(profile) client.roster.got_roster.addCallback(self._fillCachedValues, client) - + def update_cache(self, jid, name, value, profile): """update cache value - save value in memory in case of change @@ -122,7 +122,7 @@ self.host.memory.updateEntityData(jid, name, value, profile) if name == "avatar": self.avatars_cache[jid.userhost()] = value - + def get_cache(self, jid, name, profile): """return cached value for jid @param jid: target contact @@ -158,7 +158,7 @@ """Convert a VCard to a dict, and save binaries""" debug (_("parsing vcard")) dictionary = {} - + for elem in vcard.elements(): if elem.name == 'FN': dictionary['fullname'] = unicode(elem) @@ -170,7 +170,7 @@ elif elem.name == 'EMAIL': dictionary['email'] = unicode(elem) elif elem.name == 'BDAY': - dictionary['birthday'] = unicode(elem) + dictionary['birthday'] = unicode(elem) elif elem.name == 'PHOTO': dictionary["avatar"] = yield threads.deferToThread(self.save_photo, elem) if not dictionary["avatar"]: #can happen in case of e.g. empty photo elem @@ -202,7 +202,7 @@ """Called when something is wrong with registration""" error (_("Can't find VCard of %s") % failure.value.stanza['from']) self.host.bridge.actionResult("SUPPRESS", failure.value.stanza['id'], {}, profile) #FIXME: maybe an error message would be better - + def getCard(self, target_s, profile_key='@DEFAULT@'): """Ask server for VCard @param target_s: jid from which we want the VCard @@ -219,7 +219,7 @@ reg_request["to"] = to_jid.userhost() reg_request.addElement('vCard', NS_VCARD) reg_request.send(to_jid.userhost()).addCallbacks(self.vcard_ok, self.vcard_err, callbackArgs=[profile], errbackArgs=[profile]) - return reg_request["id"] + return reg_request["id"] def getAvatarFile(self, avatar_hash): """Give the full path of avatar from hash @@ -258,38 +258,38 @@ client = self.host.getClient(profile_key) if not client: raise exceptions.NotConnectedProfileError(_('Trying to set avatar for a non-existant or not connected profile')) - + vcard_set = IQ(client.xmlstream,'set') d = threads.deferToThread(self._buildSetAvatar, vcard_set, filepath) - + def elementBuilt(result): """Called once the image is at the right size/format, and the vcard set element is build""" set_avatar_elt, img_hash = result self.avatars_cache[client.jid.userhost()] = img_hash # we need to update the hash, so we can send a new presence - # element with the right hash + # element with the right hash return set_avatar_elt.send().addCallback(lambda ignore: client.presence.available()) - + d.addCallback(elementBuilt) - + return d class XEP_0054_handler(XMPPHandler): implements(iwokkel.IDisco) - + def __init__(self, plugin_parent): self.plugin_parent = plugin_parent self.host = plugin_parent.host def connectionInitialized(self): self.xmlstream.addObserver(VCARD_UPDATE, self.update) - + def getDiscoInfo(self, requestor, target, nodeIdentifier=''): return [disco.DiscoFeature(NS_VCARD)] def getDiscoItems(self, requestor, target, nodeIdentifier=''): return [] - + def update(self, presence): """Request for VCard's nickname return the cached nickname if exists, else get VCard diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0060.py --- a/src/plugins/plugin_xep_0060.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0060.py Fri Jan 18 17:55:34 2013 +0100 @@ -92,7 +92,7 @@ def publish(self, service, nodeIdentifier, items=None, profile_key='@DEFAULT@'): profile,client = self.__getClientNProfile(profile_key, 'publish item') - return client.publish(service, nodeIdentifier, items, client.parent.jid) + return client.publish(service, nodeIdentifier, items, client.parent.jid) def getItems(self, service, node, max_items=None, sub_id=None, profile_key='@DEFAULT@'): profile,client = self.__getClientNProfile(profile_key, 'get items') @@ -105,7 +105,7 @@ def setOptions(self, service, nodeIdentifier, subscriber, options, subscriptionIdentifier=None, profile_key='@DEFAULT@'): profile,client = self.__getClientNProfile(profile_key, 'set options') return client.setOptions(service, nodeIdentifier, subscriber, options, subscriptionIdentifier) - + def createNode(self, service, nodeIdentifier, options, profile_key='@DEFAULT@'): profile,client = self.__getClientNProfile(profile_key, 'create node') return client.createNode(service, nodeIdentifier, options) @@ -113,12 +113,12 @@ def deleteNode(self, service, nodeIdentifier, profile_key='@DEFAULT@'): profile,client = self.__getClientNProfile(profile_key, 'delete node') return client.deleteNode(service, nodeIdentifier) - + def subscribe(self, service, nodeIdentifier, sub_jid = None, options=None, profile_key='@DEFAULT@'): profile,client = self.__getClientNProfile(profile_key, 'subscribe node') - return client.subscribe(service, nodeIdentifier, sub_jid or client.parent.jid.userhostJID(), options=options) + return client.subscribe(service, nodeIdentifier, sub_jid or client.parent.jid.userhostJID(), options=options) - + class SatPubSubClient(pubsub.PubSubClient): implements(disco.IDisco) @@ -129,7 +129,7 @@ def connectionInitialized(self): pubsub.PubSubClient.connectionInitialized(self) - + def itemsReceived(self, event): if not self.host.trigger.point("PubSubItemsReceived", event, self.parent.profile): return @@ -149,7 +149,7 @@ _disco_info = [] self.host.trigger.point("PubSub Disco Info", _disco_info, self.parent.profile) return _disco_info - + def getDiscoItems(self, requestor, target, nodeIdentifier=''): return [] diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0065.py --- a/src/plugins/plugin_xep_0065.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0065.py Fri Jan 18 17:55:34 2013 +0100 @@ -32,7 +32,7 @@ Here is a copy of the original license: -Copyright (C) +Copyright (C) 2002-2004 Dave Smith (dizzyd@jabber.org) 2007-2008 Fabio Forno (xmpp:ff@jabber.bluendo.com) @@ -172,7 +172,7 @@ # Trim off front of the buffer self.buf = self.buf[nmethod+2:] - + # Check for supported auth mechs for m in self.supportedAuthMechs: if m in methods: @@ -219,7 +219,7 @@ result = struct.pack('!BBBBIH', SOCKS5_VER, errorcode, 0, 1, 0, 0) self.transport.write(result) self.transport.loseConnection() - + def _parseRequest(self): debug("_parseRequest") try: @@ -235,7 +235,7 @@ if self.addressType == ADDR_IPV4: addr, port = struct.unpack('!IH', self.buf[4:10]) self.buf = self.buf[10:] - elif self.addressType == ADDR_DOMAINNAME: + elif self.addressType == ADDR_DOMAINNAME: nlen = ord(self.buf[4]) addr, port = struct.unpack('!%dsH' % nlen, self.buf[5:]) self.buf = self.buf[7 + len(addr):] @@ -282,7 +282,7 @@ if self.addressType == ADDR_IPV4: addr, port = struct.unpack('!IH', self.buf[4:10]) self.buf = self.buf[10:] - elif self.addressType == ADDR_DOMAINNAME: + elif self.addressType == ADDR_DOMAINNAME: nlen = ord(self.buf[4]) addr, port = struct.unpack('!%dsH' % nlen, self.buf[5:]) self.buf = self.buf[7 + len(addr):] @@ -308,7 +308,7 @@ def connectionMade(self): debug("connectionMade (mode = %s)" % "requester" if isinstance(self.factory, Socks5ServerFactory) else "target") - + if isinstance(self.factory, Socks5ClientFactory): self.sid = self.factory.sid self.profile = self.factory.profile @@ -318,7 +318,7 @@ def connectRequested(self, addr, port): debug("connectRequested") - + # Check that this session is expected if not self.factory.hash_sid_map.has_key(addr): #no: we refuse it @@ -336,7 +336,7 @@ """Callback called when the result iq is received""" d = self.beginFileTransfer(file_obj, self.transport) d.addCallback(self.fileTransfered) - + def fileTransfered(self, d): info(_("File transfer completed, closing connection")) self.transport.loseConnection() @@ -351,10 +351,10 @@ ADDR_DOMAINNAME, len(remotehost), remotehost, remoteport) self.transport.write(result) self.state = STATE_READY - + def bindRequested(self, addr, port): pass - + def authenticateUserPass(self, user, passwd): debug("User/pass: %s/%s", user, passwd) return True @@ -440,7 +440,7 @@ class XEP_0065(): - + NAMESPACE = NS_BS params = """ @@ -463,10 +463,10 @@ def __init__(self, host): info(_("Plugin XEP_0065 initialization")) - + #session data self.hash_sid_map = {} #key: hash of the transfer session, value: (session id, profile) - + self.host = host debug(_("registering")) self.server_factory = Socks5ServerFactory(host, self.hash_sid_map, lambda sid, success, profile: self._killId(sid, success, profile=profile)) @@ -475,13 +475,13 @@ host.memory.importParams(XEP_0065.params) host.memory.setDefault("IP", "File Transfer", self.getExternalIP) port = int(self.host.memory.getParamA("Port", "File Transfer")) - + info(_("Launching Socks5 Stream server on port %d"), port) reactor.listenTCP(port, self.server_factory) - + def getHandler(self, profile): - return XEP_0065_handler(self) - + return XEP_0065_handler(self) + def profileConnected(self, profile): client = self.host.getClient(profile) if not client: @@ -503,13 +503,13 @@ data["size"] = str(client.xep_0065_current_stream[sid]["size"]) except: pass - + def _timeOut(self, sid, profile): """Delecte current_stream id, called after timeout @param id: id of client.xep_0065_current_stream""" info(_("Socks5 Bytestream: TimeOut reached for id %s [%s]") % (sid, profile)) self._killId(sid, False, "TIMEOUT", profile) - + def _killId(self, sid, success=False, failure_reason="UNKNOWN", profile=None): """Delete an current_stream id, clean up associated observers @param sid: id of client.xep_0065_current_stream""" @@ -528,11 +528,11 @@ client.xep_0065_current_stream[sid]['timer'].cancel() if client.xep_0065_current_stream[sid].has_key("size"): self.host.removeProgressCB(sid, profile) - + file_obj = client.xep_0065_current_stream[sid]['file_obj'] success_cb = client.xep_0065_current_stream[sid]['success_cb'] failure_cb = client.xep_0065_current_stream[sid]['failure_cb'] - + session_hash = client.xep_0065_current_stream[sid].get('hash') del client.xep_0065_current_stream[sid] if session_hash in self.hash_sid_map: @@ -558,14 +558,14 @@ if not client: error(_("Unknown profile, this should not happen")) raise ProfileNotInCacheError - + if length != None: error(_('stream length not managed yet')) return - + profile_jid = client.jid xmlstream = client.xmlstream - + data = client.xep_0065_current_stream[sid] = {} data["timer"] = reactor.callLater(TIMEOUT, self._timeOut, sid, profile) data["file_obj"] = file_obj @@ -615,10 +615,10 @@ except KeyError: error(_("Internal error, can't do transfer")) return - + if timer.active(): timer.cancel() - + profile_jid, xmlstream = self.host.getJidNStream(profile) query_elt = iq_elt.firstChildElement() streamhost_elts = filter(lambda elt: elt.name == 'streamhost-used', query_elt.elements()) @@ -686,23 +686,23 @@ data["timer"] = reactor.callLater(TIMEOUT, self._timeOut, sid, profile) data["success_cb"] = success_cb data["failure_cb"] = failure_cb - - + + def streamQuery(self, iq_elt, profile): """Get file using byte stream""" debug(_("BS stream query")) client = self.host.getClient(profile) - + if not client: raise ProfileNotInCacheError - + xmlstream = client.xmlstream iq_elt.handled = True query_elt = iq_elt.firstChildElement() sid = query_elt.getAttribute("sid") streamhost_elts = filter(lambda elt: elt.name == 'streamhost', query_elt.elements()) - + if not sid in client.xep_0065_current_stream: warning(_("Ignoring unexpected BS transfer: %s" % sid)) self.sendNotAcceptableError(iq_elt['id'], iq_elt['from'], xmlstream) @@ -731,7 +731,7 @@ info (_("Stream proposed: host=[%(host)s] port=[%(port)s]") % {'host':sh_host, 'port':sh_port}) factory = Socks5ClientFactory(client.xep_0065_current_stream, sid, iq_elt["id"], self.activateStream, lambda sid, success, profile: self._killId(sid, success, profile=profile), profile=profile) reactor.connectTCP(sh_host, int(sh_port), factory) - + def activateStream(self, sid, iq_id, profile): client = self.host.getClient(profile) if not client: @@ -757,7 +757,7 @@ result = domish.Element((None, 'iq')) result['type'] = 'result' result['id'] = iq_id - result['to'] = to_jid + result['to'] = to_jid error_el = result.addElement('error') error_el['type'] = 'modify' error_el.addElement(('urn:ietf:params:xml:ns:xmpp-stanzas','not-acceptable')) @@ -771,7 +771,7 @@ result = domish.Element((None, 'iq')) result['type'] = 'result' result['id'] = iq_id - result['to'] = to_jid + result['to'] = to_jid error_el = result.addElement('error') error_el['type'] = 'cancel' error_el.addElement(('urn:ietf:params:xml:ns:xmpp-stanzas','bad-request')) @@ -779,7 +779,7 @@ class XEP_0065_handler(XMPPHandler): implements(iwokkel.IDisco) - + def __init__(self, plugin_parent): self.plugin_parent = plugin_parent self.host = plugin_parent.host @@ -805,7 +805,7 @@ proxy = self.host.memory.setParam("Proxy host", streamhost_elt.getAttribute("host",""), "File Transfer", self.parent.profile) proxy = self.host.memory.setParam("Proxy port", streamhost_elt.getAttribute("port",""), "File Transfer", self.parent.profile) - + def connectionInitialized(self): def after_init(ignore): proxy_ent = self.host.memory.getServerServiceEntity("proxy", "bytestreams", self.parent.profile) @@ -823,7 +823,7 @@ proxy = self.host.memory.getParamA("Proxy", "File Transfer", profile_key = self.parent.profile) if not proxy: self.parent.client_initialized.addCallback(after_init) - + def getDiscoInfo(self, requestor, target, nodeIdentifier=''): diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0077.py --- a/src/plugins/plugin_xep_0077.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0077.py Fri Jan 18 17:55:34 2013 +0100 @@ -39,18 +39,18 @@ } class XEP_0077(): - + def __init__(self, host): info(_("Plugin XEP_0077 initialization")) self.host = host self.triggers = {} #used by other protocol (e.g. XEP-0100) to finish registration. key = target_jid host.bridge.addMethod("in_band_register", ".plugin", in_sign='ss', out_sign='s', method=self.in_band_register) host.bridge.addMethod("in_band_submit", ".plugin", in_sign='ssa(ss)s', out_sign='s', method=self.in_band_submit) - + def addTrigger(self, target, cb, profile): """Add a callback which is called when registration to target is successful""" self.triggers[target] = (cb, profile) - + def reg_ok(self, answer, profile): """Called after the first get IQ""" try: @@ -62,7 +62,7 @@ answer_type = "ERROR" self.host.bridge.actionResult(answer_type, answer['id'], answer_data, profile) return - + form = data_form.Form.fromElement(x_elem) xml_data = dataForm2xml(form) self.host.bridge.actionResult("XMLUI", answer['id'], {"target":answer["from"], "type":"registration", "xml":xml_data}, profile) @@ -75,13 +75,13 @@ answer_data={"message":"%s [code: %s]" % (failure.value.condition, unicode(failure.value))} answer_type = "ERROR" self.host.bridge.actionResult(answer_type, failure.value.stanza['id'], answer_data, profile) - + def unregistrationAnswer(self, answer, profile): debug (_("registration answer: %s") % answer.toXml()) answer_type = "SUCCESS" answer_data={"message":_("Your are now unregistred")} self.host.bridge.actionResult(answer_type, answer['id'], answer_data, profile) - + def unregistrationFailure(self, failure, profile): info (_("Unregistration failure: %s") % str(failure.value)) answer_type = "ERROR" @@ -89,7 +89,7 @@ answer_data['reason'] = 'unknown' answer_data={"message":_("Unregistration failed: %s") % failure.value.condition} self.host.bridge.actionResult(answer_type, failure.value.stanza['id'], answer_data, profile) - + def registrationAnswer(self, answer, profile): debug (_("registration answer: %s") % answer.toXml()) answer_type = "SUCCESS" @@ -99,7 +99,7 @@ callback,profile = self.triggers[answer["from"]] callback(answer["from"], profile) del self.triggers[answer["from"]] - + def registrationFailure(self, failure, profile): info (_("Registration failure: %s") % str(failure.value)) print failure.value.stanza.toXml() @@ -120,10 +120,10 @@ id, deferred = self.host.submitForm(action, target, fields, profile) if action == 'CANCEL': deferred.addCallbacks(self.unregistrationAnswer, self.unregistrationFailure, callbackArgs=[profile], errbackArgs=[profile]) - else: + else: deferred.addCallbacks(self.registrationAnswer, self.registrationFailure, callbackArgs=[profile], errbackArgs=[profile]) return id - + def in_band_register(self, target, profile_key='@DEFAULT@'): """register to a target JID""" client = self.host.getClient(profile_key) @@ -137,4 +137,4 @@ reg_request["to"] = to_jid.full() reg_request.addElement('query', NS_REG) reg_request.send(to_jid.full()).addCallbacks(self.reg_ok, self.reg_err, callbackArgs=[client.profile], errbackArgs=[client.profile]) - return reg_request["id"] + return reg_request["id"] diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0095.py --- a/src/plugins/plugin_xep_0095.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0095.py Fri Jan 18 17:55:34 2013 +0100 @@ -58,9 +58,9 @@ info(_("Plugin XEP_0095 initialization")) self.host = host self.si_profiles = {} #key: SI profile, value: callback - + def getHandler(self, profile): - return XEP_0095_handler(self) + return XEP_0095_handler(self) def registerSIProfile(self, si_profile, callback): """Add a callback for a SI Profile @@ -107,14 +107,14 @@ @param to_jid: recipient @param profile: %(doc_profile)s""" self.sendError(iq_id, to_jid, 400, 'cancel', profile=profile) - + def sendFailedError(self, iq_id, to_jid, profile): """Helper method to send when we transfer failed @param iq_id: IQ id @param to_jid: recipient @param profile: %(doc_profile)s""" self.sendError(iq_id, to_jid, 500, 'cancel', {'custom':'failed'}, profile=profile) #as there is no error code for failed transfer, we use 500 (undefined-condition) - + def sendError(self, iq_id, to_jid, err_code, err_type='cancel', data={}, profile='@NONE@'): """Send IQ error as a result @param iq_id: IQ id @@ -129,7 +129,7 @@ result = domish.Element((None, 'iq')) result['type'] = 'result' result['id'] = iq_id - result['to'] = to_jid + result['to'] = to_jid error_el = result.addElement('error') error_el['err_code'] = str(err_code) error_el['type'] = err_type @@ -162,7 +162,7 @@ result = domish.Element((None, 'iq')) result['type'] = 'result' result['id'] = iq_id - result['to'] = to_jid + result['to'] = to_jid si = result.addElement('si', NS_SI) si.addChild(feature_elt) for elt in misc_elts: @@ -182,9 +182,9 @@ if not xmlstream: error (_('Asking for an non-existant or not connected profile')) return "" - + offer = client.IQ(xmlstream,'set') - sid = str(uuid.uuid4()) + sid = str(uuid.uuid4()) debug (_("Stream Session ID: %s") % offer["id"]) offer["from"] = current_jid.full() @@ -200,10 +200,10 @@ offer.send() return sid, offer - + class XEP_0095_handler(XMPPHandler): implements(iwokkel.IDisco) - + def __init__(self, plugin_parent): self.plugin_parent = plugin_parent self.host = plugin_parent.host diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0096.py --- a/src/plugins/plugin_xep_0096.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0096.py Fri Jan 18 17:55:34 2013 +0100 @@ -57,9 +57,9 @@ def profileConnected(self, profile): client = self.host.getClient(profile) - client._xep_0096_waiting_for_approval = {} #key = id, value = [transfer data, IdelayedCall Reactor timeout, + client._xep_0096_waiting_for_approval = {} #key = id, value = [transfer data, IdelayedCall Reactor timeout, # current stream method, [failed stream methods], profile] - + def _kill_id(self, approval_id, profile): """Delete a waiting_for_approval id, called after timeout @param approval_id: id of _xep_0096_waiting_for_approval""" @@ -69,7 +69,7 @@ del client._xep_0096_waiting_for_approval[approval_id] except KeyError: warning(_("kill id called on a non existant approval id")) - + def transferRequest(self, iq_id, from_jid, si_id, si_mime_type, si_el, profile): """Called when a file transfer is requested @param iq_id: id of the iq request @@ -91,7 +91,7 @@ can_range = False file_elts = filter(lambda elt: elt.name == 'file', si_el.elements()) feature_elts = self.host.plugins["XEP-0020"].getFeatureElt(si_el) - + if file_elts: file_el = file_elts[0] filename = file_el["name"] @@ -108,7 +108,7 @@ warning(_("No file element found")) self.host.plugins["XEP-0095"].sendBadRequestError(iq_id, from_jid, profile) return - + if feature_elts: feature_el = feature_elts[0] form = data_form.Form.fromElement(feature_el.firstChildElement()) @@ -238,7 +238,7 @@ if not feature_elts: warning(_("No feature element")) return - + choosed_options = self.host.plugins["XEP-0020"].getChoosedOptions(feature_elts[0]) try: stream_method = choosed_options["stream-method"] @@ -281,9 +281,9 @@ warning(_("Trying to send a file from an unknown profile")) return "" feature_elt = self.host.plugins["XEP-0020"].proposeFeatures({'stream-method': self.managed_stream_m}) - + file_transfer_elts = [] - + statinfo = os.stat(filepath) file_elt = domish.Element((PROFILE, 'file')) file_elt['name']=os.path.basename(filepath) diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0100.py --- a/src/plugins/plugin_xep_0100.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0100.py Fri Jan 18 17:55:34 2013 +0100 @@ -48,7 +48,7 @@ if self.__gateways[request_id]['__total_items'] == self.__gateways[request_id]['__handled_items']: debug (_("All items checked for id [%s]") % str(request_id)) - + del self.__gateways[request_id]['__total_items'] del self.__gateways[request_id]['__handled_items'] self.host.actionResultExt(request_id,"DICT_DICT",self.__gateways[request_id], profile) @@ -65,14 +65,14 @@ } self.__inc_handled_items(request_id, profile) - + def discoInfoErr(self, failure, entity, request_id, profile): """Something is going wrong with disco""" failure.trap(jab_error.StanzaError,twisted.internet.error.ConnectionLost) error(_("Error when discovering [%(jid)s]: %(error)s") % {'jid':entity.full(), 'error':failure.getErrorMessage()}) self.__inc_handled_items(request_id, profile) - - + + def discoItems(self, disco, request_id, target, client): """Look for items with disco protocol, and ask infos for each one""" #FIXME: target is used as we can't find the original iq node (parent is None) @@ -100,7 +100,7 @@ debug (_("Registration successful, doing the rest")) self.host.addContact(target, profile) self.host.setPresence(target, profile) - + def gatewayRegister(self, action, target, fields, profile_key='@DEFAULT@'): """Register gateway using in-band registration, then log-in to gateway""" profile = self.host.memory.getProfileName(profile_key) diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0115.py --- a/src/plugins/plugin_xep_0115.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0115.py Fri Jan 18 17:55:34 2013 +0100 @@ -71,7 +71,7 @@ def __str__(self): return "%s/%s/%s/%s" % (self.category, self.idType, self.lang, self.name) - + class XEP_0115(): cap_hash = None #capabilities hash is class variable as it is common to all profiles @@ -83,7 +83,7 @@ host.trigger.add("Disco Handled", self.checkHash) self.hash_cache = PersistentBinaryDict(NS_ENTITY_CAPABILITY) #key = hash or jid, value = features self.hash_cache.load() - self.jid_hash = {} #jid to hash mapping, map to a discoInfo features if the hash method is unknown + self.jid_hash = {} #jid to hash mapping, map to a discoInfo features if the hash method is unknown def checkHash(self, profile): if not XEP_0115.cap_hash: @@ -91,7 +91,7 @@ else: self.presenceHack(profile) return True - + def getHandler(self, profile): return XEP_0115_handler(self, profile) @@ -127,7 +127,7 @@ if not client: error ('Requesting hash for an inexistant client') raise HashGenerationError - + def generateHash_2(services, profile): _s=[] byte_identities = [ByteIdentity(identity) for identity in filter(lambda x:isinstance(x,disco.DiscoIdentity),services)] #FIXME: lang must be managed here @@ -146,12 +146,12 @@ XEP_0115.cap_hash = b64encode(sha1(''.join(_s)).digest()) debug(_('Capability hash generated: [%s]') % XEP_0115.cap_hash) self.presenceHack(profile) - + services = client.discoHandler.info(client.jid, client.jid, '').addCallback(generateHash_2, profile) - + class XEP_0115_handler(XMPPHandler): implements(iwokkel.IDisco) - + def __init__(self, plugin_parent, profile): self.plugin_parent = plugin_parent self.host = plugin_parent.host @@ -159,7 +159,7 @@ def connectionInitialized(self): self.xmlstream.addObserver(CAPABILITY_UPDATE, self.update) - + def getDiscoInfo(self, requestor, target, nodeIdentifier=''): return [disco.DiscoFeature(NS_ENTITY_CAPABILITY)] diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0249.py --- a/src/plugins/plugin_xep_0249.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0249.py Fri Jan 18 17:55:34 2013 +0100 @@ -110,7 +110,7 @@ class XEP_0249_handler(XMPPHandler): implements(iwokkel.IDisco) - + def __init__(self, plugin_parent): self.plugin_parent = plugin_parent self.host = plugin_parent.host diff -r 6a718ede8be1 -r 952322b1d490 src/plugins/plugin_xep_0277.py --- a/src/plugins/plugin_xep_0277.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/plugins/plugin_xep_0277.py Fri Jan 18 17:55:34 2013 +0100 @@ -157,7 +157,7 @@ assert(callback) d = self.host.plugins["XEP-0060"].getItems(jid.JID(pub_jid), NS_MICROBLOG, max_items=max_items, profile_key=profile_key) d.addCallback(lambda items: map(self.item2mbdata, items)) - + def setMicroblogAccess(self, access="presence", profile_key='@DEFAULT@'): """Create a microblog node on PEP with given access If the node already exists, it change options @@ -169,7 +169,7 @@ error(_("Can't find profile's jid")) return _options = {OPT_ACCESS_MODEL:access, OPT_PERSIST_ITEMS:1, OPT_MAX_ITEMS:-1, OPT_DELIVER_PAYLOADS:1, OPT_SEND_ITEM_SUBSCRIBE: 1} - + def cb(result): #Node is created with right permission debug(_("Microblog node has now access %s") % access) @@ -188,14 +188,14 @@ change_node_options().addCallback(cb).addErrback(fatal_err) else: fatal_err(s_error) - + def create_node(): return self.host.plugins["XEP-0060"].createNode(_jid.userhostJID(), NS_MICROBLOG, _options, profile_key=profile_key) - + def change_node_options(): return self.host.plugins["XEP-0060"].setOptions(_jid.userhostJID(), NS_MICROBLOG, _jid.userhostJID(), _options, profile_key=profile_key) create_node().addCallback(cb).addErrback(err_cb) - - + + diff -r 6a718ede8be1 -r 952322b1d490 src/sat.sh --- a/src/sat.sh Fri Jan 18 17:55:27 2013 +0100 +++ b/src/sat.sh Fri Jan 18 17:55:34 2013 +0100 @@ -58,4 +58,4 @@ mkdir $log_dir fi -twistd $MAIN_OPTIONS $TAP_PATH$TAP_FILE $ADDITIONAL_OPTIONS +twistd $MAIN_OPTIONS $TAP_PATH$TAP_FILE $ADDITIONAL_OPTIONS diff -r 6a718ede8be1 -r 952322b1d490 src/test/helpers.py --- a/src/test/helpers.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/test/helpers.py Fri Jan 18 17:55:34 2013 +0100 @@ -22,8 +22,8 @@ import __builtin__ from twisted.words.protocols.jabber.jid import JID -TEST_JID_STR = u"test@example.org/SàT" -TEST_JID = JID(u"test@example.org/SàT") +TEST_JID_STR = u"test@example.org/SàT" +TEST_JID = JID(u"test@example.org/SàT") TEST_PROFILE = 'test_profile' class DifferentArgsException(Exception): @@ -35,7 +35,7 @@ def __init__(self): self.bridge = FakeBridge() self.memory = FakeMemory() - self.trigger = FakeTriggerManager() + self.trigger = FakeTriggerManager() class FakeBridge(object): @@ -50,7 +50,7 @@ print "kwargs\n------\n%s (sent)\n%s (wanted)" % (kwargs, check_kwargs) print "--------------------\n\n" raise DifferentArgsException - + setattr(self, name, checkCall) @@ -62,16 +62,16 @@ def addToHistory(self, from_jid, to_jid, message, _type='chat', timestamp=None, profile=None): pass - + def addContact(self, contact_jid, attributes, groups, profile_key='@DEFAULT@'): pass - + def setPresenceStatus(self, contact_jid, show, priority, statuses, profile_key='@DEFAULT@'): pass - + def addWaitingSub(self, type, contact_jid, profile_key): pass - + def delWaitingSub(self, contact_jid, profile_key): pass @@ -79,7 +79,7 @@ def add(self, point_name, callback): pass - + def point(self, point_name, *args, **kwargs): """We always return true to continue the action""" return True diff -r 6a718ede8be1 -r 952322b1d490 src/test/test_core_xmpp.py --- a/src/test/test_core_xmpp.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/test/test_core_xmpp.py Fri Jan 18 17:55:34 2013 +0100 @@ -34,8 +34,8 @@ def setUp(self): self.host = helpers.FakeSAT() - self.client = xmpp.SatXMPPClient(self.host, "test_profile", JID("test@example.org"), "test") - + self.client = xmpp.SatXMPPClient(self.host, "test_profile", JID("test@example.org"), "test") + def test_init(self): """Check that init values are correctly initialised""" self.assertEqual(self.client.profile, "test_profile") @@ -59,7 +59,7 @@ stanza = parseXml(xml) self.host.bridge.expectCall("newMessage", "sender@example.net/house", "test", "chat", u"test@example.org/SàT", profile="test_profile") self.message.onMessage(stanza) - + class SatRosterProtocolTest(unittest.TestCase): def setUp(self): @@ -99,16 +99,16 @@ def test_subscribedReceived(self): self.host.bridge.expectCall("subscribe", "subscribed", helpers.TEST_JID.userhost(), helpers.TEST_PROFILE) self.presence.subscribedReceived(helpers.TEST_JID) - + def test_unsubscribedReceived(self): self.host.bridge.expectCall("subscribe", "unsubscribed", helpers.TEST_JID.userhost(), helpers.TEST_PROFILE) self.presence.unsubscribedReceived(helpers.TEST_JID) - + def test_subscribeReceived(self): self.host.bridge.expectCall("subscribe", "subscribe", helpers.TEST_JID.userhost(), helpers.TEST_PROFILE) self.presence.subscribeReceived(helpers.TEST_JID) - + def test_unsubscribeReceived(self): self.host.bridge.expectCall("subscribe", "unsubscribe", helpers.TEST_JID.userhost(), helpers.TEST_PROFILE) self.presence.unsubscribeReceived(helpers.TEST_JID) - + diff -r 6a718ede8be1 -r 952322b1d490 src/tools/games.py --- a/src/tools/games.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/tools/games.py Fri Jan 18 17:55:34 2013 +0100 @@ -23,7 +23,7 @@ """This library help manage general games (e.g. card games)""" - + suits_order = ['pique', 'coeur', 'trefle', 'carreau', 'atout'] #I have switched the usual order 'trefle' and 'carreau' because card are more easy to see if suit colour change (black, red, black, red) values_order = map(str,range(1,11))+["valet","cavalier","dame","roi"] diff -r 6a718ede8be1 -r 952322b1d490 src/tools/xml_tools.py --- a/src/tools/xml_tools.py Fri Jan 18 17:55:27 2013 +0100 +++ b/src/tools/xml_tools.py Fri Jan 18 17:55:34 2013 +0100 @@ -27,20 +27,20 @@ """This library help manage XML used in SàT (parameters, registration, etc) """ - + def dataForm2xml(form): """Take a data form (xep-0004, Wokkel's implementation) and convert it to a SàT xml""" - + form_ui = XMLUI("form", "vertical") if form.instructions: form_ui.addText('\n'.join(form.instructions), 'instructions') - + labels = filter(lambda field:field.label,form.fieldList) if labels: #if there is no label, we don't need to use pairs form_ui.changeLayout("pairs") - + for field in form.fieldList: if field.fieldType == 'fixed': __field_type = 'text' @@ -53,14 +53,14 @@ else: error (u"FIXME FIXME FIXME: Type [%s] is not managed yet by SàT" % field.fieldType) __field_type = "string" - + if labels: if field.label: form_ui.addLabel(field.label) else: form_ui.addEmpty() - elem = form_ui.addElement(__field_type, field.var, field.value, [option.value for option in field.options]) + elem = form_ui.addElement(__field_type, field.var, field.value, [option.value for option in field.options]) return form_ui.toXml() def tupleList2dataForm(values): @@ -104,7 +104,7 @@ return param_ui.toXml() - + class XMLUI: @@ -140,8 +140,8 @@ self.changeLayout(layout) def __del__(self): - self.doc.unlink() - + self.doc.unlink() + def __createLayout(self, layout, parent=None): """Create a layout element @param type: layout type (cf init doc) @@ -182,7 +182,7 @@ def addEmpty(self, name=None): """Add a multi-lines text""" elem = self.__createElem('empty', name, self.currentLayout) - + def addText(self, text, name=None): """Add a multi-lines text""" elem = self.__createElem('text', name, self.currentLayout) @@ -199,7 +199,7 @@ elem = self.__createElem('string', name, self.currentLayout) if value: elem.setAttribute('value', value) - + def addPassword(self, name=None, value=None): """Add a password box""" elem = self.__createElem('password', name, self.currentLayout) @@ -211,20 +211,20 @@ elem = self.__createElem('textbox', name, self.currentLayout) if value: elem.setAttribute('value', value) - + def addBool(self, name=None, value="true"): """Add a string box""" assert value in ["true","false"] elem = self.__createElem('bool', name, self.currentLayout) elem.setAttribute('value', value) - + def addList(self, options, name=None, value=None, style=set()): """Add a list of choices""" styles = set(style) assert (options) - assert (styles.issubset(['multi'])) + assert (styles.issubset(['multi'])) elem = self.__createElem('list', name, self.currentLayout) - self.addOptions(options, elem) + self.addOptions(options, elem) if value: elem.setAttribute('value', value) for style in styles: @@ -245,7 +245,7 @@ elem.appendChild(fback_el) - + def addElement(self, type, name = None, value = None, options = None, callback_id = None): """Convenience method to add element, the params correspond to the ones in addSomething methods""" if type == 'empty': @@ -299,7 +299,7 @@ self.parentTabsLayout.appendChild(cat) def toXml(self): - """return the XML representation of the panel""" + """return the XML representation of the panel""" return self.doc.toxml() @@ -325,4 +325,4 @@ tmp = domish.Element((None, "s")) tmp.addRawXml(s.replace('\n','').replace('\t','')) parser.parse(tmp.toXml().encode('utf-8')) - return self.result.firstChildElement() + return self.result.firstChildElement()