Example #1
0
	def SetAliases(self, aliases):
		_moduleLogger.debug("Called SetAliases")
		# first validate that no other handle types are included
		handleId, alias = None, None
		for handleId, alias in aliases.iteritems():
			h = self.get_handle_by_id(telepathy.HANDLE_TYPE_CONTACT, handleId)
			if isinstance(h, handle.ConnectionHandle):
				break
		else:
			raise telepathy.errors.PermissionDenied("No user customizable aliases")

		uglyNumber = misc_utils.normalize_number(alias)
		if len(uglyNumber) == 0:
			# Reset to the original from login if one was provided
			uglyNumber = self.callbackNumberParameter
		if not misc_utils.is_valid_number(uglyNumber):
			raise telepathy.errors.InvalidArgument("Invalid phone number %r" % (uglyNumber, ))

		# Update callback
		self.session.backend.set_callback_number(uglyNumber)

		# Inform of change
		userAlias = make_pretty(uglyNumber)
		changedAliases = ((handleId, userAlias), )
		self.AliasesChanged(changedAliases)
Example #2
0
	def _call(self, contact):
		contactNumber = contact.phoneNumber

		self.__calledNumber = contactNumber
		self.CallStateChanged(self.__contactHandle, telepathy.constants.CHANNEL_CALL_STATE_RINGING)

		self._delayedClose.start(seconds=0)
		self.CallStateChanged(self.__contactHandle, telepathy.constants.CHANNEL_CALL_STATE_FORWARDED)

		try:
			result = yield (
				self._conn.session.backend.call,
				(contactNumber, ),
				{},
			)
		except Exception, e:
			_moduleLogger.exception("While placing call to %s" % (self.__calledNumber, ))
			self._conn.force_log_display()
			accountNumber = misc_utils.normalize_number(self._conn.session.backend.get_account_number())
			self._conn.log_to_user(
				__name__,
				"Error while placing call from %s to %s:\n%s" % (
					accountNumber, self.__calledNumber, str(e)
				)
			)
			return
Example #3
0
 def _populate_contacts(self, contacts):
     numbers = {}
     for contactId, contactDetails in contacts:
         contactName = contactDetails["name"]
         contactNumbers = (
             (misc_utils.normalize_number(numberDetails["phoneNumber"]), numberDetails.get("phoneType", "Mobile"))
             for numberDetails in contactDetails["numbers"]
         )
         numbers.update((number, (contactName, phoneType, contactDetails)) for (number, phoneType) in contactNumbers)
     return numbers
	def _get_text_channel(self, props):
		_, surpress_handler, h = self._get_type_requested_handle(props)

		accountNumber = misc_utils.normalize_number(self._conn.session.backend.get_account_number())
		if h.phoneNumber == accountNumber:
			_moduleLogger.debug('New Debug channel')
			chan = channel.debug_prompt.DebugPromptChannel(self._conn, self, props, h)
		else:
			_moduleLogger.debug('New text channel')
			chan = channel.text.TextChannel(self._conn, self, props, h)
		return chan
Example #5
0
def make_pretty(phonenumber):
	"""
	Function to take a phone number and return the pretty version
	pretty numbers:
		if phonenumber begins with 0:
			...-(...)-...-....
		if phonenumber begins with 1: ( for gizmo callback numbers )
			1 (...)-...-....
		if phonenumber is 13 digits:
			(...)-...-....
		if phonenumber is 10 digits:
			...-....
	>>> make_pretty("12")
	'12'
	>>> make_pretty("1234567")
	'123-4567'
	>>> make_pretty("2345678901")
	'+1 (234) 567-8901'
	>>> make_pretty("12345678901")
	'+1 (234) 567-8901'
	>>> make_pretty("01234567890")
	'+012 (345) 678-90'
	>>> make_pretty("+01234567890")
	'+012 (345) 678-90'
	>>> make_pretty("+12")
	'+1 (2)'
	>>> make_pretty("+123")
	'+1 (23)'
	>>> make_pretty("+1234")
	'+1 (234)'
	"""
	if phonenumber is None or phonenumber == "":
		return ""

	phonenumber = misc_utils.normalize_number(phonenumber)

	if phonenumber == "":
		return ""
	elif phonenumber[0] == "+":
		prettynumber = _make_pretty_international(phonenumber[1:])
		if not prettynumber.startswith("+"):
			prettynumber = "+"+prettynumber
	elif 8 < len(phonenumber) and phonenumber[0] in ("0", "1"):
		prettynumber = _make_pretty_international(phonenumber)
	elif 7 < len(phonenumber):
		prettynumber = _make_pretty_with_areacode(phonenumber)
	elif 3 < len(phonenumber):
		prettynumber = _make_pretty_local(phonenumber)
	else:
		prettynumber = phonenumber
	return prettynumber.strip()
Example #6
0
	def _select_avatar(self, handleId):
		handle = self.get_handle_by_id(telepathy.HANDLE_TYPE_CONTACT, handleId)

		if handle == self.GetSelfHandle():
			imageName = self.__SELF_AVATAR
		else:
			accountNumber = misc_utils.normalize_number(self.session.backend.get_account_number())
			phoneType = self.session.addressbook.get_phone_type(handle.phoneNumber)
			if handle.phoneNumber == accountNumber:
				imageName = self.__SELF_AVATAR
			elif phoneType in ("mobile", ):
				imageName = self.__MOBILE_AVATAR
			elif phoneType in ("home", "work"):
				imageName = self.__LANDLINE_AVATAR
			else:
				imageName = self.__OTHER_AVATAR

		return imageName
Example #7
0
    def _on_login(self, *args):
        _moduleLogger.info("Connected, setting up...")
        try:
            self.session.load(self.__cachePath)

            for plumber in self._plumbing:
                plumber.start()
            if not self.__callbackNumberParameter:
                callback = gvoice.backend.get_sane_callback(self.session.backend)
                self.__callbackNumberParameter = misc_utils.normalize_number(callback)
            self.session.backend.set_callback_number(self.__callbackNumberParameter)

            subscribeHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "subscribe")
            subscribeProps = self.generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, subscribeHandle, False)
            self.__channelManager.channel_for_props(subscribeProps, signal=True)
        except Exception:
            _moduleLogger.exception("Setup failed")
            self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
            return

        _moduleLogger.info("Connected and set up")
        self.StatusChanged(telepathy.CONNECTION_STATUS_CONNECTED, telepathy.CONNECTION_STATUS_REASON_REQUESTED)
Example #8
0
    def __init__(self, manager, parameters):
        self._loggers = []

        self.check_parameters(parameters)
        account = unicode(parameters["account"])
        encodedAccount = parameters["account"].encode("utf-8")
        encodedPassword = parameters["password"].encode("utf-8")
        encodedCallback = misc_utils.normalize_number(parameters["forward"].encode("utf-8"))
        if encodedCallback and not misc_utils.is_valid_number(encodedCallback):
            raise telepathy.errors.InvalidArgument("Invalid forwarding number")

            # Connection init must come first
        self.__options = TheOneRingOptions(parameters)
        self.__accountName = account
        self.__session = None
        tp.Connection.__init__(
            self, constants._telepathy_protocol_name_, account, constants._telepathy_implementation_name_
        )
        aliasing.AliasingMixin.__init__(self)
        avatars.AvatarsMixin.__init__(self)
        capabilities.CapabilitiesMixin.__init__(self)
        contacts.ContactsMixin.__init__(self)
        requests.RequestsMixin.__init__(self)
        simple_presence.TheOneRingPresence.__init__(self, self.__options.ignoreDND)
        simple_presence.SimplePresenceMixin.__init__(self, self)
        presence.PresenceMixin.__init__(self, self)

        self.__manager = weakref.proxy(manager)
        self.__credentials = (encodedAccount, encodedPassword)
        self.__callbackNumberParameter = encodedCallback
        self.__channelManager = channel_manager.ChannelManager(self)

        self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
        try:
            os.makedirs(self.__cachePath)
        except OSError, e:
            if e.errno != 17:
                raise
Example #9
0
	def _update(self):
		try:
			conversationResult = yield (
				self._get_raw_conversations,
				(),
				{},
			)
		except Exception:
			_moduleLogger.exception("%s While updating conversations" % (self._name, ))
			return

		oldConversationIds = set(self._conversations.iterkeys())

		updateConversationIds = set()
		conversations = list(conversationResult)
		conversations.sort()
		for conversation in conversations:
			key = misc_utils.normalize_number(conversation.number)
			try:
				mergedConversations = self._conversations[key]
			except KeyError:
				mergedConversations = MergedConversations()
				self._conversations[key] = mergedConversations

			if self._loadedFromCache or self._hasDoneUpdate:
				markAllAsRead = False
			else:
				markAllAsRead = True

			try:
				mergedConversations.append_conversation(conversation, markAllAsRead)
				isConversationUpdated = True
			except ConversationError, e:
				isConversationUpdated = False
			except AssertionError, e:
				_moduleLogger.debug("%s Skipping conversation for %r because '%s'" % (self._name, key, e))
				isConversationUpdated = False
Example #10
0
 def force_log_display(self):
     accountNumber = misc_utils.normalize_number(self.session.backend.get_account_number())
     debugHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, accountNumber)
     debugPromptProps = self.generate_props(telepathy.CHANNEL_TYPE_TEXT, debugHandle, False)
     self.__channelManager.channel_for_props(debugPromptProps, signal=True)
Example #11
0
	def __init__(self, connection, id, phoneNumber):
		self._phoneNumber = misc_utils.normalize_number(phoneNumber)

		handleType = telepathy.HANDLE_TYPE_CONTACT
		handleName = self._phoneNumber
		TheOneRingHandle.__init__(self, connection, id, handleType, handleName)