def xFollow(id: str, status: str): """ @param id = the followee user who the currently-logged-in user is following or unfollowing @param status = following status, 0=unfollow, 1=follow """ makeFollowing = (status == "1") cun = currentUserName() dpr("id=%r status=%r cun=%r", id, status, cun) if not cun: return "{}" cu = User.getDoc(cun) if not cu: return "{}" followee = User.getDoc(id) if not followee: return "{}" ai = models.getAccountInfo(cun) followingSet = set(ai.following_ids) if makeFollowing: followingSet2 = followingSet | set([id]) else: followingSet2 = followingSet - set([id]) if followingSet2 != followingSet: ai.following_ids = list(followingSet2) ai.save() return "{}"
def add_user(self, message=None, name=None): logging.debug( "processing 'add ytmt user' command" ) new_user = User() im_from = db.IM("xmpp", message.sender) new_user.google_id = im_from.address.split('/')[0] new_user.ytmt_id = name new_user.put() logging.debug( "Added " + name + " for : " + new_user.google_id ) message.reply("Added user '" + name + "'. Alerts for '" + name + "' will be sent to: " + new_user.google_id + ".")
def done(self): #make sure the user doesn't already exist u = User.by_name(self.username) if u: msg = 'That user already exists.' self.render('signup-form.html', error_username = msg) else: u = User.register(self.username, self.password, self.email) u.put() self.login(u) self.redirect('/welcome')
def add_user(self, message=None, name=None): logging.debug( "processing 'add user' command" ) if len(message.arg.split()) > 1: name = message.arg.strip().split()[1] new_user = User() im_from = db.IM("xmpp", message.sender) new_user.google_id = im_from.address.split('/')[0] new_user.ytmt_id = name new_user.put() logging.debug( "Added " + name + " for : " + new_user.google_id ) message.reply("Added user '" + name + "'. Alerts will be sent to: " + new_user.google_id + ".") else: message.reply("No name given.\nSyntax: add {ytmt-user}")
def signup_page(): form=registirationForm() if request.method =='POST': if form.validate_on_submit(): crypt_password=bcrypt.generate_password_hash(form.password.data).decode('utf-8') #creating hashed password flash(f'Account Created for {form.username.data}! Now You Can Login.', 'success') user=User(name=form.name.data, surname=form.surname.data, username=form.username.data, mail=form.mail.data, gender=form.gender.data, date=form.date.data, password=crypt_password) user.adduser() return redirect(url_for('login_page')) else: flash(f'Failed to Create Account for {form.username.data}!', 'danger') return render_template("signup.html", form=form)
def handleflair(r: praw.Reddit, user: praw.models.Redditor, db: Database) -> None: """ Give the user a new flair if they do not have one. """ if (user.name == "AutoModerator"): return if next(r.subreddit("cash4cash").flair( redditor=user))['flair_text'] is None: u = User(user.name.lower(), 0) db.add(u) praw.models.reddit.subreddit.SubredditFlair( r.subreddit("cash4cash")).set(user.name, "0 trust pts | New Trader") user.message( "Welcome to Cash4Cash!", "Hello! Welcome to r/Cash4Cash! You have been given this message because it appears you do not have a flair yet." + " Please read this message in its entirety!\n\n" + "- There's no need for either party to go first if you don't want to. Our [escrow bot](https://reddit.com/r/Cash4Cash/wiki/index/escrow)" + " can securely hold cryptocurrency so neither party runs away with the money, preventing the most common type of scam. The bot works with BTC, BCH, LTC, ETH, and DOGE." + "\n- Read our [Beginner's Guide](http://redd.it/pe8b4j) for tips on how to format posts, get rep, and avoid scams!" + "\n- Insist everyone you deal with comment somewhere on r/Cash4Cash to prove they aren't banned. Be sure to check the [Universal Scammer List](https://universalscammerlist.com), " + " which lists out every known scammer on Reddit. WE BAN SCAMMERS. If you have been scammed, message the moderators immediately with evidence." + "\n\nIf you have any questions, feel free to contact the moderators!" + config.signature) journal("User" + user.name + " was given a new flair")
def my_txn(): test_username = self.user.name self.write('<br>username is: ' + test_username) user = User.by_name(test_username) self.write('<br>user.id() is: ' + str(user.key().id())) # FOR DELETING delete_for_user(self, test_username) omlet1 = Omlet.make_omlet(test_username, 'amy1') if omlet1: omlet1.put() self.write('<br><br>put in omlet called "amy1" ') self.write('<br>list of omlets for this user is ' + string_list_omlet(Omlet.list_username(test_username))) self.write('<br>look, the omlet exists: ' + string_omlet(Omlet.by_name('amy1'))) self.write('<br><br>this should be empty: ' + string_list_bite(Bite.list_omlet_until_number('amy1', None))) make_bite_noduplicate('amy1', 'Bite AAAAA') make_bite_noduplicate('amy1', 'This is bite B of omlet1') self.write('<br>this should have two bites: ' + string_list_bite(Bite.list_omlet_until_number('amy1', None))) make_bite_noduplicate('amy1', 'Bite C') make_bite_noduplicate('amy1', 'Bite D, yay') make_bite_noduplicate('amy1', 'Nom, Bite E') self.write('<br><br> want up to bite C: ' + string_list_bite(Bite.list_omlet_until_number('amy1', 3))) self.write('<br> want bite D only: ' + string_bite(Bite.by_omlet_number('amy1', 4)))
def my_txn(): test_username = self.user.name self.write('<br>username is: ' + test_username) print('username is: ' + test_username) user = User.by_name(test_username) self.write('<br>user.id() is: ' + str(user.key().id())) print('user.id() is: ' + str(user.key().id())) # FOR DELETING delete_for_user(self, test_username) omlet1 = Omlet.make_omlet(test_username, 'amy1') print('omletparent', omlet1.parent().key().id()); print('user', user.key().id()) print('omlet:' + omlet1.name) key1 = omlet1.put() print('omlet1 newkey:', key1.id()) omlet2 = Omlet.get_by_id(key1.id(), parent = user, read_policy = db.STRONG_CONSISTENCY) print('omlet2: ' + omlet2.name) self.write('<br><br>put in omlet called "amy1" ') self.write('<br>list of omlets for this user is ' + string_list_omlet(Omlet.list_username(test_username))) self.write('<br>look, the omlet exists: ' + string_omlet(Omlet.by_name('amy1'))) self.write('<br><br>this should be empty: ' + string_list_bite(Bite.list_omlet_until_number('amy1', None))) make_bite_noduplicate('amy1', 'Bite AAAAA') make_bite_noduplicate('amy1', 'This is bite B of omlet1') self.write('<br>this should have two bites: ' + string_list_bite(Bite.list_omlet_until_number('amy1', None))) make_bite_noduplicate('amy1', 'Bite C') make_bite_noduplicate('amy1', 'Bite D, yay') make_bite_noduplicate('amy1', 'Nom, Bite E') self.write('<br><br> want up to bite C: ' + string_list_bite(Bite.list_omlet_until_number('amy1', 3))) self.write('<br> want bite D only: ' + string_bite(Bite.by_omlet_number('amy1', 4)))
def initialize(self, *a, **kw): webapp2.RequestHandler.initialize(self, *a, **kw) uid = self.read_secure_cookie('user_id') self.user = uid and User.by_id(int(uid)) if self.request.url.endswith('.json'): self.format = 'json' else: self.format = 'html'
def post(self): username = self.request.get('username') password = self.request.get('password') u = User.login(username, password) if u: self.login(u) self.redirect('/welcome') else: msg = 'Invalid login' self.render('login-form.html', error = msg)
def followerMess(id): user = User.getDoc(id) lf = FollowerFormatter(id) tem = jinjaEnv.get_template("followerMess.html") h = tem.render( id=id, user=user, lf=lf, ) return h
def userListTableH(pag): h = USER_INFO_TABLE_HEADER users = User.find( skip=pag.skip, # skip this number of docs before returning some limit=pag.numShow, # max number of docs to return sort='_id') for u in users: h += userInfoLine(u._id) #//for h += "</table>\n" return h
def userList(): """ list all users """ count = User.count() pag = paginate.Paginator(count) tem = jinjaEnv.get_template("userList.html") h = tem.render( count=count, pag=pag, table=userListTableH(pag), ) return h
def make_omlet(cls, user_name, name): user = User.by_name(user_name) if not user: print('Tried to make Omlet - User does not exist.') return None omlet = Omlet.by_name(name) if omlet: print('Tried to make Omlet - Omlet already exists.') return None return Omlet(parent = user, name = name, user_id = user.key().id())
def omlet_bite_test(self): test_username = self.user.name self.write('<br>username is: ' + test_username) user = User.by_name(test_username) self.write('<br>user.id() is: ' + str(user.key().id())) # # FOR DELETING # delete_for_user(self, test_username) omlet1 = Omlet.make_omlet(test_username, 'first') if omlet1: omlet1.put() time.sleep(0.5) self.write('<br><br>put in omlet called "first" ') self.write('<br>list of omlets for this user is ' + string_list_omlet(Omlet.list_username(test_username))) self.write('<br>look, the omlet exists: ' + string_omlet(Omlet.by_name('first'))) self.write('<br><br>this should be empty: ' + string_list_bite(Bite.list_omlet_until_number('first', None))) make_bite_noduplicate('first', 'Bite AAAAA') time.sleep(0.5) make_bite_noduplicate('first', 'This is bite B of omlet1') time.sleep(0.5) self.write('<br>this should have two bites: ' + string_list_bite(Bite.list_omlet_until_number('first', None))) make_bite_noduplicate('first', 'Bite C') time.sleep(0.5) make_bite_noduplicate('first', 'Bite D, yay') time.sleep(0.5) make_bite_noduplicate('first', 'Nom, Bite E') time.sleep(0.5) self.write('<br><br> want up to bite C: ' + string_list_bite(Bite.list_omlet_until_number('first', 3))) self.write('<br> want bite D only: ' + string_bite(Bite.by_omlet_number('first', 4))) Bite.set_eaten('first', 2) time.sleep(0.5) self.write('<br>has bite B been eaten? should be yes: ' + string_bite(Bite.by_omlet_number('first', 2))) omlet2 = Omlet.make_omlet(test_username, 'second') if omlet2: omlet2.put() time.sleep(0.5) omlet3 = Omlet.make_omlet(test_username, 'third') if omlet3: omlet3.put() time.sleep(0.5) omlet4 = Omlet.make_omlet(test_username, 'fourth') if omlet4: omlet4.put() time.sleep(0.5) self.write('<br><br>list of omlets for this user should have 4: ' + string_list_omlet(Omlet.list_username(test_username)))
def listFollowers(id): """ list of people who follow (id) """ user = User.getDoc(id) count = models.AccountInfo.count({'following_ids': id}) pag = paginate.Paginator(count) tem = jinjaEnv.get_template("listFollowers.html") h = tem.render( id=id, user=user, count=count, pag=pag, table=followersTableH(id, pag), ) return h
def listFollowing(id): """ list of people who follow (id) """ user = User.getDoc(id) ai = models.getAccountInfo(id) count = len(ai.following_ids) pag = paginate.Paginator(count) tem = jinjaEnv.get_template("listFollowing.html") h = tem.render( id=id, user=user, ai=ai, count=count, pag=pag, table=followingTableH(ai, pag), ) return h
def __init__(self, h2x, jid: JID): self.h2x = h2x self.jid = jid self.user = User(jid.userhost()) self.state = State.disconnected self.targetState = State.disconnected self.thread = None self.loop = None self.client = None self.userList = None # Track connected instances of XMPP clients, for presence control self.xmppClients = set() if not self.user.token: raise UserNotRegistered(jid) self.h2x.sendPresence(self.jid, "unavailable", "Client wrapper created")
def blog(id): user = User.getDoc(id) ai = models.getAccountInfo(id) lf = BlogFormatter(id) numPosts = models.Message.count({'author_id': id}) numHeadPosts = models.Message.count({ 'author_id': id, 'replyTo_id': { '$in': [None, ''] }, }) numFollowing = len(ai.following_ids) numFollowers = models.AccountInfo.count({'following_ids': id}) cun = currentUserName() if not cun: # not logged in, so no follow button followButton = "" else: if models.follows(cun, id): # follows, so unfollow button followButton = "unfollow" else: # doesn't currently follow, so follow button followButton = "follow" dpr("followButton=%r", followButton) tem = jinjaEnv.get_template("blog.html") h = tem.render( id=id, idJson=json.dumps(id), user=user, ai=ai, blogTitle=ai.asReadableH('title'), name=ai.asReadableH('realName'), bio=ai.bioHtml, numPosts=numPosts, numHeadPosts=numHeadPosts, numFollowing=numFollowing, numFollowers=numFollowers, followButton=followButton, lf=lf, ) return h
def accountSettings(): cun = currentUserName() dpr("id=%r cun=%r", id, cun) #if id != cun: # return http403() user = User.getDoc(cun) ai = models.getAccountInfo(cun) msg = "" if request.method=='POST': ai = ai.populateFromRequest(request) ai.save() msg = "Saved account settings" #//if tem = jinjaEnv.get_template("accountSettings.html") h = tem.render( user = user, ai = ai, msg = ht.goodMessageBox(msg), ) return h
class ClientWrapper: def __init__(self, h2x, jid: JID): self.h2x = h2x self.jid = jid self.user = User(jid.userhost()) self.state = State.disconnected self.targetState = State.disconnected self.thread = None self.loop = None self.client = None self.userList = None # Track connected instances of XMPP clients, for presence control self.xmppClients = set() if not self.user.token: raise UserNotRegistered(jid) self.h2x.sendPresence(self.jid, "unavailable", "Client wrapper created") # Provides token if refresh fails # Would be nice to ask user for token def getToken(self): return self.user.token def connect(self): self.targetState = State.connected if self.state == State.disconnected: self.state = State.connecting print("Connect!!!") self.thread = threading.Thread(target=self.clientBody) self.thread.start() self.sendPresence() def disconnect(self): self.targetState = State.disconnected if self.state == State.connected: self.state == State.disconnecting print("Disconnect!!!") self.sendPresence() try: future = asyncio.async(self.client.disconnect(), loop=self.loop) future.add_done_callback(lambda future: print("Disconnect done")) except Exception as e: print("Disconnect failed: ", e) self.sendPresence() def stateUpdate(self, current: State = None): if current: self.state = current print("StateSwitch: now: " + self.state.__str__() + " want: " + self.targetState.__str__()) if self.targetState == State.connected and self.state == State.disconnected: self.connect() if self.targetState == State.disconnected and self.state == State.connected: self.disconnect() self.sendPresence() def clientBody(self): # Initialize asyncio loop for this thread self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) # Get oauth2 cookies self.h2x.sendPresence(self.jid, "unavailable", "Getting cookies") cookies = hangups.auth.get_auth(self.getToken, self.user.tokenRefreshPath()) # Create client self.h2x.sendPresence(self.jid, "unavailable", "Initializing client") self.client = hangups.Client(cookies) # Add state change observers self.client.on_connect.add_observer(self.onConnect) self.client.on_disconnect.add_observer(self.onDisconnect) self.client.on_reconnect.add_observer(self.onReconnect) self.client.on_state_update.add_observer(self.onStateUpdate) # Connect and run client self.sendPresence() # This will return when connection ends try: print("Running in loop") self.loop.run_until_complete(self.client.connect()) print("Loop done") finally: self.loop.close() # Notify about client termination, resolve possible requested state change self.stateUpdate(State.disconnected) print("Client thread terminates") @asyncio.coroutine def onConnect(self): print("Connected!") self.state = State.connected self.h2x.sendPresence(self.jid, "available", "Online") self.userList, self.convList = (yield from hangups.build_user_conversation_list(self.client)) self.convList.on_event.add_observer(self.onEvent) yield from self.updateParticipantPresence() self.stateUpdate() # Test presence setting print("Trying to set presence") # print("PresenceStateSettings:") # pprint(vars(hangups.hangouts_pb2.PresenceStateSetting)) # print("DND settings") # pprint(vars(hangups.hangouts_pb2.DndSetting)) # print("DesktopOff") # pprint(vars(hangups.hangouts_pb2.DesktopOffSetting)) # print("Mood") # pprint(vars(hangups.hangouts_pb2.MoodSetting)) # ClientPresenceStateType # setPresenceRequest = hangups.hangouts_pb2.SetPresenceRequest( # presence_state_setting = hangups.hangouts_pb2.PresenceStateSetting( # timeout_secs = 30, # type = 0 # ), # dnd_setting = hangups.hangouts_pb2.DndSetting( # do_not_disturb = 0, # timeout_secs = 30 # ), # desktop_off_setting = hangups.hangouts_pb2.DesktopOffSetting( # desktop_off = 0 # ) # ) ## ,mood_setting = hangups.hangouts_pb2.MoodSetting( ## mood_message = hangups.hangouts_pb2.MoodMessage( ## mood_content = "Online" ## ) ## ) ## #hangups.hangouts_pb2.ClientPresenceStateType._enum_type.values[0], # asyncio.async(self.client.set_presence(setPresenceRequest), loop=self.loop) # print("Presence set started") @asyncio.coroutine def updateParticipantPresence(self): print("Sending presence for hangouts users") # Guard for empty user list (possibly not yet connected client) if not self.userList: return # Create list of all participants participants = [] for user in self.userList.get_all(): if not user.is_self: participant = hangups.hangouts_pb2.ParticipantId(gaia_id=user.id_.gaia_id, chat_id=user.id_.chat_id) participants.append(participant) # If we are supposed to be connected, query state if self.targetState == State.connected: # Create presence request req = hangups.hangouts_pb2.QueryPresenceRequest( participant_id=iter(participants), field_mask=iter([1, 2, 7]), # All fields (reachable, available, device) ) # Send the request resp = yield from asyncio.async(self.client.query_presence(req), loop=self.loop) # Process presence from result presences = resp.presence_result for presence in presences: if presence.presence.reachable: state = "available" else: state = "unavailable" if presence.presence.available: show = "xa" else: show = None self.h2x.sendPresence(self.jid, state, source=self.participant2JID(presence.user_id), show=show) else: # If we are disconnected just say everybody is disconnected for participant in participants: self.h2x.sendPresence(self.jid, "unavailable", source=self.participant2JID(participant)) # Check if uses is in contact list def isSubscribed(self, jid: JID): user = self.JID2Hang(jid) if self.userList.get_user(user): return True else: return False # Send current presence to jabber client def sendPresence(self): if self.state == State.disconnected: self.h2x.sendPresence(self.jid, "unavailable", "Client disconnected") elif self.state == State.connecting: self.h2x.sendPresence(self.jid, "unavailable", "Client connecting...") elif self.state == State.connected: self.h2x.sendPresence(self.jid, "available", "Client connected") elif self.state == State.disconnecting: self.h2x.sendPresence(self.jid, "available", "Client disconnecting...") if self.loop and not self.loop.is_closed(): asyncio.async(self.updateParticipantPresence(), loop=self.loop) def getUser(self, jid: JID): uid = self.JID2Hang(jid) return self.userList.get_user(uid) # Import Hangouts contacts to jabber def importContacts(self): print("Importing contacts") for user in self.userList.get_all(): if user.is_self == False: self.h2x.sendPresence(self.jid, "subscribe", source=self.hang2JID(user), nick=user.full_name) @asyncio.coroutine def onDisconnect(self): print("Disconnected") self.stateUpdate(State.disconnected) @asyncio.coroutine def onReconnect(self): print("Reconnected") self.stateUpdate(State.connected) @asyncio.coroutine def onStateUpdate(self, state: hangups.hangouts_pb2.StateUpdate): print("StateUpdate:" + state.__str__()) # TODO: This is stupid but works, we would like to update only changed presence try: yield from self.updateParticipantPresence() except Exception as e: print("Update participant presence failed with exception " + str(e)) print("Forcing reconnect") self.stateUpdate(State.disconnected) def ids2JID(self, chat_id: str, gaia_id: str): return chat_id + "." + gaia_id + "@" + self.h2x.config.JID def participant2JID(self, participant: hangups.user): return JID(self.ids2JID(participant.chat_id, participant.gaia_id)) def hang2JID(self, hangUser: hangups.user): return JID(self.ids2JID(hangUser.id_.chat_id, hangUser.id_.gaia_id)) def JID2Hang(self, jid: JID): if not self.h2x.isHangUser(jid): raise Exception(jid.full() + " is not valid user JID for the transport") userIdParts = jid.user.split(".") userChatId = userIdParts[0] userGaiaId = userIdParts[1] return hangups.user.UserID(userChatId, userGaiaId) def onEvent(self, convEvent: hangups.conversation_event): # Chat message if type(convEvent) is hangups.conversation_event.ChatMessageEvent: conv = self.convList.get(convEvent.conversation_id) # Not yet delivered chat message if convEvent.timestamp > conv.latest_read_timestamp: # Deliver chat message user = conv.get_user(convEvent.user_id) if not user.is_self: # TODO: message timestamp for offline delivery self.h2x.sendMessage(self.jid, self.hang2JID(user), convEvent.text) conv.update_read_timestamp() else: print("Unsupported conversation event " + type(convEvent)) # TODO: Handle other events def sendMessage(self, recipient: JID, text: str): # Pick the conversation with the recipient user only conversation = None userId = self.JID2Hang(recipient) for c in self.convList.get_all(): if len(c.users) == 2: for u in c.users: if u.id_.__dict__ == userId.__dict__: conversation = c if conversation is None: raise Exception("No conversation found for the recipient") # Send message segments = hangups.ChatMessageSegment.from_str(text) asyncio.async(conversation.send_message(segments), loop=self.loop).add_done_callback( lambda x: print("Message sent") ) def processPresence(self, recipient, presence): # TODO: Send presence to hangouts users print("Sending presence to hangouts user is not implemented") def processSubscription(self, recipient: JID): if self.isSubscribed(recipient): self.h2x.sendPresence(self.jid, "subscribed", source=recipient) if self.loop: asyncio.async(self.updateParticipantPresence(), loop=self.loop) else: self.h2x.sendPresence(self.jid, "unsubscribed", source=recipient) return def processComponentPresence(self, sender: JID, presenceType: str, recipient: JID): if presenceType == "available": if not self.xmppClients: print("Available requested, no xmpp clients yet -> connect") self.targetState = State.connected self.xmppClients.add(sender) elif presenceType == "unavailable": self.xmppClients.discard(sender) if not self.xmppClients: print("Unavailable requested, no xmpp clients now -> disconnect") self.targetState = State.disconnected elif presenceType == "probe": self.sendPresence() elif presenceType == "subscribed": print("Presence type subscribed not supported") elif presenceType == "subscribe": self.h2x.sendPresence(self.jid, "subscribed", source=recipient) else: raise NotImplementedError("Presence type: " + presenceType) # Ensure we are in the requested state self.stateUpdate()
def log(r, usera: praw.models.Redditor, userb: praw.models.Redditor, amt: int, db: Database, recurse: bool = True) -> list: """ Log a new transaction between two users Returns list of ints: [score gained by usera, score gained by userb] """ a = db.lookup(usera.name.lower()) b = db.lookup(userb.name.lower()) if (a == None): a = User(usera.name, 0) if (b == None): b = User(userb.name, 0) basescore = 0 #complicated base score calculation if (b.status == 1): if (b.score <= 100): basescore = 5 elif (b.score <= 500): basescore = 15 elif (b.score <= 1000): basescore = 25 elif (b.score <= 2000): basescore = 30 else: basescore = 35 else: if (b.score <= 100): basescore = 5 elif (b.score <= 500): basescore = 15 elif (b.score <= 1000): basescore = 30 else: basescore = 40 if (amt < 100): basescore //= 2 if (userb.comment_karma + userb.link_karma < 1000 or time.time() - userb.created_utc < 31556952): basescore //= 2 posts = 0 for submission in userb.comments.new(limit=6): if (int(time.time()) - submission.created_utc > 864000): break posts += 1 if (posts < 5): basescore //= 4 if (basescore == 0): basescore = 1 a.score += basescore db.add(a) flairuser(r, a) journal("User " + a.username + " gained " + str(basescore) + " for a trade with " + b.username) if (recurse): d = log(r, userb, usera, amt, db, False) r = [basescore] r.append(d[0]) return r return [basescore]
def list_username(cls, user_name): user = User.by_name(user_name) omlet_query = Omlet.all().ancestor(omlets_key()).filter('user_id =', user.key().id()).run() return omlet_query