feat: build access level labels from their bits and project names
Labels came from a fixed table matched by subset, so Storage (no bits) matched any level the table lacked, and a level was named after the first entry it contained: the server's Brain/MINDS 2.0 folders (0x10000) showed as Storage and 0x10104 as CBS or PW Open. Labels are now composed from the bits. Projects (bit 16 and up) take the names the server reports to their members through users/current/, and otherwise Project<n>; restrict slot 1 is CBS and any other Restrict<n>. A level with no meaning is shown as Unknown (0x...). chacl reads keys built the same way, refuses public and storage before any request, and lists the user's projects with their keys when given an invalid level.
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
from dataclasses import field
|
||||
from typing import Final
|
||||
|
||||
import requests
|
||||
@@ -20,6 +21,13 @@ class UsersCurrentResponseLaboratory:
|
||||
role: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UsersCurrentResponseProject:
|
||||
id: int
|
||||
name: str | None
|
||||
bit_position: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UsersApiCurrentResponse:
|
||||
id: int
|
||||
@@ -35,6 +43,7 @@ class UsersApiCurrentResponse:
|
||||
is_reviewer: bool
|
||||
last_login: str # ISO8601
|
||||
date_joined: str # ISO8601
|
||||
projects: list[UsersCurrentResponseProject] = field(default_factory=list)
|
||||
|
||||
|
||||
class UsersApi(BaseApi):
|
||||
@@ -50,6 +59,20 @@ class UsersApi(BaseApi):
|
||||
user = User(id=obj.id, username=obj.username, laboratory_ids=laboratory_ids, is_reviewer=obj.is_reviewer)
|
||||
return user
|
||||
|
||||
def project_names(self) -> dict[int, str]:
|
||||
"""Names of the user's projects by bit_position, the bit their access level sets."""
|
||||
url = self.ENTRYPOINT + "current/"
|
||||
response = self.connection.get(url)
|
||||
self._raise_response_error(response)
|
||||
obj = TypeAdapter(UsersApiCurrentResponse).validate_python(response.json())
|
||||
names: dict[int, list[str]] = {}
|
||||
for project in obj.projects:
|
||||
if project.name:
|
||||
# bit_position is not unique on the server, and a folder at a shared bit
|
||||
# belongs to every project holding it, so all of them are named.
|
||||
names.setdefault(project.bit_position, []).append(project.name)
|
||||
return {bit: ", ".join(sorted(x)) for bit, x in names.items()}
|
||||
|
||||
def token(self, username: str, password: str) -> Token:
|
||||
# print(self.__class__.__name__ + "::" + sys._getframe().f_code.co_name)
|
||||
url = self.ENTRYPOINT + "token/"
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
from argparse import Namespace
|
||||
from typing import Any
|
||||
from typing import Any, Final
|
||||
|
||||
import requests
|
||||
|
||||
from mdrsclient.commands.base import BaseCommand
|
||||
from mdrsclient.exceptions import IllegalArgumentException
|
||||
from mdrsclient.exceptions import IllegalArgumentException, MDRSException
|
||||
from mdrsclient.models import FolderAccessLevel
|
||||
|
||||
|
||||
class ChaclCommand(BaseCommand):
|
||||
ACCESS_LEVEL_HELP: Final[str] = (
|
||||
"access level: private, pw_open, cbs_open, project<n>_open, "
|
||||
"or several open levels joined by `_or_` (e.g. cbs_or_pw_open). "
|
||||
"<n> is the project's bit position; an invalid level lists the projects you belong to"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def register(cls, parsers: Any) -> None:
|
||||
chacl_parser = parsers.add_parser("chacl", help="change the folder access level")
|
||||
chacl_parser.add_argument("access_level", help="access level (private, cbs_open, pw_open)")
|
||||
chacl_parser.add_argument("access_level", help=cls.ACCESS_LEVEL_HELP)
|
||||
chacl_parser.add_argument("-r", "--recursive", help="change access levels recursively", action="store_true")
|
||||
chacl_parser.add_argument("-p", "--password", help="password to set when access level is `pw_open`")
|
||||
chacl_parser.add_argument(
|
||||
"-p", "--password", help="password to set when the access level includes `pw` (e.g. pw_open)"
|
||||
)
|
||||
chacl_parser.add_argument("remote_path", help="remote folder path (remote:/lab/path/)")
|
||||
chacl_parser.set_defaults(func=cls.func)
|
||||
|
||||
@@ -21,9 +31,10 @@ class ChaclCommand(BaseCommand):
|
||||
remote_path = str(args.remote_path)
|
||||
access_level = FolderAccessLevel.key2id(str(args.access_level))
|
||||
if access_level is None:
|
||||
raise IllegalArgumentException(
|
||||
"Invalid `access_level` parameter. must be `private`, `cbs_open` or `pw_open`."
|
||||
)
|
||||
raise IllegalArgumentException(cls._invalid_level_message(remote_path))
|
||||
if access_level in (FolderAccessLevel.STORAGE, FolderAccessLevel.PUBLIC):
|
||||
# The server refuses both; saying so here spares a round trip and a bare 400.
|
||||
raise IllegalArgumentException(f"`{args.access_level}` cannot be set as an access level.")
|
||||
password = str(args.password) if args.password else None
|
||||
is_recursive = bool(args.recursive)
|
||||
cls.chacl(remote_path, access_level, is_recursive, password)
|
||||
@@ -35,3 +46,24 @@ class ChaclCommand(BaseCommand):
|
||||
|
||||
client = MdrsClient.from_remote(remote)
|
||||
client.chacl(remote_path, access_level, is_recursive, password)
|
||||
|
||||
@classmethod
|
||||
def _invalid_level_message(cls, remote_path: str) -> str:
|
||||
message = (
|
||||
"Invalid `access_level` parameter. must be `private`, `pw_open`, `cbs_open`, `project<n>_open` "
|
||||
"or open levels joined by `_or_` (e.g. `cbs_or_pw_open`)."
|
||||
)
|
||||
remote = remote_path.split(":", 1)[0] if ":" in remote_path else ""
|
||||
from mdrsclient.client import MdrsClient
|
||||
|
||||
# The project numbers are known only to the server, and only for the user's own
|
||||
# projects. Not reaching it leaves the message as it is: the error being reported
|
||||
# is the level, not the connection.
|
||||
try:
|
||||
projects = MdrsClient.from_remote(remote).project_names()
|
||||
except (MDRSException, requests.RequestException):
|
||||
return message
|
||||
if not projects:
|
||||
return message
|
||||
lines = [f" project{bit}_open: {name}" for bit, name in sorted(projects.items())]
|
||||
return "\n".join([message, "Projects you belong to:", *lines])
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import json
|
||||
from argparse import Namespace
|
||||
from dataclasses import field
|
||||
from typing import Any, Final
|
||||
|
||||
from pydantic.dataclasses import dataclass
|
||||
@@ -26,6 +27,7 @@ class LsCommandContext:
|
||||
is_json: bool
|
||||
is_quiet: bool
|
||||
is_recursive: bool
|
||||
projects: dict[int, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
class LsCommand(BaseCommand):
|
||||
@@ -85,6 +87,7 @@ class LsCommand(BaseCommand):
|
||||
is_json,
|
||||
is_quiet,
|
||||
is_recursive,
|
||||
client.project_names(),
|
||||
)
|
||||
if context.is_json:
|
||||
cls._ls_json(context, folder, files)
|
||||
@@ -110,7 +113,7 @@ class LsCommand(BaseCommand):
|
||||
length = {key: len(label) if not context.is_quiet else 0 for key, label in cls.LABELS.items()}
|
||||
for sub_folder in folder.sub_folders:
|
||||
sub_laboratory_name = cls._laboratory_name(context, sub_folder.laboratory_id)
|
||||
length["acl"] = max(length["acl"], len(sub_folder.access_level_name))
|
||||
length["acl"] = max(length["acl"], len(sub_folder.access_level_label(context.projects)))
|
||||
length["laboratory"] = max(length["laboratory"], len(sub_laboratory_name))
|
||||
length["size"] = max(length["size"], len(str(sub_folder.size)))
|
||||
length["date"] = max(length["date"], len(sub_folder.updated_at_name))
|
||||
@@ -119,7 +122,7 @@ class LsCommand(BaseCommand):
|
||||
length["size"] = max(length["size"], len(str(file.size)))
|
||||
length["date"] = max(length["date"], len(file.updated_at_name))
|
||||
length["name"] = max(length["name"], len(file.name))
|
||||
length["acl"] = max(length["acl"], len(folder.access_level_name))
|
||||
length["acl"] = max(length["acl"], len(folder.access_level_label(context.projects)))
|
||||
length["laboratory"] = max(length["laboratory"], len(context.laboratory.name))
|
||||
return length
|
||||
|
||||
@@ -159,14 +162,15 @@ class LsCommand(BaseCommand):
|
||||
for sub_folder in sorted(folder.sub_folders, key=lambda x: x.name):
|
||||
sub_laboratory_name = cls._laboratory_name(context, sub_folder.laboratory_id)
|
||||
sub_folder_type = "[d]" if sub_folder.lock is False else "[l]"
|
||||
sub_folder_acl = sub_folder.access_level_label(context.projects)
|
||||
print(
|
||||
f"{sub_folder_type:{length['type']}}\t{sub_folder.access_level_name:{length['acl']}}\t"
|
||||
f"{sub_folder_type:{length['type']}}\t{sub_folder_acl:{length['acl']}}\t"
|
||||
f"{sub_laboratory_name:{length['laboratory']}}\t{sub_folder.size:{length['size']}}\t"
|
||||
f"{sub_folder.updated_at_name:{length['date']}}\t{sub_folder.name:{length['name']}}"
|
||||
)
|
||||
for file in sorted(files, key=lambda x: x.name):
|
||||
print(
|
||||
f"{'[f]':{length['type']}}\t{folder.access_level_name:{length['acl']}}\t"
|
||||
f"{'[f]':{length['type']}}\t{folder.access_level_label(context.projects):{length['acl']}}\t"
|
||||
f"{context.laboratory.name:{length['laboratory']}}\t{file.size:{length['size']}}\t"
|
||||
f"{file.updated_at_name:{length['date']}}\t{file.name:{length['name']}}"
|
||||
)
|
||||
@@ -183,7 +187,7 @@ class LsCommand(BaseCommand):
|
||||
"pid": folder.pid,
|
||||
"name": folder.name,
|
||||
"size": folder.size,
|
||||
"access_level": folder.access_level_name,
|
||||
"access_level": folder.access_level_label(context.projects),
|
||||
"lock": folder.lock,
|
||||
"laboratory": cls._laboratory_name(context, folder.laboratory_id),
|
||||
"description": folder.description,
|
||||
|
||||
+90
-25
@@ -1,4 +1,5 @@
|
||||
from typing import Any, Final, NamedTuple
|
||||
import re
|
||||
from typing import Any, Final, Mapping
|
||||
from unicodedata import normalize
|
||||
|
||||
from pydantic.dataclasses import dataclass
|
||||
@@ -6,39 +7,99 @@ from pydantic.dataclasses import dataclass
|
||||
from mdrsclient.models.utils import iso8601_to_user_friendly
|
||||
|
||||
|
||||
class FolderAccessLevelItem(NamedTuple):
|
||||
mask: int
|
||||
key: str
|
||||
label: str
|
||||
|
||||
|
||||
class FolderAccessLevel:
|
||||
# Bit Mask
|
||||
# - bit 0: Is Private
|
||||
# - bit 1: Is Public
|
||||
# - bit 2: With Password
|
||||
# - bit 3-7: (Reserved)
|
||||
# - bit 8-15: Restricted Open
|
||||
ACCESS_LEVELS: Final[list[FolderAccessLevelItem]] = [
|
||||
FolderAccessLevelItem(0x0204, "5kikan_or_pw_open", "5Kikan or PW Open"),
|
||||
FolderAccessLevelItem(0x0104, "cbs_or_pw_open", "CBS or PW Open"),
|
||||
FolderAccessLevelItem(0x0200, "5kikan_open", "5Kikan Open"),
|
||||
FolderAccessLevelItem(0x0100, "cbs_open", "CBS Open"),
|
||||
FolderAccessLevelItem(0x0004, "pw_open", "PW Open"),
|
||||
FolderAccessLevelItem(0x0002, "public", "Public"),
|
||||
FolderAccessLevelItem(0x0001, "private", "Private"),
|
||||
FolderAccessLevelItem(0x0000, "storage", "Storage"),
|
||||
]
|
||||
# - bit 8-15: Restricted Open, one bit per restrict network slot (slot 1 is bit 8)
|
||||
# - bit 16-: Project Open, one bit per project bit_position (bit_position 0 is bit 16)
|
||||
STORAGE: Final[int] = 0x0000
|
||||
PRIVATE: Final[int] = 0x0001
|
||||
PUBLIC: Final[int] = 0x0002
|
||||
PASSWORD: Final[int] = 0x0004
|
||||
RESERVED: Final[int] = 0x00F8
|
||||
RESTRICT_SHIFT: Final[int] = 8
|
||||
RESTRICT_SLOTS: Final[int] = 8
|
||||
PROJECT_SHIFT: Final[int] = 16
|
||||
# The server keeps no names for its restrict networks, so the one in use is named here.
|
||||
# Any other slot is named after its number.
|
||||
RESTRICT_NAMES: Final[dict[int, str]] = {1: "CBS"}
|
||||
LEVEL_NAMES: Final[dict[int, str]] = {STORAGE: "Storage", PRIVATE: "Private", PUBLIC: "Public"}
|
||||
|
||||
@staticmethod
|
||||
def restrict_name(slot: int) -> str:
|
||||
return FolderAccessLevel.RESTRICT_NAMES.get(slot, f"Restrict{slot}")
|
||||
|
||||
@staticmethod
|
||||
def project_name(bit_position: int, projects: Mapping[int, str] | None = None) -> str:
|
||||
name = (projects or {}).get(bit_position)
|
||||
return name if name else f"Project{bit_position}"
|
||||
|
||||
@staticmethod
|
||||
def id2label(id: int, projects: Mapping[int, str] | None = None) -> str | None:
|
||||
"""
|
||||
Label an access level from its bits, e.g. 0x0104 is "CBS or PW Open".
|
||||
|
||||
`projects` names the projects by bit_position, as the server tells their members;
|
||||
any other project gets a name made from its bit_position. None for a level that
|
||||
has no meaning: Private or Public with any other bit, or a reserved bit.
|
||||
"""
|
||||
if id in FolderAccessLevel.LEVEL_NAMES:
|
||||
return FolderAccessLevel.LEVEL_NAMES[id]
|
||||
if id < 0 or id & (FolderAccessLevel.PRIVATE | FolderAccessLevel.PUBLIC | FolderAccessLevel.RESERVED):
|
||||
return None
|
||||
names = [
|
||||
FolderAccessLevel.restrict_name(slot)
|
||||
for slot in range(1, FolderAccessLevel.RESTRICT_SLOTS + 1)
|
||||
if id & (1 << (FolderAccessLevel.RESTRICT_SHIFT + slot - 1))
|
||||
]
|
||||
project_bits = id >> FolderAccessLevel.PROJECT_SHIFT
|
||||
names += [
|
||||
FolderAccessLevel.project_name(bit, projects)
|
||||
for bit in range(project_bits.bit_length())
|
||||
if project_bits & (1 << bit)
|
||||
]
|
||||
if id & FolderAccessLevel.PASSWORD:
|
||||
names.append("PW")
|
||||
return " or ".join(names) + " Open"
|
||||
|
||||
@staticmethod
|
||||
def key2id(key: str) -> int | None:
|
||||
acl = next((x for x in FolderAccessLevel.ACCESS_LEVELS if x.key == key), None)
|
||||
return acl.mask if acl is not None else None
|
||||
"""
|
||||
The access level a key names: `private`, `public`, `storage`, or the parts of an
|
||||
open level joined by `_or_` and ending in `_open`, e.g. `cbs_or_pw_open`. A part
|
||||
is `pw`, `cbs`, `restrict<slot>` or `project<bit_position>`.
|
||||
"""
|
||||
fixed = {label.lower(): id for id, label in FolderAccessLevel.LEVEL_NAMES.items()}
|
||||
if key in fixed:
|
||||
return fixed[key]
|
||||
if not key.endswith("_open"):
|
||||
return None
|
||||
id = 0
|
||||
for part in key.removesuffix("_open").split("_or_"):
|
||||
bit = FolderAccessLevel._part2bit(part)
|
||||
if bit is None:
|
||||
return None
|
||||
id |= bit
|
||||
return id
|
||||
|
||||
@staticmethod
|
||||
def id2label(id: int) -> str | None:
|
||||
acl = next((x for x in FolderAccessLevel.ACCESS_LEVELS if (x.mask & id) == x.mask), None)
|
||||
return acl.label if acl is not None else None
|
||||
def _part2bit(part: str) -> int | None:
|
||||
if part == "pw":
|
||||
return FolderAccessLevel.PASSWORD
|
||||
slots = {name.lower(): slot for slot, name in FolderAccessLevel.RESTRICT_NAMES.items()}
|
||||
match = re.fullmatch(r"restrict([1-9][0-9]*)", part)
|
||||
slot = slots.get(part, int(match.group(1)) if match else None)
|
||||
if slot is not None:
|
||||
if slot > FolderAccessLevel.RESTRICT_SLOTS:
|
||||
return None
|
||||
return 1 << (FolderAccessLevel.RESTRICT_SHIFT + slot - 1)
|
||||
match = re.fullmatch(r"project(0|[1-9][0-9]*)", part)
|
||||
if match:
|
||||
return 1 << (FolderAccessLevel.PROJECT_SHIFT + int(match.group(1)))
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -55,10 +116,14 @@ class FolderSimple:
|
||||
updated_at: str
|
||||
restrict_opened_at: str | None
|
||||
|
||||
def access_level_label(self, projects: Mapping[int, str] | None = None) -> str:
|
||||
"""The access level as shown to a user, naming the projects given by bit_position."""
|
||||
label = FolderAccessLevel.id2label(self.access_level, projects)
|
||||
return label if label is not None else f"Unknown (0x{self.access_level:x})"
|
||||
|
||||
@property
|
||||
def access_level_name(self) -> str:
|
||||
label = FolderAccessLevel.id2label(self.access_level)
|
||||
return label if label is not None else ""
|
||||
return self.access_level_label()
|
||||
|
||||
@property
|
||||
def lock_name(self) -> str:
|
||||
|
||||
@@ -3,6 +3,7 @@ import re
|
||||
from unicodedata import normalize
|
||||
|
||||
from mdrsclient.api import DoiApi, FilesApi, FoldersApi, LaboratoriesApi, UsersApi
|
||||
from mdrsclient.api.utils import token_check
|
||||
from mdrsclient.cache import CacheInterface
|
||||
from mdrsclient.config import ConfigFile, ConfigInterface
|
||||
from mdrsclient.connection import MDRSConnection
|
||||
@@ -66,6 +67,17 @@ class MdrsService:
|
||||
def logout(self) -> None:
|
||||
self.connection.logout()
|
||||
|
||||
def project_names(self) -> dict[int, str]:
|
||||
"""
|
||||
Names of the logged-in user's projects by bit_position, for labelling access levels.
|
||||
|
||||
Empty when nobody is logged in: the server names a project only to its members.
|
||||
"""
|
||||
token_check(self.connection)
|
||||
if self.connection.token is None:
|
||||
return {}
|
||||
return UsersApi(self.connection).project_names()
|
||||
|
||||
def whoami(self) -> User:
|
||||
user_api = UsersApi(self.connection)
|
||||
return user_api.current()
|
||||
|
||||
Reference in New Issue
Block a user