def get_at_least_editable(cls, user_id): """Returns an iterable with collection summary models that are at least editable by the given user. Args: user_id: The id of the given user. Returns: iterable. An iterable with collection summary models that are at least viewable by the given user. """ return CollectionSummaryModel.query().filter( ndb.OR( CollectionSummaryModel.owner_ids == user_id, CollectionSummaryModel.editor_ids == user_id) ).filter( CollectionSummaryModel.deleted == False # pylint: disable=singleton-comparison ).fetch(feconf.DEFAULT_QUERY_LIMIT)
def has_reference_to_user_id(cls, user_id): """Check whether CollectionRightsModel or its snapshots references the given user. Args: user_id: str. The ID of the user whose data should be checked. Returns: bool. Whether any models refer to the given user ID. """ return ( cls.query(ndb.OR( cls.owner_ids == user_id, cls.editor_ids == user_id, cls.voice_artist_ids == user_id, cls.viewer_ids == user_id )).get() is not None or cls.SNAPSHOT_METADATA_CLASS.exists_for_user_id(user_id))
def get(self): """Send a reminder email to each User with an email & incomplete game. Called every hour using a cron job""" app_id = app_identity.get_application_id() users = User.query(User.email != None) for user in users: games = Game.query( Game.game_over == False, ndb.OR(Game.user_name_x == user.key, Game.user_name_o == user.key)).fetch() if games: subject = 'You have a game in progress' body = """Hello {}, you still have a game in progress! Come back & finish up!""".format(user.name) # This will send test emails, the arguments to send_mail are: # from, to, subject, body mail.send_mail('noreply@{}.appspotmail.com'.format(app_id), user.email, subject, body)
def get(self, user, institution_urlsafe): """Handle GET requests. This method returns all the RequestInstitutionParent that the institution, whose key's representation is institution_urlsafe, is involved either as a child or as a parent. """ inst_key_obj = ndb.Key(urlsafe=institution_urlsafe) queryRequests = RequestInstitutionParent.query( ndb.OR( RequestInstitutionParent.institution_requested_key == inst_key_obj, RequestInstitutionParent.institution_key == inst_key_obj), RequestInstitutionParent.status == 'sent') requests = [request.make() for request in queryRequests] self.response.write(json.dumps(requests))
def get_user_games(self, request): """Returns all of an individual User's active games""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') user = user.key # chore: figure out why I don't have to call fetch on the # queries for games and scores above - thought this just # built a query object and didn't actually query the database # without .fetch() or .get() - see the link below...when used # as an iterator the query instance returns results when it is # iterated over # http://stackoverflow.com/questions/15410609/google-app-engine-ndb-need-to-fetch-after-query games = Game.query( Game.game_over == False, ndb.OR(Game.user_name_x == user, Game.user_name_o == user)) return GameForms(items=[game.to_form("active game") for game in games])
def get_user_games(self, request): """Return the state of games for user.""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException('User not exist!') games = Game.query( ndb.OR(Game.user1 == user.key, Game.user2 == user.key)) game_forms = list() for game in games: if game.moves % 2 == 0: game_forms.append( game.to_form('It is player1 {} to make a move!'.format( game.user1.get().name))) else: game_forms.append( game.to_form('It is player2 {} to make a move!'.format( game.user2.get().name))) return GameForms(game_forms=game_forms)
def get_private_at_least_viewable(cls, user_id): """Fetches private exp summaries that are at least viewable by the given user. Args: user_id: The id of the given user. Returns: iterable. An iterable with private exp summaries that are at least viewable by the given user. """ return ExpSummaryModel.query().filter( ExpSummaryModel.status == feconf.ACTIVITY_STATUS_PRIVATE).filter( ndb.OR(ExpSummaryModel.owner_ids == user_id, ExpSummaryModel.editor_ids == user_id, ExpSummaryModel.viewer_ids == user_id)).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).fetch(feconf.DEFAULT_QUERY_LIMIT)
def cancel(self, request): """Cancel a subset of pending tasks based on the tags. Cancellation happens asynchronously, so when this call returns, cancellations will not have completed yet. """ logging.debug('%s', request) if not request.tags: # Prevent accidental cancellation of everything. raise endpoints.BadRequestException( 'You must specify tags when cancelling multiple tasks.') now = utils.utcnow() cond = task_result.TaskResultSummary.state == task_result.State.PENDING if request.kill_running: cond = ndb.OR( cond, task_result.TaskResultSummary.state == task_result.State.RUNNING) q = task_result.TaskResultSummary.query(cond).order( task_result.TaskResultSummary.key) for tag in request.tags: q = q.filter(task_result.TaskResultSummary.tags == tag) tasks, cursor = datastore_utils.fetch_page(q, request.limit, request.cursor) if tasks: payload = json.dumps({ 'tasks': [t.task_id for t in tasks], 'kill_running': request.kill_running or False, }) ok = utils.enqueue_task( '/internal/taskqueue/important/tasks/cancel', 'cancel-tasks', payload=payload) if not ok: raise endpoints.InternalServerErrorException( 'Could not enqueue cancel request, try again later') else: logging.info('No tasks to cancel.') return swarming_rpcs.TasksCancelResponse(cursor=cursor, matched=len(tasks), now=now)
def getEmojiList(lang_code, tag, show_alpha_names): tagLower = tag.lower() entries = LanguageEmojiTag.query( ndb.AND( LanguageEmojiTag.lang_code == lang_code, ndb.OR(LanguageEmojiTag.default_tags == tag, LanguageEmojiTag.default_tags == tagLower, LanguageEmojiTag.users_tags == tag, LanguageEmojiTag.users_tags == tagLower))).fetch( projection=[LanguageEmojiTag.emoji]) result = [e.getEmoji() for e in entries] emojis_in_unicode_tags = emojiTags.getEmojisForTag(tag, lang_code) result.extend(emojis_in_unicode_tags) result = list(set(result)) if show_alpha_names: from emojiUtil import getAlphaName #return ["{} :{}:".format(x,utility.escapeMarkdown(getAlphaName(x))) for x in result] return ["{} :{}:".format(x, getAlphaName(x)) for x in result] return result
def get_private_at_least_viewable(cls, user_id): """Returns an iterable with private collection summary models that are at least viewable by the given user. Args: user_id: str. The id of the given user. Returns: iterable. An iterable with private collection summary models that are at least viewable by the given user. """ return CollectionSummaryModel.query().filter( CollectionSummaryModel.status == constants.ACTIVITY_STATUS_PRIVATE).filter( ndb.OR(CollectionSummaryModel.owner_ids == user_id, CollectionSummaryModel.editor_ids == user_id, CollectionSummaryModel.viewer_ids == user_id)).filter( CollectionSummaryModel.deleted == False # pylint: disable=singleton-comparison ).fetch(feconf.DEFAULT_QUERY_LIMIT)
def permission_get(type, action, target, user, groups, keys_only=True): if user and groups: return Permission.query().filter( \ ndb.AND(Permission.type == type, Permission.action == action, Permission.target == target, ndb.OR(Permission.user == build_user_key(user), Permission.group.IN([build_group_key(group) for group in groups])))).get(keys_only=keys_only) elif user: return Permission.query(ancestor=build_user_key(user)).filter( \ ndb.AND(Permission.type == type, Permission.action == action, Permission.target == target)).get(keys_only=keys_only) elif groups: return Permission.query().filter( \ ndb.AND(Permission.type == type, Permission.action == action, Permission.target == target, Permission.group.IN([build_group_key(group) for group in groups]))).get(keys_only=keys_only)
def post(self): talker = self.request.get("talker") user = self.request.get('user') friend = User.query(User.uName == talker).get() friend.flag = False friend.put() message = Message.query( ndb.OR(ndb.AND(Message.receiver == talker, Message.sender == user), ndb.AND(Message.receiver == user, Message.sender == talker))).order( Message.timestamp).fetch(40) response = '' for m in message: response += m.str() + '\n' print(talker) print(user) print(message) self.response.write(response)
def get(self): if not self.user_bundle.user: self.response.out.write(json.dumps([])) return now = datetime.datetime.now() auth_tokens = ApiAuthAccess.query( ApiAuthAccess.owner == self.user_bundle.account.key, ndb.OR(ApiAuthAccess.expiration == None, ApiAuthAccess.expiration >= now)).fetch() event_keys = [] for token in auth_tokens: event_keys.extend(token.event_list) events = ndb.get_multi(event_keys) details = {} for event in events: details[event.key_name] = "{} {}".format(event.year, event.name) self.response.out.write(json.dumps(details))
def migrate_model(cls, old_user_id, new_user_id): """Migrate model to use the new user ID in the recipient_id and sender_id. Args: old_user_id: str. The old user ID. new_user_id: str. The new user ID. """ migrated_models = [] for model in cls.query( ndb.OR(cls.recipient_id == old_user_id, cls.sender_id == old_user_id)).fetch(): if model.recipient_id == old_user_id: model.recipient_id = new_user_id if model.sender_id == old_user_id: model.sender_id = new_user_id migrated_models.append(model) SentEmailModel.put_multi(migrated_models, update_last_updated_time=False)
def get(self): self.response.write(open('header.html').read()) an = self.request.get("tfAcNo") # query from Googe NDB result = Account.query( ndb.OR(Account.AcNo == int(an), Account.AcBalance >= 40000)) if result: self.response.write("<table border='1'>") for act in result: self.response.write("<tr>") self.response.write("<td>" + str(act.AcNo) + "</td>") self.response.write("<td>" + act.AcHName + "</td>") self.response.write("<td>" + str(act.AcBalance) + "</td>") self.response.write("<td>" + str(act.AcMobNo) + "</td>") self.response.write("<td>" + act.City + "</td>") self.response.write("</tr>") self.response.write("</table>") else: self.response.write("No Data Found")
def migrate_model(cls, old_user_id, new_user_id): """Migrate model to use the new user ID in the author_id and final_reviewer_id. Args: old_user_id: str. The old user ID. new_user_id: str. The new user ID. """ migrated_models = [] for model in cls.query( ndb.OR(cls.author_id == old_user_id, cls.final_reviewer_id == old_user_id)).fetch(): if model.author_id == old_user_id: model.author_id = new_user_id if model.final_reviewer_id == old_user_id: model.final_reviewer_id = new_user_id migrated_models.append(model) GeneralVoiceoverApplicationModel.put_multi( migrated_models, update_last_updated_time=False)
def pull_and_publish_event(): oauth_tokens = db.OAuthToken.query( db.OAuthToken.valid_token == True, ndb.OR(db.OAuthToken.next_post_time < datetime.datetime.now(), db.OAuthToken.next_post_time == None)).fetch(100) q1 = taskqueue.Queue(EVENT_PULL_QUEUE_HIGH) q2 = taskqueue.Queue(EVENT_PULL_QUEUE) for token in oauth_tokens: logging.info("Can post to OAuthToken %s: %s", token.queue_id(), token) tasks = q1.lease_tasks_by_tag(120, 1, token.queue_id()) q = q1 if not tasks: tasks = q2.lease_tasks_by_tag(120, 1, token.queue_id()) q = q2 logging.info("Fetching %d tasks with queue id %s", len(tasks), token.queue_id()) if tasks: # Should only be one task if len(tasks) != 1: logging.error( 'Found too many tasks in our lease_tasks_by_tag: %s', len(tasks)) task = tasks[0] # Backwards compatibility for items in the queue if '{' not in task.payload: data = { 'type': 'event', 'event_id': task.payload, } else: data = json.loads(task.payload) logging.info('Processing data payload: %r', data) posted = _post_data_with_authtoken(data, token) q.delete_tasks(task) # Only mark it up for delay, if we actually posted... if posted: next_post_time = datetime.datetime.now() + datetime.timedelta( seconds=token.time_between_posts) token = token.key.get() token.next_post_time = next_post_time token.put()
def migrate_model(cls, old_user_id, new_user_id): """Migrate model to use the new user ID in the owner_ids, editor_ids, voice_artist_ids, viewer_ids and contributor_ids. Args: old_user_id: str. The old user ID. new_user_id: str. The new user ID. """ migrated_models = [] for model in cls.query( ndb.OR(cls.owner_ids == old_user_id, cls.editor_ids == old_user_id, cls.voice_artist_ids == old_user_id, cls.viewer_ids == old_user_id, cls.contributor_ids == old_user_id)).fetch(): model.owner_ids = [ new_user_id if owner_id == old_user_id else owner_id for owner_id in model.owner_ids ] model.editor_ids = [ new_user_id if editor_id == old_user_id else editor_id for editor_id in model.editor_ids ] model.voice_artist_ids = [ new_user_id if voice_art_id == old_user_id else voice_art_id for voice_art_id in model.voice_artist_ids ] model.viewer_ids = [ new_user_id if viewer_id == old_user_id else viewer_id for viewer_id in model.viewer_ids ] model.contributor_ids = [ new_user_id if contributor_id == old_user_id else contributor_id for contributor_id in model.contributor_ids ] if old_user_id in model.contributors_summary: model.contributors_summary[new_user_id] = ( model.contributors_summary[old_user_id]) del model.contributors_summary[old_user_id] migrated_models.append(model) cls.put_multi(migrated_models, update_last_updated_time=False)
def getNonWorkshopSessionsBefore7(self, request): """Returns all sessions which are not of type WORKSHOP and have a startTime before 7PM""" # Create sessions query sessions = Session.query() # Filter by type (any type except WORKSHOP) # Can only use the inequality operation on one field per query. So we cannot use both # != for session type and < for startTime. Use ndb.OR instead for the session type filter. sessions = sessions.filter( ndb.OR(Session.typeOfSession == str(SessionType.KEYNOTE), Session.typeOfSession == str(SessionType.LECTURE), Session.typeOfSession == str(SessionType.NOT_SPECIFIED))) # Filter by time (any time before 19:00) seven = dt.time(19, 00) sessions = sessions.filter(Session.startTime < seven) # Return set of SessionForm objects return SessionForms( sessions=[self._copySessionToForm(s) for s in sessions])
def get(self): """Reminder to users with incomplete games""" users = User.query(User.email != None) for user in users: games = Game.query(ndb.OR(Game.playerX == user.key, Game.playerO == user.key)). \ filter(Game.game_over == False) if games.count() > 0: subject = 'This is a reminder!' body = 'Hello {}, this email is for advice you about the '\ 'games that are in progress. ' \ 'You have {} games incompleted.' \ 'The games keys are: {}'.format(user.name, games.count(), ', '.join(game.key.urlsafe() for game in games)) # This will send test emails, the arguments to send_mail are: # from, to, subject, body mail.send_mail( 'noreply@{}.appspotmail.com'.format( app_identity.get_application_id()), user.email, subject, body)
def get(self): uuid = self.request.get('group_uuid') user = api.get_user(self.request) if not user: api.write_error(self.response, 403, 'Unknown or missing user') return if uuid: query = Group.query(Group.uuid == uuid) else: query = Group.query(ndb.OR(Group.members == user.key, Group.admins == user.key)).order(-Group.update_time) groups = [] for group in query: if user.key in group.members or user.key in group.admins: groups.append(get_group_json(group)) api.write_message(self.response, 'success', extra={'groups' : groups})
def get(self): user = users.get_current_user() myId = user.user_id() otherUser = self.request.get('id') data = { 'messages': allToDict( Message.query(ndb.OR( ndb.AND(Message.sentFrom == user.user_id(), Message.sentTo == otherUser), ndb.AND(Message.sentTo == user.user_id(), Message.sentFrom == otherUser)), ancestor=root_parent()).order( Message.timeSent, Message.msg).fetch()), 'myId': myId } self.response.headers['Content-Type'] = 'application/json' print(data) self.response.write(json.dumps(data))
def post(self): name = self.request.get("name", "").strip() surname = self.request.get("surname", "").strip() username = self.request.get("username", "").strip() email = self.request.get("email", "").strip() birthdate = self.request.get("birthdate", "").strip() password = self.request.get("passwd", "").strip() rpassword = self.request.get("rpasswd", "").strip() creaks = 0 follow = 0 if len(name) == 0 or len(surname) == 0 or len(username) == 0 or \ len(email) == 0 or len(birthdate) == 0 or len(password) == 0\ or len(rpassword) == 0: self.response.write("It is necessary to complete all fields of the record.") return if len(username) < 5: self.response.write("Username must have at least 5 characters.") if rpassword != password: self.response.write("Passwords do not match.") return user = Register(username=username, name=name, surname=surname, email=email, birthdate=birthdate, password=password, creaks=0, follow=0,followers=0) userToPut = Register.query(ndb.OR(Register.username == username, Register.email == email)) if userToPut.count() > 0: values = { "error_register": "The username or email already exists." } jinja = jinja2.get_jinja2(app=self.app) self.response.write(jinja.render_template("register.html", **values)) return else: user.put() time.sleep(1) self.redirect("/")
def get(self): cursor = None bookmark = self.request.get('bookmark') search = (self.request.get('search')).strip() if bookmark: cursor = ndb.Cursor.from_websafe_string(bookmark) if search: #ndb.AND(Video.tags == tag, Video.key != video.key) query = models.Manifest.query(ndb.OR(models.Manifest.voyage == search, models.Manifest.port == search, models.Manifest.vessel_name == search)).order(-models.Manifest._key) else: query = models.Manifest.query().order(-models.Manifest.created) data, next_cursor, more = query.fetch_page(PAGE_SIZE, start_cursor=cursor) next_bookmark = None if more: next_bookmark = next_cursor.to_websafe_string() is_prev = self.request.get('prev', False) if is_prev: query = q_reverse cursor = cursor.reversed() else: query = next_bookmark if is_prev: prev_bookmark = cursor.reversed().to_websafe_string() if more else None next_bookmark = bookmark else: prev_bookmark = bookmark next_bookmark = None if more: next_bookmark = next_cursor.to_websafe_string() params = { "data": data, "bookmark": next_bookmark, "prev_bookmark": prev_bookmark, } return self.render_template("manifest.html", **params)
def infer_profile_url(self, url): """Find a Facebook profile URL (ideally the one with the user's numeric ID) Looks up existing sources by username, inferred username, and domain. Args: url: string, a person's URL Return: a string URL for their Facebook profile (or None) """ domain = util.domain_from_link(url) if domain == self.gr_source.DOMAIN: username = urlparse.urlparse(url).path.strip('/') if '/' not in username: user = FacebookPage.query(ndb.OR( FacebookPage.username == username, FacebookPage.inferred_username == username)).get() if user: return self.gr_source.user_url(user.key.id()) return super(FacebookPage, self).infer_profile_url(url)
def _getSessionsDoubleInequalityDemo(self, request): """Demonstrates my solution to the double-inequality query problem.""" # Convert request.maxStartTime from string to Time object try: maxStartTime = datetime.strptime(request.maxStartTime, '%H:%M').time() except: raise endpoints.BadRequestException("Invalid 'maxStartTime' value") # Get list of session types from the enum class, then remove the # sessionTypeToAvoid value from it. This leaves all the session types # the user still wants in their search. sessionTypes = SessionType.to_dict().keys() sessionTypes.remove(str(request.sessionTypeToAvoid)) # Generate a list of equality filters from the sessionTypes list equalityFilters = [Session.typeOfSession == st for st in sessionTypes] # Construct query, utilizing the list of equality filters in an OR # function. Add the startTime inequality filter. Then execute. query = Session.query(ndb.OR(*equalityFilters)) query = query.filter(Session.startTime <= maxStartTime) sessions = query.order(Session.startTime).fetch() return sessions
def findReplyID(post, vkchatid, tgchatid): reply_to = 0 if 'reply_message' in post: vkreplyid = post['reply_message']['conversation_message_id'] vkreplyfrom = post['reply_message']['from_id'] vkreplyname = getVkName(vkreplyfrom) vkreplytime = post['reply_message']['date'] vkreplytext = post['reply_message']['text'] # trying to find by message id dbmsgs = Message.query(Message.vkmsgid == vkreplyid, Message.vkchatid == vkchatid, Message.tgchatid == tgchatid).fetch(1) for dbmsg in dbmsgs: reply_to = dbmsg.tgmsgid vkreplychecksum = adler32(vkreplytext.encode('utf-8')) if vkreplychecksum != dbmsg.checksum: # message edited tgEditMsg(chatid=tgchatid, msgid=reply_to, text='<b>' + vkreplyname + ':</b> ' + vkreplytext) dbmsg.checksum = vkreplychecksum dbmsg.put() # trying to find by timestamp and checksum if reply_to == 0: vkreplychecksum = adler32(vkreplytext.encode('utf-8')) dbmsgs = Message.query( ndb.AND( Message.vkchatid == vkchatid, Message.tgchatid == tgchatid, Message.checksum == vkreplychecksum, ndb.OR(Message.timestamp == vkreplytime, Message.timestamp == vkreplytime + TIMETRESHOLD))).fetch() for dbmsg in dbmsgs: reply_to = dbmsg.tgmsgid dbmsg.vkmsgid = vkreplyid dbmsg.put() return reply_to
def _can(cls, user, need, group, query): action = need.action if not user.logged_in: return False if action == "index": if user.is_admin: return query return query.filter( ndb.OR(Group.member == user.key, Group.invited == user.key)) if user.is_admin: return True if not group: return False if action in ("get", "exit"): return user.key in group.member or user.key in group.invited elif action in ("invite", "remove", "reorder"): return user.key in group.member elif action in "accept": return user.key in group.invited return False
def get(self, source_short_name, id): cls = models.sources[source_short_name] self.source = cls.lookup(id) if not self.source: id = id.decode('utf-8') key = cls.query( ndb.OR(*[ ndb.GenericProperty(prop) == id for prop in ('domains', 'inferred_username', 'name', 'username') ])).get(keys_only=True) if key: return self.redirect(cls(key=key).bridgy_path(), permanent=True) if self.source and self.source.features: self.source.verify() self.source = self.preprocess_source(self.source) else: self.response.status_int = 404 super(UserHandler, self).get()
def get(self): try: name = self.request.GET['name'] print(str.format("esto es el atrib {0}",name)) except: name = None if name == None: self.redirect("/main") return else: equipo=Equipo.query(ndb.AND(Equipo.name==name,Equipo.user_id==users.get_current_user().user_id())) games=Partida.query(ndb.AND(ndb.OR(Partida.nameEquipoA==name,Partida.nameEquipoB==name),Partida.user_id==users.get_current_user().user_id())) names=[] for ga in games: names.append(ga.name) ga.key.delete() for jug in equipo: jug.key.delete() time.sleep(1) self.redirect("/main")