示例#1
0
 def test_creation(self):
     user = self.create_user()
     photo = self.add(Photo('new_photo.jpg', user))
     
     assert_obj_subset({'id': 1, 'user_id': user.id, 'title': 'new_photo.jpg', 
         'description': 'Description text goes here', 'views': 0}, photo)
     eq_(photo.creation_time, util.now())
 
     photo = self.add(Photo('new_photo.jpg', user, 'photo title', 'desc'))
     assert_obj_subset({'id': 2, 'user_id': user.id, 'title': 'photo title', 
         'description': 'desc', 'views': 0}, photo)
     eq_(photo.creation_time, util.now())
示例#2
0
 def __init__(self, sender, recipient, title, text):
     self.sender_id = sender.id
     self.recipient_id = recipient.id
     self.title = title
     self.text = text
     self.isRead = False
     self.creation_time = util.now()
示例#3
0
 def test_creation(self):
     user = self.create_user()
     photo = self.add(Photo('new_photo.jpg', user))
     note = self.add(Note(user, photo, 'Note Text', 0, 0, 0, 0))
     assert_obj_subset({'id': 1, 'user_id': 1, 'photo_id': 1, 
         'comment': 'Note Text', 'x': 0, 'y': 0, 'w': 0, 'h': 0}, note)
     eq_(note.creation_time, util.now())
示例#4
0
 def test_creation(self):
     user1 = self.create_user('Remi', '*****@*****.**', 'abc')
     user2 = self.create_user('Alyse', '*****@*****.**', 'abc')
     pm = self.add(PrivateMessage(user1, user2, 'Title', 'Body'))
     assert_obj_subset({'id': 1, 'sender_id': 1, 'recipient_id': 2,
         'title': 'Title', 'text': 'Body', 'isRead': False}, pm)
     eq_(pm.creation_time, util.now())
示例#5
0
    def test_user_group_assoc(self):
        user = self.create_user()
        group = self.add(Group('Test Group', 'test_group', 'description text', 'rules text'))

        group_assoc = GroupMemberList(user, group)
        db.session.commit()
        
        eq_(len(group.members), 1)
        eq_(group.members[0], user)
        
        eq_(len(user.groups), 1)
        eq_(user.groups[0], group)
        
        eq_(len(group.user_groups), 1)
        eq_(group.user_groups[0], group_assoc)

        eq_(len(user.user_groups), 1)
        eq_(user.user_groups[0], group_assoc)
        
        eq_(group_assoc.group, group)
        eq_(group_assoc.user, user)
        
        eq_(group_assoc.join_time, util.now())
        
        user_json = user.to_json()
        eq_(len(user_json['groups']), 1)
        eq_(user_json['groups'][0], group_assoc.to_json())
示例#6
0
    def finish(self):
        self.finished = True
        self.finished_at = now()
        self.status = "finished"
        send_event("workflow-finished", {"pk": self.pk})

        self.save()
        self.clean_up()
示例#7
0
 def test_to_json(self):
     expected = {
         'id': 1, 'sender_id': 1, 'recipient_id': 2,
         'title': 'Title', 'text': 'Body', 'isRead': False,
         'time': str(util.now())
     }
     
     u1, u2, pm = self.create_pm()
     assert_dict_contains_subset(expected, pm.to_json())
示例#8
0
    def add(cls, ip):
        created = "%s" % now()
        new_ip = cls(ip=ip, created=created)

        if db.sismember("ips", ip):
            raise BadRequest("IP address %s already registered" % ip)
        db.sadd("ips", ip)
        db.set("ip:%s" % ip, json.dumps({"created": created}))

        return new_ip
示例#9
0
 def test_user_group_assoc_to_json(self):
     expected = {
         'id': 1,
         'name': 'Test Group',
         'description': 'description text',
         'rules': 'rules text',
         'creation_time': str(util.now()),
         'photo_count': 0,
         'last_photo_url': '',
         'discussion_count': 0,
         'join_time': str(util.now())
     }
     
     user = self.create_user()
     group = self.add(Group('Test Group', 'test_group', 'description text', 'rules text'))
     group_assoc = GroupMemberList(user, group)
     db.session.commit()
     assert_dict_contains_subset(expected, group_assoc.to_json())
     eq_(user.to_json()['groups'], [group_assoc.to_json()])
示例#10
0
    def expires_in(self):
        """Return time to expiration, calculated by
        substracting the elapsed time since the creation of the token
        by the database value of exprires_in
        """
        if self.created:
            delta = (timedelta(seconds=self._expires_in) - (now() - self.created)).seconds
            return delta if delta > 0 else 0

        return self._expires_in
示例#11
0
 def test_to_json(self):
     expected = {
         'id': 1,
         'title': 'Test Discussion',
         'creation_time': str(util.now())
     }
     
     group = self.add(Group('Test Group', 'test_group'))
     d = self.add(Discussion(group, 'Test Discussion'))
     assert_dict_contains_subset(expected, d.to_json())
示例#12
0
 def test_creation(self):
     user = self.add(User('Remi', '*****@*****.**', password = '******'))
     assert_obj_subset({'id': 1, 'name': 'Remi', 'email': '*****@*****.**'}, user)
     assert_true(user.password.startswith('sha1$'))
 
     user = self.add(User('Jack', '*****@*****.**', 'Jack D', 'http://google.com/openid', 'asdfasdf'))
     assert_obj_subset({'id': 2, 'name': 'Jack', 'email': '*****@*****.**', 
         'real_name': 'Jack D', 'openid': 'http://google.com/openid'}, user)
     eq_(user.creation_time, util.now())
     assert_true(user.password.startswith('sha1$'))
示例#13
0
文件: photo.py 项目: remig/brickr
 def __init__(self, filename, user, title = None, description = "Description text goes here"):
     filename = secure_filename(filename)
     if title is None:
         title = filename
     self.binary_url = uuid4().hex + os.path.splitext(filename)[1]
     self.user_id = user.id
     self.title = title
     self.description = description
     self.views = 0
     self.creation_time = util.now()
示例#14
0
 def test_to_json(self):
     expected = {
         'id': 1,
         'user_name': 'Remi',
         'comment': 'Comment Text',
         'time': str(util.now())
     }
     
     user, photo, comment = self.create_comment()
     assert_dict_contains_subset(expected, comment.to_json())
     eq_(photo.to_json()['comments'], [comment.to_json()])
示例#15
0
 def test_to_json(self):
     expected = {
         'id': 1,
         'name': 'Test Group',
         'description': 'description text',
         'rules': 'rules text',
         'creation_time': str(util.now())
     }
     
     group = self.add(Group('Test Group', 'test_group', 'description text', 'rules text'))
     assert_dict_contains_subset(expected, group.to_json())
示例#16
0
 def test_photo_group_assoc_to_json(self):
     photo = self.create_photo()
     group = self.add(Group('Test Group', 'test_group', 'description text', 'rules text'))
     group_assoc = GroupPhotoList(photo, group)
     db.session.commit()
     
     expected = {
         'id': 1,
         'name': 'Test Group',
         'description': 'description text',
         'rules': 'rules text',
         'creation_time': str(util.now()),
         'photo_count': 1,
         'last_photo_url': photo.url(),
         'discussion_count': 0,
         'add_time': str(util.now())
     }
     
     assert_dict_contains_subset(expected, group_assoc.to_json())
     eq_(photo.to_json()['groups'], [group_assoc.to_json()])
示例#17
0
 def test_to_json(self):
     expected = {
         'id': 1,
         'user': '******',
         'target_user': '******',
         'creation': str(util.now())
     }
     
     u1, u2, contact = self.create_contact()
     assert_dict_contains_subset(expected, contact.to_json())
     eq_(u1.to_json()['contacts'], [contact.to_json()])
     eq_(u2.to_json()['contacts'], [])
示例#18
0
文件: user.py 项目: remig/brickr
 def __init__(self, name, email, real_name = None, openid = None, password = None):
     self.name = name
     self.email = email
     self.openid = openid
     self.real_name = real_name
     self.url = util.str_to_url(name)
     self.creation_time = util.now()
     if password is not None:
         if password.startswith('sha1$'):
             self.password = password
         else:  # If we somehow got passed in a raw password, hash it
             self.password = generate_password_hash(password)
示例#19
0
 def test_photo_group_assoc(self):
     photo = self.create_photo();
     group = self.add(Group('Test Group', 'test_group', 'description text', 'rules text'))
     
     eq_(len(group.photo_groups), 0)
     eq_(len(photo.photo_groups), 0)
     
     group_assoc = GroupPhotoList(photo, group)
     db.session.commit()
     
     eq_(len(group.photo_groups), 1)
     eq_(group.photo_groups[0].photo, photo)
     
     eq_(len(photo.photo_groups), 1)
     eq_(photo.photo_groups[0].group, group)
     
     eq_(group_assoc.add_time, util.now())
     
     photo_json = photo.to_json()
     eq_(len(photo_json['groups']), 1)
     eq_(photo_json['groups'][0], group_assoc.to_json())
     
     # Test second assoc
     photo2 = self.create_photo()
     group_assoc2 = GroupPhotoList(photo2, group)
     
     eq_(len(photo.photo_groups), 1)
     eq_(len(photo2.photo_groups), 1)
     eq_(len(group.photo_groups), 2)
     
     # Test group's convenience API
     photo.creation_time = datetime.datetime.now()
     db.session.commit()
     eq_(group.getNewestPhoto(), photo)
     assert_list_equal(group.getPhotosInAddOrder(), [photo, photo2])
     
     # Two ways to delete an assoc:
     db.session.delete(group_assoc)
     db.session.commit()
     eq_(len(photo.photo_groups), 0)
     eq_(len(group.photo_groups), 1)
     
     eq_(group.getNewestPhoto(), photo2)
     assert_list_equal(group.getPhotosInAddOrder(), [photo2])
     
     group.photo_groups.remove(group_assoc2)
     db.session.commit()
     eq_(len(photo2.photo_groups), 0)
     eq_(len(group.photo_groups), 0)
     
     eq_(group.getNewestPhoto(), None)
     assert_list_equal(group.getPhotosInAddOrder(), [])
示例#20
0
    def test_create(self):
        user = self.create_user()
        photo = self.add(Photo('new_photo.jpg', user))
        comment = self.add(Comment(user, photo, 'Comment Text'))
        assert_obj_subset({'id': 1, 'user_id': 1, 'photo_id': 1, 'comment': 'Comment Text'}, comment)
        eq_(comment.creation_time, util.now())
    
        comment = self.add(Comment(user, photo, 'Second Text'))
        assert_obj_subset({'id': 2, 'user_id': 1, 'photo_id': 1, 'comment': 'Second Text'}, comment)

        user2 = self.create_user('Alyse', '*****@*****.**')
        comment = self.add(Comment(user2, photo, 'Third Text'))
        assert_obj_subset({'id': 3, 'user_id': 2, 'photo_id': 1, 'comment': 'Third Text'}, comment)
示例#21
0
    def test_time_defaults_to_now(self):
        colin = self.post_valid_player('colin', rating=1100)
        kumanan = self.post_valid_player('kumanan', rating=1300)
        assert Player.query.count() == 2

        self.post_valid_challenge(colin, kumanan)
        assert Challenge.query.count() == 1
        time_created = Challenge.query.first().time_created

        # TODO: this is brittle and should instead mock out the time creation
        # in the resource, but I can't get the mock to work right now.
        delta = util.now() - time_created
        max_delta = datetime.timedelta(seconds=1)
        assert delta < max_delta
示例#22
0
def create_logfile(pod, logs):
    if pod is None:
        return

    if pod.startswith("bio"):
        pod = pod[3:]

    t = now()

    file = t.strftime(dtformat) + ".log"

    path = Path(settings.DATA_PATH) / "logs" / "/".join(pod.split("-")) / file
    os.makedirs(path.parent, exist_ok=True)
    with open(path, "w") as f:
        f.write(logs)
示例#23
0
def clear_logs():
    path = Path(settings.DATA_PATH) / "logs"
    files = list_all_files(path, relative=False, only_full_uploads=False)

    for f in files:
        file_name = f.name
        time_name = file_name[:-4]
        time = make_aware(datetime.strptime(time_name, dtformat))

        if (now() - time).total_seconds() > 60 * 60 * 24 * 7:  # 7d
            os.remove(f)

            p = f.parent
            while len(list_dirs(p)) == 0 and len(list_files(p)) == 0:
                os.rmdir(p)
                p = p.parent
示例#24
0
 def test_to_json(self):
     expected = {
         'id': 1,
         'is_placeholder': False,
         'name': 'Remi',
         'real_name': None,
         'email': '*****@*****.**',
         'joined': str(util.now()),
         'url': 'remi',
         'contacts': [],
         'favorites': [],
         'groups': []
     }
     
     user = self.create_user('Remi', '*****@*****.**', 'abc')
     assert_dict_contains_subset(expected, user.to_json())
示例#25
0
    def add(cls, source_ip, destination_ip, result):
        created = "%s" % now()
        new_ip = cls(
            source_ip=source_ip,
            destination_ip=destination_ip,
            result=result,
            created=created
        )

        db.set(
            "result:%s:%s:%s" % (source_ip, destination_ip, time.strftime("%Y%m%d%H%M%S", time.localtime())),
            json.dumps({
                "created": created,
                "source_ip": source_ip,
                "destination_ip": destination_ip,
                "result": result
            })
        )

        return new_ip
示例#26
0
 def test_to_json(self):
     user = self.create_user('Remi', '*****@*****.**', 'abc')
     expected = {
         'id': 1,
         'title': 'photo title',
         'description': 'desc',
         'photo_page_url': None,
         'views': 0,
         'creation_time': str(util.now()),
         'favorite': False,
         'favorites': [],
         'tags': [],
         'comments': [],
         'groups': [],
         'notes': [],
         'prev_photo_id': None,
         'next_photo_id': None
     }
     
     photo = Photo('new_photo.jpg', user, 'photo title', 'desc')
     db.session.add(photo)
     db.session.commit()
     assert_dict_contains_subset(expected, photo.to_json())
示例#27
0
 def expired(self):
     """Return true if the token is expired"""
     return now() > self.created + timedelta(seconds=self._expires_in)
示例#28
0
文件: comment.py 项目: remig/brickr
 def __init__(self, user, photo, comment, timestamp = None, parentID = None):
     self.user_id = user.id
     self.photo_id = photo.id
     self.comment = comment
     self.creation_time = timestamp or util.now()
     self.parentID = parentID
示例#29
0
 def test_creation(self):
     post = self.create_one_post()
     assert_obj_subset({'id': 1, 'post': 'Post Text'}, post)
     eq_(post.creation_time, util.now())
示例#30
0
文件: note.py 项目: remig/brickr
 def __init__(self, user, photo, comment, x, y, w, h):
     self.user_id = user.id
     self.photo_id = photo.id
     self.comment = comment
     self.set_coords(x, y, w, h)
     self.creation_time = util.now()
示例#31
0
文件: group.py 项目: remig/brickr
 def __init__(self, photo, group):
     self.photo = photo
     self.group = group
     self.add_time = util.now()
示例#32
0
文件: group.py 项目: remig/brickr
 def __init__(self, name, url_name, description=None, rules=None):
     self.name = name
     self.url_name = url_name
     self.description = description
     self.rules = rules
     self.creation_time = util.now()
示例#33
0
 def test_creation(self):
     user = self.create_user()
     photo = self.add(Photo('new_photo.jpg', user))
     fav = self.add(Favorite(user, photo))
     assert_obj_subset({'id': 1, 'user_id': 1, 'photo_id': 1}, fav)
     eq_(fav.creation_time, util.now())
示例#34
0
def finalize_upload(request, upload):
    """ move files according to the format annotations from the user """
    uuid = str(upload.uuid)
    tree, files, suffixes, dirs, prefixes, error = finish_upload_(
        request, upload)

    if error != False:
        return {"error": error}

    data = request.data
    manual_format = data.get("manual_format", False)
    wrap_files = data.get("wrap_files", False)
    checkboxes = data.get("checkboxes", [])
    types = data.get("types", [])
    for t in types:
        assert not ".." in t, "Illegal sequence: .."

    len_suffixes = len(suffixes)
    len_types = len(types)

    # the tree consists of one <job> folder at the end,
    # all other entries are the files.
    num_files = len(tree) - (1 if len(dirs) else 0)
    num_dirs = len(files) - num_files

    # avoid name duplicate if 'file' is part of the types
    path = base_path / "file" / (uuid + "_")
    move(base_path / "file" / uuid, path)
    if not manual_format:
        path = unwrap_path(path)

    if not manual_format:
        types_ = []
        duplicates = []
        for t in types:
            if t in types_:
                duplicates.append(t)
            types_.append(t)

        for prefix, files in prefixes.items():
            for file in files:
                # we want the longest suffix that the file matches.
                longest_find = 0, None
                for i in range(num_files):
                    if file.endswith(suffixes[i]):
                        if len(suffixes[i]) > longest_find[0]:
                            longest_find = len(suffixes[i]), i
                i = longest_find[1]

                for t in checkboxes[i]:
                    type = types[t]
                    move_file(
                        path,
                        uuid,
                        file,
                        type,
                        type_id=t,
                        job=prefix,
                        copy=(t != checkboxes[i][-1]),
                        remove_prefix=True,
                        duplicates=duplicates,
                    )
        for dir in dirs:
            for i in range(num_dirs):
                i += (
                    num_files  # suffixes is files and dirs, add an offset to the index.
                )
                for t in checkboxes[i]:
                    type = types[t]
                    move_file(
                        path / dir,
                        uuid,
                        suffixes[i],
                        type,
                        type_id=t,
                        job=dir,
                        copy=(t != checkboxes[i][-1]),
                    )

        try:
            shutil.rmtree(base_path / "file" / (uuid + "_"))
        except:
            pass
        upload.delete()
    else:
        # manual format, just specify the file type.

        assert not ".." in manual_format, "Illegal sequence: .."
        upload.file_type = manual_format
        upload.is_finished = True
        upload.save()

        to_path = base_path
        to_path /= upload.file_type
        to_path /= str(upload.uuid)
        if wrap_files:
            to_path /= "static"
        if path != to_path:
            os.makedirs(to_path.parent, exist_ok=True)
            move(path, to_path)
        try:
            shutil.rmtree(base_path / "file" / (uuid + "_"))
        except:
            pass

        upload.finished_at = now()
        upload.calc_size()

    update_file_types()
    return 0