Ejemplo n.º 1
0
 def delete(self, tag_epc, user_id=None):
     content = request.json
     print(content)
     
     _id = content.get('epc', 1)
             
     conn = get_db()
     cur = conn.cursor()
     
     SQL = "DELETE FROM {} WHERE epc = %s RETURNING epc;" 
     SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['tags']))
     data = (tag_epc, )
     
     try:
         cur.execute(SQL, data) 
     except Exception as e:
         print(e)
         conn.rollback()
     else:
         conn.commit()
     
     cur.close()
     
     
     return {"Result": "Deleted"}, 204
Ejemplo n.º 2
0
 def post(self, vehicle_id, tag_epc, user_id=None):
     content = request.json
     print(content)
     
     _id = content.get('epc', 1)
             
     conn = get_db()
     cur = conn.cursor()
     
     SQL = "INSERT INTO {} (epc, bike_id, creation_date) SELECT %s as epc, v.id as bike_id, NOW() FROM {} as v WHERE v.id = %s RETURNING epc;" 
     SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['tags']), sql.Identifier(TABLE_NAMES['vehicles']))
     data = (_id, vehicle_id )
     id_of_new_row = None
     error_message = ""        
     
     try:
         cur.execute(SQL, data) 
     except Exception as e:
         print(e)
         if hasattr(e, 'diag') and hasattr(e.diag, 'message_detail') :
             error_message = e.diag.message_detail
         else :
             error_message = "Database error" 
         conn.rollback()
     else:
         conn.commit()
         id_of_new_row = cur.fetchone()[0]        
     
     cur.close()
     
     # TODO : 409 Conflict if tagId already exists
     if id_of_new_row is None : return {"Error" : error_message}, 404
     
     return id_of_new_row, 201
Ejemplo n.º 3
0
    def post(self):
        content = request.json
        print(content)

        name = content.get('name', None)
        status = content.get('status', 0)
        lastposition = content.get('lastposition', None)
        image = content.get('image', None)
        owner = content.get('owner', None)

        conn = get_db()
        cur = conn.cursor()

        SQL = "INSERT INTO {} ( nickname, picture_gallery_id, owner_id) VALUES (%s, %s, %s) RETURNING id;"
        SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['vehicles']))
        data = (name, image, owner)
        cur.execute(SQL, data)
        id_of_new_row = cur.fetchone()[0]

        # TODO: insert lastposition in the datapoints table

        conn.commit()
        cur.close()

        return id_of_new_row, 201
Ejemplo n.º 4
0
    def get(self, vehicle_id, tag_epc, user_id=None):
        
        args = searchParser.parse_args()

        conn = get_db()
        cur = conn.cursor()
        SQL = "SELECT epc FROM {} where epc = %s limit 1;" 
        SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['tags']))
        data = (tag_epc,) # keep the comma to make it a tuple
        cur.execute(SQL, data) 
        # row = cur.fetchone()
        rows = cur.fetchall()
        if rows == None:
            print("There are no results for this query")
            rows = []
        
        columns = [desc[0] for desc in cur.description]
        result = []
        for row in rows:
            row = dict(zip(columns, row))
            result.append(row)

        conn.commit()
        cur.close()
        return jsonify(result)
Ejemplo n.º 5
0
    async def leave(self,ctx):
        async with ctx.typing():
            db=sql.SQL()
            db.Connect()
            db.RemoveUser(memberID=ctx.author.id)
            db.Close()

        await ctx.send("Hope you had a great time with us. Hope to see you again in the server. Bye! :smile:")

        await get(self.bot.guilds,name=GUILD).kick(ctx.author,reason=f"{ctx.author} used leave command.")
Ejemplo n.º 6
0
    async def un_register(self, ctx, mailID: str):
        if not self.is_in_channel(ctx, REGISTRATION_CHANNEL):
            await ctx.message.add_reaction(CROSS_EMOJI)
            return

        async with ctx.typing():
            db = sql.SQL()
            db.Connect()
            db.RemoveUser(mailID=mailID)
            db.Close()
            await ctx.message.add_reaction(CHECK_EMOJI)
Ejemplo n.º 7
0
    def delete(self, vehicle_id, user_id=None):
        conn = get_db()
        cur = conn.cursor()

        SQL = "DELETE FROM {} WHERE id = %s;"
        SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['vehicles']))
        data = (vehicle_id, )
        cur.execute(SQL, data)

        conn.commit()
        cur.close()
        return '', 204
Ejemplo n.º 8
0
    async def ExcelForm(self, ctx):
        async with ctx.typing():
            db = sql.SQL()
            db.Connect()
            ok = db.GenerateCSV()

        if ok:
            await ctx.message.add_reaction(CHECK_EMOJI)
            await ctx.send(file=discord.File(sql.EXCEL_PATH))
            db.DeleteCSV()
            db.Close()
            return

        await ctx.message.add_reaction(CROSS_EMOJI)
        db.Close()
Ejemplo n.º 9
0
    async def UpdateRoles(self, ctx, Role1: str, Role2: str):
        if self.is_a_DM(ctx):
            await ctx.message.add_reaction(CROSS_EMOJI)
            return

        async with ctx.typing():
            obj1 = discord.utils.get(ctx.guild.roles, name=Role1)
            obj2 = discord.utils.get(ctx.guild.roles, name=Role2)

        if obj1 is None:
            await ctx.message.add_reaction(CROSS_EMOJI)
            await ctx.send("Enter a valid role 1.")
            return

        if obj2 is None:
            await ctx.message.add_reaction(CROSS_EMOJI)
            await ctx.send("Enter a valid role 2.")
            return

        async with ctx.typing():
            count = 0
            for member in ctx.guild.members:
                ok = discord.utils.get(member.roles, name=Role1)
                if ok:
                    await member.add_roles(obj2)
                    count += 1

        # As a sub-process, we also remove old alumni of below CURRENT_YEAR-DELTA_YEAR seniority
        async with ctx.typing():
            count = 0
            db = sql.SQL()
            db.Connect()
            results = db.filterOldAlumni(str(datetime.now().year))
            if results is not None:
                for alumniID in results:
                    alumni = discord.utils.get(ctx.guild.members,
                                               id=int(alumniID))
                    alumni.send(
                        "Will miss you! All the best from IIIT-B community!\n")
                    ctx.guild.kick(alumni, reason="Old Alumni")
                    count += 1
            db.Close()

        await ctx.message.add_reaction(CHECK_EMOJI)
        await ctx.send(
            f"Updated roles of {count} member(s) and removed {count} Old Alumni successfully!"
        )
Ejemplo n.º 10
0
    async def kick(self, ctx, member: discord.User = None, reason=None):

        if member is None or member == ctx.message.author:
            await ctx.message.add_reaction(CROSS_EMOJI)
            await ctx.send("You cannot kick out yourself.")
            return

        async with ctx.typing():
            await member.send(
                f"<@{member.id}> You have been kicked out from {ctx.guild.name}. Contact admins."
            )
            await ctx.guild.kick(member,
                                 reason=f"{ctx.author} used kick command.")

            db = sql.SQL()
            db.Connect()
            db.RemoveUser(memberID=member.id)
            db.Close()

        await ctx.message.add_reaction(CHECK_EMOJI)
Ejemplo n.º 11
0
    def get(self, user_id):
              
        conn = get_db()
        cur = conn.cursor()
        SQL = "SELECT k.\"UID\" as id, u.username, u.first_name, u.last_name, u.email, u.is_staff, u.is_active, u.date_joined, u.nickname, u.language_preference FROM {} as u LEFT JOIN {} as k ON k.user_id = u.id where k.\"UID\" = %s limit 1;" 
        SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['users']), sql.Identifier(TABLE_NAMES['users_mapping']))
        data = (user_id,) # keep the comma to make it a tuple
        cur.execute(SQL, data) 
        rows = cur.fetchall()
        if rows == None:
            print("There are no results for this query")
            rows = []
        
        columns = [desc[0] for desc in cur.description]
        result = []
        for row in rows:
            row = dict(zip(columns, row))
            result.append(row)

        conn.commit()
        cur.close()
        return jsonify(result)
Ejemplo n.º 12
0
import sys
sys.path.insert(0, '..')
from settings import REDIRECT_URI
from flask import Flask, render_template, make_response, request
import base64, pickle, requests
from secret import CLIENT_ID, CLIENT_SECRET, TOKEN, NEWBIE, GUILD_ID
from Database import sql
import os

db = sql.SQL()

app = Flask(__name__)


@app.errorhandler(404)
def not_found(e):
    return render_template("/HTML/404.html")


_url1 = "https://discord.com/api/oauth2/token"
_headers1 = {
    'Content-Type': 'application/x-www-form-urlencoded',
}

_url2 = "https://discord.com/api/users/@me"

_headers3 = {'authorization': f'Bot {TOKEN}'}

headers = {'Content-Type': 'text/html'}

Ejemplo n.º 13
0
    async def verify(self,ctx,emailID:str,key:str):
        
        async with ctx.typing():
            ok=get(get(get(self.bot.guilds,name=GUILD).members,id=int(ctx.author.id)).roles,name=NEWBIE)
       
        if not ok:
            await ctx.send(f"<@{ctx.author.id}> You are already verified and assigned once afaik. Contact admins if I'm wrong.")
            return

        async with ctx.typing():
            db=sql.SQL()
            db.Connect()

            isPresent=db.isPresent(emailID)
            isVerified=db.isVerified(None,emailID)

        await ctx.message.add_reaction(CHECK_EMOJI)

        if not isPresent:
            db.Close()
            await ctx.send(f"<@{ctx.message.author.id}> '{emailID}' is not registered. Contact admins.")
            return

        if isVerified:
            batch=db.getBatch(emailID)
            db.Close()
            
            guild=get(self.bot.guilds,name=GUILD)
            members=guild.members
            roles=guild.roles
            role_obj=get(roles,name=batch)
            user_obj=get(members,name=ctx.author.name)
            
            await ctx.send(f"<@{ctx.message.author.id}> '{emailID}' is already verified successfully! You have been given {batch} role again. Welcome back!. :smile: ")
            await user_obj.add_roles(role_obj)
            await user_obj.remove_roles(get(roles,name=NEWBIE))
            return

        async with ctx.typing():
            ok=db.VerifyUser(str(ctx.message.author),ctx.message.author.id,emailID,key)
        
        if ok:
            async with ctx.typing():
                batch=db.getBatch(emailID)
            db.Close()
            await ctx.send(f"<@{ctx.author.id}> Yay!! You have been verified successfully and given {batch} role!")
            intro=Embeds.IntroEmbed(self.bot,str(ctx.message.author),emailID,str(ctx.message.author.id))
            await ctx.author.send(embed=intro)

            guild=get(self.bot.guilds,name=GUILD)
            members=guild.members
            roles=guild.roles
            role_obj=get(roles,name=batch)
            user_obj=get(members,name=ctx.author.name)

            await user_obj.add_roles(role_obj)
            await user_obj.remove_roles(get(roles,name=NEWBIE))

            greeting=random.choice(GREETINGS).replace(_GREETINGS, f"<@{ctx.author.id}>")
            await get(guild.channels,id=int(WELCOME_CHANNEL)).send(greeting)

            return

        db.Close()
        await ctx.send(f"<@{ctx.author.id}> Sorry, couldn't verify you.\nTry again.")
Ejemplo n.º 14
0
    def get(self):
        args = searchParser.parse_args()
         
        per_page = 50;
        offset = 0;
        dump = False;
        
        if args['per_page'] is not None:
            try:
                per_page=limit_int(int(args['per_page']), 0, 100)
            except ValueError: 
                pass
        
        if args['page'] is not None:
            try:
                offset=limit_int(int(args['page']) * per_page, 0)
            except ValueError: 
                pass
        
        if args['dump'] is not None:
            if args['dump'] == 'true':
                dump = True 

        print("DUMP is "+str(dump))        

        conn = get_db()
        cur = conn.cursor()
        
        SQL="SELECT k.\"UID\" as id, u.username, u.first_name, u.last_name, u.email, u.is_staff, u.is_active, u.date_joined, u.nickname, u.language_preference FROM {} as u LEFT JOIN {} as k ON k.user_id = u.id order by id limit %s offset %s;"
        SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['users']), sql.Identifier(TABLE_NAMES['users_mapping']))
        data = (per_page, offset)

        # if dump is true compose all users/vehicles/tags and output them
        if dump:
            SQL="SELECT k.\"UID\" as id, u.id as numeric_id, u.username, u.first_name, u.last_name, u.email, u.is_staff, u.is_active, u.date_joined, u.nickname, u.language_preference FROM {} as u LEFT JOIN {} as k ON k.user_id = u.id order by id asc;"
            SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['users']), sql.Identifier(TABLE_NAMES['users_mapping']))
            data = None
        
        
        cur.execute(SQL, data)
        # row = cur.fetchone()
        rows = cur.fetchall()
        if rows == None:
            print("There are no results for this query")
            rows = []
        
        columns = [desc[0] for desc in cur.description]
        result = []
        for row in rows:
            row = dict(zip(columns, row))
            result.append(row)

        
        if dump:
            for i in result:
                i['vehicles'] = []
                print(json.dumps(i))
                SQL="""Select v.id as id, v.lastupdate, 1 as type, v.nickname as name, CASE WHEN vs.lost = true THEN 1 ELSE 0 END as status, v.picture_gallery_id, v.owner_id as owner, 
                        CASE WHEN vp.position IS NOT NULL THEN
                            jsonb_build_object(
                                'type',       'Feature',
                                'id',         vp.id,
                                'geometry',   ST_AsGeoJSON(vp.position)::jsonb,
                                'properties', CASE WHEN vp.reporter_id IS NOT NULL THEN  json_build_object(
                                                                                        'reporter_id', vp.reporter_id
                                                                                     ) ELSE '{{}}' END
                            )
                            ELSE NULL
                        END as lastposition 
                        FROM {} as v 
                        LEFT JOIN 
                        (
                            SELECT vs1.bike_id, vs1.lost
                            FROM vehicles_bikestatus vs1
                            LEFT JOIN vehicles_bikestatus vs2 ON vs1.bike_id = vs2.bike_id AND vs1.creation_date < vs2.creation_date
                            WHERE vs2.creation_date IS NULL
                        ) as vs
                        ON vs.bike_id = v.id
                        LEFT JOIN 
                        (
                            SELECT vp1.id, vp1.bike_id, vp1.position, vp1.reporter_id
                            FROM {} vp1
                            LEFT JOIN {} vp2 ON vp1.bike_id = vp2.bike_id AND vp1.observed_at < vp2.observed_at
                            WHERE vp2.observed_at IS NULL
                        ) as vp
                        ON vp.bike_id = v.id
                        WHERE owner_id = %s order by id asc;"""
                SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['vehicles']), sql.Identifier(TABLE_NAMES['vehiclemonitor_bikeobservation']), sql.Identifier(TABLE_NAMES['vehiclemonitor_bikeobservation']))
                data = (i['numeric_id'],)
                cur.execute(SQL, data)
                vehicles = cur.fetchall()
                if vehicles == None:
                    print("There are no results for vehicles query")
                    vehicles = []
                
                v_columns = [desc[0] for desc in cur.description]
                for v in vehicles:
                    v = dict(zip(v_columns, v))
                    
                    #Fill the tags
                    v['tags'] = []
                    #print(json.dumps(v))
                    
                    SQL = "SELECT epc FROM {} where bike_id = %s order by epc;" 
                    SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['tags']))
                    data = (v['id'],)
                    cur.execute(SQL, data)
                    tags = cur.fetchall()
                    if tags == None:
                        print("There are no tags for this vehicles")
                        tags = []
                    
                    t_columns = [desc[0] for desc in cur.description]
                    for t in tags:
                        t = dict(zip(t_columns, t))
                        print(json.dumps(t))
                        v['tags'].append(t)
                    
                    #Fill the images
                    v['images'] = []
                    print(json.dumps(v))
                    
                    SQL = "SELECT concat('https://dev.savemybike.geo-solutions.it/media/', image) url FROM public.photologue_photo pp LEFT JOIN public.photologue_gallery_photos pgp on pp.id = pgp.photo_id where pgp.gallery_id = %s" 
                    data = (v['picture_gallery_id'],)
                    cur.execute(SQL, data)
                    images = cur.fetchall()
                    if images == None:
                        print("There are no images for this vehicles")
                        images = []
                    
                    #t_columns = [desc[0] for desc in cur.description]
                    for img in images:
                        #t = dict(zip(t_columns, t))
                        print(json.dumps(img))
                        v['images'].append(img[0])
                    
                    
                    i['vehicles'].append(v)
                del i['numeric_id']

        conn.commit()
        cur.close()
        return jsonify(result)
Ejemplo n.º 15
0
    def get(self, user_id):

        args = searchParser.parse_args()

        per_page = 50
        offset = 0
        tagId = None

        if args['per_page'] is not None:
            try:
                per_page = limit_int(int(args['per_page']), 0, 100)
            except ValueError:
                pass

        if args['page'] is not None:
            try:
                offset = limit_int(int(args['page']) * per_page, 0)
            except ValueError:
                pass

        if args['tagId'] is not None:
            try:
                tagId = limit_int(int(args['tagId']), 0)
            except ValueError:
                pass

        if tagId is not None:
            SQL = "SELECT v.* FROM {} as v JOIN {} as t ON v.id = t.vehicle_id where t.epc = %s;"
            SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['vehicles']),
                                      sql.Identifier(TABLE_NAMES['tags']))
            data = (tagId, )
        else:
            SQL = """Select v.id as id, v.lastupdate, 1 as type, v.nickname as name, CASE WHEN vs.lost = true THEN 1 ELSE 0 END as status, v.picture_gallery_id, k.kuid as owner, 
                        CASE WHEN vp.position IS NOT NULL THEN
                            jsonb_build_object(
                                'type',       'Feature',
                                'id',         vp.id,
                                'geometry',   ST_AsGeoJSON(vp.position)::jsonb,
                                'properties', CASE WHEN vp.reporter_id IS NOT NULL THEN  json_build_object(
                                                                                        'reporter_id', vp.reporter_id
                                                                                     ) ELSE '{{}}' END
                            )
                            ELSE NULL
                        END as lastposition 
                        FROM {} as v 
                        LEFT JOIN 
                        (
                            SELECT vs1.bike_id, vs1.lost
                            FROM vehicles_bikestatus vs1
                            LEFT JOIN vehicles_bikestatus vs2 ON vs1.bike_id = vs2.bike_id AND vs1.creation_date < vs2.creation_date
                            WHERE vs2.creation_date IS NULL
                        ) as vs
                        ON vs.bike_id = v.id
                        LEFT JOIN 
                        (
                            SELECT vp1.id, vp1.bike_id, vp1.position, vp1.reporter_id
                            FROM {} vp1
                            LEFT JOIN {} vp2 ON vp1.bike_id = vp2.bike_id AND vp1.observed_at < vp2.observed_at
                            WHERE vp2.observed_at IS NULL
                        ) as vp
                        ON vp.bike_id = v.id
                        LEFT JOIN
                        (
                            SELECT \"UID\" as kuid, user_id as portal_id
                            FROM {} as u
                        ) as k
                        ON k.portal_id = v.owner_id
                    WHERE k.kuid = %s order by k.kuid limit %s offset %s;"""
            SQL = sql.SQL(SQL).format(
                sql.Identifier(TABLE_NAMES['vehicles']),
                sql.Identifier(TABLE_NAMES['vehiclemonitor_bikeobservation']),
                sql.Identifier(TABLE_NAMES['vehiclemonitor_bikeobservation']),
                sql.Identifier(TABLE_NAMES['users_mapping']))
            data = (user_id, per_page, offset)

        conn = get_db()
        cur = conn.cursor()
        cur.execute(SQL, data)
        # row = cur.fetchone()
        rows = cur.fetchall()
        if rows == None:
            print("There are no results for this query")
            rows = []

        columns = [desc[0] for desc in cur.description]
        result = []
        for row in rows:
            row = dict(zip(columns, row))
            result.append(row)

        conn.commit()
        cur.close()
        return jsonify(result)
Ejemplo n.º 16
0
    def get(self, vehicle_id, user_id=None):

        conn = get_db()
        cur = conn.cursor()
        #SQL = "SELECT v.*, ST_AsGeoJSON(d.the_geom) as last_position FROM vehicles v LEFT JOIN datapoints d on d.vehicle_id = v._id where v.id = %s order by d.timestamp desc limit 1;"
        SQL = """Select v.id as id, v.lastupdate, 1 as type, v.nickname as name, CASE WHEN vs.lost = true THEN 1 ELSE 0 END as status, v.picture_gallery_id, v.owner_id as owner, 
                        CASE WHEN vp.position IS NOT NULL THEN
                            jsonb_build_object(
                                'type',       'Feature',
                                'id',         vp.id,
                                'geometry',   ST_AsGeoJSON(vp.position)::jsonb,
                                'properties', CASE WHEN vp.reporter_id IS NOT NULL THEN  json_build_object(
                                                                                        'reporter_id', vp.reporter_id
                                                                                     ) ELSE '{{}}' END
                            )
                            ELSE NULL
                        END as lastposition 
                        FROM {} as v 
                        LEFT JOIN 
                        (
                            SELECT vs1.bike_id, vs1.lost
                            FROM vehicles_bikestatus vs1
                            LEFT JOIN vehicles_bikestatus vs2 ON vs1.bike_id = vs2.bike_id AND vs1.creation_date < vs2.creation_date
                            WHERE vs2.creation_date IS NULL
                        ) as vs
                        ON vs.bike_id = v.id
                        LEFT JOIN 
                        (
                            SELECT vp1.id, vp1.bike_id, vp1.position, vp1.reporter_id
                            FROM {} vp1
                            LEFT JOIN {} vp2 ON vp1.bike_id = vp2.bike_id AND vp1.observed_at < vp2.observed_at
                            WHERE vp2.observed_at IS NULL
                        ) as vp
                        ON vp.bike_id = v.id
                 WHERE v.id = %s;"""
        SQL = sql.SQL(SQL).format(
            sql.Identifier(TABLE_NAMES['vehicles']),
            sql.Identifier(TABLE_NAMES['vehiclemonitor_bikeobservation']),
            sql.Identifier(TABLE_NAMES['vehiclemonitor_bikeobservation']))
        data = (vehicle_id,
                )  # using vehicle id , not uuid (uuid will be used in V2.0)

        try:
            cur.execute(SQL, data)
        except Exception as error:
            print(error)
            return jsonify([])

        rows = cur.fetchall()
        print(rows)
        if rows == None:
            print("There are no results for this query")
            rows = []

        columns = [desc[0] for desc in cur.description]
        result = []
        for row in rows:
            row = dict(zip(columns, row))
            print(json.dumps(row))

            result.append(row)

        conn.commit()
        cur.close()
        return jsonify(result)
Ejemplo n.º 17
0
    async def send_mails(self, ctx, batch, students):
        async with ctx.typing():

            success = []
            failed = []
            registered = []

            db = sql.SQL()
            db.Connect()

            smtp_object = smtp.SMTP()

            for mailID in students:
                mailID = mailID.lower()

                if (not smtp.SMTP.validMail(
                        mailID.lower())) or (mailID in NON_STUDENT_MAILS):
                    failed.append(mailID)
                    continue

                isPresent = db.isPresent(mailID)
                isVerified = db.isVerified(None, mailID)

                if isPresent and isVerified:
                    registered.append(mailID)
                    continue

                Key = Bcrypt.GeneratePassword()
                KeyHash = Bcrypt.Hash(Key)

                if isPresent and (not isVerified):
                    db.RemoveUser(mailID=mailID)

                db.AddUser(mailID, batch, str(datetime.now().year), KeyHash)

                stateObj = {'emailID': mailID, 'key': Key, 'batch': batch}
                state = base64.urlsafe_b64encode(
                    pickle.dumps(stateObj)).decode('utf-8')
                url = f"{OAUTH_URL}&state={state}"

                smtp_object.send_mail(mailID, Key, url)
                success.append(mailID)

            successLen = len(success)
            failedLen = len(failed)
            registeredLen = len(registered)

            with open(SUMMARY_PATH, 'w') as f:
                f.write("Success,Failed,Already Registered\n")
                for i in range(max([successLen, failedLen, registeredLen])):
                    if i < successLen:
                        f.write(f"{success[i]},")
                    else:
                        f.write(',')
                    if i < failedLen:
                        f.write(f"{failed[i]},")
                    else:
                        f.write(',')
                    if i < registeredLen:
                        f.write(registered[i])
                    f.write('\n')

        smtp_object.quit()

        await ctx.message.add_reaction(CHECK_EMOJI)

        await ctx.send(file=discord.File(SUMMARY_PATH))

        os.remove(SUMMARY_PATH)

        db.Close()
Ejemplo n.º 18
0
    def post(self, vehicle_id, user_id=None):
        content = request.json  #: :type content: dict
        print(' -- content -- ')
        print(content)

        if content is None: return None, 304

        name = content.get('name', None)
        status = content.get('status', 0)
        lastposition = content.get('lastposition', None)
        image = content.get('image', None)
        owner = content.get('owner', None)  #: :type owner: tuple

        conn = get_db()
        cur = conn.cursor()

        SQL = "Select id from {} where id::text = %s"
        SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['vehicles']))
        data = (vehicle_id, )
        cur.execute(SQL, data)

        query_results = cur.fetchone()

        if query_results is None:
            return {"Error": "Cannot find vehicle"}, 500

        vehicle_uuid = query_results[0]

        # update the position
        if lastposition is not None:
            # parse GeoJSON
            # position = json.loads(lastposition)
            # print(json.dumps(lastposition))
            print(' -- lastposition -- ')
            print(lastposition)
            if lastposition['type'] == 'Feature':
                print(' -- geometry -- ')
                print(lastposition['geometry'])
                print(' -- coordinates -- ')
                print(lastposition['geometry']['coordinates'])
                lon = lastposition['geometry']['coordinates'][0]
                lat = lastposition['geometry']['coordinates'][1]

                try:
                    reporter_id = lastposition['properties']['reporter_id']
                except:
                    #TODO use the id of the actual user using this API
                    reporter_id = 1

                try:
                    reporter_name = lastposition['properties']['reporter_name']
                except:
                    #TODO use the id of the actual user using this API
                    reporter_name = 1

                try:
                    reporter_type = lastposition['properties']['reporter_type']
                except:
                    #TODO use the id of the actual user using this API
                    reporter_type = 1

                SQL = "INSERT INTO {} (bike_id, position, reporter_id, reporter_name, reporter_type, created_at, observed_at, details, address) VALUES ( %s, ST_SetSRID(ST_Point(%s, %s), 4326), %s, %s, %s, now(), now(), '', '') returning id;"
                SQL = sql.SQL(SQL).format(
                    sql.Identifier(
                        TABLE_NAMES['vehiclemonitor_bikeobservation']))
                data = (vehicle_uuid, lon, lat, reporter_id, reporter_name,
                        reporter_type)

                cur.execute(SQL, data)
                id_of_new_row = cur.fetchone()[0]

                print('new datapoint row: %s' % (id_of_new_row, ))
            else:
                return {
                    'Error':
                    "Please provide 'lastposition' as a valid GeoJSON point"
                }, 500

        inputslist = []
        SQL = "UPDATE {} SET lastupdate = now()"
        if 'name' in content:
            SQL += ', nickname = %s'
            inputslist.append(name)
        if 'status' in content:
            # TODO INSERT THE NEW STATUS TO THE DATABASE
            None
        if 'image' in content:
            SQL += ', picture_gallery_id = %s'
            inputslist.append(image)
        if 'owner' in content:
            SQL += ', owner_id = %s'
            inputslist.append(owner)

        SQL += " where id = %s RETURNING id;"
        SQL = sql.SQL(SQL).format(sql.Identifier(TABLE_NAMES['vehicles']))
        inputslist.append(vehicle_id)

        data = tuple(inputslist)
        cur.execute(SQL, data)
        id_of_new_row = cur.fetchone()[0]

        conn.commit()
        cur.close()

        return id_of_new_row, 201
Ejemplo n.º 19
0
    async def register(self, ctx, batch: str, *arguments):

        if not self.is_in_channel(ctx, REGISTRATION_CHANNEL):
            await ctx.message.add_reaction(CROSS_EMOJI)
            return

        if not get(ctx.guild.roles, name=batch):
            await ctx.send("Enter a valid batch role. (case-sensitive)")
            return

        async with ctx.typing():

            sentmails = 0
            success = ""
            failed = ""
            summary = ""
            registered = ""

            db = sql.SQL()
            db.Connect()

            smtp_object = smtp.SMTP()

            for mailID in arguments:
                mailID = mailID.lower()

                if (not smtp.SMTP.validMail(
                        mailID.lower())) or (mailID in NON_STUDENT_MAILS):
                    failed += f"{mailID}\n"
                    continue

                isPresent = db.isPresent(mailID)
                isVerified = db.isVerified(None, mailID)

                if isPresent and isVerified:
                    registered += f"{mailID}\n"
                    continue

                Key = Bcrypt.GeneratePassword()
                KeyHash = Bcrypt.Hash(Key)

                if isPresent and (not isVerified):
                    db.RemoveUser(mailID=mailID)

                db.AddUser(mailID, batch, str(datetime.now().year), KeyHash)

                stateObj = {'emailID': mailID, 'key': Key, 'batch': batch}
                state = base64.urlsafe_b64encode(
                    pickle.dumps(stateObj)).decode('utf-8')
                url = f"{OAUTH_URL}&state={state}"

                smtp_object.send_mail(mailID, Key, url)

                success += f"{mailID}\n"

                sentmails += 1

            summary += f"{MAIL_EMOJI} Successfully sent {sentmails} mail(s).\n\n"

            if success:
                summary += (f"{CHECK_EMOJI} Successfully sent mails to : \n"
                            f"{success}\n")
            if failed:
                summary += (f"{CROSS_EMOJI} Failed sending mails to : \n"
                            f"{failed}\n")
            if registered:
                summary += (
                    f"{UNCHECK_EMOJI} Found few already registered mails : (skipped them)\n"
                    f"{registered}\n")

        smtp_object.quit()

        await ctx.message.add_reaction(CHECK_EMOJI)

        await ctx.send(summary)

        db.Close()