def id_probe(_id): sql = f"SELECT * FROM msg WHERE id={_id}" db = Connection() try: return db.get(sql)[0][3] except IndexError: return None
def is_accepted(uid, tpuid): db = Connection() sql = f"""SELECT * FROM `friends` WHERE ((`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid}))""" try: return db.get(sql)[-1][3] == 1 except IndexError: return 501
def fetch_id(uid, tpuid): db = Connection() sql = f"""SELECT * FROM `friends` WHERE ((`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid}))""" try: return db.get(sql)[-1][0] except IndexError: return None
def ChangeAttr(self, node, val, uid): if (node == 'pwd'): val = hashlib.sha256(val.encode()).hexdigest() elif (node in ['uid', 'mid', 'id']): return False sql = "UPDATE users SET `%s`='%s' WHERE id=%s" % (node, val, uid) obj = Connection() return obj.set(sql)
def create(self, name, email, pwd): pwd = hashlib.sha256(pwd.encode()).hexdigest() sql = """ INSERT INTO users (name, email, pwd) VALUES ( '%s', '%s', '%s' ) """ % (name, email, pwd) obj = Connection() return obj.set(sql)
def login(self, email, pwd): _pwd = hashlib.sha256(pwd.encode()).hexdigest() sql = """ SELECT * FROM users WHERE email='%s' AND pwd='%s' """ % (email, _pwd) obj = Connection() if (obj.check(sql)): return obj.get(sql)[0] else: return False
def ChangeAttr(self, node, val, uid): if (node == 'pwd'): val = hashlib.sha256(val.encode()).hexdigest() elif (node in ['uid', 'mid', 'id']): return False if (type(val) == str): val = val.replace('\\', '\\\\').replace('\"', '\\\"').replace('\'', "\\\'") sql = "UPDATE users SET `%s`='%s' WHERE id=%s" % (node, val, uid) obj = Connection() return obj.set(sql)
def fetch_requests(uid): db = Connection() sql = f"SELECT * FROM `friends` WHERE `tpuid`={uid} AND flag=0" res = db.get(sql) ret = [] for i in res: ret.append({ 'id': i[0], 'uid': i[1], 'tpuid': i[2], 'sender': fetchName(i[1]), 'recv': fetchName(i[2]) }) return ret
def __init__(self): print("#> INITIALIZING STOCK API PIPELINE ") [self.sell,self.buy,self.trade] = [SellingConditions(),TradingConditions(),BuyingConditions()] self.notif = Notification() self.prev_hist = {} self.complist = pd.Series( open("symbols.txt", "r").readlines() ) # self.complist = pd.read_csv('companylist.csv') tolower = lambda x: x.lower().strip() # self.tickers = ['msft'] self.db = Connection() self.tickers = self.complist.apply( tolower ) th = Thread(target = self.main, args = ()) th.daemon = True th.start() print("### STOCK API PIPELINE RUNNING ON %s " % th)
def fetch_friend_request(uid): sql = f"SELECT * FROM `friends` WHERE (`tpuid`={uid} OR `uid`={uid}) AND flag=0" db = Connection() res = db.get(sql) ret = [] for i in res: ret.append({ 'id': i[0], 'uid': i[1], 'tpuid': i[2], 'sender': fetchName(i[1]), 'recv': fetchName(i[2]), 'datetime': i[4] }) return ret
def send(uid, tpuid): db = Connection() sql_0 = f"""SELECT * FROM `friends` WHERE (`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid}) AND flag=0""" sql_1 = f"""SELECT * FROM `friends` WHERE (`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid}) AND flag=1""" if (db.check(sql_0)): return -1 elif (db.check(sql_1)): return -3 sql = """ INSERT INTO `friends` (`uid`, `tpuid`) VALUES ( %s, %s ) """ % (uid, tpuid) return db.set(sql)
def friend_request( tpuid ): if 'uid' not in session: abort(501) _id = api.FriendRequest.fetch_id( session['uid'], tpuid ) if ( _id == None ): abort(501) state = api.FriendRequest.is_accepted( session['uid'], tpuid ) if ( state != False ): abort(501) if ( request.method == 'POST' ): obj = api.FriendRequest( _id, session['uid'] ) if (obj.accept( )): sock.emit( "new-friend", { 'msg': f"{session['name']} Just accepted your friend request", 'uid': tpuid, 'tpuid': session['uid'] }, broadcast = True ) return redirect( url_for('chats', tpuid = tpuid ) ) elif ( request.method == 'DELETE' ): obj = api.FriendRequest( _id, session['uid'] ) if ( obj.delete() ): return redirect( url_for( 'display_profile', tpuid = tpuid, key = 0 ) ) inf = account_api.info( tpuid, Connection() ) info = { 'uid': inf[0], 'name': inf[1], 'bio': inf[4] } return render_template( "request.html", info = info )
def compute_neighbors(data, uid, babcock_mode=False): if (type(data) == dict): dst = haversine(data, {'x': 0, 'y': 0}) else: dst = data if babcock_mode: sql = f"SELECT * FROM `users` WHERE `id`!={uid}" else: update = f"UPDATE `users` SET dfe={dst} WHERE `id`={uid}" sql = f"SELECT * FROM `users` WHERE ( dfe>={dst}-2 AND dfe<={dst}+2 ) AND `id`!={uid}" db = Connection() res = db.get(sql) ret = [] for i in res: ret.append({'tpuid': i[0], 'name': i[1], 'bio': i[4]}) # print(ret, "nnin") return ret, dst
def VsOb(uid, tpuid): # friendship status check db = Connection() sql_0 = f"""SELECT * FROM `friends` WHERE ((`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid})) AND flag=0""" sql_1 = f"""SELECT * FROM `friends` WHERE ((`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid})) AND flag=1""" sql_2 = f"""SELECT * FROM `friends` WHERE (`uid`={uid} AND `tpuid`={tpuid}) AND flag=0""" sql_3 = f"""SELECT * FROM `friends` WHERE (`uid`={tpuid} AND `tpuid`={uid}) AND flag=0""" if (db.check(sql_0)): if (db.check(sql_2)): return -10 else: return -11 return -1 elif (db.check(sql_1)): return -3 return 0
class Notifications: def __init__(self, uid): self.uid = uid self.db = Connection() def send(self, msg, link): sql = """ INSERT INTO notifications ( `uid`, `msg`, `link` ) VALUES ( %s, '%s', '%s' ) """ % (self.uid, msg, link) return self.db.set(sql) def fetch(self, spec="*"): sql = f"SELECT * FROM notifications WHERE `uid`={self.uid}" dat = self.db.get(sql) ret = [] for i in dat: ret.append({ 'id': i[0], 'msg': i[2], 'link': i[3], 'seen': i[4], 'datetime': i[5] }) return ret def see(self, _id): sql = f"UPDATE notifications SET `seen`=1 WHERE `id`={_id} AND `uid`={self.uid}" return self.db.set(sql) @staticmethod def super_see(uid, link=""): db = Connection() sql = f"UPDATE notifications SET `seen`=1 WHERE `link`='{link}' AND `uid`={uid}" return db.set(sql) @staticmethod def super_pop(uid, link=""): db = Connection() sql = f"DELETE FROM notifications WHERE `link`='{link}' AND `uid`={uid}" return db.set(sql)
def display_profile( tpuid, key ): if 'uid' not in session: abort(501) inf = account_api.info( tpuid, Connection() ) info = { 'uid': inf[0], 'name': inf[1], 'bio': inf[4] } uid = session['uid'] vsob = api.FriendRequest.VsOb(uid, tpuid) if ( int(key) == 0 ): if ( vsob == -11 ): return redirect( url_for('friend_request', tpuid = tpuid) ) elif ( vsob == -3 ): return redirect( url_for( 'chats', tpuid = tpuid ) ) return render_template( "view-profile.html", info = info, vsob = vsob )
def fetch_friends(uid): db = Connection() sql = f"SELECT * FROM `friends` WHERE (`uid`={uid} OR `tpuid`={uid}) AND flag=1" res = db.get(sql) ret = [] for i in res: if (uid == i[1]): ret.append({ 'id': i[0], 'uid': i[1], 'tpuid': i[2], 'prober': i[2], 'name': fetchName(i[2]) }) else: ret.append({ 'id': i[0], 'uid': i[1], 'prober': i[1], 'tpuid': i[2], 'name': fetchName(i[1]) }) return ret
def shell(): BaseModel.install() db = Connection("172.31.15.206:3306", "admin", "pitayagames", "cUycN6&$") msgs = db.query( "SELECT * FROM adm_message where status = 1 and intask = 0 limit 1") for msg in msgs: db.execute("update adm_message set intask = 1 where msgid = %d" % (msg.get("msgid"))) if msg.get("send_all", 0) == 1: if msg.get("self_invoke", 0) == 1: yield msg_send(msg.get("msgtype", ""), "ALL_INVOKE") else: yield fetch_uids(msg.get("msgtype", "")) else: user_id = msg.get("target", "") userids = user_id.split(",") for uid in userids: yield msg_send(msg.get("msgtype", ""), uid) db.execute("update adm_message set status = 2 where msgid = %d" % (msg.get("msgid"))) db.close()
def info(uid, adapter=Connection()): sql = f"SELECT `name`,`bio`,`imageURL`,`dfe` FROM users WHERE `uid`='{uid}'" cols = ['name', 'bio', 'imageURL', 'dfe'] dat = list(adapter.getone(sql)) print(dat) res = dict() while True: try: res[cols.pop()] = dat.pop() except IndexError: break return res
def __init__(self, uid, db=Connection()): self.uid = uid self.db = db
def __init__(self, obj=Connection()): self.obj = obj
def name(uid): db = Connection() sql = f"SELECT `name` FROM users WHERE `uid`='{uid}'" return db.getone(sql)[0]
def fetchName(uid): return Connection().get(f"SELECT * FROM `users` WHERE id={uid}")[0][1]
class Watch: def __init__(self): print("#> INITIALIZING STOCK API PIPELINE ") [self.sell,self.buy,self.trade] = [SellingConditions(),TradingConditions(),BuyingConditions()] self.notif = Notification() self.prev_hist = {} self.complist = pd.Series( open("symbols.txt", "r").readlines() ) # self.complist = pd.read_csv('companylist.csv') tolower = lambda x: x.lower().strip() # self.tickers = ['msft'] self.db = Connection() self.tickers = self.complist.apply( tolower ) th = Thread(target = self.main, args = ()) th.daemon = True th.start() print("### STOCK API PIPELINE RUNNING ON %s " % th) def main(self, stock = "*"): run_event = Event() run_event.set() while True: try: for i in self.tickers: try: ticker = yf.Ticker(i) hist = ticker.history(period = "min") except: continue # hist = pd.read_csv("ext/dat.csv") hist.pop("Volume") if (i not in self.prev_hist): if ( len(hist) > 0 ): self.resolve_movers(hist, i) self.prev_hist[i] = hist.iloc[-1].to_dict() else: self.handle_delisted( i ) else: if ( hist.iloc[-1].to_dict() != self.prev_hist[i] ): if ( len(hist) > 0 ): self.resolve_movers(hist, i) self.prev_hist[i] = hist.iloc[-1].to_dict() else: self.handle_delisted( i ) except KeyboardInterrupt: print("#> TERMINATING STOCK API PIPELINE... ") run_event.clear() print("### TERMINATION SUCCESSFUL ") sys.exit() except requests.exceptions.ConnectionError: print("### COULD NOT CONNECT TO STOCK MARKET API\n#> RETRYING... ") def handle_delisted(self, symbol = ""): # method to resolve those that have seen their conditions # info = ticker.info selling = self.exec_delisted( 'sell',symbol ) buying = self.exec_delisted( 'buy', symbol ) trading = self.exec_delisted( 'trade', symbol ) # print("Sellers: ", selling) # print("Buyers: ", buying) # print("Others: ", trading) t1 = Thread(target = self.notif.bulk, args = (selling, symbol, 'delisted')) t1.start() t2 = Thread(target = self.notif.bulk, args = (buying, symbol, 'delisted')) t2.start() t3 = Thread(target = self.notif.bulk, args = (trading, symbol, 'delisted')) t3.start() def resolve_movers(self, req, symbol = ""): # method to resolve those that have seen their conditions # info = ticker.info selling = self.exec_sql( 'sell', req, symbol ) buying = self.exec_sql( 'buy', req, symbol, 'less' ) trading = self.exec_sql( 'trade', req, symbol, 'equal' ) # print("Sellers: ", selling) # print("Buyers: ", buying) # print("Others: ", trading) t1 = Thread(target = self.notif.bulk, args = (selling, symbol, 'selling')) t1.start() t2 = Thread(target = self.notif.bulk, args = (buying, symbol, 'buying')) t2.start() t3 = Thread(target = self.notif.bulk, args = (trading, symbol, 'trade')) t3.start() def exec_delisted(self, tbl, symb): sql = f"SELECT `uid` FROM `%s` WHERE `name`='{symb}'" % tbl try: uids = self.db.get(sql) self.db.set(f"DELETE FROM `%s` WHERE `name`='{symb}'" % tbl) return uids except Exception as e: raise e def exec_sql( self, tbl, req, symbol, arith_meth = "greater" ): if ( arith_meth == "greater" ): sql = """ SELECT `uid` FROM `%s` WHERE `open`<=%s AND close<=%s AND high<=%s AND low<=%s AND dividends<=%s AND splits<=%s AND name='%s' """ % ( tbl, req.Open.iloc[-1], req.Close.iloc[-1], req.High.iloc[-1], req.Low.iloc[-1], req.Dividends.iloc[-1], req['Stock Splits'].iloc[-1], symbol ) elif ( arith_meth == "less" ): sql = """ SELECT `uid` FROM `%s` WHERE `open`>=%s AND close>=%s AND high>=%s AND low>=%s AND dividends>=%s AND splits>=%s AND name='%s' """ % ( tbl, req.Open.iloc[-1], req.Close.iloc[-1], req.High.iloc[-1], req.Low.iloc[-1], req.Dividends.iloc[-1], req['Stock Splits'].iloc[-1], symbol ) elif ( arith_meth == "equal" ): sql = """ SELECT `uid` FROM `%s` WHERE `open`=%s AND close=%s AND high=%s AND low=%s AND dividends=%s AND splits=%s AND name='%s' """ % ( tbl, req.Open.iloc[-1], req.Close.iloc[-1], req.High.iloc[-1], req.Low.iloc[-1], req.Dividends.iloc[-1], req['Stock Splits'].iloc[-1], symbol ) try: return self.db.get( sql ) except Exception as e: print(req) raise e
def name(uid): db = Connection() sql = f"SELECT * FROM users WHERE id={uid}" return db.get(sql)[0][1] if db.check(sql) == True else "Anonymous"
def super_pop(uid, link=""): db = Connection() sql = f"DELETE FROM notifications WHERE `link`='{link}' AND `uid`={uid}" return db.set(sql)
def super_see(uid, link=""): db = Connection() sql = f"UPDATE notifications SET `seen`=1 WHERE `link`='{link}' AND `uid`={uid}" return db.set(sql)
class FriendRequest: def __init__(self, _id, uid): self.uid = uid self._id = _id self.db = Connection() @staticmethod def send(uid, tpuid): db = Connection() sql_0 = f"""SELECT * FROM `friends` WHERE (`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid}) AND flag=0""" sql_1 = f"""SELECT * FROM `friends` WHERE (`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid}) AND flag=1""" if (db.check(sql_0)): return -1 elif (db.check(sql_1)): return -3 sql = """ INSERT INTO `friends` (`uid`, `tpuid`) VALUES ( %s, %s ) """ % (uid, tpuid) return db.set(sql) @staticmethod def VsOb(uid, tpuid): # friendship status check db = Connection() sql_0 = f"""SELECT * FROM `friends` WHERE ((`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid})) AND flag=0""" sql_1 = f"""SELECT * FROM `friends` WHERE ((`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid})) AND flag=1""" sql_2 = f"""SELECT * FROM `friends` WHERE (`uid`={uid} AND `tpuid`={tpuid}) AND flag=0""" sql_3 = f"""SELECT * FROM `friends` WHERE (`uid`={tpuid} AND `tpuid`={uid}) AND flag=0""" if (db.check(sql_0)): if (db.check(sql_2)): return -10 else: return -11 return -1 elif (db.check(sql_1)): return -3 return 0 @staticmethod def fetch_requests(uid): db = Connection() sql = f"SELECT * FROM `friends` WHERE `tpuid`={uid} AND flag=0" res = db.get(sql) ret = [] for i in res: ret.append({ 'id': i[0], 'uid': i[1], 'tpuid': i[2], 'sender': fetchName(i[1]), 'recv': fetchName(i[2]) }) return ret @staticmethod def is_accepted(uid, tpuid): db = Connection() sql = f"""SELECT * FROM `friends` WHERE ((`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid}))""" try: return db.get(sql)[-1][3] == 1 except IndexError: return 501 @staticmethod def fetch_id(uid, tpuid): db = Connection() sql = f"""SELECT * FROM `friends` WHERE ((`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid}))""" try: return db.get(sql)[-1][0] except IndexError: return None def accept(self): sql = f"UPDATE `friends` SET `flag`=1 WHERE id={self._id} AND `tpuid`={self.uid}" return self.db.set(sql) def delete(self): sql = f"DELETE FROM `friends` WHERE `id`={self._id} AND (`uid`={self.uid} OR `tpuid`={self.uid})" return self.db.set(sql)
def __init__(self, _id, uid): self.uid = uid self._id = _id self.db = Connection()
class Messenger: def __init__(self, uid): self.uid = uid self.db = Connection() def send_message(self, msg, tpuid, _id, date_sent, quoted=0): msg = msg.replace('\\', '\\\\').replace('\"', '\\\"').replace('\'', "\\\'") # msg = json.dumps( msg ) sql = """ INSERT INTO msg ( `id`,`uid`, `tpuid`, `msg`, `quoted`, `date-sent`) VALUES (%s, %s, %s, '%s', '%s', '%s') """ % (_id, self.uid, tpuid, msg, quoted, date_sent) return self.db.set(sql) def room_id(self, tpuid): uid = self.uid sql = f"SELECT id FROM friends WHERE (tpuid={tpuid} OR `uid`={tpuid}) AND (`uid`={uid} OR tpuid={uid})" return self.db.get(sql)[0][0] def delete_message(self, _id): sql = f"DELETE FROM msg WHERE id={_id} AND `uid`={self.uid}" return self.db.set(sql) def see(self, tpuid): sql = f"UPDATE msg SET seen=1 WHERE `tpuid`={self.uid} AND `uid`={tpuid}" return self.db.set(sql) def seen(self, tpuid): sql = f"SELECT * FROM msg WHERE `tpuid`={tpuid}" try: return self.db.get(sql)[-1][5] == 1 except IndexError: return False def fetch_msg(self, tpuid, _id=0, fil=0): if (tpuid != '*'): sql = f"SELECT * FROM msg WHERE (`uid`={self.uid} AND `tpuid`={tpuid}) OR (`tpuid`={self.uid} AND `uid`={tpuid}) AND id>={_id}" else: sql = f"SELECT * FROM msg WHERE (`uid`={self.uid} OR `tpuid`={self.uid}) AND id>={_id}" res = self.db.get(sql) ret = [] for i in res: filtered = i[3] offensive = json.load(open("extras/offensive.json", "r")) for j in offensive: filtered = filtered.replace(j, offensive[j]) ret.append({ 'id': i[0], 'uid': i[1], 'msg': i[3], 'filtered': filtered, 'quoted': Messenger.id_probe(i[4]), 'seen': i[5] == 1, 'date-sent': i[6] }) return ret @staticmethod def id_probe(_id): sql = f"SELECT * FROM msg WHERE id={_id}" db = Connection() try: return db.get(sql)[0][3] except IndexError: return None