Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

User Customize Labels #946

Merged
merged 15 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 79 additions & 2 deletions emission/core/wrapper/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,14 @@ def getSettings(self):

@staticmethod
def createProfile(uuid, ts):
initProfileObj = {'user_id': uuid,
initProfileObj = {
'user_id': uuid,
'source':'Shankari',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: can eventually remove this source since it is hardcoded and never used. I don't remember the full history (will need to check the blame) but IIRC, it was an early attempt at multi-tenancy (e.g. users from my team versus from other teams at Berkeley)

'update_ts': ts,
'mpg_array': [defaultMpg]}
'mpg_array': [defaultMpg],
'mode': {},
'purpose': {}
}
writeResultProfile = get_profile_db().update_one(
{'user_id': uuid},
{'$set': initProfileObj},
Expand Down Expand Up @@ -225,3 +229,76 @@ def unregister(userEmail):
get_uuid_db().delete_one({'user_email': userEmail})
get_profile_db().delete_one({'user_id': uuid})
return uuid

def getUserCustomLabel(self, key):
user = get_profile_db().find_one({'user_id': self.uuid})
if key in user:
labels = user[key]
filteredLabels = {key: value for key, value in labels.items() if value.get('isActive', False)}
sortedLabels = dict(sorted(filteredLabels.items(), key=lambda x: (x[1]["frequency"]), reverse=True))
return list(sortedLabels)
else:
return []

def insertUserCustomLabel(self, inserted_label):
from datetime import datetime
user = get_profile_db().find_one({'user_id': self.uuid})
key = inserted_label['key']
label = inserted_label['label']
items = user[key] if key in user else {}

# if label exists in database, chage it as 'active' label
if label in items:
items[label]['isActive'] = True
else:
items[label] = {
'createdAt': datetime.now(),
'frequency': 0,
'isActive': True,
}

get_profile_db().update_one({'user_id': self.uuid}, {'$set': {key: items}})
return self.getUserCustomLabel(key)

def updateUserCustomLabel(self, updated_label):
from datetime import datetime
user = get_profile_db().find_one({'user_id': self.uuid})
key = updated_label['key']
items = user[key] if key in user else {}
old_label = updated_label['old_label']
new_label = updated_label['new_label']
is_new_label_must_added = updated_label['is_new_label_must_added']
# when a user changed a label to an exsiting customized label
if new_label in items:
updated_frequency = items[new_label]['frequency'] + 1
items[new_label]['frequency'] = updated_frequency
items[new_label]['isActive'] = True

# when a user added a new customized label
if is_new_label_must_added and not new_label in items:
items[new_label] = {
'createdAt': datetime.now(),
'frequency': 1,
'isActive': True,
}

# when a user chaged a label from an exsiting customized label
if old_label in items:
updated_frequency = items[old_label]['frequency'] - 1
items[old_label]['frequency'] = updated_frequency

get_profile_db().update_one({'user_id': self.uuid}, {'$set': {key: items}})
return self.getUserCustomLabel(key)

def deleteUserCustomLabel(self, deleted_label):
user = get_profile_db().find_one({'user_id': self.uuid})
key = deleted_label['key']
label = deleted_label['label']
items = user[key] if key in user else {}

if label in items:
items[label]['isActive'] = False

get_profile_db().update_one({'user_id': self.uuid}, {'$set': {key: items}})
return self.getUserCustomLabel(key)

41 changes: 41 additions & 0 deletions emission/net/api/cfc_webapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,47 @@ def getUserProfile():
user = User.fromUUID(user_uuid)
return user.getProfile()

@post('/customlabel/get')
def getUserCustomLabels():
logging.debug("Called getUserCustomLabels")
keys = request.json['keys']
user_uuid = getUUID(request)
user = User.fromUUID(user_uuid)
to_return = {}
for key in keys:
to_return[key] = user.getUserCustomLabel(key)
return to_return

@post('/customlabel/insert')
def insertUserCustomLabel():
logging.debug("Called insertUserCustomLabel")
inserted_label = request.json['inserted_label']
user_uuid = getUUID(request)
user = User.fromUUID(user_uuid)
to_return = user.insertUserCustomLabel(inserted_label)
logging.debug("Successfully inserted label for user %s" % user_uuid)
return { 'label' : to_return }

@post('/customlabel/update')
def updateUserCustomLabel():
logging.debug("Called updateUserCustomLabel")
updated_label = request.json['updated_label']
user_uuid = getUUID(request)
user = User.fromUUID(user_uuid)
to_return = user.updateUserCustomLabel(updated_label)
logging.debug("Successfully updated label label for user %s" % user_uuid)
return { 'label' : to_return }

@post('/customlabel/delete')
def deleteUserCustomLabel():
logging.debug("Called deleteUserCustomLabel")
deleted_label = request.json['deleted_label']
user_uuid = getUUID(request)
user = User.fromUUID(user_uuid)
to_return = user.deleteUserCustomLabel(deleted_label)
logging.debug("Successfully deleted label for user %s" % user_uuid)
return { 'label' : to_return }

@post('/result/metrics/<time_type>')
def summarize_metrics(time_type):
_fill_aggregate_backward_compat(request)
Expand Down
86 changes: 86 additions & 0 deletions emission/tests/coreTests/wrapperTests/TestUserCustomLabel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
# Standard imports
from future import standard_library
standard_library.install_aliases()
from builtins import *
import unittest

# Our imports
from emission.core.wrapper.user import User
import emission.tests.common as etc
import emission.core.get_database as edb

import emission.tests.common as etc

class TestUserCustomMode(unittest.TestCase):

def setUp(self):
self.user = User.register('[email protected]')

def testInitialGetUserCustomLabels(self):
self.assertListEqual(self.user.getUserCustomLabel('mode'), [])
self.assertListEqual(self.user.getUserCustomLabel('purpose'), [])

def testInsertCustomLabel(self):
inserted_mode = {
'key' : 'mode',
'label' : 'mode1',
}
mode = self.user.insertUserCustomLabel(inserted_mode)
self.assertListEqual(mode, ['mode1'])

inserted_purpose = {
'key' : 'purpose',
'label' : 'purpose1',
}
purpose = self.user.insertUserCustomLabel(inserted_purpose)
self.assertListEqual(purpose, ['purpose1'])

def tesUpdateUserCustomLabel(self):
self.testInsertCustomLabel()
updated_mode = {
'key' : 'mode',
'old_label' : '',
'new_label' : 'mode2',
'is_new_label_must_added': True
}
mode = self.user.updateUserCustomLabel(updated_mode)
self.assertListEqual(mode, ['mode2', 'mode1'])

updated_purpose = {
'key' : 'purpose',
'old_label' : '',
'new_label' : 'purpose2',
'is_new_label_must_added': True
}
purpose = self.user.updateUserCustomLabel(updated_purpose)
self.assertListEqual(purpose, ['purpose2', 'purpose1'])

def testDeleteUserCustomMode(self):
self.tesUpdateUserCustomLabel()
deleted_mode = {
'key' : 'mode',
'label' : 'mode2',
}
mode = self.user.deleteUserCustomLabel(deleted_mode)

self.assertListEqual(mode, ['mode1'])

deleted_purpose = {
'key' : 'purpose',
'label' : 'purpose2',
}
purpose = self.user.deleteUserCustomLabel(deleted_purpose)
self.assertListEqual(purpose, ['purpose1'])

def tearDown(self):
etc.dropAllCollections(edb._get_current_db())


if __name__ == '__main__':
etc.configLogging()
unittest.main()

Loading