GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 40fbfa...d5d9b4 )
by Daniel
51s
created

User.import_device()   C

Complexity

Conditions 7

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
c 0
b 0
f 0
dl 0
loc 33
rs 5.5
1
from __future__ import absolute_import
2
import json
3
import os
4
5
from ._connectorobject import ConnectorObject
6
7
8
class User(ConnectorObject):
9
10
    def create(self, email, password, role="user", public=True, **kwargs):
11
        """Creates the given user - using the passed in email and password.
12
13
        You can also set other default properties by passing in the relevant information::
14
15
            usr.create("my@email","mypass",description="I like trains.")
16
17
        Furthermore, ConnectorDB permits immediate initialization of an entire user tree,
18
        so that you can create all relevant devices and streams in one go::
19
20
            usr.create("my@email","mypass",devices={
21
                "device1": {
22
                    "nickname": "My train",
23
                    "streams": {
24
                        "stream1": {
25
                            "schema": "{\"type\":\"string\"}",
26
                            "datatype": "train.choochoo"
27
                        }
28
                    },
29
                }
30
            })
31
32
        The user and meta devices are created by default. If you want to add streams to the user device,
33
        use the "streams" option in place of devices in create.
34
        """
35
        kwargs["email"] = email
36
        kwargs["password"] = password
37
        kwargs["role"] = role
38
        kwargs["public"] = public
39
        self.metadata = self.db.create(
40
            self.path, kwargs).json()
41
42
    def set_password(self, new_password):
43 View Code Duplication
        """Sets a new password for the user"""
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
44
        self.set({"password": new_password})
45
46
    def devices(self):
47
        """Returns the list of devices that belong to the user"""
48
        result = self.db.read(self.path, {"q": "ls"})
49
50
        if result is None or result.json() is None:
51
            return []
52
        devices = []
53
        for d in result.json():
54
            dev = self[d["name"]]
55
            dev.metadata = d
56
            devices.append(dev)
57
        return devices
58
59
    def __getitem__(self, device_name):
60
        """Gets the child device by name"""
61
        return Device(self.db, self.path + "/" + device_name)
62
63
    def __repr__(self):
64
        """Returns a string representation of the user"""
65
        return "[User:%s]" % (self.path, )
66
67
    def export(self, directory):
68
        """Exports the ConnectorDB user into the given directory.
69
        The resulting export can be imported by using the import command (cdb.import(directory)),
70
71
        Note that Python cannot export passwords, since the REST API does
72
        not expose password hashes. Therefore, the imported user will have
73
        password same as username.
74
75
        The user export function is different than device and stream exports because
76
        it outputs a format compatible directly with connectorDB's import functionality:
77
78
            connectordb import <mydatabase> <directory>
79
80
        This also means that you can export multiple users into the same directory without issue
81
        """
82
83
        exportInfoFile = os.path.join(directory, "connectordb.json")
84
        if os.path.exists(directory):
85
            # Ensure that there is an export there already, and it is version 1
86
            if not os.path.exists(exportInfoFile):
87
                raise FileExistsError(
88
                    "The export directory already exsits, and is not a ConnectorDB export.")
89
            with open(exportInfoFile) as f:
90
                exportInfo = json.load(f)
91
            if exportInfo["Version"] != 1:
92
                raise ValueError(
93
                    "Could not export to directory: incompatible export versions.")
94
        else:
95
            # The folder doesn't exist. Make it.
96
            os.mkdir(directory)
97
98
            with open(exportInfoFile, "w") as f:
99
                json.dump(
100
                    {"Version": 1, "ConnectorDB": self.db.get("meta/version").text}, f)
101
102
        # Now we create the user directory
103
        udir = os.path.join(directory, self.name)
104
        os.mkdir(udir)
105
106
        # Write the user's info
107
        with open(os.path.join(udir, "user.json"), "w") as f:
108
            json.dump(self.data, f)
109
110
        # Now export the devices one by one
111
        for d in self.devices():
112
            d.export(os.path.join(udir, d.name))
113
114
    def import_device(self, directory):
115
        """Imports a device from the given directory. You export the device
116
        by using device.export()
117
118
        There are two special cases: user and meta devices. 
119
        If the device name is meta, import_device will not do anything. 
120
        If the device name is "user", import_device will overwrite the user device
121
        even if it exists already.
122
        """
123
124
        # read the device's info
125
        with open(os.path.join(directory, "device.json"), "r") as f:
126
            ddata = json.load(f)
127
128
        d = self[ddata["name"]]
129
130
        dname = ddata["name"]
131
        del ddata["name"]
132
133
        if dname == "meta":
134
            return
135
        elif dname == "user":
136
            d.set(ddata)
137
        elif d.exists():
138
            raise ValueError("The device " + d.name + " already exists")
139
        else:
140
            d.create(**ddata)
141
142
        # Now import all of the streams
143
        for name in os.listdir(directory):
144
            sdir = os.path.join(directory, name)
145
            if os.path.isdir(sdir):
146
                d.import_stream(sdir)
147
148
    # -----------------------------------------------------------------------
149
    # Following are getters and setters of the user's properties
150
151
    @property
152
    def email(self):
153
        """gets the user's email address"""
154
        if "email" in self.data:
155
            return self.data["email"]
156
        return None
157
158
    @email.setter
159
    def email(self, new_email):
160
        """sets the user's email address"""
161
        self.set({"email": new_email})
162
163
    @property
164
    def public(self):
165
        """gets whether the user is public
166
        (this means different things based on connectordb permissions setup - connectordb.com
167
        has this be whether the user is publically visible. Devices are individually public/private.)
168
        """
169
        if "public" in self.data:
170
            return self.data["public"]
171
        return None
172
173
    @public.setter
174
    def public(self, new_public):
175
        """Attempts to set whether the user is public"""
176
        self.set({"public": new_public})
177
178
    @property
179
    def role(self):
180
        """Gets the role of the user. This is the permissions level that the user has. It might
181
        not be accessible depending on the permissions setup of ConnectorDB. Returns None if not accessible"""
182
        if "role" in self.data:
183
            return self.data["role"]
184
        return None
185
186
    @role.setter
187
    def role(self, new_role):
188
        """ Attempts to set the user's role"""
189
        self.set({"role": new_role})
190
191
# The import has to go on the bottom because py3 imports are annoying
192
from ._device import Device
193