예제 #1
0
def update_phone(data=None, cls=True):
    render_template(context={}, template="add_phone.jinja2", cls=cls)
    phone = input()
    render_template(context={}, template="add_new_phone.jinja2", cls=cls)
    new_phone = input()
    Phone.update(phone, new_phone)
    return 51, None
예제 #2
0
def update_user_controller(data=None, cls=True):
    users = User.all()
    choice = input('Enter n, if u want to change the name, enter p, if u want \
to change the phone number: ')
    if choice == 'n':
        render_template(context={'users': users},
                        template="update_name.jinja2",
                        cls=cls)
        old_name = input()
        new_name = input("Ur new name: ")
        user = User.update(old_name, new_name)
        return '51', user
    if choice == 'p':
        render_template(context={'users': users},
                        template="user_delete.jinja2",
                        cls=cls)
        username_upd = input("Enter user's name, that phone's u want to  \
update: ")
        phones = Phone.all()
        for i in range(len(users)):
            if users[i].name == username_upd:
                numberline = ''
                for y in users[i].phones:
                    numberline += y.phone + ' '
                print(f'All numbers belonging to this user: \
{users[i].name}: {numberline}')
        old_phone = input("Enter the number, that u want to change: ")
        new_phone = input("Enter ur new number: ")
        phone = Phone.update(old_phone, new_phone)
        return '51', phone
예제 #3
0
def update_user_controller(data=None, cls=True):
    users = User.all()
    request = input(
        'Введите 1, если хотите изменить имя; любую другую клавишу - если хотите изменить номер: '
    )
    if request == '1':
        render_template(context={'users': users},
                        template="update_name1.jinja2",
                        cls=cls)
        old_name = input()
        new_name = input("Новое имя: ")
        user = User.update(old_name, new_name)
        return '1', user
    else:
        render_template(context={'users': users},
                        template="update_name2.jinja2",
                        cls=cls)
        username = input(
            "Введите имя пользователя, чей номер Вы бы хотели изменить: ")
        phones = Phone.all()
        for i in range(len(users)):
            if users[i].name == username:
                numbers_line = ''
                for k in users[i].phones:
                    numbers_line = numbers_line + k.phone + ' '
                print(
                    f'Номера, принадлежащие пользователю {users[i].name}: {numbers_line}'
                )
        old_phone = input("Введите номер, который хотите изменить: ")
        new_phone = input("Новый номер: ")
        phone = Phone.update(old_phone, new_phone)
        return '1', phone
예제 #4
0
    def post(self):
        digit = self.request.get('Digits')

        # Datastoreのを再生
        if digit == '1':
            phone = Phone.get_by_id('twilio')
            r = twiml.Response()
            r.say(unicode(phone.talk), language='ja-jp')
            self.response.headers['Content-Type'] = 'text/xml'
            self.response.write(str(r))

        # 録音して即再生
        # See: http://www.twilio.com/docs/api/rest/recording
        elif digit == '2':
            r = twiml.Response()
            r.say(u'10秒で いれてね', language='ja-jp')
            r.record(maxLength=10, finishOnKey='#', action='/play', method='POST')

            self.response.headers['Content-Type'] = 'text/xml'
            self.response.write(str(r))

        else:
            phone = Phone.get_by_id('twilio')
            r = twiml.Response()
            r.say(u'それはだめです', language='ja-jp')
            self.response.headers['Content-Type'] = 'text/xml'
            self.response.write(str(r))
예제 #5
0
파일: phone.py 프로젝트: kingst/loop-viewer
def lookup_or_create(number):
    number = number.strip()
    phone = Phone.get_by_id(number)
    if phone is None:
        phone = Phone(id=number)
        phone.put()

    return phone
예제 #6
0
def get_info(request, imeo):
    #if request.method == 'POST':
    try:
        obj = Phone.objects.get(imeo=imeo)
    except Phone.DoesNotExist:
        obj = Phone(imeo=imeo)
        obj.save()
    data = obj.as_json()
    data = json.dumps(data)
    return HttpResponse(data, content_type='application/json')
예제 #7
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()
예제 #8
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()
예제 #9
0
파일: views.py 프로젝트: MMokhtari/fury007
def subscribe(request):
    if request.method == "POST":
       username=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
       password=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
       user = User(username=username,password=password)
       user.set_password(password)
       user.save()
       profile=Profile(user=user)
       profile.save()
       phone=Phone(number_phone=request.POST.get("number_phone"),country_code=request.POST.get("country_code"),owner=profile)
       phone.save()
       user_login= authenticate(username=username, password=password)
       login(request, user_login) 
    return redirect(user_space,user.username)
예제 #10
0
    def post(self):
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'No input data provided'}, 400
        # Validate and deserialize input
        data, errors = phone_schema.load(json_data)
        if errors:
            return errors, 422
        # Check if the keys entered are the ones expected
        try:
            phone = Phone(phone_number=data['phone_number'], name=data['name'])
        except KeyError:
            return {
                'message':
                "The key/s you entered is/are invalid. Please check and try again"
            }, 400
        repeated_phone = db.session.query(Phone).filter(
            Phone.phone_number == data['phone_number']).first()
        # Check if the phone is already on the database
        if repeated_phone:
            return {
                'message':
                'Phone already exists. Check the number and try again'
            }, 400
        db.session.add(phone)
        db.session.commit()

        result = phone_schema.dump(phone).data

        return result, 200
예제 #11
0
def phone_saver(name: str, phones: str) -> bool:
    """Gets `name` and `phones` and saves them as related objects in DB 

    Args:
        name (str): Contact name
        phones (str): Contact's phones, separated by `\\n` 

    Returns:
        bool: Operation success status
    """
    if name and phones:
        user = User.add(name)
        for phone in phones.split("\n"):
            Phone.add(phone, user)
        return True
    return False
예제 #12
0
def newphone():
    if request.method == 'POST':
        json_obj = request.get_json(force=True)
        phone = Phone(key_name=json_obj['id'],phone_id = json_obj['id'],android_version = json_obj['android_version'])
        phone.put()
        """
        for thisPhone in allphones:
            if phone.phone_id == thisPhone.phone_id:
                exists = True
        if not exists:
            if not phone.is_saved():
                phone.put()
        """
        return 'db id is '
    if request.method == 'GET':
        dbphones = Phone.all()
        return render_template('phones.html',phones=dbphones)
예제 #13
0
    def get(self):
        if not self.is_logged_in():
            self.redirect(LOGIN_PAGE_URL)
        else:
            from pytz.gae import pytz
        
            customer = Customer.get_by_key_name(self.get_current_username())

            landline = Phone.all().filter('profile = ', customer).filter('phone_type = ', 'landline').get()
            mobile = Phone.all().filter('profile = ', customer).filter('phone_type = ', 'mobile').get()

            self.render('profile.html', countries=COUNTRIES_TUPLE,
                landline=landline,
                mobile=mobile,
                customer=customer,
                location=customer.locations[0],
                default_timezone=customer.timezone,
                timezones=pytz.all_timezones)
예제 #14
0
    def post(self):
        keys = _get_api_key()
        phone = Phone.get_by_id('twilio')

        client = TwilioRestClient(keys['account_sid'], keys['auth_token'])
        client.sms.messages.create(
            body=phone.talk,
            to=keys['validated_phone_number'],
            from_=keys['twilio_phone_number'],
            )

        self.response.out.write(template.render('html/sms.html', {}))
예제 #15
0
    def setUp(self):
        from app import app
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
        app.config["TESTING"] = True
        self.app = app.test_client()

        with app.app_context():
            db.init_app(app)
            db.drop_all()
            db.create_all()

            phone = Phone(11111111, "test")
            db.session.add(phone)
            db.session.commit()
예제 #16
0
def send_order(request, imeo):
    data = {}
    if request.method == 'POST':
        try:
            obj = Phone.objects.get(imeo=imeo)
        except Phone.DoesNotExist:
            obj = Phone(imeo=imeo)
            obj.save()

        obj.phone_number = request.POST.get('telefon')
        obj.count_order = obj.count_order + 1
        obj.save()

        phone_number = request.POST.get('telefon')
        address_from = request.POST.get('from')
        address_to = request.POST.get('to')



        if request.POST.get('time')=="Ближайшее время":
            time = "15:00:00"
        else:
            time = "14:00:00"

        #hist = OrderHistory.objects.filter(imeo=obj).values()[10]
        hist = "Тратата"
        history = OrderHistory(imeo=obj,
                               address_from=request.POST.get('from'),
                               address_to=request.POST.get('to'),
                               order_time=time,
                               phone_number=request.POST.get('telefon'))
        history.save()


        subject, from_email, to = 'Заказ ', '*****@*****.**', '*****@*****.**'  #[email protected]
        text_content = 'Телефон: э'
        my_context = {"phone_number": phone_number,
                      "address_from": address_from,
                      "address_to": address_to,
                      "time": time,
                      "sale": obj.sale,
                      "hist_count:": obj.count_order,
                      "history": hist}
        html_content = get_template('mail.html').render(Context(my_context)) # /usr/local/lib/python2.7/dist-packages/flat/templates
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()

        #send_mail('Новый заказ: ', tel, '*****@*****.**', ['*****@*****.**'])


    return HttpResponse(data, content_type='application/json')
예제 #17
0
def index():
    if request.method == 'POST':
        phone_number = request.form['number']
        phone = Phone.query.filter_by(number=phone_number).first()
        if phone is None:
            phone = Phone.insert_phone(phone_number)
            verification = Verification.generate_ver_code(phone)
            send_verification_code(phone, verification)
            return redirect(url_for('verify', phone_number=phone_number), code=302)
        else:
            if not phone.active:
                if phone.unsub:
                    verification = Verification.generate_ver_code(phone)
                    send_verification_code(phone, verification)

                return redirect(url_for('verify', phone_number=phone_number), code=302)
            else:
                flash('Phone number already registered', 'danger')

    return render_template('index.html')
예제 #18
0
def sendmessage2():
    dataToSend = dict()
    data = dict()
    phones = Phone.all()

    data['title'] = request.form['title'] or 'default title'
    data['post'] = request.form['post'] or 'defaul post'

    regIds = [phone.phone_id for phone in phones]
    dataToSend['registration_ids'] = regIds
    dataToSend['data'] = data

    headers = MultiDict()
    headers['Content-Type'] = 'application/json'
    headers['Authorization'] = "key=AIzaSyBsBuZuPlRkt45QstSJ_qaHC7_e1NFEIZU"
    req = urllib2.Request("https://android.googleapis.com/gcm/send", json.dumps(dataToSend), headers)
    f = urllib2.urlopen(req)
    responseMsg = f.read()
    f.close()

    if request.method == 'POST':
        return render_template('sendmessage.html',sent=True)
    if request.method == 'GET':
        return responseMsg
예제 #19
0
        "last_name": "Doe",
        "number": "87867675655"
    },
    {
        "first_name": "Minnie",
        "last_name": "Marshall",
        "number": "97654333567"
    },
    {
        "first_name": "John",
        "last_name": "Link",
        "number": "76353344333"
    },
]

# Delete database file if it exists currently
if os.path.exists("phones.db"):
    os.remove("phones.db")

# Create the database
db.create_all()

# iterate over the PEOPLE structure and populate the database
for phone in PHONES:
    p = Phone(first_name=phone.get("first_name"),
              last_name=phone.get("last_name"),
              number=phone.get("number"))
    db.session.add(p)

db.session.commit()
예제 #20
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()
예제 #21
0
    def deserialize(self, import_buffer, target_class, tenant):
        result = ImportResult()
        EMAIL_TYPES = tuple(t[0] for t in Email.TYPES)
        PHONE_TYPES = tuple(t[0] for t in Phone.TYPES)
        PHONE_SUBTYPES = tuple(t[0] for t in Phone.SUBTYPES)
        ADDRESS_TYPES = tuple(t[0] for t in Address.TYPES)
        for vcard in vobject.readComponents(import_buffer):
            if issubclass(vcard.behavior, vobject.vcard.VCard3_0):
                contact = target_class(tenant=tenant)
                try:
                    if isinstance(contact, Contact):
                        assert vcard.getChildValue('n').family
                        assert vcard.getChildValue('n').given
                        contact.name = vcard.getChildValue('n').family
                        contact.firstname = vcard.getChildValue('n').given
                        contact.additional_names = vcard.getChildValue(
                            'n').additional or None
                        # Handle organizations ?
                        if vcard.getChildValue('bday'):
                            contact.birthday = parse(vcard.bday.value)
                    if isinstance(contact, Organization):
                        assert vcard.getChildValue('org')
                        contact.corporate_name = vcard.getChildValue('org')

                    emails = vcard.contents.get(toVName('email')) or []
                    for email in emails:
                        email_type = None
                        try:
                            email_type = email.type_param
                        except:
                            pass
                        contact.emails.append(
                            Email(type=email_type
                                  if email_type in EMAIL_TYPES else None,
                                  email=email.value))

                    phones = vcard.contents.get(toVName('tel')) or []
                    for phone in phones:
                        phone_types = []
                        phone_type = None
                        phone_subtype = None
                        try:
                            phone_types = phone.type_paramlist
                            for ptype in phone_types:
                                if ptype in PHONE_TYPES and not phone_type:
                                    phone_type = ptype
                                elif ptype in PHONE_SUBTYPES and not phone_subtype:
                                    phone_subtype = ptype
                        except:
                            pass
                        contact.phones.append(
                            Phone(type=phone_type,
                                  subtype=phone_subtype,
                                  phone=phone.value))

                    addresses = vcard.contents.get(toVName('adr')) or []
                    for address in addresses:
                        address_type = None
                        try:
                            address_type = address.type_param
                        except:
                            pass
                        contact.addresses.append(
                            Address(type=address_type
                                    if address_type in ADDRESS_TYPES else None,
                                    postoffice_box=address.value.box,
                                    street_address=address.value.street,
                                    extended_address=address.value.extended,
                                    postal_code=address.value.code,
                                    city=address.value.city,
                                    state=address.value.region,
                                    country=address.value.country))
                    contact.save()
                    result.success.append(contact)
                except:
                    record_name = vcard.getChildValue('fn')
                    if not record_name:
                        name = vcard.getChildValue('n').family
                        firstname = vcard.getChildValue('n').given
                        if name and firstname:
                            record_name = u'%s %s' % (firstname, name)
                        elif name:
                            record_name = name
                        elif firstname:
                            record_name = firstname
                    if not record_name:
                        try:
                            record_name = vcard.getChildValue('org')[0]
                        except:
                            pass
                    if not record_name:
                        record_name = _('No name')
                    result.errors.append(record_name)
        return result
예제 #22
0
def db_fill(session: object, data: list):
    articles = []
    phones = []
    ids_pool = []

    logger.info('{} articles found in general.'.format(len(data) * 32))

    db_meta = meta_get_or_create(session, MetaInfo)
    db_meta.last_start = datetime.datetime.now(tz=pytz.utc)
    db_meta.status = False
    session.commit()

    ins_counter = 0
    for collection in data:
        if not isinstance(collection, list):
            logger.warning('No articles found in collection.')
            continue
        for article in collection:
            link = article['link']
            article_id = md5(link.encode()).hexdigest()

            if article_id not in ids_pool:
                ids_pool.append(article_id)
            else:
                logger.debug(
                    'Article {} with id {} already present in DB.'.format(
                        link, article_id))
                continue

            if not session.query(CarArticle).get(article_id):
                ins_counter += 1

                brutto = True if 'brutto' in article['price_detail'] else False
                netto = True if 'netto' in article['price_detail'] else False
                negotiation = True if 'donegocjacji' in article[
                    'price_detail'] else False
                vat = True if 'fakturavat' in article['price_detail'] else False

                car_obj = CarArticle(
                    article_id, article['name'], article['manufacturer'],
                    article['item_year'], article['item_mileage'],
                    article['item_engine_capacity'], article['item_fuel_type'],
                    str(article['price']), brutto, netto, negotiation, vat,
                    article['currency'], article['seller_location'], link,
                    article['seller_id'])

                articles.append(car_obj)

                for phone in article['phones']:
                    phone_obj = Phone(phone, car_obj)
                    phones.append(phone_obj)

    session.bulk_save_objects(articles)
    session.bulk_save_objects(phones)

    db_meta.status = True

    session.commit()

    logger.info(
        '\nScraper finished successfully. {} new articles found and inserted.'.
        format(ins_counter))
예제 #23
0
파일: phone.py 프로젝트: kingst/loop-viewer
def lookup(number):
    return Phone.get_by_id(number)
예제 #24
0
 def post(self):
     phone = Phone.get_by_id('twilio')
     r = twiml.Response()
     r.say(unicode(phone.talk), language='ja-jp')
     self.response.headers['Content-Type'] = 'text/xml'
     self.response.write(str(r))
예제 #25
0
url = open('/home/apoorv/.elephant/url').read()
engine = create_engine(url)

Session = sessionmaker(bind=engine)
session = Session()

# Base.metadata.create_all(engine)
# print("done with createall")
session.query(Person).delete(synchronize_session=False)  # cascades
print("deleted initial contents.")
p1 = Person(id=1,
            name="Apoorv",
            age=26,
            phones=[
                Phone(ptype='home', number=123),
                Phone(ptype='office', number=234)
            ])

p2 = Person(id=2,
            name="Billy",
            age=26,
            phones=[
                Phone(ptype='home', number=444),
                Phone(ptype='office', number=555)
            ])

p3 = Person(id=3,
            name="John",
            age=26,
            phones=[
예제 #26
0
def add_phone_controller(user, cls=True):
    render_template(context={}, template="add_phone.jinja2", cls=cls)
    phone_number = input()
    phone = Phone.add(phone_number, user)
    return 212, user # (next state, data)
예제 #27
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()
예제 #28
0
def delete_phone(data=None, cls=True):
    render_template(context={}, template="add_phone.jinja2", cls=cls)
    phone = input().strip().title()
    Phone.delete(phone)
    return 51, None
예제 #29
0
    def post(self):
        talk = self.request.get('talk') if self.request.get('talk') else u'GDG信州Aprilへようこそ'
        phone = Phone(id='twilio', talk=talk)
        phone.put()

        self.response.out.write(template.render('html/memorize.html', {}))