desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Check and prepare for update. 1) Get Identity record for requested identity. 2) Gather all of the existing known contacts for the relevant contact source. 3) Fetch the contacts from the relevant contact source (Facebook or GMail). 4) Prepare for update be determine which contacts should be Created/Removed/Deleted.'
@gen.coroutine def _Check(self):
self._identity = (yield gen.Task(Identity.Query, self._client, hash_key=self._key, col_names=None)) assert (self._identity.user_id == self._user_id), self self._do_fetch_and_update = ((self._identity.access_token is not None) and (not FetchContactsOperation._SKIP_UPDATE_FOR_TEST) and (self._identity.authori...
'Perform insert/(replace) of fetched contacts as well as deletion of duplicate contacts.'
@gen.coroutine def _Update(self):
@gen.coroutine def _InsertDeleteContact(contact_to_insert, contact_to_delete): 'Insert followed by delete (after insert is complete).' if (contact_to_insert is not None): (yield gen.Task(contact_to_insert.Update, self._client)) (yield Operation.TriggerFai...
'Creates notification: Notify of all contacts with timestamp greater than or equal to current. May also indicate that all \'removed\' contacts have been deleted and the client should reset by reloading all contacts.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyFetchContacts(self._client, self._user_id, self._notify_timestamp, self._removed_contacts_reset))
'Do GMail specific data gathering and checking. Queries Google data API for contacts in JSON format.'
@gen.coroutine def _FetchGoogleContacts(self):
assert (self._identity.refresh_token is not None), self._identity if (self._identity.expires and (self._identity.expires < time.time())): (yield gen.Task(self._identity.RefreshGoogleAccessToken, self._client)) logging.info(('fetching Google contacts for identity %r...' % self._identit...
'Do Facebook specific data gathering and checking. Queries Facebook graph API for friend list using the identity\'s access token.'
@gen.coroutine def _FetchFacebookContacts(self):
@gen.coroutine def _DetermineFacebookRankings(): "Uses The tags from friends and the authors of the\n photos are used to determine friend rank for facebook contacts. The\n basic algorithm is:\n\n...
'Query all contacts in preparation for refresh; this allows us to update only contacts which have been modified. Also get list of contacts that should be deleted (during update phase) for the purpose of garbage collection/dedup.'
@gen.coroutine def _GatherExistingContacts(self):
(self._all_contacts_dict, self._contacts_to_delete) = (yield FetchContactsOperation._GetAllContactsWithDedup(self._client, self._user_id)) for contact in self._all_contacts_dict.itervalues(): if contact.IsRemoved(): self._all_removed_contacts_count += 1 else: self._all_pr...
'Process fetched contacts. Figure out which ones to create/remove/delete/keep. On entry, we have three dicts with contacts: * All of the contacts that we just fetched: self._fetched_contacts * All of the contacts from the same source that are currently persisted: self._existing_contacts_dict. * All of the contacts (re...
def _PrepareFetchedContactsForUpdate(self):
contacts_to_unremove = [] contacts_to_create = [] contacts_to_remove = {c.contact_id: c for c in self._existing_contacts_dict.itervalues() if (not c.IsRemoved())} for fetched_contact in self._fetched_contacts.itervalues(): existing_contact = self._existing_contacts_dict.get(fetched_contact.conta...
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, user_id, episodes):
user = (yield gen.Task(User.Query, client, user_id, None)) (yield RemovePhotosOperation(client, user, episodes)._RemovePhotos())
'Orchestrates the remove_photos operation by executing each of the phases in turn.'
@gen.coroutine def _RemovePhotos(self):
lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._user.private_vp_id)) try: (yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield self._Account()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify(...
'Gathers pre-mutation information: 1. Queries for episodes. 2. Queries for user posts. 3. Checkpoints list of post ids that need to be removed. Validates the following: 1. Permission to remove photos from episodes. 2. Photos cannot be removed from shared viewpoints.'
@gen.coroutine def _Check(self):
ep_ph_ids_list = [(ep_dict['episode_id'], ep_dict['photo_ids']) for ep_dict in self._ep_dicts] self._ep_posts_list = (yield self._CheckEpisodePostAccess('remove', self._client, self._user.user_id, ep_ph_ids_list)) for (episode, post) in self._ep_posts_list: if (episode.viewpoint_id != self._user.pri...
'Updates the database: 1. Add the REMOVED label to the post.'
@gen.coroutine def _Update(self):
for (episode, posts) in self._ep_posts_list: for post in posts: post.labels.add(Post.REMOVED) (yield gen.Task(post.Update, self._client))
'Makes accounting changes: 1. Decrease user accounting by size of removed photos.'
@gen.coroutine def _Account(self):
photo_ids = [Post.DeconstructPostId(post_id)[1] for post_id in self._remove_ids] acc_accum = AccountingAccumulator() (yield acc_accum.RemovePhotos(self._client, self._user.user_id, self._user.private_vp_id, photo_ids)) (yield acc_accum.Apply(self._client))
'Creates notifications: 1. Notify all of the user\'s devices that photos have been removed from the viewpoint.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyRemovePhotos(self._client, self._user.user_id, self._ep_dicts))
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, activity, user_id, comment):
(yield PostCommentOperation(client, activity, user_id, comment)._PostComment())
'Orchestrates the post_comment operation by executing each of the phases in turn.'
@gen.coroutine def _PostComment(self):
lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._viewpoint_id)) try: if (not (yield self._Check())): return self._client.CheckDBNotModified() (yield self._Update()) (yield self._Account()) (yield Operation.TriggerFailpoint(self._client)) ...
'Gathers pre-mutation information: 1. Queries for existing followers and comment. 2. Checkpoints list of followers that need to be revived. Validates the following: 1. Checks for maximum comment size. 2. Permission to add a comment to the viewpoint.'
@gen.coroutine def _Check(self):
message_byte_size = len(escape.utf8(self._cm_dict['message'])) if (message_byte_size > Comment.COMMENT_SIZE_LIMIT_BYTES): logging.warning(('User %d attempted to exceed message size limit ( %d / %d ) on comment "%s", viewpoint "%s"' % (self._user_id, mes...
'Updates the database: 1. Revives any followers that have removed the viewpoint. 2. Creates the new comment.'
@gen.coroutine def _Update(self):
(yield gen.Task(Follower.ReviveRemovedFollowers, self._client, self._followers)) (yield Comment.CreateNew(self._client, **self._cm_dict))
'Makes accounting changes: 1. For revived followers.'
@gen.coroutine def _Account(self):
acc_accum = AccountingAccumulator() (yield acc_accum.ReviveFollowers(self._client, self._viewpoint_id, self._revive_follower_ids)) (yield acc_accum.Apply(self._client))
'Creates notifications: 1. Notifies removed followers that conversation has new activity. 2. Notifies existing followers of the viewpoint that a new comment has been added.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyReviveFollowers(self._client, self._viewpoint_id, self._revive_follower_ids, self._op.timestamp)) (yield NotificationManager.NotifyPostComment(self._client, self._followers, self._act_dict, self._cm_dict))
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, user_id, episodes):
user = (yield gen.Task(User.Query, client, user_id, None)) (yield HidePhotosOperation(client, user, episodes)._HidePhotos())
'Orchestrates the hide photos operation by executing each of the phases in turn.'
@gen.coroutine def _HidePhotos(self):
lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._user.private_vp_id)) try: (yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify()) finally: (yield g...
'Gathers pre-mutation information: 1. Queries for user posts. Validates the following: 1. Permission to remove photos from episodes.'
@gen.coroutine def _Check(self):
ep_ph_ids_list = [(ep_dict['episode_id'], ep_dict['photo_ids']) for ep_dict in self._ep_dicts] (yield self._CheckEpisodePostAccess('hide', self._client, self._user.user_id, ep_ph_ids_list)) self._user_post_keys = [DBKey(self._user.user_id, Post.ConstructPostId(ep_dict['episode_id'], photo_id)) for ep_dict i...
'Updates the database: 1. Add the HIDDEN label to the UserPost, creating it in the process if necessary.'
@gen.coroutine def _Update(self):
for (user_post, (user_id, post_id)) in zip(self._user_posts, self._user_post_keys): if (user_post is None): user_post = UserPost.CreateFromKeywords(user_id=user_id, post_id=post_id, timestamp=self._op.timestamp) if (not user_post.IsHidden()): user_post.labels.add(UserPost.HID...
'Creates notifications: 1. Notify all of the user\'s devices that photos have been hidden.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyHidePhotos(self._client, self._user.user_id, self._ep_dicts))
'Ensures that given user has access to the set of episodes and photos in "ep_ph_ids_list", which is a list of (episode_id, photo_ids) tuples. Returns list of (episode, posts) tuples that corresponds to "ep_ph_ids_list".'
@classmethod @gen.coroutine def _CheckEpisodePostAccess(cls, action, client, user_id, ep_ph_ids_list):
episode_keys = [] post_keys = [] for (episode_id, photo_ids) in ep_ph_ids_list: episode_keys.append(DBKey(episode_id, None)) for photo_id in photo_ids: post_keys.append(DBKey(episode_id, photo_id)) (episodes, posts) = (yield [gen.Task(Episode.BatchQuery, client, episode_keys,...
'Ensures that the sharer or saver has access to the source episodes and that the source photos are part of the source episodes. Caller is expected to check permission to add to the given viewpoint. Returns a list of the source episodes and posts in the form of (episode, posts) tuples.'
@classmethod @gen.coroutine def _CheckCopySources(cls, action, client, user_id, source_ep_dicts):
unique_keys = set() ep_ph_ids_list = [] for ep_dict in source_ep_dicts: ph_ids = [] for photo_id in ep_dict['photo_ids']: db_key = (ep_dict['new_episode_id'], photo_id) if (db_key in unique_keys): raise InvalidRequestError(('Photo "%s" cannot ...
'For each episode listed in "source_ep_ids", determines if a child episode already exists in the given viewpoint. If not, allocates a new episode id using the user\'s asset id allocator. The same timestamp used to create the source episode id is used to create the target episode id. Returns the list of target episodes ...
@classmethod @gen.coroutine def _AllocateTargetEpisodeIds(self, client, user_id, device_id, target_viewpoint_id, source_ep_ids):
tasks = [] for source_ep_id in source_ep_ids: query_expr = ('episode.parent_ep_id={id}', {'id': source_ep_id}) tasks.append(gen.Task(Episode.IndexQuery, client, query_expr, None)) target_ep_ids = [] allocate_ids_count = 0 target_episodes_list = (yield tasks) for target_episodes i...
'Creates list of dicts which will be used to create episodes that are the target of a share or save operation.'
@classmethod def _CreateCopyTargetDicts(cls, timestamp, user_id, target_viewpoint_id, source_ep_posts_list, target_ep_ids):
new_ep_dict_list = [] for ((source_episode, posts), target_ep_id) in zip(source_ep_posts_list, target_ep_ids): new_ep_dict = {'episode_id': target_ep_id, 'parent_ep_id': source_episode.episode_id, 'user_id': user_id, 'viewpoint_id': target_viewpoint_id, 'timestamp': source_episode.timestamp, 'publish_ti...
'Compiles a list of target episode and post ids that do not exist or are removed. These episodes and posts will not be copied as part of the operation. Returns the set of target episode and post ids that will be (re)created by the caller.'
@classmethod @gen.coroutine def _CheckCopyTargets(cls, action, client, user_id, viewpoint_id, target_ep_dicts):
episode_keys = [] post_keys = [] for ep_dict in target_ep_dicts: episode_keys.append(DBKey(ep_dict['episode_id'], None)) for photo_id in ep_dict['photo_ids']: post_keys.append(DBKey(ep_dict['episode_id'], photo_id)) (episodes, posts) = (yield [gen.Task(Episode.BatchQuery, cli...
'Creates new episodes and posts within those episodes based on a list returned by _CheckCopySources. If an episode or post id does not exist in "new_ids", it is not created. The "new_ids" set is created by _CheckCopyTargets.'
@gen.coroutine def _CreateNewEpisodesAndPosts(self, new_ep_dicts, new_ids):
tasks = [] for new_ep_dict in deepcopy(new_ep_dicts): ep_id = new_ep_dict['episode_id'] ph_ids = [ph_id for ph_id in new_ep_dict.pop('photo_ids') if (Post.ConstructPostId(ep_id, ph_id) in new_ids)] if (ep_id in new_ids): tasks.append(gen.Task(Episode.CreateNew, self._client, ...
'Query for all contacts and split into a dictionary of deduped contacts which is keyed by contact_id and a list of contacts that can be deleted because they\'re unnecessary. Returns: tuple of (retained_contacts_dict, contacts_to_delete_list)'
@classmethod @gen.coroutine def _GetAllContactsWithDedup(cls, client, user_id):
contacts_to_delete = [] contacts_to_retain = dict() existing_contacts = (yield gen.Task(Contact.RangeQuery, client, hash_key=user_id, range_desc=None, limit=(Contact.MAX_CONTACTS_LIMIT * 2), col_names=['contact_id', 'labels', 'contact_source'], scan_forward=True)) for existing_contact in existing_contac...
'Get subset of the given followers that have been removed but are still revivable.'
@classmethod def _GetRevivableFollowers(cls, followers):
return [follower.user_id for follower in followers if (follower.IsRemoved() and (not follower.IsUnrevivable()))]
'Examines each contact in "contact_dicts" (in the CONTACT_METADATA format). Returns a list of the same length containing the (True, user_id, webapp_dev_id) of the contact if it is already a Viewfinder user, or allocates new user and web device ids, and returns the tuple (False, user_id, webapp_dev_id). Raises an Invali...
@gen.coroutine def _ResolveContactIds(self, contact_dicts):
identity_keys = [DBKey(contact_dict['identity'], None) for contact_dict in contact_dicts if ('user_id' not in contact_dict)] identities = (yield gen.Task(Identity.BatchQuery, self._client, identity_keys, None, must_exist=False)) user_keys = [] ident_iter = iter(identities) for contact_dict in contac...
'Creates a prospective user account for any contacts that are not yet Viewfinder users. The "contact_ids" list should have been previously obtained by the caller via a call to _ResolveContactIds, and items in it must correspond to "contact_dicts". If specified, the "reason" string is passed to the CreateProspective op....
@gen.coroutine def _ResolveContacts(self, contact_dicts, contact_ids, reason=None):
for (contact_dict, (user_exists, user_id, webapp_dev_id)) in zip(contact_dicts, contact_ids): if (not user_exists): user = (yield gen.Task(User.Query, self._client, user_id, None, must_exist=False)) if (user is None): request = {'user_id': user_id, 'webapp_dev_id': we...
'Saves the given operation as the currently executing operation. Once the caller exits the contextmanager, the currently executing operation is cleared. Redefines the current thread\'s logger to include a handler which keeps all log messages in a buffer to include with the JSON operation args and be written to the curr...
@contextmanager def Enter(self, op):
log_handler = None log_context = None try: assert (op is not None), 'operation must not be None' assert (self.executing_op is None), 'execution of nested ops is not supported' self.executing_op = op if (op.method is not None): log_han...
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, user_id, email):
(yield BuildArchiveOperation(client, user_id, email)._BuildArchive())
'Get our temp directory into a known clean state.'
def _ResetArchiveDir(self):
if (not os.path.exists(ServerEnvironment.GetViewfinderTempDirPath())): os.mkdir(ServerEnvironment.GetViewfinderTempDirPath()) if (not os.path.exists(self._temp_dir_path)): os.mkdir(self._temp_dir_path) if os.path.exists(self._content_dir_path): shutil.rmtree(self._content_dir_path) ...
'The file for this photo should already exist.'
@gen.coroutine def _VerifyPhotoExists(self, folder_path, photo_id):
assert os.path.exists(os.path.join(folder_path, (photo_id + '.f.jpg')))
'Drive overall archive process as outlined in class header comment.'
@gen.coroutine def _BuildArchive(self):
logging.info(('building archive for user: %d' % self._user_id)) self._ResetArchiveDir() proc = process.Subprocess(['cp', '-R', os.path.join(self._offboarding_assets_dir_path, 'web_code'), self._content_dir_path]) code = (yield gen.Task(proc.set_exit_callback)) if (code != 0): log...
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, activity, user_id, episode):
(yield UpdateEpisodeOperation(client, activity, user_id, episode)._UpdateEpisode())
'Orchestrates the update_episode operation by executing each of the phases in turn.'
@gen.coroutine def _UpdateEpisode(self):
self._episode = (yield gen.Task(Episode.Query, self._client, self._episode_id, None, must_exist=False)) if (not self._episode): raise InvalidRequestError(('Episode "%s" does not exist and so cannot be updated.' % self._episode_id)) self._viewpoint_id = self._episode.viewpo...
'Gathers pre-mutation information: 1. Queries for existing followers. 2. Checkpoints list of followers that need to be revived. Validates the following: 1. Permission to update episode metadata.'
@gen.coroutine def _Check(self):
if (self._episode.user_id != self._user_id): raise PermissionError(('User id of episode "%s" does not match requesting user.' % self._episode_id)) (self._followers, _) = (yield gen.Task(Viewpoint.QueryFollowers, self._client, self._viewpoint_id, limit=Viewpoint.MAX_FOLLOWERS))...
'Updates the database: 1. Revives any followers that have removed the viewpoint. 2. Updates the episode metadata.'
@gen.coroutine def _Update(self):
(yield gen.Task(Follower.ReviveRemovedFollowers, self._client, self._followers)) (yield self._episode.UpdateExisting(self._client, **self._ep_dict))
'Makes accounting changes: 1. For revived followers.'
@gen.coroutine def _Account(self):
acc_accum = AccountingAccumulator() (yield acc_accum.ReviveFollowers(self._client, self._viewpoint_id, self._revive_follower_ids)) (yield acc_accum.Apply(self._client))
'Creates notifications: 1. Notifies removed followers that conversation has new activity. 2. Notifies existing followers of the viewpoint that episode metadata has changed.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyReviveFollowers(self._client, self._viewpoint_id, self._revive_follower_ids, self._op.timestamp)) (yield NotificationManager.NotifyUpdateEpisode(self._client, self._viewpoint_id, self._followers, self._act_dict, self._ep_dict))
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, user_dict, ident_dict, device_dict):
(yield RegisterUserOperation(client, user_dict, ident_dict, device_dict)._RegisterUser())
'Orchestrates the register operation by executing each of the phases in turn.'
@gen.coroutine def _RegisterUser(self):
(yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify())
'Gathers pre-mutation information: 1. Queries for the existing user and identity. 2. Checkpoints whether the user is prospective. 3. Checkpoints whether the identity is linked to the user. 4. Checkpoints whether the device is the first mobile device to be registered.'
@gen.coroutine def _Check(self):
if (self._op.checkpoint is None): user = (yield gen.Task(User.Query, self._client, self._user_dict['user_id'], None)) self._is_first_register = (not user.IsRegistered()) identity = (yield gen.Task(Identity.Query, self._client, self._ident_dict['key'], None)) self._is_linking = (ident...
'Updates the database: 1. Registers the user and identity. 2. Registers the device.'
@gen.coroutine def _Update(self):
(yield User.Register(self._client, self._user_dict, self._ident_dict, self._op.timestamp, rewrite_contacts=(self._is_first_register or self._is_linking))) if (self._device_dict is not None): (yield Device.Register(self._client, self._user_dict['user_id'], self._device_dict, is_first=self._is_first_devic...
'Creates notifications: 1. Notifies the user and his friends and contacts of any changes to the user or its identities.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyRegisterUser(self._client, self._user_dict, self._ident_dict, self._op.timestamp, self._is_first_register, self._is_linking))
'Ensure that a lock is acquired for the given viewpoint. The lock may have already been acquired in which case this is a no-op. Locks should be acquired one at a time, never concurrently.'
@gen.coroutine def AcquireViewpointLock(self, viewpoint_id):
if (not self._acquired_viewpoint_locks.has_key(viewpoint_id)): lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, viewpoint_id)) assert (not self._acquired_viewpoint_locks.has_key(viewpoint_id)), self self._acquired_viewpoint_locks[viewpoint_id] = lock
'Release all viewpoint locks that have been acquired up to this point.'
@gen.coroutine def ReleaseAllViewpointLocks(self):
(yield [gen.Task(Viewpoint.ReleaseLock, self._client, viewpoint_id, lock) for (viewpoint_id, lock) in self._acquired_viewpoint_locks.items()]) self._acquired_viewpoint_locks = {}
'Returns true if a lock is already held for the given viewpoint.'
def IsViewpointLocked(self, viewpoint_id):
return (viewpoint_id in self._acquired_viewpoint_locks)
'Initializes the operation map, which is a dictionary mapping from operation method str to an instance of OpMapEntry. Also initializes maps for active users (map from user id to an instance of UserOpManager).'
def __init__(self, op_map, client=None, scan_ops=False):
self.op_map = op_map self._client = (client or db_client.Instance()) self._active_users = dict() self._drain_callback = None if scan_ops: self._ScanAbandonedLocks() self._ScanFailedOps()
'Wait for all ops running on behalf of user_id to complete. WaitForOp behaves exactly like using the "synchronous" option when submitting an operation. The callback will be invoked once all operations are completed or they\'re backed off due to repeated failure.'
def WaitForUserOps(self, client, user_id, callback):
self.MaybeExecuteOp(client, user_id, None, callback)
'Invokes "callback" when there is no current work to be done. To be used for cleanup in tests.'
def Drain(self, callback):
if (not self._active_users): IOLoop.current().add_callback(callback) else: self._drain_callback = stack_context.wrap(callback)
'Adds the op\'s user to the queue and attempts to begin processing the operation. If the user is already locked by another server, or if this server is already executing operations for this user, then the operation is merely queued for later execution. If the "wait_callback" function is specified, then it is called onc...
def MaybeExecuteOp(self, client, user_id, operation_id, wait_callback=None):
from viewfinder.backend.op.user_op_manager import UserOpManager user_op_mgr = self._active_users.get(user_id, None) if (user_op_mgr is None): user_op_mgr = UserOpManager(client, self.op_map, user_id, partial(self._OnCompletedOp, user_id)) self._active_users[user_id] = user_op_mgr user_op...
'Removes the user from the list of active users, since all of that user\'s operations have been executed.'
def _OnCompletedOp(self, user_id):
del self._active_users[user_id] if ((not self._active_users) and self._drain_callback): IOLoop.current().add_callback(self._drain_callback) self._drain_callback = None
'Periodically scans the Operation table for operations which have failed and are ready to retry. If any are found, they are retried to see if the error that originally caused them to fail has been fixed.'
@gen.engine def _ScanFailedOps(self):
from viewfinder.backend.db.operation import Operation max_timeout_secs = OpManager._MAX_SCAN_FAILED_OPS_INTERVAL.total_seconds() while True: if (len(self._active_users) < self._MAX_USERS_OUTSTANDING): try: last_key = None while True: li...
'Periodically scans the Locks table looking for abandoned operation locks. If any are found, the associated operations are executed. TODO(Andy): Scanning for abandoned locks really should go into a LockManager class. See header for lock.py.'
@gen.engine def _ScanAbandonedLocks(self):
max_timeout_secs = OpManager._MAX_SCAN_ABANDONED_LOCKS_INTERVAL.total_seconds() while True: if (len(self._active_users) < self._MAX_USERS_OUTSTANDING): try: last_key = None while True: limit = min((self._MAX_USERS_OUTSTANDING - len(self._ac...
'Sets the per-process instance of the OpManager class.'
@staticmethod def SetInstance(op_manager):
OpManager._instance = op_manager
'Gets the per-process instance of the OpManager class.'
@staticmethod def Instance():
assert hasattr(OpManager, '_instance'), 'instance not initialized' return OpManager._instance
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, user_id, follower):
(yield UpdateFollowerOperation(client, user_id, follower)._UpdateFollower())
'Orchestrates the update follower operation by executing each of the phases in turn.'
@gen.coroutine def _UpdateFollower(self):
lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._viewpoint_id)) try: (yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify()) finally: (yield gen.Tas...
'Gathers pre-mutation information: 1. Queries for follower. 2. Queries for viewpoint. Validates the following: 1. Permission to update follower metadata. 2. Certain labels cannot be set.'
@gen.coroutine def _Check(self):
self._follower = (yield gen.Task(Follower.Query, self._client, self._user_id, self._viewpoint_id, None, must_exist=False)) if (self._follower is None): raise PermissionError(('User %d does not have permission to update follower "%s", or it does not exist.' % (se...
'Updates the database: 1. Updates the follower metadata.'
@gen.coroutine def _Update(self):
assert (('labels' not in self._foll_dict) or (set(self._follower.labels) == set(self._foll_dict['labels']))), (self._foll_dict, self._follower.labels) if ('viewed_seq' in self._foll_dict): if (self._foll_dict['viewed_seq'] > self._viewpoint.update_seq): self._foll_dict['viewed_seq'] = self._...
'Creates notifications: 1. Notify all of the user\'s devices that the follower has been updated.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyUpdateFollower(self._client, self._foll_dict))
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, user_id, viewpoint_id):
(yield RemoveViewpointOperation(client, user_id, viewpoint_id)._RemoveViewpoint())
'Orchestrates the update follower operation by executing each of the phases in turn.'
@gen.coroutine def _RemoveViewpoint(self):
lock = (yield gen.Task(Viewpoint.AcquireLock, self._client, self._viewpoint_id)) try: if (not (yield self._Check())): return self._client.CheckDBNotModified() (yield self._Update()) (yield self._Account()) (yield Operation.TriggerFailpoint(self._client)) ...
'Gathers pre-mutation information: 1. Queries for follower. Validates the following: 1. Permission to remove viewpoint. Returns True if all checks succeeded and operation execution should continue, or False if the operation should end immediately.'
@gen.coroutine def _Check(self):
self._follower = (yield gen.Task(Follower.Query, self._client, self._user_id, self._viewpoint_id, None, must_exist=False)) if (self._follower is None): raise PermissionError(('User %d does not have permission to remove viewpoint "%s", or it does not exist.' % (s...
'Updates the database: 1. Add the REMOVED label to the follower.'
@gen.coroutine def _Update(self):
(yield self._follower.RemoveViewpoint(self._client))
'Makes accounting changes: 1. Decrease user accounting by size of viewpoint.'
@gen.coroutine def _Account(self):
acc_accum = AccountingAccumulator() (yield acc_accum.RemoveViewpoint(self._client, self._user_id, self._viewpoint_id)) (yield acc_accum.Apply(self._client))
'Creates notifications: 1. Notify all of the user\'s devices that the viewpoint has been removed for them.'
@gen.coroutine def _Notify(self):
(yield NotificationManager.NotifyRemoveViewpoint(self._client, self._user_id, self._viewpoint_id))
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, activity, user_id, viewpoint_ids=[], episodes=[]):
user = (yield gen.Task(User.Query, client, user_id, None)) (yield SavePhotosOperation(client, activity, user, viewpoint_ids, episodes)._SavePhotos())
'Orchestrates the save_photos operation by executing each of the phases in turn.'
@gen.coroutine def _SavePhotos(self):
try: (yield self._lock_tracker.AcquireViewpointLock(self._user.private_vp_id)) (yield self._Check()) self._client.CheckDBNotModified() (yield self._Update()) (yield self._Account()) (yield Operation.TriggerFailpoint(self._client)) (yield self._Notify()) fi...
'Gathers pre-mutation information: 1. List of requested episodes and photos to save. 2. Checkpoints list of episode and post ids that need to be (re)created. 3. Acquires locks for all source viewpoints. Validates the following: 1. Permissions to share from source episodes.'
@gen.coroutine def _Check(self):
self._save_ep_dicts = (yield self._CreateSaveEpisodeDicts()) source_ep_posts_list = (yield ViewfinderOperation._CheckCopySources('save', self._client, self._user.user_id, self._save_ep_dicts)) target_ep_ids = [ep_dict['new_episode_id'] for ep_dict in self._save_ep_dicts] self._target_ep_dicts = Viewfind...
'Updates the database: 1. Creates new episodes and posts.'
@gen.coroutine def _Update(self):
(yield self._CreateNewEpisodesAndPosts(self._target_ep_dicts, self._new_ids))
'Makes accounting changes: 1. For new photos that were saved.'
@gen.coroutine def _Account(self):
photo_ids = [Post.DeconstructPostId(id)[1] for id in self._new_ids if id.startswith(IdPrefix.Post)] acc_accum = AccountingAccumulator() (yield acc_accum.SavePhotos(self._client, self._user.user_id, self._user.private_vp_id, photo_ids)) (yield acc_accum.Apply(self._client))
'Creates notifications: 1. Notifies all devices of the default viewpoint owner that new photos have been saved.'
@gen.coroutine def _Notify(self):
follower = (yield gen.Task(Follower.Query, self._client, self._user.user_id, self._user.private_vp_id, None)) (yield NotificationManager.NotifySavePhotos(self._client, self._user.private_vp_id, follower, self._act_dict, self._save_ep_dicts))
'Creates a list of dicts describing the source and target episodes of the save. The episode dicts passed in the save_photos request are combined with episodes in any of the viewpoints passed in the save_photos request. Returns the list.'
@gen.coroutine def _CreateSaveEpisodeDicts(self):
vp_ep_ids = [] skip_vp_ep_ids = set((ep_dict['existing_episode_id'] for ep_dict in self._ep_dicts)) ep_ph_ids = {} @gen.coroutine def _VisitPosts(photo_ids, post): photo_ids.append(post.photo_id) @gen.coroutine def _VisitEpisodeKeys(episode_key): episode_id = episode_key.hash...
'Raise assert if the DB has been modified by this client since ResetDBModified() was last called.'
def CheckDBNotModified(self):
assert (not self.HasDBBeenModified()), ('Something modified the db in an operation before it should have: %s' % self.GetModifiedDBStack())
'Sends an APNS and/or email alert to the given follower according to his alert settings.'
@classmethod @gen.coroutine def SendFollowerAlert(cls, client, user_id, badge, viewpoint, follower, settings, activity):
if (activity.name == 'add_followers'): args_dict = json.loads(activity.json) if (user_id not in args_dict['follower_ids']): return if follower.IsMuted(): return if ((settings.push_alerts is not None) and (settings.push_alerts != AccountSettings.PUSH_NONE)): alert_...
'Sends alert to the specified target user, notifying him that one of his contacts has registered for Viewfinder.'
@classmethod @gen.coroutine def SendRegisterAlert(cls, client, register_user_id, target_user_id, target_settings):
if ((target_settings.push_alerts is not None) and (target_settings.push_alerts != AccountSettings.PUSH_NONE)): if (register_user_id != target_user_id): target_name = (yield AlertManager._GetNameFromUserId(client, register_user_id, prefer_given_name=False)) alert_text = ('%s has ...
'Sends alert which will clear the specified user\'s badge.'
@classmethod @gen.coroutine def SendClearBadgesAlert(cls, client, user_id, exclude_device_id=None):
(yield AlertManager._SendDeviceAlert(client, user_id, viewpoint_id=None, badge=0, alert_text=None, exclude_device_id=exclude_device_id))
'Sends an APNS alert to the devices of the user who owns this NotificationManager. If "exclude_device_id" is not None, skip that device. The alert will embed the viewpoint_id as an extra "v" attribute if it\'s specified in the NotificationManager. This lets clients determine which viewpoint triggered the alert.'
@classmethod @gen.coroutine def _SendDeviceAlert(cls, client, user_id, viewpoint_id, badge, alert_text, exclude_device_id=None, sound=None):
try: extra = ({'v': viewpoint_id} if ((viewpoint_id is not None) and (alert_text is not None)) else None) (yield gen.Task(Device.PushNotification, client, user_id, alert_text, badge, exclude_device_id=exclude_device_id, extra=extra, sound=sound)) except: logging.exception('failed to ...
'Gets the text that will be pushed to the devices of users who follow the activity\'s viewpoint. This is async because some of the activity\'s identifiers may need to be resolved to actual objects in the database in order to construct the text.'
@classmethod @gen.coroutine def _FormatAlertText(cls, client, viewpoint, activity):
if (activity.name == 'add_followers'): alert_text = (yield AlertManager._FormatAddFollowersText(client, viewpoint, activity)) elif (activity.name == 'post_comment'): alert_text = (yield AlertManager._FormatPostCommentText(client, viewpoint, activity)) elif (activity.name == 'share_existing')...
'Gets the arguments to the email that will be sent to web-only customers who follow the activity\'s viewpoint.'
@classmethod @gen.coroutine def _FormatAlertEmail(cls, client, recipient_id, viewpoint, activity):
if ((activity.name == 'share_new') or (activity.name == 'add_followers')): email_args = (yield AlertManager._FormatConversationEmail(client, recipient_id, viewpoint, activity)) else: email_args = None raise gen.Return(email_args)
'Gets the arguments to the SMS that will be sent to web-only customers who follow the activity\'s viewpoint.'
@classmethod @gen.coroutine def _FormatAlertSMS(cls, client, recipient_id, viewpoint, activity):
if ((activity.name == 'share_new') or (activity.name == 'add_followers')): sms_args = (yield AlertManager._FormatConversationSMS(client, recipient_id, viewpoint, activity)) else: sms_args = None raise gen.Return(sms_args)
'Constructs the alert text for an "add_followers" operation, similar to this: Andy added you to a conversation: "And Then There Was Brick"'
@classmethod @gen.coroutine def _FormatAddFollowersText(cls, client, viewpoint, activity):
sharer_name = (yield AlertManager._GetNameFromUserId(client, activity.user_id)) raise gen.Return(('%s added you to a conversation%s' % (sharer_name, AlertManager._GetViewpointTitle(viewpoint))))
'Constructs the alert text for a "post_comment" operation, similar to this: Andy: What a great experience'
@classmethod @gen.coroutine def _FormatPostCommentText(cls, client, viewpoint, activity):
args_dict = json.loads(activity.json) comment = (yield gen.Task(Comment.Query, client, viewpoint.viewpoint_id, args_dict['comment_id'], None)) sharer_name = (yield AlertManager._GetNameFromUserId(client, activity.user_id)) raise gen.Return(('%s: %s' % (sharer_name, comment.message)))
'Constructs the alert text for a "share_existing" operation, similar to this: Andy shared 5 photos to: "And Then There Was Brick" Andy shared 5 photos'
@classmethod @gen.coroutine def _FormatShareExistingText(cls, client, viewpoint, activity):
sharer_name = (yield AlertManager._GetNameFromUserId(client, activity.user_id)) (episode_dates, num_shares) = AlertManager._GetShareInfo(activity) viewpoint_title = AlertManager._GetViewpointTitle(viewpoint) if viewpoint_title: raise gen.Return(('%s shared %d photo%s to%s' % (sharer_...
'Constructs the alert text for a "share_new" operation, similar to this: Andy started a conversation: "And Then There Was Brick" Andy shared 5 photos'
@classmethod @gen.coroutine def _FormatShareNewText(cls, client, viewpoint, activity):
sharer_name = (yield AlertManager._GetNameFromUserId(client, activity.user_id)) (episode_dates, num_shares) = AlertManager._GetShareInfo(activity) viewpoint_title = AlertManager._GetViewpointTitle(viewpoint) if viewpoint_title: raise gen.Return(('%s started a conversation%s' % (sharer_n...
'Constructs an SMS message which alerts the recipient that they have access to a new conversation, either due to a share_new operation, or to an add_followers operation. The SMS message includes a clickable link to the conversation on the web site.'
@classmethod @gen.coroutine def _FormatConversationSMS(cls, client, recipient_id, viewpoint, activity):
recipient_user = (yield gen.Task(User.Query, client, recipient_id, None)) if (recipient_user.phone is None): raise gen.Return(None) identity_key = ('Phone:%s' % recipient_user.phone) sharer = (yield gen.Task(User.Query, client, activity.user_id, None)) sharer_name = AlertManager._GetNameFrom...
'Constructs an email which alerts the recipient that they have access to a new conversation, either due to a share_new operation, or to an add_followers operation. The email includes a clickable link to the conversation on the web site.'
@classmethod @gen.coroutine def _FormatConversationEmail(cls, client, recipient_id, viewpoint, activity):
from viewfinder.backend.db.identity import Identity from viewfinder.backend.db.photo import Photo from viewfinder.backend.db.user import User recipient_user = (yield gen.Task(User.Query, client, recipient_id, None)) if (recipient_user.email is None): raise gen.Return(None) identity_key =...
'Gets the name of a user. Prefers the given name, then the full name, then the email, then just "A friend". If "prefer_given_name" is false, then don\'t use the given name.'
@classmethod def _GetNameFromUser(cls, user, prefer_given_name=True):
if (user.given_name and prefer_given_name): return user.given_name elif user.name: return user.name elif user.email: return user.email else: return 'A friend'
'Looks up a user by id and returns the name of the user by calling _GetNameFromUser.'
@classmethod @gen.coroutine def _GetNameFromUserId(cls, client, user_id, prefer_given_name=True):
from viewfinder.backend.db.user import User user = (yield gen.Task(User.Query, client, user_id, None)) raise gen.Return(AlertManager._GetNameFromUser(user, prefer_given_name))
'Returns the title of the viewpoint, or the empty string if no title exists.'
@classmethod def _GetViewpointTitle(cls, viewpoint):
viewpoint_title = (viewpoint.title if (viewpoint is not None) else None) if (viewpoint_title is not None): return (': "%s"' % viewpoint_title) return ''
'Returns a tuple with information about a "share_existing" or "share_new" operation: episode_dates: List of timestamps for each episode in the share. num_shares: Total count of photos shared.'
@classmethod def _GetShareInfo(cls, activity):
episode_dates = [] num_shares = 0 args_dict = json.loads(activity.json) for ep_dict in args_dict['episodes']: (ts, dev_id, uniquifier) = Episode.DeconstructEpisodeId(ep_dict['episode_id']) episode_dates.append(date.fromtimestamp(ts)) num_shares += len(ep_dict['photo_ids']) re...
'Creates a Short URL which links to a conversation on the website. If "use_short_domain" is true, then return a URL that uses the short domain, along with a shorter group_id prefix that will get re-mapped by ShortDomainRedirectHandler.'
@classmethod @gen.coroutine def _CreateViewpointURL(cls, client, recipient_user, identity_key, viewpoint, use_short_domain=False):
short_url = (yield Identity.CreateInvitationURL(client, recipient_user.user_id, identity_key, viewpoint.viewpoint_id, default_url=('/view#conv/%s' % viewpoint.viewpoint_id))) if use_short_domain: assert short_url.group_id.startswith('pr/'), short_url raise gen.Return(('https://%s/p%s%s' % (optio...
'Entry point called by the operation framework.'
@classmethod @gen.coroutine def Execute(cls, client, activity, user_id, viewpoint_id, remove_ids):
(yield RemoveFollowersOperation(client, activity, user_id, viewpoint_id, remove_ids)._RemoveFollowers())