Exemple #1
0
 def test_users(self):
     sql.create_table_users()
     sql.add_user("Joe", "Bob", "123-456-7890", "890-123-4567",
                  "*****@*****.**", "jeff's farm", "calgary",
                  "southern alberta", "TRUE", "TRUE", "TRUE", "2018-09-01",
                  "livestock", "5", "none", "none", "none", "none", "none",
                  "none", "none", "none", "none", "none", "hellllooooo")
     sql.add_user("Jim", "Greg", "123-456-7890", "890-123-4567",
                  "*****@*****.**", "jeff's farm", "calgary",
                  "southern alberta", "TRUE", "TRUE", "TRUE", "2018-09-01",
                  "livestock", "5", "none", "none", "none", "none", "none",
                  "none", "none", "none", "none", "none", "hellllooooo")
     users = sql.get_users()
     self.assertEqual(2, len(users))
     self.assertEqual("Joe", users[0].first_name)
     self.assertEqual("*****@*****.**", users[1].email)
     user = sql.get_user(1)
     # print(user)
     self.assertEqual("Joe", user.first_name)
     user = sql.get_user(2)
     self.assertEqual("Greg", user.last_name)
     user = sql.get_user(10)
     self.assertIsNone(None)
     sql.update_user("Jeff", "Kwok", "123-456-7890", "890-123-4567",
                     "*****@*****.**", "jeff's farm", "calgary",
                     "southern alberta", "TRUE", "TRUE", "TRUE",
                     "2018-09-01", "livestock", "5", "none", "none", "none",
                     "none", "none", "none", "none", "none", "none", "none",
                     "hellllooooo", "1")
     user = sql.get_user(1)
     # print(user)
     self.assertEqual("*****@*****.**", user.email)
     self.assertEqual("jeff's farm", user.f_name)
     # print(user.p_number)
     sql.delete_table_users()
def car_id(your_car_id):
    # Checks whether the car id provided in the URL exists in the db
    if your_car_id not in all_owners().keys():
        # Returns an Error message if not
        return render_template('qr_error.html', your_car_id=your_car_id)
    if request.method == "POST":
        # Calls the public key of the owner of the car id given in the URL
        owner = all_owners()[your_car_id]
        # Calls the hashed private key of the corresponding public key
        key_owner = all_loggins()[owner]
        # Hashes the private key typed in on the website
        password = hasher.sha1(
            request.form["password"].encode('utf-8')).hexdigest()
        # Calls the Data of the owner
        user_data = get_user(owner)
        first_name = user_data.first_name()
        last_name = user_data.last_name()
        email = user_data.email()
        # Compares if the hashed password provided on the website and in the db match
        # It also grant access if the code "123" is typed in. This is the police code!
        if password == key_owner or password == "40bd001563085fc35165329ea1ff5c5ecbdbbeef":
            return render_template('dashboard.html',
                                   first_name=first_name,
                                   last_name=last_name,
                                   email=email,
                                   car_id=your_car_id)
        else:
            error_title = "Wrong Password!"
            error_msg = "Your password does not match with the car " + your_car_id + " Please check again. Otherwise, contact the traffic office of your canton"
            return render_template('your_car.html',
                                   error_title=error_title,
                                   error_msg=error_msg)
    return render_template('your_car.html')
Exemple #3
0
def inlinenow(update, context):
    'inline implementation of notplaying() function along with exception handeling for new users'
    try: 
        uid = update.inline_query.from_user.id
        authtoken = list(sql.get_user(uid)[0])[2]
    except: 
        update.inline_query.answer(
            results=[], 
            switch_pm_text='Connect your Spotify account.',
            switch_pm_parameter='link', 
            cache_time=0
        )
        return
    try: 
        data = {
            'grant_type':'refresh_token',
            'refresh_token':authtoken,
            'redirect_uri':redirect_uri,
            'client_id':client_id,
            'client_secret':client_secret
        }
        token = requests.post('https://accounts.spotify.com/api/token', data=data).json()
    except:
        update.inline_query.answer(
            results=[], 
            switch_pm_text="Something's wrong. Lets fix it.", 
            switch_pm_parameter='relink', 
            cache_time=0
        )
        return
    try: 
        headers = {
            'Accept':'application/json', 
            'Content-Type':'application/json', 
            'Authorization':'Bearer '+token['access_token']
        }
        r = requests.get('https://api.spotify.com/v1/me/player/currently-playing', headers=headers).json()
        if   r['currently_playing_type'] == 'ad': 
            update.inline_query.answer([], switch_pm_text="You're listening to annoying ads.", switch_pm_parameter='ads', cache_time=0)
        elif r['currently_playing_type'] == 'track':
            button = InlineKeyboardButton(text="Play on Spotify", url=r['item']['external_urls']['spotify'])
            image   = getpic(r, uid, context)
            dump    = context.bot.send_photo(dumpchannel, photo=image)
            photo   = dump['photo'][1]['file_id']
            dump.delete()
            update.inline_query.answer(
                [
                    InlineQueryResultCachedPhoto(
                        id=uuid4(),
                        photo_file_id=photo,
                        reply_markup=InlineKeyboardMarkup([[button]])
                    )
                ], cache_time=0
            )
        else: 
            update.inline_query.answer([], switch_pm_text="Not sure what you're listening to.", switch_pm_parameter='notsure', cache_time=0)
    except Exception as e: 
        print(e)
        update.inline_query.answer([], switch_pm_text="You're not listening to anything.", switch_pm_parameter='notlistening', cache_time=0)
Exemple #4
0
def relink(update, context):
    'update stored token'
    if update.effective_chat.type != update.effective_chat.PRIVATE:
        button = InlineKeyboardMarkup([[InlineKeyboardButton(text="Link",url="t.me/spotifynowbot")]])
        update.effective_message.reply_text("Contact me in private chat to link your Spotify account.", reply_markup=button)
        return
    if not sql.get_user(update.effective_user.id): 
        update.effective_message.reply_text("You need to /link before using this function.")
        return
    message = "Tap the button below to authorize."
    button = InlineKeyboardMarkup([[InlineKeyboardButton(text="Authorize", url=authlink)]])
    update.effective_message.reply_text(message, reply_markup=button)
    return
Exemple #5
0
def authen(credentials: HTTPBasicCredentials = Depends(security)):
    user = sql.get_user(credentials.username)
    not_authen_msg = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Incorrect username or password",
        headers={"WWW-Authenticate": "Basic"},
    )
    if user:
        if bcrypt.verify(credentials.password, user['hashed_password']):
            return credentials.username
        else:
            raise not_authen_msg
    else:
        raise not_authen_msg
Exemple #6
0
def getpic(r, uid, context):
    'retrives and passes all arguments to the image processor'
    username  = list(sql.get_user(uid)[0])[1]
    songname  = r['item']['name']
    albumname = r['item']['album']['name']
    totaltime = r['item']['duration_ms']
    crrnttime = r['progress_ms']
    coverart  = requests.get(r['item']['album']['images'][1]['url'])
    artists   = ', '.join([x['name'] for x in r['item']['artists']])
    try:
        pfp  = context.bot.getUserProfilePhotos(uid, limit=1)['photos'][0][0]['file_id']
        user = requests.get(context.bot.getFile(pfp).file_path)
    except:
        user = requests.get('https://files.catbox.moe/jp6szj.jpg')
    return(processor.process(username, songname, albumname, artists, crrnttime, totaltime, user, coverart))
Exemple #7
0
def nowplaying(update, context):
    'collects user info, requests spotify api for song info and sends the processed image'
    context.bot.sendChatAction(update.message.chat_id, ChatAction.TYPING)
    try: 
        uid = update.message.from_user.id
        authtoken = list(sql.get_user(uid)[0])[2]
    except: 
        update.message.reply_text('You need to /link your Spotify account with me first.')
        return
    try: 
        data = {
            'grant_type': 'refresh_token', 
            'refresh_token': authtoken, 
            'redirect_uri': redirect_uri, 
            'client_id': client_id, 
            'client_secret': client_secret
        }
        token = requests.post('https://accounts.spotify.com/api/token', data=data).json()
    except:
        update.message.reply_text('Something went wrong. Try to /relink your account.')
        return
    try: 
        headers = {
            'Accept': 'application/json', 
            'Content-Type': 'application/json', 
            'Authorization': 'Bearer '+token['access_token']
        }
        r = requests.get('https://api.spotify.com/v1/me/player/currently-playing', headers=headers).json()
        if   r['currently_playing_type'] == 'ad': 
            update.message.reply_text("Ads. You're listening to those annoying ads.")
        elif r['currently_playing_type'] == 'track':
            button = InlineKeyboardButton(text="Play on Spotify", url=r['item']['external_urls']['spotify'])
            context.bot.send_photo(update.message.chat_id, getpic(r, uid, context), reply_markup=InlineKeyboardMarkup([[button]]))
        else: 
            update.message.reply_text("I'm not sure what you're listening to.")
    except Exception as e: 
        print(e)
        update.message.reply_text("You're not listening to anything on Spotify at the moment.")
Exemple #8
0
async def answer(query):
    stickerpack = await bot.get_sticker_set(config.stickerpack_name)
    yes_sticker = stickerpack.stickers[config.yes_sticker]
    no_sticker = stickerpack.stickers[config.no_sticker]
    answer = query.data.split(',')[0]
    user_id = query.data.split(',')[1]
    user = sql.get_user(c, user_id)
    if not user[4]:
        await bot.send_message(user_id,
                               config.donate_message,
                               reply_markup=config.autodonate_keyboard)
    if answer == 'yes':
        await bot.send_message(
            user_id,
            f'@PocketHelperBot: Ответ от [{query.from_user.first_name}](tg://user?id={query.from_user.id})',
            parse_mode='markdown')
        await bot.send_sticker(user_id, yes_sticker.file_id)
    else:
        await bot.send_message(
            user_id,
            f'@PocketHelperBot: Ответ от [{query.from_user.first_name}](tg://user?id={query.from_user.id})',
            parse_mode='markdown')
        await bot.send_sticker(user_id, no_sticker.file_id)
    await query.answer('Ответ отправлен')