def main(): reddit = authenticate() user = reddit.redditor(input('Enter a username u/')) commentCounts = userCommentCount(user) submissionCounts = userSubmissionCount(user) formatCount(commentCounts, submissionCounts) userSubreddit = input('\nEnter a subreddit r/') comments = subredditComments(user, userSubreddit) submissions = subredditSubmissions(user, userSubreddit) if len(comments) + len( submissions) != 0: #If they've actually submitted to that sub. txtExport( str(user) + '_' + str(userSubreddit) + '.txt', comments, submissions) exportPath = os.path.join( os.getcwd(), str(user) + '_' + str(userSubreddit) + '.txt') print(exportPath) os.startfile(exportPath, 'open') else: print('\n' + str(user) + ' has not submitted to ' + str(userSubreddit) + ' in their last 1k posts.')
def field_of_study(config, session=False): url = "https://www.lectio.dk/lectio/%s/contextcard/contextcard.aspx?lectiocontextcard=%s" % ( str(config["school_id"]), str(config["context_card_id"])) if session is False: session = authenticate.authenticate(config) if session == False: return {"status": "error", "type": "authenticate"} # Insert the session information from the auth function cookies = { "lecmobile": "0", "ASP.NET_SessionId": session["ASP.NET_SessionId"], "LastLoginUserName": session["LastLoginUserName"], "lectiogsc": session["lectiogsc"], "LectioTicket": session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded", "Host": "www.lectio.dk", "Origin": "https://www.lectio.dk", "Cookie": functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("span", attrs={"id": "ctl00_Content_cctitle"}) is None: return {"status": False, "error": "Data not found"} tables = soup.findAll("table") idProg = re.compile( r"\/lectio\/(?P<school_id>.*)\/studieretningSe.aspx\?sid=(?P<field_of_study_id>.*)" ) idGroups = idProg.match( soup.find( attrs={"id": "ctl00_Content_linksrep_ctl00_somelink"})["href"]) return { "status": "ok", "field_of_study": { "name": unicode(tables[1].findAll("td")[1].text), "field_of_study_id": idGroups.group("field_of_study_id") if not idGroups is None else "", "school_id": str(config["school_id"]), "context_card_id": str(config["context_card_id"]) } }
def image(config, session=False): url = "https://www.lectio.dk/lectio/%s/fravaer_billede.aspx?elevid=%s&year=%s&startdate=%s&enddate=%s" % ( str(config["school_id"]), str(config["student_id"]), str( config["year"]), config["start_date"].strftime("%d-%m-%Y"), config["end_date"].strftime("%d-%m-%Y")) if session is False: session = authenticate.authenticate(config) if session == False: return {"status": "error", "type": "authenticate"} # Insert the session information from the auth function cookies = { "lecmobile": "0", "ASP.NET_SessionId": session["ASP.NET_SessionId"], "LastLoginUserName": session["LastLoginUserName"], "lectiogsc": session["lectiogsc"], "LectioTicket": session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded", "Host": "www.lectio.dk", "Origin": "https://www.lectio.dk", "Cookie": functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) return response.text
def image(config, picture_id, session=False): if session is False: session = authenticate.authenticate(config) if session == False: return {"status": "error", "type": "authenticate"} else: url = "https://www.lectio.dk/lectio/%s/GetImage.aspx?pictureid=%s&fullsize=1" % ( str(config["school_id"]), str(picture_id)) # Insert the session information from the auth function cookies = { "lecmobile": "0", "ASP.NET_SessionId": session["ASP.NET_SessionId"], "LastLoginUserName": session["LastLoginUserName"], "lectiogsc": session["lectiogsc"], "LectioTicket": session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded", "Host": "www.lectio.dk", "Origin": "https://www.lectio.dk", "Cookie": functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) return response.text
def image ( config, session = False ): url = "https://www.lectio.dk/lectio/%s/fravaer_billede.aspx?elevid=%s&year=%s&startdate=%s&enddate=%s" % ( str(config["school_id"]), str(config["student_id"]), str(config["year"]), config["start_date"].strftime("%d-%m-%Y"), config["end_date"].strftime("%d-%m-%Y") ) if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) return response.text
def main(argv): # Configure Parameters and Options options = 'e:u:p:P:R:C:' longOptions = ['endpoint=', 'user='******'password='******'pwdfile=', 'resourcename=', 'cookie='] # Get Options & Arguments try: opts, args = getopt.getopt(argv, options, longOptions) # Read Module Arguments moduleArgs = readModuleArgs(opts, args) if moduleArgs['cookie'] is None and moduleArgs['endpoint'] is not None and moduleArgs['user'] is not None: if moduleArgs['password'] is None and moduleArgs['pwdfile'] is None: moduleArgs['password'] = getPassword(moduleArgs['user']) elif moduleArgs['pwdfile'] is not None: with open(moduleArgs['pwdfile'], 'r') as f: moduleArgs['password'] = f.read().rstrip('\n') moduleArgs['cookie'] = authenticate(moduleArgs['endpoint'], moduleArgs['user'], moduleArgs['password']) if moduleArgs['cookie'] is not None: jsonObj = deleteStorageVolume(moduleArgs['endpoint'], moduleArgs['resourcename'], moduleArgs['cookie']) printJSON(jsonObj) else: print ('Incorrect parameters') except getopt.GetoptError: usage() except Exception as e: print('Unknown Exception please check log file') logging.exception(e) sys.exit(1) return
def main(): options = get_options(sys.argv[1:]) subreddit, post_limit, comment_limit, upload_choice = get_args(options) reddit = authenticate() print("Starting\n") scrape_reddit(reddit, subreddit, post_limit, comment_limit) if upload_choice: upload_to_reddit(reddit)
def image ( config, picture_id, session = False ): if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} else: url = "https://www.lectio.dk/lectio/%s/GetImage.aspx?pictureid=%s&fullsize=1" % ( str(config["school_id"]), str(picture_id) ) # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) return response.text
def handle_client(host, port, file_type): """ Handles 1 client at a time. TODO: enable multithreading of client requests """ _, client_sock, addr = connect_to_client(host, port) username = receive_label(client_sock) file_name = username + file_type image_size = receive_size(client_sock) if receive_image(client_sock, file_name, image_size): print("[*] Wrote data to {}".format(file_name)) else: print("[*] Error receiving image") client_sock.shutdown(socket.SHUT_WR) client_sock.close() print("\n\n[*************** Authenticating ***************]") if authenticate.is_valid_user(username): if authenticate.authenticate(username, file_name): print("[*] Welcome back {}".format(username)) password = retrieve_credentials(username) if password: send_credentials(client_sock, password) print("{}[+] Sent credentials!\n".format(INDENT)) else: print("[!] Could not retrieve password\n") else: print("[!] Not success\n") client_sock.shutdown(socket.SHUT_WR) client_sock.close()
def __init__(self, auth, hostname, port=4712, https=True): self.auth = auth self.hostname = hostname self.port = port self.https = https self.reference = authenticate(hostname=self.hostname, port=self.port, https=self.https)
def login(): if request.method == "GET": return render_template("login.html") else: user = request.form['user'] password = request.form['pass'] if authenticate(user, password): return redirect(url_for('secret'))
def login(): if request.method == "GET": return render_template("login.html") else: user = request.form['user'] password = request.form['pass'] if authenticate(user, password): return redirect(url_for('secret'))
def get_all_ips( resource_group_name,vm_ss_name ): ips_list = [] credentials_dict = authenticate( client_id, key, tenant_id ) network_client = NetworkManagementClient( credentials_dict['credentials'], credentials_dict['subscription_id'] ) vm_nic_configs = network_client.network_interfaces.list_virtual_machine_scale_set_network_interfaces( resource_group_name,vm_ss_name ) for paged_nic_config in vm_nic_configs: for curr_private_ip in paged_nic_config.ip_configurations: ips_list.append( str( curr_private_ip.private_ip_address ) ) return ips_list
def login(): if request.method == "GET": return render_template("login.html") else: user = request.form['user'] password = request.form['pass'] favNum = request.form['favNum'] if authenticate(user, password,favNum): return render_template("game.html")
def face_detect(): camera = picamera.PiCamera() camera.resolution = (200, 150) camera.start_preview() start = time.time() detected = False TEMP_PATH = 'tmp.jpg' while True: if os.path.isfile(UNKNOWN_PATH): os.remove(UNKNOWN_PATH) camera.capture(TEMP_PATH) result = auth.authenticate(TEMP_PATH) if result[0] != 1: shutil.copy(TEMP_PATH, UNKNOWN_PATH) if result[0] == 0: print('Welcome %s' % result[1]) detected = True break else: print('Sad: %s' % result[1]) if time.time() - start > 5: print('Your time ran out') break camera.stop_preview() camera.close() if not detected: #login val = login_by_password() if (val == 1): detected = True # do not want to input password elif (val == 0): # you shall not pass gkit.tts_play('너는지나 가지 않아야한다.') return detected detect_person(detected) if detected: play_file('../data/sample_sound.wav') # Play a welcome sound gkit.tts_play('환영') print('Door open') return True # you have tried ur best. good luck on next time gkit.tts_play('다음 번에 최선을 다해 행운을 빕니다.') return False
def field_of_study(config, session=False): url = "https://www.lectio.dk/lectio/%s/studieretningElevValg.aspx?elevid=%s" % ( str(config["school_id"]), str(config["student_id"])) if session == False: session = authenticate.authenticate(config) if session == False: return {"status": "error", "type": "authenticate"} cookies = { "lecmobile": "0", "ASP.NET_SessionId": session["ASP.NET_SessionId"], "LastLoginUserName": session["LastLoginUserName"], "lectiogsc": session["lectiogsc"], "LectioTicket": session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded", "Host": "www.lectio.dk", "Origin": "https://www.lectio.dk", "Cookie": functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id": "s_m_Content_Content_id0_pa"}) is None: return {"status": False, "error": "Data not found"} elements = soup.find("div", attrs={ "id": "s_m_Content_Content_id0_pa" }).findAll("td") information = { "student_type": elements[0].find("span").text, "student_start_term": elements[1].find("span").text, "field_of_study": { "name": unicode(elements[2].find("span").text), "context_card_id": elements[2].find("span")["lectiocontextcard"], "field_of_study_id": elements[2].find("span")["lectiocontextcard"].replace("SR", "") }, "student_id": str(config["student_id"]) } return {"status": "ok", "information": information}
def handle_query(): userName = authenticate.authenticate(request) if userName is None: print 'this request is not authenticated' return build_response_not_authenticated(request) authorized, error = authorize.authorize(request,userName) if not authorized: print 'this action is not authorized for %s' % userName return build_response_not_authorized(request, error) return forward_and_resign(request)
def handle_query(): userName = authenticate.authenticate(request) if userName is None: print 'this request is not authenticated' return build_response_not_authenticated(request) authorized, error = authorize.authorize(request, userName) if not authorized: print 'this action is not authorized for %s' % userName return build_response_not_authorized(request, error) return forward_and_resign(request)
def private_activity ( config, session = False ): if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} url = "https://www.lectio.dk/lectio/%s/privat_aftale.aspx?aftaleid=%s" % ( str(config["school_id"]), str(config["activity_id"]) ) cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id" : "m_Content_island1_pa"}) is None: return { "status" : False, "error" : "Data not found" } studentProg = re.compile(r"\/lectio\/(?P<school_id>.*)\/forside.aspx\?elevid=(?P<student_id>.*)") studentGroups = studentProg.match(soup.find("meta", attrs={"name" : "msapplication-starturl"})["content"]) appointment = { "activity_id" : str(config["activity_id"]), "school_id" : str(config["school_id"]), "title" : unicode(soup.find("input", attrs={"id" : "m_Content_titelTextBox_tb"})["value"].replace("\r\n", "")), "comment" : unicode(soup.find("textarea", attrs={"id" : "m_Content_commentTextBox_tb"}).text.replace("\r\n", "")), "student_id" : studentGroups.group("student_id"), "start" : datetime.strptime("%s %s" % (soup.find("input", attrs={"id" : "m_Content_startdateCtrl__date_tb"})["value"], soup.find("input", attrs={"id" : "m_Content_startdateCtrl_startdateCtrl_time_tb"})["value"]), "%d/%m-%Y %H:%M"), "end" : datetime.strptime("%s %s" % (soup.find("input", attrs={"id" : "m_Content_enddateCtrl__date_tb"})["value"], soup.find("input", attrs={"id" : "m_Content_enddateCtrl_enddateCtrl_time_tb"})["value"]), "%d/%m-%Y %H:%M") } return { "status" : "ok", "appointment" : appointment }
def field_of_study ( config, session = False ): url = "https://www.lectio.dk/lectio/%s/studieretningElevValg.aspx?elevid=%s" % ( str(config["school_id"]), str(config["student_id"]) ) if session == False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id" : "s_m_Content_Content_id0_pa"}) is None: return { "status" : False, "error" : "Data not found" } elements = soup.find("div", attrs={"id" : "s_m_Content_Content_id0_pa"}).findAll("td") information = { "student_type" : elements[0].find("span").text, "student_start_term" : elements[1].find("span").text, "field_of_study" : { "name" : unicode(elements[2].find("span").text), "context_card_id" : elements[2].find("span")["lectiocontextcard"], "field_of_study_id" : elements[2].find("span")["lectiocontextcard"].replace("SR", "") }, "student_id" : str(config["student_id"]) } return { "status" : "ok", "information" : information }
def login(): st.sidebar.header('Login to access the App') yourname = st.sidebar.text_input('name', max_chars=20, key=11) yourpass = st.sidebar.text_input('passcode', max_chars=8, type="password", key=22) #.__hash__() hashed password field to be added auth = authenticate.authenticate( yourname, yourpass ) # authenticate with name,passcode not empty and passcode matching return yourname, yourpass, auth
def field_of_study ( config, session = False ): url = "https://www.lectio.dk/lectio/%s/contextcard/contextcard.aspx?lectiocontextcard=%s" % ( str(config["school_id"]), str(config["context_card_id"]) ) if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("span", attrs={"id" : "ctl00_Content_cctitle"}) is None: return { "status" : False, "error" : "Data not found" } tables = soup.findAll("table") idProg = re.compile(r"\/lectio\/(?P<school_id>.*)\/studieretningSe.aspx\?sid=(?P<field_of_study_id>.*)") idGroups = idProg.match(soup.find(attrs={"id" : "ctl00_Content_linksrep_ctl00_somelink"})["href"]) return { "status" : "ok", "field_of_study" : { "name" : unicode(tables[1].findAll("td")[1].text), "field_of_study_id" : idGroups.group("field_of_study_id") if not idGroups is None else "", "school_id" : str(config["school_id"]), "context_card_id" : str(config["context_card_id"]) } }
def login(): if request.method == "GET": return render_template("login.html") else: username = request.form['Username'] password = request.form['Password'] button = request.form['button'] if button == "Cancel": return render_template("login.html") if authenticate.authenticate(username, password): return render_template("secret.html") else: wrong = 'Hint #1: The Username starts with J and the password starts with P.' return render_template("login.html", wrong=wrong)
def login(): if request.method == "GET": return render_template("login.html") else: username = request.form['Username'] password = request.form['Password'] button = request.form['button'] if button == "Cancel": return render_template("login.html") if authenticate.authenticate(username,password): return render_template("secret.html") else: wrong = 'Hint #1: The Username starts with J and the password starts with P.' return render_template("login.html", wrong=wrong)
def login(): if request.method == 'GET': return render_template ("login.html") else: username = request.form['username'] password = request.form['password'] button = request.form['button'] if button=="cancel": return render_template("login.html") if authenticate.authenticate(username,password): session["authen"] = True return render_template ("secret.html") else: error = "Invalid username or password" return render_template("login.html",err=error)
def load_state(event, context): user = authenticate(event=event) if user is None: return {'statusCode': 401} # Load id's data from graphnotes db db_resp = dynamodb.get_item(TableName='graphnotes', Key={'id': { 'S': user }}) data = '{}' if 'Item' in db_resp: data = db_resp['Item']['data']['S'] return {'statusCode': 200, 'body': data}
def home(): errmess="" if request.method=="GET": return render_template("home.html",l=list) else: button = request.form['b'] uname = request.form['uname'] pword = request.form['pword'] if button=="login": if authenticate.authenticate(uname,pword): return render_template("both.html") else : errmess= "Invalid Username and/or Password. Please try again." return render_template("home.html", errmess=errmess) if button=="cancel": return render_template("home.html")
def OnSubmit(self, event): """This class uses the authenticate method to redirect the user to chatroom if if the username and password entered is correct""" chat_login.UserText = self.txt_Username.GetValue() chat_login.PasswordText = self.txt_Password.GetValue() flag = authenticate.authenticate(chat_login.UserText, chat_login.PasswordText) if flag == 0: self.frame.SetStatusText("Sorry") elif flag == 2: self.frame.SetStatusText("Username not registered") elif flag == 1: self.frame.Close(True) app = wx.App(False) OnlineOfflineScreen(chat_login.UserText, chat_login.PasswordText) OnlineOfflineThread() app.MainLoop()
def OnSubmit(self, event): """This class uses the authenticate method to redirect the user to chatroom if if the username and password entered is correct""" chat_login.UserText = self.txt_Username.GetValue() chat_login.PasswordText = self.txt_Password.GetValue() flag=authenticate.authenticate(chat_login.UserText,chat_login.PasswordText) if flag==0: self.frame.SetStatusText("Sorry") elif flag==2: self.frame.SetStatusText("Username not registered") elif flag==1: self.frame.Close(True) app = wx.App(False) OnlineOfflineScreen(chat_login.UserText, chat_login.PasswordText) OnlineOfflineThread() app.MainLoop()
def run(): key = authenticate() if key == None: exit() os.system('clear') print('[PasswordManager] Login successful') opt = None while opt != 'Q': opt = input(''' 1: Create new entry 2: Show all 3: Retrive a password 4: Delete entry Q: Exit Select an action: ''') print('-' * 68) if opt == '1': username = input('[PasswordManager] Enter the username: '******'[PasswordManager] Enter the password: '******'[PasswordManager] Enter the url: ') insert(username, password, url, key) elif opt == '2': fetch_all(key) elif opt == '3': url = input('[PasswordManager] Enter the url: ') fetch_one(url, key) elif opt == '4': id_ = input( '[PasswordManager] Enter the id of the entry you would like to remove: ' ) delete(id_) else: print('[PasswordManager] Invalid entry') save_and_close() os.system('clear') os.system('cd ~') print('[PasswordManager] Exiting ...')
def folders ( config, session = False ): if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } url = "https://www.lectio.dk/lectio/%s/DokumentOversigt.aspx?elevid=%s" %( str(config["school_id"]), str(config["student_id"]) ) response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id" : "s_m_Content_Content_FolderTreeView"}) is None: return { "status" : False, "error" : "Data not found" } folders = find_folders(soup.find("div", attrs={"id" : "s_m_Content_Content_FolderTreeView"}), False, session, config) return { "status" : "ok", "folders" : folders }
def folders(config, session=False): if session is False: session = authenticate.authenticate(config) if session == False: return {"status": "error", "type": "authenticate"} cookies = { "lecmobile": "0", "ASP.NET_SessionId": session["ASP.NET_SessionId"], "LastLoginUserName": session["LastLoginUserName"], "lectiogsc": session["lectiogsc"], "LectioTicket": session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded", "Host": "www.lectio.dk", "Origin": "https://www.lectio.dk", "Cookie": functions.implode(cookies, "{{index}}={{value}}", "; ") } url = "https://www.lectio.dk/lectio/%s/DokumentOversigt.aspx?elevid=%s" % ( str(config["school_id"]), str(config["student_id"])) response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id": "s_m_Content_Content_FolderTreeView" }) is None: return {"status": False, "error": "Data not found"} folders = find_folders( soup.find("div", attrs={"id": "s_m_Content_Content_FolderTreeView"}), False, session, config) return {"status": "ok", "folders": folders}
def save_state(event, context): user = authenticate(event=event) if user is None: return {'statusCode': 401} data = event['body'] # Save [id, data] in graphnotes db dynamodb.put_item(TableName='graphnotes', Item={ 'id': { 'S': "Test" }, 'data': { 'S': data } }) return {'statusCode': 200}
def main(): camera = picamera.PiCamera() camera.resolution = (200, 150) camera.start_preview() start = time.time() door_open = False UNKNOWN_PATH = 'unknown.jpg' TEMP_PATH = 'tmp.jpg' while True: if os.path.isfile(UNKNOWN_PATH): os.remove(UNKNOWN_PATH) camera.capture(TEMP_PATH) result = auth.authenticate(TEMP_PATH) if result[0] == 0: print('Welcome %s' % result[1]) door_open = True break else: print('Sad: %s' % result[1]) if result[0] != 1: shutil.copy(TEMP_PATH, UNKNOWN_PATH) if time.time() - start > 5: print('Your time ran out') break camera.stop_preview() camera.close() if door_open: print('Door open') else: if os.path.isfile(UNKNOWN_PATH): auth.cut_face(UNKNOWN_PATH) return door_open
def login(): #still need to figure out how to return data via session, and return "logged out" message if session['message'] == "You have logged out": print True message = session['message'] session['message'] = '' return render_template("login.html", message = message) + homeBut if (request.method == "GET"): #default return render_template("login.html") + homeBut else: username = request.form["username"] password = request.form["password"] button = request.form["button"] if button == "cancel": return render_template("login.html") + homeBut if authenticate(username, password): return render_template("account.html", username = username) + logoutBut else: error = "Wrong username or password, BIDEN UP!" return render_template("login.html", err=error) + homeBut
def login(): #still need to figure out how to return data via session, and return "logged out" message if session['message'] == "You have logged out": print True message = session['message'] session['message'] = '' return render_template("login.html", message=message) + homeBut if (request.method == "GET"): #default return render_template("login.html") + homeBut else: username = request.form["username"] password = request.form["password"] button = request.form["button"] if button == "cancel": return render_template("login.html") + homeBut if authenticate(username, password): return render_template("account.html", username=username) + logoutBut else: error = "Wrong username or password, BIDEN UP!" return render_template("login.html", err=error) + homeBut
def payment(): print('payment request') try: print('trying authentication') json_ = request.json # print(str(json_)) a = authenticate.authenticate('config/config.csv') response,token = a.get_token() returnResponse = jsonify({}) print(response.status_code) print(token) if response.status_code == 200: print(token) p = payments_api.payments_api(token,'POST') payload = p.sample_post # print(str(payload)) payload['debtorAccountId']['name'] = json_['accountB'] payload['creditor']['name'] = json_['accountA'] payload['paymentIdentification']['EndToEndId'] = json_['accountA'].strip(u'\u200b') + json_['accountB'].strip(u'\u200b') payload['instructedAmount']['amount'] = json_['amount'] print(payload) response = p.connect_endpoint(payload) print(response.text) returnResponse = jsonify(response.text) else: print('Failed login') returnReponse = jsonify(response.text) return returnResponse except: return '{"statusCode" : "500", "message": "Authentication Failed!" }'
def description ( config, session = False ): url = "https://www.lectio.dk/lectio/%s/studieplan/hold_undervisningsbeskrivelse.aspx?holdelementid=%s" % ( str(config["school_id"]), str(config["team_element_id"]) ) if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id" : "s_m_Content_Content_holduvb_UvbHoldRepeater_ctl00_uvbCtrl_uvbcontainer"}) is None: return { "status" : False, "error" : "Data not found" } tables = soup.find("div", attrs={"id" : "s_m_Content_Content_holduvb_UvbHoldRepeater_ctl00_uvbCtrl_uvbcontainer"}).findAll("table", attrs={"class" : "list"}) informationElements = tables[0].findAll("td") subjectProg = re.compile(r"(?P<subject>.*) (?P<level>.*)$") teachers = [] teamProg = re.compile(r"(?P<team>.*) \((?P<teams>.*)\)") teamGroups = teamProg.match(informationElements[9].text.replace("\n", "")) teams = [] if not teamGroups is None: teams = teamGroups.group("teams").replace("\n", "").split(", ") for row in informationElements[7].findAll("span"): teachers.append(unicode(row.text)) subjectGroups = subjectProg.match(informationElements[5].text.replace("\n", "")) terms = [] termProg = re.compile(r"(?P<value>.*)\/(?P<end>.*)") for x in informationElements[1].text.replace("\n", "").split(" - "): termGroups = termProg.match(x) terms.append({ "value" : termGroups.group("value") if not termGroups is None else "", "years_string" : x }) information = { "teachers" : teachers, "terms" : terms, "teams" : teams, "team_name" : teamGroups.group("team") if not teamGroups is None else "", "subject" : { "name" : subjectGroups.group("subject").encode("utf8") if not subjectGroups is None else informationElements[5].text.encode("utf8"), "level" : subjectGroups.group("level") if not subjectGroups is None else "" }, "institution" : informationElements[3].text.replace("\n", "").encode("utf8"), } tables.pop(0) tables.pop(0) phases = [] phaseIdProg = re.compile(r"\/lectio\/(?P<school_id>.*)\/studieplan\/forloeb_vis.aspx\?phaseid=(?P<phase_id>.*)&prevurl=(?P<prev_url>.*)") coversProg = re.compile(ur"Anvendt modullængden (?P<length>.*) (?P<type>.*)\. fra skoleåret (?P<term>.*)") for table in tables: if not table is None: rows = table.findAll("tr", recursive=False) elements = [] for row in rows: elements = elements + row.findAll("td", recursive=False) if not elements[1].find("a") is None: phaseIdGroups = phaseIdProg.match(elements[1].find("a")["href"]) reachSpans = elements[5].findAll("span") title = reachSpans[2]["title"] if "title" in reachSpans[2] else reachSpans[2].text coversGroups = coversProg.match(title) focusPoints = [] focusRows = [] if not elements[7].find("ul") is None: focusRows = elements[7].find("ul").findAll("li", recursive=False) descriptionText = elements[1].find("span").text if len(focusRows) > 0: for row in focusRows: header = unicode(row.text) focusPointElements = [] if row.find_next().name == "ul": for focusElement in row.find_next().findAll("li"): focusPointElements.append(unicode(focusElement.text)) focusPoints.append({ "header" : header, "elements" : focusPointElements }) work_methods = [] for row in elements[9].findAll("li"): work_methods.append(unicode(row.text.replace("\t", "").replace("\n", "").replace("\r", ""))) readings = [] if not elements[3].find("span").find("i") is None: elements[3].find("span").find("i").decompose() for row in elements[3].find("span").findAll("br"): text = unicode(row.find_next(text=True).string).encode("utf8") readings.append({"text" : text}) elements[3].find("span").decompose() links = [] for link in elements[3].findAll("a"): links.append({ "href" : link["href"], "text" : unicode(link.find_next(text=True).find_next(text=True)[3:].replace("\t", "").replace("\r\n", "")) }) link.find_next(text=True).find_next(text=True).extract() link.decompose() written = [] if not elements[3].find("table") is None: writtenRows = elements[3].findAll("tr") writtenRows.pop(0) for row in writtenRows: writtenRowElements = row.findAll("td") written.append({ "title" : writtenRowElements[0].text.replace("\r\n", "").replace("\t", ""), "date" : datetime.strptime(writtenRowElements[1].text.replace("\r\n", "").replace("\t", "").strip(), "%d-%m-%Y") }) elements[3].find("table").decompose() for x in elements[3].findAll("i"): x.decompose() documents = [] for row in elements[3].findAll(text=True): if len(row) > 1: documents.append({ "name" : row.strip().replace("\r\n", "").replace("\t", "") }) phases.append({ "reach" : { "covers" : { "length" : "unknown" if reachSpans[1].text == "Ikke angivet" else reachSpans[1].text.replace(" moduler", ""), "type" : "modules" }, "details" : { "length" : coversGroups.group("length") if not coversGroups is None else "45", "type" : coversGroups.group("type") if not coversGroups is None else "min", "term" : "20" + coversGroups.group("term") if not coversGroups is None else soup.find("select", attrs={"id" : "s_m_ChooseTerm_term"}).select('option[selected="selected"]')[0].text } }, "estimate" : { "type" : "modules", "length" : "unknown" if reachSpans[0].text == "Ikke angivet" else reachSpans[0].text.replace(",", ".").replace(" moduler", "").strip(), }, "methods" : work_methods, "name" : elements[1].find("a").text.encode("utf8"), "phase_id" : phaseIdGroups.group("phase_id") if not phaseIdGroups is None else "", "focus_points" : focusPoints, "readings" : readings, "links" : links, "documents" : documents, "written" : written, "description" : descriptionText, "title" : elements[1].find("a").text.encode("utf8") }) return { "status" : "ok", "information" : information, "phases" : phases, "term" : { "value" : soup.find("select", attrs={"id" : "s_m_ChooseTerm_term"}).select('option[selected="selected"]')[0]["value"], "years_string" : soup.find("select", attrs={"id" : "s_m_ChooseTerm_term"}).select('option[selected="selected"]')[0].text } }
def document(config, session=False): url = "https://www.lectio.dk/lectio/%s/dokumentrediger.aspx?dokumentid=%s" % ( str(config["school_id"]), str(config["document_id"])) if session is False: session = authenticate.authenticate(config) if session == False: return {"status": "error", "type": "authenticate"} cookies = { "lecmobile": "0", "ASP.NET_SessionId": session["ASP.NET_SessionId"], "LastLoginUserName": session["LastLoginUserName"], "lectiogsc": session["lectiogsc"], "LectioTicket": session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded", "Host": "www.lectio.dk", "Origin": "https://www.lectio.dk", "Cookie": functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id": "m_Content_Dokument_pa"}) is None: return {"status": False, "error": "Data not found"} offset = 0 elements = soup.find("div", attrs={ "id": "m_Content_Dokument_pa" }).findAll("td") if len(elements) < 7: offset = 1 creator = context_card.user( { "context_card_id": elements[3 - offset].find("span")["lectiocontextcard"], "school_id": config["school_id"] }, session)["user"] changer = elements[4 - offset].find("span")["lectiocontextcard"] elements[4 - offset].find("span").decompose() dateText = elements[4 - offset].text.replace(" af ", "").strip() dateTimeProg = re.compile( r"(?P<day>.*)/(?P<month>.*)-(?P<year>.*) (?P<hour>.*):(?P<minute>.*)") dateGroups = dateTimeProg.match(dateText) date = datetime.strptime( "%s/%s-%s %s:%s" % (functions.zeroPadding(dateGroups.group("day")), functions.zeroPadding(dateGroups.group("month")), dateGroups.group("year"), dateGroups.group("hour"), dateGroups.group("minute")), "%d/%m-%Y %H:%M") if not dateGroups is None else "" connectionRows = soup.find("table", attrs={ "id": "m_Content_AffiliationsGV" }).findAll("tr") connectionRows.pop(0) connections = [] for row in connectionRows: rowElements = row.findAll("td") data = { "context_card_id": rowElements[0]["lectiocontextcard"], "type": "team" if "H" in rowElements[0]["lectiocontextcard"] else "teacher" if "T" in rowElements[0]["lectiocontextcard"] else "student", "name": unicode(rowElements[0].find("span").text), "can_edit": True if "checked" in rowElements[1].find("input").attrs else False } if rowElements[2].find("select"): folder_id = rowElements[2].find("select").select( 'option[selected="selected"]')[0]["value"] data["folder_id"] = folder_id connections.append(data) document = { "name": unicode(elements[0].find("a").text).replace("\t", "").replace( "\n", "").replace("\r", "").strip(), "extension": os.path.splitext(elements[0].find("a").text.replace("\t", "").replace( "\n", "").replace("\r", "").strip())[1].replace(".", ""), "size": elements[2 - offset].text.replace(",", ".").replace("\t", "").replace( "\n", "").replace("\r", "").strip(), "document_id": str(config["document_id"]), "creator": creator, "changer": { "context_card_id": changer, "type": "teacher" if "T" in changer else "student", "date": date }, "comment": soup.find("textarea", attrs={ "id": "m_Content_EditDocComments_tb" }).text.replace("\r\n", ""), "public": True if "checked" in soup.find("input", attrs={ "id": "m_Content_EditDocIsPublic" }).attrs else False, "connections": connections, "term": { "value": soup.find("select", attrs={ "id": "m_ChooseTerm_term" }).select('option[selected="selected"]')[0]["value"], "years_string": soup.find("select", attrs={ "id": "m_ChooseTerm_term" }).select('option[selected="selected"]')[0].text } } return {"status": "ok", "document": document}
import praw import prawcore import os import json from time import time from pprint import pprint from authenticate import authenticate reddit = authenticate() #Put your reddit API authentification info here. def getRules(path): with open(path) as f: subreddits = f.readlines() subreddits = [subreddit.strip() for subreddit in subreddits] rulesDict = {} for subreddit in subreddits: rulesDict[subreddit] = [] try: subredditRules = reddit.subreddit(subreddit).rules()['rules'] except Exception as e: print(e) print(subreddit) print() continue for subredditRule in subredditRules: rulesDict[subreddit].append({subredditRule['short_name'] : subredditRule['description'].strip()}) return rulesDict
def activity_info(config, activity_id, session = False, modules = None ): if not session == False: if session is True: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} url = urls.activity_info.replace("{{SCHOOL_ID}}", str(config["school_id"])).replace("{{ACTIVITY_ID}}", str(activity_id)) if not session == False: # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } else: cookies = {} settings = {} # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.post(url, data=settings, headers=headers) html = response.text soup = Soup(html) # Find all the different rows in the table rows = [] for x in soup.find("div", attrs={"id" : "m_Content_LectioDetailIslandLesson_pa"}).find("table").findAll("tr", recursive=False): rows.append(x.find("td")) headers = soup.find("div", attrs={"id" : "m_Content_LectioDetailIslandLesson_pa"}).find("table").findAll("th") headers[3].string.replace_with("EleverAs") # Make rows[n] match headers[n] for index, element in enumerate(rows): table = element.find_parent("table") if table["class"][0] == u"NoFrame": del rows[index] # Generate a map of rows rowMap = functions.mapRows(headers, rows) # Retrieve the values showed_in_values = unicode(rowMap["Vises"].text).split(", ") showed_in = [] type = unicode(rowMap["Type"].text) status = unicode(rowMap["Status"].text) students_resserved = unicode(rowMap["Deltagerereserveret"].text) teams = [] # Done students = [] # Done ressources = [] # Test Missing rooms = [] # Done teachers = [] # Done documents = [] # Done links = [] # Done students_education_assigned = [] # Missing Test homework = [] ressourceProg = re.compile(r"\/lectio\/(?P<school_id>.*)\/SkemaNy.aspx\?type=lokale&nosubnav=1&id=(?P<ressource_id>.*)&week=(?P<week>.*)") for x in rowMap["Ressourcer"].findAll("a"): ressoureceGroups = ressourceProg.match(x["href"]) ressources.append({ "ressource_id" : ressoureceGroups.group("ressource_id") if not ressoureceGroups is None else "" }) for x in rowMap["EleverAs"].findAll("a"): students_education_assigned.append({ "student_id" : x["lectiocontextcard"].replace("S", "") }) dateProg = re.compile(r"(?P<day_name>.*) (?P<day>.*)\/(?P<month>.*) (?P<module>.*)\. modul, uge (?P<week>.*)") termValue = soup.find("select", attrs={"id" : "m_ChooseTerm_term"}).select('option[selected="selected"]')[0]["value"] alternativeDateProg = re.compile(r"(?P<day_name>.*) (?P<day>.*)\/(?P<month>.*) (?P<start_time>.*) - (?P<end_time>.*), uge (?P<week>.*)") multiDayProg = re.compile(r"(?P<start_day_name>.*) (?P<start_day>.*)\/(?P<start_month>.*) (?P<start_time>.*) - (?P<end_day_name>.*) (?P<end_day>.*)\/(?P<end_month>.*) (?P<end_time>.*), uge (?P<week>.*)") altDateGroups = alternativeDateProg.match(rowMap["Tidspunkt"].text.strip().replace("\r", "").replace("\n", "").replace("\t", "")) dateGroups = dateProg.match(rowMap["Tidspunkt"].text.strip().replace("\r", "").replace("\n", "").replace("\t", "")) multiDayGroups = multiDayProg.match(rowMap["Tidspunkt"].text.strip().replace("\r", "").replace("\n", "").replace("\t", "")) startDate = None endDate = None if not dateGroups is None and not modules == None: if int(dateGroups.group("month")) < 8: year = int(termValue) + 1 else: year = int(termValue) startTime = "12:00" endTime = "00:00" for x in modules: if str(x["module"]) == str(dateGroups.group("module")): startTime = x["start"] endTime = x["end"] startDate = datetime.strptime("%s/%s-%s %s" % (functions.zeroPadding(dateGroups.group("day")), functions.zeroPadding(dateGroups.group("month")), year, startTime), "%d/%m-%Y %H:%M") endDate = datetime.strptime("%s/%s-%s %s" % (functions.zeroPadding(dateGroups.group("day")), functions.zeroPadding(dateGroups.group("month")), year, endTime), "%d/%m-%Y %H:%M") elif not multiDayGroups is None: if int(multiDayGroups.group("month")) < 8: year = int(termValue) + 1 else: year = int(termValue) startDate = datetime.strptime("%s/%s-%s %s" % (functions.zeroPadding(multiDayGroups.group("day")), functions.zeroPadding(multiDayGroups.group("month")), year, multiDayGroups.group("start_time")), "%d/%m-%Y %H:%M") endDate = datetime.strptime("%s/%s-%s %s" % (functions.zeroPadding(multiDayGroups.group("day")), functions.zeroPadding(multiDayGroups.group("month")), year, multiDayGroups.group("end_time")), "%d/%m-%Y %H:%M") elif not altDateGroups is None: if int(altDateGroups.group("month")) < 8: year = int(termValue) + 1 else: year = int(termValue) startDate = datetime.strptime("%s/%s-%s %s" % (functions.zeroPadding(altDateGroups.group("day")), functions.zeroPadding(altDateGroups.group("month")), year, altDateGroups.group("start_time")), "%d/%m-%Y %H:%M") endDate = datetime.strptime("%s/%s-%s %s" % (functions.zeroPadding(altDateGroups.group("day")), functions.zeroPadding(altDateGroups.group("month")), year, altDateGroups.group("end_time")), "%d/%m-%Y %H:%M") # Created and updated dates metaProg = re.compile(values.activity_updated_regex) metaElements = rowMap["Systeminformation"].text.strip().split("\n") metaString = "" for me in metaElements: metaString = metaString + " " + me.replace("\t\t\t\t", "").replace("\r", "").strip() metaGroups = metaProg.search(metaString) # Loop through the documents and append to the list documentTable = rowMap["Dokumenter"].find("table") if not documentTable == None: documentRows = documentTable.findAll("td") for documentRow in documentRows: # Split the size from the unit fileSizeProg = re.compile(values.file_size_regex) fileSizeGroups = fileSizeProg.search(documentRow.text) # Find the different document info elements elements = documentRow.findAll("a") if len(elements) > 0: # Filter the id from the document url documentProg = re.compile(values.document_url_regex) documentGroups = documentProg.search(elements[1]["href"]) # Append to the list documents.append({ "name" : elements[1].text.encode("utf8"), "size" : { "size" : fileSizeGroups.group("size").replace(",", "."), "unit" : fileSizeGroups.group("unit_name") }, "type" : "timetable_document", "document_id" : documentGroups.group("document_id") }) # Loop through the students and append to the list studentRows = rowMap["Elever"].findAll("a") for student,classObject in functions.grouped(studentRows,2): # Filter the id from the class URL studentClassProg = re.compile(values.class_url_regex) studentClassGroups = studentClassProg.search(classObject["href"]) # Filter the student id from the URL studentIdProg = re.compile(values.student_url_regex) studentIdGroups = studentIdProg.search(student["href"]) students.append({ "name" : unicode(student.text), "class" : unicode(classObject.text), "context_card_id" : student["lectiocontextcard"], "student_id" : studentIdGroups.group("student_id"), "class_id" : studentClassGroups.group("class_id") }) # Loop through the teams and append to the list for team in rowMap["Hold"].findAll("a"): # Filter the class name from the team name teamNameProg = re.compile(values.team_class_name_regex) teamNameGroups = teamNameProg.search(unicode(team.text)) # Filter the id from the URL teamIdProg = re.compile(values.team_url_regex) teamIdGroups = teamIdProg.search(team["href"]) if not teamIdGroups == None: # Append to the list teams.append({ "class" : teamNameGroups.group("class_name"), "team" : teamNameGroups.group("team_name"), "name" : team.text, "team_id" : teamIdGroups.group("team_id") }) # Loop through the values and append English and Computer easy readable values for value in showed_in_values: if value == u"i dags- og ugeændringer": showed_in.append("day_and_week_changes") elif value == u"Inde i berørte skemaer": showed_in.append("timetable") elif value == u"I toppen af berørte skemaer": showed_in.append("top_of_timetable") # Loop through the links and append them to the list for link in rowMap["Links"].findAll("a"): links.append({ "url" : link["href"], "title" : unicode(link.text) }) # Loop through the rooms and append them to the list for room in rowMap["Lokaler"].findAll("a"): # Initialize variables roomName = "" roomNumber = "" # Filter the number from the name roomNameProg = re.compile(values.room_name_regex) roomNameGroups = roomNameProg.search(unicode(room.text)) if not roomNameGroups == None: roomName = roomNameGroups.group("room_name") roomNumber = roomNameGroups.group("room_number") # Initialize roomId RegEx roomIdProg = re.compile(values.room_url_regex) # Filter the id from the URL roomIdGroups = roomIdProg.search(room["href"]) # Append the room to the list rooms.append({ "name" : roomName, "number" : roomNumber, "room_id" : roomIdGroups.group("room_id") }) # Loop through the teachers and append them to the list for teacher in rowMap["Laerere"].findAll("a"): # Filter the abbrevation from the name teacherNameProg = re.compile(values.name_with_abbrevation_regex) teacherNameGroups = teacherNameProg.search(unicode(teacher.text)) # Filter the id from the URL teacherIdProg = re.compile(values.teacher_url_regex) teacherIdGroups = teacherIdProg.search(teacher["href"]) # Append to the list teachers.append({ "context_card_id" : teacher["lectiocontextcard"], "name" : teacherNameGroups.group("name"), "abbrevation" : teacherNameGroups.group("abbrevation"), "teacher_id" : teacherIdGroups.group("teacher_id"), "school_id" : teacherIdGroups.group("school_id") }) # Loop over the diferent homework notes and append to the list for object in values.activity_homework_regexs: prog = re.compile(object["expression"]) matches = prog.finditer(unicode(rowMap["Lektier"].text.replace("\t", ""))) # Loop over the matches for element in matches: if object["name"] == "note": if not element.group("note") == "": homework.append({ "note" : element.group("note"), "type" : "note" }) else: homework.append({ "note" : element.group("note"), "class" : element.group("class"), "authors" : element.group("writers").split(", "), "name" : element.group("name"), "pages" : element.group("pages"), "subject" : element.group("subject"), "publisher" : element.group("publisher"), "type" : "book" }) # Initialize note variable note = unicode(rowMap["Note"].text) # Return all the information return { "status" : "ok", "time" : unicode(rowMap["Tidspunkt"].text), "teams" : teams, "type" : "school" if type == "Lektion" else "other_activity" if type == "Anden aktivitet" else "other", "students_education_assigned" : students_education_assigned, "teachers" : teachers, "rooms" : rooms, "ressources" : ressources, "note" : note.encode("utf8"), "documents" : documents, "homework" : homework, # Match books with the list of books "links" : links, "students_resserved" : "true" if students_resserved.strip() == "Ja" else "false", "showed_at" : showed_in, "activity_status" : "done" if status == "Afholdt" else "planned" if status == "Planlagt" else "cancelled" if status == "Aflyst" else "other", "students" : students, "created" : { "at" : datetime.strptime("%s/%s-%s %s:%s" % (functions.zeroPadding(metaGroups.group("created_date")),functions.zeroPadding(metaGroups.group("created_month")),functions.zeroPadding(metaGroups.group("created_year")),functions.zeroPadding(metaGroups.group("created_hour")),functions.zeroPadding(metaGroups.group("created_minute"))), "%d/%m-%Y %H:%M") if not metaGroups is None else "", "by" : metaGroups.group("created_teacher") if not metaGroups is None else "" }, "updated" : { "at" : datetime.strptime("%s/%s-%s %s:%s" % (functions.zeroPadding(metaGroups.group("updated_date")),functions.zeroPadding(metaGroups.group("updated_month")),functions.zeroPadding(metaGroups.group("updated_year")),functions.zeroPadding(metaGroups.group("updated_hour")),functions.zeroPadding(metaGroups.group("updated_minute"))), "%d/%m-%Y %H:%M") if not metaGroups is None else "", "by" : metaGroups.group("updated_teacher") if not metaGroups is None else "" }, "term" : { "value" : soup.find("select", attrs={"id" : "m_ChooseTerm_term"}).select('option[selected="selected"]')[0]["value"], "years_string" : soup.find("select", attrs={"id" : "m_ChooseTerm_term"}).select('option[selected="selected"]')[0].text }, "date" : { "start" : startDate, "end" : endDate } }
def leave ( config, session = False ): url = "https://www.lectio.dk/lectio/%s/subnav/fravaerelev.aspx?elevid=%s" % ( str(config["school_id"]), str(config["student_id"]) ) if session is False: session = authenticate.authenticate(config) # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("table", attrs={"id" : "s_m_Content_Content_SFTabStudentAbsenceDataTable"}) is None: return { "status" : False, "error" : "Data not found" } rows = soup.find("table", attrs={"id" : "s_m_Content_Content_SFTabStudentAbsenceDataTable"}).findAll("tr") rows.pop(0) rows.pop(0) rows.pop(0) rows.pop(0) rows.pop(len(rows)-1) leaveRows = [] teamIdProg = re.compile(r"\/lectio\/(?P<school_id>.*)\/fravaer_elevhold.aspx\?holdelementid=(?P<team_element_id>.*)") leaveProg = re.compile(r"(?P<number>.*)\/(?P<modules>.*)") for row in rows: elements = row.findAll("td") teamIdGroups = teamIdProg.match(elements[0].find("a")["href"]) periodeGroups = leaveProg.match(elements[2].text.replace(",", ".")) calculatedGroups = leaveProg.match(elements[4].text.replace(",", ".")) yearGroups = leaveProg.match(elements[6].text.replace(",", ".")) writtenPeriodeGroups = leaveProg.match(elements[8].text.replace(",", ".")) writtenCalculatedGroups = leaveProg.match(elements[10].text.replace(",", ".")) writtenYearGroups = leaveProg.match(elements[12].text.replace(",", ".")) data = { "team" : { "name": unicode(elements[0].find("a").text), "team_id" : teamIdGroups.group("team_element_id") if not teamIdGroups is None else "" }, "leave" : { "period" : { "end_date" : datetime.strptime(soup.find("input", attrs={"id" : "s_m_Content_Content_SFTabPeriodChooserCtrl_end__date_tb"})["value"], "%d/%m-%Y"), "start_date" : datetime.strptime(soup.find("input", attrs={"id" : "s_m_Content_Content_SFTabPeriodChooserCtrl_start__date_tb"})["value"], "%d/%m-%Y"), "percent" : elements[1].text.replace(",", ".").replace("%", ""), "modules" : periodeGroups.group("modules") if not periodeGroups is None else "", "leave" : periodeGroups.group("number") if not periodeGroups is None else "" }, "calculated" : { "percent" : elements[3].text.replace(",", ".").replace("%", ""), "modules" : calculatedGroups.group("modules") if not calculatedGroups is None else "", "leave" : calculatedGroups.group("number") if not calculatedGroups is None else "" }, "year" : { "percent" : elements[5].text.replace(",", ".").replace("%", ""), "modules" : yearGroups.group("modules") if not yearGroups is None else "", "leave" : yearGroups.group("number") if not yearGroups is None else "" } }, "written" : { "period" : { "end_date" : datetime.strptime(soup.find("input", attrs={"id" : "s_m_Content_Content_SFTabPeriodChooserCtrl_end__date_tb"})["value"], "%d/%m-%Y"), "start_date" : datetime.strptime(soup.find("input", attrs={"id" : "s_m_Content_Content_SFTabPeriodChooserCtrl_start__date_tb"})["value"], "%d/%m-%Y"), "percent" : elements[7].text.replace(",", ".").replace("%", ""), "hours" : writtenPeriodeGroups.group("modules") if not writtenPeriodeGroups is None else "", "leave" : writtenPeriodeGroups.group("number") if not writtenPeriodeGroups is None else "" }, "calculated" : { "percent" : elements[9].text.replace(",", ".").replace("%", ""), "hours" : writtenCalculatedGroups.group("modules") if not writtenCalculatedGroups is None else "", "leave" : writtenCalculatedGroups.group("number") if not writtenCalculatedGroups is None else "" }, "year" : { "percent" : elements[11].text.replace(",", ".").replace("%", ""), "hours" : writtenYearGroups.group("modules") if not writtenYearGroups is None else "", "leave" : writtenYearGroups.group("number") if not writtenYearGroups is None else "" } } } leaveRows.append(data) return { "status" : "ok", "leave" : leaveRows, "term" : { "value" : soup.find("select", attrs={"id" : "s_m_ChooseTerm_term"}).select('option[selected="selected"]')[0]["value"], "years_string" : soup.find("select", attrs={"id" : "s_m_ChooseTerm_term"}).select('option[selected="selected"]')[0].text, "start_date" : datetime.strptime(soup.find("input", attrs={"id" : "s_m_Content_Content_SFTabPeriodChooserCtrl_start__date_tb"})["value"], "%d/%m-%Y") }, }
def document ( config, session = False ): url = "https://www.lectio.dk/lectio/%s/dokumentrediger.aspx?dokumentid=%s" % ( str(config["school_id"]), str(config["document_id"]) ) if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id" : "m_Content_Dokument_pa"}) is None: return { "status" : False, "error" : "Data not found" } offset = 0 elements = soup.find("div", attrs={"id" : "m_Content_Dokument_pa"}).findAll("td") if len(elements) < 7: offset = 1 creator = context_card.user({ "context_card_id" : elements[3-offset].find("span")["lectiocontextcard"], "school_id" : config["school_id"] }, session)["user"] changer = elements[4-offset].find("span")["lectiocontextcard"] elements[4-offset].find("span").decompose() dateText = elements[4-offset].text.replace(" af ", "").strip() dateTimeProg = re.compile(r"(?P<day>.*)/(?P<month>.*)-(?P<year>.*) (?P<hour>.*):(?P<minute>.*)") dateGroups = dateTimeProg.match(dateText) date = datetime.strptime("%s/%s-%s %s:%s" % (functions.zeroPadding(dateGroups.group("day")), functions.zeroPadding(dateGroups.group("month")), dateGroups.group("year"), dateGroups.group("hour"), dateGroups.group("minute")), "%d/%m-%Y %H:%M") if not dateGroups is None else "" connectionRows = soup.find("table", attrs={"id" : "m_Content_AffiliationsGV"}).findAll("tr") connectionRows.pop(0) connections = [] for row in connectionRows: rowElements = row.findAll("td") data = { "context_card_id" : rowElements[0]["lectiocontextcard"], "type" : "team" if "H" in rowElements[0]["lectiocontextcard"] else "teacher" if "T" in rowElements[0]["lectiocontextcard"] else "student", "name" : unicode(rowElements[0].find("span").text), "can_edit" : True if "checked" in rowElements[1].find("input").attrs else False } if rowElements[2].find("select"): folder_id = rowElements[2].find("select").select('option[selected="selected"]')[0]["value"] data["folder_id"] = folder_id connections.append(data) document = { "name" : unicode(elements[0].find("a").text).replace("\t", "").replace("\n", "").replace("\r", "").strip(), "extension" : os.path.splitext(elements[0].find("a").text.replace("\t", "").replace("\n", "").replace("\r", "").strip())[1].replace(".", ""), "size" : elements[2-offset].text.replace(",", ".").replace("\t", "").replace("\n", "").replace("\r", "").strip(), "document_id" : str(config["document_id"]), "creator" : creator, "changer" : { "context_card_id" : changer, "type" : "teacher" if "T" in changer else "student", "date" : date }, "comment" : soup.find("textarea", attrs={"id" : "m_Content_EditDocComments_tb"}).text.replace("\r\n",""), "public" : True if "checked" in soup.find("input", attrs={"id" : "m_Content_EditDocIsPublic"}).attrs else False, "connections" : connections, "term" : { "value" : soup.find("select", attrs={"id" : "m_ChooseTerm_term"}).select('option[selected="selected"]')[0]["value"], "years_string" : soup.find("select", attrs={"id" : "m_ChooseTerm_term"}).select('option[selected="selected"]')[0].text } } return { "status" : "ok", "document" : document }
def setUp(self): self.gmail_service = authenticate() self.emailer = Emailer() self.match_xls = '/Users/jjw036/Dropbox/GSA/LinkLunch/matches_04212015.xlsx' self.address_xls = '/Users/jjw036/Dropbox/GSA/LinkLunch/individual_info.xlsx'
def isAuthenticated(username,pw): try: s = authenticate('https://enr-apps.as.cmu.edu/audit/audit',username,pw) return True; except KeyError: return False;
def documents(config, session=False): if session is False: session = authenticate.authenticate(config) if session == False: return {"status": "error", "type": "authenticate"} cookies = { "lecmobile": "0", "ASP.NET_SessionId": session["ASP.NET_SessionId"], "LastLoginUserName": session["LastLoginUserName"], "lectiogsc": session["lectiogsc"], "LectioTicket": session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded", "Host": "www.lectio.dk", "Origin": "https://www.lectio.dk", "Cookie": functions.implode(cookies, "{{index}}={{value}}", "; ") } url = "https://www.lectio.dk/lectio/%s/DokumentOversigt.aspx?elevid=%s&folderid=%s" % ( str(config["school_id"]), str( config["student_id"]), str(config["folder_id"])) response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("table", attrs={"id": "s_m_Content_Content_DocumentGridView_ctl00" }) is None: return {"status": False, "error": "Data not found"} rows = soup.find("table", attrs={ "id": "s_m_Content_Content_DocumentGridView_ctl00" }).findAll("tr") rows.pop(0) shortDayTimeProg = re.compile( r"(?P<day_name>.*) (?P<hour>.*):(?P<minute>.*)") timeProg = re.compile( r"(?P<hour>.*):(?P<minute>.*)") # Current day, month, year dayProg = re.compile( r"(?P<day_name>.*) (?P<day>.*)/(?P<month>.*)") # Current year dateProg = re.compile(r"(?P<day>.*)/(?P<month>.*)-(?P<year>.*)") dayConversion = { u"Ma": "Mon", u"Ti": "Tue", u"On": "Wed", u"To": "Thu", u"Fr": "Fri", u"Lø": "Sat", u"Sø": "Son" } documents = [] documentIdProg = re.compile( r"\/lectio\/(?P<school_id>.*)\/dokumenthent.aspx\?documentid=(?P<document_id>.*)" ) for row in rows: elements = row.findAll("td") idGroups = documentIdProg.match(elements[1].find("a")["href"]) changer = context_card.user( { "context_card_id": elements[3]["lectiocontextcard"], "school_id": config["school_id"] }, session) if shortDayTimeProg.match(elements[4].text): timeGroups = shortDayTimeProg.match(elements[4].text) date = datetime.strptime( "%s/%s-%s %s:%s" % (dayConversion[unicode( timeGroups.group("day_name").capitalize())], today.strftime("%W"), today.strftime("%Y"), timeGroups.group("hour"), timeGroups.group("minute")), "%a/%W-%Y %H:%M") elif timeProg.match(elements[4].text): timeGroups = timeProg.match(elements[4].text) date = datetime.strptime( "%s/%s-%s %s:%s" % (today.strftime("%d"), today.strftime("%m"), today.strftime("%Y"), timeGroups.group("hour"), timeGroups.group("minute")), "%d/%m-%Y %H:%M") elif dayProg.match(elements[4].text): dayGroups = dayProg.match(elements[4].text) date = datetime.strptime( "%s/%s-%s %s:%s" % (dayGroups.group("day"), dayGroups.group("month"), today.strftime("%Y"), "12", "00"), "%d/%m-%Y %H:%M") elif dateProg.match(elements[4].text): dateGroups = dateProg.match(elements[4].text) date = datetime.strptime( "%s/%s-%s %s:%s" % (dateGroups.group("day"), dateGroups.group("month"), dateGroups.group("year"), "12", "00"), "%d/%m-%Y %H:%M") data = { "folder_id": str(config["folder_id"]), "name": unicode(elements[1].find("span")["title"].replace( "Fulde filnavn: ", "")), "extension": os.path.splitext(elements[1].find("span")["title"].replace( "Fulde filnavn: ", ""))[1].replace(".", ""), "comment": unicode(elements[2].find("span").text), "document_id": idGroups.group("document_id") if not idGroups is None else "", "size": elements[5].text.replace(",", "."), "date": date, "user": changer["user"] } documents.append(data) return {"status": "ok", "documents": documents}
def leave_reasons ( config, session = False ): url = "https://www.lectio.dk/lectio/%s/subnav/fravaerelev.aspx?elevid=%s&lectab=aarsager" % ( str(config["school_id"]), str(config["student_id"]) ) if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("table", attrs={"id" : "s_m_Content_Content_FatabAbsenceFravaerGV"}) is None: return { "status" : False, "error" : "Data not found" } missing = [] reasons = [] reasonKeys = { u"Andet" : "other", u"Kom for sent" : "too_late", u"Skolerelaterede aktiviteter" : "school_related", u"Private forhold" : "private", u"Sygdom" : "sick" } # TODO: Add Missing if soup.find(attrs={"id" : "s_m_Content_Content_FatabMissingAarsagerGV"}).find(attrs={"class" : "noRecord"}) is None: print "missing" if soup.find(attrs={"id" : "s_m_Content_Content_FatabAbsenceFravaerGV"}).find(attrs={"class" : "noRecord"}) is None: rows = soup.find(attrs={"id" : "s_m_Content_Content_FatabAbsenceFravaerGV"}).findAll("tr") rows.pop(0) activityProg = re.compile(r"\/lectio\/(?P<school_id>.*)\/aktivitet\/aktivitetinfo.aspx\?id=(?P<activity_id>.*)&prevurl=(?P<prev_url>.*)") datetimeProg = re.compile(r"(?P<day>.*)\/(?P<month>.*)-(?P<year>.*) (?P<time>.*)") for row in rows: elements = row.findAll("td") activityGroups = activityProg.match(elements[2].find("a")["href"]) dateGroups = datetimeProg.match(elements[5].find("span").text.strip().replace("\r\n", "").replace("\t", "")) reasons.append({ "type" : "lesson" if elements[0].text.strip().replace("\r\n", "").replace("\t", "") == "Lektion" else "other", "week" : elements[1].text.strip().replace("\r\n", "").replace("\t", ""), "activity_id" : activityGroups.group("activity_id") if not activityGroups is None else "", "leave" : elements[3].text.strip().replace("\r\n", "").replace("\t", "").replace("%", ""), "creadited" :True if elements[4].text.strip().replace("\r\n", "").replace("\t", "") == "Ja" else False, "registred" : datetime.strptime("%s/%s-%s %s" % (functions.zeroPadding(dateGroups.group("day")), functions.zeroPadding(dateGroups.group("month")), dateGroups.group("year"), dateGroups.group("time")), "%d/%m-%Y %H:%M"), "teacher" : { "abbrevation" : unicode(elements[6].text.strip().replace("\r\n", "").replace("\t", "")) }, "team" : { "name" : unicode(elements[7].text.strip().replace("\r\n", "").replace("\t", "")) }, "comment" : unicode(elements[8].text.strip().replace("\r\n", "").replace("\t", "")), "reason" : { "value" : unicode(elements[9].text.strip().replace("\r\n", "").replace("\t", "")), "key" : reasonKeys[unicode(elements[9].text.strip().replace("\r\n", "").replace("\t", ""))] if unicode(elements[9].text.strip().replace("\r\n", "").replace("\t", "")) in reasonKeys else "other", "note": unicode(elements[10].text.strip().replace("\r\n", "").replace("\t", "")) }, }) return { "status" : "ok", "reasons" : reasons, "missing" : missing }
user = '******' app = 'plusDomains' version = 'v1' scope = ['https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/plus.stream.write'] post = { 'object' : { 'originalContent' : 'Happy Monday! #caseofthemondays' }, 'access' : { 'items' : [{ 'type' : 'domain' }], 'domainRestricted': True } } service = authenticate.authenticate(app, version, scope, sub='*****@*****.**') def create_post(): return service.activities().insert(userId = user, body = post).execute() def create_comment(): pass if __name__ == '__main__': print(create_post())
def books( config, session = False ): if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} else: url = urls.books_list.replace("{{SCHOOL_ID}}", str(config["school_id"])).replace("{{STUDENT_ID}}", str(config["student_id"])).replace("{{BRANCH_ID}}", str(config["branch_id"])) # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Sorting settings settings = { "time" : "0", "__EVENTTARGET" : "s$m$Content$Content$ShowActiveOnlyCB", "__EVENTARGUMENT:" : "", "__VIEWSTATEX" : "kwUAAGlpZQk2Mjc5NjMyNjBpbARrAG1rAWcBbAJoaWlsBmsCfQGbc34dAQAAAGsDZwFrBGUaRWxldmVuIEJvIEhhbnMgVGhvbXNlbiwgMnFkbAJoaWRsAmcCaWwCawVlA29mZmwEZwJpZGwCZxVpZGwCZwFpbAJrBnFkZwNpZGwCZwFpZGwCZwVpZGwCZwFpZGwCZwNpbAJrB3BsBmhpZGwMZwFpZGwCZwFpbAJrCG1kZwNpbARrCG1rBnBkZwVpaWwCawZxZGwIZwFpbAJrCG1kZwNpbAJrCWwAZGcFaXMRaWwCawpxZGpsAGwAbABkZGRkZGRkZGRkcwBkZGRkZGcHaXMRaWwGawtxawpwawxoZGpsAGwAbABkZGRkZGRkZGRkcwBkZGRkbAJoaWlsBGsNZQlsaXN0IG1heFdrDmcCZGRnB2lkbAJnAWlsBGsIbWsGcGRnCWlpbAJrBnBkbAJnA2lzEWlsBGsKcWsGcGRqbABsAGwAZGRkZGRkZGRkZHMAZGRkZGRnC2lpbARrD2RrBnBkZGcBaWRsAmcBaWRsBGcBaWwCawhtZGcFaXMRaWwCawpxZGpsAGwAbABkZGRkZGRkZGRkcwBkZGRkZGcCaWRsAmcBaWRsCmcBaWpkZGwBZwFkZwNpamRkbAFoZGcFaWRsAmcDaXMRaWwCawpxZGpsAGwAbABkZGRkZGRkZGRkcwBkZGRkZGcHaWRsAmcDaXMRaWwCawpxZGpsAGwAbABkZGRkZGRkZGRkcwBkZGRkZGcJaWRsAmcDaXMRaWwCawpxZGpsAGwAbABkZGRkZGRkZGRkcwBkZGRkZHIKZRxzJG0kQ29udGVudCRDb250ZW50JG15cHVic0dWaXMMZGRkZGRkbgFlB0R1bW15SURkZ/////8PZGRkZGUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fbAFlJHMkbSRDb250ZW50JENvbnRlbnQkU2hvd0FjdGl2ZU9ubHlDQmUgcyRtJENvbnRlbnQkQ29udGVudCRCZEJvb2tMb2FuR1ZpcwxkZGRkZGRuAWUHRHVtbXlJRHMKcwF7NCcBAQAAAABzAXsvJwEBAAAAAHMBezYnAQEAAAAAcwF7OCcBAQAAAABzAXswJwEBAAAAAHMBezEnAQEAAAAAcwF7MicBAQAAAABzAXszJwEBAAAAAHMBezUnAQEAAAAAcwF7NycBAQAAAABnAWRkZGRlNXMkbSRDb250ZW50JENvbnRlbnQkcHVibGlzaGVyU2FsZXNDdHJsJHRvdGFsU2FsZXNHcmlkaXMMZGRkZGRkbgFlB0R1bW15SURkZ/////8PZGRkZGUccyRtJENvbnRlbnQkQ29udGVudCR0YWJzdHJpcGlpZGhkZSJzJG0kQ29udGVudCRDb250ZW50JHJlc2VydmF0aW9uc0dWaXMMZGRkZGRkbgFlB0R1bW15SURkZ/////8PZGRkZGUxcyRtJENvbnRlbnQkQ29udGVudCRwdWJsaXNoZXJTYWxlc0N0cmwkc2Nob29sR3JpZGlzDGRkZGRkZG4BZQdEdW1teUlEZGf/////D2RkZGRlKHMkbSRDb250ZW50JENvbnRlbnQkZWJvb2tzRm9yRmF2b3JpdGhvbGRpcwxkZGRkZGRuAWUHRHVtbXlJRGRn/////w9kZGRkZS9zJG0kQ29udGVudCRDb250ZW50JHB1Ymxpc2hlclNhbGVzQ3RybCRib29rR3JpZGlzDGRkZGRkZG4BZQdEdW1teUlEZGf/////D2RkZGRlL3MkbSRDb250ZW50JENvbnRlbnQkZWJvb2tzRm9yRmF2b3JpdEhvbGRTdHVkZW50aXMMZGRkZGRkbgFlB0R1bW15SURkaGRkZGQQAAAABXVzcmlkE1ZhbGlkYXRlUmVxdWVzdE1vZGUIbGVjdGlvaWQFbXR5cGUKRW50aXR5TmFtZQxhdXRvY29tcGxldGUHVmlzaWJsZQtzaG93aGVhZGVycxFOYXZpZ2F0ZVVybExlY3RpbwtDdXJyZW50RGF0YRRfUmVxdWlyZXNEYXRhQmluZGluZwtfIURhdGFCb3VuZAtfIUl0ZW1Db3VudAhDc3NDbGFzcwRfIVNCCVRlYWNoZXJJZAEAAQAAAP////8BAAAAAAAAAAQBAAAAf1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLk9iamVjdCwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgUAAAgICQIAAAAGAAAABgAAABACAAAACAAAAAkDAAAACQQAAAAJBQAAAAkGAAAACQcAAAAJCAAAAA0CDAkAAABKTWFjb20uTGVjdGlvLkNvbW1vbiwgVmVyc2lvbj0xLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPW51bGwFAwAAABJNYWNvbS5MZWN0aW8uVXNySUQBAAAABl92YWx1ZQAJCQAAAJ9zfh0BAAAADAoAAABDTWFjb20uTGVjdGlvLCBWZXJzaW9uPTEuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbAUEAAAAGU1hY29tLkxlY3Rpby5MZWN0aW9SZWZVcmwBAAAABGRhdGEEKk1hY29tLkxlY3Rpby5MZWN0aW9SZWZVcmwrTGVjdGlvUmVmVXJsRGF0YQoAAAAKAAAACQsAAAABBQAAAAQAAAAJDAAAAAEGAAAABAAAAAkNAAAAAQcAAAAEAAAACQ4AAAABCAAAAAQAAAAJDwAAAAULAAAAKk1hY29tLkxlY3Rpby5MZWN0aW9SZWZVcmwrTGVjdGlvUmVmVXJsRGF0YQQAAAAGcmVmdXJsEHJlZnVybFVybEVuY29kZWQSX2lzU3RhdGljUmVmZXJlbmNlCkZvcmNlSFRUUFMBAQAAAQEKAAAABhAAAABjRWJvZy9EZWZhdWx0LmFzcHg/cHJldnVybD1CRCUyZlVzZXJSZXNlcnZhdGlvbnMuYXNweCUzZkVsZXZJRCUzZDQ3ODk3OTM2OTElMjZwcmV2dXJsJTNkZm9yc2lkZS5hc3B4CgAAAQwAAAALAAAABhEAAABfQkQvQm9va3MuYXNweD9wcmV2dXJsPUJEJTJmVXNlclJlc2VydmF0aW9ucy5hc3B4JTNmRWxldklEJTNkNDc4OTc5MzY5MSUyNnByZXZ1cmwlM2Rmb3JzaWRlLmFzcHgKAAABDQAAAAsAAAAGEgAAAGdFYm9nL0NyZWF0ZUVib29rLmFzcHg/cHJldnVybD1CRCUyZlVzZXJSZXNlcnZhdGlvbnMuYXNweCUzZkVsZXZJRCUzZDQ3ODk3OTM2OTElMjZwcmV2dXJsJTNkZm9yc2lkZS5hc3B4CgAAAQ4AAAALAAAABhMAAAB/QkQvU3R1ZGVudFJlc2VydmF0aW9ucy5hc3B4P0VsZXZJRD00Nzg5NzkzNjkxJnByZXZ1cmw9QkQlMmZVc2VyUmVzZXJ2YXRpb25zLmFzcHglM2ZFbGV2SUQlM2Q0Nzg5NzkzNjkxJTI2cHJldnVybCUzZGZvcnNpZGUuYXNweAoAAAEPAAAACwAAAAYUAAAAZ0Vib2cvQ3JlYXRlRWJvb2suYXNweD9wcmV2dXJsPUJEJTJmVXNlclJlc2VydmF0aW9ucy5hc3B4JTNmRWxldklEJTNkNDc4OTc5MzY5MSUyNnByZXZ1cmwlM2Rmb3JzaWRlLmFzcHgKAAAL/HO0KMmthSVEyM2CYSzxt4utYL4=", "__VIEWSTATE:" : "", "__EVENTVALIDATION" : "6OqghX6xZOeeKUKrRIw7ICUy+1VPS7casHOeKUMsfDj6sV1LAjCrokugRNNSYnB3AtE4D/xEDXGXEUMRV8fCTtH6dqeuxRYS3AAMtYA04et59bwlJNT3c0QGpPiKz05X2fng07YiA1EvrNnE7J2D0smysbBQFSyR2nfIDZ8f6eWBxsh2hXpJJp7aM7qydcWFGsMBDBO3OCBWoLKpI/4bHnW/GiUzfgOYqQ8qCIe91qkwdY2JO1s/Szu1CkSeWJPjohv4N2UiRhGyxtJDEXUAho/DmOUtCRMrJliE7WJBf6rGpwELcczgLirEbiGyhY9b2HAkUorn0H6Kc6FL/iHvAZNQqalZQJDp0RK0QCi/6Qzo1rrCU/sVzkB7S4zDO23hyoLFmOkwm6ILTN3hehLMVOgvq9TJqhcxUFHb47KrVEI2l94BmOGnWH1eiQlr24I35qsepc7/nNp5UvL5GX/MHg==", "__LASTFOCUS:" : "", "__VIEWSTATEENCRYPTED:" : "", "LectioPostbackId:" : "", "s$m$searchinputfield:" : "" } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.post(url, data=settings, headers=headers) html = response.text soup = Soup(html) loans = soup.find("table", attrs={"id" : "s_m_Content_Content_BdBookLoanGV"}).findAll("tr") loansList = [] for loan in loans: columns = loan.findAll("td") if len(columns) > 0: # Define the short team pattern "2q KE" etc.. shortTeamPreg = re.compile(r"(?P<class>\w.) (?P<team>\w.)") # Define the long team pattern "2012 FY/i" etc... yearTeamPreg = re.compile(r"(?P<year>[0-9]*) (?P<team>[0-9A-Z]*)\/(?P<class>\w*)") # Find and prepare the team string text teamText = columns[1].text.replace("\n", "").replace("\t", "").strip() teamRows = None preg = "" # Check which and if any pattern matches the string if shortTeamPreg.match(teamText): preg = "short" teamRows = shortTeamPreg.match(teamText) elif yearTeamPreg.match(teamText): preg = "long" teamRows = yearTeamPreg.match(teamText) delivery_reg_date = columns[3].text.replace("\n","").strip() if not delivery_reg_date == "": delivery_reg_date = datetime.strptime(delivery_reg_date, "%d-%m-%Y") loansList.append({ "title" : columns[0].text.replace("\n", "").replace("\t", "").strip(), "team" : teamRows.group("team") if not teamRows == None else "", "year" : teamRows.group("year") if not teamRows == None and preg == "long" else "", "class" : teamRows.group("class") if not teamRows == None else "", "lending_reg_date" : datetime.strptime(columns[2].text.replace("\n","").strip(), "%d-%m-%Y"), "delivery_reg_date" : delivery_reg_date, "delivery_date" : datetime.strptime(columns[4].text.replace("\n","").strip(), "%d-%m-%Y"), "price" : columns[5].text.replace("\n", "").replace("\t", "").replace(",", ".").strip(), "team_name" : teamText }) return { "status" : "ok", "loans" : loansList, "term" : { "value" : soup.find("select", attrs={"id" : "s_m_ChooseTerm_term"}).select('option[selected="selected"]')[0]["value"], "years_string" : soup.find("select", attrs={"id" : "s_m_ChooseTerm_term"}).select('option[selected="selected"]')[0].text } }
def messages_headers ( config, session = False ): url = "https://www.lectio.dk/lectio/%s/beskeder2.aspx?type=liste&elevid=%s" % ( str(config["school_id"]), str(config["student_id"]) ) if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } settings = {} # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, data=settings, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id" : "s_m_Content_Content_ThreadListPanel"}) is None: return { "status" : False, "error" : "Data not found" } headers = soup.findAll("a", attrs={"class": "s_m_Content_Content_ListGridSelectionTree_0"}) indices = 0, 1, 2, 3, 4, 5, 6 headers = [i for j, i in enumerate(headers) if j not in indices] typeName = "team" teams = [] build_in_groups = [] own_groups = [] pageIdProg = re.compile(r"javascript:__doPostBack\('__Page','TREECLICKED_(?P<page_id>.*)'\)") for header in headers: text = header.text.strip() include = True if text == "Indbyggede grupper": typeName = "build_in_groups" include = False elif text == "Egne grupper": typeName = "own_groups" include = False if include is True: pageGroups = pageIdProg.match(header["href"]) data = { "name" : unicode(text), "message_page_id" : pageGroups.group("page_id") if not pageGroups is None else "" } if typeName == "team": team = context_card.team({"school_id" : str(config["school_id"]), "context_card_id" : "H" + data["message_page_id"]} ,session) data["team"] = team["team"] teams.append(data) elif typeName == "own_groups": own_groups.append(data) else: build_in_groups.append(data) return { "status" : "ok", "teams" : teams, "build_in_groups" : build_in_groups, "own_groups" : own_groups }
def messages ( config, session = False ): url = "https://www.lectio.dk/lectio/%s/beskeder2.aspx?type=liste&elevid=%s" % ( str(config["school_id"]), str(config["student_id"]) ) if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) viewStateX = soup.find("input", attrs={"id" : "__VIEWSTATEX"})["value"] settings = { "__EVENTTARGET" : "__Page", "__EVENTARGUMENT" : "TREECLICKED_%s" % ( str(config["page_id"]) ), "__VIEWSTATEX" : viewStateX, #"s_m_Content_Content_ListGridSelectionTree_ExpandState" : "nnnnnnennnnnnnnnnnennenn", "s_m_Content_Content_ListGridSelectionTree_SelectedNode" : "s_m_Content_Content_ListGridSelectionTreet8", "s_m_Content_Content_ListGridSelectionTree_PopulateLog" : "", "s$m$Content$Content$MarkChkDD" : "-1" } response = proxy.session.post(url, data=settings, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id" : "s_m_Content_Content_ThreadListPanel"}) is None: return { "status" : False, "error" : "Data not found" } rows = soup.find("table", attrs={"id" : "s_m_Content_Content_threadGV_ctl00"}).findAll("tr") if len(rows[0].findAll("td")) > 3 and not rows[0].findAll("td")[3].find("a") is None: viewStateKey = soup.find("input", attrs={"id" : "__VIEWSTATEY_KEY"})["value"] target = rows[0].findAll("td")[3].find("a")["href"] targetProg = re.compile(r'javascript:WebForm_DoPostBackWithOptions\(new WebForm_PostBackOptions\("(?P<target>.*)", "", true, "", "", false, true\)\)') targetGroups = targetProg.match(target) if targetGroups is None: return { "status" : False, "error" : "Missing target" } settings = { "__EVENTTARGET" : targetGroups.group("target"), "__EVENTARGUMENT" : "TREECLICKED_%s" % ( str(config["page_id"]) ), "__VIEWSTATEY_KEY" : viewStateKey, "s_m_Content_Content_ListGridSelectionTree_ExpandState" : "nnnnnnennnnnnnnnnnennenn", "s_m_Content_Content_ListGridSelectionTree_SelectedNode" : "s_m_Content_Content_ListGridSelectionTreet8", "s_m_Content_Content_ListGridSelectionTree_PopulateLog" : "", "s$m$Content$Content$MarkChkDD" : "-1" } response = proxy.session.post(url, data=settings, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id" : "s_m_Content_Content_ThreadListPanel"}) is None: return { "status" : False, "error" : "Data not found" } if soup.find("table", attrs={"id" : "s_m_Content_Content_threadGV_ctl00"}) is None: return { "status" : "ok", "messages" : [] } rows = soup.find("table", attrs={"id" : "s_m_Content_Content_threadGV_ctl00"}).findAll("tr") rows.pop(0) messages = [] today = datetime.now() shortDayTimeProg = re.compile(r"(?P<day_name>.*) (?P<hour>.*):(?P<minute>.*)") timeProg = re.compile(r"(?P<hour>.*):(?P<minute>.*)") # Current day, month, year dayProg = re.compile(r"(?P<day_name>.*) (?P<day>.*)/(?P<month>.*)") # Current year dateProg = re.compile(r"(?P<day>.*)/(?P<month>.*)-(?P<year>.*)") studentProg = re.compile(r"(?P<name>.*) \((?P<class_name>.*)\)") teacherProg = re.compile(r"(?P<name>.*) \((?P<abbrevation>.*)\)") messageIdProg = re.compile(r"__doPostBack\('__Page','\$LB2\$_MC_\$_(?P<message_id>.*)'\); return false;") shownIn = [] shownInMappings = { "-40" : "all_unread", "-50" : "all_with_flag", "-70" : "newest", "-60" : "all_deleted", "-10" : "own_messages", "-80" : "sent_messages", "-20" : "teams", "-30" : "build_in_groups", "-35" : "own_groups" } dayConversion = { u"Ma" : "Mon", u"Ti" : "Tue", u"On" : "Wed", u"To" : "Thu", u"Fr" : "Fri", u"Lø" : "Sat", u"Sø" : "Son" } if str(config["page_id"]) in shownInMappings: shownIn.append(shownInMappings[str(config["page_id"])]) else: shownIn.append(str(config["page_id"])) for row in rows: elements = row.findAll("td") if not elements is None and len(elements) > 0 and not elements[1].find("img") is None: flagOn = True if elements[1].find("img")["src"] == "/lectio/img/flagon.gif" else False read = False if elements[2].find("img")["src"] == "/lectio/img/munread.gif" else True subject = unicode(elements[3].find("a").text) documentsAttached = True if not elements[3].find("img") is None else False deleted = True if elements[8].find("img")["src"] == "/lectio/img/add.auto" else False date = None messageGroups = messageIdProg.match(elements[3].find("a")["onclick"]) message_id = messageGroups.group("message_id") if not messageGroups is None else "" if shortDayTimeProg.match(elements[7].text): timeGroups = shortDayTimeProg.match(elements[7].text) date = datetime.strptime("%s/%s-%s %s:%s" % (dayConversion[unicode(timeGroups.group("day_name").capitalize())], today.strftime("%W"), today.strftime("%Y"), timeGroups.group("hour"), timeGroups.group("minute")), "%a/%W-%Y %H:%M") elif timeProg.match(elements[7].text): timeGroups = timeProg.match(elements[7].text) date = datetime.strptime("%s/%s-%s %s:%s" % (today.strftime("%d"), today.strftime("%m"), today.strftime("%Y"), timeGroups.group("hour"), timeGroups.group("minute")), "%d/%m-%Y %H:%M") elif dayProg.match(elements[7].text): dayGroups = dayProg.match(elements[7].text) date = datetime.strptime("%s/%s-%s %s:%s" % (dayGroups.group("day"), dayGroups.group("month"), today.strftime("%Y"), "12", "00"), "%d/%m-%Y %H:%M") elif dateProg.match(elements[7].text): dateGroups = dateProg.match(elements[7].text) date = datetime.strptime("%s/%s-%s %s:%s" % (dateGroups.group("day"), dateGroups.group("month"), dateGroups.group("year"), "12", "00"), "%d/%m-%Y %H:%M") lastSenderType = "teacher" if elements[4].find("img")["src"] == "/lectio/img/teacher.auto" else "student" firstSenderType = "teacher" if elements[5].find("img")["src"] == "/lectio/img/teacher.auto" else "student" recipientsType = "student" if elements[6].find("img")["src"] == "/lectio/img/student.auto" else "teacher" if elements[6].find("img")["src"] == "/lectio/img/teacher.auto" else "class" lastSender = {} firstSender = {} if lastSenderType == "teacher": teacherGroups = teacherProg.match(elements[4].find("span")["title"]) lastSender["name"] = unicode(teacherGroups.group("name")) if not teacherGroups is None else "" lastSender["abbrevation"] = unicode(teacherGroups.group("abbrevation")) if not teacherGroups is None else "" else: studentGroups = studentProg.match(elements[4].find("span")["title"]) lastSender["name"] = unicode(studentGroups.group("name")) if not studentGroups is None else "" lastSender["class_name"] = unicode(studentGroups.group("class_name")) if not studentGroups is None else "" if firstSenderType == "teacher": teacherGroups = teacherProg.match(elements[5].find("span")["title"]) firstSender["name"] = unicode(teacherGroups.group("name")) if not teacherGroups is None else "" firstSender["abbrevation"] = unicode(teacherGroups.group("abbrevation")) if not teacherGroups is None else "" else: studentGroups = studentProg.match(elements[5].find("span")["title"]) firstSender["name"] = unicode(studentGroups.group("name")) if not studentGroups is None else "" firstSender["class_name"] = unicode(studentGroups.group("class_name")) if not studentGroups is None else "" messages.append({ "flagged" : flagOn, "read" : read, "documents_attached" : documentsAttached, "subject" : subject, "last_message" : { "sender_user_type" : lastSenderType, "sender" : lastSender }, "first_message" : { "sender_user_type" : firstSenderType, "sender" : firstSender }, "recipients" : { "type" : recipientsType }, "changed" : date, "thread_id" : message_id, "shown_in" : shownIn, "deleted" : deleted }) return { "status" : "ok", "messages" : messages }
def class_members ( config, session = False ): if session == False: url = "https://www.lectio.dk/lectio/%s/subnav/members.aspx?klasseid=%s&showteachers=1&showstudents=1&reporttype=std" % ( str(config["school_id"]), str(config["class_id"]) ) cookies = {} else: if session == True: session = authenticate.authenticate(config) url = "https://www.lectio.dk/lectio/%s/subnav/members.aspx?klasseid=%s&showteachers=1&showstudents=1" % ( str(config["school_id"]), str(config["class_id"]) ) # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("table", attrs={"id" : "s_m_Content_Content_laerereleverpanel_alm_gv"}) is None: return { "status" : False, "error" : "Data not found" } rows = soup.find("table", attrs={"id" : "s_m_Content_Content_laerereleverpanel_alm_gv"}).findAll("tr") headers = rows[0].findAll("th") rows.pop(0) teachers = [] students = [] pictureOffset = 1 if len(headers) == 7 else 0 pictureProg = re.compile(r"\/lectio\/(?P<school_id>.*)\/GetImage.aspx\?pictureid=(?P<picture_id>.*)") if len(rows) > 0: for row in rows: elements = row.findAll("td") personType = "teacher" if unicode(elements[0 + pictureOffset].text) == u"Lærer" else "student" data = { "type" : personType, "first_name" : unicode(elements[2 + pictureOffset].find("a").text).encode("utf8"), "person_text_id" : elements[1 + pictureOffset].find("span").text.encode("utf8"), "last_name" : elements[3 + pictureOffset].find("span").text.strip().encode("utf8"), "full_name" : unicode(unicode(elements[2 + pictureOffset].find("a").text) + " " + unicode(elements[3 + pictureOffset].find("span").text)).encode("utf8"), "person_id" : elements[1 + pictureOffset]["lectiocontextcard"].replace("T", "") if personType == "teacher" else elements[1 + pictureOffset]["lectiocontextcard"].replace("S", ""), "context_card_id" : elements[1 + pictureOffset]["lectiocontextcard"] } if pictureOffset == 1: pictureGroups = pictureProg.match(elements[0].find("img")["src"]) data["picture_id"] = pictureGroups.group("picture_id") if not pictureGroups is None else "" if personType == "teacher": data["teams"] = elements[5 + pictureOffset].text.split(", ") teachers.append(data) else: data["field_of_study"] = { "name" : unicode(elements[4 + pictureOffset].find("span").text).encode("utf8"), "context_card_id" : elements[4 + pictureOffset].find("span")["lectiocontextcard"], "field_of_study_id" : elements[4 + pictureOffset].find("span")["lectiocontextcard"].replace("SR", "") } students.append(data) return { "status" : "ok", "teachers" : teachers, "students" : students }
from Emailer import Emailer from authenticate import authenticate import pdb # send it try: match_xls = '/Users/jjw036/Dropbox/GSA/LinkLunch/matches_04212015.xlsx' address_xls = '/Users/jjw036/Dropbox/GSA/LinkLunch/individual_info.xlsx' gmail_service = authenticate() emailer = Emailer() matches = emailer.get_matches(match_xls, address_xls) #parse the list of matches #matches is a list of dicts for match in matches: template = emailer.get_template() new_body = emailer.replace_text(match,template) message, body = emailer.get_welcome_email(match,new_body) print(new_body) user_confirmation = raw_input('Send this email? (1 Y/ 2 n/ 3s) ') if float(user_confirmation) == 1: message = (gmail_service.users().messages().send(userId="me", body=body).execute()) print('Message Id: %s' % message['id']) print(message) elif float(user_confirmation) == 2: break elif float(user_confirmation) == 3:
def get_all_courses(username,pw): ''' extracts your grades from CMU's academic audit returns a json of course -> letter grade (string) * means you're taking the class and grades haven't been put in yet AP means you got it through AP credit P is pass ''' if (not isAuthenticated(username,pw)): print "Authentication Failed" return s = authenticate('https://enr-apps.as.cmu.edu/audit/audit',username,pw) # find out the params for main major auditing mainFrame = s.get('https://enr-apps.as.cmu.edu/audit/audit?call=2').content d = pq(mainFrame) params = {'call': 7} for htmlInput in d('input[type=hidden]'): name = d(htmlInput).attr('name') value = d(htmlInput).attr('value') if name != 'call': params[name] = value # get page for given major classes = s.get('https://enr-apps.as.cmu.edu/audit/audit?' + urlencode(params)).content # take grades from <pre>s in the page d = pq(classes) major_courses = Set([]) all_courses = Set([]) classlevel = "" major = -1 for pre in d('pre'): data = d(pre).text() for line in data.split('\n'): matches = re.search('(\d+-\d+) \w+\s*\'\d+ ((\w|\*)+)\s*(\d+\.\d)\s*$', line) if matches is not None: major_course = matches.group(1) major_courses.add(major_course) all_courses.add(major_course) else: nonmajor_course = re.search('(\d+-\d+) \w+\s*\'\d+ ((\w|\*)+)\s*(\d+\.\d)\s*', line) if nonmajor_course is not None: course = nonmajor_course.group(1) all_courses.add(course) else: classLevelArray = line.split("CLASSLEVEL:") if len(classLevelArray) > 1: #found class level classlevel = classLevelArray[1] majorfile = params['MajorFile'] i = majorfile.find("SCS") j = majorfile.find("ECE") #might need to change later? if i != -1: major = 0 # CS major elif j != -1: major = 1 #print major_courses print all_courses print classlevel print major return [major_courses,classlevel,major]
def documents ( config, session = False ): if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } url = "https://www.lectio.dk/lectio/%s/DokumentOversigt.aspx?elevid=%s&folderid=%s" %( str(config["school_id"]), str(config["student_id"]), str(config["folder_id"]) ) response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("table", attrs={"id" : "s_m_Content_Content_DocumentGridView_ctl00"}) is None: return { "status" : False, "error" : "Data not found" } rows = soup.find("table", attrs={"id" : "s_m_Content_Content_DocumentGridView_ctl00"}).findAll("tr") rows.pop(0) shortDayTimeProg = re.compile(r"(?P<day_name>.*) (?P<hour>.*):(?P<minute>.*)") timeProg = re.compile(r"(?P<hour>.*):(?P<minute>.*)") # Current day, month, year dayProg = re.compile(r"(?P<day_name>.*) (?P<day>.*)/(?P<month>.*)") # Current year dateProg = re.compile(r"(?P<day>.*)/(?P<month>.*)-(?P<year>.*)") dayConversion = { u"Ma" : "Mon", u"Ti" : "Tue", u"On" : "Wed", u"To" : "Thu", u"Fr" : "Fri", u"Lø" : "Sat", u"Sø" : "Son" } documents = [] documentIdProg = re.compile(r"\/lectio\/(?P<school_id>.*)\/dokumenthent.aspx\?documentid=(?P<document_id>.*)") for row in rows: elements = row.findAll("td") idGroups = documentIdProg.match(elements[1].find("a")["href"]) changer = context_card.user({ "context_card_id" : elements[3]["lectiocontextcard"], "school_id" : config["school_id"] }, session) if shortDayTimeProg.match(elements[4].text): timeGroups = shortDayTimeProg.match(elements[4].text) date = datetime.strptime("%s/%s-%s %s:%s" % (dayConversion[unicode(timeGroups.group("day_name").capitalize())], today.strftime("%W"), today.strftime("%Y"), timeGroups.group("hour"), timeGroups.group("minute")), "%a/%W-%Y %H:%M") elif timeProg.match(elements[4].text): timeGroups = timeProg.match(elements[4].text) date = datetime.strptime("%s/%s-%s %s:%s" % (today.strftime("%d"), today.strftime("%m"), today.strftime("%Y"), timeGroups.group("hour"), timeGroups.group("minute")), "%d/%m-%Y %H:%M") elif dayProg.match(elements[4].text): dayGroups = dayProg.match(elements[4].text) date = datetime.strptime("%s/%s-%s %s:%s" % (dayGroups.group("day"), dayGroups.group("month"), today.strftime("%Y"), "12", "00"), "%d/%m-%Y %H:%M") elif dateProg.match(elements[4].text): dateGroups = dateProg.match(elements[4].text) date = datetime.strptime("%s/%s-%s %s:%s" % (dateGroups.group("day"), dateGroups.group("month"), dateGroups.group("year"), "12", "00"), "%d/%m-%Y %H:%M") data = { "folder_id" : str(config["folder_id"]), "name" : unicode(elements[1].find("span")["title"].replace("Fulde filnavn: ", "")), "extension" : os.path.splitext(elements[1].find("span")["title"].replace("Fulde filnavn: ", ""))[1].replace(".", ""), "comment" : unicode(elements[2].find("span").text), "document_id" : idGroups.group("document_id") if not idGroups is None else "", "size" : elements[5].text.replace(",", "."), "date" : date, "user" : changer["user"] } documents.append(data) return { "status" : "ok", "documents" : documents }
def team_books ( config, session = False ): url = "https://www.lectio.dk/lectio/%s/BD/HoldReservations.aspx?HoldID=%s" % ( str(config["school_id"]), str(config["team_id"]) ) if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) if soup.find("div", attrs={"id" : "m_Content_ebooks_island_pa"}) is None: return { "status" : False, "error" : "Data not found" } books = [] for row in soup.find(attrs={"id" : "m_Content_ebooks_island_pa"}).find("table").findAll("tr")[1:]: elements = row.findAll("td") books.append({ "team_id" : str(config["team_id"]), "type" : "ebook", "title" : unicode(elements[0].text.replace("\r\n", "").replace("\t", "")), "read" : unicode(elements[1].text.replace("\r\n", "").replace("\t", "")) }) for row in soup.find(attrs={"id" : "m_Content_reservationsStudentGV"}).findAll("tr")[1:]: elements = row.findAll("td") books.append({ "type" : "book", "team_id" : str(config["team_id"]), "title" : unicode(elements[0].text.replace("\r\n", "").replace("\t", "")) }) return { "status" : "ok", 'books' : books }
def assignment_info ( config, session = False ): url = urls.assignment_info.replace("{{SCHOOL_ID}}", str(config["school_id"])).replace("{{ASSIGNMENT_ID}}", str(config["assignment_id"])).replace("{{STUDENT_ID}}",str(config["student_id"])) if session is False: session = authenticate.authenticate(config) if session == False: return {"status" : "error", "type" : "authenticate"} # Insert the session information from the auth function cookies = { "lecmobile" : "0", "ASP.NET_SessionId" : session["ASP.NET_SessionId"], "LastLoginUserName" : session["LastLoginUserName"], "lectiogsc" : session["lectiogsc"], "LectioTicket" : session["LectioTicket"] } settings = {} # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1665.2 Safari/537.36", "Content-Type" : "application/x-www-form-urlencoded", "Host" : "www.lectio.dk", "Origin" : "https://www.lectio.dk", "Cookie" : functions.implode(cookies, "{{index}}={{value}}", "; ") } response = proxy.session.get(url, headers=headers) html = response.text soup = Soup(html) dateTime = re.compile(r"(?P<day>.*)/(?P<month>.*)-(?P<year>.*) (?P<hour>.*):(?P<minute>.*)") if soup.find("div", attrs={"id" : "m_Content_registerAfl_pa"}) is None: return { "status" : False, "error" : "Data not found" } teacherProg = re.compile(r"(?P<name>.*) \((?P<abbrevation>.*)\)") documentProg = re.compile(r"(?P<name>.*) \((?P<upload_date>.*)\)") teamProg = re.compile(r"(?P<class_name>.*) (?P<subject_name>.*)") rows = soup.find("div", attrs={"id" : "m_Content_registerAfl_pa"}).find("table").findAll("td") headers = soup.find("div", attrs={"id" : "m_Content_registerAfl_pa"}).find("table").findAll("th") rowMap = functions.mapRows(headers, rows) dateTimeGroups = dateTime.match(rowMap["Afleveringsfrist"].text) date = datetime.strptime("%s/%s-%s %s:%s" % (functions.zeroPadding(dateTimeGroups.group("day")), functions.zeroPadding(dateTimeGroups.group("month")), dateTimeGroups.group("year"), dateTimeGroups.group("hour"), dateTimeGroups.group("minute")), "%d/%m-%Y %H:%M") group_assignment = False members = [] teachers = [] teams = [] documents = [] comments = [] uploadRows = soup.find("table", attrs={"id" : "m_Content_RecipientGV"}).findAll("tr") uploadRows.pop(0) uploadProg = re.compile(r"\/lectio/(?P<school_id>.*)\/ExerciseFileGet.aspx\?type=(?P<type>.*)&entryid=(?P<entry_id>.*)") for row in uploadRows: elements = row.findAll("td") context_card_id = elements[1].find("span")["lectiocontextcard"] dateTimeGroups = dateTime.match(elements[0].find("span").text) upload_type = "" entry_id = "" if not elements[3].find("a") is None: uploadGroups = uploadProg.match(elements[3].find("a")["href"]) entry_id = uploadGroups.group("entry_id") upload_type = "student_assignment" if uploadGroups.group("type") == "elevopgave" else "other" uploadDate = datetime.strptime("%s/%s-%s %s:%s" % (functions.zeroPadding(dateTimeGroups.group("day")), functions.zeroPadding(dateTimeGroups.group("month")), dateTimeGroups.group("year"), dateTimeGroups.group("hour"), dateTimeGroups.group("minute")), "%d/%m-%Y %H:%M") comments.append({ "file" : { "name" : elements[3].find("a").text.encode("utf8") if not elements[3].find("a") is None else "", "entry_id" : entry_id, "type" : upload_type }, "comment" : functions.cleanText(elements[2].text).encode("utf8"), "uploader" : { "name" : elements[1].find("span")["title"].encode("utf8") if context_card_id[0] == "T" else elements[1].find("span").text.encode("utf8"), "type" : "teacher" if context_card_id[0] == "T" else "student", "person_id" : context_card_id.replace("T", "") if context_card_id[0] == "T" else context_card_id.replace("S", ""), "context_card_id" : context_card_id, "abbrevation" : elements[1].find("span").text.encode("utf8") if context_card_id[0] == "T" else "" }, "date" : uploadDate }) documentIdProg = re.compile(r"\/lectio\/(?P<school_id>.*)\/ExerciseFileGet.aspx\?type=(?P<type>.*)&exercisefileid=(?P<exercise_file_id>.*)") statusProg = re.compile(r"(?P<status>.*)\/ (.*): (?P<leave>.*)%") studentDataElements = soup.find("table", attrs={"id" : "m_Content_StudentGV"}).findAll("tr")[1].findAll("td") statusGroups = statusProg.match(functions.cleanText(studentDataElements[3].text).encode("utf8")) status = functions.cleanText(statusGroups.group("status")) if not statusGroups is None else "" studentData = { "student" : { "context_card_id" : studentDataElements[0].find("img")["lectiocontextcard"], "student_id" : studentDataElements[0].find("img")["lectiocontextcard"].replace("S", ""), }, "status" : "handed" if status.strip() == "Afleveret" else "missing", "waiting_for" : "student" if functions.cleanText(studentDataElements[2].text) == "Elev" else "teacher" if unicode(functions.cleanText(studentDataElements[2].text)) == u"Lærer" else "none", "leave" : functions.cleanText(statusGroups.group("leave")) if not statusGroups is None else 0, "finished" : True if soup.find("input", attrs={"id" : "m_Content_StudentGV_ctl02_CompletedCB"}).has_attr("checked") and soup.find("input", attrs={"id" : "m_Content_StudentGV_ctl02_CompletedCB"})["checked"] == "checked" else False, "grade" : functions.cleanText(studentDataElements[5].text).encode("utf8"), "grade_note" : functions.cleanText(studentDataElements[6].text).encode("utf8"), "student_note" : functions.cleanText(studentDataElements[7].text).encode("utf8") } if u"Opgavebeskrivelse" in rowMap: for row in rowMap[u"Opgavebeskrivelse"].findAll("a"): fileNameGroups = documentProg.match(functions.cleanText(row.text.strip())) fileIdGroups = documentIdProg.match(row["href"]) documentType = fileIdGroups.group("type") if not fileIdGroups is None else "", documents.append({ "name" : fileNameGroups.group("name") if not fileNameGroups is None else "", "exercise_file_id" : fileIdGroups.group("exercise_file_id") if not fileIdGroups is None else "", "uploaded_date_string" : fileNameGroups.group("upload_date") if not fileNameGroups is None else "", "type" : "exercise_description", "school_id" : fileIdGroups.group("school_id") if not fileIdGroups is None else "" }) for row in rowMap["Hold"].findAll("span"): #teamGroups = teamProg.match(row.text) teams.append({ #"class_name" : unicode(teamGroups.group("class_name")) if not teamGroups is None else "", #"subject_name" : unicode(teamGroups.group("subject_name")) if not teamGroups is None else "", "team_element_name" : row.text, "team_element_id" : rowMap["Hold"].find("span")["lectiocontextcard"].replace("HE", ""), "context_card_id" : rowMap["Hold"].find("span")["lectiocontextcard"] }) for row in rowMap["Ansvarlig"].findAll("span"): teacherGroups = teacherProg.match(row.text) teachers.append({ "teacher_id" : row["lectiocontextcard"].replace("T", ""), "name" : teacherGroups.group("name").encode("utf8") if not teacherGroups is None else "", "context_card_id" : row["lectiocontextcard"], "abbrevation" : teacherGroups.group("abbrevation").encode("utf8") if not teacherGroups is None else "" }) if soup.find("div", attrs={"id" : "m_Content_groupIsland_pa"}): group_assignment = True memberRows = soup.find("table", attrs={"id" : "m_Content_groupMembersGV"}).findAll("tr") memberRows.pop(0) memberProg = re.compile(r"(?P<name>.*), (?P<code>.*)") for row in memberRows: elements = row.findAll("td") memberGroups = memberProg.match(elements[0].find("span").text) members.append({ "name" : memberGroups.group("name") if not memberGroups is None else "", "student_id" : elements[0].find("span")["lectiocontextcard"].replace("S", ""), "context_card_id" : elements[0].find("span")["lectiocontextcard"], "student_class_code" : memberGroups.group("code") if not memberGroups is None else "" }) else: memberProg = re.compile(r"Eleven (?P<name>.*) \((?P<code>.*)\) - Opgaveaflevering") memberGroups = memberProg.match(soup.find(attrs={"id" : "m_HeaderContent_pageHeader"}).find("div").text) members.append({ "student_id" : config["student_id"], "context_card_id" : soup.find(attrs={"id" : "m_HeaderContent_pageHeader"}).find("div")["lectiocontextcard"], "student_class_code" : memberGroups.group("code") if not memberGroups is None else "", "name" : memberGroups.group("name") if not memberGroups is None else "", }) availableStudents = [] availableStudentProg = re.compile(r"(?P<name>.*) \((?P<code>.*)\)") if not soup.find("select", attrs={"id" : "m_Content_groupStudentAddDD"}) is None: for row in soup.find("select", attrs={"id" : "m_Content_groupStudentAddDD"}).findAll("option"): progGroups = availableStudentProg.match(row.text) availableStudents.append({ "name" : str(progGroups.group("name")).decode("utf8"), "student_id" : row["value"], "student_class_code" : progGroups.group("code"), }) infomation = { "documents" : documents, "title" : rowMap[r"Opgavetitel"].find("span").text.encode("utf8"), "group_assignment" : group_assignment, "members" : members, "note" : rowMap[u"Opgavenote"].text.encode("utf8"), "team" : teams, "grading_scale" : "7-step" if rowMap[u"Karakterskala"].text == "7-trinsskala" else "13-step", "teachers" : teachers, "student_time" : rowMap[u"Elevtid"].text.replace(",", ".").replace("timer", ""), "date" : date, "in_instruction_detail" : True if rowMap[u"Iundervisningsbeskrivelse"].text == "Ja" else False, "comments" : comments, "group" : { "available_students" : availableStudents }, "student" : studentData } #Delivered by, grade, grade_note, student_note, ended, awaiting, uploaded-documents return { "status" : "ok", "information" : infomation }