def setSchedule(self, applet, schedule, **kwargs): import threading thisUser = self.getCurrentUser() if not AppletModel()._hasRole(applet['_id'], thisUser, 'user'): raise AccessException( "You aren't a user of this applet." ) profile = ProfileModel().findOne( { 'appletId': applet['_id'], 'userId': thisUser['_id'], 'profile': True } ) if not profile: raise AccessException( "You aren't a user of this applet." ) ud = profile["userDefined"] if "userDefined" in profile else {} ud["schedule"] = schedule profile["userDefined"] = ud ProfileModel().save(profile, validate=False) return(profile["userDefined"])
def changeUserName(self, username): user = self.getCurrentUser() old = self._model.setUserName(user, username) for p in list(ProfileModel().find(query={'userId': user['_id'], 'profile': True})): ProfileModel()._cacheProfileDisplay(p, user, forceManager=True) return {'message': 'username changed from {} to {}'.format(old, username)}
def removeIDCode(self, id, code): from bson.objectid import ObjectId user = self.getCurrentUser() try: p = ProfileModel().findOne({'_id': ObjectId(id)}) except: p = None if p is None or not AppletModel().isCoordinator(p['appletId'], user): raise AccessException( 'You do not have permission to update this user\'s ID code.') else: IDCode().removeCode(p['_id'], code) return (ProfileModel().profileAsUser( ProfileModel().load(p['_id'], force=True), user))
def get_profiles(self, notification): if len(notification['users']): return list(ProfileModel().get_profiles_by_ids(notification['users'])) notification_with_applet = list(PushNotificationModel().find(query={ 'applet': notification['applet'], 'users': { '$exists': True, '$ne': [] } })) notification_with_applet = list(set(user for n in notification_with_applet for user in n['users'])) profiles = list(ProfileModel().get_profiles_by_applet_id(notification['applet'])) # exclude existed users from general schedule return [profile for profile in profiles if profile['_id'] and profile['_id'] not in notification_with_applet]
def setOtherSchedule(self, profile, applet, schedule, **kwargs): import threading thisUser = self.getCurrentUser() if not AppletModel().isCoordinator(applet['_id'], thisUser): raise AccessException( "You aren't a coordinator or manager of this applet." ) if profile["appletId"] not in [applet['_id'], str(applet['_id'])]: raise AccessException( "That profile is not a user of this applet." ) ud = profile[ "coordinatorDefined" ] if "coordinatorDefined" in profile else {} ud["schedule"] = schedule profile["coordinatorDefined"] = ud ProfileModel().save(profile, validate=False) thread = threading.Thread( target=AppletModel().updateUserCacheAllUsersAllRoles, args=(applet, thisUser) ) thread.start() return(profile["coordinatorDefined"])
def updateUserCacheAllUsersAllRoles(self, applet, coordinator): from girderformindlogger.models.profile import Profile as ProfileModel [ self.updateUserCacheAllRoles(UserModel().load( id=ProfileModel().load(user['_id'], force=True).get('userId'), force=True)) for user in self.getAppletUsers( applet, coordinator).get('active', []) ]
def setUserRelationship(self, id, rel, otherId, otherName): from girderformindlogger.models.invitation import Invitation from girderformindlogger.utility.jsonld_expander import \ inferRelationships, oidIffHex user = self.getCurrentUser() grammaticalSubject = ProfileModel().getProfile(id, user) gsp = ProfileModel().load( grammaticalSubject['_id'], force=True ) grammaticalSubject = Invitation().load( grammaticalSubject['_id'], force=True ) if gsp is None else gsp print(grammaticalSubject) if grammaticalSubject is None or not AppletModel().isCoordinator( grammaticalSubject['appletId'], user ): raise AccessException( 'You do not have permission to update this user.' ) appletId = grammaticalSubject['appletId'] grammaticalObject = ProfileModel().getSubjectProfile( otherId, otherName, user ) if grammaticalObject is None: grammaticalObject = ProfileModel().getProfile( ProfileModel().createPassiveProfile( appletId, otherId, otherName, user )['_id'], grammaticalSubject ) if 'schema:knows' in grammaticalSubject: if rel in grammaticalSubject['schema:knows'] and grammaticalObject[ '_id' ] not in grammaticalSubject['schema:knows'][rel]: grammaticalSubject['schema:knows'][rel].append( grammaticalObject['_id'] ) else: grammaticalSubject['schema:knows'][rel] = [ grammaticalObject['_id'] ] else: grammaticalSubject['schema:knows'] = { rel: [grammaticalObject['_id']] } ProfileModel().save(grammaticalSubject, validate=False) inferRelationships(grammaticalSubject) return(ProfileModel().getProfile(id, user))
def sendPushNotifications(self): success = 0 error = 0 now = datetime.utcnow().strftime('%Y/%m/%d %H:%M') notifications = PushNotificationModel().find( query={ 'sendTime': { "$lt": now }, 'progress': ProgressState.ACTIVE }) for notification in notifications: users = [ UserModel().findOne({'_id': p['userId']}) for p in list(ProfileModel().find( query={ 'appletId': notification['applet'], 'userId': { '$exists': True } })) ] deviceIds = [ user['deviceId'] for user in users if ('deviceId' in user) and ( user.get('timezone', 0) == notification.get('timezone', 0)) ] proxy_dict = {} test_api_key = 'AAAAJOyOEz4:APA91bFudM5Cc1Qynqy7QGxDBa-2zrttoRw6ZdvE9PQbfIuAB9SFvPje7DcFMmPuX1IizR1NAa7eHC3qXmE6nmOpgQxXbZ0sNO_n1NITc1sE5NH3d8W9ld-cfN7sXNr6IAOuodtEwQy-' push_service = FCMNotification(api_key=test_api_key, proxy_dict=proxy_dict) registration_ids = deviceIds message_title = notification['head'] message_body = notification['content'] result = push_service.notify_multiple_devices( registration_ids=registration_ids, message_title=message_title, message_body=message_body) notification['attempts'] += 1 notification['progress'] = ProgressState.EMPTY if result['failure']: notification['progress'] = ProgressState.ERROR error += result['failure'] print(result['results']) if result['success']: notification['progress'] = ProgressState.SUCCESS success += result['success'] PushNotificationModel().save(notification, validate=False) return {'successed': success, 'errors': error}
def updateProfile(self, update={}, id=None, applet=None, idCode=None): if (id is not None) and (applet is not None or idCode is not None): raise RestException( 'Pass __either__ profile ID __OR__ (applet ID and ID code), ' 'not both.') elif (id is None) and (applet is None or idCode is None): raise RestException( 'Either profile ID __OR__ (applet ID and ID code) required.') else: currentUser = self.getCurrentUser() id = id if id is not None else Profile().getProfile( applet=AppletModel().load(applet, force=True), idCode=idCode, user=currentUser) return (ProfileModel().updateProfile(id, currentUser, update))
def deleteEvent(self, event_id): event = self.findOne({'_id': ObjectId(event_id)}) if event: if event['individualized']: ProfileModel().update( query={"_id": { "$in": event['data']['users'] }}, update={'$inc': { 'individual_events': -1 }}) push_notification = PushNotificationModel(event=event) push_notification.remove_schedules() self.removeWithQuery({'_id': ObjectId(event_id)})
def getUserByID(self, id): from bson.objectid import ObjectId user = self.getCurrentUser() return (ProfileModel().getProfile(id, user))