Ejemplo n.º 1
0
def create_account(username, password1, password2):
    if not username in get_users():
        if password1 == password2:
            add_user(username, hashlib.sha224(password1).hexdigest())
            return 0
        return 1
    return 2
Ejemplo n.º 2
0
def login(username, password):
    if username in get_users():
        if check_pass(username, password):
            session['user'] = username
            return 0
        return 1
    return 2
Ejemplo n.º 3
0
 def deal(did, session):
     user_name = check_session(app, session)
     assert isinstance(did, int)
     users = db.get_users(cursor)
     deal_states = db.get_deal_states(cursor)
     sites = db.get_sites(cursor)
     print(users, deal_states, sites)
     d = { 'description': '', 'bdcid':db.find_next_bdcid(cursor, sites[0]['id']), \
           'site_name': sites[0]['name'], 'site_pic':sites[0]['pic'], 'site_id':sites[0]['id'], \
           'creator_id':users[0]['id'], 'creator_name':users[0]['fullname'], \
           'validator_id':users[0]['id'], 'validator_name':users[0]['fullname'], \
           'state':deal_states[0] }
     devis = 0
     if (did > 0):
         deals = db.get_deals(cursor, did)
         devis = db.get_devis(cursor, did)
         print(deals, devis)
         d = deals[0]
     return bottle.template('deal',
                            app=app,
                            user_name=user_name,
                            deal=d,
                            devis=devis,
                            users=users,
                            config=config,
                            did=did,
                            deal_states=deal_states,
                            sites=sites)
Ejemplo n.º 4
0
Archivo: main.py Proyecto: Badrpas/spy
def RunSpy():
    user_ids = GetUserIds() # Из файла

    db.init()
    users_online = db.get_users() #getting last user status from DB



    start = time.time()
    try:
        print(datetime.datetime.now().strftime('%H:%M:%S'), 'Getting response. ')
        response = get_users(user_ids, 'online', timeout=3)
    except ResponseError as e:
        print(e)
        return

    end = time.time()
    print(datetime.datetime.now().strftime('%H:%M:%S'), 'Response came in {0:04.2f} sec'.format(end - start) )

    now = datetime.datetime.now()
    now_fmttd = now.strftime('%Y-%m-%d %H:%M:%S')
    for user in response:
        if not user['id'] in users_online or user['online'] != users_online[user['id']]:
            users_online[user['id']] = user['online']
            # add event to database
            db.add_online_status(user['id'], user['online'], now_fmttd)

    now = datetime.datetime.now()
    sleep_value = 10
    print(now.strftime('%H:%M:%S'), 'Now waiting for {0} sec'.format(sleep_value))
    time.sleep(sleep_value)
Ejemplo n.º 5
0
def list_users():
    q = db.get_users()
    _f = '{0:<20} {1:<20} {2:<20}'
    print(_f.format('username', 'password', 'full name'))
    print('----------------------------------------------------')
    for row in q:
        print(_f.format(*row))
Ejemplo n.º 6
0
def export_users():
    service = build('sheets', 'v4', credentials=google_auth.creds)
    sheet = service.spreadsheets()

    date = datetime.datetime.today().isoformat()[:16].replace(":", ".")

    users = list(map(lambda x: [str(i) for i in x], db.get_users()))

    requests = []
    requests.append({"addSheet": {"properties": {"title": date, "index": 0}}})

    sheets = sheet.get(spreadsheetId=config.USERS_SHEET_ID).execute()["sheets"]
    horizon = (datetime.datetime.today() -
               datetime.timedelta(days=30)).isoformat()

    for i in sheets:
        if i["properties"]["title"] < horizon:
            requests.append(
                {"deleteSheet": {
                    "sheetId": i["properties"]["sheetId"]
                }})

    add_body = {"requests": requests}
    body = {"values": users}

    response = service.spreadsheets().batchUpdate(
        spreadsheetId=config.USERS_SHEET_ID, body=add_body).execute()

    result = service.spreadsheets().values().append(
        spreadsheetId=config.USERS_SHEET_ID,
        range=date + "!A1",
        valueInputOption="RAW",
        body=body).execute()

    return len(users)
Ejemplo n.º 7
0
def index():
    #En caso de que el usuario no haya iniciado sesion
    if 'public_key' not in session or session['public_key'] == None:
        return redirect(url_for('login'))
    else:
        #Obtener monedas del user
        coins = get_galactic_coins(session['public_key'])
        if session['username'] == 'Darth Vader':
            #Users para transferir coins
            users = get_users()
            #Armas para la venta
            weapons = get_weapons(session['public_key'])
            return render_template('index.html',
                                   users=users,
                                   coins=coins,
                                   weapons=weapons,
                                   isAdmin=True)
        else:
            darth_vader = get_user_by_name('Darth Vader')
            weapons = get_weapons(darth_vader['public_key'])
            #Renderizar index
            return render_template('index.html',
                                   coins=coins,
                                   weapons=weapons,
                                   isAdmin=False)
Ejemplo n.º 8
0
def addme(message):
    try:
        users = db.get_users(message.chat.id)
        if users is None or len(users) == 0:
            users = ''
        users = users.split()
        users = [int(i) for i in users]
        if message.from_user.username:
            if message.from_user.id not in users:
                users.append(message.from_user.id)
                bot.send_message(message.chat.id,
                                 message.from_user.username + " добавлен",
                                 parse_mode='html',
                                 reply_markup=None)
            else:
                bot.send_message(message.chat.id,
                                 "Вы уже есть в списке 😉",
                                 parse_mode='html',
                                 reply_markup=None)
        else:
            bot.send_message(
                message.chat.id,
                "Добавьте в настройках своего профиля имя пользователя, чтобы быть в списке 🙂",
                parse_mode='html',
                reply_markup=None)
        users = ' '.join([str(elem) for elem in users])
        db.set_users(message.chat.id, users)
    except Exception as e:
        bot.send_message(message.chat.id,
                         "Ошибка.",
                         parse_mode='html',
                         reply_markup=None)
Ejemplo n.º 9
0
def delme(message):
    try:
        users = db.get_users(message.chat.id)
        if users is None or len(users) == 0:
            users = ''
        users = users.split()
        users = [int(i) for i in users]
        if message.from_user.id in users:
            users.remove(message.from_user.id)
            bot.send_message(message.chat.id,
                             message.from_user.username + " удален",
                             parse_mode='html',
                             reply_markup=None)
        else:
            bot.send_message(
                message.chat.id,
                "Вас нет в списке. Чтобы добавить себя в список нажмите \n/addme@tagworldbot",
                parse_mode='html',
                reply_markup=None)
        users = ' '.join([str(elem) for elem in users])
        db.set_users(message.chat.id, users)
    except Exception as e:
        bot.send_message(message.chat.id,
                         "Ошибка.",
                         parse_mode='html',
                         reply_markup=None)
Ejemplo n.º 10
0
def SignUp_user():
    username_value = username.get()
    occur = 0
    for i in db.get_users(
    ):  # i represents element of info which is list itself
        if username_value == i[
                0]:  #to access the username of the "i" list and compare with the username entered by user
            occur = 1  # if username already exists in database
    if occur == 1:
        messagebox.showerror('Username', "User already exists")
        SignUp_screen.destroy()
    else:
        if (len(username_value) >= 4 and len(username_value) <= 10):
            password_value = password.get(
            )  #input password if username doesn't already exists
            length = len(password_value)  # taking the length of password
            if length >= 5 and length <= 10:  #To check all the conditions on the password are satisfied
                t = (username_value, password_value
                     )  #create a tuple "t" containing name and password
                db.add_user(t)  # add to database
                messagebox.showinfo('SignUp', "Registration successful!")
                SignUp_screen.destroy()
            else:
                if (length < 5 or length > 10):
                    messagebox.showerror(
                        'Password',
                        "Your password should have 5-10 characters")
        else:
            if (len(username_value) < 4 or len(username_value) > 10):
                messagebox.showerror('Username',
                                     "Username should be 5-10 characters")
Ejemplo n.º 11
0
def hello_world():
    logging.info('getting users')
    users = get_users()
    print(users)
    encrypted_users = encrypt_users(users)
    print(encrypted_users)
    return str(encrypted_users)
Ejemplo n.º 12
0
def on_alert():
    users = get_users()

    for user in users:
        user = User('', user, '', '')
        client.send_message(user, 'MapleStory is back online!')

    clear_users()
Ejemplo n.º 13
0
def on_alert():
    users = get_users()

    for user in users:
        user = User('', user, '', '')
        client.send_message(user, 'MapleStory is back online!')

    clear_users()
Ejemplo n.º 14
0
    def POST(self, nick=''):
        data = web.input()
        users = db.get_users()
        nick = data.nick.lower()
        if nick:
            auth.login_direct(session, users, '/forum#top', nick, data.password)

        raise web.seeother('/login' + ['', '/'][bool(nick)] + nick)
Ejemplo n.º 15
0
def index(request):
    users = get_users(session, request.session['username'])[1]
    posts = get_posts(session, request.session['username'])[1]
    return render_template('index.html',
                           username=request.session['username'],
                           name=request.session['name'],
                           users=users,
                           posts=posts)
Ejemplo n.º 16
0
def import_users():
    service = build('sheets',
                    'v4',
                    credentials=google_auth.creds,
                    cache_discovery=False)
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=config.USERS_SHEET_ID,
                                range="A1:D",
                                majorDimension="ROWS").execute()
    values = result.get('values', [])
    values = list(map(lambda x: [x[0], x[1], x[2], int(x[3])], values))
    users = len(db.get_users())
    print("Importing user data: ", values)
    export_users()  #safety export to not lose data
    db.delete_users()
    for i in values:
        db.add_user(i[0], i[1], i[2], i[3])
    return len(db.get_users()) - users
Ejemplo n.º 17
0
 def test_create_user(self):
     """Test create user."""
     keypair = paket_stellar.get_keypair()
     call_sign = 'test_user'
     self.internal_test_create_user(keypair, call_sign)
     users = db.get_users()
     self.assertEqual(
         len(users), 1,
         "number of existing users: {} should be 1".format(len(users)))
Ejemplo n.º 18
0
def api_users():
    login = request.form.get('login', None)
    name = request.form.get('name', None)
    surname = request.form.get('surname', None)
    third_name = request.form.get('third_name', None)
    password = request.form.get('password', None)
    confirm_password = request.form.get('confirm_password', None)
    profile = request.form.get('profile', None)
    return jsonify({"users": db.get_users(login, name, surname, third_name, password, confirm_password, profile)})
Ejemplo n.º 19
0
def import_users():
    service = build('sheets', 'v4', credentials=creds)

    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=settings.secrets["sheets"]["kayttajat"], range="A1:D", majorDimension = "ROWS").execute()
    values = result.get('values', [])
    values = list(map(lambda x: [x[0], x[1], x[2], int(x[3])], values))

    users = len(db.get_users())
    print(values)

    export_users() #safety export to not lose data

    db.delete_users()
    for i in values:
        db.add_user(i[0], i[1], i[2], i[3])

    return len(db.get_users()) - users
Ejemplo n.º 20
0
 def gsm_test(self):
     location_resource = resources.get('gsmlocation')
     cell_filter = lambda c: dict([ (key,int(c[key])) for key in ['mcc','mnc','lac','cid'] ])
     location_getter = lambda c: self.local.action.datastore_search(resource_id=location_resource,filters=cell_filter(c))['records']
     
     for uid in get_users():
         sql_query = select(['mcc','mnc','lac','cid'],'gsmcell',eq={'uid':uid},ne={'cid':'None'})
         cells = self.local.action.datastore_search_sql(sql=sql_query)['records']
         hits = len(filter(lambda c: len(c) > 0, [ location_getter(cell) for cell in cells ]))
         print "User " + str(uid) + " has " + str(len(cells)) + " cells, of which " + str(hits) + " have locations."
Ejemplo n.º 21
0
def login(username, password):
    u = get_users().filter_by(username=username).first()

    if u is None:
        return False

    if not check_password_hash(u.password, password):
        return False

    return jwt.encode({'uid': u.id, 'uname': username}, SECRET_KEY)
Ejemplo n.º 22
0
def users():
    if request.method == "POST":
        assigned = request.form.getlist("assigned")
        enabled = request.form.getlist("enabled")
        update_users_roles(assigned, enabled)
        flash({
            "status": "alert-success",
            "text": "Security changes have been successfully applied."
        })
    users = get_users()
    return render_template("admin/users.html", users=users)
Ejemplo n.º 23
0
def user():

    if request.method=='POST':
        action=request.form['action']
        if action=='DELETE':
            delete_user_form= DeleteUserForm()
            if delete_user_form.validate():
                username=request.form['username']
                if username=='admin' or username=='guest':
                    flash("admin and guest accounts can't be deleted",'error')
                else:
                    ok=db.delete_user(get_db(),username)
                    if ok: flash('Deleted %s'%username,'ok')
                    else:  flash('Failed to delete %s'%username,'error')
            else:
                flash('delete form failed to validate','error')

        elif action=='CREATE':
            add_user_form = AddUserForm() # create from current form values

            if add_user_form.validate():
                password=add_user_form.password.data
                password_hash=encrypt(password)
                ok=db.create_user(get_db(),add_user_form.name.data,add_user_form.email.data,password_hash)
                if ok:
                    flash('New user %s created'%add_user_form.name.data,'ok')
                else:
                    flash('Sorry, could not create user %s'%add_user_form.name.data,'error') # validation OK, but DB failed
            else: # posted a invalid form
                flash('Please fill in all fields','warning')

        elif action=="ADMIN":
            admin_form=UserAdminForm()
            db.set_user_admin(get_db(),admin_form.username.data,admin_form.admin.data)


        # By default reget the page, can't return a new render here as the existing form would pollute the creation values of the new forms
        return redirect('/users')

    else: # GET
        add_user_form = AddUserForm()
        userlist=db.get_users(get_db())

        # Since get_users doesnt return a list of result, we have to convert the structure in order to insert the delete
        # user form into the list
        userlist2=[]
        for user in userlist:
            name=user['name']
            isadmin=user['admin']
            newrow=list(user)+[DeleteUserForm(username=name),UserAdminForm(username=name,admin=isadmin)]
            userlist2.append(newrow)

        return render_template('user.html', add_user_form=add_user_form, userlist=userlist2)
Ejemplo n.º 24
0
def home_list():
	"""The list all menu"""
	ui.lst1()
	ui.lst2()
	x = db.get_users()
	for i in x:
		z = len(i[1])
		f = 16-z
		l = " "*f
		print i[1], l, i[4]
	raw_input("Press [enter] to goto homescreen")
	home()
Ejemplo n.º 25
0
def index():
    users = db.get_users()
    vote_list = []
    for user in users:
        votes = {}
        votes['user'] = user
        votes['votes'] = db.get_votes(user)
        vote_list.append(votes)
    sorted_list = sorted(vote_list, key=lambda k: k['votes'])
    sorted_list.reverse()

    return render_template('index.html', votes=sorted_list)
Ejemplo n.º 26
0
def index():
    users = db.get_users()
    vote_list = []
    for user in users:
        votes = {}
        votes['user'] = user
        votes['votes'] = db.get_votes(user)
        vote_list.append(votes)
    sorted_list = sorted(vote_list, key=lambda k: k['votes'])
    sorted_list.reverse()

    return render_template('index.html', votes=sorted_list)
Ejemplo n.º 27
0
def home_list():
    """The list all menu"""
    ui.lst1()
    ui.lst2()
    x = db.get_users()
    for i in x:
        z = len(i[1])
        f = 16 - z
        l = " " * f
        print i[1], l, i[4], l, i[5]
    raw_input("Press [enter] to goto homescreen")
    home()
Ejemplo n.º 28
0
  def GET(self):
    tasks = db.get_tasks()
    users = db.get_users()

    task_cmp = lambda task_name: tasks[task_name]['complexity']
    sorted_tasks = sorted(tasks.keys(), key=task_cmp, reverse=False)
    print sorted_tasks
    user_cmp = lambda user_name: sum([1 for task_name in tasks.keys() if users[user_name][task_name]])
    sorted_users = sorted(users.keys(), key=user_cmp, reverse=True)
    print sorted_users

    return render.index(tasks, sorted_tasks, users, sorted_users)
Ejemplo n.º 29
0
    def GET(self):
        tasks = db.get_tasks()
        users = db.get_users()

        task_cmp = lambda task_name: tasks[task_name]['complexity']
        sorted_tasks = sorted(tasks.keys(), key=task_cmp, reverse=False)
        print sorted_tasks
        user_cmp = lambda user_name: sum(
            [1 for task_name in tasks.keys() if users[user_name][task_name]])
        sorted_users = sorted(users.keys(), key=user_cmp, reverse=True)
        print sorted_users

        return render.index(tasks, sorted_tasks, users, sorted_users)
Ejemplo n.º 30
0
def handle_users(message):
    _logger.info("/users")
    HSHBOT_ADMIN_ID = int(os.environ['HSHBOT_ADMIN_ID'])
    if message.from_user.id == HSHBOT_ADMIN_ID:
        users = db.get_users()
        users_str = ''
        for user_data in users:
            users_str += '%i - ' % (user_data['id'])
            if user_data['username']:
                users_str += '(%s) ' % (user_data['username'])
            users_str += '%s %s emails=%i\n' % (
                user_data['name'], user_data['last_name'], len(user_data['emails']))
        bot.reply_to(message, users_str)
Ejemplo n.º 31
0
 def do_login(session):
     username = bottle.request.forms.get('username')
     password = bottle.request.forms.get('password')
     users = db.get_users(cursor, 0, username)
     sha = hashlib.new('sha1')
     sha.update(password)
     if (users[0]['password'] == sha.hexdigest()):
         session.regenerate()
         session['valid'] = True
         session['name'] = username
         bottle.redirect("/")
     else:
         bottle.redirect("/login")
Ejemplo n.º 32
0
def home_list():
	print "====================="
	print "--->LIST ALL MENU<---"
	print "====================="
	print "NAME        CHECK-INS"
	x = db.get_users()
	for i in x:
		z = len(i[2])
		f = 14-z
		l = " "*f
		print i[2], l, i[4]
	raw_input("Press [enter] to goto homescreen")
	home()
Ejemplo n.º 33
0
 def do_login(session):
     username = bottle.request.forms.get('username')
     password = bottle.request.forms.get('password')
     users = db.get_users(cursor, 0, username)
     sha = hashlib.new('sha1')
     sha.update(password)
     if (users[0]['password'] == sha.hexdigest()):
         session.regenerate()
         session['valid'] = True
         session['name'] = username
         bottle.redirect("/")
     else:
         bottle.redirect("/login")
Ejemplo n.º 34
0
def main(dotfile):
    f = open(dotfile, 'w')

    f.write('digraph G {\ngraph [layout=dot rankdir=LR]\n')

    for user in db.get_users():
        f.write('uid_%s[label = "%s"]\n'%(user['uid'], user['nickname']))
        f.flush()

    for relation in db.get_relations():
        f.write('uid_%s -> uid_%s\n'%(relation['fan'], relation['me']))
        f.flush()
    f.write('}\n')
    f.close()
Ejemplo n.º 35
0
def main(dotfile):
    f = open(dotfile, 'w')

    f.write('digraph G {\ngraph [layout=dot rankdir=LR]\n')

    for user in db.get_users():
        f.write('uid_%s[label = "%s"]\n' % (user['uid'], user['nickname']))
        f.flush()

    for relation in db.get_relations():
        f.write('uid_%s -> uid_%s\n' % (relation['fan'], relation['me']))
        f.flush()
    f.write('}\n')
    f.close()
Ejemplo n.º 36
0
def start_ss(context):
    updater = context.job.context

    pairing = _generate_pairs(get_users())
    for giver, taker in pairing:
        try:
            update_pair(giver, taker)
            context.bot.send_message(
                chat_id=giver.chat_id,
                text=messages.ss_started.format(taker.username) +
                messages.ss_help)
        except telegram.error.BadRequest as error:
            logging.warning(f'{giver} got no message, error: {error}')

    _add_handlers(updater)
Ejemplo n.º 37
0
def checkPrices(schedule):
    users = db.get_users()
    for user in users:
        products = db.get_products(user[2])
        for product in products:
            prices = db.get_prices(product[0])
            price = scraper.getPrice(product[2])
            db.add_price(product[0], price)
            try:
                if (float(price) != float(prices[-1][2])):
                    bot.send_message(
                        user[2],
                        "***Price Change***\nName: {} is now \nOld-Price:€{} \nPrice: €{}\nUrl: {}"
                        .format(product[1], prices[-1][2], price, product[2]))
            except (IndexError, TypeError):
                continue
    schedule.enter(sleep, 1, checkPrices, (schedule, ))
Ejemplo n.º 38
0
def send(message):
    if message.chat.id == ADMIN:
        s = message.text[5:]
        users = db.get_users()
        print(users)
        came = 0
        notcame = 0
        for user in users:
            try:
                bot.send_message(user, s, reply_markup=tomenu())
                came += 1
                print(1)
            except:
                notcame += 1
            sleep(0.15)
        bot.send_message(message.chat.id, "Данная рассылка дошла до {came} пользователей\nНедошла до {notcame}пользователей".format(came, notcame))
        print(came, notcame)
Ejemplo n.º 39
0
def tagworld(message):
    try:
        users = db.get_users(message.chat.id)
        if users is None or len(users) == 0:
            users = ''
        users = users.split()
        users = [int(i) for i in users]
        s = bot.get_chat_member(message.chat.id, message.from_user.id).status
        s = str(s)
        if s == 'member':
            bot.send_message(message.chat.id,
                             "У тебя нет прав.",
                             parse_mode='html',
                             reply_markup=None)
        elif len(users) > 0:
            p = ""
            db.set_countUsing(message.chat.id,
                              int(db.get_countUsing(message.chat.id)) + 1)
            db.set_countPeople(
                message.chat.id,
                int(db.get_countPeople(message.chat.id)) + len(users))

            db.set_countUsingGeneral(int(db.get_countUsingGeneral()) + 1)
            db.set_countPeopleGeneral(
                int(db.get_countPeopleGeneral()) + len(users))

            for s in users:
                if s != "":
                    p = p + '\n@' + bot.get_chat_member(message.chat.id,
                                                        s).user.username
            bot.send_message(message.chat.id,
                             p,
                             parse_mode='html',
                             reply_markup=None)
        else:
            bot.send_message(
                message.chat.id,
                "Список пустой. Чтобы добавить себя в список нажмите \n/addme@tagworldbot",
                parse_mode='html',
                reply_markup=None)
    except Exception as e:
        bot.send_message(message.chat.id,
                         "Ошибка.",
                         parse_mode='html',
                         reply_markup=None)
Ejemplo n.º 40
0
    def test_send_requested_currency(self):
        """Test for send_requested_currency"""
        users = db.get_users()
        successful_address = [
            db.get_payment_address(users['callsign_0']['pubkey'],
                                   self.purchase_amount, 'ETH', 'XLM'),
            db.get_payment_address(users['callsign_1']['pubkey'],
                                   self.purchase_amount, 'ETH', 'XLM'),
            db.get_payment_address(users['callsign_2']['pubkey'],
                                   self.purchase_amount, 'ETH', 'BUL')
        ]
        failed_address = [
            db.get_payment_address(users['callsign_3']['pubkey'],
                                   self.purchase_amount, 'ETH', 'BUL'),
            db.get_payment_address(users['callsign_4']['pubkey'],
                                   self.purchase_amount, 'ETH', 'BUL'),
            db.get_payment_address(users['callsign_5']['pubkey'],
                                   self.purchase_amount, 'ETH', 'BUL')
        ]
        routines.create_new_account(users['callsign_5']['pubkey'], 50000000)
        set_trust(users['callsign_5']['pubkey'],
                  self.actual_keypairs[users['callsign_5']['pubkey']], 1000000)
        set_trust(users['callsign_2']['pubkey'],
                  self.actual_keypairs[users['callsign_2']['pubkey']])

        original_function = routines.get_balance
        routines.get_balance = lambda address, _: self.eth_full_payment

        routines.check_purchases_addresses()
        routines.send_requested_currency()
        purchases = db.get_paid_purchases()
        self.assertEqual(len(purchases), 0)
        for purchase in db.get_current_purchases():
            if purchase['payment_pubkey'] in successful_address:
                self.assertEqual(
                    purchase['paid'], 2,
                    "purchase with address: {} has paid status: {} but expected: 2"
                    .format(purchase['payment_pubkey'], purchase['paid']))
            if purchase['payment_pubkey'] in failed_address:
                self.assertEqual(
                    purchase['paid'], -1,
                    "purchase with address: {} has paid status: {} but expected: -1"
                    .format(purchase['payment_pubkey'], purchase['paid']))
        routines.get_balance = original_function
Ejemplo n.º 41
0
 def deal(did, session):
     user_name = check_session(app, session)
     assert isinstance(did, int)
     users = db.get_users(cursor)
     deal_states = db.get_deal_states(cursor)
     sites = db.get_sites(cursor)
     print (users, deal_states, sites)
     d = { 'description': '', 'bdcid':db.find_next_bdcid(cursor, sites[0]['id']), \
           'site_name': sites[0]['name'], 'site_pic':sites[0]['pic'], 'site_id':sites[0]['id'], \
           'creator_id':users[0]['id'], 'creator_name':users[0]['fullname'], \
           'validator_id':users[0]['id'], 'validator_name':users[0]['fullname'], \
           'state':deal_states[0] }
     devis = 0
     if (did > 0):
         deals = db.get_deals(cursor, did)
         devis = db.get_devis(cursor, did)
         print (deals, devis)
         d = deals[0]
     return bottle.template('deal', app=app, user_name=user_name, deal=d, devis=devis, users=users, config=config, did=did, deal_states=deal_states, sites=sites);
Ejemplo n.º 42
0
def push(filename):

    # Config:
    try:
        f = open(filename, 'r') 
    except IOError:
        logging.error("Config File does not exist, please provide a config file.(please see config.example.json)")
        return 
    
    try:
        config = json.load(f)
    except :
        logging.error("Config File is not formated correctly. (please see config.example.json)")
        return 
    
    logging.debug("recieved Config: %s" % config)

    # create notification:
    message = config["notification"]["message"]
    users = get_users(config)

    # DEBUG:
    logging.info("notifications to push: %s" % str(len(users) ))

    # push to Users:
    sent = []
    not_sent = []
    for user in users:
      token = user["token"]
      #uuid = user["uuid"]
      url = create_url(config,token)
      push_success = send_notification(token,message,url)
      if push_success:
        sent.append(token)
      else:
        not_sent.append(token)
        
    logging.info("pushed successfuly : %s" % str(len(sent) ))

    if len(not_sent):
      logging.error("error sending to : {}".format(' '.join(map(str, not_sent))))
Ejemplo n.º 43
0
                        elif "kick_user" == user_data["operation"]:
                            kick = db.kick_user(user_data["user"], user_data["room"])
                            if isinstance(kick, list):
                                for k in kick:
                                    mes = json.dumps({'operation': 'kick_user', 'user': user_data["user"], 'room': k})
                                    broadcast_data(sock, mes)
                                    auth(sock, mes)
                            elif kick:
                                kick = json.dumps(
                                    {'operation': 'kick_user', 'user': user_data["user"], 'room': user_data["room"]})
                                broadcast_data(sock, kick)
                                auth(sock, kick)

                        elif "get_users" == user_data["operation"]:
                            auth(sock, json.dumps({'operation': 'get_users', 'val': db.get_users(user_data['room'])}))

                        elif "get_perms" == user_data["operation"]:
                            auth(sock, json.dumps({'operation': 'get_perms', 'val': db.get_perms(user_data['user'])}))

                        elif "get_perm" == user_data["operation"]:
                            auth(sock, json.dumps({'operation': 'get_perm',
                                                   'val': db.get_perm_for_user(user_data['user'], user_data['room'])}))

                        elif "set_perm" == user_data["operation"]:
                            answer = db.set_perm_for_user(user_data['user'], user_data['room'], user_data['perm'])
                            if answer:
                                answer = json.dumps(
                                    {'operation': 'send_mess', 'user': '******', 'room': user_data['room'],
                                     'text': 'User "' + user_data['user'] + '" you permissions were changed by admin, so please quit from the chat and enter again!'})
                                broadcast_data(sock, answer)
Ejemplo n.º 44
0
def issue(id):

    # if id is >=0 we are editing an existing issue - GET returns a form filled with the current details, POST saves it
    # if id is <0  we are creating a new issue - GET returns a form filled with default values, POST saves it
    try:
        id=int(id)
    except ValueError:
        flash("Sorry - '%s' doesn't look like an integer"%id,"error")
        return redirect( url_for("index") )


    #Create a userlist from the current database
    user_choices=[] # Create a list of usernames for the new issue form
    user_list=db.get_users(get_db())
    for user in user_list: user_choices.append( (user['name'],user['name']) )

    # Create a specialised Form with the correct user choices
    class EditIssueForm(Form):
        formname=HiddenField('formname',default='EditIssue')
        owner= SelectField('Assign to', validators=[DataRequired()],choices=user_choices)
        short_text= TextField('Summary', validators=[DataRequired()])
        #long_text= TextField('Summary', validators=[DataRequired()])
        long_text= TextAreaField('Details')#, validators=[DataRequired()])
        estimated_time= IntegerField('Estimated time',validators=[InputRequired()],default=0) # NOTE InputRequired necessary to accept 0
        severity= SelectField('Severity',choices=severity_array,default=2,coerce=int) # NOTE: coerce to get int(2) not unicode(2)
        open=BooleanField('Open',default=True)
        issue_id=id

    edit_issue_form=EditIssueForm()
    new_att_form=UploadForm()
    new_att_form.issue_id=id

    print type(request.form)
    print dir(request.form)
    print request.form.items()
    print request.form.get('formname','UNKNOWN')


    # If GET, make all the forms and render the page
    if request.method=='GET':
        issue=db.get_issue(get_db(),id)
        if issue: # if we are editing an existing issue, fill in values, else new issue and defaults
            edit_issue_form.owner.data=issue['owner']
            edit_issue_form.short_text.data=issue['short_text']
            edit_issue_form.long_text.data=issue['long_text']
            edit_issue_form.severity.data=issue['severity']
            edit_issue_form.open.data=issue['open']

        # Get all attachments, make a list of tuples containing the filename (as given and uploaded under) and secure value that we actually saved
        atts=db.get_attachments(get_db(),id)
        attachment_list=[]
        for att in atts:
            attachment_list.append( (att['filename'] , secure_filename(att['filename'])) )

        return render_template('issue.html',form=edit_issue_form,attachments=attachment_list,new_att_form=new_att_form)

    # Else we should have a POST form submission, if not, bail:
    if request.method!='POST':
        flash('Unhandled method')
        return redirect(url_for("issues"))

    # method is POST, but which form is submitted?
    if request.form.get('formname')=='EditIssue': # posting a new issue form

        if edit_issue_form.validate():
            if id<0:
                id=db.add_issue(get_db(),
                    reporter=g.user.get_id(),
                    owner=edit_issue_form.owner.data,
                    short_text=edit_issue_form.short_text.data,
                    long_text=edit_issue_form.long_text.data,
                    estimated_time=edit_issue_form.estimated_time.data,
                    severity=edit_issue_form.severity.data,
                    open=edit_issue_form.open.data)
                if id == False:
                    flash('Failed to create issue (DB problem) :-(','error')
                    return redirect( url_for("issues") )
                else:
                    flash('Created issue!')
                    send_issue_mail(id,new=True)
                    return redirect( url_for("issue",id=id) )

            else:
                ok=db.set_issue(get_db(),
                               id,
                               owner=edit_issue_form.owner.data,
                               short_text=edit_issue_form.short_text.data,
                               long_text=edit_issue_form.long_text.data,
                               estimated_time=edit_issue_form.estimated_time.data,
                               severity=edit_issue_form.severity.data,
                               open=edit_issue_form.open.data)
                if ok:
                    flash('Updated issue!')
                    send_issue_mail(id,new=False)

                else:
                    flash('Failed to update issue (DB problem) :-(','error')
                return redirect( url_for("issue",id=id) )

        else: # form didn't validate
            print edit_issue_form.severity,edit_issue_form.severity.data,type(edit_issue_form.severity.data)
            for field,errors in edit_issue_form.errors.items():
                for error in errors: flash('Failed to validate %s:%s'%(field,error),'error')
            return redirect( url_for("index") )

    if request.form.get('formname')=='UploadAttachment':
        print 'Upload attachment'
        print new_att_form
        if new_att_form.validate_on_submit():
            file=request.files['filename']
            if file:
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # will throw on error
                db.add_attachment(get_db(),id,current_user.id,file.filename)
                return redirect(url_for('issue',id=id))
Ejemplo n.º 45
0
def check(bot=False, confile=False):
    if not bot and confile:
        Config = ConfigParser.ConfigParser()
        Config.read(confile)
        HSHBOT_TOKEN = Config.get('options', 'api_token')
        bot = telebot.TeleBot(HSHBOT_TOKEN)
        HSHBOT_ADMIN_ID = int(Config.get('options', 'admin_id') or False)
    elif bot:
        HSHBOT_ADMIN_ID = int(os.environ['HSHBOT_ADMIN_ID'])
    else:
        _logger.error("Cron execution error, bot and confile not found!")
        sys.exit()

    _logger.info("cron:: check()")

    if HSHBOT_ADMIN_ID:
        bot.send_message(HSHBOT_ADMIN_ID, '[INFO] Iniciando cron.check()...')

    users = db.get_users()
    emails_checked = {}

    try:
        for user in users:
            user_emails = [] if 'emails' not in user else user['emails']
            if not user_emails:
                bot.send_message(
                    user['id'],
                    "Se ha ejecutado el checkeo de emails, y veo que no tienes ninguno registrado "
                    "aún...\nRecuerda que puedes hacerlo con /newemail"
                )
            flag_update_urls = False
            for user_email in user_emails:
                email_urls = [] if 'urls' not in user_email else user_email['urls']
                email_urls_data = [email_url['url'] for email_url in email_urls]
                flag_notification = False
                if user_email['email'] not in emails_checked:
                    try:
                        json_data = check_email(user_email['email'])
                    except Exception, e:
                        if HSHBOT_ADMIN_ID:
                            bot.send_message(HSHBOT_ADMIN_ID, '[ERROR] HeSidoHackeadoBot is down!')
                        raise e
                    emails_checked[user_email['email']] = show_data(json_data)
                if emails_checked[user_email['email']]:
                    for line in emails_checked[user_email['email']]:
                        registered = False
                        if line[1] in email_urls_data:
                            registered = True
                            break
                        if not registered:
                            line_str = ' '.join(line)
                            if not flag_notification:
                                flag_notification = True
                                bot.send_message(user['id'], "%s con resultados..." % user_email['email'])
                            bot.send_message(user['id'], line_str)
                            email_urls += [{'url': line[1]}]
                            flag_update_urls = True
                    user_email['urls'] = email_urls
                # if not flag_notification:
                #     bot.send_message(user['id'], "%s Todo OK!" % user_email['email'])
            if flag_update_urls:
                db.register_emails(user['id'], user_emails)
    except Exception, e:
        pass
Ejemplo n.º 46
0
 def GET(self):
     users = db.get_users()
     auth.login_prompt(session, users, '/forum#top', 'Please log in.')
     return 'Authorization failed'