def geturl(self, channel, cookie=None): device_id = get_device_id() url = 'https://apac.ti-platform.com/AGL/1.0/R/ENG/PCTV/TNTGO_LATAM_BR/CONTENT/CDN/?id=%s&type=VOD&asJson=Y&accountDeviceId=%s' % (channel, device_id) retry = True if not cookie else False cookie = cookie or get_token() headers = { 'Accept': 'application/json', 'cookie': 'avs_cookie=' + cookie, 'User-Agent': 'Tnt/2.2.13.1908061505 CFNetwork/1107.1 Darwin/19.0.0' } control.log('TNT GET ' + url) control.log(headers) result = json.loads(requests.get(url, headers=headers).content) control.log(result) if 'message' in result and result['message'] == 'Token not valid' and retry: cookie = get_token(True) return self.geturl(channel, cookie) if result.get('resultCode', u'KO') == u'KO': raise Exception('%s: %s' % (result.get('message', u'ERROR'), result.get('errorDescription', u'UNKNOWN'))) return result['resultObj']['src']
def geturl(self, content_id, cookie=None, encrypted=False): device_id = get_device_id() platform = 'PCTV' if not encrypted else vod_platform # 'PCTV_DASH' url = 'https://apac.ti-platform.com/AGL/1.0/R/%s/%s/TNTGO_LATAM_BR/CONTENT/CDN/?id=%s&type=VOD&asJson=Y&accountDeviceId=%s' % (LANGUAGE, platform, content_id, device_id) retry = True if not cookie else False cookie = cookie or get_token() headers = { 'Accept': 'application/json', 'cookie': 'avs_cookie=' + cookie, 'User-Agent': 'Tnt/2.2.13.1908061505 CFNetwork/1107.1 Darwin/19.0.0' } control.log('TNT GET ' + url) control.log(headers) result = requests.get(url, headers=headers, proxies=proxy).json() or {} control.log(result) if 'message' in result and result['message'] == u'Token not valid' and retry: cookie = get_token(True) return self.geturl(content_id, cookie, encrypted) if result.get('resultCode', u'KO') == u'KO': logout() raise Exception('%s: %s' % (result.get('message', u'STREAM URL ERROR'), result.get('errorDescription', u'UNKNOWN'))) return result.get('resultObj', {}).get('src')
def make_request(self, url, payload, headers): if auth.is_active(): headers['X-Auth-Token'] = auth.get_token(False) r = requests.get(url, params=payload, headers=headers) if r.status_code == 401 and auth.is_active(): headers['X-Auth-Token'] = auth.get_token(True) r = requests.get(url, params=payload, headers=headers) return r
def get_metric_data(self, endpoint, tenant, metric_list, payload, headers): #Generate Multiplot query to get metrics in list url = self.get_multi_endpoint(endpoint,tenant) if auth.is_active(): headers['X-Auth-Token'] = auth.get_token(False) r = requests.post(url, params=payload, data=json.dumps(metric_list), headers=headers) if r.status_code == 401 and auth.is_active(): headers['X-Auth-Token'] = auth.get_token(True) r = requests.post(url, params=payload, data=json.dumps(metric_list), headers=headers) if r.status_code != 200: print("get_metric_data failed; response: ", r.status_code, tenant, metric_list) return None else: return r.json()['metrics']
def callback(): # Get access token etc from the call back information access_token, refresh_token, token_type, expires_in = auth.get_token(request, CLIENT_ID, CLIENT_SECRET, CALLBACK_URL) # Create a spotipy session for scraping data spotipy_session = auth.create_spotipy_client_session(CLIENT_ID, CLIENT_SECRET) profile_data = api_call.get_profile_data(access_token) user_id = profile_data['id'] # Scrape all of the relevant data for this user scrape = api_call.scrape_data(access_token, spotipy_session, user_id) # Combine profile and playlist data to display profile_data = scrape["profile"] playlist_data = scrape["playlists"] # Save their token for later open("tokens.txt", "a").write("{}\t{}\n".format(profile_data['id'], access_token)) # display_arr = [profile_data] + playlist_data user_basename = "static/data/{}".format(profile_data['id']) if len(PORT) > 0: base_url = BASE_URL + ":" + PORT else: base_url = BASE_URL return render_template("viz.html", user_id=profile_data['id'], base_url=base_url)
def liveblog_request(context, method, uri, data=None, with_auth=True, token=None, add_server=True, **kwargs): # payload if not data: if 'text' in context: if context.text: data = process_common_templates(context.text, context) else: data = '' if isinstance(data, dict) or isinstance(data, list): data = json.dumps(data) # uri uri = process_common_templates(uri, context) # auth if 'headers' in kwargs: headers = kwargs.pop('headers') else: headers = {} if with_auth: if not token: if not context.token: context.token = get_token(session=context.session) token = context.token headers.update({'Authorization': token}) # request itself request( context, method, uri, data=data, headers=headers, add_server=add_server, **kwargs)
def generate_alert_message(): print('Enter type: (limit, market, etc.)') type = input() print('Enter Side (buy or sell): ') side = input() print('Enter Amount:') amount = input() print('Enter Symbol') symbol = input() if type == 'limit': print('Enter limit price:') price = input() else: price = None key = get_token() print("Copy:\n:") output = { "type": type, "side": side, "amount": amount, "symbol": symbol, "price": price, "key": key } print(str(output).replace('\'', '\"'))
def flush_standup(channel_id): ''' Input: channel_id (int) Returns: Nothing Purpose: Helper function to concat messages in a standup and send them at once ''' with STANDUP_LOCK: standups = get_standup() try: [to_flush ] = list(filter(lambda x: x['channel_id'] == channel_id, standups)) to_send = '\n'.join(to_flush['messages']) # message is empty.. do not bother if not to_send: standups.remove(to_flush) return # get the token given u_id user_token = get_token(to_flush['u_id']) if user_token is None: # generate a temporary token user_token = generate_token(to_flush['u_id']) get_tokens()[user_token] = to_flush['u_id'] message_send(user_token, channel_id, to_send) auth_logout(user_token) else: message_send(user_token, channel_id, to_send) standups.remove(to_flush) except ValueError: pass
def main(self): graph = fbGraphAPI.GraphAPI(auth.get_token()) myFriends = graph.get_connections("me", "friends") outFile = open("friendData.json", "w+") print '{\n\tusers : {\n' outFile.write('{ users : {\n') # Loop through all my friends for friend in friends['data']: # Create a one-way hash of the Facebook user ID to anonymize the data print "\tuser id:\"%s\">\n" % (oneWayHash(friend["id"])) outFile.write("\tuser id:\"%s\">\n" % (oneWayHash(friend["id"]))) # Retrieve the friend's user object to get information such as gender, locale, etc... friendProfileInfo = graphApi.get_object(friend["id"]) writeStringJSON(friendProfileInfo, "gender", "gender", outFile) writeStringJSON(friendProfileInfo, "locale", "locale", outFile) writeStringJSON2(friendProfileInfo, "favorite_athletes", "name", "athletes", outFile) writeStringJSON2(friendProfileInfo, "favorite_teams", "name", "teams", outFile) # Perform a FQL query to retrieve relevant data on what interests each person... result = graphApi.fql("SELECT about_me, activities, interests, music, movies, tv, books, quotes, sports FROM user WHERE uid = %s" % (friend['id'])) # Somewhat valid assumption that FB UID's are, indeed, unique, and that FB doesn't lie... userInterests = result[0] writeStringJSON(userInterests, "about_me", "about", outFile) writeStringJSON(userInterests, "tv", "tv", outFile) writeStringJSON(userInterests, "movies", "movies", outFile) writeStringJSON(userInterests, "music", "music", outFile) writeStringJSON(userInterests, "books", "books", outFile) writeStringJSON(userInterests, "interests", "interests", outFile) writeStringJSON2(userInterests, "sports", "name", "sports", outFile) outFile.write("\n\t}\n}") print "\n\t}\n}"
def webhook(): if request.method == 'POST': # Parse the string data from tradingview into a python dict # datas = parse_webhook(request.get_data(as_text=True)) # print(datas) datas = request.get_data(as_text=True) datas = json.loads(datas) print(datas) # Check that the key is correct if get_token() == datas['key']: print(' [Alert Received] ') print('POST Received/Updated Data:', datas) try: send_order(datas) return '', 200 except Exception as e: print("Error placing your order:\n{0}".format(e)) return "Error placing your order:\n{0}".format(e) else: logger.error("Incoming Signal From Unauthorized User.") abort(403) else: abort(400)
def remove_token(token_id): if token_id is None: abort(400) rc.srem("user|%s|tokens" % auth.current_user(), token_id) token = auth.get_token(token_id) if token is not None: token.delete() return redirect("/oauth/tokens")
def reset_app(context): PUT( context, '/Tool/TestFixture/default', { 'Name': 'default', 'ApplyOnDatabase': True, 'ApplyOnFiles': True}, with_auth=False) context.token = get_token(session=context.session)
def reset_app(context): PUT(context, '/Tool/TestFixture/default', { 'Name': 'default', 'ApplyOnDatabase': True, 'ApplyOnFiles': True }, with_auth=False) context.token = get_token(session=context.session)
def renew_token(token_id): token = auth.get_token(token_id) if token is None: abort(404) token.expires += timedelta(days=30) token.save() return jsonify(dict(token_id=token_id, expires_ts=totimestamp(token.expires), expires_txt="%s" % token.expires))
def generate_alert_message(): bot_name = "None" tg = "None" print('#OrderSend Information#') print('Enter Symbol To Trade:') symbol = input() print('Are you skipping ordersend, and only sending an alert?\nY or N?') type_of_order = input() if type_of_order == 'Y' or type_of_order == 'y': type_of_order = 'skip' print('#Social Alerts Information#') tg = social() output = { "TelegramName": tg, "BotName": bot_name, "type": type_of_order } else: print('Enter type: (limit, market)') type_of_order = input() print('Enter name of bot to send order.') botname = input() print("Are you closing an open order?\nY or N") close = input() if close == 'Y' or close == 'y': amount = 'close' else: print( "Please enter a trade size (append U for USD, % for balance percent)" ) amount = input() print('Enter Side (buy or sell):') side = input() if type == 'limit': print('Enter limit price:') price = input() else: price = 'None' key = get_token() print('#Social Alerts Information#') tg = social() output = { "TelegramName": tg, "BotName": botname, "type": type_of_order, "side": side, "amount": amount, "symbol": symbol, "price": price, "key": key } print("Copy the below information into your TView alert:\n") print(str(output).replace('\'', '\"')) print('----') print('PLACE Telegram/Twitter ALERT INFO HERE')
def bungie_callback(): code = request.args.get('code') state = request.args.get('state') if auth.is_valid_state(state): session.pop('state_token', None) tokenResponse = auth.get_token(code) auth.save_session(tokenResponse) return redirect(url_for("dashboard")) else: abort(403)
def login(): """ Redirects to the proper login page (right now /google/login), but may change """ if (not google.authorized) or auth.get_token(request): return redirect(url_for("google.login")) else: resp = make_response( "Invalid credentials! Make sure you're logging in with your Choate account. <a href=\"/logout\">Try again.</a>" ) return resp
def perform_request(params, is_authenticated=True, url=constants.RTM_REST_URL): if is_authenticated: params['auth_token'] = auth.get_token() params['api_key'] = constants.API_KEY params['api_sig'] = auth.get_signature(params) response = requests.get(url, params=params) # print("Response:") # print(response.text) return ElementTree.fromstring(response.text)[0]
def main(): global TOKEN if not exist(TOKEN): TOKEN = get_token(APP_ID, SETTINGS, REDIRECT_URI, DISPLAY) else: vk = vkontakte.API(token=TOKEN) # http://vk.com/developers.php?oid=-1&p=messages.getDialogs uid = input() messages = vk.messages.getHistory(uid=uid, count='200') for elem in range(messages[0], 1, -1): msg = messages[elem]['body'].replace('<br>', '\n') print(msg)
def get_metric_data(self, endpoint, tenant, metric_list, payload, headers): #Generate Multiplot query to get metrics in list url = self.get_multi_endpoint(endpoint, tenant) if auth.is_active(): headers['X-Auth-Token'] = auth.get_token(False) r = requests.post(url, params=payload, data=json.dumps(metric_list), headers=headers) if r.status_code == 401 and auth.is_active(): headers['X-Auth-Token'] = auth.get_token(True) r = requests.post(url, params=payload, data=json.dumps(metric_list), headers=headers) if r.status_code != 200: print("get_metric_data failed; response: ", r.status_code, tenant, metric_list) return None else: return r.json()['metrics']
def webhook(): if request.method == 'POST': # Parse the string data from tradingview into a python dict data = parse_webhook(request.get_data(as_text=True)) # Check that the key is correct if get_token() == data['key']: print(' [Alert Received] ') print('POST Received:', data) send_order(data) return '', 200 else: abort(403) else: abort(400)
def webhook(): """Combine all functions in actions.py, and run flask server""" if request.method == 'POST': print('*' * 60) # Parse the string data from tradingview into a python dict data = parse_webhook(request.get_data(as_text=True))[0] tail = parse_webhook(request.get_data(as_text=True))[1] message = tail if (data['type'] != "Skip") and (get_token() == data['key']): # Check that the key is correct print(' [Alert Received] ') print(tail) for account, account_info in config.Accounts.items(): if account_info['Name'] in data['BotName']: exchange = ccxt.ftx({ 'apiKey': account_info['exchangeapi'], 'secret': account_info['exchangesecret'], 'enableRateLimit': True, }) if account_info['Subaccount'] == 'Yes': exchange.headers = { 'FTX-SUBACCOUNT': account_info['SubName'], } send_order(data, tail, exchange, account_info['Name'], account_info['Track']) if account_info['UseTelegram'] == 'Yes': send_to_telegram(tail, data) if account_info['UseTwitter'] == 'Yes': post_tweet(message) else: pass return '', 200 if data['type'] == "Skip": print(' [ALERT ONLY - NO TRADE] ') print(tail) for account, account_info in config.Accounts.items(): if account_info['Name'] in data['BotName']: if account_info['UseTelegram'] == 'Yes': send_to_telegram(tail, data) if account_info['UseTwitter'] == 'Yes': post_tweet(message) print('*' * 60, '/n') return '', 200 else: abort(400)
def main(artist): """ A flaw in the current random selection is that albums are all given equal weight meaning songs on large albums are less likely to be selected and singles will be played more often. I would like to fix this without making excessive API requests but am not sure this is possible. Another flaw is that duplicate albums are not filtered and singles are not discarded but this is probably not worth attempting to fix """ import auth token = auth.get_token() artist_id = get_artist_id(artist, token) album_id = get_random_album_id(artist_id, token) track_uri = get_random_track_uri(album_id, oauth_token) print(track_uri)
def webhook(): if request.method == 'POST': # Parse the string data from tradingview into a python dict data = parse_webhook(request.get_data(as_text=True)) # Check that the key is correct if get_token() == data['key']: logger.log("SIGNAL", "{} | Incoming Signal: {}", data['algo'], data['side']) process_alert(data) return '', 200 else: logger.error("Incoming Signal From Unauthorized User.") abort(403) else: abort(400)
def webhook(): if request.method == 'POST': # Parse the string data from tradingview into a python dict datas = parse_webhook(request.get_data(as_text=True)) print(datas) # Check that the key is correct if get_token() == datas['key']: print(' [Alert Received] ') print('POST Received/Updated Data:', datas) send_order(datas) return '', 200 else: logger.error("Incoming Signal From Unauthorized User.") abort(403) else: abort(400)
def webhook(): if request.method == 'POST': # Parse the string data from tradingview into a python dict data = parse_webhook(request.get_data(as_text=True)) # Check that the key is correct if get_token() == data['key']: print(' ---------- TradingView Alert Received!! ---------- ') if data['move'] == 'Long': send_long_order(data) set_trailing(data) else: #send_short_order(data) print("not shorting right now!") return '', 200 else: abort(403) else: abort(400)
def user_remove(token, u_id): ''' Removes a user from slackr Arguments: token and u_id of user to be removed Returns: empty dictionary, but the user is entirely removed. Exceptions: InputError: u_id is not a valid user AccessError: remover is not an admin Assumptions: removing the user means removing all traces of him including his messages ''' # verify the user if verify_token(token) is False: raise AccessError(description='Invalid token') data = get_store() # getting id of the user u_id_invoker = get_tokens()[token] # verify the invoker is an admin if not data.admins.is_admin(u_id_invoker): raise AccessError( description="You do not have permission to change permissions") if not data.users.user_exists(u_id): raise InputError(description="Invalid user id") # verify the admin is not removing himself if u_id == u_id_invoker: raise InputError(description='Cannot remove current user') # cannot remove the hangman bot if user_profile(token, u_id)['user']['name_first'] == 'Hangman': raise InputError(description='Cannot remove Hangman B0T') # removing his user details data.users.remove(u_id) # removing all his subscriptions to channels data.user_channel.remove_link_by_user(u_id) # removing all the messages sent by that user data.remove_messages(u_id) # remove the user the token store if he is logged on token = get_token(u_id) if token is not None: get_tokens().pop(token)
def search(): """ Searches for teacher meeting ids """ email, firstname, lastname = auth.check_login(request) if email and firstname and lastname: query = request.args.get('search') # ScheduleManager().createSchedule(email, firstname, lastname, check_teacher(email)) user_schedule = ScheduleManager().getSchedule(email, firstname, lastname, check_teacher(email)) user_schedule.init_db_connection() search_results = user_schedule.search_teacher(query) cards = "" for result in search_results: desc = result.get('office_desc') if desc is None: desc = "" result["office_desc"] = Markup( str(escape(desc)).replace("\n", "<br>")) cards += render_template("teacher_card.html", **result) commit = get_commit() calendar_token = auth.get_token(request) user_schedule.end_db_connection() return render_template("index.html", cards=Markup(cards), card_js="", commit=commit, calendar_token=calendar_token, email=email, firstname=firstname, lastname=lastname) else: return redirect("/")
def webhook(): if request.method == 'POST': # Parse the string data from tradingview into a python dict data = parse_webhook(request.get_data(as_text=True)) # Check that the key is correct if get_token() == data['token']: print(' [Alert Received] ') print('POST Received:', data) app.logger.info("POST Received:%s", data) if data['action'] == 'long' or data['action'] == 'short close': res = client.place_order('buy', 'XBTUSD', 2) return res[0].__str__(), 200 if data['action'] == 'short' or data['action'] == 'long close': res = client.place_order('sell', 'XBTUSD', 2) return res[0].__str__(), 200 else: abort(403) else: abort(400)
def export(): OK_SERVER = "https://okpy.org" ENDPOINT = f"/api/v3/course/{get_endpoint(course='cs61a')}/roster" FILE_PATH = "data/roster.csv" access_token = auth.get_token() print("Getting roster...") roster = requests.get( OK_SERVER + ENDPOINT, params={"access_token": access_token} ).json() if "roster" in roster["data"]: roster = roster["data"]["roster"] else: print(roster["message"]) sys.exit(1) print("Saving roster...") with open(FILE_PATH, "w") as f: f.write(roster) print("Done.")
def stop_content(self, content_id, encrypted=False): try: device_id = get_device_id() cookie = get_token() platform = 'PCTV' if not encrypted else vod_platform headers = { 'Accept': 'application/json', 'cookie': 'avs_cookie=' + cookie, 'User-Agent': 'Tnt/2.2.13.1908061505 CFNetwork/1107.1 Darwin/19.0.0' } url = 'https://apac.ti-platform.com/AGL/1.0/R/ENG/{platform}/TNTGO_LATAM_BR/CONTENT/USERDATA/VOD/{content_id}?bookmark={bookmark}&deltaThreshold={delta}&startDeltaTime=1&stopContent=Y&deviceId={device_id}&filter_brand=space%2Ctnts%2Ctnt'.format(platform=platform, content_id=content_id, device_id=device_id, bookmark=int(self.current_time), delta=int(self.current_time)) control.log('TNT GET ' + url) # control.log(headers) result = requests.get(url, headers=headers, proxies=proxy) control.log(result.status_code) control.log(result.content) except: control.log(traceback.format_exc(), control.LOGERROR)
def liveblog_request(context, method, uri, data=None, with_auth=True, token=None, add_server=True, **kwargs): # payload if not data: if 'text' in context: if context.text: data = process_common_templates(context.text, context) else: data = '' if isinstance(data, dict) or isinstance(data, list): data = json.dumps(data) # uri uri = process_common_templates(uri, context) # auth if 'headers' in kwargs: headers = kwargs.pop('headers') else: headers = {} if with_auth: if not token: if not context.token: context.token = get_token(session=context.session) token = context.token headers.update({'Authorization': token}) # request itself request(context, method, uri, data=data, headers=headers, add_server=add_server, **kwargs)
def export(): OK_SERVER = "https://okpy.org" ENDPOINT = f"/api/v3/course/{get_endpoint(course='cs61a')}/grades" FILE_PATH = "data/okpy_grades.csv" access_token = auth.get_token() print("Getting grades...") grades = requests.get(OK_SERVER + ENDPOINT, params={ "access_token": access_token }).json() if "grades" in grades["data"]: grades = grades["data"]["grades"] else: print(grades["message"]) sys.exit(1) print("Saving grades...") with open(FILE_PATH, "w") as f: f.write(grades) print("Done.")
def token_scopes(token_id): token = auth.get_token(token_id) if token is None: abort(404) data = request.get_json() if request.method == 'POST': client = token.client if 'scopes' in data: token.scopes = [x.encode('ascii') for x in data.get('scopes')] if 'client_name' in data and token.personal: print "setting client name to %s" % data.get('client_name') client.name = data.get('client_name') if token.personal: print "saving %s" % token.client.client_name client.save() token.save() d = token.to_dict() if token.personal: d.update(dict(client_name=token.client.name)) return jsonify(d)
def on_release(key): if key == keyboard.Key.scroll_lock: token = get_token() y = yadisk.YaDisk(token=token) if y.check_token() is False: token = reset_token() y = yadisk.YaDisk(token=token) filename = take_screen() try: yd.file_upload(y, get_image_save_path() + filename, yd.get_yd_dir() + filename) link = yd.publish(y, yd.get_yd_dir() + filename) clipboard.copy(link) notyfication.system_notify('Link copy to clipboard', link) except socket.timeout: write_log('Timeout error') if key == keyboard.Key.pause: # Stop listener return False
def export(): OK_SERVER = "https://okpy.org" ENDPOINT = "/api/v3/course/cal/{cc}/{sem}/grades".format(cc=COURSE_CODE, sem=SEMESTER) FILE_PATH = "data/okpy_grades.csv" access_token = auth.get_token() print("Getting grades...") grades = requests.get(OK_SERVER + ENDPOINT, params={ "access_token": access_token }).json() if "grades" in grades["data"]: grades = grades["data"]["grades"] else: print(grades["message"]) sys.exit(1) print("Saving grades...") with open(FILE_PATH, "w") as f: f.write(grades) print("Done.")
def notion_client() -> client.NotionClient: return client.NotionClient(token_v2=auth.get_token())
for d in data: d['startTime'] = time.mktime(d['startTime'].timetuple()) text, response = api_post('gsr/reservations', token, data = d) def delete_reservations(token, ids): ''' Delete GSR Reservations with `ids` of the user (`token`) Takes a list of `reservationId`s ''' for _id in ids: d = {'reservationId': _id} text, response = api_delete('gsr/reservations', token, data = d) if __name__ == '__main__': username = raw_input('Enter your UPenn login: '******'Password for %s: ' % username) token = auth.get_token(username, password) locations = get_locations(token) reservations = get_reservations(token) delete_reservations(token, [x['reservationId'] for x in reservations])
def list_tokens(): tokens = [auth.get_token(token_id) for token_id in rc.smembers("user|%s|tokens" % auth.current_user()) if token_id is not None] return render_template("tokens.html", tokens=tokens)
# The url of a specific project membership def project_membership_url(project_id, membership_id): return project_url(project_id) + 'memberships/' + str(membership_id) # The url of the all the stories in a project def stories_url(project_id): return project_url(project_id) + 'stories' # The url of a specific story def story_url(project_id, story_id): return project_url(project_id) + 'stories/' + str(story_id) # The url of all the labels on a story def story_labels_url(project_id, story_id): return story_url(project_id, story_id) + '/labels' # The url of one label on the story def story_label_url(project_id, story_id, label_id): return story_url(project_id, story_id) + '/labels/' + str(label_id) token_header = {'X-TrackerToken' : auth.get_token()} jsontype_header = {'Content-Type' : 'application/json'} all_headers = dict(token_header.items() + jsontype_header.items()) story_page_limit = 500 page_limit_header = 'X-Tracker-Pagination-Limit' page_offset_header = 'X-Tracker-Pagination-Offset' page_returned_header = 'X-Tracker-Pagination-Returned' page_total_header = 'X-Tracker-Pagination-Total'
import json import auth #初始化参数 cookie={} tokens={} username='' password='' verifycode='' codeString='' pubkey='' rsakey='' cookie = auth.get_BAIDUID() token = auth.get_token(cookie) tokens['token'] = token ubi = auth.get_UBI(cookie,tokens) cookie = auth.add_cookie(cookie,ubi,['UBI','PASSID']) key_data = auth.get_public_key(cookie,tokens) pubkey = key_data['pubkey'] rsakey = key_data['key'] username = raw_input('username:'******'password:'******'bdstoken'] = bdstoken
def index(): """ Will contain the default views for faculty, students, and teachers """ # if email := get_email(): email, firstname, lastname = auth.check_login(request) if email and firstname and lastname: # ScheduleManager().createSchedule(email, firstname, lastname, check_teacher(email)) user_schedule = ScheduleManager().getSchedule(email, firstname, lastname, check_teacher(email)) user_schedule.init_db_connection() # render_template here # log.info(Schedule().search_teacher_exact("Guelakis Patrick")) user_schedule.fetch_schedule() card_script = "" cards = "" toc = {'A': '', 'B': '', 'C': '', 'D': '', 'E': '', 'F': '', 'G': ''} # log.info(block_iter()) # if check_teacher(email): # uuid = secrets.token_hex(8) # cards += render_template("class_card.html") # card_script += render_template("card.js") top_label = "Today's Classes:" bottom_label = "Not Today" for block, start_time in block_iter(is_teacher=check_teacher(email)): if block == "Not Today": top_label = start_time + "'s Classes" bottom_label = "Not On " + start_time continue if block == "Break": cards += "<br><br><hr><br><h4>" + bottom_label + "</h4><br>" continue uuid = secrets.token_hex(8) schedule = None if block == "Office Hours": try: teacher = user_schedule.search_teacher_email_with_creation( user_schedule.email, user_schedule.lastname, user_schedule.firstname) schedule = { "block": "Office", "course": "Office Hours", "course_name": "Office Hours", "teacher_name": str(user_schedule.firstname).title() + " " + str(user_schedule.lastname).title(), "meeting_id": teacher['office_id'], "teacher_email": 'placeholder', "office_desc": teacher.get('office_desc') } if schedule['office_desc'] is None: schedule['office_desc'] = '' except TypeError as e: log_error( "Unable to create teacher schedule due to failed query" ) else: schedule = user_schedule.schedule[block] if schedule is None: continue elif not check_teacher(email): teacher = user_schedule.search_teacher_email( schedule["teacher_email"]) schedule["office_meeting_id"] = teacher.get('office_id') desc = teacher.get('office_desc') if desc is None: desc = "" schedule["office_desc"] = Markup( str(escape(desc)).replace("\n", "<br>")) schedule["user_can_change"] = not bool( teacher.get(schedule.get('block') + "_id")) else: schedule["user_can_change"] = True if len(block) == 1: # toc[block] = '<br><li><a href="#' + block + '-block">' + block + ' Block</a></li>' toc[block] = render_template("toc.html", block=block) schedule["uuid"] = uuid schedule["time"] = start_time if block == "Office Hours": schedule['office_desc'] = str( escape(str(schedule['office_desc']).replace( '\\', '\\\\'))).replace('\n', '\\n') cards += render_template("office_hours_card.html", **schedule) card_script += render_template("office_hours.js", **schedule) else: cards += render_template("class_card.html", **schedule) card_script += render_template("card.js", **schedule) commit = get_commit() calendar_token = auth.get_token(request) user_schedule.end_db_connection() response = make_response( render_template( "index.html", cards=Markup(cards), card_js=Markup(card_script), toc=Markup(toc['A'] + toc['B'] + toc['C'] + toc['D'] + toc['E'] + toc['F'] + toc['G']), top_label=top_label, calendar_token=calendar_token, email=email, firstname=str(firstname).title(), lastname=str(lastname).title(), refresh=True, commit=commit)) return auth.set_login(response, request) else: button = render_template("login.html") commit = get_commit() return render_template("landing.html", button=Markup(button), commit=commit)