comparison src/server/server.py @ 919:7b267496da1d

server: moved session interfaces to session_iface module + added SATGuestSession
author Goffi <goffi@goffi.org>
date Wed, 29 Mar 2017 19:46:04 +0200
parents 86563d6c83b0
children 8cea8bf41b03
comparison
equal deleted inserted replaced
918:96a56856d357 919:7b267496da1d
47 import tempfile 47 import tempfile
48 import shutil 48 import shutil
49 import uuid 49 import uuid
50 import urlparse 50 import urlparse
51 import urllib 51 import urllib
52 import shortuuid
53 from zope.interface import Interface, Attribute, implements
54 from httplib import HTTPS_PORT 52 from httplib import HTTPS_PORT
55 import libervia 53 import libervia
56 54
57 try: 55 try:
58 import OpenSSL 56 import OpenSSL
60 except ImportError: 58 except ImportError:
61 ssl = None 59 ssl = None
62 60
63 from libervia.server.constants import Const as C 61 from libervia.server.constants import Const as C
64 from libervia.server.blog import MicroBlog 62 from libervia.server.blog import MicroBlog
63 from libervia.server import session_iface
65 64
66 65
67 # following value are set from twisted.plugins.libervia_server initialise (see the comment there) 66 # following value are set from twisted.plugins.libervia_server initialise (see the comment there)
68 DATA_DIR_DEFAULT = OPT_PARAMETERS_BOTH = OPT_PARAMETERS_CFG = coerceDataDir = None 67 DATA_DIR_DEFAULT = OPT_PARAMETERS_BOTH = OPT_PARAMETERS_CFG = coerceDataDir = None
69 68
70 69
71 class ISATSession(Interface):
72 profile = Attribute("Sat profile")
73 jid = Attribute("JID associated with the profile")
74 uuid = Attribute("uuid associated with the profile session")
75
76
77 class SATSession(object):
78 implements(ISATSession)
79
80 def __init__(self, session):
81 self.profile = None
82 self.jid = None
83 self.uuid = unicode(shortuuid.uuid())
84 70
85 71
86 class LiberviaSession(server.Session): 72 class LiberviaSession(server.Session):
87 sessionTimeout = C.SESSION_TIMEOUT 73 sessionTimeout = C.SESSION_TIMEOUT
88 74
167 try: 153 try:
168 item = parsed_qs['item'][0] 154 item = parsed_qs['item'][0]
169 if not item: 155 if not item:
170 raise KeyError 156 raise KeyError
171 except (IndexError, KeyError): 157 except (IndexError, KeyError):
172 raise NotImplementedError(u"only item for PubSub URI is handler for the moment for url_redirections_dict") 158 raise NotImplementedError(u"only item for PubSub URI is handled for the moment for url_redirections_dict")
173 location = "/blog/{profile}/{item}".format( 159 location = "/blog/{profile}/{item}".format(
174 profile=urllib.quote(options['url_redirections_profile'].encode('utf-8')), 160 profile=urllib.quote(options['url_redirections_profile'].encode('utf-8')),
175 item = urllib.quote_plus(item), 161 item = urllib.quote_plus(item),
176 ).decode('utf-8') 162 ).decode('utf-8')
177 request_data = self._getRequestData(location) 163 request_data = self._getRequestData(location)
361 def __init__(self, sat_host): 347 def __init__(self, sat_host):
362 JSONRPCMethodManager.__init__(self, sat_host) 348 JSONRPCMethodManager.__init__(self, sat_host)
363 349
364 def render(self, request): 350 def render(self, request):
365 self.session = request.getSession() 351 self.session = request.getSession()
366 profile = ISATSession(self.session).profile 352 profile = session_iface.ISATSession(self.session).profile
367 if not profile: 353 if not profile:
368 #user is not identified, we return a jsonrpc fault 354 #user is not identified, we return a jsonrpc fault
369 parsed = jsonrpclib.loads(request.content.read()) 355 parsed = jsonrpclib.loads(request.content.read())
370 fault = jsonrpclib.Fault(C.ERRNUM_LIBERVIA, C.NOT_ALLOWED) # FIXME: define some standard error codes for libervia 356 fault = jsonrpclib.Fault(C.ERRNUM_LIBERVIA, C.NOT_ALLOWED) # FIXME: define some standard error codes for libervia
371 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc')) # pylint: disable=E1103 357 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc')) # pylint: disable=E1103
383 """Return Libervia version""" 369 """Return Libervia version"""
384 return self.sat_host.full_version 370 return self.sat_host.full_version
385 371
386 def jsonrpc_disconnect(self): 372 def jsonrpc_disconnect(self):
387 """Disconnect the profile""" 373 """Disconnect the profile"""
388 sat_session = ISATSession(self.session) 374 sat_session = session_iface.ISATSession(self.session)
389 profile = sat_session.profile 375 profile = sat_session.profile
390 self.sat_host.bridge.disconnect(profile) 376 self.sat_host.bridge.disconnect(profile)
391 377
392 def jsonrpc_getContacts(self): 378 def jsonrpc_getContacts(self):
393 """Return all passed args.""" 379 """Return all passed args."""
394 profile = ISATSession(self.session).profile 380 profile = session_iface.ISATSession(self.session).profile
395 return self.sat_host.bridge.getContacts(profile) 381 return self.sat_host.bridge.getContacts(profile)
396 382
397 def jsonrpc_addContact(self, entity, name, groups): 383 def jsonrpc_addContact(self, entity, name, groups):
398 """Subscribe to contact presence, and add it to the given groups""" 384 """Subscribe to contact presence, and add it to the given groups"""
399 profile = ISATSession(self.session).profile 385 profile = session_iface.ISATSession(self.session).profile
400 self.sat_host.bridge.addContact(entity, profile) 386 self.sat_host.bridge.addContact(entity, profile)
401 self.sat_host.bridge.updateContact(entity, name, groups, profile) 387 self.sat_host.bridge.updateContact(entity, name, groups, profile)
402 388
403 def jsonrpc_delContact(self, entity): 389 def jsonrpc_delContact(self, entity):
404 """Remove contact from contacts list""" 390 """Remove contact from contacts list"""
405 profile = ISATSession(self.session).profile 391 profile = session_iface.ISATSession(self.session).profile
406 self.sat_host.bridge.delContact(entity, profile) 392 self.sat_host.bridge.delContact(entity, profile)
407 393
408 def jsonrpc_updateContact(self, entity, name, groups): 394 def jsonrpc_updateContact(self, entity, name, groups):
409 """Update contact's roster item""" 395 """Update contact's roster item"""
410 profile = ISATSession(self.session).profile 396 profile = session_iface.ISATSession(self.session).profile
411 self.sat_host.bridge.updateContact(entity, name, groups, profile) 397 self.sat_host.bridge.updateContact(entity, name, groups, profile)
412 398
413 def jsonrpc_subscription(self, sub_type, entity): 399 def jsonrpc_subscription(self, sub_type, entity):
414 """Confirm (or infirm) subscription, 400 """Confirm (or infirm) subscription,
415 and setup user roster in case of subscription""" 401 and setup user roster in case of subscription"""
416 profile = ISATSession(self.session).profile 402 profile = session_iface.ISATSession(self.session).profile
417 self.sat_host.bridge.subscription(sub_type, entity, profile) 403 self.sat_host.bridge.subscription(sub_type, entity, profile)
418 404
419 def jsonrpc_getWaitingSub(self): 405 def jsonrpc_getWaitingSub(self):
420 """Return list of room already joined by user""" 406 """Return list of room already joined by user"""
421 profile = ISATSession(self.session).profile 407 profile = session_iface.ISATSession(self.session).profile
422 return self.sat_host.bridge.getWaitingSub(profile) 408 return self.sat_host.bridge.getWaitingSub(profile)
423 409
424 def jsonrpc_setStatus(self, presence, status): 410 def jsonrpc_setStatus(self, presence, status):
425 """Change the presence and/or status 411 """Change the presence and/or status
426 @param presence: value from ("", "chat", "away", "dnd", "xa") 412 @param presence: value from ("", "chat", "away", "dnd", "xa")
427 @param status: any string to describe your status 413 @param status: any string to describe your status
428 """ 414 """
429 profile = ISATSession(self.session).profile 415 profile = session_iface.ISATSession(self.session).profile
430 self.sat_host.bridge.setPresence('', presence, {'': status}, profile) 416 self.sat_host.bridge.setPresence('', presence, {'': status}, profile)
431 417
432 def jsonrpc_messageSend(self, to_jid, msg, subject, type_, extra={}): 418 def jsonrpc_messageSend(self, to_jid, msg, subject, type_, extra={}):
433 """send message""" 419 """send message"""
434 profile = ISATSession(self.session).profile 420 profile = session_iface.ISATSession(self.session).profile
435 return self.asyncBridgeCall("messageSend", to_jid, msg, subject, type_, extra, profile) 421 return self.asyncBridgeCall("messageSend", to_jid, msg, subject, type_, extra, profile)
436 422
437 ## PubSub ## 423 ## PubSub ##
438 424
439 def jsonrpc_psDeleteNode(self, service, node): 425 def jsonrpc_psDeleteNode(self, service, node):
440 """Delete a whole node 426 """Delete a whole node
441 427
442 @param service (unicode): service jid 428 @param service (unicode): service jid
443 @param node (unicode): node to delete 429 @param node (unicode): node to delete
444 """ 430 """
445 profile = ISATSession(self.session).profile 431 profile = session_iface.ISATSession(self.session).profile
446 return self.asyncBridgeCall("psDeleteNode", service, node, profile) 432 return self.asyncBridgeCall("psDeleteNode", service, node, profile)
447 433
448 # def jsonrpc_psRetractItem(self, service, node, item, notify): 434 # def jsonrpc_psRetractItem(self, service, node, item, notify):
449 # """Delete a whole node 435 # """Delete a whole node
450 436
451 # @param service (unicode): service jid 437 # @param service (unicode): service jid
452 # @param node (unicode): node to delete 438 # @param node (unicode): node to delete
453 # @param items (iterable): id of item to retract 439 # @param items (iterable): id of item to retract
454 # @param notify (bool): True if notification is required 440 # @param notify (bool): True if notification is required
455 # """ 441 # """
456 # profile = ISATSession(self.session).profile 442 # profile = session_iface.ISATSession(self.session).profile
457 # return self.asyncBridgeCall("psRetractItem", service, node, item, notify, profile) 443 # return self.asyncBridgeCall("psRetractItem", service, node, item, notify, profile)
458 444
459 # def jsonrpc_psRetractItems(self, service, node, items, notify): 445 # def jsonrpc_psRetractItems(self, service, node, items, notify):
460 # """Delete a whole node 446 # """Delete a whole node
461 447
462 # @param service (unicode): service jid 448 # @param service (unicode): service jid
463 # @param node (unicode): node to delete 449 # @param node (unicode): node to delete
464 # @param items (iterable): ids of items to retract 450 # @param items (iterable): ids of items to retract
465 # @param notify (bool): True if notification is required 451 # @param notify (bool): True if notification is required
466 # """ 452 # """
467 # profile = ISATSession(self.session).profile 453 # profile = session_iface.ISATSession(self.session).profile
468 # return self.asyncBridgeCall("psRetractItems", service, node, items, notify, profile) 454 # return self.asyncBridgeCall("psRetractItems", service, node, items, notify, profile)
469 455
470 ## microblogging ## 456 ## microblogging ##
471 457
472 def jsonrpc_mbSend(self, service, node, mb_data): 458 def jsonrpc_mbSend(self, service, node, mb_data):
475 @param service (unicode): service jid or empty string to use profile's microblog 461 @param service (unicode): service jid or empty string to use profile's microblog
476 @param node (unicode): publishing node, or empty string to use microblog node 462 @param node (unicode): publishing node, or empty string to use microblog node
477 @param mb_data(dict): microblog data 463 @param mb_data(dict): microblog data
478 @return: a deferred 464 @return: a deferred
479 """ 465 """
480 profile = ISATSession(self.session).profile 466 profile = session_iface.ISATSession(self.session).profile
481 return self.asyncBridgeCall("mbSend", service, node, mb_data, profile) 467 return self.asyncBridgeCall("mbSend", service, node, mb_data, profile)
482 468
483 def jsonrpc_mbRetract(self, service, node, items): 469 def jsonrpc_mbRetract(self, service, node, items):
484 """Delete a whole node 470 """Delete a whole node
485 471
486 @param service (unicode): service jid, empty string for PEP 472 @param service (unicode): service jid, empty string for PEP
487 @param node (unicode): node to delete, empty string for default node 473 @param node (unicode): node to delete, empty string for default node
488 @param items (iterable): ids of items to retract 474 @param items (iterable): ids of items to retract
489 """ 475 """
490 profile = ISATSession(self.session).profile 476 profile = session_iface.ISATSession(self.session).profile
491 return self.asyncBridgeCall("mbRetract", service, node, items, profile) 477 return self.asyncBridgeCall("mbRetract", service, node, items, profile)
492 478
493 def jsonrpc_mbGet(self, service_jid, node, max_items, item_ids, extra): 479 def jsonrpc_mbGet(self, service_jid, node, max_items, item_ids, extra):
494 """Get last microblogs from publisher_jid 480 """Get last microblogs from publisher_jid
495 481
498 @param max_items (int): maximum number of item to get or C.NO_LIMIT to get everything 484 @param max_items (int): maximum number of item to get or C.NO_LIMIT to get everything
499 @param item_ids (list[unicode]): list of item IDs 485 @param item_ids (list[unicode]): list of item IDs
500 @param rsm (dict): TODO 486 @param rsm (dict): TODO
501 @return: a deferred couple with the list of items and metadatas. 487 @return: a deferred couple with the list of items and metadatas.
502 """ 488 """
503 profile = ISATSession(self.session).profile 489 profile = session_iface.ISATSession(self.session).profile
504 return self.asyncBridgeCall("mbGet", service_jid, node, max_items, item_ids, extra, profile) 490 return self.asyncBridgeCall("mbGet", service_jid, node, max_items, item_ids, extra, profile)
505 491
506 def jsonrpc_mbGetFromMany(self, publishers_type, publishers, max_items, extra): 492 def jsonrpc_mbGetFromMany(self, publishers_type, publishers, max_items, extra):
507 """Get many blog nodes at once 493 """Get many blog nodes at once
508 494
510 @param publishers (tuple(unicode)): tuple of publishers (empty list for all, list of groups or list of jids) 496 @param publishers (tuple(unicode)): tuple of publishers (empty list for all, list of groups or list of jids)
511 @param max_items (int): maximum number of item to get or C.NO_LIMIT to get everything 497 @param max_items (int): maximum number of item to get or C.NO_LIMIT to get everything
512 @param extra (dict): TODO 498 @param extra (dict): TODO
513 @return (str): RT Deferred session id 499 @return (str): RT Deferred session id
514 """ 500 """
515 profile = ISATSession(self.session).profile 501 profile = session_iface.ISATSession(self.session).profile
516 return self.sat_host.bridge.mbGetFromMany(publishers_type, publishers, max_items, extra, profile) 502 return self.sat_host.bridge.mbGetFromMany(publishers_type, publishers, max_items, extra, profile)
517 503
518 def jsonrpc_mbGetFromManyRTResult(self, rt_session): 504 def jsonrpc_mbGetFromManyRTResult(self, rt_session):
519 """Get results from RealTime mbGetFromMany session 505 """Get results from RealTime mbGetFromMany session
520 506
521 @param rt_session (str): RT Deferred session id 507 @param rt_session (str): RT Deferred session id
522 """ 508 """
523 profile = ISATSession(self.session).profile 509 profile = session_iface.ISATSession(self.session).profile
524 return self.asyncBridgeCall("mbGetFromManyRTResult", rt_session, profile) 510 return self.asyncBridgeCall("mbGetFromManyRTResult", rt_session, profile)
525 511
526 def jsonrpc_mbGetFromManyWithComments(self, publishers_type, publishers, max_items, max_comments, rsm_dict, rsm_comments_dict): 512 def jsonrpc_mbGetFromManyWithComments(self, publishers_type, publishers, max_items, max_comments, rsm_dict, rsm_comments_dict):
527 """Helper method to get the microblogs and their comments in one shot 513 """Helper method to get the microblogs and their comments in one shot
528 514
533 @param rsm_dict (dict): RSM data for initial items only 519 @param rsm_dict (dict): RSM data for initial items only
534 @param rsm_comments_dict (dict): RSM data for comments only 520 @param rsm_comments_dict (dict): RSM data for comments only
535 @param profile_key: profile key 521 @param profile_key: profile key
536 @return (str): RT Deferred session id 522 @return (str): RT Deferred session id
537 """ 523 """
538 profile = ISATSession(self.session).profile 524 profile = session_iface.ISATSession(self.session).profile
539 return self.sat_host.bridge.mbGetFromManyWithComments(publishers_type, publishers, max_items, max_comments, rsm_dict, rsm_comments_dict, profile) 525 return self.sat_host.bridge.mbGetFromManyWithComments(publishers_type, publishers, max_items, max_comments, rsm_dict, rsm_comments_dict, profile)
540 526
541 def jsonrpc_mbGetFromManyWithCommentsRTResult(self, rt_session): 527 def jsonrpc_mbGetFromManyWithCommentsRTResult(self, rt_session):
542 """Get results from RealTime mbGetFromManyWithComments session 528 """Get results from RealTime mbGetFromManyWithComments session
543 529
544 @param rt_session (str): RT Deferred session id 530 @param rt_session (str): RT Deferred session id
545 """ 531 """
546 profile = ISATSession(self.session).profile 532 profile = session_iface.ISATSession(self.session).profile
547 return self.asyncBridgeCall("mbGetFromManyWithCommentsRTResult", rt_session, profile) 533 return self.asyncBridgeCall("mbGetFromManyWithCommentsRTResult", rt_session, profile)
548 534
549 535
550 # def jsonrpc_sendMblog(self, type_, dest, text, extra={}): 536 # def jsonrpc_sendMblog(self, type_, dest, text, extra={}):
551 # """ Send microblog message 537 # """ Send microblog message
552 # @param type_ (unicode): one of "PUBLIC", "GROUP" 538 # @param type_ (unicode): one of "PUBLIC", "GROUP"
553 # @param dest (tuple(unicode)): recipient groups (ignored for "PUBLIC") 539 # @param dest (tuple(unicode)): recipient groups (ignored for "PUBLIC")
554 # @param text (unicode): microblog's text 540 # @param text (unicode): microblog's text
555 # """ 541 # """
556 # profile = ISATSession(self.session).profile 542 # profile = session_iface.ISATSession(self.session).profile
557 # extra['allow_comments'] = 'True' 543 # extra['allow_comments'] = 'True'
558 544
559 # if not type_: # auto-detect 545 # if not type_: # auto-detect
560 # type_ = "PUBLIC" if dest == [] else "GROUP" 546 # type_ = "PUBLIC" if dest == [] else "GROUP"
561 547
574 # def jsonrpc_deleteMblog(self, pub_data, comments): 560 # def jsonrpc_deleteMblog(self, pub_data, comments):
575 # """Delete a microblog node 561 # """Delete a microblog node
576 # @param pub_data: a tuple (service, comment node identifier, item identifier) 562 # @param pub_data: a tuple (service, comment node identifier, item identifier)
577 # @param comments: comments node identifier (for main item) or False 563 # @param comments: comments node identifier (for main item) or False
578 # """ 564 # """
579 # profile = ISATSession(self.session).profile 565 # profile = session_iface.ISATSession(self.session).profile
580 # return self.sat_host.bridge.deleteGroupBlog(pub_data, comments if comments else '', profile) 566 # return self.sat_host.bridge.deleteGroupBlog(pub_data, comments if comments else '', profile)
581 567
582 # def jsonrpc_updateMblog(self, pub_data, comments, message, extra={}): 568 # def jsonrpc_updateMblog(self, pub_data, comments, message, extra={}):
583 # """Modify a microblog node 569 # """Modify a microblog node
584 # @param pub_data: a tuple (service, comment node identifier, item identifier) 570 # @param pub_data: a tuple (service, comment node identifier, item identifier)
586 # @param message: new message 572 # @param message: new message
587 # @param extra: dict which option name as key, which can be: 573 # @param extra: dict which option name as key, which can be:
588 # - allow_comments: True to accept an other level of comments, False else (default: False) 574 # - allow_comments: True to accept an other level of comments, False else (default: False)
589 # - rich: if present, contain rich text in currently selected syntax 575 # - rich: if present, contain rich text in currently selected syntax
590 # """ 576 # """
591 # profile = ISATSession(self.session).profile 577 # profile = session_iface.ISATSession(self.session).profile
592 # if comments: 578 # if comments:
593 # extra['allow_comments'] = 'True' 579 # extra['allow_comments'] = 'True'
594 # return self.sat_host.bridge.updateGroupBlog(pub_data, comments if comments else '', message, extra, profile) 580 # return self.sat_host.bridge.updateGroupBlog(pub_data, comments if comments else '', message, extra, profile)
595 581
596 # def jsonrpc_sendMblogComment(self, node, text, extra={}): 582 # def jsonrpc_sendMblogComment(self, node, text, extra={}):
597 # """ Send microblog message 583 # """ Send microblog message
598 # @param node: url of the comments node 584 # @param node: url of the comments node
599 # @param text: comment 585 # @param text: comment
600 # """ 586 # """
601 # profile = ISATSession(self.session).profile 587 # profile = session_iface.ISATSession(self.session).profile
602 # if node and text: 588 # if node and text:
603 # return self.sat_host.bridge.sendGroupBlogComment(node, text, extra, profile) 589 # return self.sat_host.bridge.sendGroupBlogComment(node, text, extra, profile)
604 # else: 590 # else:
605 # raise Exception("Invalid data") 591 # raise Exception("Invalid data")
606 592
607 # def jsonrpc_getMblogs(self, publisher_jid, item_ids, max_items=C.RSM_MAX_ITEMS): 593 # def jsonrpc_getMblogs(self, publisher_jid, item_ids, max_items=C.RSM_MAX_ITEMS):
608 # """Get specified microblogs posted by a contact 594 # """Get specified microblogs posted by a contact
609 # @param publisher_jid: jid of the publisher 595 # @param publisher_jid: jid of the publisher
610 # @param item_ids: list of microblogs items IDs 596 # @param item_ids: list of microblogs items IDs
611 # @return list of microblog data (dict)""" 597 # @return list of microblog data (dict)"""
612 # profile = ISATSession(self.session).profile 598 # profile = session_iface.ISATSession(self.session).profile
613 # d = self.asyncBridgeCall("getGroupBlogs", publisher_jid, item_ids, {'max_': unicode(max_items)}, False, profile) 599 # d = self.asyncBridgeCall("getGroupBlogs", publisher_jid, item_ids, {'max_': unicode(max_items)}, False, profile)
614 # return d 600 # return d
615 601
616 # def jsonrpc_getMblogsWithComments(self, publisher_jid, item_ids, max_comments=C.RSM_MAX_COMMENTS): 602 # def jsonrpc_getMblogsWithComments(self, publisher_jid, item_ids, max_comments=C.RSM_MAX_COMMENTS):
617 # """Get specified microblogs posted by a contact and their comments 603 # """Get specified microblogs posted by a contact and their comments
618 # @param publisher_jid: jid of the publisher 604 # @param publisher_jid: jid of the publisher
619 # @param item_ids: list of microblogs items IDs 605 # @param item_ids: list of microblogs items IDs
620 # @return list of couple (microblog data, list of microblog data)""" 606 # @return list of couple (microblog data, list of microblog data)"""
621 # profile = ISATSession(self.session).profile 607 # profile = session_iface.ISATSession(self.session).profile
622 # d = self.asyncBridgeCall("getGroupBlogsWithComments", publisher_jid, item_ids, {}, max_comments, profile) 608 # d = self.asyncBridgeCall("getGroupBlogsWithComments", publisher_jid, item_ids, {}, max_comments, profile)
623 # return d 609 # return d
624 610
625 # def jsonrpc_getMassiveMblogs(self, publishers_type, publishers, rsm=None): 611 # def jsonrpc_getMassiveMblogs(self, publishers_type, publishers, rsm=None):
626 # """Get lasts microblogs posted by several contacts at once 612 # """Get lasts microblogs posted by several contacts at once
630 # @param rsm (dict): TODO 616 # @param rsm (dict): TODO
631 # @return: dict{unicode: list[dict]) 617 # @return: dict{unicode: list[dict])
632 # key: publisher's jid 618 # key: publisher's jid
633 # value: list of microblog data (dict) 619 # value: list of microblog data (dict)
634 # """ 620 # """
635 # profile = ISATSession(self.session).profile 621 # profile = session_iface.ISATSession(self.session).profile
636 # if rsm is None: 622 # if rsm is None:
637 # rsm = {'max_': unicode(C.RSM_MAX_ITEMS)} 623 # rsm = {'max_': unicode(C.RSM_MAX_ITEMS)}
638 # d = self.asyncBridgeCall("getMassiveGroupBlogs", publishers_type, publishers, rsm, profile) 624 # d = self.asyncBridgeCall("getMassiveGroupBlogs", publishers_type, publishers, rsm, profile)
639 # self.sat_host.bridge.massiveSubscribeGroupBlogs(publishers_type, publishers, profile) 625 # self.sat_host.bridge.massiveSubscribeGroupBlogs(publishers_type, publishers, profile)
640 # return d 626 # return d
642 # def jsonrpc_getMblogComments(self, service, node, rsm=None): 628 # def jsonrpc_getMblogComments(self, service, node, rsm=None):
643 # """Get all comments of given node 629 # """Get all comments of given node
644 # @param service: jid of the service hosting the node 630 # @param service: jid of the service hosting the node
645 # @param node: comments node 631 # @param node: comments node
646 # """ 632 # """
647 # profile = ISATSession(self.session).profile 633 # profile = session_iface.ISATSession(self.session).profile
648 # if rsm is None: 634 # if rsm is None:
649 # rsm = {'max_': unicode(C.RSM_MAX_COMMENTS)} 635 # rsm = {'max_': unicode(C.RSM_MAX_COMMENTS)}
650 # d = self.asyncBridgeCall("getGroupBlogComments", service, node, rsm, profile) 636 # d = self.asyncBridgeCall("getGroupBlogComments", service, node, rsm, profile)
651 # return d 637 # return d
652 638
653 def jsonrpc_getPresenceStatuses(self): 639 def jsonrpc_getPresenceStatuses(self):
654 """Get Presence information for connected contacts""" 640 """Get Presence information for connected contacts"""
655 profile = ISATSession(self.session).profile 641 profile = session_iface.ISATSession(self.session).profile
656 return self.sat_host.bridge.getPresenceStatuses(profile) 642 return self.sat_host.bridge.getPresenceStatuses(profile)
657 643
658 def jsonrpc_historyGet(self, from_jid, to_jid, size, between, search=''): 644 def jsonrpc_historyGet(self, from_jid, to_jid, size, between, search=''):
659 """Return history for the from_jid/to_jid couple""" 645 """Return history for the from_jid/to_jid couple"""
660 sat_session = ISATSession(self.session) 646 sat_session = session_iface.ISATSession(self.session)
661 profile = sat_session.profile 647 profile = sat_session.profile
662 sat_jid = sat_session.jid 648 sat_jid = sat_session.jid
663 if not sat_jid: 649 if not sat_jid:
664 # we keep a session cache for jid to avoir jid spoofing 650 # we keep a session cache for jid to avoir jid spoofing
665 sat_jid = sat_session.jid = jid.JID(self.sat_host.bridge.getParamA("JabberID", "Connection", profile_key=profile)) 651 sat_jid = sat_session.jid = jid.JID(self.sat_host.bridge.getParamA("JabberID", "Connection", profile_key=profile))
683 """Join a Multi-User Chat room 669 """Join a Multi-User Chat room
684 670
685 @param room_jid (unicode): room JID or empty string to generate a unique name 671 @param room_jid (unicode): room JID or empty string to generate a unique name
686 @param nick (unicode): user nick 672 @param nick (unicode): user nick
687 """ 673 """
688 profile = ISATSession(self.session).profile 674 profile = session_iface.ISATSession(self.session).profile
689 d = self.asyncBridgeCall("joinMUC", room_jid, nick, {}, profile) 675 d = self.asyncBridgeCall("joinMUC", room_jid, nick, {}, profile)
690 return d 676 return d
691 677
692 def jsonrpc_inviteMUC(self, contact_jid, room_jid): 678 def jsonrpc_inviteMUC(self, contact_jid, room_jid):
693 """Invite a user to a Multi-User Chat room 679 """Invite a user to a Multi-User Chat room
694 680
695 @param contact_jid (unicode): contact to invite 681 @param contact_jid (unicode): contact to invite
696 @param room_jid (unicode): room JID or empty string to generate a unique name 682 @param room_jid (unicode): room JID or empty string to generate a unique name
697 """ 683 """
698 profile = ISATSession(self.session).profile 684 profile = session_iface.ISATSession(self.session).profile
699 room_id = room_jid.split("@")[0] 685 room_id = room_jid.split("@")[0]
700 service = room_jid.split("@")[1] 686 service = room_jid.split("@")[1]
701 self.sat_host.bridge.inviteMUC(contact_jid, service, room_id, {}, profile) 687 self.sat_host.bridge.inviteMUC(contact_jid, service, room_id, {}, profile)
702 688
703 def jsonrpc_mucLeave(self, room_jid): 689 def jsonrpc_mucLeave(self, room_jid):
704 """Quit a Multi-User Chat room""" 690 """Quit a Multi-User Chat room"""
705 profile = ISATSession(self.session).profile 691 profile = session_iface.ISATSession(self.session).profile
706 try: 692 try:
707 room_jid = jid.JID(room_jid) 693 room_jid = jid.JID(room_jid)
708 except: 694 except:
709 log.warning('Invalid room jid') 695 log.warning('Invalid room jid')
710 return 696 return
711 self.sat_host.bridge.mucLeave(room_jid.userhost(), profile) 697 self.sat_host.bridge.mucLeave(room_jid.userhost(), profile)
712 698
713 def jsonrpc_mucGetRoomsJoined(self): 699 def jsonrpc_mucGetRoomsJoined(self):
714 """Return list of room already joined by user""" 700 """Return list of room already joined by user"""
715 profile = ISATSession(self.session).profile 701 profile = session_iface.ISATSession(self.session).profile
716 return self.sat_host.bridge.mucGetRoomsJoined(profile) 702 return self.sat_host.bridge.mucGetRoomsJoined(profile)
717 703
718 def jsonrpc_mucGetDefaultService(self): 704 def jsonrpc_mucGetDefaultService(self):
719 """@return: the default MUC""" 705 """@return: the default MUC"""
720 d = self.asyncBridgeCall("mucGetDefaultService") 706 d = self.asyncBridgeCall("mucGetDefaultService")
724 """Create a room, invite the other players and start a Tarot game. 710 """Create a room, invite the other players and start a Tarot game.
725 711
726 @param other_players (list[unicode]): JIDs of the players to play with 712 @param other_players (list[unicode]): JIDs of the players to play with
727 @param room_jid (unicode): room JID or empty string to generate a unique name 713 @param room_jid (unicode): room JID or empty string to generate a unique name
728 """ 714 """
729 profile = ISATSession(self.session).profile 715 profile = session_iface.ISATSession(self.session).profile
730 self.sat_host.bridge.tarotGameLaunch(other_players, room_jid, profile) 716 self.sat_host.bridge.tarotGameLaunch(other_players, room_jid, profile)
731 717
732 def jsonrpc_getTarotCardsPaths(self): 718 def jsonrpc_getTarotCardsPaths(self):
733 """Give the path of all the tarot cards""" 719 """Give the path of all the tarot cards"""
734 _join = os.path.join 720 _join = os.path.join
735 _media_dir = _join(self.sat_host.media_dir, '') 721 _media_dir = _join(self.sat_host.media_dir, '')
736 return map(lambda x: _join(C.MEDIA_DIR, x[len(_media_dir):]), glob.glob(_join(_media_dir, C.CARDS_DIR, '*_*.png'))) 722 return map(lambda x: _join(C.MEDIA_DIR, x[len(_media_dir):]), glob.glob(_join(_media_dir, C.CARDS_DIR, '*_*.png')))
737 723
738 def jsonrpc_tarotGameReady(self, player, referee): 724 def jsonrpc_tarotGameReady(self, player, referee):
739 """Tell to the server that we are ready to start the game""" 725 """Tell to the server that we are ready to start the game"""
740 profile = ISATSession(self.session).profile 726 profile = session_iface.ISATSession(self.session).profile
741 self.sat_host.bridge.tarotGameReady(player, referee, profile) 727 self.sat_host.bridge.tarotGameReady(player, referee, profile)
742 728
743 def jsonrpc_tarotGamePlayCards(self, player_nick, referee, cards): 729 def jsonrpc_tarotGamePlayCards(self, player_nick, referee, cards):
744 """Tell to the server the cards we want to put on the table""" 730 """Tell to the server the cards we want to put on the table"""
745 profile = ISATSession(self.session).profile 731 profile = session_iface.ISATSession(self.session).profile
746 self.sat_host.bridge.tarotGamePlayCards(player_nick, referee, cards, profile) 732 self.sat_host.bridge.tarotGamePlayCards(player_nick, referee, cards, profile)
747 733
748 def jsonrpc_launchRadioCollective(self, invited, room_jid=""): 734 def jsonrpc_launchRadioCollective(self, invited, room_jid=""):
749 """Create a room, invite people, and start a radio collective. 735 """Create a room, invite people, and start a radio collective.
750 736
751 @param invited (list[unicode]): JIDs of the contacts to play with 737 @param invited (list[unicode]): JIDs of the contacts to play with
752 @param room_jid (unicode): room JID or empty string to generate a unique name 738 @param room_jid (unicode): room JID or empty string to generate a unique name
753 """ 739 """
754 profile = ISATSession(self.session).profile 740 profile = session_iface.ISATSession(self.session).profile
755 self.sat_host.bridge.radiocolLaunch(invited, room_jid, profile) 741 self.sat_host.bridge.radiocolLaunch(invited, room_jid, profile)
756 742
757 def jsonrpc_getEntitiesData(self, jids, keys): 743 def jsonrpc_getEntitiesData(self, jids, keys):
758 """Get cached data for several entities at once 744 """Get cached data for several entities at once
759 745
760 @param jids: list jids from who we wants data, or empty list for all jids in cache 746 @param jids: list jids from who we wants data, or empty list for all jids in cache
761 @param keys: name of data we want (list) 747 @param keys: name of data we want (list)
762 @return: requested data""" 748 @return: requested data"""
763 if not C.ALLOWED_ENTITY_DATA.issuperset(keys): 749 if not C.ALLOWED_ENTITY_DATA.issuperset(keys):
764 raise exceptions.PermissionError("Trying to access unallowed data (hack attempt ?)") 750 raise exceptions.PermissionError("Trying to access unallowed data (hack attempt ?)")
765 profile = ISATSession(self.session).profile 751 profile = session_iface.ISATSession(self.session).profile
766 try: 752 try:
767 return self.sat_host.bridge.getEntitiesData(jids, keys, profile) 753 return self.sat_host.bridge.getEntitiesData(jids, keys, profile)
768 except Exception as e: 754 except Exception as e:
769 raise failure.Failure(jsonrpclib.Fault(C.ERRNUM_BRIDGE_ERRBACK, unicode(e))) 755 raise failure.Failure(jsonrpclib.Fault(C.ERRNUM_BRIDGE_ERRBACK, unicode(e)))
770 756
774 @param jid: jid of contact from who we want data 760 @param jid: jid of contact from who we want data
775 @param keys: name of data we want (list) 761 @param keys: name of data we want (list)
776 @return: requested data""" 762 @return: requested data"""
777 if not C.ALLOWED_ENTITY_DATA.issuperset(keys): 763 if not C.ALLOWED_ENTITY_DATA.issuperset(keys):
778 raise exceptions.PermissionError("Trying to access unallowed data (hack attempt ?)") 764 raise exceptions.PermissionError("Trying to access unallowed data (hack attempt ?)")
779 profile = ISATSession(self.session).profile 765 profile = session_iface.ISATSession(self.session).profile
780 try: 766 try:
781 return self.sat_host.bridge.getEntityData(jid, keys, profile) 767 return self.sat_host.bridge.getEntityData(jid, keys, profile)
782 except Exception as e: 768 except Exception as e:
783 raise failure.Failure(jsonrpclib.Fault(C.ERRNUM_BRIDGE_ERRBACK, unicode(e))) 769 raise failure.Failure(jsonrpclib.Fault(C.ERRNUM_BRIDGE_ERRBACK, unicode(e)))
784 770
785 def jsonrpc_getCard(self, jid_): 771 def jsonrpc_getCard(self, jid_):
786 """Get VCard for entiry 772 """Get VCard for entiry
787 @param jid_: jid of contact from who we want data 773 @param jid_: jid of contact from who we want data
788 @return: id to retrieve the profile""" 774 @return: id to retrieve the profile"""
789 profile = ISATSession(self.session).profile 775 profile = session_iface.ISATSession(self.session).profile
790 return self.sat_host.bridge.getCard(jid_, profile) 776 return self.sat_host.bridge.getCard(jid_, profile)
791 777
792 @defer.inlineCallbacks 778 @defer.inlineCallbacks
793 def jsonrpc_avatarGet(self, entity, cache_only, hash_only): 779 def jsonrpc_avatarGet(self, entity, cache_only, hash_only):
794 session_data = ISATSession(self.session) 780 session_data = session_iface.ISATSession(self.session)
795 profile = session_data.profile 781 profile = session_data.profile
796 # profile_uuid = session_data.uuid 782 # profile_uuid = session_data.uuid
797 avatar = yield self.asyncBridgeCall("avatarGet", entity, cache_only, hash_only, profile) 783 avatar = yield self.asyncBridgeCall("avatarGet", entity, cache_only, hash_only, profile)
798 if hash_only: 784 if hash_only:
799 defer.returnValue(avatar) 785 defer.returnValue(avatar)
803 defer.returnValue(avatar_url) 789 defer.returnValue(avatar_url)
804 790
805 def jsonrpc_getAccountDialogUI(self): 791 def jsonrpc_getAccountDialogUI(self):
806 """Get the dialog for managing user account 792 """Get the dialog for managing user account
807 @return: XML string of the XMLUI""" 793 @return: XML string of the XMLUI"""
808 profile = ISATSession(self.session).profile 794 profile = session_iface.ISATSession(self.session).profile
809 return self.sat_host.bridge.getAccountDialogUI(profile) 795 return self.sat_host.bridge.getAccountDialogUI(profile)
810 796
811 def jsonrpc_getParamsUI(self): 797 def jsonrpc_getParamsUI(self):
812 """Return the parameters XML for profile""" 798 """Return the parameters XML for profile"""
813 profile = ISATSession(self.session).profile 799 profile = session_iface.ISATSession(self.session).profile
814 return self.asyncBridgeCall("getParamsUI", C.SECURITY_LIMIT, C.APP_NAME, profile) 800 return self.asyncBridgeCall("getParamsUI", C.SECURITY_LIMIT, C.APP_NAME, profile)
815 801
816 def jsonrpc_asyncGetParamA(self, param, category, attribute="value"): 802 def jsonrpc_asyncGetParamA(self, param, category, attribute="value"):
817 """Return the parameter value for profile""" 803 """Return the parameter value for profile"""
818 profile = ISATSession(self.session).profile 804 profile = session_iface.ISATSession(self.session).profile
819 if category == "Connection": 805 if category == "Connection":
820 # we need to manage the followings params here, else SECURITY_LIMIT would block them 806 # we need to manage the followings params here, else SECURITY_LIMIT would block them
821 if param == "JabberID": 807 if param == "JabberID":
822 return self.asyncBridgeCall("asyncGetParamA", param, category, attribute, profile_key=profile) 808 return self.asyncBridgeCall("asyncGetParamA", param, category, attribute, profile_key=profile)
823 elif param == "autoconnect": 809 elif param == "autoconnect":
824 return defer.succeed(C.BOOL_TRUE) 810 return defer.succeed(C.BOOL_TRUE)
825 d = self.asyncBridgeCall("asyncGetParamA", param, category, attribute, C.SECURITY_LIMIT, profile_key=profile) 811 d = self.asyncBridgeCall("asyncGetParamA", param, category, attribute, C.SECURITY_LIMIT, profile_key=profile)
826 return d 812 return d
827 813
828 def jsonrpc_setParam(self, name, value, category): 814 def jsonrpc_setParam(self, name, value, category):
829 profile = ISATSession(self.session).profile 815 profile = session_iface.ISATSession(self.session).profile
830 return self.sat_host.bridge.setParam(name, value, category, C.SECURITY_LIMIT, profile) 816 return self.sat_host.bridge.setParam(name, value, category, C.SECURITY_LIMIT, profile)
831 817
832 def jsonrpc_launchAction(self, callback_id, data): 818 def jsonrpc_launchAction(self, callback_id, data):
833 #FIXME: any action can be launched, this can be a huge security issue if callback_id can be guessed 819 #FIXME: any action can be launched, this can be a huge security issue if callback_id can be guessed
834 # a security system with authorised callback_id must be implemented, similar to the one for authorised params 820 # a security system with authorised callback_id must be implemented, similar to the one for authorised params
835 profile = ISATSession(self.session).profile 821 profile = session_iface.ISATSession(self.session).profile
836 d = self.asyncBridgeCall("launchAction", callback_id, data, profile) 822 d = self.asyncBridgeCall("launchAction", callback_id, data, profile)
837 return d 823 return d
838 824
839 def jsonrpc_chatStateComposing(self, to_jid_s): 825 def jsonrpc_chatStateComposing(self, to_jid_s):
840 """Call the method to process a "composing" state. 826 """Call the method to process a "composing" state.
841 @param to_jid_s: contact the user is composing to 827 @param to_jid_s: contact the user is composing to
842 """ 828 """
843 profile = ISATSession(self.session).profile 829 profile = session_iface.ISATSession(self.session).profile
844 self.sat_host.bridge.chatStateComposing(to_jid_s, profile) 830 self.sat_host.bridge.chatStateComposing(to_jid_s, profile)
845 831
846 def jsonrpc_getNewAccountDomain(self): 832 def jsonrpc_getNewAccountDomain(self):
847 """@return: the domain for new account creation""" 833 """@return: the domain for new account creation"""
848 d = self.asyncBridgeCall("getNewAccountDomain") 834 d = self.asyncBridgeCall("getNewAccountDomain")
853 @param text: text to convert 839 @param text: text to convert
854 @param syntax_from: source syntax (e.g. "markdown") 840 @param syntax_from: source syntax (e.g. "markdown")
855 @param syntax_to: dest syntax (e.g.: "XHTML") 841 @param syntax_to: dest syntax (e.g.: "XHTML")
856 @param safe: clean resulting XHTML to avoid malicious code if True (forced here) 842 @param safe: clean resulting XHTML to avoid malicious code if True (forced here)
857 @return: converted text """ 843 @return: converted text """
858 profile = ISATSession(self.session).profile 844 profile = session_iface.ISATSession(self.session).profile
859 return self.sat_host.bridge.syntaxConvert(text, syntax_from, syntax_to, True, profile) 845 return self.sat_host.bridge.syntaxConvert(text, syntax_from, syntax_to, True, profile)
860 846
861 def jsonrpc_getLastResource(self, jid_s): 847 def jsonrpc_getLastResource(self, jid_s):
862 """Get the last active resource of that contact.""" 848 """Get the last active resource of that contact."""
863 profile = ISATSession(self.session).profile 849 profile = session_iface.ISATSession(self.session).profile
864 return self.sat_host.bridge.getLastResource(jid_s, profile) 850 return self.sat_host.bridge.getLastResource(jid_s, profile)
865 851
866 def jsonrpc_getFeatures(self): 852 def jsonrpc_getFeatures(self):
867 """Return the available features in the backend for profile""" 853 """Return the available features in the backend for profile"""
868 profile = ISATSession(self.session).profile 854 profile = session_iface.ISATSession(self.session).profile
869 return self.sat_host.bridge.getFeatures(profile) 855 return self.sat_host.bridge.getFeatures(profile)
870 856
871 def jsonrpc_skipOTR(self): 857 def jsonrpc_skipOTR(self):
872 """Tell the backend to leave OTR handling to Libervia.""" 858 """Tell the backend to leave OTR handling to Libervia."""
873 profile = ISATSession(self.session).profile 859 profile = session_iface.ISATSession(self.session).profile
874 return self.sat_host.bridge.skipOTR(profile) 860 return self.sat_host.bridge.skipOTR(profile)
875 861
876 862
877 class WaitingRequests(dict): 863 class WaitingRequests(dict):
878 864
938 _session = request.getSession() 924 _session = request.getSession()
939 parsed = jsonrpclib.loads(request.content.read()) 925 parsed = jsonrpclib.loads(request.content.read())
940 method = parsed.get("method") # pylint: disable=E1103 926 method = parsed.get("method") # pylint: disable=E1103
941 if method not in ['getSessionMetadata', 'registerParams', 'menusGet']: 927 if method not in ['getSessionMetadata', 'registerParams', 'menusGet']:
942 #if we don't call these methods, we need to be identified 928 #if we don't call these methods, we need to be identified
943 profile = ISATSession(_session).profile 929 profile = session_iface.ISATSession(_session).profile
944 if not profile: 930 if not profile:
945 #user is not identified, we return a jsonrpc fault 931 #user is not identified, we return a jsonrpc fault
946 fault = jsonrpclib.Fault(C.ERRNUM_LIBERVIA, C.NOT_ALLOWED) # FIXME: define some standard error codes for libervia 932 fault = jsonrpclib.Fault(C.ERRNUM_LIBERVIA, C.NOT_ALLOWED) # FIXME: define some standard error codes for libervia
947 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc')) # pylint: disable=E1103 933 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc')) # pylint: disable=E1103
948 self.request = request 934 self.request = request
1119 - C.SESSION_ACTIVE 1105 - C.SESSION_ACTIVE
1120 """ 1106 """
1121 register_with_ext_jid = self.waiting_profiles.getRegisterWithExtJid(profile) 1107 register_with_ext_jid = self.waiting_profiles.getRegisterWithExtJid(profile)
1122 self.waiting_profiles.purgeRequest(profile) 1108 self.waiting_profiles.purgeRequest(profile)
1123 _session = request.getSession() 1109 _session = request.getSession()
1124 sat_session = ISATSession(_session) 1110 sat_session = session_iface.ISATSession(_session)
1125 if sat_session.profile: 1111 if sat_session.profile:
1126 log.error(_(u'/!\\ Session has already a profile, this should NEVER happen!')) 1112 log.error(_(u'/!\\ Session has already a profile, this should NEVER happen!'))
1127 request.write(C.SESSION_ACTIVE) 1113 request.write(C.SESSION_ACTIVE)
1128 request.finish() 1114 request.finish()
1129 return 1115 return
1152 request.write(C.PROFILE_LOGGED_REGISTERED_WITH_EXT_JID if register_with_ext_jid else C.PROFILE_LOGGED) 1138 request.write(C.PROFILE_LOGGED_REGISTERED_WITH_EXT_JID if register_with_ext_jid else C.PROFILE_LOGGED)
1153 request.finish() 1139 request.finish()
1154 1140
1155 def jsonrpc_isConnected(self): 1141 def jsonrpc_isConnected(self):
1156 _session = self.request.getSession() 1142 _session = self.request.getSession()
1157 profile = ISATSession(_session).profile 1143 profile = session_iface.ISATSession(_session).profile
1158 return self.sat_host.bridge.isConnected(profile) 1144 return self.sat_host.bridge.isConnected(profile)
1159 1145
1160 def jsonrpc_connect(self): 1146 def jsonrpc_connect(self):
1161 _session = self.request.getSession() 1147 _session = self.request.getSession()
1162 profile = ISATSession(_session).profile 1148 profile = session_iface.ISATSession(_session).profile
1163 if self.waiting_profiles.getRequest(profile): 1149 if self.waiting_profiles.getRequest(profile):
1164 raise jsonrpclib.Fault(1, C.ALREADY_WAITING) # FIXME: define some standard error codes for libervia 1150 raise jsonrpclib.Fault(1, C.ALREADY_WAITING) # FIXME: define some standard error codes for libervia
1165 self.waiting_profiles.setRequest(self.request, profile) 1151 self.waiting_profiles.setRequest(self.request, profile)
1166 self.sat_host.bridge.connect(profile) 1152 self.sat_host.bridge.connect(profile)
1167 return server.NOT_DONE_YET 1153 return server.NOT_DONE_YET
1179 - registered: 1165 - registered:
1180 - message: 1166 - message:
1181 """ 1167 """
1182 metadata = {} 1168 metadata = {}
1183 _session = self.request.getSession() 1169 _session = self.request.getSession()
1184 profile = ISATSession(_session).profile 1170 profile = session_iface.ISATSession(_session).profile
1185 if profile: 1171 if profile:
1186 metadata["plugged"] = True 1172 metadata["plugged"] = True
1187 else: 1173 else:
1188 metadata["plugged"] = False 1174 metadata["plugged"] = False
1189 metadata["warning"] = self._getSecurityWarning() 1175 metadata["warning"] = self._getSecurityWarning()
1233 1219
1234 def jsonrpc_getSignals(self): 1220 def jsonrpc_getSignals(self):
1235 """Keep the connection alive until a signal is received, then send it 1221 """Keep the connection alive until a signal is received, then send it
1236 @return: (signal, *signal_args)""" 1222 @return: (signal, *signal_args)"""
1237 _session = self.request.getSession() 1223 _session = self.request.getSession()
1238 profile = ISATSession(_session).profile 1224 profile = session_iface.ISATSession(_session).profile
1239 if profile in self.queue: # if we have signals to send in queue 1225 if profile in self.queue: # if we have signals to send in queue
1240 if self.queue[profile]: 1226 if self.queue[profile]:
1241 return self.queue[profile].pop(0) 1227 return self.queue[profile].pop(0)
1242 else: 1228 else:
1243 #the queue is empty, we delete the profile from queue 1229 #the queue is empty, we delete the profile from queue
1330 """ 1316 """
1331 Render method wich reject access if user is not identified 1317 Render method wich reject access if user is not identified
1332 """ 1318 """
1333 _session = request.getSession() 1319 _session = request.getSession()
1334 parsed = jsonrpclib.loads(request.content.read()) 1320 parsed = jsonrpclib.loads(request.content.read())
1335 profile = ISATSession(_session).profile 1321 profile = session_iface.ISATSession(_session).profile
1336 if not profile: 1322 if not profile:
1337 #user is not identified, we return a jsonrpc fault 1323 #user is not identified, we return a jsonrpc fault
1338 fault = jsonrpclib.Fault(C.ERRNUM_LIBERVIA, C.NOT_ALLOWED) # FIXME: define some standard error codes for libervia 1324 fault = jsonrpclib.Fault(C.ERRNUM_LIBERVIA, C.NOT_ALLOWED) # FIXME: define some standard error codes for libervia
1339 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc')) # pylint: disable=E1103 1325 return jsonrpc.JSONRPC._cbRender(self, fault, request, parsed.get('id'), parsed.get('jsonrpc')) # pylint: disable=E1103
1340 self.request = request 1326 self.request = request
1410 @param request: HTTP request object 1396 @param request: HTTP request object
1411 @param filepath: full filepath on the server 1397 @param filepath: full filepath on the server
1412 @return: a tuple with the name of the async bridge method 1398 @return: a tuple with the name of the async bridge method
1413 to be called followed by its arguments. 1399 to be called followed by its arguments.
1414 """ 1400 """
1415 profile = ISATSession(request.getSession()).profile 1401 profile = session_iface.ISATSession(request.getSession()).profile
1416 return ("radiocolSongAdded", request.args['referee'][0], filepath, profile) 1402 return ("radiocolSongAdded", request.args['referee'][0], filepath, profile)
1417 1403
1418 1404
1419 class UploadManagerAvatar(UploadManager): 1405 class UploadManagerAvatar(UploadManager):
1420 NAME = 'avatar_path' 1406 NAME = 'avatar_path'
1427 @param request: HTTP request object 1413 @param request: HTTP request object
1428 @param filepath: full filepath on the server 1414 @param filepath: full filepath on the server
1429 @return: a tuple with the name of the async bridge method 1415 @return: a tuple with the name of the async bridge method
1430 to be called followed by its arguments. 1416 to be called followed by its arguments.
1431 """ 1417 """
1432 profile = ISATSession(request.getSession()).profile 1418 profile = session_iface.ISATSession(request.getSession()).profile
1433 return ("setAvatar", filepath, profile) 1419 return ("setAvatar", filepath, profile)
1434 1420
1435 1421
1436 class LiberviaPage(web_resource.Resource): 1422 class LiberviaPage(web_resource.Resource):
1437 isLeaf = True # we handle subpages ourself 1423 isLeaf = True # we handle subpages ourself
1783 self._startService() 1769 self._startService()
1784 1770
1785 self.initialised.addCallback(initOk) 1771 self.initialised.addCallback(initOk)
1786 1772
1787 ## URLs ## 1773 ## URLs ##
1774
1788 def putChild(self, path, resource): 1775 def putChild(self, path, resource):
1789 """Add a child to the root resource""" 1776 """Add a child to the root resource"""
1790 # FIXME: check that no information is leaked (c.f. https://twistedmatrix.com/documents/current/web/howto/using-twistedweb.html#request-encoders) 1777 # FIXME: check that no information is leaked (c.f. https://twistedmatrix.com/documents/current/web/howto/using-twistedweb.html#request-encoders)
1791 self.root.putChild(path, web_resource.EncodingResourceWrapper(resource, [server.GzipEncoderFactory()])) 1778 self.root.putChild(path, web_resource.EncodingResourceWrapper(resource, [server.GzipEncoderFactory()]))
1792 1779
1930 netloc = request.URLPath().netloc.replace(':%s' % self.old_port, ':%s' % self.new_port) 1917 netloc = request.URLPath().netloc.replace(':%s' % self.old_port, ':%s' % self.new_port)
1931 url = "https://" + netloc + request.uri 1918 url = "https://" + netloc + request.uri
1932 return web_util.redirectTo(url, request) 1919 return web_util.redirectTo(url, request)
1933 1920
1934 1921
1935 registerAdapter(SATSession, server.Session, ISATSession) 1922 registerAdapter(session_iface.SATSession, server.Session, session_iface.ISATSession)
1923 registerAdapter(session_iface.SATGuestSession, server.Session, session_iface.ISATGuestSession)