Exemplo n.º 1
0
def sms():
    if request.method == 'POST':
        print >> sys.stderr, "Received POST request to /plivo/sms/" # this is how you write messages to yourself in the Apache /var/log/apache2/error.log
        try:
            s = SMS(timeAnswered = datetime.datetime.now(),
                                action = 'super text',
                                direction = 'incoming',
                                smsTo = request.form['To'],
                                smsType = request.form['Type'],
                                smsMessageUUID = request.form['MessageUUID'],
                                smsFrom = request.form['From'],
                                smsText = request.form['Text'],
                                )
            print >> sys.stderr, s.direction
            s.save()
            message = request.form['Text'].lower()
            #response = showtimeandloc(message)
            #Dispatcher for the various commands
            try:
                response = commands[message[0]](message)
            except:
                response = "This was not a valid command.  Try @,!,g, or h.  H for help."

            print >> sys.stderr, response
            caller = request.form['From']
            if User.query.filter(User.number == caller).first():
                if type(response) == type(dict()):
                    regisUser = User.query.filter(User.number == caller).first()
                    location = response['location']
                    print >> sys.stderr, location
                    hours = int(response['hours'])
                    print >> sys.stderr, hours
                    timeExpired = datetime.datetime.now() + datetime.timedelta(hours=hours)
                    print >> sys.stderr, timeExpired
                    condition = 'safe'
                    newStatus = Status(location=location,timeEntered=datetime.datetime.now(),timeExpired=timeExpired,condition=condition)
                    newStatus.save()
                    regisUser.status = newStatus
                    regisUser.save()
                    yourStatus = 'We know you are at ' + location + ' for ' + str(hours) + ' hours. Now we are watching you.'
                    send_txt(caller,yourStatus.upper())
                elif type(response) == type(str()):
                    send_txt(caller,response.upper(), src=MASTER_NUMBER)
                else:
                    oops = 'Sorry. Please make sure you enter your status in this format: @ location 4 numberofhours.'
                    send_txt(caller,oops.upper())
            else:
                response = "Welcome to Panoptincon, where we aren't always watching. Your default location is Speke Apartments."
                timeExpired = datetime.datetime.now() + datetime.timedelta(hours=24)
                newStatus = Status(location='Speke Apartments',timeEntered=datetime.datetime.now(),timeExpired=timeExpired,condition='safe')
                newStatus.save()
                newUser = User(number=caller, status=newStatus, createdAt=datetime.datetime.now(), name=message, isChin=False)
                newUser.save()
                send_txt(caller,response.upper(), src=MASTER_NUMBER)
        except:
            print >> sys.stderr, str(sys.exc_info()[0])
            print >> sys.stderr, str(sys.exc_info()[1])
            #entering the gateway where stuff happens!
    else:
        return "These aren't the droids you're looking for. Move along, move along."
Exemplo n.º 2
0
def store_SMS(message):
    print >> sys.stderr, "within store SMS"
    number = create_Number(message) # gets number from incoming SMS
    numberID = store_Number(number) # creates and stores number as Number object
    newSMS = SMS(sms_id = message['_id'], body = message['body'].lower(), date = message['date'], number = numberID)
    newSMS.save()
    return newSMS
Exemplo n.º 3
0
def create_tables():
    Number.create_table(True)
    SMS.create_table(True)
    Seller.create_table(True)
    Market.create_table(True)
    List.create_table(True)
    ListRelationship.create_table(True)
    Outbox.create_table(True)
Exemplo n.º 4
0
def recipient_is(name, TRAIN=0.9):
    #: TRAIN = percent of the data to have in training set
    train = {}
    test = {}
    person = Contact.get(name=name)
    recipient = set(SMS.select().where(contact=person).where(from_me=False))
    not_recipient = set(SMS.select().where(contact__ne=person).where(from_me=False))

    train[person.name], test[person.name] = split_set(recipient, TRAIN)
    train["not_" + person.name], test["not_" + person.name] = split_set(not_recipient, TRAIN)

    return train, test
Exemplo n.º 5
0
def split_me_not_me(TRAIN_SIZE=0.9):
    train, test = {}, {}

    not_me = SMS.select().where(from_me=False)
    me = SMS.select().where(from_me=True)

    not_me = set(not_me)
    me = set(me)

    train["me"], test["me"] = split_set(me, TRAIN_SIZE)
    train["not_me"], test["not_me"] = split_set(not_me, TRAIN_SIZE)

    return train, test
Exemplo n.º 6
0
def split_me_not_me(TRAIN_SIZE=0.9):
    train, test = {}, {}

    not_me = SMS.select().where(from_me=False)
    me = SMS.select().where(from_me=True)

    not_me = set(not_me)
    me = set(me)

    train['me'], test['me'] = split_set(me, TRAIN_SIZE)
    train['not_me'], test['not_me'] = split_set(not_me, TRAIN_SIZE)

    return train, test
Exemplo n.º 7
0
def recipient_is(name, TRAIN=0.9):
    #: TRAIN = percent of the data to have in training set
    train = {}
    test = {}
    person = Contact.get(name=name)
    recipient = set(SMS.select().where(contact=person).where(from_me=False))
    not_recipient = set(
        SMS.select().where(contact__ne=person).where(from_me=False))

    train[person.name], test[person.name] = split_set(recipient, TRAIN)
    train['not_' + person.name], test['not_' + person.name] = \
            split_set(not_recipient, TRAIN)

    return train, test
Exemplo n.º 8
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobiles',
                            type=list,
                            required=True,
                            help='A mobiles list field is require',
                            location='json')
        parser.add_argument('content',
                            type=unicode,
                            required=True,
                            help='A content field is require',
                            location='json')
        args = parser.parse_args()
        try:
            sms = SMS(mobiles=json.dumps(request.json['mobiles']),
                      content=request.json['content'],
                      returned_value=-99,
                      user_id=1)
            db.session.add(sms)
            db.session.commit()
            sms_ini = app.config['SMS_WSDL_PARAMS']
            sms_client = SMSClient(sms_ini['url'])
            sms_client.sms_init(sms_ini['db_ip'], sms_ini['db_name'],
                                sms_ini['db_port'], sms_ini['user'],
                                sms_ini['pwd'])
            r = sms_client.sms_send(sms_ini['user'], sms_ini['user'],
                                    sms_ini['pwd'], request.json['mobiles'],
                                    request.json['content'], sms.id)
            sms.returned_value = r
            db.session.commit()
            del sms_client
        except Exception as e:
            logger.error(e)
            raise
        result = {
            'id': sms.id,
            'mobiles': json.loads(sms.mobiles),
            'date_send': str(sms.date_send),
            'content': sms.content,
            'user_id': sms.user_id,
            'returned_value': sms.returned_value
        }
        if sms.returned_value == 0:
            result['succeed'] = True
        else:
            result['succeed'] = False

        return result, 201
Exemplo n.º 9
0
def send_sms(number, text):
    sms = SMS()
    sms.number = number
    sms.text = text
    sms.state = SMS.STATE_NEW
    sms.received = False
    sms.save()
    add_processor_jobs(sms)
Exemplo n.º 10
0
def sms():
    if request.method == 'POST':
        print >> sys.stderr, "Received POST request to /plivo/sms/" # this is how you write messages to yourself in the Apache /var/log/apache2/error.log
        try:
            s = SMS(timeAnswered = datetime.datetime.now(),
                    direction = 'incoming',
                    smsTo = request.form['To'],
                    smsType = request.form['Type'],
                    smsMessageUUID = request.form['MessageUUID'],
                    smsFrom = request.form['From'],
                    smsText = request.form['Text'],
                    )
            s.save()
            send_txt(s.smsFrom,s.smsText.upper())
        except:
            print >> sys.stderr, str(sys.exc_info()[0]) # These write the nature of the error
            print >> sys.stderr, str(sys.exc_info()[1]) 
    else:
        return "These aren't the droids you're looking for.  Move along, move along."
Exemplo n.º 11
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobiles', type=list, required=True,
                            help='A mobiles list field is require',
                            location='json')
        parser.add_argument('content', type=unicode, required=True,
                            help='A content field is require', location='json')
        args = parser.parse_args()
        try:
            sms = SMS(mobiles=json.dumps(request.json['mobiles']),
                      content=request.json['content'],
                      returned_value=-99, user_id=1)
            db.session.add(sms)
            db.session.commit()
            sms_ini = app.config['SMS_WSDL_PARAMS']
            sms_client = SMSClient(sms_ini['url'])
            sms_client.sms_init(sms_ini['db_ip'], sms_ini['db_name'],
                                sms_ini['db_port'], sms_ini['user'],
                                sms_ini['pwd'])
            r = sms_client.sms_send(sms_ini['user'], sms_ini['user'],
                                    sms_ini['pwd'],request.json['mobiles'],
                                    request.json['content'], sms.id)
            sms.returned_value = r
            db.session.commit()
            del sms_client
        except Exception as e:
            logger.error(e)
            raise
        result = {
            'id': sms.id,
            'mobiles': json.loads(sms.mobiles),
            'date_send': str(sms.date_send),
            'content': sms.content,
            'user_id': sms.user_id,
            'returned_value': sms.returned_value
        }
        if sms.returned_value == 0:
            result['succeed'] = True
        else:
            result['succeed'] = False

        return result, 201
Exemplo n.º 12
0
def gv_to_db(me):
    files = os.listdir(settings.CONVERSATIONS_DIR)
    os.chdir(settings.CONVERSATIONS_DIR)
    files = [f for f in files if f.endswith('html')]

    database.set_autocommit(False)

    print len(files)
    count = 1
    for f in files:
        print str(count) + '. ' + f
        count += 1

        # set name
        name = parse.parse('{} - {}', f).fixed[0]

        soup = BeautifulSoup(open(f))
        chat = soup.find('div', {'class': 'hChatLog hfeed'})
        if not chat:
            continue

        messages = chat.findAll('div', {'class': 'message'})
        for message in messages:
            # time
            t = message.find('abbr', {'class': 'dt'})
            if t.get('title'):
                time = parse.parse('{:ti}', t.get('title')).fixed[0]

            # telephone number
            tel = message.find('a', {'class': 'tel'})
            tel = tel.get('href').split('+')[-1].replace('tel:', '')

            # name
            name_tag = message.find('span', 'fn') or message.find('abbr', 'fn')
            name_tag = name_tag.get('title') or name_tag.string

            text = ' '.join(HTMLParser().unescape(i)
                            for i in message.q.contents
                            if isinstance(i, basestring))

            person = Contact.get_or_create(name=name)
            sms = SMS.get_or_create(text=text, time=time, contact=person)
            if name_tag != me.name:
                phone = Phone.get_or_create(phone=tel, contact=person)
            else:
                sms.from_me = True
            sms.phone = Phone.get(phone=tel)

            person.save()
            sms.save()
            phone.save()

    database.commit()
Exemplo n.º 13
0
def gv_to_db(me):
    files = os.listdir(settings.CONVERSATIONS_DIR)
    os.chdir(settings.CONVERSATIONS_DIR)
    files = [f for f in files if f.endswith('html')]

    database.set_autocommit(False)

    print len(files)
    count = 1
    for f in files:
        print str(count) + '. ' + f
        count += 1

        # set name
        name = parse.parse('{} - {}', f).fixed[0]

        soup = BeautifulSoup(open(f))
        chat = soup.find('div', {'class': 'hChatLog hfeed'})
        if not chat:
            continue

        messages = chat.findAll('div', {'class': 'message'})
        for message in messages:
            # time
            t = message.find('abbr', {'class': 'dt'})
            if t.get('title'):
                time = parse.parse('{:ti}', t.get('title')).fixed[0]

            # telephone number
            tel = message.find('a', {'class': 'tel'})
            tel = tel.get('href').split('+')[-1].replace('tel:', '')

            # name
            name_tag = message.find('span', 'fn') or message.find('abbr', 'fn')
            name_tag = name_tag.get('title') or name_tag.string

            text = ' '.join(HTMLParser().unescape(i) for i in message.q.contents if isinstance(i, basestring))

            person = Contact.get_or_create(name=name)
            sms = SMS.get_or_create(text=text, time=time, contact=person)
            if name_tag != me.name:
                phone = Phone.get_or_create(phone=tel, contact=person)
            else:
                sms.from_me = True
            sms.phone = Phone.get(phone=tel)

            person.save()
            sms.save()
            phone.save()

    database.commit()
Exemplo n.º 14
0
def recv_sms():
    new = False
    for message in device.get_message_list():
        number = message.number
        date = message.date
        text = message.text
        if not SMS.objects.filter(date=date, number=number, text=text).exists():
            sms = SMS()
            sms.number = number
            sms.text = text
            sms.date = date
            sms.state = SMS.STATE_NEW
            sms.received = False
            sms.save()
            add_processor_jobs(sms)
            new = True
            device.del_message(message)
    return new
Exemplo n.º 15
0
def create(request):
    try:
        json_obj = commonHttp.get_json(request.body)

        req_attrs = [
            expectedAttr["TO"], expectedAttr["TITLE"], expectedAttr["MESSAGE"]
        ]

        commonHttp.check_keys(json_obj, req_attrs)

        new_sms = SMS(to=json_obj[expectedAttr["TO"]],
                      title=json_obj[expectedAttr["TITLE"]],
                      message=json_obj[expectedAttr["MESSAGE"]])

        commonHttp.save_model_obj(new_sms)

        url = "http://smsgateway.me/api/v3/messages/send"
        data = {
            'email':
            '*****@*****.**',
            'password':
            env.SMS_ACC_PASSWORD,
            'device':
            '32326',
            'number':
            json_obj[expectedAttr["TO"]],
            'message':
            json_obj[expectedAttr["TITLE"]] + "," +
            json_obj[expectedAttr["MESSAGE"]]
        }

        r = requests.post(url, data)
        print "test"
        print r.json()['success']

        if r.json()['success'] == True:
            status = True
        else:
            status = False

        response = JsonResponse({"id": new_sms.id, "success": status})

        return response

    except commonHttp.HttpBadRequestException as e:
        return HttpResponseBadRequest(e.reason_phrase)
Exemplo n.º 16
0
def people_with_many_texts(n, TRAIN=0.9):
    # TRAIN = percent of data to have in training set
    contacts = peewee.RawQuery(
        Contact, '''SELECT * from sms, contact
    where from_me=0 and contact.id=contact_id GROUP BY contact_id
    HAVING count(*) >= ?;''', n)

    data = {}
    for c in contacts:
        data[c.name] = set(SMS.select().where(contact=c))

    train = {}
    test = {}

    for c in data:
        train[c], test[c] = split_set(data[c], TRAIN)

    print 'There are %d people with >= %d texts.' % (len(data), n)

    return train, test
Exemplo n.º 17
0
def index(password):
    print >> sys.stderr, "within index"
    try:
        if password == PASSWORD:
            print >> sys.stderr, "within try"
            sellerList = Seller.select()
            smsList = SMS.select()
            numberList = Number.select()
            l = List.select()
            marketList = Market.select()
            lrList = ListRelationship.select()
            outboxList = Outbox.select()
            return render_template("index.html", title = 'TABLES', sellerList = sellerList, smsList = smsList, l = l, marketList = marketList)
            #return 'hello world'
        else:
            print >> sys.stderr, "wrong password"
    except:
        print >> sys.stderr, "within except"
        print >> sys.stderr, str(sys.exc_info()[0]) # These write the nature of the error
        print >> sys.stderr, str(sys.exc_info()[1])
        statement = 'An exception has Occured'+ str(sys.exc_type) + '[' + str(sys.exc_value) + ']'
        return statement
Exemplo n.º 18
0
def people_with_many_texts(n, TRAIN=0.9):
    # TRAIN = percent of data to have in training set
    contacts = peewee.RawQuery(
        Contact,
        """SELECT * from sms, contact
    where from_me=0 and contact.id=contact_id GROUP BY contact_id
    HAVING count(*) >= ?;""",
        n,
    )

    data = {}
    for c in contacts:
        data[c.name] = set(SMS.select().where(contact=c))

    train = {}
    test = {}

    for c in data:
        train[c], test[c] = split_set(data[c], TRAIN)

    print "There are %d people with >= %d texts." % (len(data), n)

    return train, test
Exemplo n.º 19
0
            person = Contact.get_or_create(name=name)
            sms = SMS.get_or_create(text=text, time=time, contact=person)
            if name_tag != me.name:
                phone = Phone.get_or_create(phone=tel, contact=person)
            else:
                sms.from_me = True
            sms.phone = Phone.get(phone=tel)

            person.save()
            sms.save()
            phone.save()

    database.commit()

if __name__ == '__main__':
    database.connect()

    if not database.get_tables():
        Contact.create_table()
        SMS.create_table()
        Phone.create_table()

    me = Contact.get_or_create(name=settings.OWNER_NAME)
    me.save()
    for phone in settings.OWNER_PHONES:
        p = Phone.get_or_create(phone=phone, contact=me)
        p.save()

    gv_to_db(me)
    database.close()
Exemplo n.º 20
0
def sms(request):
    """
    Handles both the GET and the POST
    
    first thing is checks to make sure that the incoming message
    has the right secret device key
    
    POST:
    use the post data to create a SMS, and add it to the database
    will return empty 200 if success, or 500/400 with an {'error': <error message>} json body
    
    GET:
    gets up to max_sms sms, and returns them in a json list
    as well as a sms_count
    """

    attrs = ('to_number', 'from_number', 'body')

    if request.method == "POST":
        """
        Handles an incoming SMS
        """
        device = authorize(request.POST.get('key'))
        if device is None:
            return HttpResponseForbidden(str(device))

        sms_dict = {}
        for attr in attrs:
            post_val = request.POST.get(attr)
            if post_val is None:
                return HttpResponseBadRequest("POST must have attribute %s" %
                                              attr)
            sms_dict[attr] = post_val
        new_sms = SMS(**sms_dict)

        sms_handlers = []
        sms_handler_tuple = getattr(settings, 'SMS_HANDLERS', [])
        for sms_handler_string in sms_handler_tuple:
            sms_handlers.append(get_callable(sms_handler_string))

        # call the handlers? is this the best way?
        for sms_handler in sms_handlers:
            retval = sms_handler(new_sms)
            if retval is False:
                break

        return HttpResponse()

    elif request.method == "GET":
        """
        Remove this section if you will not be using
        The database as a queue for SMS sending-consumers
        """
        device = authorize(request.GET.get('key'))
        if device is None:
            return HttpResponseForbidden(str(device))

        try:
            return dj_simple_sms.SMS_SENDER.respond_to_get(request)
        except NotImplementedError:
            return HttpResponseNotAllowed('GET')
Exemplo n.º 21
0
def sms(request):
    """
    Handles both the get and the post
    
    first thing is checks to make sure that the incoming message
    has the right secret device key
    
    POST:
    use the post data to create a SMS, and add it to the database
    will return empty 200 if success, or 500/400 with an {'error': <error message>} json body
    
    GET:
    gets up to max_sms sms, and returns them in a json list
    as well as a sms_count
    """

    attrs = ('to_number', 'from_number', 'body')

    if request.method == "POST":

        device = authorize(request.POST.get('key'))
        if device is None:
            return HttpResponseForbidden()

        sms_dict = {}
        for attr in attrs:

            post_val = request.POST.get(attr)
            if post_val is None:
                return HttpResponseBadRequest("POST must have attribute %s" %
                                              attr)

            sms_dict[attr] = post_val

        new_sms = SMS(**sms_dict)

        sms_handlers = []
        sms_handler_tuple = getattr(settings, 'SMS_HANDLERS', [])
        for sms_handler_string in sms_handler_tuple:
            sms_handlers.append(get_callable(sms_handler_string))

        # call the handlers? is this the best way?
        for sms_handler in sms_handlers:
            retval = sms_handler(new_sms)
            if retval is False:
                break

        return HttpResponse()

    elif request.method == "GET":
        """
        Remove this section if you will not be using
        The database as a queue for SMS sending-consumers
        """

        device = authorize(request.GET.get('key'))
        if device is None:
            return HttpResponseForbidden()

        max_sms = request.GET.get('max_sms',
                                  getattr(settings, 'SMS_MAX_SMS_GET', 10))

        # ok, get that many!
        if max_sms is None:
            sms_set = SMS.objects.all().order_by('datetime')
        else:
            sms_set = SMS.objects.all().order_by('datetime')[:max_sms]

        sms_list = list(sms_set.values(*attrs))

        count = len(sms_list)

        data_out = {'sms_count': count, 'sms': sms_list}

        for sms in sms_set:
            sms.delete()

        return HttpResponse(json.dumps(data_out))
Exemplo n.º 22
0
            sms = SMS.get_or_create(text=text, time=time, contact=person)
            if name_tag != me.name:
                phone = Phone.get_or_create(phone=tel, contact=person)
            else:
                sms.from_me = True
            sms.phone = Phone.get(phone=tel)

            person.save()
            sms.save()
            phone.save()

    database.commit()


if __name__ == '__main__':
    database.connect()

    if not database.get_tables():
        Contact.create_table()
        SMS.create_table()
        Phone.create_table()

    me = Contact.get_or_create(name=settings.OWNER_NAME)
    me.save()
    for phone in settings.OWNER_PHONES:
        p = Phone.get_or_create(phone=phone, contact=me)
        p.save()

    gv_to_db(me)
    database.close()