comparison libervia.tac @ 258:53c7f0237f1e

removed trailing spaces in libervia.tac
author Goffi <goffi@goffi.org>
date Fri, 15 Nov 2013 15:01:29 +0100
parents 24335e82fef0
children a20815c75c15
comparison
equal deleted inserted replaced
257:377de26d5bc2 258:53c7f0237f1e
100 100
101 def waitForId(self, callback, action_id, profile, *args, **kwargs): 101 def waitForId(self, callback, action_id, profile, *args, **kwargs):
102 """Wait for an action result 102 """Wait for an action result
103 @param callback: method to call when action gave a result back 103 @param callback: method to call when action gave a result back
104 @param action_id: action_id to wait for 104 @param action_id: action_id to wait for
105 @param profile: %(doc_profile)s 105 @param profile: %(doc_profile)s
106 @param *args: additional argument to pass to callback 106 @param *args: additional argument to pass to callback
107 @param **kwargs: idem""" 107 @param **kwargs: idem"""
108 action_tuple = (action_id, profile) 108 action_tuple = (action_id, profile)
109 self.waiting_ids[action_tuple] = (callback, args, kwargs) 109 self.waiting_ids[action_tuple] = (callback, args, kwargs)
110 reactor.callLater(self.ID_LIFETIME, self.purgeID, action_tuple) 110 reactor.callLater(self.ID_LIFETIME, self.purgeID, action_tuple)
145 Exception("Multiple return arguments not supported") 145 Exception("Multiple return arguments not supported")
146 d.callback(args[0]) 146 d.callback(args[0])
147 147
148 def _errback(result): 148 def _errback(result):
149 d.errback(Failure(unicode(result))) 149 d.errback(Failure(unicode(result)))
150 150
151 kwargs["callback"] = d.callback 151 kwargs["callback"] = d.callback
152 kwargs["errback"] = _errback 152 kwargs["errback"] = _errback
153 getattr(self.sat_host.bridge, method_name)(*args, **kwargs) 153 getattr(self.sat_host.bridge, method_name)(*args, **kwargs)
154 return d 154 return d
155 155
174 """Return the jid of the profile""" 174 """Return the jid of the profile"""
175 sat_session = ISATSession(self.session) 175 sat_session = ISATSession(self.session)
176 profile = sat_session.profile 176 profile = sat_session.profile
177 sat_session.jid = JID(self.sat_host.bridge.getParamA("JabberID", "Connection", profile_key=profile)) 177 sat_session.jid = JID(self.sat_host.bridge.getParamA("JabberID", "Connection", profile_key=profile))
178 return sat_session.jid.full() 178 return sat_session.jid.full()
179 179
180 def jsonrpc_disconnect(self): 180 def jsonrpc_disconnect(self):
181 """Disconnect the profile""" 181 """Disconnect the profile"""
182 sat_session = ISATSession(self.session) 182 sat_session = ISATSession(self.session)
183 profile = sat_session.profile 183 profile = sat_session.profile
184 self.sat_host.bridge.disconnect(profile) 184 self.sat_host.bridge.disconnect(profile)
185 185
186 def jsonrpc_getContacts(self): 186 def jsonrpc_getContacts(self):
187 """Return all passed args.""" 187 """Return all passed args."""
188 profile = ISATSession(self.session).profile 188 profile = ISATSession(self.session).profile
189 return self.sat_host.bridge.getContacts(profile) 189 return self.sat_host.bridge.getContacts(profile)
190 190
213 self.sat_host.bridge.updateContact(entity, name, groups, profile) 213 self.sat_host.bridge.updateContact(entity, name, groups, profile)
214 214
215 def jsonrpc_getWaitingSub(self): 215 def jsonrpc_getWaitingSub(self):
216 """Return list of room already joined by user""" 216 """Return list of room already joined by user"""
217 profile = ISATSession(self.session).profile 217 profile = ISATSession(self.session).profile
218 return self.sat_host.bridge.getWaitingSub(profile) 218 return self.sat_host.bridge.getWaitingSub(profile)
219 219
220 def jsonrpc_setStatus(self, status): 220 def jsonrpc_setStatus(self, status):
221 """Change the status""" 221 """Change the status"""
222 profile = ISATSession(self.session).profile 222 profile = ISATSession(self.session).profile
223 self.sat_host.bridge.setPresence('', '', 0, {'':status}, profile) 223 self.sat_host.bridge.setPresence('', '', 0, {'':status}, profile)
224 224
225 225
226 def jsonrpc_sendMessage(self, to_jid, msg, subject, _type, options={}): 226 def jsonrpc_sendMessage(self, to_jid, msg, subject, _type, options={}):
227 """send message""" 227 """send message"""
228 profile = ISATSession(self.session).profile 228 profile = ISATSession(self.session).profile
229 return self.sat_host.bridge.sendMessage(to_jid, msg, subject, _type, options, profile) 229 return self.sat_host.bridge.sendMessage(to_jid, msg, subject, _type, options, profile)
230 230
253 """ 253 """
254 profile = ISATSession(self.session).profile 254 profile = ISATSession(self.session).profile
255 if node and text: 255 if node and text:
256 return self.sat_host.bridge.sendGroupBlogComment(node, text, profile) 256 return self.sat_host.bridge.sendGroupBlogComment(node, text, profile)
257 else: 257 else:
258 raise Exception("Invalid data") 258 raise Exception("Invalid data")
259 259
260 def jsonrpc_getLastMblogs(self, publisher_jid, max_item): 260 def jsonrpc_getLastMblogs(self, publisher_jid, max_item):
261 """Get last microblogs posted by a contact 261 """Get last microblogs posted by a contact
262 @param publisher_jid: jid of the publisher 262 @param publisher_jid: jid of the publisher
263 @param max_item: number of items to ask 263 @param max_item: number of items to ask
264 @return list of microblog data (dict)""" 264 @return list of microblog data (dict)"""
288 288
289 289
290 def jsonrpc_getPresenceStatus(self): 290 def jsonrpc_getPresenceStatus(self):
291 """Get Presence information for connected contacts""" 291 """Get Presence information for connected contacts"""
292 profile = ISATSession(self.session).profile 292 profile = ISATSession(self.session).profile
293 return self.sat_host.bridge.getPresenceStatus(profile) 293 return self.sat_host.bridge.getPresenceStatus(profile)
294 294
295 def jsonrpc_getHistory(self, from_jid, to_jid, size, between): 295 def jsonrpc_getHistory(self, from_jid, to_jid, size, between):
296 """Return history for the from_jid/to_jid couple""" 296 """Return history for the from_jid/to_jid couple"""
297 sat_session = ISATSession(self.session) 297 sat_session = ISATSession(self.session)
298 profile = sat_session.profile 298 profile = sat_session.profile
336 self.sat_host.bridge.mucLeave(room_jid.userhost(), profile) 336 self.sat_host.bridge.mucLeave(room_jid.userhost(), profile)
337 337
338 def jsonrpc_getRoomsJoined(self): 338 def jsonrpc_getRoomsJoined(self):
339 """Return list of room already joined by user""" 339 """Return list of room already joined by user"""
340 profile = ISATSession(self.session).profile 340 profile = ISATSession(self.session).profile
341 return self.sat_host.bridge.getRoomsJoined(profile) 341 return self.sat_host.bridge.getRoomsJoined(profile)
342 342
343 def jsonrpc_launchTarotGame(self, other_players): 343 def jsonrpc_launchTarotGame(self, other_players):
344 """Create a room, invite the other players and start a Tarot game""" 344 """Create a room, invite the other players and start a Tarot game"""
345 profile = ISATSession(self.session).profile 345 profile = ISATSession(self.session).profile
346 self.sat_host.bridge.tarotGameLaunch(other_players, profile) 346 self.sat_host.bridge.tarotGameLaunch(other_players, profile)
358 358
359 def jsonrpc_tarotGameContratChoosed(self, player_nick, referee, contrat): 359 def jsonrpc_tarotGameContratChoosed(self, player_nick, referee, contrat):
360 """Tell to the server that we are ready to start the game""" 360 """Tell to the server that we are ready to start the game"""
361 profile = ISATSession(self.session).profile 361 profile = ISATSession(self.session).profile
362 self.sat_host.bridge.tarotGameContratChoosed(player_nick, referee, contrat, profile) 362 self.sat_host.bridge.tarotGameContratChoosed(player_nick, referee, contrat, profile)
363 363
364 def jsonrpc_tarotGamePlayCards(self, player_nick, referee, cards): 364 def jsonrpc_tarotGamePlayCards(self, player_nick, referee, cards):
365 """Tell to the server the cards we want to put on the table""" 365 """Tell to the server the cards we want to put on the table"""
366 profile = ISATSession(self.session).profile 366 profile = ISATSession(self.session).profile
367 self.sat_host.bridge.tarotGamePlayCards(player_nick, referee, cards, profile) 367 self.sat_host.bridge.tarotGamePlayCards(player_nick, referee, cards, profile)
368 368
400 self.authorized_params[cat.getAttribute("name")] = params_list 400 self.authorized_params[cat.getAttribute("name")] = params_list
401 if self.authorized_params: 401 if self.authorized_params:
402 return d 402 return d
403 else: 403 else:
404 return None 404 return None
405 405
406 d.addCallback(setAuthorizedParams) 406 d.addCallback(setAuthorizedParams)
407 407
408 from sat.tools.xml_tools import paramsXml2xmlUI 408 from sat.tools.xml_tools import paramsXml2xmlUI
409 d.addCallback(lambda d: paramsXml2xmlUI(d) if d else "") 409 d.addCallback(lambda d: paramsXml2xmlUI(d) if d else "")
410 410
413 def jsonrpc_asyncGetParamA(self, param, category, attribute="value"): 413 def jsonrpc_asyncGetParamA(self, param, category, attribute="value"):
414 """Return the parameter value for profile""" 414 """Return the parameter value for profile"""
415 profile = ISATSession(self.session).profile 415 profile = ISATSession(self.session).profile
416 d = self.asyncBridgeCall("asyncGetParamA", param, category, attribute, SECURITY_LIMIT, profile_key=profile) 416 d = self.asyncBridgeCall("asyncGetParamA", param, category, attribute, SECURITY_LIMIT, profile_key=profile)
417 return d 417 return d
418 418
419 def jsonrpc_setParam(self, name, value, category): 419 def jsonrpc_setParam(self, name, value, category):
420 profile = ISATSession(self.session).profile 420 profile = ISATSession(self.session).profile
421 if category in self.authorized_params and name in self.authorized_params[category]: 421 if category in self.authorized_params and name in self.authorized_params[category]:
422 return self.sat_host.bridge.setParam(name, value, category, SECURITY_LIMIT, profile) 422 return self.sat_host.bridge.setParam(name, value, category, SECURITY_LIMIT, profile)
423 else: 423 else:
425 % (name, category)) 425 % (name, category))
426 426
427 def jsonrpc_launchAction(self, action_type, data): 427 def jsonrpc_launchAction(self, action_type, data):
428 profile = ISATSession(self.session).profile 428 profile = ISATSession(self.session).profile
429 return self.sat_host.bridge.launchAction(action_type, data, profile) 429 return self.sat_host.bridge.launchAction(action_type, data, profile)
430 430
431 def jsonrpc_chatStateComposing(self, to_jid_s): 431 def jsonrpc_chatStateComposing(self, to_jid_s):
432 """Call the method to process a "composing" state. 432 """Call the method to process a "composing" state.
433 @param to_jid_s: contact the user is composing to 433 @param to_jid_s: contact the user is composing to
434 """ 434 """
435 profile = ISATSession(self.session).profile 435 profile = ISATSession(self.session).profile
492 @return: A constant indicating the state: 492 @return: A constant indicating the state:
493 - BAD REQUEST: something is wrong in the request (bad arguments, profile_key for login) 493 - BAD REQUEST: something is wrong in the request (bad arguments, profile_key for login)
494 - AUTH ERROR: either the profile or the password is wrong 494 - AUTH ERROR: either the profile or the password is wrong
495 - ALREADY WAITING: a request has already be made for this profile 495 - ALREADY WAITING: a request has already be made for this profile
496 - server.NOT_DONE_YET: the profile is being processed, the return value will be given by self._logged or self._logginError 496 - server.NOT_DONE_YET: the profile is being processed, the return value will be given by self._logged or self._logginError
497 """ 497 """
498 498
499 try: 499 try:
500 if request.args['submit_type'][0] == 'login': 500 if request.args['submit_type'][0] == 'login':
501 _login = request.args['login'][0] 501 _login = request.args['login'][0]
502 if _login.startswith('@'): 502 if _login.startswith('@'):
503 raise Exception('No profile_key allowed') 503 raise Exception('No profile_key allowed')
504 _pass = request.args['login_password'][0] 504 _pass = request.args['login_password'][0]
505 505
506 elif request.args['submit_type'][0] == 'register': 506 elif request.args['submit_type'][0] == 'register':
507 return self._registerNewAccount(request) 507 return self._registerNewAccount(request)
508 508
509 else: 509 else:
510 raise Exception('Unknown submit type') 510 raise Exception('Unknown submit type')
511 except KeyError: 511 except KeyError:
512 return "BAD REQUEST" 512 return "BAD REQUEST"
513 513
514 _profile_check = self.sat_host.bridge.getProfileName(_login) 514 _profile_check = self.sat_host.bridge.getProfileName(_login)
515 515
516 def profile_pass_cb(_profile_pass): 516 def profile_pass_cb(_profile_pass):
517 if not _profile_check or _profile_check != _login or _profile_pass != _pass: 517 if not _profile_check or _profile_check != _login or _profile_pass != _pass:
518 request.write("AUTH ERROR") 518 request.write("AUTH ERROR")
519 request.finish() 519 request.finish()
520 return 520 return
521 521
522 if self.profiles_waiting.has_key(_login): 522 if self.profiles_waiting.has_key(_login):
523 request.write("ALREADY WAITING") 523 request.write("ALREADY WAITING")
524 request.finish() 524 request.finish()
525 return 525 return
526 526
527 if self.sat_host.bridge.isConnected(_login): 527 if self.sat_host.bridge.isConnected(_login):
528 request.write(self._logged(_login, request, finish=False)) 528 request.write(self._logged(_login, request, finish=False))
529 request.finish() 529 request.finish()
530 return 530 return
531 531
532 self.profiles_waiting[_login] = request 532 self.profiles_waiting[_login] = request
533 d = self.asyncBridgeCall("asyncConnect", _login) 533 d = self.asyncBridgeCall("asyncConnect", _login)
534 return d 534 return d
535 535
536 def profile_pass_errback(ignore): 536 def profile_pass_errback(ignore):
537 error("INTERNAL ERROR: can't check profile password") 537 error("INTERNAL ERROR: can't check profile password")
538 request.write("AUTH ERROR") 538 request.write("AUTH ERROR")
539 request.finish() 539 request.finish()
540 540
541 d = self.asyncBridgeCall("asyncGetParamA", "Password", "Connection", profile_key=_login) 541 d = self.asyncBridgeCall("asyncGetParamA", "Password", "Connection", profile_key=_login)
542 d.addCallbacks(profile_pass_cb, profile_pass_errback) 542 d.addCallbacks(profile_pass_cb, profile_pass_errback)
543 543
544 return server.NOT_DONE_YET 544 return server.NOT_DONE_YET
545 545
547 """Called when a account has just been created, 547 """Called when a account has just been created,
548 setup stuff has microblog access""" 548 setup stuff has microblog access"""
549 def _connected(ignore): 549 def _connected(ignore):
550 mblog_d = self.asyncBridgeCall("setMicroblogAccess", "open", profile) 550 mblog_d = self.asyncBridgeCall("setMicroblogAccess", "open", profile)
551 mblog_d.addBoth(lambda ignore: self.sat_host.bridge.disconnect(profile)) 551 mblog_d.addBoth(lambda ignore: self.sat_host.bridge.disconnect(profile))
552 552
553 d = self.asyncBridgeCall("asyncConnect", profile) 553 d = self.asyncBridgeCall("asyncConnect", profile)
554 d.addCallback(_connected) 554 d.addCallback(_connected)
555 555
556 def _registerNewAccount(self, request): 556 def _registerNewAccount(self, request):
557 """Create a new account, or return error 557 """Create a new account, or return error
558 @param request: initial login request 558 @param request: initial login request
559 @return: "REGISTRATION" in case of success""" 559 @return: "REGISTRATION" in case of success"""
560 #TODO: must be moved in SàT core 560 #TODO: must be moved in SàT core
561 561
562 try: 562 try:
563 profile = login = request.args['register_login'][0] 563 profile = login = request.args['register_login'][0]
564 password = request.args['register_password'][0] #FIXME: password is ignored so far 564 password = request.args['register_password'][0] #FIXME: password is ignored so far
565 email = request.args['email'][0] 565 email = request.args['email'][0]
566 except KeyError: 566 except KeyError:
572 def registered(result): 572 def registered(result):
573 request.write('REGISTRATION') 573 request.write('REGISTRATION')
574 request.finish() 574 request.finish()
575 #import pudb 575 #import pudb
576 #pudb.set_trace() 576 #pudb.set_trace()
577 577
578 def registeringError(failure): 578 def registeringError(failure):
579 reason = str(failure.value) 579 reason = str(failure.value)
580 if reason == "CONFLICT": 580 if reason == "CONFLICT":
581 request.write('ALREADY EXISTS') 581 request.write('ALREADY EXISTS')
582 elif reason == "INTERNAL": 582 elif reason == "INTERNAL":
583 request.write('INTERNAL') 583 request.write('INTERNAL')
584 else: 584 else:
585 #import pdb 585 #import pdb
586 #pdb.set_trace() 586 #pdb.set_trace()
587 587
588 error('Unknown registering error: %s' % (reason,)) 588 error('Unknown registering error: %s' % (reason,))
589 request.write('Unknown error (%s)' % reason) 589 request.write('Unknown error (%s)' % reason)
590 request.finish() 590 request.finish()
591 591
592 d = self.asyncBridgeCall("registerSatAccount", email, password, profile) 592 d = self.asyncBridgeCall("registerSatAccount", email, password, profile)
593 d.addCallback(registered) 593 d.addCallback(registered)
594 d.addErrback(registeringError) 594 d.addErrback(registeringError)
595 return server.NOT_DONE_YET 595 return server.NOT_DONE_YET
596 596
608 if finish: 608 if finish:
609 request.write(answer) 609 request.write(answer)
610 request.finish() 610 request.finish()
611 else: 611 else:
612 return answer 612 return answer
613 613
614 self.__cleanWaiting(profile) 614 self.__cleanWaiting(profile)
615 _session = request.getSession() 615 _session = request.getSession()
616 sat_session = ISATSession(_session) 616 sat_session = ISATSession(_session)
617 if sat_session.profile: 617 if sat_session.profile:
618 error (('/!\\ Session has already a profile, this should NEVER happen !')) 618 error (('/!\\ Session has already a profile, this should NEVER happen !'))
619 return result('SESSION_ACTIVE') 619 return result('SESSION_ACTIVE')
620 sat_session.profile = profile 620 sat_session.profile = profile
621 self.sat_host.prof_connected.add(profile) 621 self.sat_host.prof_connected.add(profile)
622 622
623 def onExpire(): 623 def onExpire():
624 info ("Session expired (profile=%s)" % (profile,)) 624 info ("Session expired (profile=%s)" % (profile,))
625 try: 625 try:
626 #We purge the queue 626 #We purge the queue
627 del self.sat_host.signal_handler.queue[profile] 627 del self.sat_host.signal_handler.queue[profile]
628 except KeyError: 628 except KeyError:
629 pass 629 pass
630 #and now we disconnect the profile 630 #and now we disconnect the profile
631 self.sat_host.bridge.disconnect(profile) 631 self.sat_host.bridge.disconnect(profile)
632 632
633 _session.notifyOnExpire(onExpire) 633 _session.notifyOnExpire(onExpire)
634 634
635 d = defer.Deferred() 635 d = defer.Deferred()
636 return result('LOGGED') 636 return result('LOGGED')
637 637
638 def _logginError(self, login, request, error_type): 638 def _logginError(self, login, request, error_type):
639 """Something went wrong during loggin, return an error""" 639 """Something went wrong during loggin, return an error"""
642 642
643 def jsonrpc_isConnected(self): 643 def jsonrpc_isConnected(self):
644 _session = self.request.getSession() 644 _session = self.request.getSession()
645 profile = ISATSession(_session).profile 645 profile = ISATSession(_session).profile
646 return self.sat_host.bridge.isConnected(profile) 646 return self.sat_host.bridge.isConnected(profile)
647 647
648 def jsonrpc_connect(self): 648 def jsonrpc_connect(self):
649 _session = self.request.getSession() 649 _session = self.request.getSession()
650 profile = ISATSession(_session).profile 650 profile = ISATSession(_session).profile
651 if self.profiles_waiting.has_key(profile): 651 if self.profiles_waiting.has_key(profile):
652 raise jsonrpclib.Fault('1','Already waiting') #FIXME: define some standard error codes for libervia 652 raise jsonrpclib.Fault('1','Already waiting') #FIXME: define some standard error codes for libervia
653 self.profiles_waiting[profile] = self.request 653 self.profiles_waiting[profile] = self.request
654 self.sat_host.bridge.connect(profile) 654 self.sat_host.bridge.connect(profile)
655 return server.NOT_DONE_YET 655 return server.NOT_DONE_YET
656 656
657 def jsonrpc_isRegistered(self): 657 def jsonrpc_isRegistered(self):
658 """Tell if the user is already registered""" 658 """Tell if the user is already registered"""
659 _session = self.request.getSession() 659 _session = self.request.getSession()
660 profile = ISATSession(_session).profile 660 profile = ISATSession(_session).profile
661 return bool(profile) 661 return bool(profile)
662 662
663 663
664 class SignalHandler(jsonrpc.JSONRPC): 664 class SignalHandler(jsonrpc.JSONRPC):
665 665
666 def __init__(self, sat_host): 666 def __init__(self, sat_host):
667 Resource.__init__(self) 667 Resource.__init__(self)
668 self.register=None 668 self.register=None
669 self.sat_host=sat_host 669 self.sat_host=sat_host
670 self.signalDeferred = {} 670 self.signalDeferred = {}
692 if source_defer.called and source_defer.result[0] == "disconnected": 692 if source_defer.called and source_defer.result[0] == "disconnected":
693 info(u"[%s] disconnected" % (profile,)) 693 info(u"[%s] disconnected" % (profile,))
694 _session.expire() 694 _session.expire()
695 except IndexError: 695 except IndexError:
696 error("Deferred result should be a tuple with fonction name first") 696 error("Deferred result should be a tuple with fonction name first")
697 697
698 self.signalDeferred[profile] = defer.Deferred() 698 self.signalDeferred[profile] = defer.Deferred()
699 self.request.notifyFinish().addBoth(unlock, profile) 699 self.request.notifyFinish().addBoth(unlock, profile)
700 return self.signalDeferred[profile] 700 return self.signalDeferred[profile]
701 701
702 def getGenericCb(self, function_name): 702 def getGenericCb(self, function_name):
703 """Return a generic function which send all params to signalDeferred.callback 703 """Return a generic function which send all params to signalDeferred.callback
704 function must have profile as last argument""" 704 function must have profile as last argument"""
705 def genericCb(*args): 705 def genericCb(*args):
706 profile = args[-1] 706 profile = args[-1]
712 else: 712 else:
713 if not self.queue.has_key(profile): 713 if not self.queue.has_key(profile):
714 self.queue[profile] = [] 714 self.queue[profile] = []
715 self.queue[profile].append((function_name, args[:-1])) 715 self.queue[profile].append((function_name, args[:-1]))
716 return genericCb 716 return genericCb
717 717
718 def connected(self, profile): 718 def connected(self, profile):
719 assert(self.register) #register must be plugged 719 assert(self.register) #register must be plugged
720 request = self.register.getWaitingRequest(profile) 720 request = self.register.getWaitingRequest(profile)
721 if request: 721 if request:
722 self.register._logged(profile, request) 722 self.register._logged(profile, request)
731 del self.signalDeferred[profile] 731 del self.signalDeferred[profile]
732 else: 732 else:
733 if not self.queue.has_key(profile): 733 if not self.queue.has_key(profile):
734 self.queue[profile] = [] 734 self.queue[profile] = []
735 self.queue[profile].append(("disconnected",)) 735 self.queue[profile].append(("disconnected",))
736 736
737 737
738 def connectionError(self, error_type, profile): 738 def connectionError(self, error_type, profile):
739 assert(self.register) #register must be plugged 739 assert(self.register) #register must be plugged
740 request = self.register.getWaitingRequest(profile) 740 request = self.register.getWaitingRequest(profile)
741 if request: #The user is trying to log in 741 if request: #The user is trying to log in
792 filename = self._getFileName(request) 792 filename = self._getFileName(request)
793 filepath = os.path.join(self.upload_dir, filename) 793 filepath = os.path.join(self.upload_dir, filename)
794 #FIXME: the uploaded file is fully loaded in memory at form parsing time so far 794 #FIXME: the uploaded file is fully loaded in memory at form parsing time so far
795 # (see twisted.web.http.Request.requestReceived). A custom requestReceived should 795 # (see twisted.web.http.Request.requestReceived). A custom requestReceived should
796 # be written in the futur. In addition, it is not yet possible to get progression informations 796 # be written in the futur. In addition, it is not yet possible to get progression informations
797 # (see http://twistedmatrix.com/trac/ticket/288) 797 # (see http://twistedmatrix.com/trac/ticket/288)
798 798
799 with open(filepath,'w') as f: 799 with open(filepath,'w') as f:
800 f.write(request.args[self.NAME][0]) 800 f.write(request.args[self.NAME][0])
801 self._fileWritten(request, filepath) 801 self._fileWritten(request, filepath)
802 #end = time.time() 802 #end = time.time()
803 #print "time spent in render: %fs" % (end - start) 803 #print "time spent in render: %fs" % (end - start)
806 class UploadManagerRadioCol(UploadManager): 806 class UploadManagerRadioCol(UploadManager):
807 NAME = 'song' 807 NAME = 'song'
808 808
809 def _getFileName(self, request): 809 def _getFileName(self, request):
810 return "%s.ogg" % str(uuid.uuid4()) #XXX: chromium doesn't seem to play song without the .ogg extension, even with audio/ogg mime-type 810 return "%s.ogg" % str(uuid.uuid4()) #XXX: chromium doesn't seem to play song without the .ogg extension, even with audio/ogg mime-type
811 811
812 def _fileWritten(self, request, filepath): 812 def _fileWritten(self, request, filepath):
813 """Called once the file is actually written on disk""" 813 """Called once the file is actually written on disk"""
814 profile = ISATSession(request.getSession()).profile 814 profile = ISATSession(request.getSession()).profile
815 self.sat_host.bridge.radiocolSongAdded(request.args['referee'][0], filepath, profile) 815 self.sat_host.bridge.radiocolSongAdded(request.args['referee'][0], filepath, profile)
816 816
817 class UploadManagerAvatar(UploadManager): 817 class UploadManagerAvatar(UploadManager):
818 NAME = 'avatar_path' 818 NAME = 'avatar_path'
819 819
820 def _getFileName(self, request): 820 def _getFileName(self, request):
821 return str(uuid.uuid4()) 821 return str(uuid.uuid4())
822 822
823 def _fileWritten(self, request, filepath): 823 def _fileWritten(self, request, filepath):
824 """Called once the file is actually written on disk""" 824 """Called once the file is actually written on disk"""
825 profile = ISATSession(request.getSession()).profile 825 profile = ISATSession(request.getSession()).profile
826 print u"fichier écrit:", filepath 826 print u"fichier écrit:", filepath
827 self.sat_host.bridge.setAvatar(filepath, profile) 827 self.sat_host.bridge.setAvatar(filepath, profile)
828 828
829 class Libervia(service.Service): 829 class Libervia(service.Service):
830 830
831 def __init__(self): 831 def __init__(self):
832 self._cleanup = [] 832 self._cleanup = []
833 root = ProtectedFile(LIBERVIA_DIR) 833 root = ProtectedFile(LIBERVIA_DIR)
834 self.signal_handler = SignalHandler(self) 834 self.signal_handler = SignalHandler(self)
835 _register = Register(self) 835 _register = Register(self)
836 _upload_radiocol = UploadManagerRadioCol(self) 836 _upload_radiocol = UploadManagerRadioCol(self)
837 _upload_avatar = UploadManagerAvatar(self) 837 _upload_avatar = UploadManagerAvatar(self)
838 self.signal_handler.plugRegister(_register) 838 self.signal_handler.plugRegister(_register)
846 print(u"Can't connect to SàT backend, are you sure it's launched ?") 846 print(u"Can't connect to SàT backend, are you sure it's launched ?")
847 sys.exit(1) 847 sys.exit(1)
848 self.bridge.register("connected", self.signal_handler.connected) 848 self.bridge.register("connected", self.signal_handler.connected)
849 self.bridge.register("disconnected", self.signal_handler.disconnected) 849 self.bridge.register("disconnected", self.signal_handler.disconnected)
850 self.bridge.register("connectionError", self.signal_handler.connectionError) 850 self.bridge.register("connectionError", self.signal_handler.connectionError)
851 self.bridge.register("actionResult", self.action_handler.actionResultCb) 851 self.bridge.register("actionResult", self.action_handler.actionResultCb)
852 #core 852 #core
853 for signal_name in ['presenceUpdate', 'newMessage', 'subscribe', 'contactDeleted', 'newContact', 'entityDataUpdated', 'askConfirmation', 'newAlert']: 853 for signal_name in ['presenceUpdate', 'newMessage', 'subscribe', 'contactDeleted', 'newContact', 'entityDataUpdated', 'askConfirmation', 'newAlert']:
854 self.bridge.register(signal_name, self.signal_handler.getGenericCb(signal_name)) 854 self.bridge.register(signal_name, self.signal_handler.getGenericCb(signal_name))
855 #plugins 855 #plugins
856 for signal_name in ['personalEvent', 'roomJoined', 'roomUserJoined', 'roomUserLeft', 'tarotGameStarted', 'tarotGameNew', 'tarotGameChooseContrat', 856 for signal_name in ['personalEvent', 'roomJoined', 'roomUserJoined', 'roomUserLeft', 'tarotGameStarted', 'tarotGameNew', 'tarotGameChooseContrat',
857 'tarotGameShowCards', 'tarotGameInvalidCards', 'tarotGameCardsPlayed', 'tarotGameYourTurn', 'tarotGameScore', 857 'tarotGameShowCards', 'tarotGameInvalidCards', 'tarotGameCardsPlayed', 'tarotGameYourTurn', 'tarotGameScore',
858 'radiocolStarted', 'radiocolPreload', 'radiocolPlay', 'radiocolNoUpload', 'radiocolUploadOk', 'radiocolSongRejected', 858 'radiocolStarted', 'radiocolPreload', 'radiocolPlay', 'radiocolNoUpload', 'radiocolUploadOk', 'radiocolSongRejected',
859 'chatStateReceived']: 859 'chatStateReceived']:
860 self.bridge.register(signal_name, self.signal_handler.getGenericCb(signal_name), "plugin") 860 self.bridge.register(signal_name, self.signal_handler.getGenericCb(signal_name), "plugin")
861 self.media_dir = self.bridge.getConfig('','media_dir') 861 self.media_dir = self.bridge.getConfig('','media_dir')
862 self.local_dir = self.bridge.getConfig('','local_dir') 862 self.local_dir = self.bridge.getConfig('','local_dir')
887 887
888 def stopService(self): 888 def stopService(self):
889 print "launching cleaning methods" 889 print "launching cleaning methods"
890 for callback, args, kwargs in self._cleanup: 890 for callback, args, kwargs in self._cleanup:
891 callback(*args, **kwargs) 891 callback(*args, **kwargs)
892 892
893 def run(self): 893 def run(self):
894 reactor.run() 894 reactor.run()
895 895
896 def stop(self): 896 def stop(self):
897 reactor.stop() 897 reactor.stop()
898 898
899 899
900 registerAdapter(SATSession, server.Session, ISATSession) 900 registerAdapter(SATSession, server.Session, ISATSession)