Esempio n. 1
0
def read_message(mobile_number, message, auto_mode=True):
    index, keyword, message_array = parse(message)

    # *ensure* that there is both a device with that number and a corresponding contributor
    devices = Device.objects.filter(phone_number=mobile_number)
    if len(devices) > 0:
        device = devices[0]
        # check if user exists; otherwise create an unknown user
        if device.contributor is None:
            logger.debug("found mobile device " + str(device) + " without a contributor")
            logger.debug("creating a new contributor")
            contributor = Contributor(name=mobile_number,
                        email=mobile_number + "@feowl.com",
                        status=Contributor.UNKNOWN)
            # if we can deduce the language from the current keyword, set
            #  contributor language
            if keyword in kw2lang:
                contributor.language = kw2lang[keyword].upper()
            contributor.save()
            device.contributor = contributor
            device.save()
        else:
            contributor = device.contributor
    else:
        logger.debug("device does not exist")
        logger.debug("creating a new device and contributor")
        # create a new user (potentially with language) and device
        (device, contributor) = create_unknown_user(mobile_number)
        if keyword in kw2lang:
            contributor.language = kw2lang[keyword].upper()
        contributor.save()
    logger.debug("associating incoming message with " + str(device) + " // " + str(contributor))

    # set the language for upcoming messages
    language = (keyword in kw2lang and kw2lang[keyword]) or contributor.language or "en"
    activate(language.lower())

    # invariant: if we arrive here, we are sure that we have a device
    #  and a contributor. now, do the processing
    if keyword in ("pc", "rep"):
        return contribute(message_array, device, auto_mode)
    if keyword in ("pcm", "repm"):
        return contribute_multiple(message_array, device, auto_mode)
    elif keyword in ("help", "aide"):
        return help(message_array, device, auto_mode)
    elif keyword in ("register", "inscription"):
        return register(message_array, device, auto_mode)
    elif keyword == "stop":
        return unregister(message_array, device, auto_mode)
    elif keyword in ("cancel", "annule"):
        return cancel(message_array, device. auto_mode)
    elif keyword in ("test"):
        return test(message_array, device, auto_mode)
    elif index == -1:  # Should send an error messages and maybe plus help
        return invalid(message_array, device, auto_mode)