Example #1
0
def AvgMarks(marks):
    try:
        queryDict = {i[0]:[int(x[0]) for x in i[1]] for i in zip(map(lambda x:int(x[0]),marks['subdata']),marks['marks'])}
        return vtop.marksupdater.avgClass.getAvg(queryDict)
    except:
        modifyExp()
        raise Exception('error in fetchMarks')
Example #2
0
def nameParse(s):
    try:
        ind = s.index('font-weight: bold;">Student')
        name_text = re.findall(
            '<td style="background-color: #f2dede;">(.*?)</td>',
            s[ind:s.index('</tr>', ind)])
        return name_text[0]
    except:
        modifyExp()
        raise Exception('getName failed')
Example #3
0
def verifyLogin(cred):
    try:
        username = cred['username'].upper()
        password = cred['password']
        userDatabaseDetails = SQLclasses.users.query.filter_by(
            regno=username).first()
        return username, password, userDatabaseDetails
    except:
        exploitLog(sys._getframe())
        modifyExp(exploitRedirect(), 418)
        raise Exception('Error in getting username/password')
Example #4
0
def gradecalcParse(s):
    try:
        ind = s.find('Total Number Of Credits: ')
        totalCredit = int(
            re.findall('<span>(.*?)</span>', s[ind:ind + 100])[0])
        courseTable = re.search("<table class=\"table\"(.*?)<\/table>", s,
                                re.DOTALL).group(1)
        courseCol = re.findall(
            '#3c8dbc;vertical-align: middle;text-align: left;\">(.*?)</td>',
            courseTable)
        lis = []
        for i in courseCol:
            temp = i.split(' - ')
            lis.append([temp[0], temp[1]])
        # lis contains names of subject and subject code as it is in the table // list

        classInfo = re.findall('<p style=\"margin: 0px;\">(.*?)</p>',
                               courseTable)

        r = [[lis[i // 9][0], lis[i // 9][1], classInfo[i + 2].split(' ')[-1]]
             for i in range(0, len(classInfo), 9)]
        # r contains subject code and roomno mapped with classno and subject name // dict

        finlist = []
        gradelist = []
        credit = 0
        for i in r:
            if i[0] + ' - ' + i[1] not in finlist:
                finlist.append(i[0] + ' - ' + i[1])
                gradelist.append(credit)
                credit = int(i[2])
            else:
                credit += int(i[2])
        gradelist.append(credit)

        if sum(gradelist) != totalCredit:
            raise ValueError('problem in varifying gradelist')

        out = [
            finlist[i].split(' - ') + [gradelist[i + 1]]
            for i in range(len(finlist))
        ]
        if totalCredit and out:
            return {
                'gradeCalc': out,
                'totalCredit': totalCredit,
                "response": 'OK'
            }
        raise ValueError('Empty data')
    except:
        modifyExp()
        raise Exception('error in gradecalcParse')
Example #5
0
def oldUserLogin(loginid, password, queryResult, userAgent):
    cookieTime, dbPassword, cookies, marksTime = queryResult.time, queryResult.passwrd, eval(queryResult.cookies), queryResult.marksTime
    hashpassword = utils.data2hash(loginid, password)
    if hashpassword != dbPassword:
        exploitLog(sys._getframe())
        return exploitRedirect(), 418

    session = requests.session()
    session.trust_env = False
    
    for cookie in cookies:
        session.cookies.set(cookie[0],cookie[1])
    session.headers.update({'User-Agent':userAgent})
    cookieUpdate =  False
    Time = math.trunc(time.time())
    # test login by fetching attendance, relogin
    reLogin = True
    if Time - queryResult.time < 900:
        attendance_data = fetchAPI.Attendance(session, loginid)
        # fetching attendance failed. User might logged in from another device.
        reLogin = not attendance_data

    if reLogin:
        session.cookies.clear()
        error, session = fetchLogin(session, loginid, password)
        if error: return loginError
        attendance_data = fetchAPI.Attendance(session, loginid)
        cookieUpdate = True

    # fetch marks data
    marks = fetchAPI.Marks(session, loginid)    
    if not marks:
        modifyExp()
        raise Exception('Attendance fetched but not marks')

    avg  = AvgMarks(marks['marksdata'])
    marks['marksdata']['AvgData'] = avg

    if cookieUpdate:
        cookieList = getCookies(session)
        queryResult.cookies = str(cookieList)

    queryResult.time = Time
    db.session.commit()

    if Time - marksTime > 86400:
        threading.Thread(target = marksUpdate, args= (loginid, marks['marksdata'],)).start()
    
    return {'attendance':attendance_data,'marks':marks, 'response':'OK'}
Example #6
0
def fetchLogin(session, loginid, password, count=0):
    # if count==1: return {'status':False}
    loginUrl = urlList['LOGIN']
    login_page = session.get(loginUrl, verify=False, allow_redirects = False).text
    token = re.search('logintoken\" value=\"(.*?)">',login_page)
    if token:
        token  = token.group(1)
    else:
        modifyExp()
        raise 'Token not found'
    
    keys={'username':loginid, 'password': password, 'logintoken':token, 'anchor':''}
    login = session.post(loginUrl, data = keys, verify = False, allow_redirects = False)
    if login.text.find('testsession') != -1: 
        return 0, session
    return 1, loginError
Example #7
0
def marksParse(s):
    try:
        s = s.replace('\r', '').replace('\t', '')
        p = s
        JSONformat = {}
        s = re.findall("tableContent-level1\">(.*?)</tr>", s, re.DOTALL)
        l = []
        m = []
        for i in s:
            #if i[0:28]=='\n<td><output>1</output></td>':
            k = i.replace('></output>', '').replace('</output>', '$').replace(
                'output', '').replace('td', '').replace('\n', '').replace(
                    '/', '').replace('<', '').replace('>',
                                                      '')[:-1:].split('$')[:7]
            if int(k[0]) == 1:
                l.append(m)
                m = []
            m.append([
                int(k[0]),
                k[1].replace('Digital Assignment',
                             'DA').replace('Continous Assessment Test',
                                           'CAT'), k[2], k[3], k[5], k[6]
            ])
        # if end
        l.append(m)
        del l[0]
        # subject
        cpy = []
        p = re.findall('<tr class=\"tableContent\" >(.*?)<\/tr>', p, re.DOTALL)

        for i in p:
            k = i.replace('\t', '').replace('</td>\n', '$').replace(
                '<td>', '').replace('\n', '')[:-1:].split('$')
            cpy.append([k[1][-5:], k[2], k[3], k[6]])
        if cpy and l:
            JSONformat['subdata'] = cpy
            JSONformat['marks'] = l
            return {'marksdata': JSONformat, 'response': 'OK'}

        raise ValueError('Empty data')
    except:
        modifyExp()
        raise Exception('error in marksParse')
Example #8
0
def attendanceParse(data):
    try:
        JSONformat = {}
        classno = re.findall("AttendanceDetail\(&#39;(.*?)&#39;", data)
        data = re.findall("style=\"margin: 0px;\">(.*?)</p>", data)
        data = [{
            'uid':
            classno[i // 9][-5:],
            'value':
            [data[i + 1], data[i + 2], data[i + 6], data[i + 7], data[i + 8]]
        } for i in range(0, len(data), 9)]
        JSONformat['total'] = len(data)
        JSONformat['values'] = data
        response = "OK"
        if data:
            return {'attendance': JSONformat, "response": response}
        raise ValueError('Empty data')
    except:
        modifyExp()
        raise Exception('error in attendanceParse')
Example #9
0
def getAssignmentData(session, sessionKey):
    try:
        timestampfrom = int(
            datetime.datetime.timestamp(
                datetime.datetime.combine((datetime.datetime.now() -
                                           datetime.timedelta(days=7)).date(),
                                          datetime.datetime.min.time())))
        timestampto = int(
            datetime.datetime.timestamp(
                datetime.datetime.combine((datetime.datetime.now() +
                                           datetime.timedelta(days=14)).date(),
                                          datetime.datetime.min.time())))
        jsondata = [{
            "index": 0,
            "methodname": "core_calendar_get_action_events_by_timesort",
            "args": {
                "limitnum": 11,
                "timesortfrom": timestampfrom,
                'timesortto': timestampto
            }
        }]
        jsonresponse = session.post(
            f'{serverUrl}/lib/ajax/service.php?sesskey={sessionKey}&info=core_calendar_get_action_events_by_timesort',
            json=jsondata,
            verify=False)
        jsonObj = json.loads(jsonresponse.text)[0]
        if jsonObj['error']:
            raise 'JSON response error'
        assignList = jsonObj['data']['events']
        data = []
        for i in assignList:
            data.append([
                i['id'], i['name'], i['course']['fullname'], i['timesort'],
                i['component']
            ])
        return {'assignmentData': data, 'response': 'OK'}
    except:
        modifyExp()
        raise 'function getAssignmentData'
Example #10
0
def gradelistParse(s):
    gradeList = []
    creditCalc = []
    try:
        s = s.replace('\r', '').replace('\t', '')
        ind0 = s.index('Effective Grades')
        ind1 = s.index(
            'Student fails to clear one or more components of a course', ind0)
        table = re.findall('<tr class="tableContent">(.*?)</tr>', s[ind0:ind1],
                           re.DOTALL)
        for i in table:
            td = re.findall('>(.*?)</td>', i)
            gradeList.append([td[1], td[2], td[4], td[5]])

        ind0 = s.index('Credits Earned', ind1)
        ind1 = s.index('Basket Details', ind0)
        table = re.findall('<tr class="tableContent">(.*?)</tr>', s[ind0:ind1],
                           re.DOTALL)
        for i in table:
            td = re.findall('>(.*?)</td>', i)
            creditCalc.append(td)
        ind0 = s.index('N Grades', ind1)
        table = re.findall('<tr class="tableContent">(.*?)</tr>', s[ind0:],
                           re.DOTALL)
        for i in table:
            td = re.findall('>(.*?)</td>', i)
            gpaList = td
        if gradeList and creditCalc and gpaList:
            return {
                'gradeList': gradeList,
                'creditCalc': creditCalc,
                'gpaList': gpaList,
                'response': 'OK'
            }
        raise ValueError('Empty data')
    except:
        modifyExp()
        raise Exception('error in gradelistParse')
Example #11
0
def fetchLogin(session, loginid, password):
    
    vtop_page = "http://vtopcc.vit.ac.in:8080/vtop/"
    login_page = "http://vtopcc.vit.ac.in:8080/vtop/vtopLogin"
    doLogin_page = "http://vtopcc.vit.ac.in:8080/vtop/doLogin"
    
    login = session.get(vtop_page, verify = False, stream = True)
    utils.chunkDownloader(login, 10)
    pageSource = session.get(login_page, verify = False).text
    cap,msg =  captcha.break_captcha(pageSource)
    if not cap:
        if msg == 'VIT_ERROR':
            modifyExp(response ={'response':'error', 'msg':'VTOP server is not responding', 'code':22},code = 503)
        else:
            modifyExp()
        raise Exception('captcha failed') 
    keys={'uname': loginid,'passwd': password,'captchaCheck':cap}
    dologin =  session.post(doLogin_page,data=keys,verify=False, stream = True)
    chunkdata  = utils.chunkDownloader(dologin, 200)

    if 'container-fluid' in chunkdata[150:]:
        return 0, session
    return 1,loginError
Example #12
0
def routineParse(s):
    def processLab(lb):
        new = []
        time = ''
        old = ''
        for ind, i in enumerate(lb):
            if time == '':
                time = i[1]
                old = i
            else:
                if i[2] == old[2]:
                    time += i[1]
                else:
                    splt = time.split('-')
                    time = '-'.join([splt[0], splt[-1]])
                    old[1] = time
                    new.append(old)
                    time = i[1]
                    old = i
        if time != '':
            splt = time.split('-')
            time = '-'.join([splt[0], splt[-1]])
            old[1] = time
            new.append(old)
        return new

    try:
        courseTable = re.search("<table class=\"table\"(.*?)<\/table>", s,
                                re.DOTALL).group(1)
        courseCol = re.findall(
            '#3c8dbc;vertical-align: middle;text-align: left;\">(.*?)</td>',
            courseTable)
        lis = []
        emptyCheck = 1
        for i in courseCol:
            temp = i.split(' - ')
            lis.append([temp[0], temp[1]])
        # lis contains names of subject and subject code as it is in the table // list
        classInfo = re.findall('<p style=\"margin: 0px;\">(.*?)</p>',
                               courseTable)
        r = {
            lis[i // 9][0] + '-' + classInfo[i:i + 8][6]:
            [classInfo[i:i + 8][4][-5:], lis[i // 9][1]]
            for i in range(0, len(classInfo), 9)
        }
        # r contains subject code and roomno mapped with classno and subject name // dict
        s = re.search("<table id=\"timeTableStyle\"(.*?)<\/table>",
                      s, re.DOTALL).group(1).replace('\r', '').replace(
                          '\t', '').replace('\n', '')
        JSONformat = []
        day = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']

        tr = re.findall("<tr(.*?)/tr>", s, re.DOTALL)

        td = tr[0]
        txt = re.findall('>(.*?)</td>', td)
        tempth = [i for i in txt[2:]]

        td = tr[1]
        txt = re.findall('>(.*?)</td>', td)
        tempth2 = [i for i in txt[1:]]
        theoryTime = {
            ind: f'{dat1}-{dat2}'
            for ind, (dat1, dat2) in enumerate(zip(tempth, tempth2))
        }

        td = tr[2]
        txt = re.findall('>(.*?)</td>', td)
        tempth = [i for i in txt[2:]]

        td = tr[3]
        txt = re.findall('>(.*?)</td>', td)
        tempth2 = [i for i in txt[1:]]
        labTime = {
            ind: f'{dat1}-{dat2}'
            for ind, (dat1, dat2) in enumerate(zip(tempth, tempth2))
        }

        JSONparse = []
        for ind in range(4, len(tr), 2):
            td = re.findall('>(.*?)</td>', tr[ind])
            th, lb = [], []
            for ind2, txt in enumerate(td[2:]):
                if txt.count('-') > 2:
                    splt = txt.split('-')
                    dat = '-'.join([splt[lin] for lin in [1, 3, 4]])
                    code, name = r[dat]
                    th.append(
                        [ind2, theoryTime[ind2], dat + '-' + code, name, 'th'])

            td = re.findall('>(.*?)</td>', tr[ind + 1])
            for ind2, txt in enumerate(td[1:]):
                if txt.count('-') > 2:
                    emptyCheck = 0
                    splt = txt.split('-')
                    dat = '-'.join([splt[lin] for lin in [1, 3, 4]])
                    code, name = r[dat]
                    lb.append(
                        [ind2, labTime[ind2], dat + '-' + code, name, 'lb'])
            lb = processLab(lb)
            JSONformat.append({
                'day': day[ind // 2 - 2],
                'class': sorted(th + lb)
            })

        if emptyCheck:
            raise ValueError('Empty Data')

        return json.dumps({'routine': JSONformat, 'response': 'OK'})
    except:
        modifyExp()
        raise Exception('error in RoutineParse')