Пример #1
0
def rename_user(store, old, new):
    c = store.get_cursor()
    old_user = store.get_user(old)
    if not old_user:
        raise SystemExit("Old does not exist")
    if store.get_user(new):
        raise SystemExit("New user already exists!")

    c.execute(
        'UPDATE accounts_user SET username = %s WHERE username = %s',
        (new, old),
    )
    c.execute('update openids set name=%s where name=%s', (new, old))
    c.execute('update sshkeys set name=%s where name=%s', (new, old))
    c.execute('update roles set user_name=%s where user_name=%s', (new, old))
    c.execute('delete from rego_otk where name=%s', (old, ))
    c.execute('update journals set submitted_by=%s where submitted_by=%s',
              (new, old))
    c.execute('update mirrors set user_name=%s where user_name=%s', (new, old))
    c.execute('update comments set user_name=%s where user_name=%s',
              (new, old))
    c.execute('update ratings set user_name=%s where user_name=%s', (new, old))
    c.execute(
        'update comments_journal set submitted_by=%s where submitted_by=%s',
        (new, old))
Пример #2
0
def merge_user(store, old, new):
    c = store.get_cursor()
    if not store.get_user(old):
        print "Old does not exist"
        raise SystemExit
    if not store.get_user(new):
        print "New does not exist"
        raise SystemExit

    c.execute('update openids set name=%s where name=%s', (new, old))
    c.execute('update sshkeys set name=%s where name=%s', (new, old))
    c.execute('update roles set user_name=%s where user_name=%s', (new, old))
    c.execute('delete from rego_otk where name=%s', (old, ))
    c.execute('update journals set submitted_by=%s where submitted_by=%s',
              (new, old))
    c.execute('update mirrors set user_name=%s where user_name=%s', (new, old))
    c.execute('update comments set user_name=%s where user_name=%s',
              (new, old))
    c.execute('update ratings set user_name=%s where user_name=%s', (new, old))
    c.execute(
        'update comments_journal set submitted_by=%s where submitted_by=%s',
        (new, old))
    c.execute(
        'delete from accounts_email where user_id=(select id from accounts_user where username=%s)',
        (old, ))
    c.execute('delete from accounts_user where username=%s', (old, ))
Пример #3
0
def watchlist(bot, update):
    logger.info("watchlist")
    message = update.message
    chat = message.chat
    update.message.reply_text("Listing pokemons on watchlist")

    u = store.get_user(chat.id)
    if u is None:
        update.message.reply_text("Please start by setting your location")
        return

    ups = store.get_user_pokemons(chat.id)

    wl = []

    for p in settings.pokemons:
        show = True
        for up in ups:
            if p == up.pokemon:
                show = False

        if show:
            wl.append(settings.pokemons[p])

    update.message.reply_text("\n".join(wl))
Пример #4
0
def remove_spammer(store, name, confirm=False):
    user = store.get_user(name)
    if not user:
        sys.exit('user %r does not exist' % name)

    cursor = st.get_cursor()
    cursor.execute(
        """
       select distinct(submitted_from)
        from journals
        where submitted_by = %s
    """, (name, ))
    print 'IP addresses of spammers to possibly block:'
    for (ip, ) in cursor.fetchall():
        print '  ', ip

    for p in store.get_user_packages(name):
        print p['package_name']
        if confirm:
            store.remove_package(p['package_name'])

    if confirm:
        cursor.execute(
            "update accounts_user set password='******' where name=%s",
            (name, ))
Пример #5
0
def add_owner(store, package, owner):
    user = store.get_user(owner)
    if user is None:
        raise ValueError, 'user name unknown to me'
    if not store.has_package(package):
        raise ValueError, 'no such package'
    store.add_role(owner, 'Owner', package)
Пример #6
0
def watch(bot, update, args):
    logger.info("watch")
    message = update.message
    chat = message.chat

    if len(args) != 1:
        update.message.reply_text(
            "Usage: /watch <pokemon>, i.e. /watch pidgey")
        return

    u = store.get_user(chat.id)
    if u is None:
        update.message.reply_text("Please start by setting your location")
        return

    pokemon_to_find = args[0]

    p = get_pokemon_by_name(pokemon_to_find)
    if p:
        rows = store.delete_userpokemons(u, p)
        update.message.reply_text("Added " + settings.pokemons[p] +
                                  " to watchlist")
    else:
        update.message.reply_text("Could not find any pokemon named " +
                                  message.text)
Пример #7
0
def show_user(store, name):
    user = store.get_user(name)
    if not user:
        sys.exit('user %r does not exist' % name)
    for key in user.keys():
        print '%s: %s' % (key, user[key])
    for p in store.get_user_packages(name):
        print '%s: %s' % (p['package_name'], p['role_name'])
Пример #8
0
def set_password(store, name, pw):
    """ Reset the user's password and send an email to the address given.
    """
    user = store.get_user(name.strip())
    if user is None:
        raise ValueError, 'user name unknown to me'
    store.store_user(user['name'], pw.strip(), user['email'], None)
    print 'done'
Пример #9
0
def is_valid_login():
    try:
        h = hashlib.new('sha512')
        h.update(request.form['password'])
        user = get_user(request.form['username'])
        return True if user['password'] == h.hexdigest() else False
    except KeyError:
        return False
Пример #10
0
def show_user(store, name):
    user = store.get_user(name)
    if not user:
        sys.exit('user %r does not exist' % name)
    for key in user.keys():
        print '%s: %s' % (key, user[key])
    for p in store.get_user_packages(name):
        print '%s: %s' % (p['package_name'], p['role_name'])
Пример #11
0
def merge_user(store, old, new):
    c = store.get_cursor()
    if not store.get_user(old):
        print "Old does not exist"
        raise SystemExit
    if not store.get_user(new):
        print "New does not exist"
        raise SystemExit

    c.execute('update openids set name=%s where name=%s', (new, old))
    c.execute('update sshkeys set name=%s where name=%s', (new, old))
    c.execute('update roles set user_name=%s where user_name=%s', (new, old))
    c.execute('delete from rego_otk where name=%s', (old,))
    c.execute('update journals set submitted_by=%s where submitted_by=%s', (new, old))
    c.execute('update mirrors set user_name=%s where user_name=%s', (new, old))
    c.execute('update comments set user_name=%s where user_name=%s', (new, old))
    c.execute('update ratings set user_name=%s where user_name=%s', (new, old))
    c.execute('update comments_journal set submitted_by=%s where submitted_by=%s', (new, old))
    c.execute('delete from users where name=%s', (old,))
Пример #12
0
def delete_owner(store, package, owner):
    user = store.get_user(owner)
    if user is None:
        raise ValueError, 'user name unknown to me'
    if not store.has_package(package):
        raise ValueError, 'no such package'
    for role in store.get_package_roles(package):
        if role['role_name']=='Owner' and role['user_name']==owner:
            break
    else:
        raise ValueError, "user is not currently owner"
    store.delete_role(owner, 'Owner', package)
Пример #13
0
def rename_user(store, old, new):
    c = store.get_cursor()
    old_user = store.get_user(old)
    if not old_user:
        raise SystemExit("Old does not exist")
    if store.get_user(new):
        raise SystemExit("New user already exists!")

    c.execute(
        'UPDATE accounts_user SET username = %s WHERE username = %s',
        (new, old),
    )
    c.execute('update openids set name=%s where name=%s', (new, old))
    c.execute('update sshkeys set name=%s where name=%s', (new, old))
    c.execute('update roles set user_name=%s where user_name=%s', (new, old))
    c.execute('delete from rego_otk where name=%s', (old,))
    c.execute('update journals set submitted_by=%s where submitted_by=%s', (new, old))
    c.execute('update mirrors set user_name=%s where user_name=%s', (new, old))
    c.execute('update comments set user_name=%s where user_name=%s', (new, old))
    c.execute('update ratings set user_name=%s where user_name=%s', (new, old))
    c.execute('update comments_journal set submitted_by=%s where submitted_by=%s', (new, old))
Пример #14
0
def default(bot, update):
    logger.info("default")
    update.message.reply_text(
        "Defaulting your settings, check ignorelist/watchlist")

    message = update.message
    chat = message.chat

    u = store.get_user(chat.id)
    if u is None:
        update.message.reply_text("Please start by setting your location")
        return

    set_default(u)
Пример #15
0
def stop(bot, update):
    logger.info("stop")
    message = update.message
    chat = message.chat

    u = store.get_user(chat.id)
    if u is None:
        update.message.reply_text("Please start by setting your location")
        return

    u.active = False
    rows = u.save()

    if rows == 1:
        update.message.reply_text("You are deactivated")
Пример #16
0
def ignorelist(bot, update):
    logger.info("ignorelist")
    message = update.message
    chat = message.chat
    update.message.reply_text("Listing pokemons on ignorelist")

    u = store.get_user(chat.id)
    if u is None:
        update.message.reply_text("Please start by setting your location")
        return

    il = []

    ups = store.get_user_pokemons(chat.id)
    for up in ups:
        il.append(settings.pokemons[up.pokemon])

    update.message.reply_text("\n".join(il))
Пример #17
0
def status(bot, update):
    logger.info("status")
    message = update.message
    chat = message.chat

    u = store.get_user(chat.id)
    if u is None:
        update.message.reply_text("Please start by setting your location")
        return

    if u.active:
        update.message.reply_text("You are active at " + str(u.latitude) +
                                  " " + str(u.longitude))
        lastupdated_text = u.lastupdated.strftime("%H:%M:%S")
        update.message.reply_text("Last check for pokemons: " +
                                  lastupdated_text)

    else:
        update.message.reply_text("You are inactive")
Пример #18
0
def run():
    from store import get_coll, SMS
    # ensure proper indexing
    get_coll(SMS).ensure_index([('send_on', 1)])

    one_minute = timedelta(minutes=1)

    logger.info('Starting main scheduling loop')
    while True:  # main loop
        logger.debug("I'm awake.")

        now = datetime.utcnow()
        one_minute_later = now + one_minute

        logger.info("Current time: %s." % now)

        uid_cache = {}
        smses = store.get_smses(send_on={'$gte': now, '$lt': one_minute_later})

        smses = list(smses)  # needed to get a length
        logger.info('Got %d SMSes.' % len(smses))

        for sms in smses:
            uid = sms.user_id
            if uid in uid_cache:
                user = uid_cache[uid]
            else:
                user = store.get_user(_id=sms.user_id)
                if not user:
                    logger.error("Cannot find user_id %d, skipping." % uid)
                    continue
                uid_cache[uid] = user

            logger.debug("Sending SMS with API id '%s...'" % user.api_id[4:])
            ret = send_sms(sms.text, user.api_id, user.api_key)
            logger.debug("return %s" % str(ret))
            logger.debug("deleting SMS")
            store.del_sms(sms)
            sleep(0.2)  # this gives us a maximum of 5*60=300 SMSes/minute

        logger.debug('Going to sleep.')
        sleep(60)
Пример #19
0
def maxdistance(bot, update, args):
    logger.info("maxdistance")
    message = update.message
    chat = message.chat

    u = store.get_user(chat.id)
    if u is None:
        update.message.reply_text("Please start by setting your location")
        return

    if len(args) != 1:
        update.message.reply_text(
            "Usage: /watch <pokemon>, i.e. /watch pidgey")
        return

    u.normal_distance = int(args[0])
    rows = u.save()

    if rows == 1:
        update.message.reply_text("maxdistance is set to %s" % args[0])
Пример #20
0
def remove_spammer(store, name, confirm=False):
    user = store.get_user(name)
    if not user:
        sys.exit('user %r does not exist' % name)

    cursor = st.get_cursor()
    cursor.execute("""
       select distinct(submitted_from)
        from journals
        where submitted_by = %s
    """, (name,))
    print 'IP addresses of spammers to possibly block:'
    for (ip,) in cursor.fetchall():
        print '  ', ip

    for p in store.get_user_packages(name):
        print p['package_name']
        if confirm:
            store.remove_package(p['package_name'])

    if confirm:
        cursor.execute("update accounts_user set password='******' where name=%s",
             (name,))
Пример #21
0
def settings():
    try:
        if not user.logged_in():
            return redirect(url_for('login'))
        _user = store.get_user(session['username'])
        db = store.get_db()
        errors = []
        feed_rss = db.get('subrss/user/%s/rss' % session['username']) if db.exists('subrss/user/%s/rss' % session['username']) else ""
        if request.method == 'GET':
            return render_template('settings_form.html',    success = False,
                                                            username = _user['username'],
                                                            email = _user['mail'],
                                                            feed_rss = feed_rss,
                                                            errors = errors,
                                                            logged_in = user.logged_in())
        else:
            if user.validate_email(request.form['mail']) and not request.form['mail'] in db.smembers('subrss/emails'):
                db.srem('subrss/mails', _user['mail'])
                db.sadd('subrss/mails', request.form['mail'])
                db.set('subrss/user/%s/mail' % session['username'], request.form['mail'])
            else:
                errors.append("El email introducido no es válido o ya está en uso.")
            if request.form['password']:
                if len(request.form['password']) >= 8 and _user['password'] == store.crypt_password(request.form['password_repeat']):
                    db.set('subrss/user/%s/password' % session['username'], store.crypt_password(request.form['password']))
                else:
                    errors.append("La clave introducida no es correcta.")
            if request.form['feed']:
                db.set('subrss/user/%s/rss' % session['username'], request.form['feed'])
            return render_template('settings_form.html',    success = True if not errors else False,
                                                            username = _user['username'],
                                                            email = _user['mail'],
                                                            feed_rss = feed_rss,
                                                            errors = errors,
                                                            logged_in = user.logged_in())
    except Exception, e:
        return redirect(url_for('home'))
Пример #22
0
def ignore(bot, update, args):
    logger.info("ignore")
    message = update.message
    chat = message.chat

    if len(args) != 1:
        update.message.reply_text(
            "Usage: /ignore <pokemon>, i.e. /ignore pidgey")
        return

    u = store.get_user(chat.id)
    if u is None:
        update.message.reply_text("Please start by setting your location")
        return

    pokemon_to_find = args[0]

    p = get_pokemon_by_name(pokemon_to_find)
    if p:
        up, created = store.get_or_create_userpokemons(u, p)
        update.message.reply_text("Ignoring " + settings.pokemons[p])
    else:
        update.message.reply_text("Could not find any pokemon named " +
                                  pokemon_to_find)
Пример #23
0
    fpackage = store.find_package(package)

    if not fpackage:
        continue

    package = fpackage[0]
    hosting_mode = store.get_package_hosting_mode(package)

    if hosting_mode != "pypi-scrape-crawl":
        continue

    users = sorted(set(users))

    emails = []
    for username in users:
        user = store.get_user(username)
        if user["email"]:
            emails.append(user["email"])

    msg = MIMEText(EMAIL_BODY % {"project": package})
    msg["Subject"] = "Important Information about %s on PyPI" % package
    msg["From"] = "*****@*****.**"
    msg["To"] = ", ".join(emails)

    print "Sending for", package, "[%s/%s]" % (i, len(package_users))

    try:
        server.sendmail("*****@*****.**", emails, msg.as_string())
        sent.append(("*****@*****.**", emails, msg.as_string()))
    except:
        traceback.print_exc()
Пример #24
0
def owner_email(p):
    result = set()
    for r,u in store.get_package_roles(p):
        if r == 'Owner':
            result.add(store.get_user(u)['email'])
    return result
Пример #25
0
    for role in store.get_package_roles(new):
        user_packages = users.setdefault(role["user_name"], [])
        user_packages.append((old, new))

sent = []

# Email each user
server = smtplib.SMTP(config.mailgun_hostname)
if config.smtp_starttls:
    server.starttls()
if config.smtp_auth:
    server.login(config.smtp_login, config.smtp_password)
for username, packages in users.iteritems():
    packages = sorted(set(packages))

    user = store.get_user(username)

    if not user["email"]:
        continue

    if len(packages) > 1:
        msg = MIMEText(
            EMAIL_PLURAL % {
                "old": ", ".join(['"%s"' % x[0] for x in packages]),
                "new": ", ".join(['"%s"' % x[1] for x in packages]),
            })
    elif packages:
        msg = MIMEText(EMAIL_SINGLE % {
            "old": packages[0][0],
            "new": packages[0][1],
        })