Esempio n. 1
0
def signup(username, password, phonenum, deviceid):
    """
    Handles put requests for signups from our Android app
    """
    # hash the password
    pwhash = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    # check to see if a username is already in the database
    userexist = User.objects.filter(username=username).exists()

    if userexist:
        return "User already exists"

    user = User(username=username,
                pwhash=pwhash,
                phonenum=phonenum,
                deviceid=deviceid)
    user.save()

    device = Device(deviceid=deviceid,
                    username=username,
                    pendingrequest=False,
                    requestgranted=False,
                    imagebytes='')
    device.save()

    return "User and Device added"
Esempio n. 2
0
class DeviceModelTestCase(TestCase):
    """This class defines the test suite for the Device model."""
    def create_company(self, name="Apple"):
        return Company.objects.create(name=name)

    def create_device_model(self,
                            name="iPhone 3GS",
                            release_year=2000,
                            company=None):
        company = self.create_company()
        return DeviceModel.objects.create(name=name,
                                          release_year=release_year,
                                          company=company)

    def setUp(self):
        """Define the test client and other test variables."""
        self.color = "Black"
        self.capacity = 32
        self.os_version = "iOS 6"
        self.device_model = self.create_device_model()
        self.device = Device(color=self.color,
                             capacity=self.capacity,
                             os_version=self.os_version,
                             device_model=self.device_model)

    def test_model_can_create_a_device(self):
        """Test the device model can create a device."""
        old_count = Device.objects.count()
        self.device.save()
        new_count = Device.objects.count()
        self.assertNotEqual(old_count, new_count)
Esempio n. 3
0
    def __process_record(cls, path):
        """Read, extract and store a single Dreem records data."""
        try:
            record = h5py.File(path, 'r')
        except OSError:
            # The file is still copying. It will be considered again on next poll.
            return

        # These two attributes are stored as ASCII strings.
        username = str(record.attrs["user"], "utf-8")
        devicename = str(record.attrs["device"], "utf-8")

        # Retrieving the user
        try:
            user = User.objects.get(username=username)
        except ObjectDoesNotExist:
            print("Unknown user, skipping the record…")
            path.unlink()
            return

        # Retrieving the device
        try:
            device = Device.objects.get(name=devicename)
        except Device.DoesNotExist:
            # Temporary: we create the device
            print("Unknown device, inserting…")
            device = Device(name=devicename,
                            dreempy_version=record.attrs["dreempy_version"])
            device.save()

        record = Record(
            start_time=datetime.fromtimestamp(int(record.attrs["start_time"]),
                                              timezone(timedelta(hours=1))),
            stop_time=datetime.fromtimestamp(int(record.attrs["stop_time"]),
                                             timezone(timedelta(hours=1))),
            sleep_start_time=datetime.fromtimestamp(
                int(record.attrs["sleep_start_time"]),
                timezone(timedelta(hours=1))),
            sleep_stop_time=datetime.fromtimestamp(
                int(record.attrs["sleep_stop_time"]),
                timezone(timedelta(hours=1))),
            sleep_score=record.attrs["sleep_score"],
            number_of_stimulations=int(record.attrs["number_of_stimulations"]),
            number_of_wake=int(record.attrs["number_of_wake"]),
            hypnogram=JSONRenderer().render(
                record["reporting"]["dreemnogram"][()]),
            user=user,
            device=device)
        record.save()
        path.unlink()
Esempio n. 4
0
def POST_devices(request, format):
    """ Respond to the "POST devices" request.

        We create a new device in the system, overwriting the existing device
        if it exists.
    """
    # Get the request parameters.

    params = apiHelper.get_params(request, resource_name="device")

    error = apiHelper.check_params(params,
                                   required_params=["token",
                                                    "notification_type",
                                                    "notification_token"])
    if error != None: return error

    token              = params['token']
    notification_type  = params['notification_type']
    notification_token = params['notification_token']

    if not session.validate(token):
        return HttpResponseBadRequest("Invalid token")

    user = session.get_user(token)

    # Delete any existing devices with the given notification type and token.

    Device.objects.filter(notification_type=notification_type,
                          notification_token=notification_token).delete()

    # Create the new device.

    device = Device()
    device.user               = user
    device.notification_type  = notification_type
    device.notification_token = notification_token
    device.created_at         = datetime.datetime.now()
    device.updated_at         = datetime.datetime.now()
    device.save()

    # Finally, return the device back to our caller.

    return apiHelper.response({'device' : device.to_dict()},
                              format=format, status=HTTP_RESPONSE_POST_OK)
Esempio n. 5
0
    def handle(self, *args, **options):

        try:

            contest = Contest.objects.all()
            contest.delete()

            contest_2014 = Contest()
            contest_2014.year = 2014
            contest_2014.theme = 'Ritim'
            contest_2014.poster = 'http://beste.halici.com.tr/afis/2014.jpg'
            contest_2014.start_date = datetime.datetime(2014, 6, 1, 0, 0)
            contest_2014.final_date = datetime.datetime(2014, 11, 1, 0, 0)
            contest_2014.finish_date = datetime.datetime(2014, 12, 15, 0, 0)
            contest_2014.save()

            contest_2015 = Contest()
            contest_2015.year = 2015
            contest_2014.theme = 'Attila Özdemiroğlu'
            contest_2014.poster = 'http://beste.halici.com.tr/afis/2015.jpg'
            contest_2015.start_date = datetime.datetime(2015, 6, 1, 0, 0)
            contest_2015.final_date = datetime.datetime(2015, 11, 1, 0, 0)
            contest_2015.finish_date = datetime.datetime(2015, 12, 15, 0, 0)
            contest_2015.save()

            devices = Device.objects.all()
            devices.delete()

            device = Device()
            device.name = 'Bilgisayar'
            device.save()

            softwares = Software.objects.all()
            softwares.delete()

            software = Software()
            software.name = 'FL Studio'
            software.save()

            stage_materials = StageMaterial.objects.all()
            stage_materials.delete()

            stage_material = StageMaterial()
            stage_material.name = 'Gitar'
            stage_material.save()

            contents = Content.objects.all()
            contents.delete()

            content_file = open('default_contents/api_content.csv', 'rb')
            reader = csv.reader(content_file)

            for row in reader:
                content = Content()
                content.create_date = row[1]
                content.title = row[2]
                content.link = row[3]
                content.content = row[4]
                content.category_name = row[5]
                content.is_active = True if row[7] == '1' else False
                content.is_for_static_content = True if row[8] == '1' else False

                content.save()

            content_vote = Content()
            content_vote.title = 'Oylama'
            content_vote.link = 'oylama'
            content_vote.category_name = 'link'
            content_vote.is_active = True
            content_vote.is_for_static_content = False
            content_vote.save()

            users = User.objects.all()
            users.delete()

            user = User()
            user.username = '******'
            user.email = '*****@*****.**'
            user.first_name = 'Abdullah'
            user.last_name = 'Karacabey'
            user.set_password('674311')
            user.addres = 'Bağlum'
            user.city = 'Ankara'
            user.save()

            compositions = Composition.objects.all()
            compositions.delete()

            composition_1 = Composition()
            composition_1.owner = user
            composition_1.contest = contest_2014
            composition_1.name = 'İlk Şarkı'
            composition_1.url = 'https://s3-eu-west-1.amazonaws.com/gong-ir/temp_attachments/beste/1441108257899wjzK3Htv'
            composition_1.save()
            composition_1.softwares = [software]
            composition_1.devices = [device]
            composition_1.stage_materials = [stage_material]

            composition_2 = Composition(owner=user, contest=contest_2014)
            composition_2.name = 'İkinci Şarkı'
            composition_2.url = 'https://s3-eu-west-1.amazonaws.com/gong-ir/temp_attachments/beste/1441108257899wjzK3Htv'
            composition_2.save()
            composition_2.softwares = [software]
            composition_2.devices = [device]
            composition_2.stage_materials = [stage_material]

            composition_3 = Composition(owner=user, contest=contest_2015)
            composition_3.name = 'Üçüncü Şarkı'
            composition_3.url = 'https://s3-eu-west-1.amazonaws.com/gong-ir/temp_attachments/beste/1441108257899wjzK3Htv'
            composition_3.save()
            composition_3.softwares = [software]
            composition_3.devices = [device]
            composition_3.stage_materials = [stage_material]

            composition_4 = Composition(owner=user, contest=contest_2015)
            composition_4.name = 'Dördüncü Şarkı'
            composition_4.url = 'https://s3-eu-west-1.amazonaws.com/gong-ir/temp_attachments/beste/1441108257899wjzK3Htv'
            composition_4.save()
            composition_4.softwares = [software]
            composition_4.devices = [device]
            composition_4.stage_materials = [stage_material]

            composition_1.save()
            composition_2.save()
            composition_3.save()
            composition_4.save()

            print 'Default contents are created'
        except IOError:
            print 'File is not found'
    def handle(self, *args, **options):

        try:

            contest = Contest.objects.all()
            contest.delete()

            contest_2014 = Contest()
            contest_2014.year = 2014
            contest_2014.theme = 'Ritim'
            contest_2014.poster = 'http://beste.halici.com.tr/afis/2014.jpg'
            contest_2014.start_date = datetime.datetime(2014, 6, 1, 0, 0)
            contest_2014.final_date = datetime.datetime(2014, 11, 1, 0, 0)
            contest_2014.finish_date = datetime.datetime(2014, 12, 15, 0, 0)
            contest_2014.save()

            contest_2015 = Contest()
            contest_2015.year = 2015
            contest_2014.theme='Attila Özdemiroğlu'
            contest_2014.poster = 'http://beste.halici.com.tr/afis/2015.jpg'
            contest_2015.start_date = datetime.datetime(2015, 6, 1, 0, 0)
            contest_2015.final_date = datetime.datetime(2015, 11, 1, 0, 0)
            contest_2015.finish_date = datetime.datetime(2015, 12, 15, 0, 0)
            contest_2015.save()

            devices = Device.objects.all()
            devices.delete()

            device = Device()
            device.name = 'Bilgisayar'
            device.save()

            softwares = Software.objects.all()
            softwares.delete()

            software = Software()
            software.name = 'FL Studio'
            software.save()

            stage_materials = StageMaterial.objects.all()
            stage_materials.delete()

            stage_material = StageMaterial()
            stage_material.name = 'Gitar'
            stage_material.save()

            contents = Content.objects.all()
            contents.delete()

            content_file = open('default_contents/api_content.csv', 'rb')
            reader = csv.reader(content_file)

            for row in reader:
                content = Content()
                content.create_date = row[1]
                content.title = row[2]
                content.link = row[3]
                content.content = row[4]
                content.category_name = row[5]
                content.is_active = True if row[7] == '1' else False
                content.is_for_static_content = True if row[8] == '1' else False

                content.save()

            content_vote=Content()
            content_vote.title = 'Oylama'
            content_vote.link='oylama'
            content_vote.category_name = 'link'
            content_vote.is_active = True
            content_vote.is_for_static_content = False
            content_vote.save()

            users = User.objects.all()
            users.delete()

            user = User()
            user.username = '******'
            user.email = '*****@*****.**'
            user.first_name = 'Abdullah'
            user.last_name = 'Karacabey'
            user.set_password('674311')
            user.addres = 'Bağlum'
            user.city = 'Ankara'
            user.save()

            compositions = Composition.objects.all()
            compositions.delete()

            composition_1 = Composition()
            composition_1.owner=user
            composition_1.contest=contest_2014
            composition_1.name = 'İlk Şarkı'
            composition_1.url = 'https://s3-eu-west-1.amazonaws.com/gong-ir/temp_attachments/beste/1441108257899wjzK3Htv'
            composition_1.save()
            composition_1.softwares = [software]
            composition_1.devices = [device]
            composition_1.stage_materials = [stage_material]


            composition_2 = Composition(owner=user, contest=contest_2014)
            composition_2.name = 'İkinci Şarkı'
            composition_2.url = 'https://s3-eu-west-1.amazonaws.com/gong-ir/temp_attachments/beste/1441108257899wjzK3Htv'
            composition_2.save()
            composition_2.softwares = [software]
            composition_2.devices = [device]
            composition_2.stage_materials = [stage_material]

            composition_3 = Composition(owner=user, contest=contest_2015)
            composition_3.name = 'Üçüncü Şarkı'
            composition_3.url = 'https://s3-eu-west-1.amazonaws.com/gong-ir/temp_attachments/beste/1441108257899wjzK3Htv'
            composition_3.save()
            composition_3.softwares = [software]
            composition_3.devices = [device]
            composition_3.stage_materials = [stage_material]

            composition_4 = Composition(owner=user, contest=contest_2015)
            composition_4.name = 'Dördüncü Şarkı'
            composition_4.url = 'https://s3-eu-west-1.amazonaws.com/gong-ir/temp_attachments/beste/1441108257899wjzK3Htv'
            composition_4.save()
            composition_4.softwares = [software]
            composition_4.devices = [device]
            composition_4.stage_materials = [stage_material]

            composition_1.save()
            composition_2.save()
            composition_3.save()
            composition_4.save()



            print 'Default contents are created'
        except IOError:
            print 'File is not found'
Esempio n. 7
0
class APITests(TestCase):
    """API tests."""
    __client = None
    __user = None
    __basic_digest = None
    __device = None

    def setUp(self):
        """Prepare the dummy user account."""
        username = "******"
        password = "******"
        self.__client = APIClient()
        self.__user = User.objects.create_user(username, '*****@*****.**',
                                               password)
        self.__basic_digest = "Basic " + base64.b64encode("{}:{}".format(
            username, password).encode('ascii')).decode('ascii')
        self.__device = Device(name="dummydevice", dreempy_version="1.2.3")
        self.__device.save()

    def test_anonymous_get_users(self):
        """Try to fetch users while being anonymous."""
        response = self.__client.get("/users/")
        self.assertEqual(response.status_code, 403, "Permissions looks wrong.")

    def test_anonymous_get_devices(self):
        """Try to fetch devices while being anonymous."""
        response = self.__client.get("/records/")
        self.assertEqual(response.status_code, 403, "Permissions looks wrong.")

    def test_anonymous_get_records(self):
        """Try to fetch records while being anonymous."""
        response = self.__client.get("/records/")
        self.assertEqual(response.status_code, 403, "Permissions looks wrong.")

    def test_anonymous_get_signal(self):
        """Try to fetch record signals while being anonymous."""
        response = self.__client.get("/signal/{}/{}/{}/".format(
            "whoever", 0, 0))
        self.assertEqual(response.status_code, 403, "Permissions looks wrong.")

    def test_get_records(self):
        """Send a GET request on the /records/ resource."""
        response = self.__client.get("/records/",
                                     HTTP_AUTHORIZATION=self.__basic_digest)
        self.assertEqual(response.status_code, 200, "Can not GET /records/.")

    def test_get_devices(self):
        """Send a GET request on the /devices/ resource."""
        response = self.__client.get("/devices/",
                                     HTTP_AUTHORIZATION=self.__basic_digest)
        self.assertEqual(response.status_code, 200, "Can not GET /devices/.")

    def test_get_users(self):
        """Send a GET request on the /users/ resource. Only admins are authorised."""
        username = "******"
        password = "******"
        User.objects.create_superuser(username, '*****@*****.**',
                                      password)
        basic_digest = "Basic " + base64.b64encode("{}:{}".format(
            username, password).encode('ascii')).decode('ascii')

        response = self.__client.get("/users/",
                                     HTTP_AUTHORIZATION=basic_digest)
        self.assertEqual(response.status_code, 200, "Can not GET /users/.")

    def test_get_signal(self):
        """Send a GET on the /signal/ resource and ensure the proper record is provided."""
        # The record will start yesterday at this exact same hour.
        ts_start = int(time()) - 60 * 60 * 24
        # It will last from 6 to 10 hours.
        ts_stop = ts_start + 60 * 60 * randint(6, 10)

        record = Record(
            start_time=datetime.fromtimestamp(ts_start,
                                              timezone(timedelta(hours=1))),
            stop_time=datetime.fromtimestamp(ts_stop,
                                             timezone(timedelta(hours=1))),
            sleep_start_time=datetime.fromtimestamp(
                ts_start + 60 * 60, timezone(timedelta(hours=1))),
            sleep_stop_time=datetime.fromtimestamp(
                ts_stop - 60 * 60, timezone(timedelta(hours=1))),
            sleep_score=random(),
            number_of_stimulations=randint(0, 2000),
            number_of_wake=randint(0, 50),
            hypnogram=
            "[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,3,3,3]",
            user=self.__user,
            device=self.__device)
        record.save()

        response = self.__client.get("/signal/{}/{}/{}/".format(
            self.__user.username, ts_start, ts_stop),
                                     HTTP_AUTHORIZATION=self.__basic_digest)

        records = json.loads(response.content.decode('utf-8'))

        self.assertEqual(response.status_code, 200,
                         "Can not retrieve my signal.")
        self.assertEqual(len(records), 1, "I should have add a single record.")
        self.assertGreaterEqual(
            parse(records[0]["start_time"]),
            datetime.fromtimestamp(ts_start, timezone(timedelta(hours=1))),
            "The start_time is wrong.")
        self.assertGreaterEqual(
            datetime.fromtimestamp(ts_stop, timezone(timedelta(hours=1))),
            parse(records[0]["stop_time"]), "The stop_time is wrong.")